-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBytecodeCompiler.java
More file actions
1113 lines (950 loc) · 39.5 KB
/
BytecodeCompiler.java
File metadata and controls
1113 lines (950 loc) · 39.5 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.runtime.*;
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<>();
private final Map<String, Integer> registerMap = new HashMap<>();
// Token index tracking for error reporting
private final Map<Integer, Integer> pcToTokenIndex = new HashMap<>();
// Register allocation
private int nextRegister = 3; // 0=this, 1=@_, 2=wantarray
// Track last result register for expression chaining
private int lastResultReg = -1;
// 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) {
this.sourceName = sourceName;
this.sourceLine = sourceLine;
}
/**
* 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 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
);
}
// =========================================================================
// 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<>();
// This is a simplified version - we collect variables from registerMap
// which contains all lexically declared variables in the current compilation unit
locals.addAll(registerMap.keySet());
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) {
stmt.accept(this);
}
}
@Override
public void visit(NumberNode node) {
// Emit LOAD_INT: rd = RuntimeScalarCache.getScalarInt(value)
int rd = allocateRegister();
try {
if (node.value.contains(".")) {
// TODO: Handle double values properly
int intValue = (int) Double.parseDouble(node.value);
emit(Opcodes.LOAD_INT);
emit(rd);
emitInt(intValue);
} else {
int intValue = Integer.parseInt(node.value);
emit(Opcodes.LOAD_INT);
emit(rd);
emitInt(intValue);
}
} 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 (registerMap.containsKey(varName)) {
// Lexical variable - already has a register
lastResultReg = registerMap.get(varName);
} else {
// Try with sigils
boolean found = false;
for (String sigil : sigils) {
String varNameWithSigil = sigil + varName;
if (registerMap.containsKey(varNameWithSigil)) {
lastResultReg = registerMap.get(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) {
// Handle assignment separately (doesn't follow standard left-right-op pattern)
if (node.operator.equals("=")) {
// 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;
// Allocate register for new lexical variable
int reg = allocateRegister();
registerMap.put(varName, reg);
// Compile RHS
node.right.accept(this);
int valueReg = lastResultReg;
// Move to variable register
emit(Opcodes.MOVE);
emit(reg);
emit(valueReg);
lastResultReg = reg;
return;
}
}
// Handle my x (direct identifier without sigil)
if (myOperand instanceof IdentifierNode) {
String varName = ((IdentifierNode) myOperand).name;
// Allocate register for new lexical variable
int reg = allocateRegister();
registerMap.put(varName, reg);
// Compile RHS
node.right.accept(this);
int valueReg = lastResultReg;
// Move to variable register
emit(Opcodes.MOVE);
emit(reg);
emit(valueReg);
lastResultReg = reg;
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)
if (leftVarName.equals(rightLeftVarName) && registerMap.containsKey(leftVarName)) {
int targetReg = registerMap.get(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 (registerMap.containsKey(varName)) {
// Lexical variable - copy to its register
int targetReg = registerMap.get(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-scalar not yet supported");
}
} else if (node.left instanceof IdentifierNode) {
String varName = ((IdentifierNode) node.left).name;
if (registerMap.containsKey(varName)) {
// Lexical variable - copy to its register
int targetReg = registerMap.get(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());
}
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 "<=>" -> {
emit(Opcodes.COMPARE_NUM);
emit(rd);
emit(rs1);
emit(rs2);
}
case "==" -> {
emit(Opcodes.EQ_NUM);
emit(rd);
emit(rs1);
emit(rs2);
}
case "<" -> {
emit(Opcodes.LT_NUM);
emit(rd);
emit(rs1);
emit(rs2);
}
case "()", "->" -> {
// Apply operator: $coderef->(args) or &subname(args)
// left (rs1) = code reference (RuntimeScalar containing RuntimeCode or SubroutineNode)
// right (rs2) = arguments (should be RuntimeList from ListNode)
// Note: rs2 should contain a RuntimeList (from visiting the ListNode)
// We need to convert it to RuntimeArray for the CALL_SUB opcode
// For now, rs2 is a RuntimeList - we'll pass it directly and let
// BytecodeInterpreter convert it to RuntimeArray
// Emit CALL_SUB: rd = coderef.apply(args, context)
emit(Opcodes.CALL_SUB);
emit(rd); // Result register
emit(rs1); // Code reference register
emit(rs2); // Arguments register (RuntimeList to be converted to RuntimeArray)
emit(RuntimeContextType.SCALAR); // Context (TODO: detect from usage)
// Note: CALL_SUB may return RuntimeControlFlowList
// The interpreter will handle control flow propagation
}
default -> throw new RuntimeException("Unsupported operator: " + node.operator);
}
lastResultReg = rd;
}
@Override
public void visit(OperatorNode node) {
String op = node.operator;
// Handle specific operators
if (op.equals("my")) {
// my $x - variable declaration
// The operand will be OperatorNode("$", IdentifierNode("x"))
if (node.operand instanceof OperatorNode) {
OperatorNode sigilOp = (OperatorNode) node.operand;
if (sigilOp.operator.equals("$") && sigilOp.operand instanceof IdentifierNode) {
String varName = "$" + ((IdentifierNode) sigilOp.operand).name;
int reg = allocateRegister();
registerMap.put(varName, reg);
// Load undef initially
emit(Opcodes.LOAD_UNDEF);
emit(reg);
lastResultReg = reg;
return;
}
}
throw new RuntimeException("Unsupported my operand: " + node.operand.getClass().getSimpleName());
} else if (op.equals("$")) {
// Scalar variable dereference: $x
if (node.operand instanceof IdentifierNode) {
String varName = "$" + ((IdentifierNode) node.operand).name;
if (registerMap.containsKey(varName)) {
// Lexical variable - use existing register
lastResultReg = registerMap.get(varName);
} else {
// Global variable - load it
int rd = allocateRegister();
int nameIdx = addToStringPool(varName);
emit(Opcodes.LOAD_GLOBAL_SCALAR);
emit(rd);
emit(nameIdx);
lastResultReg = rd;
}
} else {
throw new RuntimeException("Unsupported $ operand: " + node.operand.getClass().getSimpleName());
}
} else if (op.equals("@")) {
// Array variable dereference: @x or @_
if (node.operand instanceof IdentifierNode) {
String varName = "@" + ((IdentifierNode) node.operand).name;
// Special case: @_ is register 1
if (varName.equals("@_")) {
lastResultReg = 1; // @_ is always in register 1
return;
}
// For now, only support @_ - other arrays require global variable support
throw new RuntimeException("Array variables other than @_ not yet supported: " + varName);
} else {
throw new RuntimeException("Unsupported @ operand: " + node.operand.getClass().getSimpleName());
}
} else if (op.equals("%")) {
// Hash variable dereference: %x
throw new RuntimeException("Hash variables not yet supported");
} else if (op.equals("say") || op.equals("print")) {
// say/print $x
if (node.operand != null) {
node.operand.accept(this);
int rs = lastResultReg;
emit(op.equals("say") ? Opcodes.SAY : Opcodes.PRINT);
emit(rs);
}
} else if (op.equals("++") || op.equals("--") || op.equals("++postfix") || op.equals("--postfix")) {
// Pre/post increment/decrement
boolean isPostfix = op.endsWith("postfix");
boolean isIncrement = op.startsWith("++");
if (node.operand instanceof IdentifierNode) {
String varName = ((IdentifierNode) node.operand).name;
if (registerMap.containsKey(varName)) {
int varReg = registerMap.get(varName);
// Use optimized autoincrement/decrement opcodes
if (isPostfix) {
// Postfix: returns old value before modifying
if (isIncrement) {
emit(Opcodes.POST_AUTOINCREMENT);
} else {
emit(Opcodes.POST_AUTODECREMENT);
}
} else {
// Prefix: returns new value after modifying
if (isIncrement) {
emit(Opcodes.PRE_AUTOINCREMENT);
} else {
emit(Opcodes.PRE_AUTODECREMENT);
}
}
emit(varReg);
lastResultReg = varReg;
} else {
throw new RuntimeException("Increment/decrement of non-lexical variable not yet supported");
}
} else if (node.operand instanceof OperatorNode) {
// Handle $x++
OperatorNode innerOp = (OperatorNode) node.operand;
if (innerOp.operator.equals("$") && innerOp.operand instanceof IdentifierNode) {
String varName = "$" + ((IdentifierNode) innerOp.operand).name;
if (registerMap.containsKey(varName)) {
int varReg = registerMap.get(varName);
// Use optimized autoincrement/decrement opcodes
if (isPostfix) {
if (isIncrement) {
emit(Opcodes.POST_AUTOINCREMENT);
} else {
emit(Opcodes.POST_AUTODECREMENT);
}
} else {
if (isIncrement) {
emit(Opcodes.PRE_AUTOINCREMENT);
} else {
emit(Opcodes.PRE_AUTODECREMENT);
}
}
emit(varReg);
lastResultReg = varReg;
} else {
throw new RuntimeException("Increment/decrement of non-lexical variable not yet supported");
}
}
}
} else if (op.equals("return")) {
// return $expr;
if (node.operand != null) {
// Evaluate return expression
node.operand.accept(this);
int exprReg = lastResultReg;
// Emit RETURN with expression register
emitWithToken(Opcodes.RETURN, node.getIndex());
emit(exprReg);
} else {
// return; (no value - return empty list/undef)
int undefReg = allocateRegister();
emit(Opcodes.LOAD_UNDEF);
emit(undefReg);
emitWithToken(Opcodes.RETURN, node.getIndex());
emit(undefReg);
}
lastResultReg = -1; // No result after return
} else if (op.equals("die")) {
// die $message;
if (node.operand != null) {
// Evaluate die message
node.operand.accept(this);
int msgReg = lastResultReg;
// Emit DIE with message register
emitWithToken(Opcodes.DIE, node.getIndex());
emit(msgReg);
} else {
// die; (no message - use $@)
// For now, emit with undef register
int undefReg = allocateRegister();
emit(Opcodes.LOAD_UNDEF);
emit(undefReg);
emitWithToken(Opcodes.DIE, node.getIndex());
emit(undefReg);
}
lastResultReg = -1; // No result after die
} else {
throw new UnsupportedOperationException("Unsupported operator: " + op);
}
}
// =========================================================================
// HELPER METHODS
// =========================================================================
private int allocateRegister() {
return nextRegister++;
}
private int addToStringPool(String str) {
int index = stringPool.indexOf(str);
if (index >= 0) {
return index;
}
stringPool.add(str);
return stringPool.size() - 1;
}
private int addToConstantPool(Object obj) {
int index = constants.indexOf(obj);
if (index >= 0) {
return index;
}
constants.add(obj);
return constants.size() - 1;
}
private void emit(byte opcode) {
bytecode.write(opcode);
}
/**
* Emit opcode and track tokenIndex for error reporting.
* Use this for opcodes that may throw exceptions (DIE, method calls, etc.)
*/
private void emitWithToken(byte opcode, int tokenIndex) {
int pc = bytecode.size();
pcToTokenIndex.put(pc, tokenIndex);
bytecode.write(opcode);
}
private void emit(int value) {
bytecode.write(value & 0xFF);
}
private void emitInt(int value) {
bytecode.write((value >> 24) & 0xFF);
bytecode.write((value >> 16) & 0xFF);
bytecode.write((value >> 8) & 0xFF);
bytecode.write(value & 0xFF);
}
// =========================================================================
// UNIMPLEMENTED VISITOR METHODS (TODO)
// =========================================================================
@Override
public void visit(ArrayLiteralNode node) {
throw new UnsupportedOperationException("Arrays not yet implemented");
}
@Override
public void visit(HashLiteralNode node) {
throw new UnsupportedOperationException("Hashes not yet implemented");
}
@Override
public void visit(SubroutineNode node) {
// For now, only handle anonymous subroutines used as eval blocks
if (node.useTryCatch) {
// This is an eval block: eval { ... }
visitEvalBlock(node);
} else {
// Regular named or anonymous subroutine - not yet supported
throw new UnsupportedOperationException("Named subroutines not yet implemented in interpreter");
}
}
/**
* Visit an eval block: eval { ... }
*
* Generates:
* EVAL_TRY catch_offset # Set up exception handler, clear $@
* ... block bytecode ...
* EVAL_END # Clear $@ on success
* GOTO end
* LABEL catch:
* EVAL_CATCH rd # Set $@, store undef in rd
* LABEL end:
*
* The result is stored in lastResultReg.
*/
private void visitEvalBlock(SubroutineNode node) {
int resultReg = allocateRegister();
// Emit EVAL_TRY with placeholder for catch offset
int tryPc = bytecode.size();
emitWithToken(Opcodes.EVAL_TRY, node.getIndex());
int catchOffsetPos = bytecode.size();
emit(0); // High byte placeholder
emit(0); // Low byte placeholder
// Compile the eval block body
node.block.accept(this);
// Store result from block
if (lastResultReg >= 0) {
emit(Opcodes.MOVE);
emit(resultReg);
emit(lastResultReg);
}
// Emit EVAL_END (clears $@)
emit(Opcodes.EVAL_END);
// Jump over catch block
int gotoEndPos = bytecode.size();
emit(Opcodes.GOTO);
int gotoEndOffsetPos = bytecode.size();
emit(0); // High byte placeholder
emit(0); // Low byte placeholder
// CATCH block starts here
int catchPc = bytecode.size();
// Patch EVAL_TRY with catch offset
int catchOffset = catchPc - tryPc;
byte[] bc = bytecode.toByteArray();
bc[catchOffsetPos] = (byte) ((catchOffset >> 8) & 0xFF);
bc[catchOffsetPos + 1] = (byte) (catchOffset & 0xFF);
bytecode.reset();
bytecode.write(bc, 0, bc.length);
// Emit EVAL_CATCH (sets $@, stores undef)
emit(Opcodes.EVAL_CATCH);
emit(resultReg);
// END label (after catch)
int endPc = bytecode.size();
// Patch GOTO to end
int gotoEndOffset = endPc - gotoEndPos;
bc = bytecode.toByteArray();
bc[gotoEndOffsetPos] = (byte) ((gotoEndOffset >> 8) & 0xFF);
bc[gotoEndOffsetPos + 1] = (byte) (gotoEndOffset & 0xFF);
bytecode.reset();
bytecode.write(bc, 0, bc.length);
lastResultReg = resultReg;
}
@Override
public void visit(For1Node node) {
// For1Node: foreach-style loop
// for my $var (@list) { body }
// Step 1: Evaluate list in list context
node.list.accept(this);
int listReg = lastResultReg;
// Step 2: Convert to RuntimeArray if needed
// TODO: Handle list-to-array conversion
int arrayReg = allocateRegister();
emit(Opcodes.CREATE_ARRAY); // Placeholder - need to convert list to array
emit(arrayReg);
emit(listReg);
// Step 3: Allocate iterator index register
int indexReg = allocateRegister();
emit(Opcodes.LOAD_INT);
emit(indexReg);
emitInt(0);
// Step 4: Allocate array size register
int sizeReg = allocateRegister();
emit(Opcodes.ARRAY_SIZE);
emit(sizeReg);
emit(arrayReg);
// Step 5: Allocate loop variable register
int varReg = allocateRegister();
if (node.variable != null && node.variable instanceof OperatorNode) {
OperatorNode varOp = (OperatorNode) node.variable;
if (varOp.operator.equals("my") && varOp.operand instanceof OperatorNode) {
OperatorNode sigilOp = (OperatorNode) varOp.operand;
if (sigilOp.operator.equals("$") && sigilOp.operand instanceof IdentifierNode) {
String varName = "$" + ((IdentifierNode) sigilOp.operand).name;
registerMap.put(varName, varReg);
}
}
}
// Step 6: Loop start - check if index < size
int loopStartPc = bytecode.size();
// Compare index with size
int cmpReg = allocateRegister();
emit(Opcodes.LT_NUM);
emit(cmpReg);
emit(indexReg);
emit(sizeReg);
// If false, jump to end (we'll patch this later)
emit(Opcodes.GOTO_IF_FALSE);
emit(cmpReg);
int loopEndJumpPc = bytecode.size();
emitInt(0); // Placeholder for jump target
// Step 7: Get array element and assign to loop variable
emit(Opcodes.ARRAY_GET);
emit(varReg);
emit(arrayReg);
emit(indexReg);
// Step 8: Execute body
if (node.body != null) {
node.body.accept(this);
}
// Step 9: Increment index
emit(Opcodes.ADD_SCALAR_INT);
emit(indexReg);
emit(indexReg);
emitInt(1);
// Step 10: Jump back to loop start
emit(Opcodes.GOTO);
emitInt(loopStartPc);
// Step 11: Loop end - patch the forward jump
int loopEndPc = bytecode.size();
patchJump(loopEndJumpPc, loopEndPc);
lastResultReg = -1; // For loop returns empty
}
@Override
public void visit(For3Node node) {
// For3Node: C-style for loop
// for (init; condition; increment) { body }
// Step 1: Execute initialization
if (node.initialization != null) {
node.initialization.accept(this);
}
// Step 2: Loop start
int loopStartPc = bytecode.size();
// Step 3: Check condition
int condReg = allocateRegister();
if (node.condition != null) {
node.condition.accept(this);
condReg = lastResultReg;
} else {
// No condition means infinite loop - load true
emit(Opcodes.LOAD_INT);
emit(condReg);
emitInt(1);
}
// Step 4: If condition is false, jump to end
emit(Opcodes.GOTO_IF_FALSE);
emit(condReg);
int loopEndJumpPc = bytecode.size();
emitInt(0); // Placeholder for jump target (will be patched)
// Step 5: Execute body
if (node.body != null) {
node.body.accept(this);
}
// Step 6: Execute continue block if present
if (node.continueBlock != null) {
node.continueBlock.accept(this);
}
// Step 7: Execute increment
if (node.increment != null) {
node.increment.accept(this);
}
// Step 8: Jump back to loop start
emit(Opcodes.GOTO);
emitInt(loopStartPc);
// Step 9: Loop end - patch the forward jump