This repository has been archived by the owner on Jul 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 396
/
runtime.js
1993 lines (1773 loc) · 66.3 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
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 4 -*- */
var runtimeOptions = systemOptions.register(new OptionSet("Runtime Options"));
var traceScope = runtimeOptions.register(new Option("ts", "traceScope", "boolean", false, "trace scope execution"));
var traceExecution = runtimeOptions.register(new Option("tx", "traceExecution", "number", 0, "trace script execution"));
var tracePropertyAccess = runtimeOptions.register(new Option("tpa", "tracePropertyAccess", "boolean", false, "trace property access"));
var functionBreak = runtimeOptions.register(new Option("fb", "functionBreak", "number", -1, "Inserts a debugBreak at function index #."));
var compileOnly = runtimeOptions.register(new Option("co", "compileOnly", "number", -1, "Compiles only function number."));
var compileUntil = runtimeOptions.register(new Option("cu", "compileUntil", "number", -1, "Compiles only until a function number."));
var debuggerMode = runtimeOptions.register(new Option("dm", "debuggerMode", "boolean", false, "matches avm2 debugger build semantics"));
var enableVerifier = runtimeOptions.register(new Option("verify", "verify", "boolean", false, "Enable verifier."));
var enableInlineCaching = runtimeOptions.register(new Option("ic", "inlineCaching", "boolean", false, "Enable inline caching."));
var traceInlineCaching = runtimeOptions.register(new Option("tic", "traceInlineCaching", "boolean", false, "Trace inline caching execution."));
var compilerEnableExceptions = runtimeOptions.register(new Option("cex", "exceptions", "boolean", false, "Compile functions with catch blocks."));
var compilerMaximumMethodSize = runtimeOptions.register(new Option("cmms", "maximumMethodSize", "number", 4 * 1024, "Compiler maximum method size."));
var jsGlobal = (function() { return this || (1, eval)('this'); })();
var VM_SLOTS = "vm slots";
var VM_LENGTH = "vm length";
var VM_BINDINGS = "vm bindings";
var VM_NATIVE_PROTOTYPE_FLAG = "vm native prototype";
var VM_ENUMERATION_KEYS = "vm enumeration keys";
var VM_TOMBSTONE = {};
var VM_OPEN_METHODS = "vm open methods";
var VM_NEXT_NAME = "vm next name";
var VM_NEXT_NAME_INDEX = "vm next name index";
var VM_UNSAFE_CLASSES = ["Shumway"];
var VM_OPEN_METHOD_PREFIX = "open$";
var VM_NATIVE_BUILTINS = [Object, Number, Boolean, String, Array, Date, RegExp];
var VM_NATIVE_BUILTIN_SURROGATES = [
{ object: Object, methods: ["toString", "valueOf"] },
{ object: Function, methods: ["toString", "valueOf"] }
];
var VM_NATIVE_BUILTIN_ORIGINALS = "vm originals";
var SAVED_SCOPE_NAME = "$SS";
var PARAMETER_PREFIX = "p";
var $M = [];
/**
* This is used to keep track if we're in a runtime context. Proxies need to know
* if a proxied operation is triggered by AS3 code or VM code.
*/
var RUNTIME_ENTER_LEAVE_STACK = [false];
function enter(runtime) {
RUNTIME_ENTER_LEAVE_STACK.push(runtime);
}
function leave(runtime) {
var top = RUNTIME_ENTER_LEAVE_STACK.pop();
assert (top === runtime);
}
function inRuntime() {
return RUNTIME_ENTER_LEAVE_STACK.top();
}
/**
* To embed object references in compiled code we index into globally accessible constant table [$C].
* This table maintains an unique set of object references, each of which holds its own position in
* the constant table, thus providing for fast lookup. We can also define constants in the JS global
* scope.
*/
var $C = [];
function objectConstantName(object) {
release || assert(object);
if (object.hasOwnProperty("objectID")) {
return "$C_" + object.objectID;
}
var id = $C.length;
Object.defineProperty(object, "objectID", {value: id, writable: false, enumerable: false});
$C.push(object);
var name = "$C_" + id;
jsGlobal[name] = object;
return name;
}
function initializeGlobalObject(global) {
var PUBLIC_MANGLED = /^public\$/;
function getEnumerationKeys(obj) {
var keys = [];
var boxedValue = obj.valueOf();
// TODO: This is probably broken if the object has overwritten |valueOf|.
if (typeof boxedValue === "string" || typeof boxedValue === "number") {
return [];
}
// TODO: Implement fast path for Array objects.
for (var key in obj) {
if (isNumeric(key)) {
keys.push(Number(key));
} else if (PUBLIC_MANGLED.test(key)) {
if (obj[VM_BINDINGS] && obj[VM_BINDINGS].indexOf(key) >= 0) {
continue;
}
keys.push(key.substr(7));
}
}
return keys;
}
/**
* Gets the next name index of an object. Index |zero| is actually not an
* index, but rather an indicator to start the iteration.
*/
defineReadOnlyProperty(global.Object.prototype, VM_NEXT_NAME_INDEX, function (index) {
if (index === 0) {
/**
* We're starting a new iteration. Hope that VM_ENUMERATION_KEYS haven't been
* defined already.
*/
this[VM_ENUMERATION_KEYS] = getEnumerationKeys(this);
}
var keys = this[VM_ENUMERATION_KEYS];
while (index < keys.length) {
if (keys[index] !== VM_TOMBSTONE) {
return index + 1;
}
index ++;
}
delete this[VM_ENUMERATION_KEYS];
return 0;
});
/**
* Gets the nextName after the specified |index|, which you would expect to
* be index + 1, but it's actually index - 1;
*/
defineReadOnlyProperty(global.Object.prototype, VM_NEXT_NAME, function (index) {
var keys = this[VM_ENUMERATION_KEYS];
release || assert(keys && index > 0 && index < keys.length + 1);
return keys[index - 1];
});
/**
* Surrogates are used to make |toString| and |valueOf| work transparently. For instance, the expression
* |a + b| should implicitly expand to |a.public$valueOf() + b.public$valueOf()|. Since, we don't want
* to call |public$valueOf| explicitly we instead patch the |valueOf| property in the prototypes of native
* builtins to call the |public$valueOf| instead.
*/
var originals = global[VM_NATIVE_BUILTIN_ORIGINALS] = {};
VM_NATIVE_BUILTIN_SURROGATES.forEach(function (surrogate) {
var object = surrogate.object;
originals[object.name] = {};
surrogate.methods.forEach(function (originalFunctionName) {
var originalFunction = object.prototype[originalFunctionName];
// Save the original method in case |getNative| needs it.
originals[object.name][originalFunctionName] = originalFunction;
var overrideFunctionName = Multiname.getPublicQualifiedName(originalFunctionName);
if (compatibility) {
// Patch the native builtin with a surrogate.
global[object.name].prototype[originalFunctionName] = function surrogate() {
if (this[overrideFunctionName]) {
return this[overrideFunctionName]();
}
return originalFunction.call(this);
};
}
});
});
VM_NATIVE_BUILTINS.forEach(function (o) {
defineReadOnlyProperty(o.prototype, VM_NATIVE_PROTOTYPE_FLAG, true);
});
}
/**
* Checks if the specified |obj| is the prototype of a native JavaScript object.
*/
function isNativePrototype(obj) {
return obj.hasOwnProperty(VM_NATIVE_PROTOTYPE_FLAG);
}
initializeGlobalObject(jsGlobal);
function createNewGlobalObject() {
var global = null;
if (inBrowser) {
var iFrame = document.createElement("iframe");
iFrame.style.display = "none";
document.body.appendChild(iFrame);
global = window.frames[window.frames.length - 1];
} else {
global = newGlobal('new-compartment');
}
initializeGlobalObject(global);
return global;
}
function toDouble(x) {
return Number(x);
}
function toBoolean(x) {
return !!x;
}
function toUint(x) {
var obj = x | 0;
return obj < 0 ? (obj + 4294967296) : obj;
}
function toInt(x) {
return x | 0;
}
function toString(x) {
return String(x);
}
function coerce(value, type) {
if (type.coerce) {
return type.coerce(value);
}
if (isNullOrUndefined(value)) {
return null;
}
if (type.isInstance(value)) {
return value;
} else {
// FIXME throwErrorFromVM needs to be called from within the runtime
// because it needs access to the domain or the domain has to be
// aquired through some other mechanism.
// throwErrorFromVM("TypeError", "Cannot coerce " + obj + " to type " + type);
// For now just assert false to print the message.
release || assert(false, "Cannot coerce " + value + " to type " + type);
}
}
/**
* Similar to |toString| but returns |null| for |null| or |undefined| instead
* of "null" or "undefined".
*/
function coerceString(x) {
if (x === null || x === undefined) {
return null;
}
return String(x);
}
function typeOf(x) {
// ABC doesn't box primitives, so typeof returns the primitive type even when
// the value is new'd
if (x) {
if (x.constructor==String) {
return "string"
}
else if (x.constructor==Number) {
return "number"
}
else if (x.constructor==Boolean) {
return "boolean"
}
}
return typeof x;
}
function getSlot(obj, index) {
return obj[obj[VM_SLOTS][index].name];
}
function setSlot(obj, index, value) {
var binding = obj[VM_SLOTS][index];
if (binding.const) {
return;
}
var name = binding.name;
var type = binding.type;
if (type && type.coerce) {
obj[name] = type.coerce(value);
} else {
obj[name] = value;
}
}
function nextName(obj, index) {
return obj[VM_NEXT_NAME](index);
}
function nextValue(obj, index) {
return obj[Multiname.getPublicQualifiedName(obj[VM_NEXT_NAME](index))];
}
/**
* Determine if the given object has any more properties after the specified |index| in the given |obj|
* and if so, return the next index or |zero| otherwise. If the |obj| has no more properties then continue
* the search in |obj.__proto__|. This function returns an updated index and object to be used during
* iteration.
*
* the |for (x in obj) { ... }| statement is compiled into the following pseudo bytecode:
*
* index = 0;
* while (true) {
* (obj, index) = hasNext2(obj, index);
* if (index) { #1
* x = nextName(obj, index); #2
* } else {
* break;
* }
* }
*
* #1 If we return zero, the iteration stops.
* #2 The spec says we need to get the nextName at index + 1, but it's actually index - 1, this caused
* me two hours of my life that I will probably never get back.
*
* TODO: We can't match the iteration order semantics of Action Script, hopefully programmers don't rely on it.
*/
function hasNext2(obj, index) {
if (obj === null || obj === undefined) {
return {index: 0, object: null};
}
obj = Object(obj);
release || assert(index >= 0);
/**
* Because I don't think hasnext/hasnext2/nextname opcodes are used outside
* of loops in "normal" ABC code, we can deviate a little for semantics here
* and leave the prototype-chaining to the |for..in| operator in JavaScript
* itself, in |obj[VM_NEXT_NAME_INDEX]|. That is, the object pushed onto the
* stack, if the original object has any more properties left, will _always_
* be the original object.
*/
return {index: obj[VM_NEXT_NAME_INDEX](index), object: obj};
}
function getDescendants(multiname, obj) {
notImplemented("getDescendants");
}
function checkFilter(value) {
notImplemented("checkFilter");
}
function Activation (methodInfo) {
this.methodInfo = methodInfo;
}
var Interface = (function () {
function Interface(classInfo) {
var ii = classInfo.instanceInfo;
release || assert(ii.isInterface());
this.name = ii.name;
this.classInfo = classInfo;
}
Interface.prototype = {
toString: function () {
return "[interface " + this.name + "]";
},
isInstance: function (value) {
if (value === null || typeof value !== "object") {
return false;
}
var cls = value.class;
while (cls) {
var interfaces = cls.implementedInterfaces;
if (interfaces) {
for (var i = 0, j = interfaces.length; i < j; i++) {
if (interfaces[i] === this) {
return true;
}
}
}
cls = cls.baseClass;
}
return false;
},
call: function (v) {
return v;
},
apply: function ($this, args) {
return args[0];
}
};
return Interface;
})();
/**
* Scopes are used to emulate the scope stack as a linked list of scopes, rather than a stack. Each
* scope holds a reference to a scope [object] (which may exist on multiple scope chains, thus preventing
* us from chaining the scope objects together directly).
*
* Scope Operations:
*
* push scope: scope = new Scope(scope, object)
* pop scope: scope = scope.parent
* get global scope: scope.global
* get scope object: scope.object
*
* Method closures have a [savedScope] property which is bound when the closure is created. Since we use a
* linked list of scopes rather than a scope stack, we don't need to clone the scope stack, we can bind
* the closure to the current scope.
*
* The "scope stack" for a method always starts off as empty and methods push and pop scopes on their scope
* stack explicitly. If a property is not found on the current scope stack, it is then looked up
* in the [savedScope]. To emulate this we actually wrap every generated function in a closure, such as
*
* function fnClosure(scope) {
* return function fn() {
* ... scope;
* };
* }
*
* When functions are created, we bind the function to the current scope, using fnClosure.bind(null, this)();
*
* Scope Caching:
*
* Calls to |findProperty| are very expensive. They recurse all the way to the top of the scope chain and then
* laterally across other scripts. We optimize this by caching property lookups in each scope using Multiname
* |id|s as keys. Each Multiname object is given a unique ID when it's constructed. For QNames we only cache
* string QNames.
*
* TODO: This is not sound, since you can add/delete properties to/from with scopes.
*/
var Scope = (function () {
function scope(parent, object, isWith) {
this.parent = parent;
this.object = object;
this.global = parent ? parent.global : this;
this.isWith = isWith;
this.cache = Object.create(null);
}
scope.prototype.findDepth = function findDepth(obj) {
var current = this;
var depth = 0;
while (current) {
if (current.object === obj) {
return depth;
}
depth ++;
current = current.parent;
}
return -1;
};
scope.prototype.findProperty = function findProperty(mn, domain, strict, scopeOnly) {
release || assert(this.object);
release || assert(Multiname.isMultiname(mn));
var obj;
var cache = this.cache;
var id = typeof mn === "string" ? mn : mn.id;
if (!scopeOnly && id && (obj = cache[id])) {
return obj;
}
if (traceScope.value || tracePropertyAccess.value) {
print("Scope.findProperty(" + mn + ")");
}
obj = this.object;
if (Multiname.isQName(mn)) {
if (this.isWith) {
if (Multiname.getQualifiedName(mn) in obj) {
return obj;
}
} else {
if (nameInTraits(obj, Multiname.getQualifiedName(mn))) {
id && (cache[id] = obj);
return obj;
}
}
} else {
if (this.isWith) {
if (resolveMultiname(obj, mn)) {
return obj;
}
} else {
if (resolveMultinameInTraits(obj, mn)) {
id && (cache[id] = obj);
return obj;
}
}
}
if (this.parent) {
obj = this.parent.findProperty(mn, domain, strict, scopeOnly);
id && (cache[mn.id] = obj);
return obj;
}
if (scopeOnly) {
return null;
}
// If we can't find it still, then look at the domain toplevel.
var r;
if ((r = domain.findProperty(mn, strict, true))) {
return r;
}
if (strict) {
unexpected("Cannot find property " + mn);
}
return this.global.object;
};
scope.prototype.trace = function () {
var current = this;
while (current) {
print(current.object + (current.object ? " - " + current.object.debugName : ""));
current = current.parent;
}
};
return scope;
})();
/**
* Check if a qualified name is in an object's traits.
*/
function nameInTraits(obj, qn) {
// If the object itself holds traits, try to resolve it. This is true for
// things like global objects and activations, but also for classes, which
// both have their own traits and the traits of the Class class.
if (obj.hasOwnProperty(VM_BINDINGS) && obj.hasOwnProperty(qn)) {
return true;
}
// Else look on the prototype.
var proto = Object.getPrototypeOf(obj);
return proto.hasOwnProperty(VM_BINDINGS) && proto.hasOwnProperty(qn);
}
function resolveMultinameInTraits(obj, mn) {
release || assert(!Multiname.isQName(mn), mn, " already resolved");
obj = Object(obj);
for (var i = 0, j = mn.namespaces.length; i < j; i++) {
var qn = mn.getQName(i);
if (nameInTraits(obj, Multiname.getQualifiedName(qn))) {
return qn;
}
}
return undefined;
}
/**
* Resolving a multiname on an object using linear search.
*/
function resolveMultiname(obj, mn, traitsOnly) {
assert(!Multiname.isQName(mn), mn, " already resolved");
obj = Object(obj);
enter(true);
var publicQn;
// Check if the object that we are resolving the multiname on is a JavaScript native prototype
// and if so only look for public (dynamic) properties. The reason for this is because we cannot
// overwrite the native prototypes to fit into our trait/dynamic prototype scheme, so we need to
// work around it here during name resolution.
var isNative = isNativePrototype(obj);
for (var i = 0, j = mn.namespaces.length; i < j; i++) {
var qn = mn.getQName(i);
if (traitsOnly) {
if (nameInTraits(obj, Multiname.getQualifiedName(qn))) {
leave(true);
return qn;
}
continue;
}
if (mn.namespaces[i].isDynamic()) {
publicQn = qn;
if (isNative) {
break;
}
} else if (!isNative) {
if (Multiname.getQualifiedName(qn) in obj) {
leave(true);
return qn;
}
}
}
if (publicQn && !traitsOnly && (Multiname.getQualifiedName(publicQn) in obj)) {
leave(true);
return publicQn;
}
leave(true);
return undefined;
}
function isPrimitiveType(x) {
return typeof x === "number" || typeof x === "string" || typeof x === "boolean";
}
function sliceArguments(args, offset) {
return Array.prototype.slice.call(args, offset);
}
function getProperty(obj, mn) {
release || assert(obj !== undefined, "getProperty(", mn, ") on undefined");
if (obj.canHandleProperties) {
return obj.get(mn.name);
}
release || assert(Multiname.isMultiname(mn));
var resolved = Multiname.isQName(mn) ? mn : resolveMultiname(obj, mn);
var value = undefined;
if (!resolved && (isPrimitiveType(obj))) {
throw new ReferenceError(formatErrorMessage(Errors.ReadSealedError, mn.name, typeof obj));
}
if (resolved !== undefined) {
if (Multiname.isAnyName(resolved)) {
return undefined;
}
if (Multiname.isNumeric(resolved) && obj.indexGet) {
value = obj.indexGet(Multiname.getQualifiedName(resolved), value);
} else {
value = obj[Multiname.getQualifiedName(resolved)];
}
} else {
value = obj[Multiname.getPublicQualifiedName(mn.name)];
}
if (tracePropertyAccess.value) {
print("getProperty(" + obj.toString() + ", " + mn + " -> " + resolved + ") has value: " + !!value);
}
return value;
}
function hasProperty(obj, mn) {
release || assert(obj !== undefined, "hasProperty(", mn, ") on undefined");
var resolved = Multiname.isQName(mn) ? mn : resolveMultiname(obj, mn);
if (!resolved) {
Multiname.getPublicQualifiedName(mn.name) in obj;
return false;
}
return Multiname.getQualifiedName(resolved) in obj;
}
function getSuper(scope, obj, mn) {
release || assert(scope instanceof Scope);
release || assert(obj !== undefined, "getSuper(" + mn + ") on undefined");
release || assert(Multiname.isMultiname(mn));
var superClass = scope.object.baseClass;
release || assert(superClass);
var superTraits = superClass.instance.prototype;
var resolved = mn.isQName() ? mn : resolveMultiname(superTraits, mn);
var value = undefined;
if (resolved) {
if (Multiname.isNumeric(resolved) && superTraits.indexGet) {
value = superTraits.indexGet(Multiname.getQualifiedName(resolved), value);
} else {
// Which class is it really on?
var qn = Multiname.getQualifiedName(resolved);
var openMethod = superTraits[VM_OPEN_METHODS][qn];
var superName = superClass.classInfo.instanceInfo.name;
// If we're getting a method closure on the super class, close the open
// method now and save it to a mangled name. We can't go through the
// normal memoizer here because we could be overriding our own method or
// getting into an infinite loop (getters that access the property
// they're set to on the same object is bad news).
if (openMethod) {
value = obj[superName + " " + qn];
if (!value) {
value = obj[superName + " " + qn] = openMethod.bind(obj);
}
} else {
var descriptor = Object.getOwnPropertyDescriptor(superTraits, qn);
release || assert(descriptor);
value = descriptor.get ? descriptor.get.call(obj) : obj[qn];
}
}
}
if (tracePropertyAccess.value) {
print("getSuper(" + mn + ") has value: " + !!value);
}
return value;
}
function setProperty(obj, mn, value) {
release || assert(obj);
if (obj.canHandleProperties) {
return obj.set(mn.name, value);
}
release || assert(Multiname.isMultiname(mn));
var resolved = Multiname.isQName(mn) ? mn : resolveMultiname(obj, mn);
if (tracePropertyAccess.value) {
print("setProperty(" + mn + ") trait: " + value);
}
if (resolved === undefined) {
// If we couldn't find the property, create one dynamically.
// TODO: check sealed status
resolved = Multiname.getPublicQualifiedName(mn.name);
}
if (Multiname.isNumeric(resolved) && obj.indexSet) {
obj.indexSet(Multiname.getQualifiedName(resolved), value);
} else {
obj[Multiname.getQualifiedName(resolved)] = value;
}
}
function setSuper(scope, obj, mn, value) {
release || assert(obj);
release || assert(Multiname.isMultiname(mn));
var superClass = scope.object.baseClass;
release || assert(superClass);
if (tracePropertyAccess.value) {
print("setProperty(" + mn + ") trait: " + value);
}
var superTraits = superClass.instance.prototype;
var resolved = Multiname.isQName(mn) ? mn : resolveMultiname(superTraits, mn);
if (resolved !== undefined) {
if (Multiname.isNumeric(resolved) && superTraits.indexSet) {
superTraits.indexSet(Multiname.getQualifiedName(resolved), value);
} else {
var qn = Multiname.getQualifiedName(resolved);
var descriptor = Object.getOwnPropertyDescriptor(superTraits, qn);
release || assert(descriptor);
if (descriptor.set) {
descriptor.set.call(obj, value);
} else {
obj[qn] = value;
}
}
} else {
throw new ReferenceError("Cannot create property " + mn.name +
" on " + superClass.debugName);
}
}
function deleteProperty(obj, mn) {
release || assert(obj);
if (obj.canHandleProperties) {
return obj.delete(mn.name);
}
release || assert(Multiname.isMultiname(mn), mn);
var resolved = Multiname.isQName(mn) ? mn : resolveMultiname(obj, mn);
if (resolved === undefined) {
return true;
}
// Only dynamic properties can be deleted, so only look for those.
if (resolved instanceof Multiname && !resolved.namespaces[0].isPublic() ||
typeof obj !== "object" || obj === null) { // if primitive, then return false
return false;
}
var qn = Multiname.getQualifiedName(resolved);
if (!(qn in Object.getPrototypeOf(obj))) {
/**
* If we're in the middle of an enumeration "delete" the property from the
* enumeration keys as well. Setting it to |undefined| will cause it to be
* skipped by the enumeration bytecodes.
*/
if (obj[VM_ENUMERATION_KEYS]) {
var index = obj[VM_ENUMERATION_KEYS].indexOf(qn);
if (index >= 0) {
obj[VM_ENUMERATION_KEYS][index] = VM_TOMBSTONE;
}
}
return delete obj[Multiname.getQualifiedName(resolved)];
}
return false;
}
function isInstanceOf(value, type) {
/*
if (type instanceof Class) {
return value instanceof type.instance;
} else if (typeof type === "function") {
return value instanceof type;
} else {
return false;
}
*/
return type.isInstanceOf(value);
}
function asInstance(value, type) {
return type.isInstance(value) ? value : null;
}
function isInstance(value, type) {
return type.isInstance(value);
}
function createActivation(methodInfo) {
return Object.create(methodInfo.activationPrototype);
}
/**
* Scope object backing for catch blocks.
*/
function CatchScopeObject(runtime, varTrait) {
if (varTrait) {
runtime.applyTraits(this, new Scope(null, this), null, [varTrait], null, false);
}
}
/**
* Global object for a script.
*/
var Global = (function () {
function Global(runtime, script) {
this.scriptInfo = script;
script.global = this;
script.abc = runtime.abc;
runtime.applyTraits(this, new Scope(null, this), null, script.traits, null, false);
script.loaded = true;
}
Global.prototype.toString = function () {
return "[object global]";
};
Global.prototype.isExecuted = function () {
return this.scriptInfo.executed;
};
Global.prototype.ensureExecuted = function () {
ensureScriptIsExecuted(this.scriptInfo);
};
defineNonEnumerableProperty(Global.prototype, Multiname.getPublicQualifiedName("toString"), function () {
return this.toString();
});
return Global;
})();
/**
* Execution context for an ABC.
*/
var Runtime = (function () {
var totalFunctionCount = 0;
var compiledFunctionCount = 0;
/**
* Checks if the specified method should be compiled. For now we just ignore very large methods.
*/
function shouldCompile(mi) {
if (mi.hasExceptions() && !compilerEnableExceptions.value) {
return false;
} else if (mi.code.length > compilerMaximumMethodSize.value) {
return false;
}
return true;
}
function runtime(abc) {
this.abc = abc;
this.domain = abc.domain;
if (this.domain.mode !== EXECUTION_MODE.INTERPRET) {
this.compiler = new C4Compiler(abc);
}
this.interpreter = new Interpreter(abc);
/**
* All runtime exceptions are boxed in this object to tag them as having
* originated from within the VM.
*/
this.exception = { value: undefined };
}
// We sometimes need to know where we came from, such as in
// |ApplicationDomain.currentDomain|.
runtime.stack = [];
runtime.currentDomain = function () {
if (Runtime.stack.length) {
return Runtime.stack.top().domain;
}
return null;
};
// This is called from catch blocks.
runtime.unwindStackTo = function unwindStackTo(rt) {
var stack = runtime.stack;
var unwind = stack.length;
while (stack[unwind - 1] !== rt) {
unwind--;
}
stack.length = unwind;
};
/**
* Creates a method from the specified |methodInfo| that is bound to the given |scope|. If the
* scope is dynamic (as is the case for closures) the compiler generates an additional prefix
* parameter for the compiled function named |SAVED_SCOPE_NAME| and then wraps the compiled
* function in a closure that is bound to the given |scope|. If the scope is not dynamic, the
* compiler bakes it in as a constant which should be much more efficient.
*/
runtime.prototype.createFunction = function createFunction(methodInfo, scope, hasDynamicScope, breakpoint) {
var mi = methodInfo;
release || assert(!mi.isNative(), "Method should have a builtin: ", mi.name);
var hasDefaults = false;
var defaults = mi.parameters.map(function (p) {
if (p.value !== undefined) {
hasDefaults = true;
}
return p.value;
});
function interpretedMethod(interpreter, methodInfo, scope) {
var fn = function () {
var global = (this === jsGlobal ? scope.global.object : this);
var args;
if (hasDefaults && arguments.length < defaults.length) {
args = Array.prototype.slice.call(arguments);
args = args.concat(defaults.slice(arguments.length - defaults.length));
} else {
args = arguments;
}
return interpreter.interpretMethod(global, methodInfo, scope, args);
};
fn.instance = fn;
return fn;
}
var mode = this.domain.mode;
// We use not having an analysis to mean "not initialized".
if (!mi.analysis) {
mi.analysis = new Analysis(mi, { massage: true });
if (mi.traits) {
mi.activationPrototype = this.applyTraits(new Activation(mi), null, null, mi.traits, null, false);
}
// If we have exceptions, make the catch scopes now.
var exceptions = mi.exceptions;
for (var i = 0, j = exceptions.length; i < j; i++) {
var handler = exceptions[i];
if (handler.varName) {
var varTrait = Object.create(Trait.prototype);
varTrait.kind = TRAIT_Slot;
varTrait.name = handler.varName;
varTrait.typeName = handler.typeName;
varTrait.holder = mi;
handler.scopeObject = new CatchScopeObject(this, varTrait);
} else {
handler.scopeObject = new CatchScopeObject();
}
}
}
totalFunctionCount ++;
if (mode === EXECUTION_MODE.INTERPRET || !shouldCompile(mi)) {
return interpretedMethod(this.interpreter, mi, scope);
}
if (compileOnly.value >= 0) {
if (Number(compileOnly.value) !== totalFunctionCount) {
print("Compile Only Skipping " + totalFunctionCount);
return interpretedMethod(this.interpreter, mi, scope);
}
}
if (compileUntil.value >= 0) {