-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathCodeCompiler.java
More file actions
2891 lines (2527 loc) · 96.7 KB
/
CodeCompiler.java
File metadata and controls
2891 lines (2527 loc) · 96.7 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
// Copyright (c) Corporation for National Research Initiatives
package org.python.compiler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.ListIterator;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
import org.python.antlr.ParseException;
import org.python.antlr.PythonTree;
import org.python.antlr.Visitor;
import org.python.antlr.ast.Assert;
import org.python.antlr.ast.Assign;
import org.python.antlr.ast.Attribute;
import org.python.antlr.ast.AugAssign;
import org.python.antlr.ast.BinOp;
import org.python.antlr.ast.BoolOp;
import org.python.antlr.ast.Break;
import org.python.antlr.ast.Call;
import org.python.antlr.ast.ClassDef;
import org.python.antlr.ast.Compare;
import org.python.antlr.ast.Continue;
import org.python.antlr.ast.Delete;
import org.python.antlr.ast.Dict;
import org.python.antlr.ast.DictComp;
import org.python.antlr.ast.Ellipsis;
import org.python.antlr.ast.ExceptHandler;
import org.python.antlr.ast.Exec;
import org.python.antlr.ast.Expr;
import org.python.antlr.ast.Expression;
import org.python.antlr.ast.ExtSlice;
import org.python.antlr.ast.For;
import org.python.antlr.ast.FunctionDef;
import org.python.antlr.ast.GeneratorExp;
import org.python.antlr.ast.Global;
import org.python.antlr.ast.If;
import org.python.antlr.ast.IfExp;
import org.python.antlr.ast.Import;
import org.python.antlr.ast.ImportFrom;
import org.python.antlr.ast.Index;
import org.python.antlr.ast.Interactive;
import org.python.antlr.ast.Lambda;
import org.python.antlr.ast.List;
import org.python.antlr.ast.ListComp;
import org.python.antlr.ast.Name;
import org.python.antlr.ast.Num;
import org.python.antlr.ast.Pass;
import org.python.antlr.ast.Print;
import org.python.antlr.ast.Raise;
import org.python.antlr.ast.Repr;
import org.python.antlr.ast.Return;
import org.python.antlr.ast.Set;
import org.python.antlr.ast.SetComp;
import org.python.antlr.ast.Slice;
import org.python.antlr.ast.Str;
import org.python.antlr.ast.Subscript;
import org.python.antlr.ast.Suite;
import org.python.antlr.ast.TryExcept;
import org.python.antlr.ast.TryFinally;
import org.python.antlr.ast.Tuple;
import org.python.antlr.ast.UnaryOp;
import org.python.antlr.ast.While;
import org.python.antlr.ast.With;
import org.python.antlr.ast.Yield;
import org.python.antlr.ast.alias;
import org.python.antlr.ast.cmpopType;
import org.python.antlr.ast.comprehension;
import org.python.antlr.ast.expr_contextType;
import org.python.antlr.ast.keyword;
import org.python.antlr.ast.operatorType;
import org.python.antlr.base.expr;
import org.python.antlr.base.mod;
import org.python.antlr.base.stmt;
import org.python.core.CompilerFlags;
import org.python.core.ContextGuard;
import org.python.core.ContextManager;
import org.python.core.imp;
import org.python.core.Py;
import org.python.core.PyCode;
import org.python.core.PyComplex;
import org.python.core.PyDictionary;
import org.python.core.PyException;
import org.python.core.PyFloat;
import org.python.core.PyFrame;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyList;
import org.python.core.PyLong;
import org.python.core.PyObject;
import org.python.core.PySet;
import org.python.core.PySlice;
import org.python.core.PyString;
import org.python.core.PyTuple;
import org.python.core.PyUnicode;
import org.python.core.ThreadState;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
import static org.python.util.CodegenUtils.*;
public class CodeCompiler extends Visitor implements Opcodes, ClassConstants {
private static final Object Exit = Integer.valueOf(1);
private static final Object NoExit = null;
private Module module;
private Code code;
private CompilerFlags cflags;
private int temporary;
private expr_contextType augmode;
private int augtmp1;
private int augtmp2;
private int augtmp3;
private int augtmp4;
private boolean fast_locals, print_results;
private Map<String, SymInfo> tbl;
private ScopeInfo my_scope;
private boolean optimizeGlobals = true;
private String className;
private Stack<Label> continueLabels, breakLabels;
private Stack<ExceptionHandler> exceptionHandlers;
private Vector<Label> yields = new Vector<Label>();
/*
* break/continue finally's level. This is the lowest level in the exceptionHandlers which
* should be executed at break or continue. It is saved/updated/restored when compiling loops. A
* similar level for returns is not needed because a new CodeCompiler is used for each PyCode,
* in other words: each 'function'. When returning through finally's all the exceptionHandlers
* are executed.
*/
private int bcfLevel = 0;
private int yield_count = 0;
private Stack<String> stack = new Stack<String>();
public CodeCompiler(Module module, boolean print_results) {
this.module = module;
this.print_results = print_results;
continueLabels = new Stack<Label>();
breakLabels = new Stack<Label>();
exceptionHandlers = new Stack<ExceptionHandler>();
}
public void getNone() throws IOException {
code.getstatic(p(Py.class), "None", ci(PyObject.class));
}
public void loadFrame() throws Exception {
code.aload(1);
}
public void loadThreadState() throws Exception {
code.aload(2);
}
public void setLastI(int idx) throws Exception {
loadFrame();
code.iconst(idx);
code.putfield(p(PyFrame.class), "f_lasti", "I");
}
private void loadf_back() throws Exception {
code.getfield(p(PyFrame.class), "f_back", ci(PyFrame.class));
}
public int storeTop() throws Exception {
int tmp = code.getLocal(p(PyObject.class));
code.astore(tmp);
return tmp;
}
public void setline(int line) throws Exception {
if (module.linenumbers) {
code.setline(line);
loadFrame();
code.iconst(line);
code.invokevirtual(p(PyFrame.class), "setline", sig(Void.TYPE, Integer.TYPE));
}
}
public void setline(PythonTree node) throws Exception {
setline(node.getLineno());
}
public void set(PythonTree node) throws Exception {
int tmp = storeTop();
set(node, tmp);
code.aconst_null();
code.astore(tmp);
code.freeLocal(tmp);
}
public void set(PythonTree node, int tmp) throws Exception {
temporary = tmp;
visit(node);
}
private void saveAugTmps(PythonTree node, int count) throws Exception {
if (count >= 4) {
augtmp4 = code.getLocal(ci(PyObject.class));
code.astore(augtmp4);
}
if (count >= 3) {
augtmp3 = code.getLocal(ci(PyObject.class));
code.astore(augtmp3);
}
if (count >= 2) {
augtmp2 = code.getLocal(ci(PyObject.class));
code.astore(augtmp2);
}
augtmp1 = code.getLocal(ci(PyObject.class));
code.astore(augtmp1);
code.aload(augtmp1);
if (count >= 2) {
code.aload(augtmp2);
}
if (count >= 3) {
code.aload(augtmp3);
}
if (count >= 4) {
code.aload(augtmp4);
}
}
private void restoreAugTmps(PythonTree node, int count) throws Exception {
code.aload(augtmp1);
code.freeLocal(augtmp1);
if (count == 1) {
return;
}
code.aload(augtmp2);
code.freeLocal(augtmp2);
if (count == 2) {
return;
}
code.aload(augtmp3);
code.freeLocal(augtmp3);
if (count == 3) {
return;
}
code.aload(augtmp4);
code.freeLocal(augtmp4);
}
static boolean checkOptimizeGlobals(boolean fast_locals, ScopeInfo scope) {
return fast_locals && !scope.exec && !scope.from_import_star;
}
void parse(mod node, Code code, boolean fast_locals, String className, Str classDoc,
boolean classBody, ScopeInfo scope, CompilerFlags cflags) throws Exception {
this.fast_locals = fast_locals;
this.className = className;
this.code = code;
this.cflags = cflags;
this.my_scope = scope;
this.tbl = scope.tbl;
// BEGIN preparse
if (classBody) {
// Set the class's __module__ to __name__. fails when there's no __name__
loadFrame();
code.ldc("__module__");
loadFrame();
code.ldc("__name__");
code.invokevirtual(p(PyFrame.class), "getname", sig(PyObject.class, String.class));
code.invokevirtual(p(PyFrame.class), "setlocal",
sig(Void.TYPE, String.class, PyObject.class));
if (classDoc != null) {
loadFrame();
code.ldc("__doc__");
visit(classDoc);
code.invokevirtual(p(PyFrame.class), "setlocal",
sig(Void.TYPE, String.class, PyObject.class));
}
}
Label genswitch = new Label();
if (my_scope.generator) {
code.goto_(genswitch);
}
Label start = new Label();
code.label(start);
int nparamcell = my_scope.jy_paramcells.size();
if (nparamcell > 0) {
java.util.List<String> paramcells = my_scope.jy_paramcells;
for (int i = 0; i < nparamcell; i++) {
code.aload(1);
SymInfo syminf = tbl.get(paramcells.get(i));
code.iconst(syminf.locals_index);
code.iconst(syminf.env_index);
code.invokevirtual(p(PyFrame.class), "to_cell",
sig(Void.TYPE, Integer.TYPE, Integer.TYPE));
}
}
// END preparse
optimizeGlobals = checkOptimizeGlobals(fast_locals, my_scope);
if (my_scope.max_with_count > 0) {
// allocate for all the with-exits we will have in the frame;
// this allows yield and with to happily co-exist
loadFrame();
code.iconst(my_scope.max_with_count);
code.anewarray(p(PyObject.class));
code.putfield(p(PyFrame.class), "f_exits", ci(PyObject[].class));
}
Object exit = visit(node);
if (classBody) {
loadFrame();
code.invokevirtual(p(PyFrame.class), "getf_locals", sig(PyObject.class));
code.areturn();
} else {
if (exit == null) {
setLastI(-1);
getNone();
code.areturn();
}
}
// BEGIN postparse
// similar to visitResume code in pyasm.py
if (my_scope.generator) {
code.label(genswitch);
code.aload(1);
code.getfield(p(PyFrame.class), "f_lasti", "I");
Label[] y = new Label[yields.size() + 1];
y[0] = start;
for (int i = 1; i < y.length; i++) {
y[i] = yields.get(i - 1);
}
code.tableswitch(0, y.length - 1, start, y);
}
// END postparse
}
@Override
public Object visitInteractive(Interactive node) throws Exception {
traverse(node);
return null;
}
@Override
public Object visitModule(org.python.antlr.ast.Module suite) throws Exception {
Str docStr = getDocStr(suite.getInternalBody());
if (docStr != null) {
loadFrame();
code.ldc("__doc__");
visit(docStr);
code.invokevirtual(p(PyFrame.class), "setglobal",
sig(Void.TYPE, String.class, PyObject.class));
}
traverse(suite);
return null;
}
@Override
public Object visitExpression(Expression node) throws Exception {
if (my_scope.generator && node.getInternalBody() != null) {
module.error("'return' with argument inside generator", true, node);
}
return visitReturn(new Return(node, node.getInternalBody()), true);
}
public void loadArray(Code code, java.util.List<? extends PythonTree> nodes) throws Exception {
final int n;
if (nodes == null) {
n = 0;
} else {
n = nodes.size();
}
if (n == 0) {
code.getstatic(p(Py.class), "EmptyObjects", ci(PyObject[].class));
return;
} else if (module.emitPrimitiveArraySetters(nodes, code)) {
return;
}
code.iconst(n);
code.anewarray(p(PyObject.class));
for (int i = 0; i < n; i++) {
code.dup();
code.iconst(i);
visit(nodes.get(i));
code.aastore();
}
}
public int makeArray(java.util.List<? extends PythonTree> nodes) throws Exception {
final int n;
if (nodes == null) {
n = 0;
} else {
n = nodes.size();
}
int array = code.getLocal(ci(PyObject[].class));
if (n == 0) {
code.getstatic(p(Py.class), "EmptyObjects", ci(PyObject[].class));
code.astore(array);
} else {
code.iconst(n);
code.anewarray(p(PyObject.class));
code.astore(array);
for (int i = 0; i < n; i++) {
visit(nodes.get(i));
code.aload(array);
code.swap();
code.iconst(i);
code.swap();
code.aastore();
}
}
return array;
}
// nulls out an array of references
public void freeArray(int array) {
code.aload(array);
code.aconst_null();
code.invokestatic(p(Arrays.class), "fill", sig(Void.TYPE, Object[].class, Object.class));
code.freeLocal(array);
}
public void freeArrayRef(int array) {
code.aconst_null();
code.astore(array);
code.freeLocal(array);
}
public Str getDocStr(java.util.List<stmt> suite) {
if (suite.size() > 0) {
stmt stmt = suite.get(0);
if (stmt instanceof Expr && ((Expr)stmt).getInternalValue() instanceof Str) {
return (Str)((Expr)stmt).getInternalValue();
}
}
return null;
}
public boolean makeClosure(ScopeInfo scope) throws Exception {
if (scope == null || scope.freevars == null) {
return false;
}
int n = scope.freevars.size();
if (n == 0) {
return false;
}
int tmp = code.getLocal(ci(PyObject[].class));
code.iconst(n);
code.anewarray(p(PyObject.class));
code.astore(tmp);
Map<String, SymInfo> upTbl = scope.up.tbl;
for (int i = 0; i < n; i++) {
code.aload(tmp);
code.iconst(i);
loadFrame();
for (int j = 1; j < scope.distance; j++) {
loadf_back();
}
SymInfo symInfo = upTbl.get(scope.freevars.elementAt(i));
code.iconst(symInfo.env_index);
code.invokevirtual(p(PyFrame.class), "getclosure", sig(PyObject.class, Integer.TYPE));
code.aastore();
}
code.aload(tmp);
code.freeLocal(tmp);
return true;
}
@Override
public Object visitFunctionDef(FunctionDef node) throws Exception {
String name = getName(node.getInternalName());
setline(node);
ScopeInfo scope = module.getScopeInfo(node);
// NOTE: this is attached to the constructed PyFunction, so it cannot be nulled out
// with freeArray, unlike other usages of makeArray here
int defaults = makeArray(scope.ac.getDefaults());
code.new_(p(PyFunction.class));
code.dup();
loadFrame();
code.getfield(p(PyFrame.class), "f_globals", ci(PyObject.class));
code.aload(defaults);
code.freeLocal(defaults);
scope.setup_closure();
scope.dump();
module.codeConstant(new Suite(node, node.getInternalBody()), name, true, className, false,
false, node.getLineno(), scope, cflags).get(code);
Str docStr = getDocStr(node.getInternalBody());
if (docStr != null) {
visit(docStr);
} else {
code.aconst_null();
}
if (!makeClosure(scope)) {
code.invokespecial(p(PyFunction.class), "<init>",
sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class));
} else {
code.invokespecial(
p(PyFunction.class),
"<init>",
sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class,
PyObject[].class));
}
applyDecorators(node.getInternalDecorator_list());
set(new Name(node, node.getInternalName(), expr_contextType.Store));
return null;
}
private void applyDecorators(java.util.List<expr> decorators) throws Exception {
if (decorators != null && !decorators.isEmpty()) {
int res = storeTop();
for (expr decorator : decorators) {
visit(decorator);
stackProduce();
}
for (int i = decorators.size(); i > 0; i--) {
stackConsume();
loadThreadState();
code.aload(res);
code.invokevirtual(p(PyObject.class), "__call__",
sig(PyObject.class, ThreadState.class, PyObject.class));
code.astore(res);
}
code.aload(res);
code.freeLocal(res);
}
}
@Override
public Object visitExpr(Expr node) throws Exception {
setline(node);
visit(node.getInternalValue());
if (print_results) {
code.invokestatic(p(Py.class), "printResult", sig(Void.TYPE, PyObject.class));
} else {
code.pop();
}
return null;
}
@Override
public Object visitAssign(Assign node) throws Exception {
setline(node);
visit(node.getInternalValue());
if (node.getInternalTargets().size() == 1) {
set(node.getInternalTargets().get(0));
} else {
int tmp = storeTop();
for (expr target : node.getInternalTargets()) {
set(target, tmp);
}
code.freeLocal(tmp);
}
return null;
}
@Override
public Object visitPrint(Print node) throws Exception {
setline(node);
int tmp = -1;
if (node.getInternalDest() != null) {
visit(node.getInternalDest());
tmp = storeTop();
}
if (node.getInternalValues() == null || node.getInternalValues().size() == 0) {
if (node.getInternalDest() != null) {
code.aload(tmp);
code.invokestatic(p(Py.class), "printlnv", sig(Void.TYPE, PyObject.class));
} else {
code.invokestatic(p(Py.class), "println", sig(Void.TYPE));
}
} else {
for (int i = 0; i < node.getInternalValues().size(); i++) {
if (node.getInternalDest() != null) {
code.aload(tmp);
visit(node.getInternalValues().get(i));
if (node.getInternalNl() && i == node.getInternalValues().size() - 1) {
code.invokestatic(p(Py.class), "println",
sig(Void.TYPE, PyObject.class, PyObject.class));
} else {
code.invokestatic(p(Py.class), "printComma",
sig(Void.TYPE, PyObject.class, PyObject.class));
}
} else {
visit(node.getInternalValues().get(i));
if (node.getInternalNl() && i == node.getInternalValues().size() - 1) {
code.invokestatic(p(Py.class), "println", sig(Void.TYPE, PyObject.class));
} else {
code.invokestatic(p(Py.class), "printComma", sig(Void.TYPE, PyObject.class));
}
}
}
}
if (node.getInternalDest() != null) {
code.freeLocal(tmp);
}
return null;
}
@Override
public Object visitDelete(Delete node) throws Exception {
setline(node);
traverse(node);
return null;
}
@Override
public Object visitPass(Pass node) throws Exception {
setline(node);
return null;
}
@Override
public Object visitBreak(Break node) throws Exception {
// setline(node); Not needed here...
if (breakLabels.empty()) {
throw new ParseException("'break' outside loop", node);
}
doFinallysDownTo(bcfLevel);
code.goto_(breakLabels.peek());
return null;
}
@Override
public Object visitContinue(Continue node) throws Exception {
// setline(node); Not needed here...
if (continueLabels.empty()) {
throw new ParseException("'continue' not properly in loop", node);
}
doFinallysDownTo(bcfLevel);
code.goto_(continueLabels.peek());
return Exit;
}
@Override
public Object visitYield(Yield node) throws Exception {
setline(node);
if (!fast_locals) {
throw new ParseException("'yield' outside function", node);
}
int stackState = saveStack();
if (node.getInternalValue() != null) {
visit(node.getInternalValue());
} else {
getNone();
}
setLastI(++yield_count);
saveLocals();
code.areturn();
Label restart = new Label();
yields.addElement(restart);
code.label(restart);
restoreLocals();
restoreStack(stackState);
loadFrame();
code.invokevirtual(p(PyFrame.class), "getGeneratorInput", sig(Object.class));
code.dup();
code.instanceof_(p(PyException.class));
Label done2 = new Label();
code.ifeq(done2);
code.checkcast(p(Throwable.class));
code.athrow();
code.label(done2);
code.checkcast(p(PyObject.class));
return null;
}
private void stackProduce() {
stackProduce(p(PyObject.class));
}
private void stackProduce(String signature) {
stack.push(signature);
}
private void stackConsume() {
stackConsume(1);
}
private void stackConsume(int numItems) {
for (int i = 0; i < numItems; i++) {
stack.pop();
}
}
private int saveStack() throws Exception {
if (stack.size() > 0) {
int array = code.getLocal(ci(Object[].class));
code.iconst(stack.size());
code.anewarray(p(Object.class));
code.astore(array);
ListIterator<String> content = stack.listIterator(stack.size());
for (int i = 0; content.hasPrevious(); i++) {
String signature = content.previous();
if (p(ThreadState.class).equals(signature)) {
// Stack: ... threadstate
code.pop();
// Stack: ...
} else {
code.aload(array);
// Stack: |- ... value array
code.swap();
code.iconst(i++);
code.swap();
// Stack: |- ... array index value
code.aastore();
// Stack: |- ...
}
}
return array;
} else {
return -1;
}
}
private void restoreStack(int array) throws Exception {
if (stack.size() > 0) {
int i = stack.size() - 1;
for (String signature : stack) {
if (p(ThreadState.class).equals(signature)) {
loadThreadState();
} else {
code.aload(array);
// Stack: |- ... array
code.iconst(i--);
code.aaload();
// Stack: |- ... value
code.checkcast(signature);
}
}
code.freeLocal(array);
}
}
private void restoreLocals() throws Exception {
endExceptionHandlers();
Vector<String> v = code.getActiveLocals();
loadFrame();
code.getfield(p(PyFrame.class), "f_savedlocals", ci(Object[].class));
int locals = code.getLocal(ci(Object[].class));
code.astore(locals);
for (int i = 0; i < v.size(); i++) {
String type = v.elementAt(i);
if (type == null) {
continue;
}
code.aload(locals);
code.iconst(i);
code.aaload();
code.checkcast(type);
code.astore(i);
}
code.freeLocal(locals);
restartExceptionHandlers();
}
/**
* Close all the open exception handler ranges. This should be paired with
* restartExceptionHandlers to delimit internal code that shouldn't be handled by user handlers.
* This allows us to set variables without the verifier thinking we might jump out of our
* handling with an exception.
*/
private void endExceptionHandlers() {
Label end = new Label();
code.label(end);
for (int i = 0; i < exceptionHandlers.size(); ++i) {
ExceptionHandler handler = exceptionHandlers.elementAt(i);
handler.exceptionEnds.addElement(end);
}
}
private void restartExceptionHandlers() {
Label start = new Label();
code.label(start);
for (int i = 0; i < exceptionHandlers.size(); ++i) {
ExceptionHandler handler = exceptionHandlers.elementAt(i);
handler.exceptionStarts.addElement(start);
}
}
private void saveLocals() throws Exception {
Vector<String> v = code.getActiveLocals();
code.iconst(v.size());
code.anewarray(p(Object.class));
int locals = code.getLocal(ci(Object[].class));
code.astore(locals);
for (int i = 0; i < v.size(); i++) {
String type = v.elementAt(i);
if (type == null) {
continue;
}
code.aload(locals);
code.iconst(i);
// code.checkcast(code.pool.Class(p(Object.class)));
if (i == 2222) {
code.aconst_null();
} else {
code.aload(i);
}
code.aastore();
}
loadFrame();
code.aload(locals);
code.putfield(p(PyFrame.class), "f_savedlocals", ci(Object[].class));
code.freeLocal(locals);
}
@Override
public Object visitReturn(Return node) throws Exception {
return visitReturn(node, false);
}
public Object visitReturn(Return node, boolean inEval) throws Exception {
setline(node);
if (!inEval && !fast_locals) {
throw new ParseException("'return' outside function", node);
}
int tmp = 0;
if (node.getInternalValue() != null) {
if (my_scope.generator && !(node instanceof LambdaSyntheticReturn)) {
throw new ParseException("'return' with argument " + "inside generator", node);
}
visit(node.getInternalValue());
tmp = code.getReturnLocal();
code.astore(tmp);
}
doFinallysDownTo(0);
setLastI(-1);
if (node.getInternalValue() != null) {
code.aload(tmp);
} else {
getNone();
}
code.areturn();
return Exit;
}
@Override
public Object visitRaise(Raise node) throws Exception {
setline(node);
if (node.getInternalType() != null) {
visit(node.getInternalType());
stackProduce();
}
if (node.getInternalInst() != null) {
visit(node.getInternalInst());
stackProduce();
}
if (node.getInternalTback() != null) {
visit(node.getInternalTback());
stackProduce();
}
if (node.getInternalType() == null) {
code.invokestatic(p(Py.class), "makeException", sig(PyException.class));
} else if (node.getInternalInst() == null) {
stackConsume();
code.invokestatic(p(Py.class), "makeException", sig(PyException.class, PyObject.class));
} else if (node.getInternalTback() == null) {
stackConsume(2);
code.invokestatic(p(Py.class), "makeException",
sig(PyException.class, PyObject.class, PyObject.class));
} else {
stackConsume(3);
code.invokestatic(p(Py.class), "makeException",
sig(PyException.class, PyObject.class, PyObject.class, PyObject.class));
}
code.athrow();
return Exit;
}
/**
* Return the implied import level, which is different from the argument only if the argument is
* zero (no leading dots) meaning try relative then absolute (in Python 2), signified by
* returning level <code>-1</code>.
*/
private int impliedImportLevel(int level) {
// already prepared for a future change of DEFAULT_LEVEL
if (imp.DEFAULT_LEVEL == 0 || level != 0 || module.getFutures().isAbsoluteImportOn()) {
return level;
} else {
return imp.DEFAULT_LEVEL;
}
}
@Override
public Object visitImport(Import node) throws Exception {
setline(node);
for (alias a : node.getInternalNames()) {
String asname = null;
if (a.getInternalAsname() != null) {
String name = a.getInternalName();
asname = a.getInternalAsname();
code.ldc(name);
loadFrame();
code.iconst(impliedImportLevel(0));
code.invokestatic(p(imp.class), "importOneAs",
sig(PyObject.class, String.class, PyFrame.class, Integer.TYPE));
} else {
String name = a.getInternalName();
asname = name;
if (asname.indexOf('.') > 0) {
asname = asname.substring(0, asname.indexOf('.'));
}
code.ldc(name);
loadFrame();
code.iconst(impliedImportLevel(0));
code.invokestatic(p(imp.class), "importOne",
sig(PyObject.class, String.class, PyFrame.class, Integer.TYPE));
}
set(new Name(a, asname, expr_contextType.Store));
}
return null;
}
@Override
public Object visitImportFrom(ImportFrom node) throws Exception {
Future.checkFromFuture(node); // future stmt support
setline(node);
code.ldc(node.getInternalModule());
java.util.List<alias> aliases = node.getInternalNames();
if (aliases == null || aliases.size() == 0) {
throw new ParseException("Internel parser error", node);
} else if (aliases.size() == 1 && aliases.get(0).getInternalName().equals("*")) {
if (my_scope.func_level > 0) {
module.error("import * only allowed at module level", false, node);
if (my_scope.contains_ns_free_vars) {
module.error("import * is not allowed in function '" + my_scope.scope_name
+ "' because it contains a nested function with free variables", true,
node);
}
}
if (my_scope.func_level > 1) {
module.error("import * is not allowed in function '" + my_scope.scope_name
+ "' because it is a nested function", true, node);
}
loadFrame();
code.iconst(impliedImportLevel(node.getInternalLevel()));
code.invokestatic(p(imp.class), "importAll",
sig(Void.TYPE, String.class, PyFrame.class, Integer.TYPE));
} else {
java.util.List<String> fromNames = new ArrayList<String>(); // [names.size()];
java.util.List<String> asnames = new ArrayList<String>(); // [names.size()];
for (int i = 0; i < aliases.size(); i++) {
fromNames.add(aliases.get(i).getInternalName());
asnames.add(aliases.get(i).getInternalAsname());