-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBytecodeCompiler.java
More file actions
2812 lines (2407 loc) · 109 KB
/
BytecodeCompiler.java
File metadata and controls
2812 lines (2407 loc) · 109 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.interpreter;
import org.perlonjava.astnode.*;
import org.perlonjava.astvisitor.Visitor;
import org.perlonjava.codegen.EmitterContext;
import org.perlonjava.lexer.LexerToken;
import org.perlonjava.runtime.*;
import org.perlonjava.symbols.ScopedSymbolTable;
import org.perlonjava.symbols.SymbolTable;
import java.io.ByteArrayOutputStream;
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 {
private final ByteArrayOutputStream bytecode = new ByteArrayOutputStream();
private final List<Object> constants = new ArrayList<>();
private final List<String> stringPool = new ArrayList<>();
// Simple variable-to-register mapping for the interpreter
// Each scope is a Map<String, Integer> mapping variable names to register indices
private final Stack<Map<String, Integer>> variableScopes = new Stack<>();
// Track current package name (for global variables)
private String currentPackage = "main";
// Token index tracking for error reporting
private final Map<Integer, Integer> pcToTokenIndex = new HashMap<>();
private int currentTokenIndex = -1; // Track current token for error reporting
// Error reporting
private final ErrorMessageUtil errorUtil;
// Register allocation
private int nextRegister = 3; // 0=this, 1=@_, 2=wantarray
// Track last result register for expression chaining
private int lastResultReg = -1;
// Track current calling context for subroutine calls
private int currentCallContext = RuntimeContextType.LIST; // Default to LIST
// Closure support
private RuntimeBase[] capturedVars; // Captured variable values
private String[] capturedVarNames; // Parallel array of names
private Map<String, Integer> capturedVarIndices; // Name → register index
// Source information
private final String sourceName;
private final int sourceLine;
public BytecodeCompiler(String sourceName, int sourceLine, ErrorMessageUtil errorUtil) {
this.sourceName = sourceName;
this.sourceLine = sourceLine;
this.errorUtil = errorUtil;
// Initialize with global scope containing the 3 reserved registers
Map<String, Integer> globalScope = new HashMap<>();
globalScope.put("this", 0);
globalScope.put("@_", 1);
globalScope.put("wantarray", 2);
variableScopes.push(globalScope);
}
// 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 variableScopes 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 with global scope containing the 3 reserved registers
// plus any variables from parent scope (for eval STRING)
Map<String, Integer> globalScope = new HashMap<>();
globalScope.put("this", 0);
globalScope.put("@_", 1);
globalScope.put("wantarray", 2);
if (parentRegistry != null) {
// Add parent scope variables (for eval STRING variable capture)
globalScope.putAll(parentRegistry);
// 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();
// Skip reserved registers
if (regIndex >= 3) {
capturedVarIndices.put(varName, regIndex);
}
}
// Adjust nextRegister to account for captured variables
// Find the maximum register index used by parent scope
int maxRegister = 2; // Start with reserved registers (0-2)
for (Integer regIndex : parentRegistry.values()) {
if (regIndex > maxRegister) {
maxRegister = regIndex;
}
}
// Next available register is one past the maximum used
this.nextRegister = maxRegister + 1;
}
variableScopes.push(globalScope);
}
/**
* Helper: Check if a variable exists in any scope.
*/
private boolean hasVariable(String name) {
for (int i = variableScopes.size() - 1; i >= 0; i--) {
if (variableScopes.get(i).containsKey(name)) {
return true;
}
}
return false;
}
/**
* Helper: Get the register index for a variable.
* Returns -1 if not found.
*/
private int getVariableRegister(String name) {
for (int i = variableScopes.size() - 1; i >= 0; i--) {
Integer reg = variableScopes.get(i).get(name);
if (reg != null) {
return reg;
}
}
return -1;
}
/**
* Helper: Add a variable to the current scope and return its register index.
* Allocates a new register.
*/
private int addVariable(String name, String declType) {
int reg = allocateRegister();
variableScopes.peek().put(name, reg);
return reg;
}
/**
* Helper: Enter a new lexical scope.
*/
private void enterScope() {
variableScopes.push(new HashMap<>());
}
/**
* Helper: Exit the current lexical scope.
*/
private void exitScope() {
if (variableScopes.size() > 1) {
variableScopes.pop();
}
}
/**
* Helper: Get current package name for global variable resolution.
*/
private String getCurrentPackage() {
return currentPackage;
}
/**
* Helper: Get all variable names in all scopes (for closure detection).
*/
private String[] getVariableNames() {
Set<String> allVars = new HashSet<>();
for (Map<String, Integer> scope : variableScopes) {
allVars.addAll(scope.keySet());
}
return allVars.toArray(new String[0]);
}
/**
* 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
*/
private 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
*/
private 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) {
// Detect closure variables if context is provided
if (ctx != null) {
detectClosureVariables(node, ctx);
}
// If we have captured variables, allocate registers for them
if (capturedVars != null && capturedVars.length > 0) {
// 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 (or register 0 for empty)
emit(Opcodes.RETURN);
emit(lastResultReg >= 0 ? lastResultReg : 0);
// Build variable registry for eval STRING support
// This maps variable names to their register indices for variable capture
Map<String, Integer> variableRegistry = new HashMap<>();
for (Map<String, Integer> scope : variableScopes) {
variableRegistry.putAll(scope);
}
// Build InterpretedCode
return new InterpretedCode(
bytecode.toByteArray(),
constants.toArray(),
stringPool.toArray(new String[0]),
nextRegister, // maxRegisters
capturedVars, // NOW POPULATED!
sourceName,
sourceLine,
pcToTokenIndex, // Pass token index map for error reporting
variableRegistry // Variable registry for eval STRING
);
}
// =========================================================================
// 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) {
// Step 1: Collect all variable references in AST
Set<String> referencedVars = collectReferencedVariables(ast);
// Step 2: Get local variable declarations from symbol table
Set<String> localVars = getLocalVariableNames(ctx);
// Step 3: Closure vars = referenced - local
Set<String> closureVarNames = new HashSet<>(referencedVars);
closureVarNames.removeAll(localVars);
// Remove special variables that don't need capture (they're globals)
closureVarNames.removeIf(name ->
name.equals("$_") || name.equals("$@") || name.equals("$!")
);
if (closureVarNames.isEmpty()) {
return; // No closure vars
}
// Step 4: Build arrays
capturedVarNames = closureVarNames.toArray(new String[0]);
capturedVarIndices = new HashMap<>();
List<RuntimeBase> values = new ArrayList<>();
for (int i = 0; i < capturedVarNames.length; i++) {
String varName = capturedVarNames[i];
capturedVarIndices.put(varName, 3 + i); // Registers 3+
// Get variable value from eval runtime context
RuntimeBase value = getVariableValueFromContext(varName, ctx);
values.add(value);
}
capturedVars = values.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
// =========================================================================
@Override
public void visit(BlockNode node) {
// Visit each statement in the block
for (Node stmt : node.elements) {
// Standalone statements (not assignments) use VOID context
int savedContext = currentCallContext;
// If this is not an assignment or other value-using construct, use VOID context
if (!(stmt instanceof BinaryOperatorNode && ((BinaryOperatorNode) stmt).operator.equals("="))) {
currentCallContext = RuntimeContextType.VOID;
}
stmt.accept(this);
currentCallContext = savedContext;
}
}
@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 = org.perlonjava.runtime.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 MOVE just copies references,
// and we need mutable scalars for variables (++, --, etc.)
int intValue = Integer.parseInt(value);
emit(Opcodes.LOAD_INT);
emit(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);
emit(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);
emit(rd);
emit(constIdx);
}
} catch (NumberFormatException e) {
throw new RuntimeException("Invalid number: " + node.value, e);
}
lastResultReg = rd;
}
@Override
public void visit(StringNode node) {
// Emit LOAD_STRING: rd = new RuntimeScalar(stringPool[index])
int rd = allocateRegister();
int strIndex = addToStringPool(node.value);
emit(Opcodes.LOAD_STRING);
emit(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) {
// Global variable
int rd = allocateRegister();
int nameIdx = addToStringPool(varName);
emit(Opcodes.LOAD_GLOBAL_SCALAR);
emit(rd);
emit(nameIdx);
lastResultReg = rd;
}
}
}
@Override
public void visit(BinaryOperatorNode node) {
// Track token index for error reporting
currentTokenIndex = node.getIndex();
// Handle print/say early (special handling for filehandle)
if (node.operator.equals("print") || node.operator.equals("say")) {
// print/say FILEHANDLE LIST
// left = filehandle reference (\*STDERR)
// right = list to print
// Compile the filehandle (left operand)
node.left.accept(this);
int filehandleReg = lastResultReg;
// Compile the content (right operand)
node.right.accept(this);
int contentReg = lastResultReg;
// Emit PRINT or SAY with both registers
emit(node.operator.equals("say") ? Opcodes.SAY : Opcodes.PRINT);
emit(contentReg);
emit(filehandleReg);
// print/say return 1 on success
int rd = allocateRegister();
emit(Opcodes.LOAD_INT);
emit(rd);
emitInt(1);
lastResultReg = rd;
return;
}
// Handle assignment separately (doesn't follow standard left-right-op pattern)
if (node.operator.equals("=")) {
// Determine the calling context for the RHS based on LHS type
int rhsContext = RuntimeContextType.LIST; // Default
// Check if LHS is a scalar assignment (my $x = ...)
if (node.left instanceof OperatorNode) {
OperatorNode leftOp = (OperatorNode) node.left;
if (leftOp.operator.equals("my") && leftOp.operand instanceof OperatorNode) {
OperatorNode sigilOp = (OperatorNode) leftOp.operand;
if (sigilOp.operator.equals("$")) {
// Scalar assignment: use SCALAR context for RHS
rhsContext = RuntimeContextType.SCALAR;
}
} else if (leftOp.operator.equals("$")) {
// Regular scalar assignment: $x = ...
rhsContext = RuntimeContextType.SCALAR;
}
}
// Set the context for subroutine calls in RHS
int savedContext = currentCallContext;
currentCallContext = rhsContext;
// Special case: my $x = value
if (node.left instanceof OperatorNode) {
OperatorNode leftOp = (OperatorNode) node.left;
if (leftOp.operator.equals("my")) {
// Extract variable name from "my" operand
Node myOperand = leftOp.operand;
// Handle my $x (where $x is OperatorNode("$", IdentifierNode("x")))
if (myOperand instanceof OperatorNode) {
OperatorNode sigilOp = (OperatorNode) myOperand;
if (sigilOp.operator.equals("$") && sigilOp.operand instanceof IdentifierNode) {
String varName = "$" + ((IdentifierNode) sigilOp.operand).name;
// Check if this variable is captured by named subs (Parser marks with id)
if (sigilOp.id != 0) {
// RETRIEVE the persistent variable (creates if doesn't exist)
int beginId = sigilOp.id;
int nameIdx = addToStringPool(varName);
int reg = allocateRegister();
emitWithToken(Opcodes.SLOW_OP, node.getIndex());
emit(Opcodes.SLOWOP_RETRIEVE_BEGIN_SCALAR);
emit(reg);
emit(nameIdx);
emit(beginId);
// Now register contains a reference to the persistent RuntimeScalar
// Store the initializer value INTO that RuntimeScalar
node.right.accept(this);
int valueReg = lastResultReg;
// Set the value in the persistent scalar using SET_SCALAR
// This calls .set() on the RuntimeScalar without overwriting the reference
emit(Opcodes.SET_SCALAR);
emit(reg);
emit(valueReg);
// Track this variable - map the name to the register we already allocated
variableScopes.peek().put(varName, reg);
lastResultReg = reg;
return;
}
// Regular lexical variable (not captured)
// Allocate register for new lexical variable and add to symbol table
int reg = addVariable(varName, "my");
// Compile RHS
node.right.accept(this);
int valueReg = lastResultReg;
// Move to variable register
emit(Opcodes.MOVE);
emit(reg);
emit(valueReg);
lastResultReg = reg;
return;
} else if (sigilOp.operator.equals("@") && sigilOp.operand instanceof IdentifierNode) {
// Handle my @array = ...
String varName = "@" + ((IdentifierNode) sigilOp.operand).name;
// Check if this variable is captured by named subs
if (sigilOp.id != 0) {
// RETRIEVE the persistent array
int beginId = sigilOp.id;
int nameIdx = addToStringPool(varName);
int arrayReg = allocateRegister();
emitWithToken(Opcodes.SLOW_OP, node.getIndex());
emit(Opcodes.SLOWOP_RETRIEVE_BEGIN_ARRAY);
emit(arrayReg);
emit(nameIdx);
emit(beginId);
// Compile RHS (should evaluate to a list)
node.right.accept(this);
int listReg = lastResultReg;
// Populate array from list
emit(Opcodes.ARRAY_SET_FROM_LIST);
emit(arrayReg);
emit(listReg);
// Track this variable - map the name to the register we already allocated
variableScopes.peek().put(varName, arrayReg);
lastResultReg = arrayReg;
return;
}
// Regular lexical array (not captured)
// Allocate register for new lexical array and add to symbol table
int arrayReg = addVariable(varName, "my");
// Create empty array
emit(Opcodes.NEW_ARRAY);
emit(arrayReg);
// Compile RHS (should evaluate to a list)
node.right.accept(this);
int listReg = lastResultReg;
// Populate array from list using setFromList
emit(Opcodes.ARRAY_SET_FROM_LIST);
emit(arrayReg);
emit(listReg);
lastResultReg = arrayReg;
return;
} else if (sigilOp.operator.equals("%") && sigilOp.operand instanceof IdentifierNode) {
// Handle my %hash = ...
String varName = "%" + ((IdentifierNode) sigilOp.operand).name;
// Check if this variable is captured by named subs
if (sigilOp.id != 0) {
// RETRIEVE the persistent hash
int beginId = sigilOp.id;
int nameIdx = addToStringPool(varName);
int hashReg = allocateRegister();
emitWithToken(Opcodes.SLOW_OP, node.getIndex());
emit(Opcodes.SLOWOP_RETRIEVE_BEGIN_HASH);
emit(hashReg);
emit(nameIdx);
emit(beginId);
// Compile RHS (should evaluate to a list)
node.right.accept(this);
int listReg = lastResultReg;
// Populate hash from list
emit(Opcodes.HASH_SET_FROM_LIST);
emit(hashReg);
emit(listReg);
// Track this variable - map the name to the register we already allocated
variableScopes.peek().put(varName, hashReg);
lastResultReg = hashReg;
return;
}
// Regular lexical hash (not captured)
// Allocate register for new lexical hash and add to symbol table
int hashReg = addVariable(varName, "my");
// Create empty hash
emit(Opcodes.NEW_HASH);
emit(hashReg);
// Compile RHS (should evaluate to a list)
node.right.accept(this);
int listReg = lastResultReg;
// Populate hash from list
emit(Opcodes.HASH_SET_FROM_LIST);
emit(hashReg);
emit(listReg);
lastResultReg = hashReg;
return;
}
}
// Handle my x (direct identifier without sigil)
if (myOperand instanceof IdentifierNode) {
String varName = ((IdentifierNode) myOperand).name;
// Allocate register for new lexical variable and add to symbol table
int reg = addVariable(varName, "my");
// Compile RHS
node.right.accept(this);
int valueReg = lastResultReg;
// Move to variable register
emit(Opcodes.MOVE);
emit(reg);
emit(valueReg);
lastResultReg = reg;
return;
}
}
// Special case: local $x = value
if (leftOp.operator.equals("local")) {
// Extract variable from "local" operand
Node localOperand = leftOp.operand;
// Handle local $x (where $x is OperatorNode("$", IdentifierNode("x")))
if (localOperand instanceof OperatorNode) {
OperatorNode sigilOp = (OperatorNode) localOperand;
if (sigilOp.operator.equals("$") && sigilOp.operand instanceof IdentifierNode) {
String varName = "$" + ((IdentifierNode) sigilOp.operand).name;
// Check if it's a lexical variable (should not be localized)
if (hasVariable(varName)) {
throwCompilerException("Can't localize lexical variable " + varName);
return;
}
// It's a global variable - emit SLOW_OP to call GlobalRuntimeScalar.makeLocal()
String packageName = getCurrentPackage();
String globalVarName = packageName + "::" + ((IdentifierNode) sigilOp.operand).name;
int nameIdx = addToStringPool(globalVarName);
int localReg = allocateRegister();
emitWithToken(Opcodes.SLOW_OP, node.getIndex());
emit(Opcodes.SLOWOP_LOCAL_SCALAR);
emit(localReg);
emit(nameIdx);
// Compile RHS
node.right.accept(this);
int valueReg = lastResultReg;
// Assign value to the localized variable
// The localized variable is a RuntimeScalar, so we use set() on it
emit(Opcodes.STORE_GLOBAL_SCALAR);
emit(nameIdx);
emit(valueReg);
lastResultReg = localReg;
return;
}
}
}
}
// Regular assignment: $x = value
// OPTIMIZATION: Detect $x = $x + $y and emit ADD_ASSIGN instead of ADD_SCALAR + MOVE
if (node.left instanceof OperatorNode && node.right instanceof BinaryOperatorNode) {
OperatorNode leftOp = (OperatorNode) node.left;
BinaryOperatorNode rightBin = (BinaryOperatorNode) node.right;
if (leftOp.operator.equals("$") && leftOp.operand instanceof IdentifierNode &&
rightBin.operator.equals("+") &&
rightBin.left instanceof OperatorNode) {
String leftVarName = "$" + ((IdentifierNode) leftOp.operand).name;
OperatorNode rightLeftOp = (OperatorNode) rightBin.left;
if (rightLeftOp.operator.equals("$") && rightLeftOp.operand instanceof IdentifierNode) {
String rightLeftVarName = "$" + ((IdentifierNode) rightLeftOp.operand).name;
// Pattern match: $x = $x + $y (emit ADD_ASSIGN)
// Skip optimization for captured variables (need SET_SCALAR)
boolean isCaptured = capturedVarIndices != null &&
capturedVarIndices.containsKey(leftVarName);
if (leftVarName.equals(rightLeftVarName) && hasVariable(leftVarName) && !isCaptured) {
int targetReg = getVariableRegister(leftVarName);
// Compile RHS operand ($y)
rightBin.right.accept(this);
int rhsReg = lastResultReg;
// Emit ADD_ASSIGN instead of ADD_SCALAR + MOVE
emit(Opcodes.ADD_ASSIGN);
emit(targetReg);
emit(rhsReg);
lastResultReg = targetReg;
return;
}
}
}
}
// Regular assignment: $x = value (no optimization)
// Compile RHS first
node.right.accept(this);
int valueReg = lastResultReg;
// Assign to LHS
if (node.left instanceof OperatorNode) {
OperatorNode leftOp = (OperatorNode) node.left;
if (leftOp.operator.equals("$") && leftOp.operand instanceof IdentifierNode) {
String varName = "$" + ((IdentifierNode) leftOp.operand).name;
if (hasVariable(varName)) {
// Lexical variable - check if it's captured
int targetReg = getVariableRegister(varName);
if (capturedVarIndices != null && capturedVarIndices.containsKey(varName)) {
// Captured variable - use SET_SCALAR to preserve aliasing
emit(Opcodes.SET_SCALAR);
emit(targetReg);
emit(valueReg);
} else {
// Regular lexical - use MOVE
emit(Opcodes.MOVE);
emit(targetReg);
emit(valueReg);
}
lastResultReg = targetReg;
} else {
// Global variable
int nameIdx = addToStringPool(varName);
emit(Opcodes.STORE_GLOBAL_SCALAR);
emit(nameIdx);
emit(valueReg);
lastResultReg = valueReg;
}
} else if (leftOp.operator.equals("@") && leftOp.operand instanceof IdentifierNode) {
// Array assignment: @array = ...
String varName = "@" + ((IdentifierNode) leftOp.operand).name;
int arrayReg;
if (hasVariable(varName)) {
// Lexical array
arrayReg = getVariableRegister(varName);
} else {
// Global array - load it
arrayReg = allocateRegister();
String globalArrayName = "main::" + ((IdentifierNode) leftOp.operand).name;
int nameIdx = addToStringPool(globalArrayName);
emit(Opcodes.LOAD_GLOBAL_ARRAY);
emit(arrayReg);
emit(nameIdx);
}
// Populate array from list using setFromList
emit(Opcodes.ARRAY_SET_FROM_LIST);
emit(arrayReg);
emit(valueReg);
lastResultReg = arrayReg;
} else if (leftOp.operator.equals("%") && leftOp.operand instanceof IdentifierNode) {
// Hash assignment: %hash = ...
String varName = "%" + ((IdentifierNode) leftOp.operand).name;
int hashReg;
if (hasVariable(varName)) {
// Lexical hash
hashReg = getVariableRegister(varName);
} else {
// Global hash - load it
hashReg = allocateRegister();
String globalHashName = "main::" + ((IdentifierNode) leftOp.operand).name;
int nameIdx = addToStringPool(globalHashName);
emit(Opcodes.LOAD_GLOBAL_HASH);
emit(hashReg);
emit(nameIdx);
}
// Populate hash from list using setFromList
emit(Opcodes.HASH_SET_FROM_LIST);
emit(hashReg);
emit(valueReg);
lastResultReg = hashReg;
} else {
throw new RuntimeException("Assignment to unsupported operator: " + leftOp.operator);
}
} else if (node.left instanceof IdentifierNode) {
String varName = ((IdentifierNode) node.left).name;
if (hasVariable(varName)) {
// Lexical variable - copy to its register
int targetReg = getVariableRegister(varName);
emit(Opcodes.MOVE);
emit(targetReg);
emit(valueReg);
lastResultReg = targetReg;
} else {
// Global variable
int nameIdx = addToStringPool(varName);
emit(Opcodes.STORE_GLOBAL_SCALAR);
emit(nameIdx);
emit(valueReg);
lastResultReg = valueReg;
}
} else {
throw new RuntimeException("Assignment to non-identifier not yet supported: " + node.left.getClass().getSimpleName());
}
// Restore the calling context
currentCallContext = savedContext;
return;
}
// Compile left and right operands
node.left.accept(this);
int rs1 = lastResultReg;
node.right.accept(this);
int rs2 = lastResultReg;
// Allocate result register
int rd = allocateRegister();
// Emit opcode based on operator
switch (node.operator) {
case "+" -> {
emit(Opcodes.ADD_SCALAR);
emit(rd);
emit(rs1);
emit(rs2);
}
case "-" -> {
emit(Opcodes.SUB_SCALAR);
emit(rd);
emit(rs1);
emit(rs2);
}
case "*" -> {
emit(Opcodes.MUL_SCALAR);
emit(rd);
emit(rs1);
emit(rs2);
}
case "." -> {
emit(Opcodes.CONCAT);
emit(rd);
emit(rs1);
emit(rs2);
}
case "x" -> {