-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathStatementWriter.java
More file actions
840 lines (715 loc) · 34.1 KB
/
StatementWriter.java
File metadata and controls
840 lines (715 loc) · 34.1 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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.classgen.asm;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.VariableScope;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.ClosureListExpression;
import org.codehaus.groovy.ast.expr.EmptyExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.MethodCall;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.stmt.AssertStatement;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.BreakStatement;
import org.codehaus.groovy.ast.stmt.CaseStatement;
import org.codehaus.groovy.ast.stmt.CatchStatement;
import org.codehaus.groovy.ast.stmt.ContinueStatement;
import org.codehaus.groovy.ast.stmt.DoWhileStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.ast.stmt.SwitchStatement;
import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
import org.codehaus.groovy.ast.stmt.ThrowStatement;
import org.codehaus.groovy.ast.stmt.TryCatchStatement;
import org.codehaus.groovy.ast.stmt.WhileStatement;
import org.codehaus.groovy.classgen.AsmClassGenerator;
import org.codehaus.groovy.classgen.asm.CompileStack.BlockRecorder;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import static org.apache.groovy.ast.tools.ExpressionUtils.isNullConstant;
import static org.codehaus.groovy.ast.tools.GeneralUtils.ConditionValue;
import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.castX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.constantBooleanValue;
import static org.codehaus.groovy.ast.tools.GeneralUtils.isEmptyStatement;
import static org.codehaus.groovy.ast.tools.GeneralUtils.mayReachLoopCondition;
import static org.codehaus.groovy.ast.tools.GeneralUtils.maybeFallsThrough;
import static org.codehaus.groovy.ast.tools.GeneralUtils.maybeFallsThroughToNextSwitchCase;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ATHROW;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.GOTO;
import static org.objectweb.asm.Opcodes.IADD;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Opcodes.ICONST_M1;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.IFNULL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.MONITORENTER;
import static org.objectweb.asm.Opcodes.MONITOREXIT;
import static org.objectweb.asm.Opcodes.NOP;
import static org.objectweb.asm.Opcodes.RETURN;
/**
* Generates bytecode for Groovy statements by visiting AST statement nodes
* and emitting corresponding JVM instructions via the {@link WriterController}.
* Handles control flow (loops, branches, try/catch), synchronization, assertions,
* and expression statements.
*/
public class StatementWriter {
private static final MethodCaller iteratorHasNextMethod = MethodCaller.newInterface(Iterator.class, "hasNext");
private static final MethodCaller iteratorNextMethod = MethodCaller.newInterface(Iterator.class, "next");
/** The controller coordinating all bytecode writers for the current class. */
protected final WriterController controller;
/**
* Creates a statement writer backed by the given controller.
*
* @param controller the writer controller for the current compilation
*/
public StatementWriter(final WriterController controller) {
this.controller = controller;
}
/**
* Emits bytecode labels for any statement labels attached to {@code statement}.
* Called before emitting the body of every statement so that named labels
* ({@code break foo} / {@code continue foo}) resolve correctly.
*
* @param statement the statement whose labels should be emitted
*/
protected void writeStatementLabel(final Statement statement) {
List<String> labels = statement.getStatementLabels();
if (labels != null) {
CompileStack cs = controller.getCompileStack ();
MethodVisitor mv = controller.getMethodVisitor();
for (String label : labels) {
mv.visitLabel(cs.createLocalLabel(label));
}
}
}
/**
* Generates bytecode for a block statement by visiting each contained statement.
* Pushes the block's variable scope, emits the statements, and pops afterward.
* Named labels on the block create a breakable region so that {@code break label}
* within the block jumps to the end of it.
*
* @param block the block statement to compile
*/
public void writeBlockStatement(final BlockStatement block) {
writeStatementLabel(block);
CompileStack compileStack = controller.getCompileStack();
OperandStack operandStack = controller.getOperandStack();
int mark = operandStack.getStackLength();
compileStack.pushVariableScope(block.getVariableScope());
List<String> labels = block.getStatementLabels(); // GROOVY-6844
Label end = (labels != null && !labels.isEmpty()) ? compileStack.pushBreakable(labels) : null;
for (Statement statement : block.getStatements()) {
statement.visit(controller.getAcg());
}
if (end != null) {
controller.getMethodVisitor().visitLabel(end);
compileStack.pop();
}
compileStack.pop();
operandStack.popDownTo(mark);
}
/**
* Generates bytecode for a for statement.
* Delegates to {@link #writeForLoopWithClosureList} for C-style loops (using a
* {@link ClosureListExpression}), or to {@link #writeForInLoop} for for-in loops.
*
* @param statement the for statement to compile
*/
public void writeForStatement(final ForStatement statement) {
if (statement.getCollectionExpression() instanceof ClosureListExpression) {
writeForLoopWithClosureList(statement);
} else {
writeForInLoop(statement);
}
}
/**
* Generates bytecode for a for-in loop by calling {@code iterator()} on the
* collection expression and delegating loop control to
* {@link #writeForInLoopControlAndBlock}.
*
* @param statement the for-in statement to compile
*/
protected void writeForInLoop(final ForStatement statement) {
controller.getAcg().onLineNumber(statement, "visitForLoop");
writeStatementLabel(statement);
CompileStack compileStack = controller.getCompileStack();
compileStack.pushLoop(statement.getVariableScope(), statement.getStatementLabels());
// then get the iterator and generate the loop control
Expression iterator = callX(statement.getCollectionExpression(), "iterator");
((MethodCallExpression) iterator).setImplicitThis(false);
iterator = castX(ClassHelper.Iterator_TYPE, iterator);
iterator.visit(controller.getAcg());
writeForInLoopControlAndBlock(statement);
compileStack.pop();
}
/**
* Emits the loop-control structure and body for a for-in loop.
* Assumes the iterator object is already on the operand stack.
* Declares loop variables, emits the {@code hasNext}/{@code next} check-and-advance,
* generates the loop body, and handles index-variable increment when present.
*
* @param statement the for-in statement whose control and body should be emitted
*/
protected void writeForInLoopControlAndBlock(ForStatement statement) {
CompileStack compileStack = controller.getCompileStack();
MethodVisitor mv = controller.getMethodVisitor();
OperandStack operandStack = controller.getOperandStack();
// declare the loop index and value variables
BytecodeVariable indexVariable = defineLoopIndexVariable(statement);
BytecodeVariable valueVariable = compileStack.defineVariable(statement.getValueVariable(), false);
// get the iterator and generate the loop control
int iterator = compileStack.defineTemporaryVariable("iterator", ClassHelper.Iterator_TYPE, true);
Label breakLabel = compileStack.getBreakLabel(), continueLabel = compileStack.getContinueLabel();
boolean bodyMayReachContinue = mayReachLoopCondition(statement);
mv.visitVarInsn(ALOAD, iterator);
mv.visitJumpInsn(IFNULL, breakLabel);
mv.visitLabel(continueLabel);
mv.visitVarInsn(ALOAD, iterator);
writeIteratorHasNext(mv);
mv.visitJumpInsn(IFEQ, breakLabel); // jump if zero (aka false)
mv.visitVarInsn(ALOAD, iterator);
writeIteratorNext(mv);
operandStack.push(ClassHelper.OBJECT_TYPE);
operandStack.storeVar(valueVariable);
if (indexVariable != null) {
if (!indexVariable.isHolder()) {
mv.visitIincInsn(indexVariable.getIndex(), 1);
} else { // GROOVY-11751: shared variable reference
mv.visitVarInsn(ALOAD, indexVariable.getIndex());
mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;", false);
mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
mv.visitInsn(ICONST_1);
mv.visitInsn(IADD);
operandStack.push(ClassHelper.int_TYPE);
operandStack.storeVar(indexVariable);
}
}
// generate the loop body
statement.getLoopBlock().visit(controller.getAcg());
writeLoopBackEdge(continueLabel, bodyMayReachContinue);
mv.visitLabel(breakLabel);
compileStack.removeVar(iterator);
}
protected final BytecodeVariable defineLoopIndexVariable(final ForStatement statement) {
CompileStack compileStack = controller.getCompileStack();
return Optional.ofNullable(statement.getIndexVariable()).map(iv -> {
controller.getMethodVisitor().visitInsn(ICONST_M1); // initialize to -1 so increment can pair with next()
return compileStack.defineVariable(iv, true);
}).orElse(null);
}
protected final void writeLoopBackEdge(final Label continueLabel, final boolean bodyMayReachContinue) {
if (bodyMayReachContinue) {
controller.getMethodVisitor().visitJumpInsn(GOTO, continueLabel);
}
}
/**
* Emits the {@link java.util.Iterator#hasNext()} call via the given visitor.
* Overrideable so subclasses can substitute a specialized or inlined variant.
*
* @param mv the method visitor to write to
*/
protected void writeIteratorHasNext(final MethodVisitor mv) {
iteratorHasNextMethod.call(mv);
}
/**
* Emits the {@link java.util.Iterator#next()} call via the given visitor.
* Overrideable so subclasses can substitute a specialized or inlined variant.
*
* @param mv the method visitor to write to
*/
protected void writeIteratorNext(final MethodVisitor mv) {
iteratorNextMethod.call(mv);
}
/**
* Generates bytecode for a C-style {@code for(init; cond; incr)} loop.
* The collection expression is a {@link ClosureListExpression} whose middle
* element is the boolean condition, lower elements are initializers, and
* upper elements are incrementors.
*
* @param statement the for statement with a {@link ClosureListExpression} collection
*/
protected void writeForLoopWithClosureList(final ForStatement statement) {
controller.getAcg().onLineNumber(statement, "visitForLoop");
writeStatementLabel(statement);
MethodVisitor mv = controller.getMethodVisitor();
controller.getCompileStack().pushLoop(statement.getVariableScope(), statement.getStatementLabels());
ClosureListExpression clExpr = (ClosureListExpression) statement.getCollectionExpression();
controller.getCompileStack().pushVariableScope(clExpr.getVariableScope());
List<Expression> expressions = clExpr.getExpressions();
int size = expressions.size();
// middle element is condition, lower half is init, higher half is increment
int condIndex = (size - 1) / 2;
// visit init
for (int i = 0; i < condIndex; i += 1) {
visitExpressionOfLoopStatement(expressions.get(i));
}
Label continueLabel = controller.getCompileStack().getContinueLabel();
Label breakLabel = controller.getCompileStack().getBreakLabel();
Label cond = new Label();
mv.visitLabel(cond);
ConditionValue conditionValue = visitConditionOfLoopStatement(expressions.get(condIndex), breakLabel, mv);
boolean bodyMayReachContinue = mayReachLoopCondition(statement);
if (conditionValue != ConditionValue.ALWAYS_FALSE) {
// Generate the loop body
statement.getLoopBlock().visit(controller.getAcg());
if (bodyMayReachContinue) {
// visit increment
mv.visitLabel(continueLabel);
// fix for being on the wrong line when debugging for loop
controller.getAcg().onLineNumber(statement, "increment condition");
for (int i = condIndex + 1; i < size; i += 1) {
visitExpressionOfLoopStatement(expressions.get(i));
}
// jump to test the condition again
writeLoopBackEdge(cond, true);
}
}
// loop end
mv.visitLabel(breakLabel);
controller.getCompileStack().pop();
controller.getCompileStack().pop();
}
private void visitExpressionOfLoopStatement(final Expression expression) {
Consumer<Expression> visit = expr -> {
if (expr instanceof EmptyExpression) return;
int mark = controller.getOperandStack().getStackLength();
expr.visit(controller.getAcg());
controller.getOperandStack().popDownTo(mark);
};
if (expression instanceof ClosureListExpression) {
((ClosureListExpression) expression).getExpressions().forEach(visit);
} else {
visit.accept(expression);
}
}
private ConditionValue visitConditionOfLoopStatement(final Expression expression, final Label breakLabel, final MethodVisitor mv) {
ConditionValue conditionValue = constantBooleanValue(expression);
if (conditionValue == ConditionValue.ALWAYS_FALSE) {
mv.visitJumpInsn(GOTO, breakLabel); // unconditional exit
return conditionValue;
}
if (conditionValue == ConditionValue.ALWAYS_TRUE) {
return conditionValue; // unconditional loop
}
int mark = controller.getOperandStack().getStackLength();
expression.visit(controller.getAcg());
controller.getOperandStack().castToBool(mark, true);
controller.getOperandStack().jump(IFEQ, breakLabel);
return ConditionValue.UNKNOWN;
}
/**
* Generates bytecode for a while loop.
*
* @param statement the while statement to compile
*/
public void writeWhileLoop(final WhileStatement statement) {
controller.getAcg().onLineNumber(statement, "visitWhileLoop");
writeStatementLabel(statement);
CompileStack compileStack = controller.getCompileStack();
compileStack.pushLoop(statement.getStatementLabels());
Label continueLabel = compileStack.getContinueLabel();
Label breakLabel = compileStack.getBreakLabel();
boolean bodyMayReachContinue = mayReachLoopCondition(statement);
MethodVisitor mv = controller.getMethodVisitor();
mv.visitLabel(continueLabel);
if (visitConditionOfLoopStatement(statement.getBooleanExpression(), breakLabel, mv) != ConditionValue.ALWAYS_FALSE) {
statement.getLoopBlock().visit(controller.getAcg());
writeLoopBackEdge(continueLabel, bodyMayReachContinue);
}
mv.visitLabel(breakLabel);
compileStack.pop();
}
/**
* Generates bytecode for a do-while loop.
*
* @param statement the do-while statement to compile
*/
public void writeDoWhileLoop(final DoWhileStatement statement) {
writeStatementLabel(statement);
CompileStack compileStack = controller.getCompileStack();
compileStack.pushLoop(statement.getStatementLabels());
Label continueLabel = compileStack.getContinueLabel();
Label breakLabel = compileStack.getBreakLabel();
Label blockLabel = new Label();
MethodVisitor mv = controller.getMethodVisitor();
mv.visitLabel(blockLabel);
statement.getLoopBlock().visit(controller.getAcg());
if (mayReachLoopCondition(statement)) {
mv.visitLabel(continueLabel); // GROOVY-11739: continue jumps to condition
if (visitConditionOfLoopStatement(statement.getBooleanExpression(), breakLabel, mv) != ConditionValue.ALWAYS_FALSE) {
mv.visitJumpInsn(GOTO, blockLabel);
}
}
mv.visitLabel(breakLabel);
compileStack.pop();
}
/**
* Generates bytecode for an if/else statement.
*
* @param statement the if statement to compile
*/
public void writeIfElse(final IfStatement statement) {
controller.getAcg().onLineNumber(statement, "visitIfElse");
writeStatementLabel(statement);
Label exitPath = controller.getCompileStack().pushBreakable(statement.getStatementLabels()); // GROOVY-7463
statement.getBooleanExpression().visit(controller.getAcg());
Label elsePath = controller.getOperandStack().jump(IFEQ);
statement.getIfBlock().visit(controller.getAcg());
controller.getCompileStack().pop();
MethodVisitor mv = controller.getMethodVisitor();
if (statement.getElseBlock().isEmpty()) {
mv.visitLabel(elsePath);
} else {
if (maybeFallsThrough(statement.getIfBlock())) {
mv.visitJumpInsn(GOTO, exitPath);
}
mv.visitLabel(elsePath);
statement.getElseBlock().visit(controller.getAcg());
}
mv.visitLabel(exitPath);
}
/**
* Generates bytecode for a try/catch/finally statement.
* Handles exception table registration, finally-block inlining at every
* exit path, and a catch-all rethrow for exceptions not handled by
* any {@code catch} clause.
*
* @param statement the try/catch/finally statement to compile
*/
public void writeTryCatchFinally(final TryCatchStatement statement) {
writeStatementLabel(statement);
MethodVisitor mv = controller.getMethodVisitor();
CompileStack compileStack = controller.getCompileStack();
OperandStack operandStack = controller.getOperandStack();
Statement tryStatement = statement.getTryStatement();
Statement finallyStatement = statement.getFinallyStatement();
BlockRecorder tryBlock = makeBlockRecorder(finallyStatement);
startRange(tryBlock, mv);
tryStatement.visit(controller.getAcg());
// skip past catch block(s)
Label finallyStart = new Label();
boolean fallthroughFinally = false;
if (maybeFallsThrough(tryStatement)) {
mv.visitJumpInsn(GOTO, finallyStart);
fallthroughFinally = true;
}
closeRange(tryBlock, mv);
// pop for BlockRecorder
compileStack.pop();
BlockRecorder catches = makeBlockRecorder(finallyStatement);
for (CatchStatement catchStatement : statement.getCatchStatements()) {
Label catchBlock = startRange(catches, mv);
// create variable for the exception
compileStack.pushState();
ClassNode type = catchStatement.getExceptionType();
compileStack.defineVariable(catchStatement.getVariable(), type, true);
// handle catch body
catchStatement.visit(controller.getAcg());
// placeholder to avoid problems with empty catch block
mv.visitInsn(NOP);
// pop for the variable
compileStack.pop();
// end of catch
closeRange(catches, mv);
if (maybeFallsThrough(catchStatement.getCode())) {
mv.visitJumpInsn(GOTO, finallyStart);
fallthroughFinally = true;
}
String typeName = BytecodeHelper.getClassInternalName(type);
compileStack.writeExceptionTable(tryBlock, catchBlock, typeName);
}
// used to handle exceptions in catches and regularly visited finals
Label catchAll = new Label(), afterCatchAll = new Label();
// add "catch all" block to exception table for try part; we do this
// after the exception blocks so they are not superseded by this one
compileStack.writeExceptionTable(tryBlock, catchAll, null);
// same for the catch parts
compileStack.writeExceptionTable(catches , catchAll, null);
// pop for BlockRecorder
compileStack.pop();
if (fallthroughFinally) {
mv.visitLabel(finallyStart);
finallyStatement.visit(controller.getAcg());
// skip over the catch-finally-rethrow
mv.visitJumpInsn(GOTO, afterCatchAll);
}
mv.visitLabel(catchAll);
operandStack.push(ClassHelper.THROWABLE_TYPE);
int anyThrowable = compileStack.defineTemporaryVariable("throwable", ClassHelper.THROWABLE_TYPE, true);
finallyStatement.visit(controller.getAcg());
// load the throwable and rethrow it
mv.visitVarInsn(ALOAD, anyThrowable);
mv.visitInsn(ATHROW);
if (fallthroughFinally)
mv.visitLabel(afterCatchAll);
compileStack.removeVar(anyThrowable);
}
private BlockRecorder makeBlockRecorder(final Statement finallyStatement) {
BlockRecorder recorder = new BlockRecorder();
final CompileStack compileStack = controller.getCompileStack();
recorder.excludedStatement = () -> {
if (isEmptyStatement(finallyStatement)) return;
final VariableScope originalScope = compileStack.getScope();
compileStack.pop();
compileStack.pushBlockRecorderVisit(recorder);
finallyStatement.visit(controller.getAcg());
compileStack.popBlockRecorderVisit(recorder);
compileStack.pushVariableScope(originalScope);
};
compileStack.pushBlockRecorder(recorder);
return recorder;
}
private static Label startRange(final BlockRecorder br, final MethodVisitor mv) {
Label label = new Label();
mv.visitLabel(label);
br.startRange(label);
return label;
}
private static void closeRange(final BlockRecorder br, final MethodVisitor mv) {
Label label = new Label();
mv.visitLabel(label);
br.closeRange(label);
}
/**
* Generates bytecode for a switch statement.
* Each {@code case} expression is compared using Groovy's {@code isCase} operator,
* so non-integer switch expressions are supported.
*
* @param statement the switch statement to compile
*/
public void writeSwitch(final SwitchStatement statement) {
controller.getAcg().onLineNumber(statement, "visitSwitch");
writeStatementLabel(statement);
statement.getExpression().visit(controller.getAcg());
ClassNode exprType = controller.getOperandStack().getTopOperand();
if (ClassHelper.isPrimitiveType(exprType)) exprType = ClassHelper.getWrapper(exprType);
// switch does not have a continue label; use enclosing continue label
CompileStack compileStack = controller.getCompileStack();
Label breakLabel = compileStack.pushSwitch(statement.getStatementLabels());
int switchVariableIndex = compileStack.defineTemporaryVariable("switch", exprType, true);
List<CaseStatement> caseStatements = statement.getCaseStatements();
int caseCount = caseStatements.size();
Label[] labels = new Label[caseCount + 1];
for (int i = 0; i < caseCount; i += 1) {
labels[i] = new Label();
}
int i = 0;
for (Iterator<CaseStatement> iter = caseStatements.iterator(); iter.hasNext(); i += 1) {
writeCaseStatement(iter.next(), statement, switchVariableIndex, labels[i], labels[i + 1]);
}
statement.getDefaultStatement().visit(controller.getAcg());
if (maybeFallsThrough(statement) || statement.getStatementLabels() != null) {
controller.getMethodVisitor().visitLabel(breakLabel);
}
compileStack.removeVar(switchVariableIndex);
compileStack.pop();
}
private void writeCaseStatement(final CaseStatement caseStatement, final SwitchStatement switchStatement, final int switchVariableIndex, final Label thisLabel, final Label nextLabel) {
controller.getAcg().onLineNumber(caseStatement, "visitCaseStatement");
MethodVisitor mv = controller.getMethodVisitor();
OperandStack operandStack = controller.getOperandStack();
mv.visitVarInsn(ALOAD, switchVariableIndex);
caseStatement.getExpression().visit(controller.getAcg());
operandStack.box();
controller.getBinaryExpressionHelper().getIsCaseMethod().call(mv);
operandStack.replace(ClassHelper.boolean_TYPE);
Label l0 = controller.getOperandStack().jump(IFEQ);
mv.visitLabel(thisLabel);
caseStatement.getCode().visit(controller.getAcg());
// now if we don't finish with a break we need to jump past the next comparison
if (nextLabel != null && maybeFallsThroughToNextSwitchCase(caseStatement.getCode(), switchStatement)) {
mv.visitJumpInsn(GOTO, nextLabel);
}
mv.visitLabel(l0);
}
/**
* Generates bytecode for a break statement, applying any intervening
* finally blocks before the jump.
*
* @param statement the break statement to compile
*/
public void writeBreak(final BreakStatement statement) {
controller.getAcg().onLineNumber(statement, "visitBreakStatement");
writeStatementLabel(statement);
Label label = controller.getCompileStack().getNamedBreakLabel(statement.getLabel());
controller.getCompileStack().applyFinallyBlocks(label, true);
controller.getMethodVisitor().visitJumpInsn(GOTO, label);
}
/**
* Generates bytecode for a continue statement, applying any intervening
* finally blocks before the jump.
*
* @param statement the continue statement to compile
*/
public void writeContinue(final ContinueStatement statement) {
controller.getAcg().onLineNumber(statement, "visitContinueStatement");
writeStatementLabel(statement);
Label label = controller.getCompileStack().getNamedContinueLabel(statement.getLabel());
controller.getCompileStack().applyFinallyBlocks(label, false);
controller.getMethodVisitor().visitJumpInsn(GOTO, label);
}
/**
* Generates bytecode for a synchronized statement.
* Stores the monitor object in a local variable, emits
* {@code MONITORENTER}/{@code MONITOREXIT} guards, and registers
* a catch-all exception handler that exits the monitor before rethrowing.
*
* @param statement the synchronized statement to compile
*/
public void writeSynchronized(final SynchronizedStatement statement) {
controller.getAcg().onLineNumber(statement, "visitSynchronizedStatement");
writeStatementLabel(statement);
MethodVisitor mv = controller.getMethodVisitor();
CompileStack compileStack = controller.getCompileStack();
statement.getExpression().visit(controller.getAcg());
controller.getOperandStack().box();
int index = compileStack.defineTemporaryVariable("synchronized", ClassHelper.OBJECT_TYPE, true);
Label synchronizedStart = new Label();
Label synchronizedEnd = new Label();
Label catchAll = new Label();
mv.visitVarInsn(ALOAD, index);
mv.visitInsn(MONITORENTER);
mv.visitLabel(synchronizedStart);
// placeholder for "empty" synchronized blocks, for example
// if there is only a break/continue.
mv.visitInsn(NOP);
Runnable finallyPart = () -> {
mv.visitVarInsn(ALOAD, index);
mv.visitInsn(MONITOREXIT);
};
BlockRecorder fb = new BlockRecorder(finallyPart);
fb.startRange(synchronizedStart);
compileStack.pushBlockRecorder(fb);
statement.getCode().visit(controller.getAcg());
fb.closeRange(catchAll);
compileStack.writeExceptionTable(fb, catchAll, null);
compileStack.pop(); //pop fb
boolean fallthrough = maybeFallsThrough(statement.getCode());
if (fallthrough) {
finallyPart.run();
mv.visitJumpInsn(GOTO, synchronizedEnd);
}
mv.visitLabel(catchAll);
finallyPart.run();
mv.visitInsn(ATHROW);
if (fallthrough) {
mv.visitLabel(synchronizedEnd);
}
compileStack.removeVar(index);
}
/**
* Generates bytecode for an assert statement.
*
* @param statement the assert statement to compile
*/
public void writeAssert(final AssertStatement statement) {
controller.getAcg().onLineNumber(statement, "visitAssertStatement");
writeStatementLabel(statement);
controller.getAssertionWriter().writeAssertStatement(statement);
}
/**
* Generates bytecode for a throw statement.
* Casts the expression to {@code Throwable} and emits {@code ATHROW}.
*
* @param statement the throw statement to compile
*/
public void writeThrow(final ThrowStatement statement) {
controller.getAcg().onLineNumber(statement, "visitThrowStatement");
writeStatementLabel(statement);
MethodVisitor mv = controller.getMethodVisitor();
statement.getExpression().visit(controller.getAcg());
// we should infer the type of the exception from the expression
mv.visitTypeInsn(CHECKCAST, "java/lang/Throwable");
mv.visitInsn(ATHROW);
controller.getOperandStack().remove(1);
}
/**
* Generates bytecode for a return statement.
* For void methods emits {@code RETURN} after applying any finally blocks.
* For value-returning methods evaluates the expression, casts it to the
* declared return type, and emits the appropriate typed return instruction.
*
* @param statement the return statement to compile
*/
public void writeReturn(final ReturnStatement statement) {
controller.getAcg().onLineNumber(statement, "visitReturnStatement");
writeStatementLabel(statement);
var cs = controller.getCompileStack();
var os = controller.getOperandStack();
var mv = controller.getMethodVisitor();
var returnType = controller.getReturnType();
if (ClassHelper.isPrimitiveVoid(returnType)) {
if (!statement.isReturningNullOrVoid()) { // TODO: move to Verifier
controller.getAcg().throwException("Cannot use return statement with an expression on a method that returns void");
}
cs.applyBlockRecorder();
mv.visitInsn(RETURN);
} else { // return value
Expression expression = statement.getExpression();
expression.visit(controller.getAcg());
if (!isNullConstant(expression) || ClassHelper.isPrimitiveType(returnType)) {
os.doGroovyCast(returnType);
} else { // GROOVY-10617
os.replace(returnType);
}
if (cs.hasBlockRecorder()) {
int rv = cs.defineTemporaryVariable("returnValue", returnType, true);
cs.applyBlockRecorder(); // handle finally block
BytecodeHelper.load(mv, returnType, rv);
BytecodeHelper.doReturn(mv, returnType);
cs.removeVar(rv);
} else {
BytecodeHelper.doReturn(mv, returnType);
os.remove(1);
}
}
}
/**
* Generates bytecode for an expression statement.
* Evaluates the expression and discards any value left on the operand stack.
* Marks method-call and binary expressions so that unused return values
* are elided rather than boxed.
*
* @param statement the expression statement to compile
*/
public void writeExpressionStatement(final ExpressionStatement statement) {
Expression expression = statement.getExpression();
controller.getAcg().onLineNumber(statement, "visitExpressionStatement: " + expression.getClass().getName());
writeStatementLabel(statement);
if (expression instanceof MethodCall || expression instanceof BinaryExpression)
expression.putNodeMetaData(AsmClassGenerator.ELIDE_EXPRESSION_VALUE, Boolean.TRUE);
var operandStack = controller.getOperandStack();
int mark = operandStack.getStackLength();
expression.visit(controller.getAcg());
operandStack.popDownTo(mark);
}
}