-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBytecodeCompiler.java
More file actions
4887 lines (4317 loc) · 211 KB
/
BytecodeCompiler.java
File metadata and controls
4887 lines (4317 loc) · 211 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.bytecode;
import org.perlonjava.frontend.analysis.RegexUsageDetector;
import org.perlonjava.frontend.analysis.Visitor;
import org.perlonjava.backend.jvm.EmitterMethodCreator;
import org.perlonjava.backend.jvm.EmitterContext;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.runtime.perlmodule.Strict;
import org.perlonjava.runtime.runtimetypes.*;
import org.perlonjava.frontend.semantic.ScopedSymbolTable;
import java.util.*;
/**
* BytecodeCompiler traverses the AST and generates interpreter bytecode.
*
* This is analogous to EmitterVisitor but generates custom bytecode
* for the interpreter instead of JVM bytecode via ASM.
*
* Key responsibilities:
* - Visit AST nodes and emit interpreter opcodes
* - Allocate registers for variables and temporaries
* - Build constant pool and string pool
* - Generate 3-address code (rd = rs1 op rs2)
*/
public class BytecodeCompiler implements Visitor {
// Pre-allocate with reasonable initial capacity to reduce resizing
// Typical small eval/subroutine needs 20-50 bytecodes, 5-10 constants, 3-8 strings
final List<Integer> bytecode = new ArrayList<>(64);
private final List<Object> constants = new ArrayList<>(16);
private final List<String> stringPool = new ArrayList<>(16);
private final Map<String, Integer> stringPoolIndex = new HashMap<>(16); // O(1) lookup
private final Map<Object, Integer> constantPoolIndex = new HashMap<>(16); // O(1) lookup
// Scoped symbol table for variable tracking, package/class tracking, and eval STRING support.
// Replaces the old variableScopes Stack + allDeclaredVariables flat map.
// Using ScopedSymbolTable gives us proper scope-aware variable lookups and
// getAllVisibleVariables()/getVisibleVariableRegistry() for per-eval-site snapshots.
final ScopedSymbolTable symbolTable = new ScopedSymbolTable();
// Scope index stack for proper ScopedSymbolTable.exitScope() calls
private final Stack<Integer> scopeIndices = new Stack<>();
// Stack to save/restore register state when entering/exiting scopes
private final Stack<Integer> savedNextRegister = new Stack<>();
private final Stack<Integer> savedBaseRegister = new Stack<>();
// Loop label stack for last/next/redo control flow
// Each entry tracks loop boundaries and optional label
private final Stack<LoopInfo> loopStack = new Stack<>();
// Helper class to track loop boundaries
private static class LoopInfo {
final String label; // Loop label (null if unlabeled)
final int startPc; // PC for redo (start of loop body)
int continuePc; // PC for next (continue block or increment)
final List<Integer> breakPcs; // PCs to patch for last (break)
final List<Integer> nextPcs; // PCs to patch for next
final List<Integer> redoPcs; // PCs to patch for redo
final boolean isTrueLoop; // True for for/while/foreach; false for do-while/bare blocks
LoopInfo(String label, int startPc, boolean isTrueLoop) {
this.label = label;
this.startPc = startPc;
this.isTrueLoop = isTrueLoop;
this.continuePc = -1; // Will be set later
this.breakPcs = new ArrayList<>();
this.nextPcs = new ArrayList<>();
this.redoPcs = new ArrayList<>();
}
}
// Goto label support: maps label names to their PC addresses for intra-function goto.
// pendingGotos tracks forward references (goto before label) needing patch-up.
final Map<String, Integer> gotoLabelPcs = new HashMap<>();
final List<Object[]> pendingGotos = new ArrayList<>(); // [patchPc(Integer), labelName(String)]
// Token index tracking for error reporting
private final TreeMap<Integer, Integer> pcToTokenIndex = new TreeMap<>();
int currentTokenIndex = -1; // Track current token for error reporting
// Error reporting
final ErrorMessageUtil errorUtil;
// EmitterContext for strict checks and other compile-time options
private EmitterContext emitterContext;
// Register allocation
private int nextRegister = 3; // 0=this, 1=@_, 2=wantarray
private int baseRegisterForStatement = 3; // Reset point after each statement
private int maxRegisterEverUsed = 2; // Track highest register ever allocated
// Track last result register for expression chaining
int lastResultReg = -1;
// Track current calling context for subroutine calls
int currentCallContext = RuntimeContextType.LIST; // Default to LIST
// Closure support
private RuntimeBase[] capturedVars; // Captured variable values
private String[] capturedVarNames; // Parallel array of names
Map<String, Integer> capturedVarIndices; // Name → register index
// Per-eval-site variable registries: each eval STRING emission snapshots the
// currently visible variables so at runtime the correct registers are captured.
final List<Map<String, Integer>> evalSiteRegistries = new ArrayList<>();
// BEGIN support for named subroutine closures
int currentSubroutineBeginId = 0; // BEGIN ID for current named subroutine (0 = not in named sub)
Set<String> currentSubroutineClosureVars = new HashSet<>(); // Variables captured from outer scope
// Source information
final String sourceName;
final int sourceLine;
public BytecodeCompiler(String sourceName, int sourceLine, ErrorMessageUtil errorUtil) {
this.sourceName = sourceName;
this.sourceLine = sourceLine;
this.errorUtil = errorUtil;
// Initialize symbolTable with the 3 reserved registers
symbolTable.addVariableWithIndex("this", 0, "reserved");
symbolTable.addVariableWithIndex("@_", 1, "reserved");
symbolTable.addVariableWithIndex("wantarray", 2, "reserved");
}
// Legacy constructor for backward compatibility
public BytecodeCompiler(String sourceName, int sourceLine) {
this(sourceName, sourceLine, null);
}
/**
* Constructor for eval STRING with parent scope variable registry.
* Initializes symbolTable with variables from parent scope.
*
* @param sourceName Source name for error messages
* @param sourceLine Source line for error messages
* @param errorUtil Error message utility
* @param parentRegistry Variable registry from parent scope (for eval STRING)
*/
public BytecodeCompiler(String sourceName, int sourceLine, ErrorMessageUtil errorUtil,
Map<String, Integer> parentRegistry) {
this.sourceName = sourceName;
this.sourceLine = sourceLine;
this.errorUtil = errorUtil;
// Initialize symbolTable with the 3 reserved registers
symbolTable.addVariableWithIndex("this", 0, "reserved");
symbolTable.addVariableWithIndex("@_", 1, "reserved");
symbolTable.addVariableWithIndex("wantarray", 2, "reserved");
if (parentRegistry != null) {
// Add parent scope variables to symbolTable (for eval STRING variable capture)
for (Map.Entry<String, Integer> entry : parentRegistry.entrySet()) {
String varName = entry.getKey();
int regIndex = entry.getValue();
if (regIndex >= 3) {
symbolTable.addVariableWithIndex(varName, regIndex, "my");
}
}
// Mark parent scope variables as captured so assignments use SET_SCALAR
capturedVarIndices = new HashMap<>();
for (Map.Entry<String, Integer> entry : parentRegistry.entrySet()) {
String varName = entry.getKey();
int regIndex = entry.getValue();
if (regIndex >= 3) {
capturedVarIndices.put(varName, regIndex);
}
}
// Adjust nextRegister to account for captured variables
int maxRegister = 2;
for (Integer regIndex : parentRegistry.values()) {
if (regIndex > maxRegister) {
maxRegister = regIndex;
}
}
this.nextRegister = maxRegister + 1;
this.maxRegisterEverUsed = maxRegister;
this.baseRegisterForStatement = this.nextRegister;
}
}
boolean hasVariable(String name) {
return symbolTable.getVariableIndex(name) != -1;
}
int getVariableRegister(String name) {
return symbolTable.getVariableIndex(name);
}
int addVariable(String name, String declType) {
int reg = allocateRegister();
symbolTable.addVariableWithIndex(name, reg, declType);
return reg;
}
void registerVariable(String name, int reg) {
symbolTable.addVariableWithIndex(name, reg, "my");
}
private void enterScope() {
int scopeIdx = symbolTable.enterScope();
scopeIndices.push(scopeIdx);
savedNextRegister.push(nextRegister);
savedBaseRegister.push(baseRegisterForStatement);
baseRegisterForStatement = nextRegister;
if (emitterContext != null && emitterContext.symbolTable != null) {
ScopedSymbolTable st = emitterContext.symbolTable;
st.strictOptionsStack.push(st.strictOptionsStack.peek());
st.featureFlagsStack.push(st.featureFlagsStack.peek());
st.warningFlagsStack.push((java.util.BitSet) st.warningFlagsStack.peek().clone());
}
}
private void exitScope() {
if (!scopeIndices.isEmpty()) {
symbolTable.exitScope(scopeIndices.pop());
if (!savedNextRegister.isEmpty()) {
nextRegister = savedNextRegister.pop();
}
if (!savedBaseRegister.isEmpty()) {
baseRegisterForStatement = savedBaseRegister.pop();
}
if (emitterContext != null && emitterContext.symbolTable != null) {
ScopedSymbolTable st = emitterContext.symbolTable;
st.strictOptionsStack.pop();
st.featureFlagsStack.pop();
st.warningFlagsStack.pop();
}
}
}
/**
* Helper: Get current package name for global variable resolution.
* Uses symbolTable for proper package/class tracking.
*/
String getCurrentPackage() {
return symbolTable.getCurrentPackage();
}
/**
* Set the compile-time package for name normalization.
* Called by eval STRING handlers to sync the package from the call site,
* so bare names like *named compile to FOO3::named instead of main::named.
*/
public void setCompilePackage(String packageName) {
symbolTable.setCurrentPackage(packageName, false);
}
private String[] getVariableNames() {
return symbolTable.getVariableNames();
}
/**
* Helper: Check if a variable is a built-in special length-one variable.
* Single-character non-letter variables like $_, $0, $!, $; are always allowed under strict.
* Mirrors logic from EmitVariable.java.
*/
private static boolean isBuiltinSpecialLengthOneVar(String sigil, String name) {
if (!"$".equals(sigil) || name == null || name.length() != 1) {
return false;
}
char c = name.charAt(0);
// In Perl, many single-character non-identifier variables (punctuation/digits)
// are built-in special vars and are exempt from strict 'vars'.
return !Character.isLetter(c);
}
/**
* Helper: Check if a variable is a built-in special scalar variable.
* Variables like ${^GLOBAL_PHASE}, $ARGV, $ENV are always allowed under strict.
* Mirrors logic from EmitVariable.java.
*/
private static boolean isBuiltinSpecialScalarVar(String sigil, String name) {
if (!"$".equals(sigil) || name == null || name.isEmpty()) {
return false;
}
// ${^FOO} variables are encoded as a leading ASCII control character.
// (e.g. ${^GLOBAL_PHASE} -> "\aLOBAL_PHASE"). These are built-in and strict-safe.
if (name.charAt(0) < 32) {
return true;
}
return name.equals("ARGV")
|| name.equals("ARGVOUT")
|| name.equals("ENV")
|| name.equals("INC")
|| name.equals("SIG")
|| name.equals("STDIN")
|| name.equals("STDOUT")
|| name.equals("STDERR");
}
/**
* Helper: Check if a variable is a built-in special container variable.
* Variables like %ENV, @ARGV, @INC are always allowed under strict.
* Mirrors logic from EmitVariable.java.
*/
private static boolean isBuiltinSpecialContainerVar(String sigil, String name) {
if (name == null) {
return false;
}
if ("%".equals(sigil)) {
return name.equals("SIG")
|| name.equals("ENV")
|| name.equals("INC")
|| name.equals("+")
|| name.equals("-");
}
if ("@".equals(sigil)) {
return name.equals("ARGV")
|| name.equals("INC")
|| name.equals("_")
|| name.equals("F");
}
return false;
}
/**
* Helper: Check if a non-ASCII length-1 scalar is allowed under 'no utf8'.
* Under 'no utf8', Latin-1 characters (0x80-0xFF) in single-char variable names
* are treated as special and exempt from strict vars checking.
* Mirrors logic from EmitVariable.java lines 82-88.
*
* @param sigil The variable sigil
* @param name The bare variable name (without sigil)
* @return true if this is a non-ASCII length-1 scalar allowed under 'no utf8'
*/
private boolean isNonAsciiLengthOneScalarAllowedUnderNoUtf8(String sigil, String name) {
if (!"$".equals(sigil) || name == null || name.length() != 1) {
return false;
}
char c = name.charAt(0);
// Allow if character > 127 (Latin-1) and 'use utf8' is NOT enabled
return c > 127 && emitterContext != null && emitterContext.symbolTable != null
&& !emitterContext.symbolTable.isStrictOptionEnabled(Strict.HINT_UTF8);
}
/**
* Helper: Check if strict vars should block access to this global variable.
* Returns true if the variable should be BLOCKED (not allowed).
* Mirrors the createIfNotExists logic from EmitVariable.java lines 362-371.
*
* @param varName The variable name with sigil (e.g., "$A", "@array")
* @return true if access should be blocked under strict vars
*/
/** Returns true if strict refs is currently enabled in the symbol table. */
boolean isStrictRefsEnabled() {
return emitterContext != null && emitterContext.symbolTable != null
&& emitterContext.symbolTable.isStrictOptionEnabled(Strict.HINT_STRICT_REFS);
}
boolean isIntegerEnabled() {
return emitterContext != null && emitterContext.symbolTable != null
&& emitterContext.symbolTable.isStrictOptionEnabled(Strict.HINT_INTEGER);
}
boolean shouldBlockGlobalUnderStrictVars(String varName) {
// Only check if strict vars is enabled
if (emitterContext == null || emitterContext.symbolTable == null) {
return false; // No context, allow access
}
boolean strictEnabled = emitterContext.symbolTable.isStrictOptionEnabled(Strict.HINT_STRICT_VARS);
if (!strictEnabled) {
return false; // Strict vars not enabled, allow access
}
// Extract sigil and bare name
String sigil = varName.substring(0, 1);
String bareVarName = varName.substring(1);
// Allow qualified names (contain ::)
if (bareVarName.contains("::")) {
return false;
}
// Allow regex capture variables ($1, $2, etc.)
if (ScalarUtils.isInteger(bareVarName)) {
return false;
}
// Allow special sort variables $a and $b
if (sigil.equals("$") && (bareVarName.equals("a") || bareVarName.equals("b"))) {
return false;
}
// Allow built-in special variables
if (isBuiltinSpecialLengthOneVar(sigil, bareVarName)) {
return false;
}
if (isBuiltinSpecialScalarVar(sigil, bareVarName)) {
return false;
}
if (isBuiltinSpecialContainerVar(sigil, bareVarName)) {
return false;
}
// Allow non-ASCII length-1 scalars under 'no utf8'
// e.g., $ª, $µ, $º under 'no utf8' are treated as special variables
if (isNonAsciiLengthOneScalarAllowedUnderNoUtf8(sigil, bareVarName)) {
return false;
}
// BLOCK: Unqualified variable under strict vars
return true;
}
/**
* Throw a compiler exception with proper error formatting.
* Uses PerlCompilerException which formats with line numbers and code context.
*
* @param message The error message
* @param tokenIndex The token index where the error occurred
*/
void throwCompilerException(String message, int tokenIndex) {
if (errorUtil != null && tokenIndex >= 0) {
throw new PerlCompilerException(tokenIndex, message, errorUtil);
} else {
// Fallback to simple error (no context available)
throw new RuntimeException(message);
}
}
/**
* Throw a compiler exception using the current token index.
*
* @param message The error message
*/
void throwCompilerException(String message) {
throwCompilerException(message, currentTokenIndex);
}
/**
* Compile an AST node to InterpretedCode.
*
* @param node The AST node to compile
* @return InterpretedCode ready for execution
*/
public InterpretedCode compile(Node node) {
return compile(node, null);
}
/**
* Compile an AST node to InterpretedCode with optional closure support.
*
* @param node The AST node to compile
* @param ctx EmitterContext for closure detection (may be null)
* @return InterpretedCode ready for execution
*/
public InterpretedCode compile(Node node, EmitterContext ctx) {
// Store context for strict checks and other compile-time options
this.emitterContext = ctx;
// Detect closure variables if context is provided
if (ctx != null) {
detectClosureVariables(node, ctx);
// Use the calling context from EmitterContext for top-level expressions
// This is crucial for eval STRING to propagate context correctly
currentCallContext = ctx.contextType;
// Inherit package from the JVM compiler context so that eval STRING
// compiles unqualified names in the caller's package, not "main".
// This is compile-time package propagation — it sets the symbol table's
// current package so the parser/emitter qualify names correctly.
// Note: the *runtime* package (InterpreterState.currentPackage) is a
// separate concern used only by caller(); it must be scoped via
// DynamicVariableManager around eval execution to prevent leaking.
// See InterpreterState.currentPackage javadoc for details.
if (ctx.symbolTable != null) {
symbolTable.setCurrentPackage(ctx.symbolTable.getCurrentPackage(),
ctx.symbolTable.currentPackageIsClass());
}
}
// If we have captured variables, allocate registers for them
// BUT: If we were constructed with a parentRegistry (for eval STRING),
// nextRegister is already correctly set by the constructor.
// Only reset it if we have runtime capturedVars but no parentRegistry.
if (capturedVars != null && capturedVars.length > 0 && capturedVarIndices == null) {
// Registers 0-2 are reserved (this, @_, wantarray)
// Registers 3+ are captured variables
nextRegister = 3 + capturedVars.length;
}
// Visit the node to generate bytecode
node.accept(this);
// Emit RETURN with last result register
// If no result was produced, return undef instead of register 0 ("this")
int returnReg;
if (lastResultReg >= 0) {
returnReg = lastResultReg;
} else {
// No result - allocate register for undef
returnReg = allocateRegister();
emit(Opcodes.LOAD_UNDEF);
emitReg(returnReg);
}
emit(Opcodes.RETURN);
emitReg(returnReg);
// Build variable registry for eval STRING support.
// At this point all inner scopes have exited, so getVisibleVariableRegistry()
// returns only the outermost scope variables. Per-eval-site registries
// (stored in evalSiteRegistries) provide the correct scope-aware mappings.
Map<String, Integer> variableRegistry = symbolTable.getVisibleVariableRegistry();
// Extract strict/feature/warning flags for eval STRING inheritance
int strictOptions = 0;
int featureFlags = 0;
BitSet warningFlags = new BitSet();
if (emitterContext != null && emitterContext.symbolTable != null) {
strictOptions = emitterContext.symbolTable.strictOptionsStack.peek();
featureFlags = emitterContext.symbolTable.featureFlagsStack.peek();
warningFlags = (BitSet) emitterContext.symbolTable.warningFlagsStack.peek().clone();
}
// Build InterpretedCode
return new InterpretedCode(
toShortArray(),
constants.toArray(),
stringPool.toArray(new String[0]),
maxRegisterEverUsed + 1,
capturedVars,
sourceName,
sourceLine,
pcToTokenIndex,
variableRegistry,
errorUtil,
strictOptions,
featureFlags,
warningFlags,
symbolTable.getCurrentPackage(),
evalSiteRegistries.isEmpty() ? null : evalSiteRegistries
);
}
// =========================================================================
// CLOSURE DETECTION
// =========================================================================
/**
* Detect closure variables: variables referenced but not declared locally.
* Populates capturedVars, capturedVarNames, and capturedVarIndices.
*
* @param ast AST to scan for variable references
* @param ctx EmitterContext containing symbol table and eval context
*/
private void detectClosureVariables(Node ast, EmitterContext ctx) {
if (capturedVarIndices != null) {
return;
}
if (ctx == null || ctx.symbolTable == null) {
return;
}
// Use getAllVisibleVariables() (TreeMap sorted by register index) with the same
// filtering as SubroutineParser to ensure capturedVars ordering matches exactly.
Map<Integer, org.perlonjava.frontend.semantic.SymbolTable.SymbolEntry> outerVars =
ctx.symbolTable.getAllVisibleVariables();
int skipVariables = org.perlonjava.backend.jvm.EmitterMethodCreator.skipVariables;
List<String> outerVarNames = new ArrayList<>();
List<RuntimeBase> outerValues = new ArrayList<>();
capturedVarIndices = new HashMap<>();
int reg = 3;
for (Map.Entry<Integer, org.perlonjava.frontend.semantic.SymbolTable.SymbolEntry> e :
outerVars.entrySet()) {
if (e.getKey() < skipVariables) continue;
org.perlonjava.frontend.semantic.SymbolTable.SymbolEntry entry = e.getValue();
String name = entry.name();
// Match SubroutineParser filters: skip @_, empty decl, fields, code refs
if (name.equals("@_")) continue;
if (entry.decl().isEmpty()) continue;
if (entry.decl().equals("field")) continue;
if (name.startsWith("&")) continue;
capturedVarIndices.put(name, reg);
outerVarNames.add(name);
outerValues.add(getVariableValueFromContext(name, ctx));
reg++;
}
// Register captured variables in the compiler's symbol table so that
// all existing hasVariable()/getVariableRegister() lookups find them.
// This is critical for handleHashElementAccess, handleArrayElementAccess, etc.
for (int i = 0; i < outerVarNames.size(); i++) {
symbolTable.addVariableWithIndex(outerVarNames.get(i), 3 + i, "my");
}
// Reserve registers for captured variables so local my declarations don't collide
nextRegister = reg;
maxRegisterEverUsed = Math.max(maxRegisterEverUsed, nextRegister - 1);
baseRegisterForStatement = nextRegister;
// Also scan AST for referenced variables and add them to capturedVarIndices.
// This prevents aggressive register recycling (getHighestVariableRegister uses this).
Set<String> referencedVars = collectReferencedVariables(ast);
Set<String> localVars = getLocalVariableNames(ctx);
referencedVars.removeAll(localVars);
referencedVars.removeIf(name ->
name.equals("$_") || name.equals("$@") || name.equals("$!")
);
for (String varName : referencedVars) {
if (!capturedVarIndices.containsKey(varName)) {
capturedVarIndices.put(varName, reg++);
}
}
if (outerVarNames.isEmpty() && capturedVarIndices.isEmpty()) {
capturedVarIndices = null;
return;
}
capturedVarNames = outerVarNames.toArray(new String[0]);
capturedVars = outerValues.toArray(new RuntimeBase[0]);
}
/**
* Collect all variable references in AST.
*
* @param ast AST node to scan
* @return Set of variable names (with sigils)
*/
private Set<String> collectReferencedVariables(Node ast) {
Set<String> refs = new HashSet<>();
ast.accept(new VariableCollectorVisitor(refs));
return refs;
}
/**
* Get local variable names from current scope (not parent scopes).
*
* @param ctx EmitterContext containing symbol table
* @return Set of local variable names
*/
private Set<String> getLocalVariableNames(EmitterContext ctx) {
Set<String> locals = new HashSet<>();
// Collect variables from all scopes
String[] varNames = getVariableNames();
for (String name : varNames) {
// Skip the 3 reserved registers (this, @_, wantarray)
if (!name.equals("this") && !name.equals("@_") && !name.equals("wantarray")) {
locals.add(name);
}
}
return locals;
}
/**
* Get variable value from eval runtime context for closure capture.
*
* @param varName Variable name (with sigil)
* @param ctx EmitterContext containing eval tag
* @return RuntimeBase value to capture
*/
private RuntimeBase getVariableValueFromContext(String varName, EmitterContext ctx) {
// For eval STRING, runtime values are available via evalRuntimeContext ThreadLocal
RuntimeCode.EvalRuntimeContext evalCtx = RuntimeCode.getEvalRuntimeContext();
if (evalCtx != null && evalCtx.runtimeValues != null) {
// Find variable in captured environment
String[] capturedEnv = evalCtx.capturedEnv;
Object[] runtimeValues = evalCtx.runtimeValues;
for (int i = 0; i < capturedEnv.length; i++) {
if (capturedEnv[i].equals(varName)) {
Object value = runtimeValues[i];
if (value instanceof RuntimeBase) {
return (RuntimeBase) value;
}
}
}
}
// If we can't find a runtime value, return a placeholder
// This is OK - closures are typically created at runtime via eval
return new RuntimeScalar();
}
// =========================================================================
// VISITOR METHODS
// =========================================================================
/**
* Compiles a block node, creating a new lexical scope.
*
* <p>Special case: the parser wraps implicit-{@code $_} foreach loops as
* {@code BlockNode([local $_, For1Node(needsArrayOfAlias=true)])}.
* In that pattern the {@code local $_} child is skipped here because
* {@link #visit(For1Node)} emits {@code LOCAL_SCALAR_SAVE_LEVEL} itself,
* which atomically saves the pre-push dynamic level and calls {@code makeLocal}.
* This allows {@code POP_LOCAL_LEVEL} after the loop to restore {@code $_}
* correctly regardless of nesting depth.
*/
@Override
public void visit(BlockNode node) {
// Blocks create a new lexical scope
// But if the block needs to return a value (not VOID context),
// allocate a result register BEFORE entering the scope so it's valid after
int outerResultReg = -1;
if (currentCallContext != RuntimeContextType.VOID) {
outerResultReg = allocateRegister();
}
// Detect the BlockNode([local $_, For1Node(needsArrayOfAlias)]) pattern produced
// by the parser for implicit-$_ foreach loops. For1Node emits LOCAL_SCALAR_SAVE_LEVEL
// itself, so the 'local $_' child must be skipped here to avoid double-emission.
// Using a local variable (not a field) makes this safe against nesting and exceptions.
boolean skipFirstChild = node.elements.size() == 2
&& node.elements.get(1) instanceof For1Node for1
&& for1.needsArrayOfAlias
&& node.elements.get(0) instanceof OperatorNode localOp
&& localOp.operator.equals("local");
// If the first statement is a scoped package (package Foo { }),
// save the DynamicVariableManager level before the block body so PUSH_PACKAGE is restored.
int scopedPackageLevelReg = -1;
if (!node.elements.isEmpty()
&& node.elements.get(0) instanceof OperatorNode firstOp
&& (firstOp.operator.equals("package") || firstOp.operator.equals("class"))
&& Boolean.TRUE.equals(firstOp.getAnnotation("isScoped"))) {
scopedPackageLevelReg = allocateRegister();
emit(Opcodes.GET_LOCAL_LEVEL);
emitReg(scopedPackageLevelReg);
}
enterScope();
int regexSaveReg = -1;
if (!node.getBooleanAnnotation("blockIsSubroutine")
&& RegexUsageDetector.containsRegexOperation(node)) {
regexSaveReg = allocateRegister();
emit(Opcodes.SAVE_REGEX_STATE);
emitReg(regexSaveReg);
}
// Visit each statement in the block
int numStatements = node.elements.size();
int lastMeaningfulIndex = -1;
for (int i = numStatements - 1; i >= 0; i--) {
Node elem = node.elements.get(i);
if (elem == null) continue;
if (elem instanceof ListNode ln && ln.elements.isEmpty()) continue;
if (elem instanceof AbstractNode an && an.getBooleanAnnotation("compileTimeOnly")) continue;
lastMeaningfulIndex = i;
break;
}
if (lastMeaningfulIndex == -1) lastMeaningfulIndex = numStatements - 1;
for (int i = 0; i < numStatements; i++) {
// Skip the 'local $_' child when For1Node handles it via LOCAL_SCALAR_SAVE_LEVEL
if (i == 0 && skipFirstChild) continue;
Node stmt = node.elements.get(i);
if (stmt instanceof AbstractNode an && an.getBooleanAnnotation("compileTimeOnly")) continue;
// Track line number for this statement (like codegen's setDebugInfoLineNumber)
if (stmt != null) {
int tokenIndex = stmt.getIndex();
int pc = bytecode.size();
pcToTokenIndex.put(pc, tokenIndex);
}
// Standalone statements (not assignments) use VOID context
int savedContext = currentCallContext;
// If this is not an assignment or other value-using construct, use VOID context
// EXCEPT for the last statement in a block, which should use the block's context
boolean isLastStatement = (i == lastMeaningfulIndex);
if (!isLastStatement && !(stmt instanceof BinaryOperatorNode && ((BinaryOperatorNode) stmt).operator.equals("="))) {
currentCallContext = RuntimeContextType.VOID;
}
stmt.accept(this);
currentCallContext = savedContext;
// Recycle temporary registers after each statement
// enterScope() protects registers allocated before entering a scope
recycleTemporaryRegisters();
}
// Save the last statement's result to the outer register BEFORE exiting scope
if (outerResultReg >= 0 && lastResultReg >= 0) {
emit(Opcodes.ALIAS);
emitReg(outerResultReg);
emitReg(lastResultReg);
}
if (regexSaveReg >= 0) {
emit(Opcodes.RESTORE_REGEX_STATE);
emitReg(regexSaveReg);
}
// Exit scope restores register state
exitScope();
// Restore DynamicVariableManager level after scoped package block
// (undoes PUSH_PACKAGE emitted by the package operator inside the block)
if (scopedPackageLevelReg >= 0) {
emit(Opcodes.POP_LOCAL_LEVEL);
emitReg(scopedPackageLevelReg);
}
// Set lastResultReg to the outer register (or -1 if VOID context)
lastResultReg = outerResultReg;
}
@Override
public void visit(NumberNode node) {
// Handle number literals with proper Perl semantics
int rd = allocateRegister();
// Remove underscores which Perl allows as digit separators (e.g., 10_000_000)
String value = node.value.replace("_", "");
try {
// Use ScalarUtils.isInteger() for consistent number parsing with compiler
boolean isInteger = ScalarUtils.isInteger(value);
// For 32-bit Perl emulation, check if this is a large integer
// that needs to be stored as a string to preserve precision
boolean isLargeInteger = !isInteger && value.matches("^-?\\d+$");
if (isInteger) {
// Regular integer - use LOAD_INT to create mutable scalar
// Note: We don't use RuntimeScalarCache here because ALIAS just copies references,
// and we need mutable scalars for variables (++, --, etc.)
int intValue = Integer.parseInt(value);
emit(Opcodes.LOAD_INT);
emitReg(rd);
emitInt(intValue);
} else if (isLargeInteger) {
// Large integer - store as string to preserve precision (32-bit Perl emulation)
int strIdx = addToStringPool(value);
emit(Opcodes.LOAD_STRING);
emitReg(rd);
emit(strIdx);
} else {
// Floating-point number - create RuntimeScalar with double value
RuntimeScalar doubleScalar = new RuntimeScalar(Double.parseDouble(value));
int constIdx = addToConstantPool(doubleScalar);
emit(Opcodes.LOAD_CONST);
emitReg(rd);
emit(constIdx);
}
} catch (NumberFormatException e) {
throw new RuntimeException("Invalid number: " + node.value, e);
}
lastResultReg = rd;
}
void handleArrayKeyValueSlice(BinaryOperatorNode node, OperatorNode leftOp) {
int arrayReg;
// Index/value slice: %array[indices] returns alternating index/value pairs.
// Postfix ->%[...] is parsed into this form by the parser.
if (leftOp.operand instanceof IdentifierNode) {
String varName = "@" + ((IdentifierNode) leftOp.operand).name;
if (hasVariable(varName)) {
arrayReg = getVariableRegister(varName);
} else {
arrayReg = allocateRegister();
String globalArrayName = NameNormalizer.normalizeVariableName(((IdentifierNode) leftOp.operand).name, getCurrentPackage());
int nameIdx = addToStringPool(globalArrayName);
emit(Opcodes.LOAD_GLOBAL_ARRAY);
emitReg(arrayReg);
emit(nameIdx);
}
} else {
// %$arrayref[...] / %{expr}[...] / $aref->%[...] / ['a'..'z']->%[...]
leftOp.operand.accept(this);
int scalarRefReg = lastResultReg;
arrayReg = allocateRegister();
if (isStrictRefsEnabled()) {
emitWithToken(Opcodes.DEREF_ARRAY, node.getIndex());
emitReg(arrayReg);
emitReg(scalarRefReg);
} else {
int pkgIdx = addToStringPool(getCurrentPackage());
emitWithToken(Opcodes.DEREF_ARRAY_NONSTRICT, node.getIndex());
emitReg(arrayReg);
emitReg(scalarRefReg);
emit(pkgIdx);
}
}
if (!(node.right instanceof ArrayLiteralNode indicesNode)) {
throwCompilerException("Index/value slice requires ArrayLiteralNode");
return;
}
if (indicesNode.elements.isEmpty()) {
throwCompilerException("Index/value slice requires at least one index");
return;
}
// Compile indices into a list
List<Integer> pairRegs = new ArrayList<>();
for (Node indexElement : indicesNode.elements) {
indexElement.accept(this);
int indexReg = lastResultReg;
int valueReg = allocateRegister();
emit(Opcodes.ARRAY_GET);
emitReg(valueReg);
emitReg(arrayReg);
emitReg(indexReg);
pairRegs.add(indexReg);
pairRegs.add(valueReg);
}
int listReg = allocateRegister();
emit(Opcodes.CREATE_LIST);
emitReg(listReg);
emit(pairRegs.size());
for (int r : pairRegs) {
emitReg(r);
}
if (currentCallContext == RuntimeContextType.SCALAR) {
int rd = allocateRegister();
emit(Opcodes.LIST_TO_SCALAR);
emitReg(rd);
emitReg(listReg);
lastResultReg = rd;
} else {
lastResultReg = listReg;
}
}
@Override
public void visit(StringNode node) {
// Emit LOAD_STRING or LOAD_VSTRING depending on whether this is a v-string literal.
// LOAD_VSTRING sets type=VSTRING so that ModuleOperators.require() recognises version strings.
int rd = allocateRegister();
int strIndex = addToStringPool(node.value);
emit(node.isVString ? Opcodes.LOAD_VSTRING : Opcodes.LOAD_STRING);
emitReg(rd);
emit(strIndex);
lastResultReg = rd;
}
@Override
public void visit(IdentifierNode node) {
// Variable reference
String varName = node.name;
// Check if this is a captured variable (with sigil)
// Try common sigils: $, @, %
String[] sigils = {"$", "@", "%"};
for (String sigil : sigils) {
String varNameWithSigil = sigil + varName;
if (capturedVarIndices != null && capturedVarIndices.containsKey(varNameWithSigil)) {
// Captured variable - use its pre-allocated register
lastResultReg = capturedVarIndices.get(varNameWithSigil);
return;
}
}
// Check if it's a lexical variable (may have sigil or not)
if (hasVariable(varName)) {
// Lexical variable - already has a register
lastResultReg = getVariableRegister(varName);
} else {
// Try with sigils
boolean found = false;
for (String sigil : sigils) {
String varNameWithSigil = sigil + varName;
if (hasVariable(varNameWithSigil)) {
lastResultReg = getVariableRegister(varNameWithSigil);
found = true;
break;
}
}
if (!found) {
// Not a lexical variable - could be a global or a bareword
// Check for strict subs violation (bareword without sigil)
if (!varName.startsWith("$") && !varName.startsWith("@") && !varName.startsWith("%")) {
// This is a bareword (no sigil)
if (emitterContext != null && emitterContext.symbolTable != null &&
emitterContext.symbolTable.isStrictOptionEnabled(Strict.HINT_STRICT_SUBS)) {
throwCompilerException("Bareword \"" + varName + "\" not allowed while \"strict subs\" in use");
}
// Not strict - treat bareword as string literal
int rd = allocateRegister();
emit(Opcodes.LOAD_STRING);
emitReg(rd);
int strIdx = addToStringPool(varName);
emit(strIdx);