/
runtime.js
2539 lines (2072 loc) · 75.2 KB
/
runtime.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(global_object) {
"use strict";
// @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).
var console;
// Detect the global object
if (typeof(globalThis) !== 'undefined') { global_object = globalThis; }
else if (typeof(global) !== 'undefined') { global_object = global; }
else if (typeof(window) !== 'undefined') { global_object = window; }
// Setup a dummy console object if missing
if (typeof(global_object.console) === 'object') {
console = global_object.console;
} else if (global_object.console == null) {
console = global_object.console = {};
} else {
console = {};
}
if (!('log' in console)) { console.log = function () {}; }
if (!('warn' in console)) { console.warn = console.log; }
if (typeof(global_object.Opal) !== 'undefined') {
console.warn('Opal already loaded. Loading twice can cause troubles, please fix your setup.');
return global_object.Opal;
}
var nil;
// The actual class for BasicObject
var BasicObject;
// The actual Object class.
// The leading underscore is to avoid confusion with window.Object()
var _Object;
// The actual Module class
var Module;
// The actual Class class
var Class;
// The Opal object that is exposed globally
var Opal = global_object.Opal = {};
// This is a useful reference to global object inside ruby files
Opal.global = global_object;
global_object.Opal = Opal;
// Configure runtime behavior with regards to require and unsupported features
Opal.config = {
missing_require_severity: 'error', // error, warning, ignore
unsupported_features_severity: 'warning', // error, warning, ignore
enable_stack_trace: true // true, false
};
// Minify common function calls
var $has_own = Object.hasOwnProperty;
var $bind = Function.prototype.bind;
var $set_proto = Object.setPrototypeOf;
var $slice = Array.prototype.slice;
var $splice = Array.prototype.splice;
// Nil object id is always 4
var nil_id = 4;
// Generates even sequential numbers greater than 4
// (nil_id) to serve as unique ids for ruby objects
var unique_id = nil_id;
// Return next unique id
Opal.uid = function() {
unique_id += 2;
return unique_id;
};
// 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;
};
// Globals table
Opal.gvars = {};
// 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); };
// keeps track of exceptions for $!
Opal.exceptions = [];
// @private
// Pops an exception from the stack and updates `$!`.
Opal.pop_exception = function() {
Opal.gvars["!"] = Opal.exceptions.pop() || nil;
};
// 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();
}
};
function $defineProperty(object, name, initialValue) {
if (typeof(object) === "string") {
// 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 null do not support it.
object[name] = initialValue;
} else {
Object.defineProperty(object, name, {
value: initialValue,
enumerable: false,
configurable: true,
writable: true
});
}
}
Opal.defineProperty = $defineProperty;
Opal.slice = $slice;
// Helpers
// -----
Opal.truthy = function(val) {
return (val !== nil && val != null && (!val.$$is_boolean || val == true));
};
Opal.falsy = function(val) {
return (val === nil || val == null || (val.$$is_boolean && val == false))
};
Opal.type_error = function(object, type, method, coerced) {
object = object.$$class;
if (coerced && method) {
coerced = coerced.$$class;
return Opal.TypeError.$new(
"can't convert " + object + " into " + type +
" (" + object + "#" + method + " gives " + coerced + ")"
)
} else {
return Opal.TypeError.$new(
"no implicit conversion of " + object + " into " + type
)
}
};
Opal.coerce_to = function(object, type, method, args) {
if (type['$==='](object)) return object;
if (!object['$respond_to?'](method)) {
throw Opal.type_error(object, type);
}
if (args == null) args = [];
return Opal.send(object, method, args);
}
Opal.respond_to = function(obj, jsid, include_all) {
if (obj == null || !obj.$$class) return false;
include_all = !!include_all;
var body = obj[jsid];
if (obj['$respond_to?'].$$pristine) {
if (obj['$respond_to_missing?'].$$pristine) {
return typeof(body) === "function" && !body.$$stub;
} else {
return Opal.send(obj, obj['$respond_to_missing?'], [jsid.substr(1), include_all]);
}
} else {
return Opal.send(obj, obj['$respond_to?'], [jsid.substr(1), include_all]);
}
}
// Constants
// ---------
//
// For future reference:
// - The Rails autoloading guide (http://guides.rubyonrails.org/v5.0/autoloading_and_reloading_constants.html)
// - @ConradIrwin's 2012 post on “Everything you ever wanted to know about constant lookup in Ruby” (http://cirw.in/blog/constant-lookup.html)
//
// 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]`
// Get the constant in the scope of the current cref
function const_get_name(cref, name) {
if (cref) return cref.$$const[name];
}
// Walk up the nesting array looking for the constant
function const_lookup_nesting(nesting, name) {
var i, ii, 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;
}
}
// Walk up the ancestors chain looking for the constant
function const_lookup_ancestors(cref, name) {
var i, ii, ancestors;
if (cref == null) return;
ancestors = Opal.ancestors(cref);
for (i = 0, ii = ancestors.length; i < ii; i++) {
if (ancestors[i].$$const && $has_own.call(ancestors[i].$$const, name)) {
return ancestors[i].$$const[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);
}
}
// Call const_missing if nothing else worked
function const_missing(cref, name, skip_missing) {
if (!skip_missing) {
return (cref || _Object).$const_missing(name);
}
}
// 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;
};
// 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);
};
// Initialize the top level constant cache generation counter
Opal.const_cache_version = 1;
// 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);
};
// 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;
};
// 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], 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];
// Do 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);
};
// 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");
};
// Setup some shortcuts to reduce compiled size
Opal.$$ = Opal.const_get_relative;
Opal.$$$ = Opal.const_get_qualified;
// Modules & Classes
// -----------------
// 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
$set_proto(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) {
$set_proto(klass, Opal.Class.prototype);
}
if (superclass != null) {
$set_proto(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;
};
function find_existing_class(scope, name) {
// Try to find the class in the current scope
var klass = const_get_name(scope, name);
// If the class exists in the scope, then we must use that
if (klass) {
// Make sure the existing constant is a class, or raise error
if (!klass.$$is_class) {
throw Opal.TypeError.$new(name + " is not a class");
}
return klass;
}
}
function ensureSuperclassMatch(klass, superclass) {
if (klass.$$super !== superclass) {
throw Opal.TypeError.$new("superclass mismatch for class " + klass.$$name);
}
}
Opal.klass = function(scope, superclass, name) {
var bridged;
if (scope == null) {
// Global scope
scope = _Object;
} else if (!scope.$$is_class && !scope.$$is_module) {
// Scope is an object, use its class
scope = scope.$$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')) {
bridged = superclass;
superclass = _Object;
}
var klass = find_existing_class(scope, name);
if (klass) {
if (superclass) {
// Make sure existing class has same superclass
ensureSuperclassMatch(klass, superclass);
}
return klass;
}
// Class doesn't exist, create a new one with given superclass...
// Not specifying a superclass means we can assume it to be Object
if (superclass == null) {
superclass = _Object;
}
// Create the class object (instance of Class)
klass = Opal.allocate_class(name, superclass);
Opal.const_set(scope, name, klass);
// Call .inherited() hook with new class on the superclass
if (superclass.$inherited) {
superclass.$inherited(klass);
}
if (bridged) {
Opal.bridge(bridged, klass);
}
return klass;
};
// 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);
$set_proto(module, Opal.Module.prototype);
return module;
};
function find_existing_module(scope, name) {
var module = const_get_name(scope, name);
if (module == null && scope === _Object) module = const_lookup_ancestors(_Object, name);
if (module) {
if (!module.$$is_module && module !== _Object) {
throw Opal.TypeError.$new(name + " is not a module");
}
}
return module;
}
Opal.module = function(scope, name) {
var module;
if (scope == null) {
// Global scope
scope = _Object;
} else if (!scope.$$is_class && !scope.$$is_module) {
// Scope is an object, use its class
scope = scope.$$class;
}
module = find_existing_module(scope, name);
if (module) {
return module;
}
// Module doesnt exist, create a new one...
module = Opal.allocate_module(name);
Opal.const_set(scope, name, module);
return module;
};
// 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_singleton_class(object);
} else {
return Opal.build_object_singleton_class(object);
}
};
// 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);
$set_proto(klass, meta.$$prototype);
// Restoring ClassName.class
$defineProperty(klass, '$$class', Opal.Class);
return meta;
};
Opal.build_module_singleton_class = function(mod) {
if (mod.$$meta) {
return mod.$$meta;
}
var meta = Opal.allocate_class(null, Opal.Module, function(){});
$defineProperty(meta, '$$is_singleton', true);
$defineProperty(meta, '$$singleton_of', mod);
$defineProperty(mod, '$$meta', meta);
$set_proto(mod, meta.$$prototype);
// Restoring ModuleName.class
$defineProperty(mod, '$$class', Opal.Module);
return meta;
};
// 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);
$set_proto(object, object.$$meta.$$prototype);
return klass;
};
Opal.is_method = function(prop) {
return (prop[0] === '$' && prop[1] !== '$');
};
Opal.instance_methods = function(mod) {
var exclude = [], results = [], ancestors = Opal.ancestors(mod);
for (var i = 0, l = ancestors.length; i < l; i++) {
var ancestor = ancestors[i],
proto = ancestor.$$prototype;
if (proto.hasOwnProperty('$$dummy')) {
proto = proto.$$define_methods_on;
}
var props = Object.getOwnPropertyNames(proto);
for (var j = 0, ll = props.length; j < ll; j++) {
var prop = props[j];
if (Opal.is_method(prop)) {
var method_name = prop.slice(1),
method = proto[prop];
if (method.$$stub && exclude.indexOf(method_name) === -1) {
exclude.push(method_name);
}
if (!method.$$stub && results.indexOf(method_name) === -1 && exclude.indexOf(method_name) === -1) {
results.push(method_name);
}
}
}
}
return results;
};
Opal.own_instance_methods = function(mod) {
var results = [],
proto = mod.$$prototype;
if (proto.hasOwnProperty('$$dummy')) {
proto = proto.$$define_methods_on;
}
var props = Object.getOwnPropertyNames(proto);
for (var i = 0, length = props.length; i < length; i++) {
var prop = props[i];
if (Opal.is_method(prop)) {
var method = proto[prop];
if (!method.$$stub) {
var method_name = prop.slice(1);
results.push(method_name);
}
}
}
return results;
};
Opal.methods = function(obj) {
return Opal.instance_methods(Opal.get_singleton_class(obj));
};
Opal.own_methods = function(obj) {
return Opal.own_instance_methods(Opal.get_singleton_class(obj));
};
Opal.receiver_methods = function(obj) {
var mod = Opal.get_singleton_class(obj);
var singleton_methods = Opal.own_instance_methods(mod);
var instance_methods = Opal.own_instance_methods(mod.$$super);
return singleton_methods.concat(instance_methods);
};
// 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;
};
// 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 ($has_own.call(ancestor.$$cvars, name)) {
ancestor.$$cvars[name] = value;
return value;
}
}
module.$$cvars[name] = value;
return value;
};
function isRoot(proto) {
return proto.hasOwnProperty('$$iclass') && proto.hasOwnProperty('$$root');
}
function own_included_modules(module) {
var result = [], mod, proto = Object.getPrototypeOf(module.$$prototype);
while (proto) {
if (proto.hasOwnProperty('$$class')) {
// superclass
break;
}
mod = protoToModule(proto);
if (mod) {
result.push(mod);
}
proto = Object.getPrototypeOf(proto);
}
return result;
}
function own_prepended_modules(module) {
var result = [], mod, proto = Object.getPrototypeOf(module.$$prototype);
if (module.$$prototype.hasOwnProperty('$$dummy')) {
while (proto) {
if (proto === module.$$prototype.$$define_methods_on) {
break;
}
mod = protoToModule(proto);
if (mod) {
result.push(mod);
}
proto = Object.getPrototypeOf(proto);
}
}
return result;
}
// 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);