-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEmitterMethodCreator.java
More file actions
1717 lines (1528 loc) · 86.9 KB
/
EmitterMethodCreator.java
File metadata and controls
1717 lines (1528 loc) · 86.9 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 org.perlonjava.backend.jvm;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.analysis.*;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.Printer;
import org.objectweb.asm.util.TraceClassVisitor;
import org.perlonjava.backend.bytecode.BytecodeCompiler;
import org.perlonjava.backend.bytecode.Disassemble;
import org.perlonjava.backend.bytecode.InterpretedCode;
import org.perlonjava.frontend.analysis.EmitterVisitor;
import org.perlonjava.frontend.analysis.TempLocalCountVisitor;
import org.perlonjava.frontend.astnode.BlockNode;
import org.perlonjava.frontend.astnode.Node;
import org.perlonjava.runtime.runtimetypes.*;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* EmitterMethodCreator is a utility class that uses the ASM library to dynamically generate Java
* classes with specific methods. It is designed to create classes with methods that can be used for
* runtime evaluation of expressions or statements in a simulated Perl environment.
*/
public class EmitterMethodCreator implements Opcodes {
// Feature flags for control flow implementation
// Set to true to enable tail call trampoline (Phase 3)
private static final boolean ENABLE_TAILCALL_TRAMPOLINE = true;
// Set to true to enable debug output for control flow
private static final boolean DEBUG_CONTROL_FLOW = false;
// Feature flag for interpreter fallback (enabled by default, can be disabled)
private static final boolean USE_INTERPRETER_FALLBACK =
System.getenv("JPERL_DISABLE_INTERPRETER_FALLBACK") == null;
private static final boolean SHOW_FALLBACK =
System.getenv("JPERL_SHOW_FALLBACK") != null;
// Number of local variables to skip when processing a closure (this, @_, wantarray)
public static int skipVariables = 3;
// Counter for generating unique class names
public static int classCounter = 0;
// Generate a unique internal class name
public static String generateClassName() {
return "org/perlonjava/anon" + classCounter++;
}
private static String insnToString(AbstractInsnNode n) {
if (n == null) {
return "<null>";
}
int op = n.getOpcode();
String opName = (op >= 0 && op < Printer.OPCODES.length) ? Printer.OPCODES[op] : "<no-opcode>";
if (n instanceof org.objectweb.asm.tree.VarInsnNode vn) {
return opName + " " + vn.var;
}
if (n instanceof org.objectweb.asm.tree.MethodInsnNode mn) {
return opName + " " + mn.owner + "." + mn.name + mn.desc;
}
if (n instanceof org.objectweb.asm.tree.FieldInsnNode fn) {
return opName + " " + fn.owner + "." + fn.name + " : " + fn.desc;
}
if (n instanceof org.objectweb.asm.tree.TypeInsnNode tn) {
return opName + " " + tn.desc;
}
if (n instanceof org.objectweb.asm.tree.LdcInsnNode ln) {
return opName + " " + ln.cst;
}
if (n instanceof org.objectweb.asm.tree.IntInsnNode in) {
return opName + " " + in.operand;
}
if (n instanceof org.objectweb.asm.tree.IincInsnNode ii) {
return opName + " " + ii.var + " " + ii.incr;
}
if (n instanceof org.objectweb.asm.tree.LineNumberNode ln) {
return "LINE " + ln.line;
}
if (n instanceof org.objectweb.asm.tree.LabelNode) {
return "LABEL";
}
if (n instanceof org.objectweb.asm.tree.JumpInsnNode) {
return opName + " <label>";
}
return opName;
}
private static void debugAnalyzeWithBasicInterpreter(ClassReader cr, PrintWriter out) {
try {
ClassNode cn = new ClassNode();
cr.accept(cn, ClassReader.EXPAND_FRAMES);
for (Object m : cn.methods) {
MethodNode mn = (MethodNode) m;
try {
Analyzer<BasicValue> analyzer = new Analyzer<>(new BasicInterpreter());
analyzer.analyze(cn.name, mn);
} catch (AnalyzerException ae) {
int insnIndex = (ae.node != null) ? mn.instructions.indexOf(ae.node) : -1;
if (insnIndex < 0) {
try {
String msg = String.valueOf(ae);
int atPos = msg.indexOf("Error at instruction ");
if (atPos >= 0) {
int start = atPos + "Error at instruction ".length();
int end = start;
while (end < msg.length() && Character.isDigit(msg.charAt(end))) {
end++;
}
if (end > start) {
insnIndex = Integer.parseInt(msg.substring(start, end));
}
}
} catch (Throwable ignored) {
}
}
out.println("BasicInterpreter failure in " + cn.name + "." + mn.name + mn.desc + " at instruction " + insnIndex);
if (insnIndex >= 0) {
int from = Math.max(0, insnIndex - 10);
int to = Math.min(mn.instructions.size() - 1, insnIndex + 10);
for (int i = from; i <= to; i++) {
org.objectweb.asm.tree.AbstractInsnNode n = mn.instructions.get(i);
if (n instanceof org.objectweb.asm.tree.JumpInsnNode j) {
int target = mn.instructions.indexOf(j.label);
out.println(" [" + i + "] " + insnToString(n) + " -> [" + target + "]");
} else {
out.println(" [" + i + "] " + insnToString(n));
}
}
org.objectweb.asm.tree.AbstractInsnNode failing = mn.instructions.get(insnIndex);
if (failing instanceof org.objectweb.asm.tree.JumpInsnNode j) {
int target = mn.instructions.indexOf(j.label);
if (target >= 0) {
out.println(" --- jump target window: [" + target + "] ---");
int tFrom = Math.max(0, target - 10);
int tTo = Math.min(mn.instructions.size() - 1, target + 10);
for (int i = tFrom; i <= tTo; i++) {
org.objectweb.asm.tree.AbstractInsnNode n = mn.instructions.get(i);
if (n instanceof org.objectweb.asm.tree.JumpInsnNode tj) {
int tTarget = mn.instructions.indexOf(tj.label);
out.println(" [" + i + "] " + insnToString(n) + " -> [" + tTarget + "]");
} else {
out.println(" [" + i + "] " + insnToString(n));
}
}
out.println(" --- other predecessors targeting [" + target + "] ---");
java.util.ArrayList<Integer> predecessors = new java.util.ArrayList<>();
for (int i = 0; i < mn.instructions.size(); i++) {
if (i == insnIndex) {
continue;
}
org.objectweb.asm.tree.AbstractInsnNode n = mn.instructions.get(i);
if (n instanceof org.objectweb.asm.tree.JumpInsnNode pj && pj.label == j.label) {
out.println(" [" + i + "] " + insnToString(n) + " -> [" + target + "]");
predecessors.add(i);
}
}
try {
Analyzer<BasicValue> analyzer = new Analyzer<>(new BasicInterpreter());
try {
analyzer.analyze(cn.name, mn);
} catch (AnalyzerException ignored) {
}
org.objectweb.asm.tree.analysis.Frame<BasicValue>[] frames = analyzer.getFrames();
org.objectweb.asm.tree.analysis.Frame<SourceValue>[] sourceFrames = null;
try {
Analyzer<SourceValue> sourceAnalyzer = new Analyzer<>(new SourceInterpreter());
try {
sourceAnalyzer.analyze(cn.name, mn);
} catch (AnalyzerException ignored) {
}
sourceFrames = sourceAnalyzer.getFrames();
} catch (Throwable ignored) {
}
java.util.ArrayList<Integer> framePoints = new java.util.ArrayList<>();
framePoints.add(insnIndex);
framePoints.add(target);
framePoints.addAll(predecessors);
out.println(" --- frame stack sizes (if available) ---");
for (Integer idx : framePoints) {
if (idx == null || idx < 0 || idx >= frames.length) {
continue;
}
org.objectweb.asm.tree.analysis.Frame<BasicValue> f = frames[idx];
if (f == null) {
out.println(" [" + idx + "] <no frame>");
continue;
}
out.println(" [" + idx + "] stack=" + f.getStackSize() + " locals=" + f.getLocals());
for (int s = 0; s < f.getStackSize(); s++) {
out.println(" stack[" + s + "]=" + f.getStack(s));
}
if (sourceFrames != null && idx >= 0 && idx < sourceFrames.length) {
org.objectweb.asm.tree.analysis.Frame<SourceValue> sf = sourceFrames[idx];
if (sf != null) {
out.println(" --- stack sources at [" + idx + "] ---");
java.util.LinkedHashSet<Integer> sourceInsnsToPrint = new java.util.LinkedHashSet<>();
for (int s = 0; s < sf.getStackSize(); s++) {
SourceValue sv = sf.getStack(s);
if (sv == null || sv.insns == null) {
continue;
}
java.util.ArrayList<Integer> srcIdxs = new java.util.ArrayList<>();
for (org.objectweb.asm.tree.AbstractInsnNode src : sv.insns) {
int si = mn.instructions.indexOf(src);
if (si >= 0) {
srcIdxs.add(si);
sourceInsnsToPrint.add(si);
}
}
if (!srcIdxs.isEmpty()) {
out.println(" stack[" + s + "] sources=" + srcIdxs);
}
}
int printed = 0;
for (Integer srcIdx : sourceInsnsToPrint) {
if (srcIdx == null) {
continue;
}
if (printed++ >= 12) {
out.println(" (additional source windows omitted)");
break;
}
out.println(" --- source instruction window: [" + srcIdx + "] ---");
int sFrom = Math.max(0, srcIdx - 20);
int sTo = Math.min(mn.instructions.size() - 1, srcIdx + 20);
for (int i = sFrom; i <= sTo; i++) {
org.objectweb.asm.tree.AbstractInsnNode n = mn.instructions.get(i);
if (n instanceof org.objectweb.asm.tree.JumpInsnNode pj) {
int sTarget = mn.instructions.indexOf(pj.label);
out.println(" [" + i + "] " + insnToString(n) + " -> [" + sTarget + "]");
} else {
out.println(" [" + i + "] " + insnToString(n));
}
}
}
}
}
}
} catch (Throwable t) {
out.println(" <frame dump failed: " + t + ">");
}
for (Integer p : predecessors) {
out.println(" --- predecessor window: [" + p + "] -> [" + target + "] ---");
int pFrom = Math.max(0, p - 6);
int pTo = Math.min(mn.instructions.size() - 1, p + 6);
for (int i = pFrom; i <= pTo; i++) {
org.objectweb.asm.tree.AbstractInsnNode n = mn.instructions.get(i);
if (n instanceof org.objectweb.asm.tree.JumpInsnNode pj) {
int pTarget = mn.instructions.indexOf(pj.label);
out.println(" [" + i + "] " + insnToString(n) + " -> [" + pTarget + "]");
} else {
out.println(" [" + i + "] " + insnToString(n));
}
}
}
}
}
}
ae.printStackTrace(out);
return;
}
}
} catch (Throwable t) {
t.printStackTrace(out);
}
}
/**
* Generates a descriptor string based on the prefix of a Perl variable name.
*
* @param varName The Perl variable name, which typically starts with a special character
* indicating its type (e.g., '%', '@', or '$').
* @return A descriptor string representing the type of the Perl variable.
*/
public static String getVariableDescriptor(String varName) {
// Handle null or empty variable names (gaps in symbol table)
// These represent unused slots in the local variable array
if (varName == null || varName.isEmpty()) {
return "Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;";
}
// Extract the first character of the variable name
char firstChar = varName.charAt(0);
// Use a switch statement to determine the descriptor based on the first character
return switch (firstChar) {
case '%' -> "Lorg/perlonjava/runtime/runtimetypes/RuntimeHash;";
case '@' -> "Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;";
default -> "Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;";
};
}
/**
* Generates a class name based on the prefix of a Perl variable name.
*
* @param varName The Perl variable name, which typically starts with a special character
* indicating its type (e.g., '%', '@', or '$').
* @return A class name string representing the type of the Perl variable.
*/
public static String getVariableClassName(String varName) {
// Handle null or empty variable names (gaps in symbol table)
// These represent unused slots in the local variable array
if (varName == null || varName.isEmpty()) {
return "org/perlonjava/runtime/runtimetypes/RuntimeScalar";
}
// Extract the first character of the variable name
char firstChar = varName.charAt(0);
// Use a switch statement to determine the class name based on the first character
return switch (firstChar) {
case '%' -> "org/perlonjava/runtime/runtimetypes/RuntimeHash";
case '@' -> "org/perlonjava/runtime/runtimetypes/RuntimeArray";
default -> "org/perlonjava/runtime/runtimetypes/RuntimeScalar";
};
}
/**
* Creates a new class with a method based on the provided context, environment, and abstract
* syntax tree (AST).
*
* @param ctx The emitter context containing information for code generation.
* @param ast The abstract syntax tree representing the method body.
* @param useTryCatch Flag to enable try-catch in the generated class. This is used in `eval` operator.
* @return The generated class.
*/
public static Class<?> createClassWithMethod(EmitterContext ctx, Node ast, boolean useTryCatch) {
byte[] classData = getBytecode(ctx, ast, useTryCatch);
return loadBytecode(ctx, classData);
}
public static byte[] getBytecode(EmitterContext ctx, Node ast, boolean useTryCatch) {
boolean asmDebug = System.getenv("JPERL_ASM_DEBUG") != null;
try {
return getBytecodeInternal(ctx, ast, useTryCatch, false);
} catch (MethodTooLargeException tooLarge) {
throw tooLarge;
} catch (InterpreterFallbackException fallback) {
// Re-throw - caller will handle interpreter fallback
throw fallback;
} catch (ArrayIndexOutOfBoundsException frameComputeCrash) {
// ASM frame computation failed - fall back to interpreter
// This commonly happens with nested defers and complex control flow
boolean showFallback = System.getenv("JPERL_SHOW_FALLBACK") != null;
if (showFallback || asmDebug) {
frameComputeCrash.printStackTrace();
try {
String failingClass = (ctx != null && ctx.javaClassInfo != null)
? ctx.javaClassInfo.javaClassName
: "<unknown>";
int failingIndex = ast != null ? ast.getIndex() : -1;
String fileName = (ctx != null && ctx.errorUtil != null) ? ctx.errorUtil.getFileName() : "<unknown>";
int lineNumber = -1;
if (ctx != null && ctx.errorUtil != null && failingIndex >= 0) {
ctx.errorUtil.setTokenIndex(-1);
ctx.errorUtil.setLineNumber(1);
lineNumber = ctx.errorUtil.getLineNumber(failingIndex);
}
String at = lineNumber >= 0 ? (fileName + ":" + lineNumber) : fileName;
System.err.println("ASM frame compute crash in generated class: " + failingClass +
" (astIndex=" + failingIndex + ", at " + at + ") - using interpreter fallback");
} catch (Throwable ignored) {
}
}
if (asmDebug) {
try {
// Reset JavaClassInfo to avoid reusing partially-resolved Labels.
if (ctx != null && ctx.javaClassInfo != null) {
String previousName = ctx.javaClassInfo.javaClassName;
ctx.javaClassInfo = new JavaClassInfo();
ctx.javaClassInfo.javaClassName = previousName;
ctx.clearContextCache();
}
getBytecodeInternal(ctx, ast, useTryCatch, true);
} catch (Throwable diagErr) {
diagErr.printStackTrace();
}
}
// Compile to interpreter as fallback
InterpretedCode interpretedCode = compileToInterpreter(ast, ctx, useTryCatch);
String[] envNames = ctx.capturedEnv != null ? ctx.capturedEnv : ctx.symbolTable.getVariableNames();
throw new InterpreterFallbackException(interpretedCode, envNames);
}
}
private static byte[] getBytecodeInternal(EmitterContext ctx, Node ast, boolean useTryCatch, boolean disableFrames) {
String className = ctx.javaClassInfo.javaClassName;
String methodName = "apply";
byte[] classData = null;
boolean asmDebug = System.getenv("JPERL_ASM_DEBUG") != null;
String asmDebugClassFilter = System.getenv("JPERL_ASM_DEBUG_CLASS");
boolean asmDebugClassMatches = asmDebugClassFilter == null
|| asmDebugClassFilter.isEmpty()
|| className.contains(asmDebugClassFilter)
|| className.replace('/', '.').contains(asmDebugClassFilter);
try {
// Use capturedEnv if available (for eval), otherwise get from symbol table
String[] env = (ctx.capturedEnv != null) ? ctx.capturedEnv : ctx.symbolTable.getVariableNames();
// Create a ClassWriter with COMPUTE_FRAMES for automatic frame computation
// Only disable for explicit diagnostic pass
int cwFlags = disableFrames
? ClassWriter.COMPUTE_MAXS
: (ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
ClassWriter cw = new ClassWriter(cwFlags);
ctx.cw = cw;
// The context type is determined by the caller.
ctx.contextType = RuntimeContextType.RUNTIME;
ByteCodeSourceMapper.setDebugInfoFileName(ctx);
// Define the class with version, access flags, name, signature, superclass, and interfaces
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null);
ctx.logDebug("Create class: " + className);
// Add instance fields to the class for closure variables
for (String fieldName : env) {
// Skip null entries (gaps in sparse symbol table)
if (fieldName == null || fieldName.isEmpty()) {
continue;
}
String descriptor = getVariableDescriptor(fieldName);
ctx.logDebug("Create instance field: " + descriptor);
cw.visitField(Opcodes.ACC_PUBLIC, fieldName, descriptor, null, null).visitEnd();
}
// Add instance field for __SUB__ code reference
cw.visitField(Opcodes.ACC_PUBLIC, "__SUB__", "Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", null, null).visitEnd();
// Add a constructor with parameters for initializing the fields
// Include ALL env slots (even nulls) so signature matches caller expectations
StringBuilder constructorDescriptor = new StringBuilder("(");
for (int i = skipVariables; i < env.length; i++) {
String descriptor = getVariableDescriptor(env[i]); // handles nulls gracefully
constructorDescriptor.append(descriptor);
}
constructorDescriptor.append(")V");
ctx.logDebug("constructorDescriptor: " + constructorDescriptor);
ctx.mv =
cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", constructorDescriptor.toString(), null, null);
MethodVisitor mv = ctx.mv;
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0); // Load 'this'
mv.visitMethodInsn(
Opcodes.INVOKESPECIAL,
"java/lang/Object",
"<init>",
"()V",
false); // Call the superclass constructor
for (int i = skipVariables; i < env.length; i++) {
// Skip null entries (gaps in sparse symbol table)
if (env[i] == null || env[i].isEmpty()) {
continue;
}
String descriptor = getVariableDescriptor(env[i]);
mv.visitVarInsn(Opcodes.ALOAD, 0); // Load 'this'
mv.visitVarInsn(Opcodes.ALOAD, i - 2); // Load the constructor argument
mv.visitFieldInsn(
Opcodes.PUTFIELD, ctx.javaClassInfo.javaClassName, env[i], descriptor); // Set the instance field
}
mv.visitInsn(Opcodes.RETURN); // Return void
mv.visitMaxs(0, 0); // Automatically computed
mv.visitEnd();
// Create the public "apply" method for the generated class
ctx.logDebug("Create the method");
ctx.mv =
cw.visitMethod(
Opcodes.ACC_PUBLIC,
"apply",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;",
null,
new String[]{"java/lang/Exception"});
mv = ctx.mv;
// Generate the subroutine block
mv.visitCode();
// Initialize local variables with closure values from instance fields
// Skip some indices because they are reserved for special arguments (this, "@_" and call
// context)
for (int i = skipVariables; i < env.length; i++) {
// Skip null entries (gaps in sparse array)
if (env[i] == null) {
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitVarInsn(Opcodes.ASTORE, i);
continue;
}
String descriptor = getVariableDescriptor(env[i]);
mv.visitVarInsn(Opcodes.ALOAD, 0); // Load 'this'
ctx.logDebug("Init closure variable: " + descriptor);
mv.visitFieldInsn(Opcodes.GETFIELD, ctx.javaClassInfo.javaClassName, env[i], descriptor);
mv.visitVarInsn(Opcodes.ASTORE, i);
}
// IMPORTANT (JVM verifier): captured/lexical variables may live in *sparse* local slots,
// because their indices come from the symbol table (pad) and can include gaps.
//
// During bytecode emission we also allocate temporary locals via
// ctx.symbolTable.allocateLocalVariable(). If that allocator's current index is still
// below env.length, temporaries could be assigned into slots that are reserved for
// captured variables (even if those slots are currently "null" gaps in env[]), or into
// slots that will be accessed later as references.
//
// That overlap can produce invalid stack frames such as: locals[n] == TOP at an ALOAD,
// which the JVM rejects with VerifyError: Bad local variable type.
//
// Ensure temporaries start *after* the captured variable range.
//
// NOTE: ctx.symbolTable.allocateLocalVariable() mutates the symbol table's internal
// index counter. In eval-string compilation we may reuse the captured symbol table
// instance across many eval invocations. If we don't reset the counter for each
// generated method, the local slot numbers will grow without bound (eventually
// producing invalid stack map frames / VerifyError).
ctx.symbolTable.resetLocalVariableIndex(env.length);
// Pre-initialize temporary local slots to avoid VerifyError
// Temporaries are allocated dynamically during bytecode emission via
// ctx.symbolTable.allocateLocalVariable(). We pre-initialize slots to ensure
// they're not in TOP state when accessed. Use a visitor to estimate the
// actual number needed based on AST structure rather than a fixed count.
int preInitTempLocalsStart = ctx.symbolTable.getCurrentLocalVariableIndex();
TempLocalCountVisitor tempCountVisitor =
new TempLocalCountVisitor();
ast.accept(tempCountVisitor);
int preInitTempLocalsCount = tempCountVisitor.getMaxTempCount() + 64; // Optimized: removed min-128 baseline
for (int i = preInitTempLocalsStart; i < preInitTempLocalsStart + preInitTempLocalsCount; i++) {
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitVarInsn(Opcodes.ASTORE, i);
}
// Manual frames removed - using COMPUTE_FRAMES for automatic frame computation
// Allocate slots for tail call trampoline (codeRef and args)
// These are used at returnLabel for TAILCALL handling
int tailCallCodeRefSlot = ctx.symbolTable.allocateLocalVariable();
int tailCallArgsSlot = ctx.symbolTable.allocateLocalVariable();
ctx.javaClassInfo.tailCallCodeRefSlot = tailCallCodeRefSlot;
ctx.javaClassInfo.tailCallArgsSlot = tailCallArgsSlot;
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitVarInsn(Opcodes.ASTORE, tailCallCodeRefSlot);
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitVarInsn(Opcodes.ASTORE, tailCallArgsSlot);
// Allocate slot for control flow check temp storage
// This is used at call sites to temporarily store marked RuntimeControlFlowList
int controlFlowTempSlot = ctx.symbolTable.allocateLocalVariable();
ctx.javaClassInfo.controlFlowTempSlot = controlFlowTempSlot;
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitVarInsn(Opcodes.ASTORE, controlFlowTempSlot);
int controlFlowActionSlot = ctx.symbolTable.allocateLocalVariable();
ctx.javaClassInfo.controlFlowActionSlot = controlFlowActionSlot;
mv.visitInsn(Opcodes.ICONST_0);
mv.visitVarInsn(Opcodes.ISTORE, controlFlowActionSlot);
int spillSlotCount = System.getenv("JPERL_SPILL_SLOTS") != null
? Integer.parseInt(System.getenv("JPERL_SPILL_SLOTS"))
: 16;
ctx.javaClassInfo.spillSlots = new int[spillSlotCount];
ctx.javaClassInfo.spillTop = 0;
for (int i = 0; i < spillSlotCount; i++) {
int slot = ctx.symbolTable.allocateLocalVariable();
ctx.javaClassInfo.spillSlots[i] = slot;
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitVarInsn(Opcodes.ASTORE, slot);
}
// Create a label for the return point
ctx.javaClassInfo.returnLabel = new Label();
// Prepare to visit the AST to generate bytecode
EmitterVisitor visitor = new EmitterVisitor(ctx);
// Setup local variables and environment for the method
int dynamicIndex = Local.localSetup(ctx, ast, mv);
// Store dynamicIndex so goto &sub can access it for cleanup before tail call
ctx.javaClassInfo.dynamicLevelSlot = dynamicIndex;
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RegexState", "save", "()V", false);
// Store the computed RuntimeList return value in a dedicated local slot.
// This keeps the operand stack empty at join labels (endCatch), avoiding
// inconsistent stack map frames when multiple control-flow paths merge.
int returnListSlot = ctx.symbolTable.allocateLocalVariable();
// Spill the raw RuntimeBase return value for stack-neutral joins at returnLabel.
// Any path that jumps to returnLabel must arrive with an empty operand stack.
int returnValueSlot = ctx.symbolTable.allocateLocalVariable();
ctx.javaClassInfo.returnValueSlot = returnValueSlot;
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitVarInsn(Opcodes.ASTORE, returnValueSlot);
// Slot to save eval error across DVM teardown (used only when useTryCatch=true)
int evalErrorSlot = -1;
// Labels for eval-block try/catch wrapping (used only when useTryCatch=true)
Label tryStart = null;
Label tryEnd = null;
Label catchBlock = null;
Label endCatch = null;
if (useTryCatch) {
ctx.logDebug("useTryCatch");
// --------------------------------
// Start of try-catch block
// --------------------------------
evalErrorSlot = ctx.symbolTable.allocateLocalVariable();
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitVarInsn(Opcodes.ASTORE, evalErrorSlot);
tryStart = new Label();
tryEnd = new Label();
catchBlock = new Label();
endCatch = new Label();
// Define the try-catch block
mv.visitTryCatchBlock(tryStart, tryEnd, catchBlock, "java/lang/Throwable");
mv.visitLabel(tryStart);
// --------------------------------
// Start of the try block
// --------------------------------
// Set $@ to an empty string if no exception occurs
mv.visitLdcInsn("main::@");
mv.visitLdcInsn("");
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/GlobalVariable",
"setGlobalVariable",
"(Ljava/lang/String;Ljava/lang/String;)V", false);
ast.accept(visitor);
// Normal fallthrough return: spill and jump with empty operand stack.
mv.visitVarInsn(Opcodes.ASTORE, returnValueSlot);
mv.visitJumpInsn(Opcodes.GOTO, ctx.javaClassInfo.returnLabel);
// Handle the return value
ctx.logDebug("Return the last value");
// --------------------------------
// End of the try block
// --------------------------------
// NOTE: We intentionally delay tryEnd/endCatch labels until after the
// return-value materialization and trampoline checks below.
// This ensures eval BLOCK catches control-flow marker errors raised
// during epilogue processing (e.g. bad goto), instead of escaping and
// terminating top-level execution.
// --------------------------------
// End of try-catch block is emitted AFTER the epilogue/trampoline.
// --------------------------------
} else {
// No try-catch block is used
ast.accept(visitor);
// Normal fallthrough return: spill and jump with empty operand stack.
mv.visitVarInsn(Opcodes.ASTORE, returnValueSlot);
mv.visitJumpInsn(Opcodes.GOTO, ctx.javaClassInfo.returnLabel);
// Handle the return value
ctx.logDebug("Return the last value");
}
// Join point for all returns/gotos. Must be stack-neutral.
mv.visitLabel(ctx.javaClassInfo.returnLabel);
mv.visitVarInsn(Opcodes.ALOAD, returnValueSlot);
// Transform the value in the stack to RuntimeList BEFORE local teardown.
// Materialize it into a local slot immediately so all subsequent control-flow
// checks operate from locals and join points don't depend on operand stack shape.
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/perlonjava/runtime/runtimetypes/RuntimeBase", "getList", "()Lorg/perlonjava/runtime/runtimetypes/RuntimeList;", false);
mv.visitVarInsn(Opcodes.ASTORE, returnListSlot);
// Check for non-local control flow markers (LAST/NEXT/REDO/GOTO).
// TAILCALL is now handled at call sites, so we only see non-TAILCALL markers here.
// For eval blocks, these are errors. For normal subs, we just propagate (return with marker).
if (ENABLE_TAILCALL_TRAMPOLINE) {
Label normalReturn = new Label();
mv.visitVarInsn(Opcodes.ALOAD, returnListSlot);
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/runtime/runtimetypes/RuntimeList",
"isNonLocalGoto",
"()Z",
false);
mv.visitJumpInsn(Opcodes.IFEQ, normalReturn); // Not marked, return normally
// Marked with non-TAILCALL marker (LAST/NEXT/REDO/GOTO)
if (useTryCatch) {
// For eval BLOCK, any marked non-TAILCALL result is an eval failure.
mv.visitVarInsn(Opcodes.ALOAD, returnListSlot);
mv.visitTypeInsn(Opcodes.CHECKCAST, "org/perlonjava/runtime/runtimetypes/RuntimeControlFlowList");
int msgSlot = ctx.symbolTable.allocateLocalVariable();
// msg = marker.buildErrorMessage()
mv.visitInsn(Opcodes.DUP);
mv.visitFieldInsn(Opcodes.GETFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeControlFlowList",
"marker",
"Lorg/perlonjava/runtime/runtimetypes/ControlFlowMarker;");
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/runtime/runtimetypes/ControlFlowMarker",
"buildErrorMessage",
"()Ljava/lang/String;",
false);
mv.visitVarInsn(Opcodes.ASTORE, msgSlot);
// $@ = msg
mv.visitLdcInsn("main::@");
mv.visitVarInsn(Opcodes.ALOAD, msgSlot);
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/GlobalVariable",
"setGlobalVariable",
"(Ljava/lang/String;Ljava/lang/String;)V",
false);
// Replace marker with undef/empty list
mv.visitInsn(Opcodes.POP);
Label evalBlockList = new Label();
Label evalBlockDone = new Label();
mv.visitVarInsn(Opcodes.ILOAD, 2);
mv.visitInsn(Opcodes.ICONST_2); // RuntimeContextType.LIST
mv.visitJumpInsn(Opcodes.IF_ICMPEQ, evalBlockList);
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeList");
mv.visitInsn(Opcodes.DUP);
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeScalar");
mv.visitInsn(Opcodes.DUP);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeScalar", "<init>", "()V", false);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeList", "<init>", "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", false);
mv.visitJumpInsn(Opcodes.GOTO, evalBlockDone);
mv.visitLabel(evalBlockList);
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeList");
mv.visitInsn(Opcodes.DUP);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeList", "<init>", "()V", false);
mv.visitLabel(evalBlockDone);
// Materialize return value in local slot and jump to endCatch with empty stack.
mv.visitVarInsn(Opcodes.ASTORE, returnListSlot);
// Skip the success epilogue that clears $@.
// This path represents an eval failure (bad goto/other marker),
// so $@ must be preserved.
mv.visitJumpInsn(Opcodes.GOTO, endCatch);
}
// For non-eval subs: marker just propagates (falls through to return)
// Normal return (or propagate marker for non-eval subs)
mv.visitLabel(normalReturn);
} // End of if (ENABLE_TAILCALL_TRAMPOLINE)
if (useTryCatch) {
// --------------------------------
// End of the try block (includes epilogue/trampoline)
// --------------------------------
mv.visitLabel(tryEnd);
// Clear $@ on successful completion of eval (nested evals may have set it).
mv.visitLdcInsn("main::@");
mv.visitLdcInsn("");
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/GlobalVariable",
"setGlobalVariable",
"(Ljava/lang/String;Ljava/lang/String;)V", false);
// Jump over the catch block if no exception occurs
mv.visitJumpInsn(Opcodes.GOTO, endCatch);
// Start of the catch block
mv.visitLabel(catchBlock);
// The throwable object is on the stack
// Catch the throwable
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/operators/WarnDie",
"catchEval",
"(Ljava/lang/Throwable;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
mv.visitInsn(Opcodes.POP);
// Save a snapshot of $@ so we can re-set it after DVM teardown
// (DVM pop may restore `local $@` from a callee, clobbering $@)
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeScalar");
mv.visitInsn(Opcodes.DUP);
mv.visitLdcInsn("main::@");
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/GlobalVariable",
"getGlobalVariable",
"(Ljava/lang/String;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"<init>",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", false);
mv.visitVarInsn(Opcodes.ASTORE, evalErrorSlot);
// Return undef/empty list from eval on error.
Label evalCatchList = new Label();
Label evalCatchDone = new Label();
mv.visitVarInsn(Opcodes.ILOAD, 2);
mv.visitInsn(Opcodes.ICONST_2); // RuntimeContextType.LIST
mv.visitJumpInsn(Opcodes.IF_ICMPEQ, evalCatchList);
// Scalar/void: RuntimeList(new RuntimeScalar())
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeList");
mv.visitInsn(Opcodes.DUP);
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeScalar");
mv.visitInsn(Opcodes.DUP);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeScalar", "<init>", "()V", false);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeList", "<init>", "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", false);
mv.visitJumpInsn(Opcodes.GOTO, evalCatchDone);
// List: new RuntimeList()
mv.visitLabel(evalCatchList);
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeList");
mv.visitInsn(Opcodes.DUP);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeList", "<init>", "()V", false);
mv.visitLabel(evalCatchDone);
// Materialize return value in local slot.
mv.visitVarInsn(Opcodes.ASTORE, returnListSlot);
// End of the catch block
mv.visitLabel(endCatch);
// Load the return value for the method epilogue.
mv.visitVarInsn(Opcodes.ALOAD, returnListSlot);
} else {
// No try/catch: ensure the method epilogue sees the return value
// on the operand stack.
mv.visitVarInsn(Opcodes.ALOAD, returnListSlot);
}
// Materialize $1, $&, etc. into concrete scalars BEFORE restoring regex state.
// The return list may contain lazy ScalarSpecialVariable references; if we
// restored first, they would resolve to the caller's (stale) values.
mv.visitInsn(Opcodes.DUP);
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"materializeSpecialVarsInResult",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeList;)V", false);
if (useTryCatch) {
// For eval BLOCK, wrap the teardown in a try-catch to catch exceptions
// from defer blocks. If a defer block throws, we need to:
// 1. Catch the exception
// 2. Set $@ to the new exception (last exception wins, Perl semantics)
// 3. Return undef/empty list
// Spill RuntimeList to slot before try block to keep stack clean
mv.visitVarInsn(Opcodes.ASTORE, returnListSlot);
Label teardownTryStart = new Label();
Label teardownTryEnd = new Label();
Label teardownCatch = new Label();
Label teardownDone = new Label();
mv.visitTryCatchBlock(teardownTryStart, teardownTryEnd, teardownCatch, "java/lang/Throwable");
mv.visitLabel(teardownTryStart);
// Teardown local variables — popToLocalLevel() also restores regex state
// (RegexState was pushed onto the DVM stack at sub entry).
Local.localTeardown(dynamicIndex, mv);
mv.visitLabel(teardownTryEnd);
// After DVM teardown, re-set $@ if we caught an eval error.
// DVM pop may have restored `local $@` from a callee, clobbering
// the error that catchEval set.
Label skipErrorRestore = new Label();
mv.visitVarInsn(Opcodes.ALOAD, evalErrorSlot);
mv.visitJumpInsn(Opcodes.IFNULL, skipErrorRestore);
mv.visitLdcInsn("main::@");
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/GlobalVariable",
"getGlobalVariable",
"(Ljava/lang/String;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
mv.visitVarInsn(Opcodes.ALOAD, evalErrorSlot);
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"set",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
mv.visitInsn(Opcodes.POP);
mv.visitLabel(skipErrorRestore);
mv.visitJumpInsn(Opcodes.GOTO, teardownDone);
// Catch exceptions from defer blocks during teardown
mv.visitLabel(teardownCatch);
// Stack: [Throwable]
// Set $@ to the new exception (last exception wins)
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/operators/WarnDie",
"catchEval",
"(Ljava/lang/Throwable;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
mv.visitInsn(Opcodes.POP);
// Save the new error
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeScalar");
mv.visitInsn(Opcodes.DUP);
mv.visitLdcInsn("main::@");
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/GlobalVariable",
"getGlobalVariable",
"(Ljava/lang/String;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"<init>",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", false);
mv.visitVarInsn(Opcodes.ASTORE, evalErrorSlot);
// Create undef/empty list return value
Label teardownCatchList = new Label();
Label teardownCatchDone = new Label();
mv.visitVarInsn(Opcodes.ILOAD, 2);
mv.visitInsn(Opcodes.ICONST_2); // RuntimeContextType.LIST
mv.visitJumpInsn(Opcodes.IF_ICMPEQ, teardownCatchList);
// Scalar/void: RuntimeList(new RuntimeScalar())
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeList");
mv.visitInsn(Opcodes.DUP);
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeScalar");
mv.visitInsn(Opcodes.DUP);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeScalar", "<init>", "()V", false);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeList", "<init>", "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", false);
mv.visitJumpInsn(Opcodes.GOTO, teardownCatchDone);
// List: new RuntimeList()
mv.visitLabel(teardownCatchList);
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeList");
mv.visitInsn(Opcodes.DUP);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/perlonjava/runtime/runtimetypes/RuntimeList", "<init>", "()V", false);
mv.visitLabel(teardownCatchDone);
// Store new return value
mv.visitVarInsn(Opcodes.ASTORE, returnListSlot);
// Restore $@ from saved slot
mv.visitLdcInsn("main::@");
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/GlobalVariable",
"getGlobalVariable",
"(Ljava/lang/String;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
mv.visitVarInsn(Opcodes.ALOAD, evalErrorSlot);
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"set",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
mv.visitInsn(Opcodes.POP);
// Both paths join here with empty stack
mv.visitLabel(teardownDone);
// Load the return value for ARETURN
mv.visitVarInsn(Opcodes.ALOAD, returnListSlot);
} else {
// No try-catch: just do the teardown
// Teardown local variables — popToLocalLevel() also restores regex state
// (RegexState was pushed onto the DVM stack at sub entry).
Local.localTeardown(dynamicIndex, mv);
}
mv.visitInsn(Opcodes.ARETURN); // Returns an Object
mv.visitMaxs(0, 0); // Automatically computed
mv.visitEnd();
// Complete the class
cw.visitEnd();
classData = cw.toByteArray(); // Generate the bytecode