runtime.js

``

@note A few conventions for the documentation of this file:

  1. Always use "//" (in contrast with "/**/")
  2. The syntax used is Yardoc (yardoc.org), which is intended for Ruby (se below)
  3. @param and @return types should be preceded by JS. when referring to JavaScript constructors (e.g. JS.Function) otherwise Ruby is assumed.
  4. nil and null being unambiguous refer to the respective objects/values in Ruby and JavaScript
  5. This is still WIP :) so please give feedback and suggestions on how to improve or for alternative solutions

The way the code is digested before going through Yardoc is a secret kept in the docs repo (https://github.com/opal/docs/tree/master).


if (typeof(global) !== 'undefined') { global_object = global; }

Detect the global object

if (typeof(global) !== 'undefined') { global_object = global; }

if (typeof(global_object.console) === 'object')

Setup a dummy console object if missing

if (typeof(global_object.console) === 'object') {

BasicObject

The actual class for BasicObject

var BasicObject;

_Object

The actual Object class. The leading underscore is to avoid confusion with window.Object()

var _Object;

Module

The actual Module class

var Module;

Class

The actual Class class

var Class;

Opal = this.Opal = {}

The Opal object that is exposed globally

var Opal = this.Opal = {};

Opal.global = global_object

This is a useful reference to global object inside ruby files

Opal.global = global_object;

Opal.config =

Configure runtime behavior with regards to require and unsupported fearures

Opal.config = {

$hasOwn = Object.hasOwnProperty

Minify common function calls

var $hasOwn       = Object.hasOwnProperty;

nil_id = 4

Nil object id is always 4

var nil_id = 4;

unique_id = nil_id

Generates even sequential numbers greater than 4 (nil_id) to serve as unique ids for ruby objects

var unique_id = nil_id;

Opal.uid = function()

Return next unique id

Opal.uid = function() {
  unique_id += 2;
  return unique_id;
};

Opal.id = function(obj)

Retrieve or assign the id of an object

Opal.id = function(obj) {
  if (obj.$$is_number) return (obj * 2)+1;
  if (obj.$$id != null) {
    return obj.$$id;
  }
  $defineProperty(obj, '$$id', Opal.uid());
  return obj.$$id;
};

Opal.gvars = {}

Globals table

Opal.gvars = {};

Opal.exit = function(status) { if (Opal.gvars.DEBUG) console.log('Exited with status '+status); }

Exit function, this should be replaced by platform specific implementation (See nodejs and chrome for examples)

Opal.exit = function(status) { if (Opal.gvars.DEBUG) console.log('Exited with status '+status); };

Opal.exceptions = []

keeps track of exceptions for $!

Opal.exceptions = [];

Opal.pop_exception = function()

@private Pops an exception from the stack and updates $!.

Opal.pop_exception = function() {
  Opal.gvars["!"] = Opal.exceptions.pop() || nil;
};

Opal.inspect = function(obj)

Inspect any kind of object, including non Ruby ones

Opal.inspect = function(obj) {
  if (obj === undefined) {
    return "undefined";
  }
  else if (obj === null) {
    return "null";
  }
  else if (!obj.$$class) {
    return obj.toString();
  }
  else {
    return obj.$inspect();
  }
};

object[name] = initialValue

Special case for: s = "string" def s.m; end String class is the only class that:

  • compiles to JS primitive
  • allows method definition directly on instances numbers, true, false and nil do not support it.
object[name] = initialValue;

``

Truth


``

Constants

For future reference:

Legend of MRI concepts/names:

  • constant reference (cref): the module/class that acts as a namespace
  • nesting: the namespaces wrapping the current scope, e.g. nesting inside module A; module B::C; end; end is [B::C, A]

function const_get_name(cref, name)

Get the constant in the scope of the current cref

function const_get_name(cref, name) {
  if (cref) return cref.$$const[name];
}

function const_lookup_nesting(nesting, name)

Walk up the nesting array looking for the constant

function const_lookup_nesting(nesting, name) {
  var i, ii, result, constant;

  if (nesting.length === 0) return;

  // If the nesting is not empty the constant is looked up in its elements
  // and in order. The ancestors of those elements are ignored.
  for (i = 0, ii = nesting.length; i < ii; i++) {
    constant = nesting[i].$$const[name];
    if (constant != null) return constant;
  }
}

function const_lookup_ancestors(cref, name)

Walk up the ancestors chain looking for the constant

function const_lookup_ancestors(cref, name) {
  var i, ii, result, ancestors;

  if (cref == null) return;

  ancestors = Opal.ancestors(cref);

  for (i = 0, ii = ancestors.length; i < ii; i++) {
    if (ancestors[i].$$const && $hasOwn.call(ancestors[i].$$const, name)) {
      return ancestors[i].$$const[name];
    }
  }
}

function const_lookup_Object(cref, name)

Walk up Object's ancestors chain looking for the constant, but only if cref is missing or a module.

function const_lookup_Object(cref, name) {
  if (cref == null || cref.$$is_module) {
    return const_lookup_ancestors(_Object, name);
  }
}

function const_missing(cref, name, skip_missing)

Call const_missing if nothing else worked

function const_missing(cref, name, skip_missing) {
  if (!skip_missing) {
    return (cref || _Object).$const_missing(name);
  }
}

Opal.const_get_local = function(cref, name, skip_missing)

Look for the constant just in the current cref or call #const_missing

Opal.const_get_local = function(cref, name, skip_missing) {
  var result;

  if (cref == null) return;

  if (cref === '::') cref = _Object;

  if (!cref.$$is_module && !cref.$$is_class) {
    throw new Opal.TypeError(cref.toString() + " is not a class/module");
  }

  result = const_get_name(cref, name);              if (result != null) return result;
  result = const_missing(cref, name, skip_missing); if (result != null) return result;
};

Opal.const_get_qualified = function(cref, name, skip_missing)

Look for the constant relative to a cref or call #const_missing (when the constant is prefixed by ::).

Opal.const_get_qualified = function(cref, name, skip_missing) {
  var result, cache, cached, current_version = Opal.const_cache_version;

  if (cref == null) return;

  if (cref === '::') cref = _Object;

  if (!cref.$$is_module && !cref.$$is_class) {
    throw new Opal.TypeError(cref.toString() + " is not a class/module");
  }

  if ((cache = cref.$$const_cache) == null) {
    $defineProperty(cref, '$$const_cache', Object.create(null));
    cache = cref.$$const_cache;
  }
  cached = cache[name];

  if (cached == null || cached[0] !== current_version) {
    ((result = const_get_name(cref, name))              != null) ||
    ((result = const_lookup_ancestors(cref, name))      != null);
    cache[name] = [current_version, result];
  } else {
    result = cached[1];
  }

  return result != null ? result : const_missing(cref, name, skip_missing);
};

Opal.const_cache_version = 1

Initialize the top level constant cache generation counter

Opal.const_cache_version = 1;

Opal.const_get_relative = function(nesting, name, skip_missing)

Look for the constant in the open using the current nesting and the nearest cref ancestors or call #const_missing (when the constant has no :: prefix).

Opal.const_get_relative = function(nesting, name, skip_missing) {
  var cref = nesting[0], result, current_version = Opal.const_cache_version, cache, cached;

  if ((cache = nesting.$$const_cache) == null) {
    $defineProperty(nesting, '$$const_cache', Object.create(null));
    cache = nesting.$$const_cache;
  }
  cached = cache[name];

  if (cached == null || cached[0] !== current_version) {
    ((result = const_get_name(cref, name))              != null) ||
    ((result = const_lookup_nesting(nesting, name))     != null) ||
    ((result = const_lookup_ancestors(cref, name))      != null) ||
    ((result = const_lookup_Object(cref, name))         != null);

    cache[name] = [current_version, result];
  } else {
    result = cached[1];
  }

  return result != null ? result : const_missing(cref, name, skip_missing);
};

Opal.const_set = function(cref, name, value)

Register the constant on a cref and opportunistically set the name of unnamed classes/modules.

Opal.const_set = function(cref, name, value) {
  if (cref == null || cref === '::') cref = _Object;

  if (value.$$is_a_module) {
    if (value.$$name == null || value.$$name === nil) value.$$name = name;
    if (value.$$base_module == null) value.$$base_module = cref;
  }

  cref.$$const = (cref.$$const || Object.create(null));
  cref.$$const[name] = value;

  // Add a short helper to navigate constants manually.
  // @example
  //   Opal.$$.Regexp.$$.IGNORECASE
  cref.$$ = cref.$$const;

  Opal.const_cache_version++;

  // Expose top level constants onto the Opal object
  if (cref === _Object) Opal[name] = value;

  // Name new class directly onto current scope (Opal.Foo.Baz = klass)
  $defineProperty(cref, name, value);

  return value;
};

Opal.constants = function(cref, inherit)

Get all the constants reachable from a given cref, by default will include inherited constants.

Opal.constants = function(cref, inherit) {
  if (inherit == null) inherit = true;

  var module, modules = [cref], module_constants, i, ii, constants = {}, constant;

  if (inherit) modules = modules.concat(Opal.ancestors(cref));
  if (inherit && cref.$$is_module) modules = modules.concat([Opal.Object]).concat(Opal.ancestors(Opal.Object));

  for (i = 0, ii = modules.length; i < ii; i++) {
    module = modules[i];

    // Don not show Objects constants unless we're querying Object itself
    if (cref !== _Object && module == _Object) break;

    for (constant in module.$$const) {
      constants[constant] = true;
    }
  }

  return Object.keys(constants);
};

Opal.const_remove = function(cref, name)

Remove a constant from a cref.

Opal.const_remove = function(cref, name) {
  Opal.const_cache_version++;

  if (cref.$$const[name] != null) {
    var old = cref.$$const[name];
    delete cref.$$const[name];
    return old;
  }

  if (cref.$$autoload != null && cref.$$autoload[name] != null) {
    delete cref.$$autoload[name];
    return nil;
  }

  throw Opal.NameError.$new("constant "+cref+"::"+cref.$name()+" not defined");
};

``

Modules & Classes


Opal.allocate_class = function(name, superclass)

A class Foo; end expression in ruby is compiled to call this runtime method which either returns an existing class of the given name, or creates a new class in the given base scope.

If a constant with the given name exists, then we check to make sure that it is a class and also that the superclasses match. If either of these fail, then we raise a TypeError. Note, superclass may be null if one was not specified in the ruby code.

We pass a constructor to this method of the form function ClassName() {} simply so that classes show up with nicely formatted names inside debuggers in the web browser (or node/sprockets).

The scope is the current self value where the class is being created from. We use this to get the scope for where the class should be created. If scope is an object (not a class/module), we simple get its class and use that as the scope instead.

@param scope [Object] where the class is being created @param superclass [Class,null] superclass of the new class (may be null) @param id [String] the name of the class to be created @param constructor [JS.Function] function to use as constructor

@return new [Class] or existing ruby class

Opal.allocate_class = function(name, superclass) {
  var klass, constructor;

  if (superclass != null && superclass.$$bridge) {
    // Inheritance from bridged classes requires
    // calling original JS constructors
    constructor = function() {
      var args = $slice.call(arguments),
          self = new ($bind.apply(superclass.$$constructor, [null].concat(args)))();

      // and replacing a __proto__ manually
      $setPrototype(self, klass.$$prototype);
      return self;
    }
  } else {
    constructor = function(){};
  }

  if (name) {
    $defineProperty(constructor, 'displayName', '::'+name);
  }

  klass = constructor;

  $defineProperty(klass, '$$name', name);
  $defineProperty(klass, '$$constructor', constructor);
  $defineProperty(klass, '$$prototype', constructor.prototype);
  $defineProperty(klass, '$$const', {});
  $defineProperty(klass, '$$is_class', true);
  $defineProperty(klass, '$$is_a_module', true);
  $defineProperty(klass, '$$super', superclass);
  $defineProperty(klass, '$$cvars', {});
  $defineProperty(klass, '$$own_included_modules', []);
  $defineProperty(klass, '$$own_prepended_modules', []);
  $defineProperty(klass, '$$ancestors', []);
  $defineProperty(klass, '$$ancestors_cache_version', null);

  $defineProperty(klass.$$prototype, '$$class', klass);

  // By default if there are no singleton class methods
  // __proto__ is Class.prototype
  // Later singleton methods generate a singleton_class
  // and inject it into ancestors chain
  if (Opal.Class) {
    $setPrototype(klass, Opal.Class.prototype);
  }

  if (superclass != null) {
    $setPrototype(klass.$$prototype, superclass.$$prototype);

    if (superclass.$$meta) {
      // If superclass has metaclass then we have explicitely inherit it.
      Opal.build_class_singleton_class(klass);
    }
  }

  return klass;
};

klass = const_get_name(scope, name)

Try to find the class in the current scope

var klass = const_get_name(scope, name);

if (klass)

If the class exists in the scope, then we must use that

if (klass) {

if (!klass.$$is_class)

Make sure the existing constant is a class, or raise error

if (!klass.$$is_class) {

scope = _Object

Global scope

scope = _Object;

scope = scope.$$class

Scope is an object, use its class

scope = scope.$$class;

if (superclass != null && !superclass.hasOwnProperty('$$is_class'))

If the superclass is not an Opal-generated class then we're bridging a native JS class

if (superclass != null && !superclass.hasOwnProperty('$$is_class')) {

ensureSuperclassMatch(klass, superclass)

Make sure existing class has same superclass

ensureSuperclassMatch(klass, superclass);

``

Class doesn't exist, create a new one with given superclass...


if (superclass == null)

Not specifying a superclass means we can assume it to be Object

if (superclass == null) {

klass = Opal.allocate_class(name, superclass)

Create the class object (instance of Class)

klass = Opal.allocate_class(name, superclass);

if (superclass.$inherited)

Call .inherited() hook with new class on the superclass

if (superclass.$inherited) {

Opal.allocate_module = function(name)

Define new module (or return existing module). The given scope is basically the current self value the module statement was defined in. If this is a ruby module or class, then it is used, otherwise if the scope is a ruby object then that objects real ruby class is used (e.g. if the scope is the main object, then the top level Object class is used as the scope).

If a module of the given name is already defined in the scope, then that instance is just returned.

If there is a class of the given name in the scope, then an error is generated instead (cannot have a class and module of same name in same scope).

Otherwise, a new module is created in the scope with the given name, and that new instance is returned back (to be referenced at runtime).

@param scope [Module, Class] class or module this definition is inside @param id [String] the name of the new (or existing) module

@return [Module]

Opal.allocate_module = function(name) {
  var constructor = function(){};
  if (name) {
    $defineProperty(constructor, 'displayName', name+'.$$constructor');
  }

  var module = constructor;

  if (name)
    $defineProperty(constructor, 'displayName', name+'.constructor');

  $defineProperty(module, '$$name', name);
  $defineProperty(module, '$$prototype', constructor.prototype);
  $defineProperty(module, '$$const', {});
  $defineProperty(module, '$$is_module', true);
  $defineProperty(module, '$$is_a_module', true);
  $defineProperty(module, '$$cvars', {});
  $defineProperty(module, '$$iclasses', []);
  $defineProperty(module, '$$own_included_modules', []);
  $defineProperty(module, '$$own_prepended_modules', []);
  $defineProperty(module, '$$ancestors', [module]);
  $defineProperty(module, '$$ancestors_cache_version', null);

  $setPrototype(module, Opal.Module.prototype);

  return module;
};

scope = _Object

Global scope

scope = _Object;

scope = scope.$$class

Scope is an object, use its class

scope = scope.$$class;

module = Opal.allocate_module(name)

Module doesnt exist, create a new one...

module = Opal.allocate_module(name);

Opal.get_singleton_class = function(object)

Return the singleton class for the passed object.

If the given object alredy has a singleton class, then it will be stored on the object as the $$meta property. If this exists, then it is simply returned back.

Otherwise, a new singleton object for the class or object is created, set on the object at $$meta for future use, and then returned.

@param object [Object] the ruby object @return [Class] the singleton class for object

Opal.get_singleton_class = function(object) {
  if (object.$$meta) {
    return object.$$meta;
  }

  if (object.hasOwnProperty('$$is_class')) {
    return Opal.build_class_singleton_class(object);
  } else if (object.hasOwnProperty('$$is_module')) {
    return Opal.build_module_singletin_class(object);
  } else {
    return Opal.build_object_singleton_class(object);
  }
};

Opal.build_class_singleton_class = function(klass)

Build the singleton class for an existing class. Class object are built with their singleton class already in the prototype chain and inheriting from their superclass object (up to Class itself).

NOTE: Actually in MRI a class' singleton class inherits from its superclass' singleton class which in turn inherits from Class.

@param klass [Class] @return [Class]

Opal.build_class_singleton_class = function(klass) {
  var superclass, meta;

  if (klass.$$meta) {
    return klass.$$meta;
  }

  // The singleton_class superclass is the singleton_class of its superclass;
  // but BasicObject has no superclass (its `$$super` is null), thus we
  // fallback on `Class`.
  superclass = klass === BasicObject ? Class : Opal.get_singleton_class(klass.$$super);

  meta = Opal.allocate_class(null, superclass, function(){});

  $defineProperty(meta, '$$is_singleton', true);
  $defineProperty(meta, '$$singleton_of', klass);
  $defineProperty(klass, '$$meta', meta);
  $setPrototype(klass, meta.$$prototype);
  // Restoring ClassName.class
  $defineProperty(klass, '$$class', Opal.Class);

  return meta;
};

$defineProperty(mod, '$$class', Opal.Module)

Restoring ModuleName.class

$defineProperty(mod, '$$class', Opal.Module);

Opal.build_object_singleton_class = function(object)

Build the singleton class for a Ruby (non class) Object.

@param object [Object] @return [Class]

Opal.build_object_singleton_class = function(object) {
  var superclass = object.$$class,
      klass = Opal.allocate_class(nil, superclass, function(){});

  $defineProperty(klass, '$$is_singleton', true);
  $defineProperty(klass, '$$singleton_of', object);

  delete klass.$$prototype.$$class;

  $defineProperty(object, '$$meta', klass);

  $setPrototype(object, object.$$meta.$$prototype);

  return klass;
};

Opal.class_variables = function(module)

Returns an object containing all pairs of names/values for all class variables defined in provided +module+ and its ancestors.

@param module [Module] @return [Object]

Opal.class_variables = function(module) {
  var ancestors = Opal.ancestors(module),
      i, length = ancestors.length,
      result = {};

  for (i = length - 1; i >= 0; i--) {
    var ancestor = ancestors[i];

    for (var cvar in ancestor.$$cvars) {
      result[cvar] = ancestor.$$cvars[cvar];
    }
  }

  return result;
};

Opal.class_variable_set = function(module, name, value)

Sets class variable with specified +name+ to +value+ in provided +module+

@param module [Module] @param name [String] @param value [Object]

Opal.class_variable_set = function(module, name, value) {
  var ancestors = Opal.ancestors(module),
      i, length = ancestors.length;

  for (i = length - 2; i >= 0; i--) {
    var ancestor = ancestors[i];

    if ($hasOwn.call(ancestor.$$cvars, name)) {
      ancestor.$$cvars[name] = value;
      return value;
    }
  }

  module.$$cvars[name] = value;

  return value;
};

break

superclass

break;

Opal.append_features = function(module, includer)

The actual inclusion of a module into a class.

Class $$parent and iclass

To handle super calls, every class has a $$parent. This parent is used to resolve the next class for a super call. A normal class would have this point to its superclass. However, if a class includes a module then this would need to take into account the module. The module would also have to then point its $$parent to the actual superclass. We cannot modify modules like this, because it might be included in more then one class. To fix this, we actually insert an iclass as the class' $$parent which can then point to the superclass. The iclass acts as a proxy to the actual module, so the super chain can then search it for the required method.

@param module [Module] the module to include @param includer [Module] the target class to include module into @return [null]

Opal.append_features = function(module, includer) {
  var module_ancestors = Opal.ancestors(module);
  var iclasses = [];

  if (module_ancestors.indexOf(includer) !== -1) {
    throw Opal.ArgumentError.$new('cyclic include detected');
  }

  for (var i = 0, length = module_ancestors.length; i < length; i++) {
    var ancestor = module_ancestors[i], iclass = create_iclass(ancestor);
    $defineProperty(iclass, '$$included', true);
    iclasses.push(iclass);
  }
  var includer_ancestors = Opal.ancestors(includer),
      chain = chain_iclasses(iclasses),
      start_chain_after,
      end_chain_on;

  if (includer_ancestors.indexOf(module) === -1) {
    // first time include

    // includer -> chain.first -> ...chain... -> chain.last -> includer.parent
    start_chain_after = includer.$$prototype;
    end_chain_on = Object.getPrototypeOf(includer.$$prototype);
  } else {
    // The module has been already included,
    // we don't need to put it into the ancestors chain again,
    // but this module may have new included modules.
    // If it's true we need to copy them.
    //
    // The simplest way is to replace ancestors chain from
    //          parent
    //            |
    //   `module` iclass (has a $$root flag)
    //            |
    //   ...previos chain of module.included_modules ...
    //            |
    //  "next ancestor" (has a $$root flag or is a real class)
    //
    // to
    //          parent
    //            |
    //    `module` iclass (has a $$root flag)
    //            |
    //   ...regenerated chain of module.included_modules
    //            |
    //   "next ancestor" (has a $$root flag or is a real class)
    //
    // because there are no intermediate classes between `parent` and `next ancestor`.
    // It doesn't break any prototypes of other objects as we don't change class references.

    var proto = includer.$$prototype, parent = proto, module_iclass = Object.getPrototypeOf(parent);

    while (module_iclass != null) {
      if (isRoot(module_iclass) && module_iclass.$$module === module) {
        break;
      }

      parent = module_iclass;
      module_iclass = Object.getPrototypeOf(module_iclass);
    }

    var next_ancestor = Object.getPrototypeOf(module_iclass);

    // skip non-root iclasses (that were recursively included)
    while (next_ancestor.hasOwnProperty('$$iclass') && !isRoot(next_ancestor)) {
      next_ancestor = Object.getPrototypeOf(next_ancestor);
    }

    start_chain_after = parent;
    end_chain_on = next_ancestor;
  }

  $setPrototype(start_chain_after, chain.first);
  $setPrototype(chain.last, end_chain_on);

  // recalculate own_included_modules cache
  includer.$$own_included_modules = own_included_modules(includer);

  Opal.const_cache_version++;
};

module_ancestors = Opal.ancestors(module)

Here we change the ancestors chain from

prepender | parent

to:

dummy(prepender) | iclass(module) | iclass(prepender) | parent

var module_ancestors = Opal.ancestors(module);

prepender_iclass = dummy_prepender.$$define_methods_on

The module already has some prepended modules which means that we don't need to make it "dummy"

prepender_iclass = dummy_prepender.$$define_methods_on;

prepender_iclass = create_dummy_iclass(prepender)

Making the module "dummy"

prepender_iclass = create_dummy_iclass(prepender);

$setPrototype(dummy_prepender, prepender_iclass)

Converting dummy(prepender) -> previous_parent to dummy(prepender) -> iclass(prepender) -> previous_parent

$setPrototype(dummy_prepender, prepender_iclass);

``

first time prepend


end_chain_on = Object.getPrototypeOf(dummy_prepender)

next $$root or prepender_iclass or non-$$iclass

end_chain_on = Object.getPrototypeOf(dummy_prepender);

prepender.$$own_prepended_modules = own_prepended_modules(prepender)

recalculate own_prepended_modules cache

prepender.$$own_prepended_modules = own_prepended_modules(prepender);

function create_dummy_iclass(module)

Dummy iclass doesn't receive updates when the module gets a new method.

function create_dummy_iclass(module) {
  var iclass = {},
      proto = module.$$prototype;

  if (proto.hasOwnProperty('$$dummy')) {
    proto = proto.$$define_methods_on;
  }

  var props = Object.getOwnPropertyNames(proto),
      length = props.length, i;

  for (i = 0; i < length; i++) {
    var prop = props[i];
    $defineProperty(iclass, prop, proto[prop]);
  }

  $defineProperty(iclass, '$$iclass', true);
  $defineProperty(iclass, '$$module', module);

  return iclass;
}

Opal.bridge = function(native_klass, klass)

For performance, some core Ruby classes are toll-free bridged to their native JavaScript counterparts (e.g. a Ruby Array is a JavaScript Array).

This method is used to setup a native constructor (e.g. Array), to have its prototype act like a normal Ruby class. Firstly, a new Ruby class is created using the native constructor so that its prototype is set as the target for the new class. Note: all bridged classes are set to inherit from Object.

Example:

Opal.bridge(self, Function);

@param klass [Class] the Ruby class to bridge @param constructor [JS.Function] native JavaScript constructor to use @return [Class] returns the passed Ruby class

Opal.bridge = function(native_klass, klass) {
  if (native_klass.hasOwnProperty('$$bridge')) {
    throw Opal.ArgumentError.$new("already bridged");
  }

  var klass_to_inject, klass_reference;

  klass_to_inject = klass.$$super || Opal.Object;
  klass_reference = klass;
  var original_prototype = klass.$$prototype;

  // constructor is a JS function with a prototype chain like:
  // - constructor
  //   - super
  //
  // What we need to do is to inject our class (with its prototype chain)
  // between constructor and super. For example, after injecting ::Object
  // into JS String we get:
  //
  // - constructor (window.String)
  //   - Opal.Object
  //     - Opal.Kernel
  //       - Opal.BasicObject
  //         - super (window.Object)
  //           - null
  //
  $defineProperty(native_klass, '$$bridge', klass);
  $setPrototype(native_klass.prototype, (klass.$$super || Opal.Object).$$prototype);
  $defineProperty(klass, '$$prototype', native_klass.prototype);

  $defineProperty(klass.$$prototype, '$$class', klass);
  $defineProperty(klass, '$$constructor', native_klass);
  $defineProperty(klass, '$$bridge', true);
};

Opal.ancestors = function(module)

The Array of ancestors for a given module/class

Opal.ancestors = function(module) {
  if (!module) { return []; }

  if (module.$$ancestors_cache_version === Opal.const_cache_version) {
    return module.$$ancestors;
  }

  var result = [], i, mods, length;

  for (i = 0, mods = own_ancestors(module), length = mods.length; i < length; i++) {
    result.push(mods[i]);
  }

  if (module.$$super) {
    for (i = 0, mods = Opal.ancestors(module.$$super), length = mods.length; i < length; i++) {
      result.push(mods[i]);
    }
  }

  module.$$ancestors_cache_version = Opal.const_cache_version;
  module.$$ancestors = result;

  return result;
};

``

Method Missing


Opal.add_stubs = function(stubs)

Methods stubs are used to facilitate method_missing in opal. A stub is a placeholder function which just calls method_missing on the receiver. If no method with the given name is actually defined on an object, then it is obvious to say that the stub will be called instead, and then in turn method_missing will be called.

When a file in ruby gets compiled to javascript, it includes a call to this function which adds stubs for every method name in the compiled file. It should then be safe to assume that method_missing will work for any method call detected.

Method stubs are added to the BasicObject prototype, which every other ruby object inherits, so all objects should handle method missing. A stub is only added if the given property name (method name) is not already defined.

Note: all ruby methods have a $ prefix in javascript, so all stubs will have this prefix as well (to make this method more performant).

Opal.add_stubs(["$foo", "$bar", "$baz="]);

All stub functions will have a private $$stub property set to true so that other internal methods can detect if a method is just a stub or not. Kernel#respond_to? uses this property to detect a methods presence.

@param stubs [Array] an array of method stubs to add @return [undefined]

Opal.add_stubs = function(stubs) {
  var proto = Opal.BasicObject.$$prototype;

  for (var i = 0, length = stubs.length; i < length; i++) {
    var stub = stubs[i], existing_method = proto[stub];

    if (existing_method == null || existing_method.$$stub) {
      Opal.add_stub_for(proto, stub);
    }
  }
};

Opal.add_stub_for = function(prototype, stub)

Add a method_missing stub function to the given prototype for the given name.

@param prototype [Prototype] the target prototype @param stub [String] stub name to add (e.g. "$foo") @return [undefined]

Opal.add_stub_for = function(prototype, stub) {
  var method_missing_stub = Opal.stub_for(stub);
  $defineProperty(prototype, stub, method_missing_stub);
};

Opal.stub_for = function(method_name)

Generate the method_missing stub for a given method name.

@param method_name [String] The js-name of the method to stub (e.g. "$foo") @return [undefined]

Opal.stub_for = function(method_name) {
  function method_missing_stub() {
    // Copy any given block onto the method_missing dispatcher
    this.$method_missing.$$p = method_missing_stub.$$p;

    // Set block property to null ready for the next call (stop false-positives)
    method_missing_stub.$$p = null;

    // call method missing with correct args (remove '$' prefix on method name)
    var args_ary = new Array(arguments.length);
    for(var i = 0, l = args_ary.length; i < l; i++) { args_ary[i] = arguments[i]; }

    return this.$method_missing.apply(this, [method_name.slice(1)].concat(args_ary));
  }

  method_missing_stub.$$stub = true;

  return method_missing_stub;
};

``

Methods


Opal.ac = function(actual, expected, object, meth)

Arity count error dispatcher for methods

@param actual [Fixnum] number of arguments given to method @param expected [Fixnum] expected number of arguments @param object [Object] owner of the method +meth+ @param meth [String] method name that got wrong number of arguments @raise [ArgumentError]

Opal.ac = function(actual, expected, object, meth) {
  var inspect = '';
  if (object.$$is_a_module) {
    inspect += object.$$name + '.';
  }
  else {
    inspect += object.$$class.$$name + '#';
  }
  inspect += meth;

  throw Opal.ArgumentError.$new('[' + inspect + '] wrong number of arguments(' + actual + ' for ' + expected + ')');
};

Opal.block_ac = function(actual, expected, context)

Arity count error dispatcher for blocks

@param actual [Fixnum] number of arguments given to block @param expected [Fixnum] expected number of arguments @param context [Object] context of the block definition @raise [ArgumentError]

Opal.block_ac = function(actual, expected, context) {
  var inspect = "`block in " + context + "'";

  throw Opal.ArgumentError.$new(inspect + ': wrong number of arguments (' + actual + ' for ' + expected + ')');
};

Opal.find_super_dispatcher = function(obj, mid, current_func, defcheck, defs)

Super dispatcher

Opal.find_super_dispatcher = function(obj, mid, current_func, defcheck, defs) {
  var jsid = '$' + mid, ancestors, super_method;

  if (obj.hasOwnProperty('$$meta')) {
    ancestors = Opal.ancestors(obj.$$meta);
  } else {
    ancestors = Opal.ancestors(obj.$$class);
  }

  var current_index = ancestors.indexOf(current_func.$$owner);

  for (var i = current_index + 1; i < ancestors.length; i++) {
    var ancestor = ancestors[i],
        proto = ancestor.$$prototype;

    if (proto.hasOwnProperty('$$dummy')) {
      proto = proto.$$define_methods_on;
    }

    if (proto.hasOwnProperty(jsid)) {
      var method = proto[jsid];

      if (!method.$$stub) {
        super_method = method;
      }
      break;
    }
  }

  if (!defcheck && super_method == null && Opal.Kernel.$method_missing === obj.$method_missing) {
    // method_missing hasn't been explicitly defined
    throw Opal.NoMethodError.$new('super: no superclass method `'+mid+"' for "+obj, mid);
  }

  return super_method;
};

Opal.find_iter_super_dispatcher = function(obj, jsid, current_func, defcheck, implicit)

Iter dispatcher for super in a block

Opal.find_iter_super_dispatcher = function(obj, jsid, current_func, defcheck, implicit) {
  var call_jsid = jsid;

  if (!current_func) {
    throw Opal.RuntimeError.$new("super called outside of method");
  }

  if (implicit && current_func.$$define_meth) {
    throw Opal.RuntimeError.$new("implicit argument passing of super from method defined by define_method() is not supported. Specify all arguments explicitly");
  }

  if (current_func.$$def) {
    call_jsid = current_func.$$jsid;
  }

  return Opal.find_super_dispatcher(obj, call_jsid, current_func, defcheck);
};

Opal.ret = function(val)

Used to return as an expression. Sometimes, we can't simply return from a javascript function as if we were a method, as the return is used as an expression, or even inside a block which must "return" to the outer method. This helper simply throws an error which is then caught by the method. This approach is expensive, so it is only used when absolutely needed.

Opal.ret = function(val) {
  Opal.returner.$v = val;
  throw Opal.returner;
};

Opal.brk = function(val, breaker)

Used to break out of a block.

Opal.brk = function(val, breaker) {
  breaker.$v = val;
  throw breaker;
};

Opal.new_brk = function()

Builds a new unique breaker, this is to avoid multiple nested breaks to get in the way of each other.

Opal.new_brk = function() {
  return new Error('unexpected break');
};

Opal.yield1 = function(block, arg)

handles yield calls for 1 yielded arg

Opal.yield1 = function(block, arg) {
  if (typeof(block) !== "function") {
    throw Opal.LocalJumpError.$new("no block given");
  }

  var has_mlhs = block.$$has_top_level_mlhs_arg,
      has_trailing_comma = block.$$has_trailing_comma_in_args;

  if (block.length > 1 || ((has_mlhs || has_trailing_comma) && block.length === 1)) {
    arg = Opal.to_ary(arg);
  }

  if ((block.length > 1 || (has_trailing_comma && block.length === 1)) && arg.$$is_array) {
    return block.apply(null, arg);
  }
  else {
    return block(arg);
  }
};

Opal.yieldX = function(block, args)

handles yield for > 1 yielded arg

Opal.yieldX = function(block, args) {
  if (typeof(block) !== "function") {
    throw Opal.LocalJumpError.$new("no block given");
  }

  if (block.length > 1 && args.length === 1) {
    if (args[0].$$is_array) {
      return block.apply(null, args[0]);
    }
  }

  if (!args.$$is_array) {
    var args_ary = new Array(args.length);
    for(var i = 0, l = args_ary.length; i < l; i++) { args_ary[i] = args[i]; }

    return block.apply(null, args_ary);
  }

  return block.apply(null, args);
};

Opal.rescue = function(exception, candidates)

Finds the corresponding exception match in candidates. Each candidate can be a value, or an array of values. Returns null if not found.

Opal.rescue = function(exception, candidates) {
  for (var i = 0; i < candidates.length; i++) {
    var candidate = candidates[i];

    if (candidate.$$is_array) {
      var result = Opal.rescue(exception, candidate);

      if (result) {
        return result;
      }
    }
    else if (candidate === Opal.JS.Error) {
      return candidate;
    }
    else if (candidate['$==='](exception)) {
      return candidate;
    }
  }

  return null;
};

Opal.to_hash = function(value)

Helpers for extracting kwsplats Used for: { **h }

Opal.to_hash = function(value) {
  if (value.$$is_hash) {
    return value;
  }
  else if (value['$respond_to?']('to_hash', true)) {
    var hash = value.$to_hash();
    if (hash.$$is_hash) {
      return hash;
    }
    else {
      throw Opal.TypeError.$new("Can't convert " + value.$$class +
        " to Hash (" + value.$$class + "#to_hash gives " + hash.$$class + ")");
    }
  }
  else {
    throw Opal.TypeError.$new("no implicit conversion of " + value.$$class + " into Hash");
  }
};

``

Helpers for implementing multiple assignment Our code for extracting the values and assigning them only works if the return value is a JS array. So if we get an Array subclass, extract the wrapped JS array from it


Opal.to_ary = function(value)

Used for: a, b = something (no splat)

Opal.to_ary = function(value) {
  if (value.$$is_array) {
    return value;
  }
  else if (value['$respond_to?']('to_ary', true)) {
    var ary = value.$to_ary();
    if (ary === nil) {
      return [value];
    }
    else if (ary.$$is_array) {
      return ary;
    }
    else {
      throw Opal.TypeError.$new("Can't convert " + value.$$class +
        " to Array (" + value.$$class + "#to_ary gives " + ary.$$class + ")");
    }
  }
  else {
    return [value];
  }
};

Opal.to_a = function(value)

Used for: a, b = *something (with splat)

Opal.to_a = function(value) {
  if (value.$$is_array) {
    // A splatted array must be copied
    return value.slice();
  }
  else if (value['$respond_to?']('to_a', true)) {
    var ary = value.$to_a();
    if (ary === nil) {
      return [value];
    }
    else if (ary.$$is_array) {
      return ary;
    }
    else {
      throw Opal.TypeError.$new("Can't convert " + value.$$class +
        " to Array (" + value.$$class + "#to_a gives " + ary.$$class + ")");
    }
  }
  else {
    return [value];
  }
};

Opal.extract_kwargs = function(parameters)

Used for extracting keyword arguments from arguments passed to JS function. If provided +arguments+ list doesn't have a Hash as a last item, returns a blank Hash.

@param parameters [Array] @return [Hash]

Opal.extract_kwargs = function(parameters) {
  var kwargs = parameters[parameters.length - 1];
  if (kwargs != null && kwargs['$respond_to?']('to_hash', true)) {
    $splice.call(parameters, parameters.length - 1, 1);
    return kwargs.$to_hash();
  }
  else {
    return Opal.hash2([], {});
  }
};

Opal.kwrestargs = function(given_args, used_args)

Used to get a list of rest keyword arguments. Method takes the given keyword args, i.e. the hash literal passed to the method containing all keyword arguemnts passed to method, as well as the used args which are the names of required and optional arguments defined. This method then just returns all key/value pairs which have not been used, in a new hash literal.

@param given_args [Hash] all kwargs given to method @param used_args [Object] all keys used as named kwargs @return [Hash]

Opal.kwrestargs = function(given_args, used_args) {
  var keys      = [],
      map       = {},
      key           ,
      given_map = given_args.$$smap;

  for (key in given_map) {
    if (!used_args[key]) {
      keys.push(key);
      map[key] = given_map[key];
    }
  }

  return Opal.hash2(keys, map);
};

Opal.send = function(recv, method, args, block)

Calls passed method on a ruby object with arguments and block:

Can take a method or a method name.

  1. When method name gets passed it invokes it by its name and calls 'method_missing' when object doesn't have this method. Used internally by Opal to invoke method that takes a block or a splat.
  2. When method (i.e. method body) gets passed, it doesn't trigger 'method_missing' because it doesn't know the name of the actual method. Used internally by Opal to invoke 'super'.

@example var my_array = [1, 2, 3, 4] Opal.send(my_array, 'length') # => 4 Opal.send(my_array, my_array.$length) # => 4

Opal.send(my_array, 'reverse!') # => [4, 3, 2, 1] Opal.send(my_array, my_array['$reverse!']') # => [4, 3, 2, 1]

@param recv [Object] ruby object @param method [Function, String] method body or name of the method @param args [Array] arguments that will be passed to the method call @param block [Function] ruby block @return [Object] returning value of the method call

Opal.send = function(recv, method, args, block) {
  var body = (typeof(method) === 'string') ? recv['$'+method] : method;

  if (body != null) {
    if (typeof block === 'function') {
      body.$$p = block;
    }
    return body.apply(recv, args);
  }

  return recv.$method_missing.apply(recv, [method].concat(args));
};

Opal.def = function(obj, jsid, body)

Used to define methods on an object. This is a helper method, used by the compiled source to define methods on special case objects when the compiler can not determine the destination object, or the object is a Module instance. This can get called by Module#define_method as well.

Modules

Any method defined on a module will come through this runtime helper. The method is added to the module body, and the owner of the method is set to be the module itself. This is used later when choosing which method should show on a class if more than 1 included modules define the same method. Finally, if the module is in module_function mode, then the method is also defined onto the module itself.

Classes

This helper will only be called for classes when a method is being defined indirectly; either through Module#define_method, or by a literal def method inside an instance_eval or class_eval body. In either case, the method is simply added to the class' prototype. A special exception exists for BasicObject and Object. These two classes are special because they are used in toll-free bridged classes. In each of these two cases, extra work is required to define the methods on toll-free bridged class' prototypes as well.

Objects

If a simple ruby object is the object, then the method is simply just defined on the object as a singleton method. This would be the case when a method is defined inside an instance_eval block.

@param obj [Object, Class] the actual obj to define method for @param jsid [String] the JavaScript friendly method name (e.g. '$foo') @param body [JS.Function] the literal JavaScript function used as method @return [null]

Opal.def = function(obj, jsid, body) {
  // Special case for a method definition in the
  // top-level namespace
  if (obj === Opal.top) {
    Opal.defn(Opal.Object, jsid, body)
  }
  // if instance_eval is invoked on a module/class, it sets inst_eval_mod
  else if (!obj.$$eval && obj.$$is_a_module) {
    Opal.defn(obj, jsid, body);
  }
  else {
    Opal.defs(obj, jsid, body);
  }
};

Opal.defn = function(module, jsid, body)

Define method on a module or class (see Opal.def).

Opal.defn = function(module, jsid, body) {
  body.displayName = jsid;
  body.$$owner = module;

  var proto = module.$$prototype;
  if (proto.hasOwnProperty('$$dummy')) {
    proto = proto.$$define_methods_on;
  }
  $defineProperty(proto, jsid, body);

  if (module.$$is_module) {
    if (module.$$module_function) {
      Opal.defs(module, jsid, body)
    }

    for (var i = 0, iclasses = module.$$iclasses, length = iclasses.length; i < length; i++) {
      var iclass = iclasses[i];
      $defineProperty(iclass, jsid, body);
    }
  }

  var singleton_of = module.$$singleton_of;
  if (module.$method_added && !module.$method_added.$$stub && !singleton_of) {
    module.$method_added(jsid.substr(1));
  }
  else if (singleton_of && singleton_of.$singleton_method_added && !singleton_of.$singleton_method_added.$$stub) {
    singleton_of.$singleton_method_added(jsid.substr(1));
  }
};

Opal.defs = function(obj, jsid, body)

Define a singleton method on the given object (see Opal.def).

Opal.defs = function(obj, jsid, body) {
  if (obj.$$is_string || obj.$$is_number) {
    throw Opal.TypeError.$new("can't define singleton");
  }
  Opal.defn(Opal.get_singleton_class(obj), jsid, body)
};

Opal.rdef = function(obj, jsid)

Called from #remove_method.

Opal.rdef = function(obj, jsid) {
  if (!$hasOwn.call(obj.$$prototype, jsid)) {
    throw Opal.NameError.$new("method '" + jsid.substr(1) + "' not defined in " + obj.$name());
  }

  delete obj.$$prototype[jsid];

  if (obj.$$is_singleton) {
    if (obj.$$prototype.$singleton_method_removed && !obj.$$prototype.$singleton_method_removed.$$stub) {
      obj.$$prototype.$singleton_method_removed(jsid.substr(1));
    }
  }
  else {
    if (obj.$method_removed && !obj.$method_removed.$$stub) {
      obj.$method_removed(jsid.substr(1));
    }
  }
};

Opal.udef = function(obj, jsid)

Called from #undef_method.

Opal.udef = function(obj, jsid) {
  if (!obj.$$prototype[jsid] || obj.$$prototype[jsid].$$stub) {
    throw Opal.NameError.$new("method '" + jsid.substr(1) + "' not defined in " + obj.$name());
  }

  Opal.add_stub_for(obj.$$prototype, jsid);

  if (obj.$$is_singleton) {
    if (obj.$$prototype.$singleton_method_undefined && !obj.$$prototype.$singleton_method_undefined.$$stub) {
      obj.$$prototype.$singleton_method_undefined(jsid.substr(1));
    }
  }
  else {
    if (obj.$method_undefined && !obj.$method_undefined.$$stub) {
      obj.$method_undefined(jsid.substr(1));
    }
  }
};

if (obj.$$eval)

When running inside #instance_eval the alias refers to class methods.

if (obj.$$eval) {

body = Opal.Object.$$prototype[old_id]

try to look into Object

body = Opal.Object.$$prototype[old_id]

if (body.$$alias_of) body = body.$$alias_of

If the body is itself an alias use the original body to keep the max depth at 1.

if (body.$$alias_of) body = body.$$alias_of;

alias = function()

We need a wrapper because otherwise properties would be ovrewritten on the original body.

alias = function() {
  var block = alias.$$p, args, i, ii;

  args = new Array(arguments.length);
  for(i = 0, ii = arguments.length; i < ii; i++) {
    args[i] = arguments[i];
  }

  if (block != null) { alias.$$p = null }

  return Opal.send(this, body, args, block);
};

alias.displayName = name

Try to make the browser pick the right name

alias.displayName       = name;

``

Hashes


Opal.hash2 = function(keys, smap)

A faster Hash creator for hashes that just use symbols and strings as keys. The map and keys array can be constructed at compile time, so they are just added here by the constructor function.

Opal.hash2 = function(keys, smap) {
  var hash = new Opal.Hash();

  hash.$$smap = smap;
  hash.$$map  = Object.create(null);
  hash.$$keys = keys;

  return hash;
};

Opal.range = function(first, last, exc)

Create a new range instance with first and last values, and whether the range excludes the last value.

Opal.range = function(first, last, exc) {
  var range         = new Opal.Range();
      range.begin   = first;
      range.end     = last;
      range.excl    = exc;

  return range;
};

Opal.ivar = function(name)

Get the ivar name for a given name. Mostly adds a trailing $ to reserved names.

Opal.ivar = function(name) {
  if (
      // properties
      name === "constructor" ||
      name === "displayName" ||
      name === "__count__" ||
      name === "__noSuchMethod__" ||
      name === "__parent__" ||
      name === "__proto__" ||

      // methods
      name === "hasOwnProperty" ||
      name === "valueOf"
     )
  {
    return name + "$";
  }

  return name;
};

``

Regexps


Opal.escape_regexp = function(str)

Escape Regexp special chars letting the resulting string be used to build a new Regexp.

Opal.escape_regexp = function(str) {
  return str.replace(/([-[\]\/{}()*+?.^$\\| ])/g, '\\$1')
            .replace(/[\n]/g, '\\n')
            .replace(/[\r]/g, '\\r')
            .replace(/[\f]/g, '\\f')
            .replace(/[\t]/g, '\\t');
};

Opal.global_regexp = function(pattern)

Create a global Regexp from a RegExp object and cache the result on the object itself ($$g attribute).

Opal.global_regexp = function(pattern) {
  if (pattern.global) {
    return pattern; // RegExp already has the global flag
  }
  if (pattern.$$g == null) {
    pattern.$$g = new RegExp(pattern.source, (pattern.multiline ? 'gm' : 'g') + (pattern.ignoreCase ? 'i' : ''));
  } else {
    pattern.$$g.lastIndex = null; // reset lastIndex property
  }
  return pattern.$$g;
};

Opal.global_multiline_regexp = function(pattern)

Create a global multiline Regexp from a RegExp object and cache the result on the object itself ($$gm or $$g attribute).

Opal.global_multiline_regexp = function(pattern) {
  var result;
  if (pattern.multiline) {
    if (pattern.global) {
      return pattern; // RegExp already has the global and multiline flag
    }
    // we are using the $$g attribute because the Regexp is already multiline
    if (pattern.$$g != null) {
      result = pattern.$$g;
    } else {
      result = pattern.$$g = new RegExp(pattern.source, 'gm' + (pattern.ignoreCase ? 'i' : ''));
    }
  } else if (pattern.$$gm != null) {
    result = pattern.$$gm;
  } else {
    result = pattern.$$gm = new RegExp(pattern.source, 'gm' + (pattern.ignoreCase ? 'i' : ''));
  }
  result.lastIndex = null; // reset lastIndex property
  return result;
};

``

Require system


function $BasicObject() {}

Initialization

function $BasicObject() {}

BasicObject.$$const["BasicObject"] = BasicObject

BasicObject can reach itself, avoid const_set to skip the $$base_module logic

BasicObject.$$const["BasicObject"] = BasicObject;

Opal.const_set(_Object, "BasicObject", BasicObject)

Assign basic constants

Opal.const_set(_Object, "BasicObject",  BasicObject);

BasicObject.$$class = Class

Fix booted classes to have correct .class value

BasicObject.$$class = Class;

$defineProperty(_Object.$$prototype, 'toString', function()

Forward .toString() to #to_s

$defineProperty(_Object.$$prototype, 'toString', function() {
  var to_s = this.$to_s();
  if (to_s.$$is_string && typeof(to_s) === 'object') {
    // a string created using new String('string')
    return to_s.valueOf();
  } else {
    return to_s;
  }
});

$defineProperty(_Object.$$prototype, '$require', Opal.require)

Make Kernel#require immediately available as it's needed to require all the other corelib files.

$defineProperty(_Object.$$prototype, '$require', Opal.require);

Opal.$$ = _Object.$$

Add a short helper to navigate constants manually. @example Opal.$$.Regexp.$$.IGNORECASE

Opal.$$ = _Object.$$;

Opal.top = new _Object()

Instantiate the main object

Opal.top = new _Object();

function $NilClass() {}

Nil

function $NilClass() {}

Opal.breaker = new Error('unexpected break (old)')

Errors

Opal.breaker  = new Error('unexpected break (old)');