-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathEmitSubroutine.java
More file actions
1445 lines (1302 loc) · 72.3 KB
/
Copy pathEmitSubroutine.java
File metadata and controls
1445 lines (1302 loc) · 72.3 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.perlonjava.app.cli.CompilerOptions;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.perlonjava.backend.bytecode.InterpretedCode;
import org.perlonjava.backend.bytecode.VariableCollectorVisitor;
import org.perlonjava.frontend.analysis.EmitterVisitor;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.frontend.semantic.ScopedSymbolTable;
import org.perlonjava.frontend.semantic.SymbolTable;
import org.perlonjava.runtime.runtimetypes.NameNormalizer;
import org.perlonjava.runtime.runtimetypes.GlobalVariable;
import org.perlonjava.runtime.runtimetypes.PerlCompilerException;
import org.perlonjava.runtime.runtimetypes.RuntimeBase;
import org.perlonjava.runtime.runtimetypes.RuntimeCode;
import org.perlonjava.runtime.runtimetypes.RuntimeContextType;
import org.perlonjava.runtime.runtimetypes.RuntimeScalar;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import static org.perlonjava.runtime.perlmodule.Strict.HINT_STRICT_REFS;
import static org.perlonjava.runtime.perlmodule.Strict.HINT_STRICT_SUBS;
import static org.perlonjava.runtime.perlmodule.Strict.HINT_STRICT_VARS;
/**
* The EmitSubroutine class is responsible for handling subroutine-related operations
* and generating the corresponding bytecode using ASM.
*/
public class EmitSubroutine {
// Feature flags for control flow implementation
//
// IMPORTANT:
// These flags are intentionally conservative and are part of perl5 test-suite stability.
// In particular, many core tests rely on SKIP/TODO blocks implemented via test.pl:
// sub skip { ...; last SKIP; }
// which requires non-local control flow (LAST/NEXT/REDO/GOTO) to propagate across
// subroutine boundaries correctly.
//
// Historically, toggling these flags has caused large test regressions (e.g. op/pack.t collapsing)
// and JVM verifier/ASM frame computation failures due to stack-map frame merge issues.
// Do not change these settings unless you also re-run the perl5 test suite and verify
// both semantics and bytecode verification.
//
// WHAT THIS WOULD DO IF ENABLED:
// After every subroutine call, check if the returned RuntimeList is a RuntimeControlFlowList
// (marked with last/next/redo/goto), and if so, immediately propagate it to returnLabel
// instead of continuing execution. This would enable loop handlers to catch control flow
// at the loop level instead of propagating all the way up the call stack.
//
// WHY IT'S DISABLED:
// The inline check pattern causes ArrayIndexOutOfBoundsException in ASM's frame computation:
// DUP // Duplicate result
// INSTANCEOF RuntimeControlFlowList // Check if marked
// IFEQ notMarked // Branch
// ASTORE tempSlot // Store (slot allocated dynamically)
// emitPopInstructions(0) // Clean stack
// ALOAD tempSlot // Restore
// GOTO returnLabel // Propagate
// notMarked: POP // Discard duplicate
//
// The complex branching with dynamic slot allocation breaks ASM's ability to merge frames
// at the branch target, especially when the tempSlot is allocated after the branch instruction.
//
// INVESTIGATION NEEDED:
// 1. Try allocating tempSlot statically at method entry (not dynamically per call)
// 2. Try simpler pattern without DUP (accept performance hit of extra ALOAD/ASTORE)
// 3. Try manual frame hints with visitFrame() at merge points
// 4. Consider moving check to VOID context only (after POP) - but this loses marked returns
// 5. Profile real-world code to see if this optimization actually matters
//
// CURRENT WORKAROUND:
// Without call-site checks, marked returns propagate through normal return paths.
// This works correctly but is less efficient for deeply nested loops crossing subroutines.
// Performance impact is minimal since most control flow is local (uses plain JVM GOTO).
private static final boolean ENABLE_CONTROL_FLOW_CHECKS = true;
// Set to true to enable debug output for control flow checks
private static final boolean DEBUG_CONTROL_FLOW = false;
/**
* Emits bytecode for a subroutine, including handling of closure variables.
*
* @param ctx The context used for code emission.
* @param node The subroutine node representing the subroutine.
*/
public static void emitSubroutine(EmitterContext ctx, SubroutineNode node) {
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("SUB start");
if (node.getBooleanAnnotation("futureAsyncAwaitSub")
&& !org.perlonjava.frontend.parser.FutureAsyncAwaitParser.hasAwaitableFuture(node)) {
throw new PerlCompilerException(
node.tokenIndex,
org.perlonjava.frontend.parser.FutureAsyncAwaitParser.BACKEND_MESSAGE,
ctx.errorUtil);
}
if (ctx.contextType == RuntimeContextType.VOID) {
return;
}
MethodVisitor mv = ctx.mv;
Set<String> declaredLexicalNames = new LinkedHashSet<>();
if (node.block != null) {
node.block.accept(new VariableCollectorVisitor(
new HashSet<>(), declaredLexicalNames));
}
// Retrieve closure variable list (copy to avoid corrupting the cache)
Map<Integer, SymbolTable.SymbolEntry> visibleVariables = new TreeMap<>(ctx.symbolTable.getAllVisibleVariables());
// IMPORTANT: Package-level subs (named subs) should NOT capture closure variables from their
// definition context. Only anonymous subs (my sub, state sub, or true anonymous subs) should
// capture variables. This prevents issues like defining 'sub bar::foo' inside a block with
// 'our sub foo' from incorrectly capturing the 'our sub' as a closure variable.
// Note: "(eval)" is a special name for eval blocks which should capture variables like anonymous subs
boolean isPackageSub = node.name != null && !node.name.equals("<anon>") && !node.name.equals("(eval)");
if (isPackageSub) {
// Package subs should not capture any closure variables
// They can only access global variables and their parameters
visibleVariables.clear();
} else {
// For anonymous/lexical subs, filter out 'our sub' declarations only
visibleVariables.entrySet().removeIf(entry -> {
SymbolTable.SymbolEntry symbolEntry = entry.getValue();
if (symbolEntry.name().startsWith("&") && symbolEntry.ast() instanceof OperatorNode operatorNode) {
Boolean isOurSub = (Boolean) operatorNode.getAnnotation("isOurSub");
return isOurSub != null && isOurSub;
}
return false;
});
}
// Optimization: Only capture variables actually used in the subroutine body.
// This prevents hitting JVM's 255 constructor argument limit for closures
// in modules like Perl::Tidy that have 200+ lexicals in scope.
if (!isPackageSub && node.block != null && !visibleVariables.isEmpty()) {
Set<String> usedVars = new HashSet<>();
VariableCollectorVisitor collector = new VariableCollectorVisitor(usedVars);
node.block.accept(collector);
if (!collector.hasEvalString()) {
int skip = EmitterMethodCreator.skipVariables;
int pos = 0;
Iterator<Map.Entry<Integer, SymbolTable.SymbolEntry>> it =
visibleVariables.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, SymbolTable.SymbolEntry> entry = it.next();
if (pos >= skip && !usedVars.contains(entry.getValue().name())) {
it.remove();
}
pos++;
}
}
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("AnonSub ctx.symbolTable.getAllVisibleVariables");
// Create a new symbol table for the subroutine, but manually add only the filtered variables
ScopedSymbolTable newSymbolTable = new ScopedSymbolTable();
newSymbolTable.enterScope();
// Add only the filtered visible variables (excluding 'our sub' entries)
// IMPORTANT: Use the 4-argument version to preserve the original perlPackage
// This is critical for 'our' variables declared in BEGIN captures (PerlOnJava::_BEGIN_*)
// which must retain their original package to work correctly with the 'local' fix
for (SymbolTable.SymbolEntry entry : visibleVariables.values()) {
newSymbolTable.addVariable(entry.name(), entry.decl(), entry.perlPackage(), entry.ast());
}
// Copy package, subroutine, and flags from the current context
newSymbolTable.setCurrentPackage(ctx.symbolTable.getCurrentPackage(), ctx.symbolTable.currentPackageIsClass());
// For eval blocks "(eval)", set the subroutine name so caller() reports it correctly
if ("(eval)".equals(node.name)) {
newSymbolTable.setCurrentSubroutine("(eval)");
} else if (node.name == null || node.name.equals("<anon>")) {
// True anonymous sub: caller() should report it as "Package::__ANON__",
// NOT as the enclosing named sub. Matches Perl 5 behavior.
newSymbolTable.setCurrentSubroutine(ctx.symbolTable.getCurrentPackage() + "::__ANON__");
} else {
newSymbolTable.setCurrentSubroutine(ctx.symbolTable.getCurrentSubroutine());
}
newSymbolTable.warningFlagsStack.pop();
newSymbolTable.warningFlagsStack.push((java.util.BitSet) ctx.symbolTable.warningFlagsStack.peek().clone());
newSymbolTable.warningFatalStack.pop();
newSymbolTable.warningFatalStack.push((java.util.BitSet) ctx.symbolTable.warningFatalStack.peek().clone());
newSymbolTable.warningDisabledStack.pop();
newSymbolTable.warningDisabledStack.push((java.util.BitSet) ctx.symbolTable.warningDisabledStack.peek().clone());
newSymbolTable.featureFlagsStack.pop();
newSymbolTable.featureFlagsStack.push(ctx.symbolTable.featureFlagsStack.peek());
newSymbolTable.strictOptionsStack.pop();
newSymbolTable.strictOptionsStack.push(ctx.symbolTable.strictOptionsStack.peek());
String[] newEnv = newSymbolTable.getVariableNames();
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("AnonSub " + newSymbolTable);
// Reset the index counter to start after the closure variables
// This prevents allocateLocalVariable() from creating slots that overlap with uninitialized slots
// We need to use the MAXIMUM of newEnv.length and the current index to avoid conflicts
int currentVarIndex = newSymbolTable.getCurrentLocalVariableIndex();
int resetTo = Math.max(newEnv.length, currentVarIndex);
newSymbolTable.resetLocalVariableIndex(resetTo);
// Create the new method context
JavaClassInfo newJavaClassInfo = new JavaClassInfo();
// Check if this subroutine is a defer block - control flow restrictions apply
Boolean isDeferBlock = (Boolean) node.getAnnotation("isDeferBlock");
if (isDeferBlock != null && isDeferBlock) {
newJavaClassInfo.isInDeferBlock = true;
}
// Check if this is an eval block - goto &sub is prohibited
if (node.useTryCatch) {
newJavaClassInfo.isInEvalBlock = true;
}
java.util.Set<Integer> capturedVariableIndices = new java.util.HashSet<>();
for (SymbolTable.SymbolEntry entry : visibleVariables.values()) {
int capturedIndex = newSymbolTable.getVariableIndex(entry.name());
if (capturedIndex >= EmitterMethodCreator.skipVariables) {
capturedVariableIndices.add(capturedIndex);
}
}
newJavaClassInfo.capturedVariableIndices = capturedVariableIndices;
// Check if this subroutine is a map/grep block - return should propagate non-locally
Boolean isMapGrepBlock = (Boolean) node.getAnnotation("isMapGrepBlock");
if (isMapGrepBlock != null && isMapGrepBlock) {
newJavaClassInfo.isMapGrepBlock = true;
}
EmitterContext subCtx =
new EmitterContext(
newJavaClassInfo, // Internal Java class name
newSymbolTable, // Closure symbolTable
null, // Method visitor
null, // Class writer
RuntimeContextType.RUNTIME, // Call context
true, // Is boxed
ctx.errorUtil, // Error message utility
ctx.compilerOptions,
null);
int skipVariables = EmitterMethodCreator.skipVariables; // Skip (this, @_, wantarray)
try {
if (node.getBooleanAnnotation("futureAsyncAwaitSub")) {
InterpretedCode interpreted = EmitterMethodCreator.compileToInterpreter(
node.block, subCtx, node.useTryCatch);
interpreted.futureAsyncAwaitSub = true;
interpreted.futureAsyncAwaitFutureClass =
(String) node.getAnnotation("futureAsyncAwaitFutureClass");
throw new InterpreterFallbackException(interpreted, newEnv);
}
Class<?> generatedClass =
EmitterMethodCreator.createClassWithMethod(
subCtx, node.block, node.useTryCatch
);
String newClassNameDot = subCtx.javaClassInfo.javaClassName.replace('/', '.');
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("Generated class name: " + newClassNameDot + " internal " + subCtx.javaClassInfo.javaClassName);
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("Generated class env: " + Arrays.toString(newEnv));
RuntimeCode.registerAnonymousSub(
subCtx.javaClassInfo.javaClassName, generatedClass); // Cache the class
String cvStartFile = "-e";
int cvStartLine = 0;
if (ctx.errorUtil != null && node.block != null) {
var loc = ctx.errorUtil.getSourceLocationAccurate(node.block.getIndex());
cvStartLine = loc.lineNumber();
if (loc.fileName() != null && !loc.fileName().isEmpty()) {
cvStartFile = loc.fileName();
}
} else if (ctx.compilerOptions != null && ctx.compilerOptions.fileName != null) {
cvStartFile = ctx.compilerOptions.fileName;
}
int deparseSourceOffset = -1;
int deparseSourceEnd = -1;
if (ctx.errorUtil != null) {
// The subroutine node carries the lexer token index. The
// block's index is the first AST child index and can point at
// a later enclosing block for adjacent anonymous subs,
// causing Storable::Deparse to retain the wrong source.
deparseSourceOffset = ctx.errorUtil.getSourceOffset(node.getIndex());
if (node.sourceEndTokenIndex >= 0) {
deparseSourceEnd = ctx.errorUtil.getSourceOffset(node.sourceEndTokenIndex);
}
}
String deparseSourceText = null;
if (ctx.compilerOptions != null) {
deparseSourceText = ctx.compilerOptions.deparseSourceCode != null
? ctx.compilerOptions.deparseSourceCode
: ctx.compilerOptions.code;
}
int deparseFlags = 0;
int strictAll = HINT_STRICT_REFS | HINT_STRICT_SUBS | HINT_STRICT_VARS;
if ((ctx.symbolTable.getStrictOptions() & strictAll) == strictAll) {
deparseFlags |= RuntimeCode.DEPARSE_FLAG_STRICT;
}
if (ctx.symbolTable.warningFlagsStack != null
&& !ctx.symbolTable.warningFlagsStack.isEmpty()
&& !ctx.symbolTable.warningFlagsStack.peek().isEmpty()) {
deparseFlags |= RuntimeCode.DEPARSE_FLAG_WARNINGS;
}
// Transfer pad constants (cached string literals referenced via \) from compile time
// to a registry so makeCodeObject() can attach them to the RuntimeCode at runtime.
if (subCtx.javaClassInfo.padConstants != null && !subCtx.javaClassInfo.padConstants.isEmpty()) {
RuntimeCode.registerPadConstants(subCtx.javaClassInfo.javaClassName,
subCtx.javaClassInfo.padConstants.toArray(new RuntimeBase[0]));
}
// Direct instantiation approach - no reflection needed!
// 1. NEW - Create new instance
mv.visitTypeInsn(Opcodes.NEW, subCtx.javaClassInfo.javaClassName);
mv.visitInsn(Opcodes.DUP);
// 2. Load all captured variables for the constructor
int newIndex = 0;
for (Integer currentIndex : visibleVariables.keySet()) {
if (newIndex >= skipVariables) {
mv.visitVarInsn(Opcodes.ALOAD, currentIndex); // Load the captured variable
}
newIndex++;
}
// 3. Build the constructor descriptor
StringBuilder constructorDescriptor = new StringBuilder("(");
for (int i = skipVariables; i < newEnv.length; i++) {
String descriptor = EmitterMethodCreator.getVariableDescriptor(newEnv[i]);
constructorDescriptor.append(descriptor);
}
constructorDescriptor.append(")V");
// 4. INVOKESPECIAL - Call the constructor
mv.visitMethodInsn(
Opcodes.INVOKESPECIAL,
subCtx.javaClassInfo.javaClassName,
"<init>",
constructorDescriptor.toString(),
false);
// 5. Create a CODE variable using RuntimeCode.makeCodeObject
// Always pass the current package name (CvSTASH) so anonymous subs
// know which package they were compiled in. This is critical for
// $AUTOLOAD being set in the correct package and for B::svref_2object->STASH->NAME.
if (node.prototype != null) {
mv.visitLdcInsn(node.prototype);
} else {
mv.visitInsn(Opcodes.ACONST_NULL);
}
mv.visitLdcInsn(ctx.symbolTable.getCurrentPackage());
mv.visitLdcInsn(cvStartFile);
mv.visitLdcInsn(cvStartLine);
if (deparseSourceText != null) {
mv.visitLdcInsn(deparseSourceText);
} else {
mv.visitInsn(Opcodes.ACONST_NULL);
}
mv.visitLdcInsn(deparseFlags);
mv.visitLdcInsn(deparseSourceOffset);
mv.visitLdcInsn(deparseSourceEnd);
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"makeCodeObject",
"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;III)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;",
false);
} catch (InterpreterFallbackException fallback) {
// JVM compilation failed (e.g., ASM frame crash) - use InterpretedCode instead
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("Using interpreter fallback for subroutine");
// Set CvSTASH on the InterpretedCode if not already set
if (fallback.interpretedCode.packageName == null) {
fallback.interpretedCode.packageName = ctx.symbolTable.getCurrentPackage();
}
// Store the InterpretedCode in the interpretedSubs map with a unique key
String fallbackKey = "interpreted_" + System.identityHashCode(fallback.interpretedCode);
RuntimeCode.putInterpretedSub(fallbackKey, fallback.interpretedCode);
// Generate bytecode to retrieve and configure the InterpretedCode
// 1. Load the InterpretedCode from the map
mv.visitLdcInsn(fallbackKey);
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"getInterpretedSub",
"(Ljava/lang/String;)Ljava/lang/Object;",
false);
mv.visitTypeInsn(Opcodes.CHECKCAST, "org/perlonjava/backend/bytecode/InterpretedCode");
// 2. Build RuntimeBase[] array of captured variables
int numCaptured = newEnv.length - skipVariables;
if (numCaptured > 0) {
// Store the InterpretedCode temporarily
int codeSlot = ctx.symbolTable.allocateLocalVariable();
mv.visitVarInsn(Opcodes.ASTORE, codeSlot);
// Create array for captured vars
mv.visitLdcInsn(numCaptured);
mv.visitTypeInsn(Opcodes.ANEWARRAY, "org/perlonjava/runtime/runtimetypes/RuntimeBase");
// Fill the array with captured variables
int arrayIndex = 0;
int varIndex = 0;
for (Integer currentIndex : visibleVariables.keySet()) {
if (varIndex >= skipVariables) {
mv.visitInsn(Opcodes.DUP);
mv.visitLdcInsn(arrayIndex);
mv.visitVarInsn(Opcodes.ALOAD, currentIndex);
mv.visitInsn(Opcodes.AASTORE);
arrayIndex++;
}
varIndex++;
}
// Call withCapturedVars to create a new InterpretedCode with captured vars
int arraySlot = ctx.symbolTable.allocateLocalVariable();
mv.visitVarInsn(Opcodes.ASTORE, arraySlot);
mv.visitVarInsn(Opcodes.ALOAD, codeSlot);
mv.visitVarInsn(Opcodes.ALOAD, arraySlot);
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/backend/bytecode/InterpretedCode",
"withCapturedVars",
"([Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)Lorg/perlonjava/backend/bytecode/InterpretedCode;",
false);
}
// 3. Wrap in RuntimeScalar(RuntimeCode)
mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeScalar");
mv.visitInsn(Opcodes.DUP_X1);
mv.visitInsn(Opcodes.SWAP);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"<init>",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeCode;)V",
false);
// Set prototype if needed
if (node.prototype != null) {
mv.visitInsn(Opcodes.DUP);
mv.visitFieldInsn(Opcodes.GETFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"value",
"Ljava/lang/Object;");
mv.visitTypeInsn(Opcodes.CHECKCAST, "org/perlonjava/runtime/runtimetypes/RuntimeCode");
mv.visitLdcInsn(node.prototype);
mv.visitFieldInsn(Opcodes.PUTFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"prototype",
"Ljava/lang/String;");
}
}
// Set isMapGrepBlock on the RuntimeCode so RuntimeCode.apply() can propagate
// non-local returns through map/grep blocks
if (isMapGrepBlock != null && isMapGrepBlock) {
mv.visitInsn(Opcodes.DUP);
mv.visitFieldInsn(Opcodes.GETFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"value",
"Ljava/lang/Object;");
mv.visitTypeInsn(Opcodes.CHECKCAST, "org/perlonjava/runtime/runtimetypes/RuntimeCode");
mv.visitInsn(Opcodes.ICONST_1);
mv.visitFieldInsn(Opcodes.PUTFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"isMapGrepBlock",
"Z");
// map/grep blocks are callbacks within the current Perl sub, not
// anonymous Perl subs of their own. Preserve the enclosing __SUB__.
mv.visitInsn(Opcodes.DUP);
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitFieldInsn(Opcodes.GETFIELD,
ctx.javaClassInfo.javaClassName,
"__SUB__",
"Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;");
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"inheritSelfReference",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V",
false);
}
if (node.getBooleanAnnotation("inheritsSelfReference")
&& !(isMapGrepBlock != null && isMapGrepBlock)) {
mv.visitInsn(Opcodes.DUP);
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitFieldInsn(Opcodes.GETFIELD,
ctx.javaClassInfo.javaClassName,
"__SUB__",
"Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;");
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"inheritSelfReference",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V",
false);
}
if (node.getBooleanAnnotation("regexCallbackPseudoBlock")) {
mv.visitInsn(Opcodes.DUP);
mv.visitFieldInsn(Opcodes.GETFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"value",
"Ljava/lang/Object;");
mv.visitTypeInsn(Opcodes.CHECKCAST,
"org/perlonjava/runtime/runtimetypes/RuntimeCode");
mv.visitInsn(Opcodes.ICONST_1);
mv.visitFieldInsn(Opcodes.PUTFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"isRegexCallbackPseudoBlock",
"Z");
}
// Set isEvalBlock on the RuntimeCode so RuntimeCode.apply() propagates
// non-local returns through eval BLOCK boundaries
if (node.useTryCatch) {
mv.visitInsn(Opcodes.DUP);
mv.visitFieldInsn(Opcodes.GETFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"value",
"Ljava/lang/Object;");
mv.visitTypeInsn(Opcodes.CHECKCAST, "org/perlonjava/runtime/runtimetypes/RuntimeCode");
mv.visitInsn(Opcodes.ICONST_1);
mv.visitFieldInsn(Opcodes.PUTFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"isEvalBlock",
"Z");
}
if (node.getBooleanAnnotation("tryExpressionWrapper")) {
mv.visitInsn(Opcodes.DUP);
mv.visitFieldInsn(Opcodes.GETFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"value",
"Ljava/lang/Object;");
mv.visitTypeInsn(Opcodes.CHECKCAST, "org/perlonjava/runtime/runtimetypes/RuntimeCode");
mv.visitInsn(Opcodes.ICONST_1);
mv.visitFieldInsn(Opcodes.PUTFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"isTryExpressionWrapper",
"Z");
}
// Set attributes if needed (after try-catch, both paths leave RuntimeScalar on stack)
if (node.attributes != null && !node.attributes.isEmpty()) {
mv.visitInsn(Opcodes.DUP);
mv.visitFieldInsn(Opcodes.GETFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"value",
"Ljava/lang/Object;");
mv.visitTypeInsn(Opcodes.CHECKCAST, "org/perlonjava/runtime/runtimetypes/RuntimeCode");
// Create a new ArrayList and populate it
mv.visitTypeInsn(Opcodes.NEW, "java/util/ArrayList");
mv.visitInsn(Opcodes.DUP);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL,
"java/util/ArrayList",
"<init>",
"()V",
false);
for (String attr : node.attributes) {
mv.visitInsn(Opcodes.DUP);
mv.visitLdcInsn(attr);
mv.visitMethodInsn(Opcodes.INVOKEINTERFACE,
"java/util/List",
"add",
"(Ljava/lang/Object;)Z",
true);
mv.visitInsn(Opcodes.POP); // pop boolean return of add()
}
mv.visitFieldInsn(Opcodes.PUTFIELD,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"attributes",
"Ljava/util/List;");
}
RuntimeScalar compileTimeAttributeCodeRef =
node.getAnnotation("compileTimeAttributeCodeRef") instanceof RuntimeScalar ref
? ref : null;
if (compileTimeAttributeCodeRef != null) {
String key = "compile_time_attr_"
+ System.identityHashCode(compileTimeAttributeCodeRef);
RuntimeCode.putInterpretedSub(key, compileTimeAttributeCodeRef);
// Stack: [compiledRef]
mv.visitLdcInsn(key);
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"getInterpretedSub",
"(Ljava/lang/String;)Ljava/lang/Object;",
false);
mv.visitTypeInsn(Opcodes.CHECKCAST,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar");
// Stack: [compiledRef, compileTimeRef]
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/perlmodule/Attributes",
"adoptCompileTimeCodeRef",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;"
+ "Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)"
+ "Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;",
false);
} else if (node.name == null && node.attributes != null && !node.attributes.isEmpty()) {
// Legacy fallback for ASTs created outside the parser.
java.util.Set<String> builtinAttrs = java.util.Set.of("lvalue", "method", "const");
boolean hasNonBuiltin = false;
for (String attr : node.attributes) {
String name = attr.startsWith("-") ? attr.substring(1) : attr;
int parenIdx = name.indexOf('(');
String baseName = parenIdx >= 0 ? name.substring(0, parenIdx) : name;
if (!builtinAttrs.contains(baseName) && !baseName.equals("prototype")) {
hasNonBuiltin = true;
break;
}
}
if (hasNonBuiltin) {
// Determine if this sub is a closure (captures outer lexical variables).
// Closures get closure prototype semantics: MODIFY_CODE_ATTRIBUTES receives
// the prototype (non-callable), and the expression result is a callable clone.
boolean isClosure = visibleVariables.size() > skipVariables;
// Stack: [RuntimeScalar(codeRef)]
mv.visitInsn(Opcodes.DUP);
// Stack: [codeRef, codeRef]
mv.visitLdcInsn(ctx.symbolTable.getCurrentPackage());
mv.visitInsn(Opcodes.SWAP);
// Stack: [codeRef, pkg, codeRef]
mv.visitInsn(isClosure ? Opcodes.ICONST_1 : Opcodes.ICONST_0);
// Stack: [codeRef, pkg, codeRef, isClosure]
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/perlmodule/Attributes",
"runtimeDispatchModifyCodeAttributes",
"(Ljava/lang/String;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Z)V",
false);
// Stack: [codeRef] (codeRef.value now points to clone if isClosure)
}
}
// PadWalker::peek_sub must also see lexicals declared by anonymous
// subs. Named subs get this metadata from SubroutineParser, while
// anonymous subs are materialized here at runtime.
mv.visitLdcInsn(declaredLexicalNames.size());
mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
int declaredNameIndex = 0;
for (String variableName : declaredLexicalNames) {
mv.visitInsn(Opcodes.DUP);
mv.visitLdcInsn(declaredNameIndex++);
mv.visitLdcInsn(variableName);
mv.visitInsn(Opcodes.AASTORE);
}
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"attachLexicalVariableNames",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;[Ljava/lang/String;)"
+ "Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;",
false);
// 6. Clean up the stack if context is VOID
if (ctx.contextType == RuntimeContextType.VOID) {
mv.visitInsn(Opcodes.POP); // Remove the RuntimeScalar object from the stack
}
// If the context is not VOID, the stack should contain [RuntimeScalar] (the CODE variable)
// If the context is VOID, the stack should be empty
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("SUB end");
}
/**
* Handles the postfix `()` node, which runs a subroutine.
*
* @param emitterVisitor The visitor used for code emission.
* @param node The binary operator node representing the apply operation.
*/
static void handleApplyOperator(EmitterVisitor emitterVisitor, BinaryOperatorNode node) {
if (CompilerOptions.DEBUG_ENABLED) emitterVisitor.ctx.logDebug("handleApplyElementOperator " + node + " in context " + emitterVisitor.ctx.contextType);
MethodVisitor mv = emitterVisitor.ctx.mv;
// Note: The call context is NOT stored in a local variable slot.
// pushCallContext() emits either a compile-time constant (LDC) or loads the
// callContext method parameter (ILOAD 2). Both are side-effect-free and can be
// re-emitted at the exact moment the value is needed on the JVM operand stack,
// so there is no need to stash the int in a slot.
//
// Storing it in a slot would be WRONG: the pre-initialisation loop in
// EmitterMethodCreator initialises every temporary slot to null (ACONST_NULL /
// ASTORE) so that reference slots are never in TOP state at merge points.
// An int slot initialised that way acquires the reference type "null" from the
// pre-init path. At a merge point (e.g. blockDispatcher) that is reachable from
// both a path that executed ISTORE-callContextSlot and a path through a
// conditional branch that skipped it, the JVM verifier sees conflicting types
// (int vs null-reference) and throws VerifyError: "Bad local variable type".
// This VerifyError triggers the interpreter-fallback which re-runs the main
// script body, calling plan() a second time and causing the "tried to plan
// twice" error in DBIx::Class torture.t (perf/reduce-apply-bytecode Phase 2).
String subroutineName = "";
if (node.left instanceof OperatorNode operatorNode && operatorNode.operator.equals("&")) {
if (operatorNode.operand instanceof IdentifierNode identifierNode) {
subroutineName = NameNormalizer.normalizeVariableName(identifierNode.name, emitterVisitor.ctx.symbolTable.getCurrentPackage());
if (CompilerOptions.DEBUG_ENABLED) emitterVisitor.ctx.logDebug("handleApplyElementOperator subroutine " + subroutineName);
}
}
if (node.left instanceof OperatorNode operatorNode
&& operatorNode.operator.equals("&")
&& operatorNode.getAnnotation("parseTimeCodeRef") instanceof RuntimeScalar codeRef) {
int codeRefId = GlobalVariable.registerCompiledCodeRef(codeRef);
mv.visitLdcInsn(codeRefId);
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/GlobalVariable",
"getCompiledCodeRef",
"(I)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;",
false);
} else {
node.left.accept(emitterVisitor.with(RuntimeContextType.SCALAR)); // Target - left parameter: Code ref
}
// Dereference the scalar to get the CODE reference if needed
// When we have &$x() the left side is OperatorNode("$") (the & is consumed by the parser)
// We need to look up the CODE slot from the glob if the scalar contains a string.
// Check if the left side is a scalar variable or a block containing a scalar variable
boolean isScalarVariable = false;
boolean isLexicalSub = false;
OperatorNode scalarOpNode = null;
boolean isBlockDeref = false; // &{expr} syntax - always need to deref for symbolic refs
if (node.left instanceof OperatorNode operatorNode && operatorNode.operator.equals("$")) {
// This is &$var() or $var->() syntax
isScalarVariable = true;
scalarOpNode = operatorNode;
} else if (node.left instanceof BlockNode blockNode) {
// This is &{expr} syntax where expr can be:
// - &{$var} - simple variable
// - &{$hash{key}} - hash element
// - &{$array[idx]} - array element
// - &{some_expression} - any expression
// All of these may return a string that needs to be resolved as a symbolic reference
isBlockDeref = true;
if (blockNode.elements.size() == 1 &&
blockNode.elements.get(0) instanceof OperatorNode opNode &&
opNode.operator.equals("$")) {
// Specific case: &{$var}
isScalarVariable = true;
scalarOpNode = opNode;
}
}
if (isScalarVariable && scalarOpNode != null) {
// Check if the variable is a lexical subroutine (already a CODE reference)
// Lexical subs have a "hiddenVarName" annotation and should not be dereferenced
String hiddenVarName = (String) scalarOpNode.getAnnotation("hiddenVarName");
isLexicalSub = (hiddenVarName != null);
// Only call codeDerefNonStrict when strict refs is disabled AND not a lexical sub
// This allows symbolic references like: my $x = "main::test"; &$x()
if (!isLexicalSub && !emitterVisitor.ctx.symbolTable.isStrictOptionEnabled(HINT_STRICT_REFS)) {
// Without strict refs and not a lexical sub: allow symbolic references
// Call codeDerefNonStrict to look up CODE slot from glob if needed
emitterVisitor.pushCurrentPackage();
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"codeDerefNonStrict",
"(Ljava/lang/String;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;",
false);
}
} else if (isBlockDeref && !emitterVisitor.ctx.symbolTable.isStrictOptionEnabled(HINT_STRICT_REFS)) {
// For &{expr} where expr is not a simple variable (e.g., &{$hash{key}})
// We need to call codeDerefNonStrict to resolve symbolic references
// using the current package
emitterVisitor.pushCurrentPackage();
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/runtime/runtimetypes/RuntimeScalar",
"codeDerefNonStrict",
"(Ljava/lang/String;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;",
false);
}
int codeRefSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot();
boolean pooledCodeRef = codeRefSlot >= 0;
if (!pooledCodeRef) {
codeRefSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable();
}
mv.visitVarInsn(Opcodes.ASTORE, codeRefSlot);
// Special handling for eval blocks: share @_ with enclosing sub directly.
// In Perl 5, eval { } shares @_ with its enclosing sub, so shift/pop inside
// eval { } modifies the caller's @_. We achieve this by passing the caller's
// RuntimeArray directly instead of expanding @_ into a new array.
// Note: use apply() not applyEval() because the eval block's own generated
// method already has try/catch handling (useTryCatch=true). Using applyEval
// would add a second layer that clears $@ after the block returns.
if (node.left instanceof SubroutineNode subNode && subNode.useTryCatch) {
mv.visitVarInsn(Opcodes.ALOAD, codeRefSlot);
mv.visitVarInsn(Opcodes.ALOAD, 1); // caller's @_ (slot 1) - shared, not copied
emitterVisitor.pushCallContext();
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"apply",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;",
false);
if (pooledCodeRef) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
emitTaggedControlFlowHandling(emitterVisitor);
if (emitterVisitor.ctx.contextType == RuntimeContextType.SCALAR
|| emitterVisitor.ctx.contextType == RuntimeContextType.LVALUE) {
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/runtime/runtimetypes/RuntimeList", "scalar",
"()Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
} else if (emitterVisitor.ctx.contextType == RuntimeContextType.VOID) {
mv.visitInsn(Opcodes.POP);
}
return;
}
// Special handling for &func (no parens): share @_ with caller directly.
// In Perl 5, &func without parens shares the caller's @_ by alias,
// so shift/pop inside the callee modifies the caller's @_.
// We achieve this by passing the caller's RuntimeArray (slot 1) directly
// instead of creating a new array from @_ elements.
if (node.getBooleanAnnotation("shareCallerArgs")) {
mv.visitVarInsn(Opcodes.ALOAD, codeRefSlot);
mv.visitVarInsn(Opcodes.ALOAD, 1); // caller's @_ (slot 1) - shared, not copied
emitterVisitor.pushCallContext();
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"apply",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;",
false);
if (pooledCodeRef) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
// Registry-based non-local control flow check (for next/last/redo LABEL from closures)
emitControlFlowCheck(emitterVisitor.ctx);
if (emitterVisitor.ctx.contextType == RuntimeContextType.SCALAR
|| emitterVisitor.ctx.contextType == RuntimeContextType.LVALUE) {
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"org/perlonjava/runtime/runtimetypes/RuntimeList", "scalar",
"()Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
} else if (emitterVisitor.ctx.contextType == RuntimeContextType.VOID) {
mv.visitInsn(Opcodes.POP);
}
return;
}
int nameSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot();
boolean pooledName = nameSlot >= 0;
if (!pooledName) {
nameSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable();
}
mv.visitLdcInsn(subroutineName);
mv.visitVarInsn(Opcodes.ASTORE, nameSlot);
// Generate native RuntimeBase[] array for parameters instead of RuntimeList
ListNode paramList = ListNode.makeList(node.right);
int argCount = paramList.elements.size();
int argsArraySlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot();
boolean pooledArgsArray = argsArraySlot >= 0;
if (!pooledArgsArray) {
argsArraySlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable();
}
if (argCount <= 5) {
mv.visitInsn(Opcodes.ICONST_0 + argCount);
} else if (argCount <= 127) {
mv.visitIntInsn(Opcodes.BIPUSH, argCount);
} else {
mv.visitIntInsn(Opcodes.SIPUSH, argCount);
}
mv.visitTypeInsn(Opcodes.ANEWARRAY, "org/perlonjava/runtime/runtimetypes/RuntimeBase");
mv.visitVarInsn(Opcodes.ASTORE, argsArraySlot);
EmitterVisitor listVisitor = emitterVisitor.with(RuntimeContextType.LIST);
int savedArgumentCallerLineOverride =
emitterVisitor.ctx.javaClassInfo.callerLineTokenOverride;
if (savedArgumentCallerLineOverride <= 0
&& node.left != null && node.left.getIndex() > 0) {
emitterVisitor.ctx.javaClassInfo.callerLineTokenOverride = node.left.getIndex();
}
try {
for (int index = 0; index < argCount; index++) {
int argSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot();
boolean pooledArg = argSlot >= 0;
if (!pooledArg) {
argSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable();
}
paramList.elements.get(index).accept(listVisitor);
mv.visitVarInsn(Opcodes.ASTORE, argSlot);
mv.visitVarInsn(Opcodes.ALOAD, argsArraySlot);
if (index <= 5) {
mv.visitInsn(Opcodes.ICONST_0 + index);
} else if (index <= 127) {
mv.visitIntInsn(Opcodes.BIPUSH, index);
} else {
mv.visitIntInsn(Opcodes.SIPUSH, index);
}
mv.visitVarInsn(Opcodes.ALOAD, argSlot);
mv.visitInsn(Opcodes.AASTORE);
if (pooledArg) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
}
} finally {
emitterVisitor.ctx.javaClassInfo.callerLineTokenOverride =
savedArgumentCallerLineOverride;
}
// Undefined direct-call diagnostics report the line containing the
// function token, while caller() inside a successfully entered sub sees
// the completed call expression's closing line. Keep those as two
// separate bytecode locations.
int errorSiteIndex = node.left != null && node.left.getIndex() > 0
? node.left.getIndex()
: (node.getIndex() > 0 ? node.getIndex() : -1);
if (errorSiteIndex > 0) {
ByteCodeSourceMapper.setDebugInfoLineNumber(emitterVisitor.ctx, errorSiteIndex);
}
mv.visitVarInsn(Opcodes.ALOAD, codeRefSlot);
mv.visitVarInsn(Opcodes.ALOAD, nameSlot);
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"throwIfDirectCallUndefined",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Ljava/lang/String;)V",
false);
// Set debug line number to the call site. Perl reports the expression
// start for ordinary multi-line calls, but literal anon sub/block
// arguments and &-prototype calls report the block/arg line.
Object annotatedCallerLine = node.getAnnotation("callerLineTokenOverride");
int callSiteIndex = annotatedCallerLine instanceof Integer token && token > 0
? token
: (emitterVisitor.ctx.javaClassInfo.callerLineTokenOverride > 0
? emitterVisitor.ctx.javaClassInfo.callerLineTokenOverride
: callerLineCallSiteIndex(node));
if (callSiteIndex > 0) {
ByteCodeSourceMapper.setDebugInfoLineNumber(emitterVisitor.ctx, callSiteIndex);
}
mv.visitVarInsn(Opcodes.ALOAD, codeRefSlot);
mv.visitVarInsn(Opcodes.ALOAD, nameSlot);
mv.visitVarInsn(Opcodes.ALOAD, argsArraySlot);
emitterVisitor.pushCallContext(); // Push call context to stack
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/runtimetypes/RuntimeCode",
"apply",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Ljava/lang/String;[Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;",
false); // Generate an .apply() call
if (pooledArgsArray) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
if (pooledName) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
if (pooledCodeRef) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
// Tagged returns control-flow handling:
// If RuntimeCode.apply() returned a RuntimeControlFlowList marker, handle it here.
if (ENABLE_CONTROL_FLOW_CHECKS
&& emitterVisitor.ctx.javaClassInfo.returnLabel != null
&& emitterVisitor.ctx.javaClassInfo.controlFlowTempSlot >= 0) {
// Get or create a block-level dispatcher for the current loop state
String loopStateSignature = emitterVisitor.ctx.javaClassInfo.getLoopStateSignature();
Label blockDispatcher = emitterVisitor.ctx.javaClassInfo.blockDispatcherLabels.get(loopStateSignature);
boolean isFirstUse = (blockDispatcher == null);
if (isFirstUse) {
blockDispatcher = new Label();
emitterVisitor.ctx.javaClassInfo.blockDispatcherLabels.put(loopStateSignature, blockDispatcher);
}
Label notControlFlow = new Label();
int belowResultStackLevel = 0;
JavaClassInfo.SpillRef[] baseSpills = new JavaClassInfo.SpillRef[0];
// Store result in temp slot
mv.visitVarInsn(Opcodes.ASTORE, emitterVisitor.ctx.javaClassInfo.controlFlowTempSlot);
// If the caller kept values on the JVM operand stack below the call result (e.g. a left operand),