This repository has been archived by the owner on Jul 3, 2019. It is now read-only.
/
compiler.js
1257 lines (1152 loc) · 44.5 KB
/
compiler.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
var enableOpt = options.register(new Option("opt", "opt", true, "Enable optimizations."));
const T = estransform;
const Literal = T.Literal;
const Identifier = T.Identifier;
const VariableDeclaration = T.VariableDeclaration;
const VariableDeclarator = T.VariableDeclarator;
const MemberExpression = T.MemberExpression;
const BinaryExpression = T.BinaryExpression;
const SequenceExpression = T.SequenceExpression;
const CallExpression = T.CallExpression;
const AssignmentExpression = T.AssignmentExpression;
const ExpressionStatement = T.ExpressionStatement;
const ReturnStatement = T.ReturnStatement;
const Program = T.Program;
const Statement = T.Statement;
const FunctionDeclaration = T.FunctionDeclaration;
const FunctionExpression = T.FunctionExpression;
const ConditionalExpression = T.ConditionalExpression;
const ObjectExpression = T.ObjectExpression;
const ArrayExpression = T.ArrayExpression;
const UnaryExpression = T.UnaryExpression;
const NewExpression = T.NewExpression;
const UpdateExpression = T.UpdateExpression;
const ForStatement = T.ForStatement;
const BlockStatement = T.BlockStatement;
const ThisExpression = T.ThisExpression;
const TypeAliasDirective = T.TypeAliasDirective;
const CastExpression = T.CastExpression;
const ThrowStatement = T.ThrowStatement;
const IfStatement = T.IfStatement;
const WhileStatement = T.WhileStatement;
const BreakStatement = T.BreakStatement;
const ContinueStatement = T.ContinueStatement;
const scopeName = new Identifier("$S");
const savedScopeName = new Identifier("$$S");
const constantsName = new Identifier("$C");
/**
* 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. To embed a reference to an object [k] we call
* [constant(k)] which may generate the literal "$C[12]".
*/
var $C = [];
const SCOPE_NAME = "$S";
const SAVED_SCOPE_NAME = "$" + SCOPE_NAME;
function generate(node) {
return escodegen.generate(node, {base: "", indent: " "});
}
var Compiler = (function () {
function objectId(obj) {
assert(obj);
if (obj.hasOwnProperty("objectId")) {
return obj.objectId;
}
var id = $C.length;
Object.defineProperty(obj, "objectId", {value: id, writable: false, enumerable: false});
$C.push(obj);
return id;
}
Control.Break.prototype.compile = function (cx, state) {
return cx.compileBreak(this, state);
};
Control.Continue.prototype.compile = function (cx, state) {
return cx.compileContinue(this, state);
};
Control.Exit.prototype.compile = function (cx, state) {
return cx.compileExit(this, state);
};
Control.LabelSwitch.prototype.compile = function (cx, state) {
return cx.compileLabelSwitch(this, state);
};
Control.Seq.prototype.compile = function (cx, state) {
return cx.compileSequence(this, state);
};
Bytecode.prototype.compile = function (cx, state) {
return cx.compileBytecode(this, state);
};
Control.Loop.prototype.compile = function (cx, state) {
return cx.compileLoop(this, state);
};
Control.Switch.prototype.compile = function (cx, state) {
return cx.compileSwitch(this, state);
};
Control.If.prototype.compile = function (cx, state) {
return cx.compileIf(this, state);
};
var Constant = (function () {
function constant(value) {
this.value = value;
if (value === undefined) {
Identifier.call(this, "undefined");
} else if (value !== null && typeof value === "object") {
assert (value instanceof Multiname ||
value instanceof Runtime ||
value instanceof MethodInfo ||
value instanceof ClassInfo ||
value instanceof AbcFile ||
value instanceof Array,
"Should not make constants from ", value);
MemberExpression.call(this, constantsName, new Literal(objectId(value)), true);
} else {
Literal.call(this, value);
}
}
constant.prototype.isEquivalent = function (other) {
return other instanceof Constant && this.value === other.value;
};
return constant;
})();
function constant(value) {
return new Constant(value);
}
function property(obj, path) {
path.split(".").forEach(function(x) {
obj = new MemberExpression(obj, new Identifier(x), false);
});
return obj;
}
function call(callee, args) {
assert (args instanceof Array);
args.forEach(function (x) {
assert (!(x instanceof Array));
});
return new CallExpression(callee, args);
}
function callCall(callee, args) {
return call(property(callee, "call"), args);
}
function assignment(left, right) {
assert (left && right);
return new AssignmentExpression(left, "=", right);
}
function binary (operator, left, right) {
return new BinaryExpression(operator.name, left, right);
}
function asInt32(value) {
return binary(Operator.OR, value, constant(0));
}
function id(name) {
return new Identifier(name);
}
function removeBlock(node) {
if (node instanceof BlockStatement) {
return node.body;
}
return node;
}
function compiler(abc) {
this.writer = new IndentingWriter();
this.abc = abc;
}
/**
* Abstract program state.
*/
var State = (function () {
var stateCounter = 0;
function state() {
this.stack = [];
this.scopeHeight = 0;
this.id = stateCounter ++;
}
state.prototype.clone = function clone() {
var s = new State();
s.stack = this.stack.slice(0);
s.scopeHeight = this.scopeHeight;
return s;
};
state.prototype.trace = function trace(writer) {
writer.enter("state id: " + stateCounter + ", scopeHeight: " + this.scopeHeight + ", stack: {");
for (var i = 0; i < this.stack.length; i++) {
writer.writeLn(i + ": " + generate(this.stack[i]));
}
writer.leave("}");
};
return state;
})();
/**
* Describes binary and unary operators.
*/
var Operator = (function () {
var map = {};
function operator(name, fn, binary) {
this.name = name;
this.fn = fn;
this.binary = binary;
map[name] = this;
}
operator.ADD = new operator("+", function (l, r) { return l + r; }, true);
operator.SUB = new operator("-", function (l, r) { return l - r; }, true);
operator.MUL = new operator("*", function (l, r) { return l * r; }, true);
operator.DIV = new operator("/", function (l, r) { return l / r; }, true);
operator.MOD = new operator("%", function (l, r) { return l % r; }, true);
operator.AND = new operator("&", function (l, r) { return l & r; }, true);
operator.OR = new operator("|", function (l, r) { return l | r; }, true);
operator.XOR = new operator("^", function (l, r) { return l ^ r; }, true);
operator.LSH = new operator("<<", function (l, r) { return l << r; }, true);
operator.RSH = new operator(">>", function (l, r) { return l >> r; }, true);
operator.URSH = new operator(">>>", function (l, r) { return l >>> r; }, true);
operator.SEQ = new operator("===", function (l, r) { return l === r; }, true);
operator.SNE = new operator("!==", function (l, r) { return l !== r; }, true);
operator.EQ = new operator("==", function (l, r) { return l == r; }, true);
operator.NE = new operator("!=", function (l, r) { return l != r; }, true);
operator.LE = new operator("<=", function (l, r) { return l <= r; }, true);
operator.GT = new operator(">", function (l, r) { return l > r; }, true);
operator.LT = new operator("<", function (l, r) { return l < r; }, true);
operator.GE = new operator(">=", function (l, r) { return l >= r; }, true);
operator.BITWISE_NOT = new operator("~", function (a) { return ~a; }, false);
operator.NEG = new operator("-", function (a) { return -a; }, false);
operator.TRUE = new operator("!!", function (a) { return !!a; }, false);
operator.FALSE = new operator("!", function (a) { return !a; }, false);
function linkOpposites(a, b) {
a.not = b;
b.not = a;
}
/**
* Note that arithmetic comparisons aren't partial orders and cannot be
* negated to each other.
*/
linkOpposites(operator.SEQ, operator.SNE);
linkOpposites(operator.EQ, operator.NE);
linkOpposites(operator.TRUE, operator.FALSE);
operator.fromName = function fromName(name) {
return map[name];
};
operator.prototype.isBinary = function isBinary() {
return this.binary;
};
operator.prototype.toString = function toString() {
return this.name;
};
return operator;
})();
function negate(node) {
assert (node instanceof BinaryExpression || node instanceof UnaryExpression);
var left = node instanceof BinaryExpression ? node.left : node.argument;
var right = node.right;
var operator = Operator.fromName(node.operator);
if (operator === Operator.EQ && right instanceof Literal && right.value === false) {
return left;
}
if (operator === Operator.FALSE) {
return left;
}
if (operator.not) {
if (node instanceof BinaryExpression) {
return new BinaryExpression(operator.not.name, left, right);
} else {
return new UnaryExpression(operator.not.name, left);
}
}
return new UnaryExpression(Operator.FALSE.name, node);
}
var FindProperty = (function () {
function findProperty(multiname, strict) {
this.strict = strict;
this.multiname = multiname;
CallExpression.call(this, property(scopeName, "findProperty"), [this.multiname, new Literal(this.strict)]);
};
findProperty.prototype = Object.create(CallExpression.prototype);
findProperty.prototype.isEquivalent = function isEquivalent(other) {
return other instanceof findProperty &&
this.multiname.isEquivalent(other.multiname) &&
this.strict === other.strict;
};
return findProperty;
})();
/**
* Wrapper around a named local variable.
*/
var Variable = (function () {
function variable(name) {
Identifier.call(this, name);
}
variable.prototype = Object.create(Identifier.prototype);
variable.prototype.toString = function toString() {
return this.name;
};
variable.prototype.isEquivalent = function isEquivalent(other) {
return other instanceof variable && this.name === other.name;
};
return variable;
})();
/**
* Keeps track of a pool of variables that may be reused.
*/
var VariablePool = (function () {
function variablePool() {
this.count = 0;
this.used = [];
this.available = [];
}
variablePool.prototype.acquire = function () {
if (!this.available.empty()) {
return this.available.pop();
}
var variable = new Variable("v" + this.count++);
this.used.push(variable);
return variable;
};
variablePool.prototype.release = function (variable) {
assert (this.used.contains(variable));
this.available.push(variable);
};
variablePool.prototype.releaseAll = function () {
this.available = this.available.concat(this.used);
this.used = [];
};
return variablePool;
})();
/**
* Common subexpression elimination is only used to CSE scope lookups for now,
* use it more aggressively. Each basic block maintains a list of values which
* are checked whenever new values are added to the list. If a [equivalent] value
* already exists in the list, the old value is returned. The values are first
* looked up in the current list, then in the parent's (immediate dominator) list.
*/
var CSE = (function () {
function cse(parent, variablePool) {
this.parent = parent;
this.variablePool = variablePool;
this.values = [];
}
/**
* Finds and returns an equivalent value or returns null if not found.
* If |allocate| is true and an equivalent value is not found, then
* a variable is allocated for the current value and the original value
* is returned.
*/
cse.prototype.get = function get(value, allocate) {
if (value instanceof Variable || value instanceof Literal) {
return value;
}
var values = this.values;
for (var i = values.length - 1; i >= 0; i--) {
var other = values[i];
if (value.isEquivalent(other)) {
assert (other.variable);
return other;
}
}
if (this.parent) {
var otherValue = this.parent.get(value, false);
if (otherValue) {
return otherValue;
}
}
if (!allocate) {
return null;
}
value.variable = this.variablePool.acquire();
this.values.push(value);
return value;
};
cse.prototype.reset = function reset() {
this.values = [];
this.variablePool.releaseAll();
};
return cse;
})();
var Compilation = (function () {
function compilation(compiler, methodInfo, scope) {
this.compiler = compiler;
var mi = this.methodInfo = methodInfo;
this.bytecodes = methodInfo.analysis.bytecodes;
this.state = new State();
this.variablePool = new VariablePool();
this.temporary = [];
/* Initialize local variables, first local is the |this| reference. */
this.local = [new Variable("this")];
var freeVariableNames = "abcdefghijklmnopqrstuvwxyz".split("");
/* Create variables for the method's parameters. */
for (var i = 0; i < mi.parameters.length; i++) {
var name = mi.parameters[i].name;
this.local.push(new Variable(name));
if (freeVariableNames.indexOf(name) >= 0) {
delete freeVariableNames[freeVariableNames.indexOf(name)];
}
}
var freshVariableCount = 0;
function newVariableName() {
var name = null;
for (var i = 0; i < freeVariableNames.length; i++) {
if ((name = freeVariableNames[i])) {
delete freeVariableNames[i];
return name;
}
}
return "$l" + freshVariableCount++;
}
/* Create variables for the method's remaining locals. */
for (var i = mi.parameters.length; i < mi.localCount; i++) {
this.local.push(new Variable(newVariableName()));
}
this.prologue = [];
this.prologue.push(new VariableDeclaration("var", [
new VariableDeclarator(id(SCOPE_NAME), id(SAVED_SCOPE_NAME))
]));
/* Declare local variables. */
if (this.local.length > 1) {
this.prologue.push(new VariableDeclaration("var", this.local.slice(1).map(function (x) {
return new VariableDeclarator(x, null);
})));
}
var parameterCount = mi.parameters.length;
if (mi.needsRest() || mi.needsArguments()) {
this.prologue.push(new ExpressionStatement(
assignment(this.local[parameterCount + 1],
call(property(id("Array"), "prototype.slice.call"),
[id("arguments"), constant(mi.needsRest() ? parameterCount + 1 : 1)]))));
}
/* Initialize default arguments. */
var argumentCount = property(id("arguments"), "length");
for (var i = 0; i < parameterCount; i++) {
var value = mi.parameters[i].value;
if (value) {
var local = this.local[i + 1];
this.prologue.push(new IfStatement(binary(Operator.LT, argumentCount, constant(i + 2)),
new ExpressionStatement(assignment(local, constant(value))),
null));
}
}
}
compilation.prototype.compile = function compile() {
var node = this.methodInfo.analysis.controlTree.compile(this, this.state).node;
assert (node instanceof BlockStatement);
if (this.temporary.length > 1) {
this.prologue.push(new VariableDeclaration("var", this.temporary.map(function (x) {
return new VariableDeclarator(x, null);
})));
}
var usedVariables = this.variablePool.used;
if (usedVariables.length) {
this.prologue.push(new VariableDeclaration("var", usedVariables.map(function (x) {
return new VariableDeclarator(x, null);
})));
}
Array.prototype.unshift.apply(node.body, this.prologue);
return node;
};
compilation.prototype.compileLabelSwitch = function compileLabelSwitch(item, state) {
var node = null;
var firstCase = true;
for (var i = item.cases.length - 1; i >=0; i--) {
var c = item.cases[i];
node = new IfStatement(new BinaryExpression("===", id("$label"), constant(c.label)),
c.body ? c.body.compile(this, state).node : new BlockStatement(),
node);
}
return {node: node, state: state};
};
compilation.prototype.compileContinue = function compileContinue(item, state) {
var body = [];
if (item.label) {
body.push(new VariableDeclaration("var", [
new VariableDeclarator(id("$label"), id(item.label))
]));
}
body.push(new ContinueStatement(null));
return {node: new BlockStatement(body), state: state};
};
compilation.prototype.compileBreak = function compileBreak(item, state) {
var body = [];
if (item.label) {
body.push(new VariableDeclaration("var", [
new VariableDeclarator(id("$label"), id(item.label))
]));
}
body.push(new BreakStatement(null));
return {node: new BlockStatement(body), state: state};
};
compilation.prototype.compileSequence = function compileSequence(item, state) {
var cx = this;
var body = [];
item.body.forEach(function (x) {
var result = x.compile(cx, state);
if (result.node instanceof BlockStatement) {
body = body.concat(result.node.body);
} else {
body.push(result.node);
}
state = result.state;
});
return {node: new BlockStatement(body), state: state};
};
compilation.prototype.compileLoop = function compileLoop(item, state) {
var br = item.body.compile(this, state);
return {node: new WhileStatement(constant(true), br.node), state: state};
};
compilation.prototype.compileIf = function compileIf(item, state) {
var cr = item.cond.compile(this, state);
var tr = null, er = null;
if (item.then) {
tr = item.then.compile(this, cr.state.clone());
}
if (item.else) {
er = item.else.compile(this, cr.state.clone());
}
assert (tr || er);
var node = cr.node;
var condition = item.negated ? negate(cr.condition) : cr.condition;
generate(condition);
node.body.push(new IfStatement(condition, tr ? tr.node : new BlockStatement([]), er ? er.node : null));
return {node: node, state: (tr || er).state};
};
compilation.prototype.compileBytecode = function compileBytecode(block, state) {
var writer = traceLevel.value <= 2 ? null : this.compiler.writer;
if (writer) {
writer.enter("block " + block.blockId + ", dom: " + block.dominator.blockId + " [" + block.position + "-" + block.end.position + "] {");
writer.leave("}");
}
var body = [];
var local = this.local;
var temporary = this.temporary;
var abc = this.compiler.abc;
var ints = abc.constantPool.ints;
var uints = abc.constantPool.uints;
var doubles = abc.constantPool.doubles;
var strings = abc.constantPool.strings;
var methods = abc.methods;
var multinames = abc.constantPool.multinames;
var runtime = abc.runtime;
var savedScope = this.savedScope;
var multiname, args, value, obj, qn, ns, name, type, factory, index;
function classObject() {
return property(savedScopeName, "object");
}
function superClassInstanceObject() {
return property(classObject(), "baseClass.instance");
}
function superOf(obj) {
return property(obj, "public$constructor.baseClass.instance.prototype");
}
function runtimeProperty(propertyName) {
var result = constant(abc.runtime);
if (propertyName) {
result = property(result, propertyName);
}
return result;
}
function push(value) {
assert (typeof value !== "string");
state.stack.push(value);
}
function cseValue(value) {
if (block.cse) {
var otherValue = block.cse.get(value, true);
if (otherValue === value) {
// flushStack();
emit(assignment(value.variable, value));
value.variable.value = value;
// print("CSE: " + generate(value) + " -> " + value.variable);
}
return otherValue.variable;
}
return value;
}
function flushScope() {
if (block.cse) {
block.cse.reset();
}
}
function setLocal(index) {
assert (state.stack.length);
var value = state.stack.pop();
flushStack();
emit(assignment(local[index], value));
}
function duplicate(value) {
var temp = getTemporary(state.stack.length);
state.stack.push(assignment(temp, value));
state.stack.push(temp);
}
function popValue() {
emit(state.stack.pop());
}
function kill(index) {
flushStack();
emit(assignment(local[index], constant(undefined)));
}
function getSlot(obj, index) {
push(call(id("getSlot"), [obj, constant(index)]));
}
function setSlot(obj, index, value) {
flushStack();
emit(call(id("setSlot"), [obj, constant(index), value]));
}
function getTemporary(index) {
if (index in temporary) {
return temporary[index];
}
return temporary[index] = id("t" + index);
}
/**
* Emits assignments that store stack expressions into temporaries.
*/
function flushStack() {
for (var i = 0; i < state.stack.length; i++) {
if (state.stack[i] !== getTemporary(i)) {
emit(assignment(getTemporary(i), state.stack[i]));
state.stack[i] = getTemporary(i);
}
}
}
function emit(value) {
if (!(value instanceof Statement)) {
value = new ExpressionStatement(value);
}
body.push(value);
}
function emitComment(value) {
// TODO
}
if (enableOpt.value) {
if (block.dominator === block) {
block.cse = new CSE(null, this.variablePool);
} else {
assert (block.dominator.cse, "Dominator should have a CSE map.");
block.cse = new CSE(block.dominator.cse, this.variablePool);
}
}
function expression(operator) {
if (operator.isBinary()) {
var b = state.stack.pop();
var a = state.stack.pop();
push(new BinaryExpression(operator.name, a, b));
} else {
var a = state.stack.pop();
push(new UnaryExpression(operator.name, a));
}
}
var condition = null;
/**
* Remembers the branch condition for this block, which is passed and used by the If control
* node.
*/
function setCondition(operator) {
assert (condition === null);
var b = undefined;
if (operator.isBinary()) {
b = state.stack.pop();
}
var a = state.stack.pop();
if (b) {
condition = new BinaryExpression(operator.name, a, b);
} else {
condition = new UnaryExpression(operator.name, a);
}
}
function setNegatedCondition(operator) {
setCondition(operator);
condition = new UnaryExpression(Operator.FALSE.name, condition);
}
/**
* Find the scope object containing the specified multiname.
*/
function findProperty(multiname, strict) {
return cseValue(new FindProperty(multiname, strict));
}
function getProperty(obj, multiname) {
assert (!(multiname instanceof Multiname), multiname);
if (enableOpt.value && multiname instanceof RuntimeMultiname) {
return new MemberExpression(obj, multiname.name, true);
}
if (multiname instanceof Constant) {
var val = obj instanceof Variable ? obj.value : obj;
if (val instanceof FindProperty && multiname.isEquivalent(val.multiname)) {
if (multiname.value.isQName()) {
return property(obj, multiname.value.getQualifiedName());
}
}
}
/**
* Looping over arrays by index will use a MultinameL
* as it's the simplest type of late name. Instead of
* doing a runtime looking, quickly go through late
* name lookup here.
*/
/*
if (multiname.isRuntimeName() && !multiname.isPublicNamespaced()) {
var value = state.stack.pop();
return call(property(obj, GET_ACCESSOR), [value]);
}
*/
return call(id("getProperty"), [obj, multiname]);
/*
if (enableAccessors.value) {
push(call(property(obj, GET_ACCESSOR), [qn.name]));
} else {
push(new MemberExpression(obj, qn.name, true));
}
*/
}
function setProperty(obj, multiname, value) {
if (enableOpt.value && multiname instanceof RuntimeMultiname) {
return assignment(new MemberExpression(obj, multiname.name, true), value);
}
return call(id("setProperty"), [obj, multiname, value]);
}
function getMultiname(index) {
var multiname = multinames[index];
assert (!multiname.isRuntime());
var c = constant(multiname);
c.multiname = multiname;
return c;
}
var RuntimeMultiname = (function () {
function runtimeMultiname(multiname, ns, name) {
this.multiname = multiname;
this.ns = ns;
this.name = name;
NewExpression.call(this, id("Multiname"), [ns, name]);
};
return runtimeMultiname;
})();
function popMultiname(index) {
var multiname = multinames[index];
if (multiname.isRuntime()) {
var ns = constant(multiname.namespaces), name = constant(multiname.name);
if (multiname.isRuntimeName()) {
name = state.stack.pop();
}
if (multiname.isRuntimeNamespace()) {
ns = state.stack.pop();
}
return new RuntimeMultiname(multiname, ns, name);
} else {
return constant(multiname);
}
}
var bytecodes = this.bytecodes;
for (var bci = block.position, end = block.end.position; bci <= end; bci++) {
var bc = bytecodes[bci];
var op = bc.op;
if (writer) {
writer.writeLn("bytecode bci: " + bci + ", originalBci: " + bc.originalPosition + ", " + bc);
}
switch (op) {
case OP_bkpt: notImplemented(); break;
case OP_throw:
emit(assignment(getTemporary(0), property(constant(abc), "runtime.exception")));
emit(assignment(property(getTemporary(0), "value"), state.stack.pop()));
emit(new ThrowStatement(getTemporary(0)));
break;
case OP_getsuper: notImplemented(); break;
case OP_setsuper: notImplemented(); break;
case OP_dxns: notImplemented(); break;
case OP_dxnslate: notImplemented(); break;
case OP_kill: kill(bc.index); break;
case OP_lf32x4: notImplemented(); break;
case OP_sf32x4: notImplemented(); break;
case OP_ifnlt: setNegatedCondition(Operator.LT); break;
case OP_ifge: setCondition(Operator.GE); break;
case OP_ifnle: setNegatedCondition(Operator.LE); break;
case OP_ifgt: setCondition(Operator.GT); break;
case OP_ifngt: setNegatedCondition(Operator.GT); break;
case OP_ifle: setCondition(Operator.LE); break;
case OP_ifnge: setNegatedCondition(Operator.GE); break;
case OP_iflt: setCondition(Operator.LT); break;
case OP_jump:
// NOP
break;
case OP_iftrue:
setCondition(Operator.TRUE);
break;
case OP_iffalse:
setCondition(Operator.FALSE);
break;
case OP_ifeq: setCondition(Operator.EQ); break;
case OP_ifne: setCondition(Operator.NE); break;
case OP_ifstricteq: setCondition(Operator.SEQ); break;
case OP_ifstrictne: setCondition(Operator.SNE); break;
case OP_lookupswitch:
// notImplemented();
break;
case OP_pushwith:
flushStack();
obj = state.stack.pop();
emit(assignment(scopeName, new NewExpression(id("Scope"), [scopeName, obj])));
state.scopeHeight += 1;
break;
case OP_popscope:
flushStack();
flushScope();
emit(assignment(scopeName, property(scopeName, "parent")));
state.scopeHeight -= 1;
break;
case OP_nextname:
index = state.stack.pop();
obj = state.stack.pop();
push(call(id("nextName"), [obj, index]));
break;
case OP_hasnext:
// TODO: Temporary implementation, totally broken.
push(constant(false));
break;
case OP_hasnext2:
flushStack();
obj = local[bc.object];
index = local[bc.index];
emit(assignment(getTemporary(0), call(id("hasNext2"), [obj, index])));
emit(assignment(local[bc.object], property(getTemporary(0), "object")));
emit(assignment(local[bc.index], property(getTemporary(0), "index")));
push(property(getTemporary(0), "index"));
break;
case OP_pushnull: push(constant(null)); break;
case OP_pushundefined: push(constant(undefined)); break;
case OP_pushfloat: notImplemented(); break;
case OP_nextvalue: notImplemented(); break;
case OP_pushbyte: push(constant(bc.value)); break;
case OP_pushshort: push(constant(bc.value)); break;
case OP_pushstring: push(constant(strings[bc.index])); break;
case OP_pushint: push(constant(ints[bc.index])); break;
case OP_pushuint: push(constant(uints[bc.index])); break;
case OP_pushdouble: push(constant(doubles[bc.index])); break;
case OP_pushtrue: push(constant(true)); break;
case OP_pushfalse: push(constant(false)); break;
case OP_pushnan: push(constant(NaN)); break;
case OP_pop: popValue(); break;
case OP_dup: duplicate(state.stack.pop()); break;
case OP_swap: state.stack.push(state.stack.pop(), state.stack.pop()); break;
case OP_pushscope:
flushStack();
flushScope();
obj = state.stack.pop();
emit(assignment(scopeName, new NewExpression(id("Scope"), [scopeName, obj])));
state.scopeHeight += 1;
break;
case OP_pushnamespace: notImplemented(); break;
case OP_li8: notImplemented(); break;
case OP_li16: notImplemented(); break;
case OP_li32: notImplemented(); break;
case OP_lf32: notImplemented(); break;
case OP_lf64: notImplemented(); break;
case OP_si8: notImplemented(); break;
case OP_si16: notImplemented(); break;
case OP_si32: notImplemented(); break;
case OP_sf32: notImplemented(); break;
case OP_sf64: notImplemented(); break;
case OP_newfunction:
push(call(runtimeProperty("createFunction"), [constant(methods[bc.index]), scopeName]));
break;
case OP_call:
args = state.stack.popMany(bc.argCount);
obj = state.stack.pop();
push(callCall(state.stack.pop(), [obj].concat(args)));
break;
case OP_construct:
args = state.stack.popMany(bc.argCount);
obj = state.stack.pop();
push(new NewExpression(property(obj, "instance"), args));
break;
case OP_callmethod: notImplemented(); break;
case OP_callstatic: notImplemented(); break;
case OP_callsuper:
flushStack();
multiname = getMultiname(bc.index);
args = state.stack.popMany(bc.argCount);
obj = state.stack.pop();
push(call(getProperty(superOf(obj), multiname), [obj].concat(args)));
break;
case OP_callproperty:
flushStack();
args = state.stack.popMany(bc.argCount);
multiname = popMultiname(bc.index);
obj = state.stack.pop();
push(callCall(getProperty(obj, multiname), [obj].concat(args)));
break;
case OP_returnvoid: emit(new ReturnStatement()); break;
case OP_returnvalue: emit(new ReturnStatement(state.stack.pop())); break;
case OP_constructsuper:
args = state.stack.popMany(bc.argCount);
obj = state.stack.pop();
emit(callCall(superClassInstanceObject(), [obj].concat(args)));
break;
case OP_constructprop:
multiname = getMultiname(bc.index);
args = state.stack.popMany(bc.argCount);
obj = state.stack.pop();
push(new NewExpression(property(getProperty(obj, multiname), "instance"), args));
break;
case OP_callsuperid: notImplemented(); break;
case OP_callproplex:
multiname = getMultiname(bc.index);
args = state.stack.popMany(bc.argCount);
obj = state.stack.pop();
push(callCall(getProperty(obj, multiname), [obj].concat(args)));
break;
case OP_callinterface: notImplemented(); break;
case OP_callsupervoid:
flushStack();
multiname = getMultiname(bc.index);
args = state.stack.popMany(bc.argCount);
obj = state.stack.pop();
emit(callCall(getProperty(superOf(obj), multiname), [obj].concat(args)));
break;
case OP_callpropvoid:
args = state.stack.popMany(bc.argCount);
multiname = popMultiname(bc.index);
obj = state.stack.pop();
emit(callCall(getProperty(obj, multiname), [obj].concat(args)));
break;