Repository navigation
Expand file tree
/
Copy pathAsmCodeEmitter.java
More file actions
1897 lines (1563 loc) · 72.4 KB
/
Copy pathAsmCodeEmitter.java
File metadata and controls
1897 lines (1563 loc) · 72.4 KB
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
package loop;
import loop.ast.*;
import loop.ast.script.ArgDeclList;
import loop.ast.script.FunctionDecl;
import loop.ast.script.Unit;
import loop.runtime.Closure;
import loop.runtime.Scope;
import loop.runtime.regex.NamedPattern;
import org.objectweb.asm.*;
import org.objectweb.asm.util.TraceClassVisitor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author dhanji@gmail.com (Dhanji R. Prasanna)
*/
@SuppressWarnings({"FieldCanBeLocal"}) public class AsmCodeEmitter implements Opcodes {
private static final boolean printBytecode = true|| System.getProperty("print_bytecode") != null;
private static final AtomicInteger functionNameSequence = new AtomicInteger();
private static final String IS_LIST_VAR_PREFIX = "__$isList_";
private static final String RUNTIME_LIST_SIZE_VAR_PREFIX = "__$runtimeListSize_";
private static final String RUNTIME_STR_LEN_PREFIX = "__$str_len_";
private static final String IS_STRING_PREFIX = "__$isStr_";
private static final String IS_READER_PREFIX = "__$isRdr_";
private static final String WHERE_SCOPE_FN_PREFIX = "$wh$";
private final Stack<Context> functionStack = new Stack<Context>();
private final Scope scope;
public static class SourceLocation implements Comparable<SourceLocation> {
public final int line;
public final int column;
public SourceLocation(int line, int column) {
this.line = line;
this.column = column;
}
@Override
public int compareTo(SourceLocation that) {
return (this.line * 1000000 + this.column) - (that.line * 1000000 + that.column);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SourceLocation that = (SourceLocation) o;
return column == that.column && line == that.line;
}
@Override
public int hashCode() {
return 31 * line + column;
}
}
private final Map<Class<?>, Emitter> EMITTERS = new HashMap<Class<?>, Emitter>();
AsmCodeEmitter(Scope scope) {
this.scope = scope;
EMITTERS.put(Call.class, callEmitter);
EMITTERS.put(Dereference.class, dereferenceEmitter);
EMITTERS.put(Computation.class, computationEmitter);
EMITTERS.put(IntLiteral.class, intEmitter);
EMITTERS.put(FloatLiteral.class, floatEmitter);
EMITTERS.put(LongLiteral.class, longEmitter);
EMITTERS.put(DoubleLiteral.class, doubleEmitter);
EMITTERS.put(BigIntegerLiteral.class, bigIntegerEmitter);
EMITTERS.put(BigDecimalLiteral.class, bigDecimalEmitter);
EMITTERS.put(BooleanLiteral.class, booleanEmitter);
EMITTERS.put(TypeLiteral.class, typeLiteralEmitter);
EMITTERS.put(Variable.class, variableEmitter);
EMITTERS.put(JavaLiteral.class, javaLiteralEmitter);
EMITTERS.put(BinaryOp.class, binaryOpEmitter);
EMITTERS.put(StringLiteral.class, stringLiteralEmitter);
EMITTERS.put(RegexLiteral.class, regexLiteralEmitter);
EMITTERS.put(Assignment.class, assignmentEmitter);
EMITTERS.put(InlineMapDef.class, inlineMapEmitter);
EMITTERS.put(InlineListDef.class, inlineListEmitter);
EMITTERS.put(IndexIntoList.class, indexIntoListEmitter);
EMITTERS.put(CallChain.class, callChainEmitter);
EMITTERS.put(FunctionDecl.class, functionDeclEmitter);
EMITTERS.put(ArgDeclList.class, argDeclEmitter);
EMITTERS.put(PrivateField.class, privateFieldEmitter);
EMITTERS.put(PatternRule.class, patternRuleEmitter);
EMITTERS.put(TernaryIfExpression.class, ternaryExpressionEmitter);
EMITTERS.put(TernaryUnlessExpression.class, ternaryExpressionEmitter);
EMITTERS.put(Comprehension.class, comprehensionEmitter);
EMITTERS.put(ConstructorCall.class, constructorCallEmitter);
EMITTERS.put(ListRange.class, inlineListRangeEmitter);
}
private final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
private final Stack<MethodVisitor> methodStack = new Stack<MethodVisitor>();
public Class<?> write(Unit unit) {
Thread.currentThread().setContextClassLoader(LoopClassLoader.CLASS_LOADER);
// We always emit functions as static into a containing Java class.
String javaClass = unit.name();
String fileName = unit.getFileName();
if (fileName != null) {
if (!fileName.endsWith(".loop"))
fileName += ".loop";
classWriter.visitSource(fileName, null);
}
classWriter.visit(V1_6, ACC_PUBLIC, javaClass, null, "java/lang/Object", new String[0]);
for (FunctionDecl functionDecl : unit.functions()) {
emit(functionDecl);
}
// Emit any static initializer here.
if (unit.initializer() != null)
emitInitializerBlock(unit.initializer());
classWriter.visitEnd();
if (printBytecode) {
try {
new ClassReader(new ByteArrayInputStream(classWriter.toByteArray())).accept(
new TraceClassVisitor(new PrintWriter(System.out)), ClassReader.SKIP_DEBUG);
} catch (IOException e) {
e.printStackTrace();
}
}
LoopClassLoader.CLASS_LOADER.put(javaClass, classWriter.toByteArray());
try {
return LoopClassLoader.CLASS_LOADER.findClass(javaClass);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private void emitInitializerBlock(List<Node> exprs) {
MethodVisitor initializer = classWriter.visitMethod(ACC_STATIC,
"<clinit>",
"()V",
null,
null);
methodStack.push(initializer);
Context context = new Context(FunctionDecl.STATIC_INITIALIZER);
functionStack.push(context);
scope.pushScope(context);
for (Node expr : exprs) {
emit(expr);
initializer.visitInsn(POP);
}
initializer.visitInsn(RETURN);
initializer.visitMaxs(1, 0);
initializer.visitEnd();
scope.popScope();
functionStack.pop();
methodStack.pop();
}
private void trackLineAndColumn(Node node) {
Label line = new Label();
methodStack.peek().visitLabel(line);
methodStack.peek().visitLineNumber(node.sourceLine, line);
}
private void emitChildren(Node node) {
for (Node child : node.children()) {
emit(child);
}
}
private void emitOnlyChild(Node node) {
emit(node.children().get(0));
}
public void emit(Node node) {
if (!EMITTERS.containsKey(node.getClass()))
throw new RuntimeException("Missing emitter for " + node.getClass().getSimpleName());
EMITTERS.get(node.getClass()).emitCode(node);
}
// -------------------------------------------------------------------
// EMITTERS ----------------------------------------------------------
// -------------------------------------------------------------------
private final Emitter ternaryExpressionEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
boolean unless = node instanceof TernaryUnlessExpression;
MethodVisitor methodVisitor = methodStack.peek();
Label elseBranch = new Label();
Label end = new Label();
// If condition
emit(node.children().get(0));
methodVisitor.visitTypeInsn(CHECKCAST, "java/lang/Boolean");
methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z");
// Flip the clauses in an "unless" expression.
if (unless)
methodVisitor.visitJumpInsn(IFNE, elseBranch);
else
methodVisitor.visitJumpInsn(IFEQ, elseBranch);
emit(node.children().get(1));
methodVisitor.visitJumpInsn(GOTO, end);
methodVisitor.visitLabel(elseBranch);
emit(node.children().get(2));
methodVisitor.visitLabel(end);
}
};
private final Emitter computationEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
trackLineAndColumn(node);
emitChildren(node);
}
};
private final Emitter dereferenceEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
Dereference dereference = (Dereference) node;
trackLineAndColumn(dereference);
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitLdcInsn(dereference.name());
// Special form to call on a java type rather than lookup by class name.
if (dereference.isJavaStatic()) {
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "getStatic",
"(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Object;");
} else {
// If JDK7, use invokedynamic instead for better performance.
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "dereference",
"(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;");
}
}
};
private final Emitter callEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
Call call = (Call) node;
trackLineAndColumn(call);
MethodVisitor methodVisitor = methodStack.peek();
Context context = functionStack.peek();
FunctionDecl resolvedFunction;
if (call.namespace() != null)
resolvedFunction = scope.resolveNamespacedFunction(call.name(), call.namespace());
else
resolvedFunction = call.callJava() ? null : scope.resolveFunctionOnStack(call.name());
// All Loop functions are Java static.
boolean isStatic = resolvedFunction != null, isClosure = false;
// Is this a tail-recursive function?
boolean isTailRecursive = call.isTailCall()
&& call.namespace() == null
&& !call.isJavaStatic()
&& context.thisFunction.equals(resolvedFunction);
// The parse-tree knows if we are calling a java method statically.
if (!isStatic)
isStatic = call.isJavaStatic();
// This is a special invocation so we emit it without the dot.
String name;
if (Closure.CALL_FORM.equals(call.name())) {
name = "";
isStatic = true;
isClosure = true;
} else if (isStatic && resolvedFunction != null) {
name = normalizeMethodName(resolvedFunction.scopedName());
} else
name = normalizeMethodName(call.name());
// No such function exists and it's not a method-call, so let's treat this as a closure call.
if (resolvedFunction == null && !isClosure && !call.isJavaStatic() && isStatic) {
name = "";
isClosure = true;
isStatic = true;
}
// Compute if we should "call as postfix method" (can be overridden with <- operator)
List<Node> arguments = call.args().children();
int callAsPostfixVar = -1;
boolean callAsPostfix = false;
int argSize = arguments.size();
if (resolvedFunction != null && resolvedFunction.arguments() != null) {
// The actual call is 1 less argument than the function takes, so this is a
// "call-as-method" syntax.
if (resolvedFunction.arguments().children().size() - argSize == 1) {
callAsPostfix = true;
callAsPostfixVar = context.localVarIndex(context.newLocalVariable());
argSize++;
// Save the top of the stack for use as the first argument.
methodVisitor.visitVarInsn(ASTORE, callAsPostfixVar);
}
}
// TAIL CALL ELIMINATION:
// Store the call-args into the args of this function and short-circuit the call.
if (isTailRecursive) {
List<Node> children = call.args().children();
for (int i = 0, childrenSize = children.size(); i < childrenSize; i++) {
Node arg = children.get(i);
emit(arg); // value
// Store into the local vars representing the arguments to the recursive function.
methodVisitor.visitVarInsn(ASTORE, i);
}
// If there's anything left, pop it off. If some expression results in void on stack
// rather than null or 0, then we might be screwed.
// Pattern matching functions are well behaved (i.e. not multiline, so leave them alone)
if (!context.thisFunction.patternMatching && context.thisFunction.children().size() > 1) {
for (int i = 1; i < context.thisFunction.children().size(); i++) {
methodVisitor.visitInsn(POP);
}
}
// Loop.
methodVisitor.visitJumpInsn(GOTO, context.startOfFunction);
return;
}
// push name of containing type if this is a static call.
boolean isExternalFunction = resolvedFunction != null
&& resolvedFunction.moduleName != null
&& !scope.getModuleName().equals(resolvedFunction.moduleName);
if (isStatic && !call.isJavaStatic()) {
if (isClosure)
methodVisitor.visitTypeInsn(CHECKCAST, "loop/runtime/Closure");
if (!isExternalFunction)
methodVisitor.visitLdcInsn(scope.getModuleName());
}
// push method name onto stack
if (!isClosure) {
// Emit the module name of the containing class for the resolved function, BUT only
// if it is not in the same module as us.
if (isExternalFunction) {
methodVisitor.visitLdcInsn(resolvedFunction.moduleName);
}
methodVisitor.visitLdcInsn(name);
}
if (argSize > 0) {
int arrayVar = context.localVarIndex(context.newLocalVariable());
// push args as array.
methodVisitor.visitIntInsn(BIPUSH, argSize); // size of array
methodVisitor.visitTypeInsn(ANEWARRAY, "java/lang/Object");
methodVisitor.visitVarInsn(ASTORE, arrayVar);
int i = 0;
if (callAsPostfix) {
methodVisitor.visitVarInsn(ALOAD, arrayVar); // array
methodVisitor.visitIntInsn(BIPUSH, i); // index
methodVisitor.visitVarInsn(ALOAD, callAsPostfixVar); // value
methodVisitor.visitInsn(AASTORE);
i++;
}
for (Node arg : arguments) {
methodVisitor.visitVarInsn(ALOAD, arrayVar); // array
methodVisitor.visitIntInsn(BIPUSH, i); // index
emit(arg); // value
methodVisitor.visitInsn(AASTORE);
i++;
}
// Load the array back in.
methodVisitor.visitVarInsn(ALOAD, arrayVar);
if (isStatic) {
// If JDK7, use invokedynamic instead for better performance.
if (isClosure)
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "callClosure",
"(Lloop/runtime/Closure;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;");
else {
// Special form to call on a java type rather than lookup by class name.
if (call.callJava()) {
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "callStatic",
"(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;");
} else {
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "callStatic",
"(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;");
}
}
} else {
// If JDK7, use invokedynamic instead for better performance.
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "call",
"(Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;");
}
} else {
if (isStatic) {
// If JDK7, use invokedynamic instead for better performance.
if (isClosure)
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "callClosure",
"(Lloop/runtime/Closure;Ljava/lang/String;)Ljava/lang/Object;");
else {
// Special form to call on a java type rather than lookup by class name.
if (call.callJava()) {
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "callStatic",
"(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Object;");
} else {
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "callStatic",
"(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;");
}
}
} else {
// If JDK7, use invokedynamic instead for better performance.
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "call",
"(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;");
}
}
}
};
private final Emitter constructorCallEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
ConstructorCall call = (ConstructorCall) node;
MethodVisitor methodVisitor = methodStack.peek();
Context context = functionStack.peek();
// Try to resolve as an aliased dep first.
ClassDecl classDecl = null;
if (call.modulePart != null && call.modulePart.split("[.]").length == 1)
classDecl = scope.resolveAliasedType(
call.modulePart.substring(0, call.modulePart.length() - 1),
call.name);
// Resolve a loop type internally. Note that this makes dynamic linking
// of Loop types impossible, but we CAN link Java binaries dynamically.
if (classDecl == null)
classDecl = scope.resolve(call.name, true);
if (classDecl != null) {
// Instatiate the loop object first. With the correct type
int objectVar = context.localVarIndex(context.newLocalVariable());
methodVisitor.visitTypeInsn(NEW, "loop/lang/LoopObject");
methodVisitor.visitInsn(DUP);
methodVisitor.visitTypeInsn(NEW, "loop/lang/LoopClass");
methodVisitor.visitInsn(DUP);
methodVisitor.visitLdcInsn(classDecl.name);
methodVisitor.visitMethodInsn(INVOKESPECIAL, "loop/lang/LoopClass", "<init>",
"(Ljava/lang/String;)V");
methodVisitor.visitMethodInsn(INVOKESPECIAL, "loop/lang/LoopObject", "<init>",
"(Lloop/lang/LoopClass;)V");
methodVisitor.visitVarInsn(ASTORE, objectVar);
Map<String, Node> fields = new HashMap<String, Node>();
for (Node nodeAssign : classDecl.children()) {
if (nodeAssign instanceof Assignment) {
Assignment assignment = (Assignment) nodeAssign;
fields.put(((Variable) assignment.lhs()).name, assignment.rhs());
}
}
List<Node> children = call.args().children();
if (!children.isEmpty() || !fields.isEmpty()) {
// First emit named-args as overrides of defaults.
for (Node child : children) {
CallArguments.NamedArg arg = (CallArguments.NamedArg) child;
methodVisitor.visitVarInsn(ALOAD, objectVar);
methodVisitor.visitLdcInsn(arg.name);
emit(arg.arg);
methodVisitor.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
// Puts return crap which we need to discard.
methodVisitor.visitInsn(POP);
}
// Now emit any remaining defaults.
for (Map.Entry<String, Node> field : fields.entrySet()) {
methodVisitor.visitVarInsn(ALOAD, objectVar);
methodVisitor.visitLdcInsn(field.getKey());
emit(field.getValue());
methodVisitor.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
// Puts return crap which we need to discard.
methodVisitor.visitInsn(POP);
}
}
// Leave the object on the stack.
methodVisitor.visitVarInsn(ALOAD, objectVar);
// Should we freeze this object?
if (classDecl.immutable) {
methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "loop/lang/LoopObject", "immutize",
"()Lloop/lang/ImmutableLoopObject;");
// Overwrite the old var in case there is a reference later on.
methodVisitor.visitVarInsn(ASTORE, objectVar);
methodVisitor.visitVarInsn(ALOAD, objectVar);
}
} else {
// Emit Java constructor call.
String javaType;
if (call.modulePart != null)
javaType = call.modulePart + call.name;
else
javaType = scope.resolveJavaType(call.name);
boolean isNullary = call.args().children().isEmpty();
if (!isNullary) {
int arrayVar = context.localVarIndex(context.newLocalVariable());
methodVisitor.visitIntInsn(BIPUSH, call.args().children().size()); // size of array
methodVisitor.visitTypeInsn(ANEWARRAY, "java/lang/Object");
methodVisitor.visitVarInsn(ASTORE, arrayVar);
int i = 0;
for (Node arg : call.args().children()) {
methodVisitor.visitVarInsn(ALOAD, arrayVar); // array
methodVisitor.visitIntInsn(BIPUSH, i); // index
emit(arg); // value
methodVisitor.visitInsn(AASTORE);
i++;
}
// push type and constructor arg array.
methodVisitor.visitLdcInsn(javaType);
methodVisitor.visitVarInsn(ALOAD, arrayVar);
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "instantiate",
"(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;");
} else {
// Otherwise invoke the Java constructor directly. We don't need to resolve it.
// This is an optimization.
javaType = javaType.replace('.', '/');
methodVisitor.visitTypeInsn(NEW, javaType);
methodVisitor.visitInsn(DUP);
methodVisitor.visitMethodInsn(INVOKESPECIAL, javaType, "<init>", "()V");
}
}
}
};
private final Emitter binaryOpEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
BinaryOp binaryOp = (BinaryOp) node;
emitOnlyChild(binaryOp);
MethodVisitor methodVisitor = methodStack.peek();
switch (binaryOp.operator.kind) {
case PLUS:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "plus",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
break;
case MINUS:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "minus",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
break;
case STAR:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "multiply",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
break;
case DIVIDE:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "divide",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
break;
case MODULUS:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "remainder",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
break;
case LESSER:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "lesserThan",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Boolean;");
break;
case LEQ:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "lesserThanOrEqual",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Boolean;");
break;
case GREATER:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "greaterThan",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Boolean;");
break;
case GEQ:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations",
"greaterThanOrEqual",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Boolean;");
break;
case EQUALS:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "equal",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Boolean;");
break;
case AND:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "and",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Boolean;");
// methodVisitor.visitInsn(IAND);
break;
case OR:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "or",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Boolean;");
// methodVisitor.visitInsn(IOR);
break;
case NOT:
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Operations", "notEqual",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Boolean;");
break;
case IN: // HACK for instanceof
methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "isInstance",
"(Ljava/lang/Object;)Z");
break;
default:
throw new UnsupportedOperationException(
"Unsupported binary operator " + binaryOp.toSymbol());
}
}
};
private final Emitter assignmentEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
Assignment assignment = (Assignment) node;
trackLineAndColumn(assignment);
Context context = functionStack.peek();
MethodVisitor methodVisitor = methodStack.peek();
if (assignment.lhs() instanceof Variable) {
int lhsVar = context.localVarIndex(context.newLocalVariable((Variable) assignment.lhs()));
emit(assignment.rhs());
// Leave the result of the assignment on the stack.
methodVisitor.visitInsn(DUP);
methodVisitor.visitVarInsn(ASTORE, lhsVar);
} else if (assignment.lhs() instanceof CallChain) {
// this is a setter/put style assignment.
CallChain lhs = (CallChain) assignment.lhs();
List<Node> children = lhs.children();
Node last = children.remove(children.size() - 1);
if (last instanceof IndexIntoList) {
// The object to assign into.
emit(lhs);
// The slot where this assignment will go.
emit(((IndexIntoList) last).from());
// The value to assign.
emit(assignment.rhs());
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Collections", "store",
"(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
} else if (last instanceof MemberAccess) {
MemberAccess call = (MemberAccess) last;
if (call instanceof Call)
throw new RuntimeException("Cannot assign value to a function call");
// The object to assign into.
emit(lhs);
// The slot where this assignment will go.
methodVisitor.visitLdcInsn(call.name());
// The value to assign.
emit(assignment.rhs());
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Collections", "store",
"(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
} else
throw new RuntimeException("Can only assign a value to variable or object property");
}
}
};
private final Emitter variableEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
Variable var = (Variable) node;
Context context = functionStack.peek();
Integer index = context.argumentIndex.get(var.name);
if (index == null)
index = context.localVarIndex(var.name);
if (index == null) {
// It could be a function-reference. In which case emit it as a closure.
FunctionDecl functionDecl = scope.resolveFunctionOnStack(var.name);
if (functionDecl != null) {
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitTypeInsn(NEW, "loop/runtime/Closure");
methodVisitor.visitInsn(DUP);
methodVisitor.visitLdcInsn(functionDecl.moduleName);
methodVisitor.visitLdcInsn(functionDecl.scopedName());
methodVisitor.visitMethodInsn(INVOKESPECIAL, "loop/runtime/Closure", "<init>",
"(Ljava/lang/String;Ljava/lang/String;)V");
}
} else
methodStack.peek().visitVarInsn(ALOAD, index);
}
};
private static String normalizeMethodName(String name) {
return name.replaceFirst("@", "__");
}
private final Emitter intEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
IntLiteral intLiteral = (IntLiteral) node;
// Emit int wrappers.
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitLdcInsn(intLiteral.value);
methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf",
"(I)Ljava/lang/Integer;");
}
};
private final Emitter floatEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
FloatLiteral floatLiteral = (FloatLiteral) node;
// Emit float wrappers.
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitLdcInsn(floatLiteral.value);
methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf",
"(F)Ljava/lang/Float;");
}
};
private final Emitter longEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
LongLiteral longLiteral = (LongLiteral) node;
// Emit long wrappers.
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitLdcInsn(longLiteral.value);
methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf",
"(J)Ljava/lang/Long;");
}
};
private final Emitter doubleEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
DoubleLiteral doubleLiteral = (DoubleLiteral) node;
// Emit double wrappers.
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitLdcInsn(doubleLiteral.value);
methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf",
"(D)Ljava/lang/Double;");
}
};
private final Emitter bigIntegerEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
BigIntegerLiteral bigIntegerLiteral = (BigIntegerLiteral) node;
// Emit bigint wrappers.
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitTypeInsn(NEW, "java/math/BigInteger");
methodVisitor.visitInsn(DUP);
methodVisitor.visitLdcInsn(bigIntegerLiteral.value);
methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/math/BigInteger", "<init>",
"(Ljava/lang/String;)V");
}
};
private final Emitter bigDecimalEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
BigDecimalLiteral bigDecimalLiteral = (BigDecimalLiteral) node;
// Emit bigdecimal wrappers.
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitTypeInsn(NEW, "java/math/BigDecimal");
methodVisitor.visitInsn(DUP);
methodVisitor.visitLdcInsn(bigDecimalLiteral.value);
methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/math/BigDecimal", "<init>",
"(Ljava/lang/String;)V");
}
};
private final Emitter booleanEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
BooleanLiteral booleanLiteral = (BooleanLiteral) node;
// Emit boolean wrappers.
MethodVisitor methodVisitor = methodStack.peek();
methodVisitor.visitIntInsn(BIPUSH, booleanLiteral.value ? 1 : 0);
methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf",
"(Z)Ljava/lang/Boolean;");
}
};
private final Emitter typeLiteralEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
TypeLiteral type = (TypeLiteral) node;
trackLineAndColumn(type);
MethodVisitor methodVisitor = methodStack.peek();
if (TypeLiteral.NOTHING.equals(type.name)) // Special-case the bottom type.
methodVisitor.visitInsn(ACONST_NULL);
else {
ClassDecl classDecl = scope.resolve(type.name, true);
if (classDecl != null)
throw new UnsupportedOperationException(); // TODO reflection.
String fqn = scope.resolveJavaType(type.name);
if (fqn != null) {
methodVisitor.visitLdcInsn(fqn);
methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName",
"(Ljava/lang/String;)Ljava/lang/Class;");
}
}
}
};
private final Emitter javaLiteralEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
JavaLiteral java = (JavaLiteral) node;
trackLineAndColumn(java);
MethodVisitor methodVisitor = methodStack.peek();
if (java.staticFieldAccess == null)
methodVisitor.visitLdcInsn(java.value);
else {
methodVisitor.visitLdcInsn(java.value);
methodVisitor.visitLdcInsn(java.staticFieldAccess);
methodVisitor.visitMethodInsn(INVOKESTATIC, "loop/runtime/Caller", "getStatic",
"(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;");
}
}
};
private final Emitter stringLiteralEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
StringLiteral string = (StringLiteral) node;
trackLineAndColumn(string);
if (string.parts != null) {
MethodVisitor methodVisitor = methodStack.peek();
// Emit stringbuilder for string interpolation.
methodVisitor.visitTypeInsn(NEW, "java/lang/StringBuilder");
methodVisitor.visitInsn(DUP);
methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V");
for (Node part : string.parts) {
if (part instanceof StringLiteral)
methodVisitor.visitLdcInsn(((StringLiteral) part).value);
else
emit(part);
methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
"(Ljava/lang/Object;)Ljava/lang/StringBuilder;");
}
methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString",
"()Ljava/lang/String;");
} else {
methodStack.peek().visitLdcInsn(string.value.substring(1, string.value.length() - 1));
}
}
};
private final Emitter regexLiteralEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
throw new UnsupportedOperationException();
}
};
private final Emitter functionDeclEmitter = new Emitter() {
@Override
public void emitCode(Node node) {
FunctionDecl functionDecl = (FunctionDecl) node;
String name = functionDecl.scopedName();
boolean isClosure = functionDecl.isAnonymous();
if (isClosure) {
// Function is anonymous, generate a globally unique name for it.
name = "$fn_" + functionNameSequence.incrementAndGet();
}
Context innerContext = new Context(functionDecl);
// Before we emit the body of this method into the class scope, let's
// see if this is closure, and if it is, emit it as a function reference.
List<Variable> freeVariables;
if (isClosure) {
MethodVisitor currentVisitor = methodStack.peek();
// Discover any free variables and save them to this closure.
freeVariables = new ArrayList<Variable>();
detectFreeVariables(functionDecl, functionDecl.arguments(), freeVariables);
functionDecl.freeVariables = freeVariables;
// Add them to the argument list of the function.
for (Variable freeVariable : freeVariables) {
functionDecl.arguments().add(new ArgDeclList.Argument(freeVariable.name, null));
}
currentVisitor.visitTypeInsn(NEW, "loop/runtime/Closure");
currentVisitor.visitInsn(DUP);
currentVisitor.visitLdcInsn(functionDecl.moduleName);
currentVisitor.visitLdcInsn(name);
if (!freeVariables.isEmpty()) {
Context outerContext = functionStack.peek();
int arrayIndex = outerContext.localVarIndex(outerContext.newLocalVariable());
// push free variables as array.
currentVisitor.visitIntInsn(BIPUSH, freeVariables.size()); // size of array
currentVisitor.visitTypeInsn(ANEWARRAY, "java/lang/Object");
currentVisitor.visitVarInsn(ASTORE, arrayIndex);
int i = 0;
for (Variable freeVariable : freeVariables) {
currentVisitor.visitVarInsn(ALOAD, arrayIndex); // array
currentVisitor.visitIntInsn(BIPUSH, i); // index
emit(freeVariable); // value
currentVisitor.visitInsn(AASTORE);
i++;
}
// Load the array back in.
currentVisitor.visitVarInsn(ALOAD, arrayIndex);
currentVisitor.visitMethodInsn(INVOKESPECIAL, "loop/runtime/Closure", "<init>",
"(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V");
} else
currentVisitor.visitMethodInsn(INVOKESPECIAL, "loop/runtime/Closure", "<init>",
"(Ljava/lang/String;Ljava/lang/String;)V");
}
//******* BEGIN FUNCTION SIGNATURE ********
// Start writing this function in its own scope.
StringBuilder args = new StringBuilder("(");
List<Node> children = functionDecl.arguments().children();
for (int functionArgIndex = 0, childrenSize = children.size(); functionArgIndex < childrenSize; functionArgIndex++) {
Node arg = children.get(functionArgIndex);
String argName = ((ArgDeclList.Argument) arg).name();
innerContext.arguments.add(argName);
innerContext.argumentIndex.put(argName, functionArgIndex);
args.append("Ljava/lang/Object;");
}
args.append(")");