-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBytecodeInterpreter.java
More file actions
1148 lines (985 loc) · 54.4 KB
/
BytecodeInterpreter.java
File metadata and controls
1148 lines (985 loc) · 54.4 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.runtime.*;
import org.perlonjava.operators.*;
/**
* Bytecode interpreter with switch-based dispatch and pure register architecture.
*
* Key design principles:
* 1. Pure register machine (NO expression stack) - required for control flow correctness
* 2. 3-address code format: rd = rs1 op rs2 (explicit register operands)
* 3. Call same org.perlonjava.operators.* methods as compiler (100% code reuse)
* 4. Share GlobalVariable maps with compiled code (same global state)
* 5. Handle RuntimeControlFlowList for last/next/redo/goto/tail-call
* 6. Switch-based dispatch (JVM optimizes to tableswitch - O(1) jump table)
*/
public class BytecodeInterpreter {
/**
* Execute interpreted bytecode.
*
* @param code The InterpretedCode to execute
* @param args The arguments array (@_)
* @param callContext The calling context (VOID/SCALAR/LIST/RUNTIME)
* @return RuntimeList containing the result (may be RuntimeControlFlowList)
*/
public static RuntimeList execute(InterpretedCode code, RuntimeArray args, int callContext) {
return execute(code, args, callContext, null);
}
/**
* Execute interpreted bytecode with subroutine name for stack traces.
*
* @param code The InterpretedCode to execute
* @param args The arguments array (@_)
* @param callContext The calling context
* @param subroutineName Subroutine name for stack traces (may be null)
* @return RuntimeList containing the result (may be RuntimeControlFlowList)
*/
public static RuntimeList execute(InterpretedCode code, RuntimeArray args, int callContext, String subroutineName) {
// Pure register file (NOT stack-based - matches compiler for control flow correctness)
RuntimeBase[] registers = new RuntimeBase[code.maxRegisters];
// Initialize special registers (same as compiler)
registers[0] = code; // $this (for closures - register 0)
registers[1] = args; // @_ (arguments - register 1)
registers[2] = RuntimeScalarCache.getScalarInt(callContext); // wantarray (register 2)
// Copy captured variables (closure support)
if (code.capturedVars != null && code.capturedVars.length > 0) {
System.arraycopy(code.capturedVars, 0, registers, 3, code.capturedVars.length);
}
int pc = 0; // Program counter
byte[] bytecode = code.bytecode;
// Eval block exception handling: stack of catch PCs
// When EVAL_TRY is executed, push the catch PC onto this stack
// When exception occurs, pop from stack and jump to catch PC
java.util.Stack<Integer> evalCatchStack = new java.util.Stack<>();
try {
// Main dispatch loop - JVM JIT optimizes switch to tableswitch (O(1) jump)
while (pc < bytecode.length) {
byte opcode = bytecode[pc++];
switch (opcode) {
// =================================================================
// CONTROL FLOW
// =================================================================
case Opcodes.NOP:
// No operation
break;
case Opcodes.RETURN: {
// Return from subroutine: return rd
int retReg = bytecode[pc++] & 0xFF;
RuntimeBase retVal = registers[retReg];
if (retVal == null) {
return new RuntimeList();
} else if (retVal instanceof RuntimeList) {
return (RuntimeList) retVal;
} else if (retVal instanceof RuntimeScalar) {
return new RuntimeList((RuntimeScalar) retVal);
} else if (retVal instanceof RuntimeArray) {
return ((RuntimeArray) retVal).getList();
} else {
// Shouldn't happen, but handle gracefully
return new RuntimeList(new RuntimeScalar(retVal.toString()));
}
}
case Opcodes.GOTO: {
// Unconditional jump: pc = offset
int offset = readInt(bytecode, pc);
pc = offset; // Registers persist across jump (unlike stack-based!)
break;
}
case Opcodes.GOTO_IF_FALSE: {
// Conditional jump: if (!rs) pc = offset
int condReg = bytecode[pc++] & 0xFF;
int target = readInt(bytecode, pc);
pc += 4;
RuntimeScalar cond = (RuntimeScalar) registers[condReg];
if (!cond.getBoolean()) {
pc = target; // Jump - all registers stay valid!
}
break;
}
case Opcodes.GOTO_IF_TRUE: {
// Conditional jump: if (rs) pc = offset
int condReg = bytecode[pc++] & 0xFF;
int target = readInt(bytecode, pc);
pc += 4;
RuntimeScalar cond = (RuntimeScalar) registers[condReg];
if (cond.getBoolean()) {
pc = target;
}
break;
}
// =================================================================
// REGISTER OPERATIONS
// =================================================================
case Opcodes.MOVE: {
// Register copy: rd = rs
int dest = bytecode[pc++] & 0xFF;
int src = bytecode[pc++] & 0xFF;
registers[dest] = registers[src];
break;
}
case Opcodes.LOAD_CONST: {
// Load from constant pool: rd = constants[index]
int rd = bytecode[pc++] & 0xFF;
int constIndex = bytecode[pc++] & 0xFF;
registers[rd] = (RuntimeBase) code.constants[constIndex];
break;
}
case Opcodes.LOAD_INT: {
// Load integer: rd = immediate (create NEW mutable scalar, not cached)
int rd = bytecode[pc++] & 0xFF;
int value = readInt(bytecode, pc);
pc += 4;
// Create NEW RuntimeScalar (mutable) instead of using cache
// This is needed for local variables that may be modified (++/--)
registers[rd] = new RuntimeScalar(value);
break;
}
case Opcodes.LOAD_STRING: {
// Load string: rd = new RuntimeScalar(stringPool[index])
int rd = bytecode[pc++] & 0xFF;
int strIndex = bytecode[pc++] & 0xFF;
registers[rd] = new RuntimeScalar(code.stringPool[strIndex]);
break;
}
case Opcodes.LOAD_UNDEF: {
// Load undef: rd = new RuntimeScalar()
int rd = bytecode[pc++] & 0xFF;
registers[rd] = new RuntimeScalar();
break;
}
// =================================================================
// VARIABLE ACCESS - GLOBAL
// =================================================================
case Opcodes.LOAD_GLOBAL_SCALAR: {
// Load global scalar: rd = GlobalVariable.getGlobalVariable(name)
int rd = bytecode[pc++] & 0xFF;
int nameIdx = bytecode[pc++] & 0xFF;
String name = code.stringPool[nameIdx];
// Uses SAME GlobalVariable as compiled code
registers[rd] = GlobalVariable.getGlobalVariable(name);
break;
}
case Opcodes.STORE_GLOBAL_SCALAR: {
// Store global scalar: GlobalVariable.getGlobalVariable(name).set(rs)
int nameIdx = bytecode[pc++] & 0xFF;
int srcReg = bytecode[pc++] & 0xFF;
String name = code.stringPool[nameIdx];
GlobalVariable.getGlobalVariable(name).set((RuntimeScalar) registers[srcReg]);
break;
}
case Opcodes.LOAD_GLOBAL_ARRAY: {
// Load global array: rd = GlobalVariable.getGlobalArray(name)
int rd = bytecode[pc++] & 0xFF;
int nameIdx = bytecode[pc++] & 0xFF;
String name = code.stringPool[nameIdx];
registers[rd] = GlobalVariable.getGlobalArray(name);
break;
}
case Opcodes.LOAD_GLOBAL_HASH: {
// Load global hash: rd = GlobalVariable.getGlobalHash(name)
int rd = bytecode[pc++] & 0xFF;
int nameIdx = bytecode[pc++] & 0xFF;
String name = code.stringPool[nameIdx];
registers[rd] = GlobalVariable.getGlobalHash(name);
break;
}
case Opcodes.LOAD_GLOBAL_CODE: {
// Load global code: rd = GlobalVariable.getGlobalCodeRef(name)
int rd = bytecode[pc++] & 0xFF;
int nameIdx = bytecode[pc++] & 0xFF;
String name = code.stringPool[nameIdx];
registers[rd] = GlobalVariable.getGlobalCodeRef(name);
break;
}
case Opcodes.STORE_GLOBAL_CODE: {
// Store global code: GlobalVariable.globalCodeRefs.put(name, codeRef)
int nameIdx = bytecode[pc++] & 0xFF;
int codeReg = bytecode[pc++] & 0xFF;
String name = code.stringPool[nameIdx];
RuntimeScalar codeRef = (RuntimeScalar) registers[codeReg];
// Store the code reference in the global namespace
GlobalVariable.globalCodeRefs.put(name, codeRef);
break;
}
case Opcodes.CREATE_CLOSURE: {
// Create closure with captured variables
// Format: CREATE_CLOSURE rd template_idx num_captures reg1 reg2 ...
int rd = bytecode[pc++] & 0xFF;
int templateIdx = bytecode[pc++] & 0xFF;
int numCaptures = bytecode[pc++] & 0xFF;
// Get the template InterpretedCode from constants
InterpretedCode template = (InterpretedCode) code.constants[templateIdx];
// Capture the current register values
RuntimeBase[] capturedVars = new RuntimeBase[numCaptures];
for (int i = 0; i < numCaptures; i++) {
int captureReg = bytecode[pc++] & 0xFF;
capturedVars[i] = registers[captureReg];
}
// Create a new InterpretedCode with the captured variables
InterpretedCode closureCode = new InterpretedCode(
template.bytecode,
template.constants,
template.stringPool,
template.maxRegisters,
capturedVars, // The captured variables!
template.sourceName,
template.sourceLine,
template.pcToTokenIndex
);
// Wrap in RuntimeScalar
registers[rd] = new RuntimeScalar((RuntimeCode) closureCode);
break;
}
case Opcodes.SET_SCALAR: {
// Set scalar value: registers[rd].set(registers[rs])
// Used to set the value in a persistent scalar without overwriting the reference
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
((RuntimeScalar) registers[rd]).set((RuntimeScalar) registers[rs]);
break;
}
// =================================================================
// ARITHMETIC OPERATORS
// =================================================================
case Opcodes.ADD_SCALAR: {
// Addition: rd = rs1 + rs2
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
// Calls SAME method as compiled code
registers[rd] = MathOperators.add(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.SUB_SCALAR: {
// Subtraction: rd = rs1 - rs2
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = MathOperators.subtract(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.MUL_SCALAR: {
// Multiplication: rd = rs1 * rs2
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = MathOperators.multiply(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.DIV_SCALAR: {
// Division: rd = rs1 / rs2
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = MathOperators.divide(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.NEG_SCALAR: {
// Negation: rd = -rs
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
registers[rd] = MathOperators.unaryMinus((RuntimeScalar) registers[rs]);
break;
}
// Specialized unboxed operations (rare optimizations)
case Opcodes.ADD_SCALAR_INT: {
// Addition with immediate: rd = rs + immediate
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
int immediate = readInt(bytecode, pc);
pc += 4;
// Calls specialized unboxed method (rare optimization)
registers[rd] = MathOperators.add(
(RuntimeScalar) registers[rs],
immediate // primitive int, not RuntimeScalar
);
break;
}
// =================================================================
// STRING OPERATORS
// =================================================================
case Opcodes.CONCAT: {
// String concatenation: rd = rs1 . rs2
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = StringOperators.stringConcat(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.REPEAT: {
// String/list repetition: rd = rs1 x rs2
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
// Call Operator.repeat(base, count, context)
// Context: 1 = scalar context (for string repetition)
registers[rd] = Operator.repeat(
registers[rs1],
(RuntimeScalar) registers[rs2],
1 // scalar context
);
break;
}
case Opcodes.LENGTH: {
// String length: rd = length(rs)
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
registers[rd] = StringOperators.length((RuntimeScalar) registers[rs]);
break;
}
// =================================================================
// COMPARISON OPERATORS
// =================================================================
case Opcodes.COMPARE_NUM: {
// Numeric comparison: rd = rs1 <=> rs2
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = CompareOperators.spaceship(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.EQ_NUM: {
// Numeric equality: rd = (rs1 == rs2)
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = CompareOperators.equalTo(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.LT_NUM: {
// Less than: rd = (rs1 < rs2)
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = CompareOperators.lessThan(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.GT_NUM: {
// Greater than: rd = (rs1 > rs2)
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = CompareOperators.greaterThan(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
case Opcodes.NE_NUM: {
// Not equal: rd = (rs1 != rs2)
int rd = bytecode[pc++] & 0xFF;
int rs1 = bytecode[pc++] & 0xFF;
int rs2 = bytecode[pc++] & 0xFF;
registers[rd] = CompareOperators.notEqualTo(
(RuntimeScalar) registers[rs1],
(RuntimeScalar) registers[rs2]
);
break;
}
// =================================================================
// LOGICAL OPERATORS
// =================================================================
case Opcodes.NOT: {
// Logical NOT: rd = !rs
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
RuntimeScalar val = (RuntimeScalar) registers[rs];
registers[rd] = val.getBoolean() ?
RuntimeScalarCache.scalarFalse : RuntimeScalarCache.scalarTrue;
break;
}
// =================================================================
// ARRAY OPERATIONS
// =================================================================
case Opcodes.ARRAY_GET: {
// Array element access: rd = array[index]
int rd = bytecode[pc++] & 0xFF;
int arrayReg = bytecode[pc++] & 0xFF;
int indexReg = bytecode[pc++] & 0xFF;
// Check type
if (!(registers[arrayReg] instanceof RuntimeArray)) {
throw new RuntimeException("ARRAY_GET: register " + arrayReg + " contains " +
(registers[arrayReg] == null ? "null" : registers[arrayReg].getClass().getName()) +
" instead of RuntimeArray");
}
RuntimeArray arr = (RuntimeArray) registers[arrayReg];
RuntimeScalar idx = (RuntimeScalar) registers[indexReg];
// Uses RuntimeArray API directly
registers[rd] = arr.get(idx.getInt());
break;
}
case Opcodes.ARRAY_SET: {
// Array element store: array[index] = value
int arrayReg = bytecode[pc++] & 0xFF;
int indexReg = bytecode[pc++] & 0xFF;
int valueReg = bytecode[pc++] & 0xFF;
RuntimeArray arr = (RuntimeArray) registers[arrayReg];
RuntimeScalar idx = (RuntimeScalar) registers[indexReg];
RuntimeScalar val = (RuntimeScalar) registers[valueReg];
arr.get(idx.getInt()).set(val); // Get element then set its value
break;
}
case Opcodes.ARRAY_PUSH: {
// Array push: push(@array, value)
int arrayReg = bytecode[pc++] & 0xFF;
int valueReg = bytecode[pc++] & 0xFF;
RuntimeArray arr = (RuntimeArray) registers[arrayReg];
RuntimeScalar val = (RuntimeScalar) registers[valueReg];
arr.push(val);
break;
}
case Opcodes.ARRAY_SIZE: {
// Array size: rd = scalar(@array) or scalar(list)
int rd = bytecode[pc++] & 0xFF;
int operandReg = bytecode[pc++] & 0xFF;
RuntimeBase operand = registers[operandReg];
int size;
if (operand instanceof RuntimeArray) {
size = ((RuntimeArray) operand).size();
} else if (operand instanceof RuntimeList) {
size = ((RuntimeList) operand).size();
} else if (operand instanceof RuntimeScalar) {
// Scalar in array context - treat as 1-element list
size = 1;
} else {
throw new RuntimeException("ARRAY_SIZE: register " + operandReg + " contains unexpected type: " +
(operand == null ? "null" : operand.getClass().getName()));
}
registers[rd] = new RuntimeScalar(size);
break;
}
case Opcodes.CREATE_ARRAY: {
// Create array reference from list: rd = new RuntimeArray(rs_list).createReference()
// Array literals always return references in Perl
int rd = bytecode[pc++] & 0xFF;
int listReg = bytecode[pc++] & 0xFF;
// Convert to list (polymorphic - works for PerlRange, RuntimeList, etc.)
RuntimeBase source = registers[listReg];
RuntimeArray array;
if (source instanceof RuntimeArray) {
// Already an array - pass through
array = (RuntimeArray) source;
} else {
// Convert to list, then to array (works for PerlRange, RuntimeList, etc.)
RuntimeList list = source.getList();
array = new RuntimeArray(list);
}
// Create reference (array literals always return references!)
registers[rd] = array.createReference();
break;
}
// =================================================================
// HASH OPERATIONS
// =================================================================
case Opcodes.HASH_GET: {
// Hash element access: rd = hash{key}
int rd = bytecode[pc++] & 0xFF;
int hashReg = bytecode[pc++] & 0xFF;
int keyReg = bytecode[pc++] & 0xFF;
RuntimeHash hash = (RuntimeHash) registers[hashReg];
RuntimeScalar key = (RuntimeScalar) registers[keyReg];
// Uses RuntimeHash API directly
registers[rd] = hash.get(key);
break;
}
case Opcodes.HASH_SET: {
// Hash element store: hash{key} = value
int hashReg = bytecode[pc++] & 0xFF;
int keyReg = bytecode[pc++] & 0xFF;
int valueReg = bytecode[pc++] & 0xFF;
RuntimeHash hash = (RuntimeHash) registers[hashReg];
RuntimeScalar key = (RuntimeScalar) registers[keyReg];
RuntimeScalar val = (RuntimeScalar) registers[valueReg];
hash.put(key.toString(), val); // Convert key to String
break;
}
// =================================================================
// SUBROUTINE CALLS
// =================================================================
case Opcodes.CALL_SUB: {
// Call subroutine: rd = coderef->(args)
// May return RuntimeControlFlowList!
int rd = bytecode[pc++] & 0xFF;
int coderefReg = bytecode[pc++] & 0xFF;
int argsReg = bytecode[pc++] & 0xFF;
int context = bytecode[pc++] & 0xFF;
RuntimeScalar codeRef = (RuntimeScalar) registers[coderefReg];
RuntimeBase argsBase = registers[argsReg];
// Convert args to RuntimeArray if needed
RuntimeArray callArgs;
if (argsBase instanceof RuntimeArray) {
callArgs = (RuntimeArray) argsBase;
} else if (argsBase instanceof RuntimeList) {
// Convert RuntimeList to RuntimeArray (from ListNode)
callArgs = new RuntimeArray((RuntimeList) argsBase);
} else {
// Single scalar argument
callArgs = new RuntimeArray((RuntimeScalar) argsBase);
}
// RuntimeCode.apply works for both compiled AND interpreted code
RuntimeList result = RuntimeCode.apply(codeRef, "", callArgs, context);
registers[rd] = result;
// Check for control flow (last/next/redo/goto/tail-call)
if (result.isNonLocalGoto()) {
// Propagate control flow up the call stack
return result;
}
break;
}
// =================================================================
// CONTROL FLOW - SPECIAL (RuntimeControlFlowList)
// =================================================================
case Opcodes.CREATE_LAST: {
// Create LAST control flow: rd = RuntimeControlFlowList(LAST, label)
int rd = bytecode[pc++] & 0xFF;
int labelIdx = bytecode[pc++] & 0xFF;
String label = labelIdx == 255 ? null : code.stringPool[labelIdx];
registers[rd] = new RuntimeControlFlowList(
ControlFlowType.LAST, label,
code.sourceName, code.sourceLine
);
break;
}
case Opcodes.CREATE_NEXT: {
// Create NEXT control flow: rd = RuntimeControlFlowList(NEXT, label)
int rd = bytecode[pc++] & 0xFF;
int labelIdx = bytecode[pc++] & 0xFF;
String label = labelIdx == 255 ? null : code.stringPool[labelIdx];
registers[rd] = new RuntimeControlFlowList(
ControlFlowType.NEXT, label,
code.sourceName, code.sourceLine
);
break;
}
case Opcodes.CREATE_REDO: {
// Create REDO control flow: rd = RuntimeControlFlowList(REDO, label)
int rd = bytecode[pc++] & 0xFF;
int labelIdx = bytecode[pc++] & 0xFF;
String label = labelIdx == 255 ? null : code.stringPool[labelIdx];
registers[rd] = new RuntimeControlFlowList(
ControlFlowType.REDO, label,
code.sourceName, code.sourceLine
);
break;
}
case Opcodes.IS_CONTROL_FLOW: {
// Check if value is control flow: rd = (rs instanceof RuntimeControlFlowList)
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
boolean isControlFlow = registers[rs] instanceof RuntimeControlFlowList;
registers[rd] = isControlFlow ?
RuntimeScalarCache.scalarTrue : RuntimeScalarCache.scalarFalse;
break;
}
// =================================================================
// MISCELLANEOUS
// =================================================================
case Opcodes.PRINT: {
// Print to filehandle
// Format: [PRINT] [rs_content] [rs_filehandle]
int contentReg = bytecode[pc++] & 0xFF;
int filehandleReg = bytecode[pc++] & 0xFF;
Object val = registers[contentReg];
RuntimeScalar fh = (RuntimeScalar) registers[filehandleReg];
RuntimeList list;
if (val instanceof RuntimeList) {
list = (RuntimeList) val;
} else if (val instanceof RuntimeScalar) {
// Convert scalar to single-element list
list = new RuntimeList();
list.add((RuntimeScalar) val);
} else {
list = new RuntimeList();
}
// Call IOOperator.print()
org.perlonjava.operators.IOOperator.print(list, fh);
break;
}
case Opcodes.SAY: {
// Say to filehandle
// Format: [SAY] [rs_content] [rs_filehandle]
int contentReg = bytecode[pc++] & 0xFF;
int filehandleReg = bytecode[pc++] & 0xFF;
Object val = registers[contentReg];
RuntimeScalar fh = (RuntimeScalar) registers[filehandleReg];
RuntimeList list;
if (val instanceof RuntimeList) {
list = (RuntimeList) val;
} else if (val instanceof RuntimeScalar) {
// Convert scalar to single-element list
list = new RuntimeList();
list.add((RuntimeScalar) val);
} else {
list = new RuntimeList();
}
// Call IOOperator.say()
org.perlonjava.operators.IOOperator.say(list, fh);
break;
}
// =================================================================
// SUPERINSTRUCTIONS - Eliminate MOVE overhead
// =================================================================
case Opcodes.INC_REG: {
// Increment register in-place: r++
int rd = bytecode[pc++] & 0xFF;
registers[rd] = MathOperators.add((RuntimeScalar) registers[rd], 1);
break;
}
case Opcodes.DEC_REG: {
// Decrement register in-place: r--
int rd = bytecode[pc++] & 0xFF;
registers[rd] = MathOperators.subtract((RuntimeScalar) registers[rd], 1);
break;
}
case Opcodes.ADD_ASSIGN: {
// Add and assign: rd = rd + rs
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
registers[rd] = MathOperators.add(
(RuntimeScalar) registers[rd],
(RuntimeScalar) registers[rs]
);
break;
}
case Opcodes.ADD_ASSIGN_INT: {
// Add immediate and assign: rd = rd + imm
int rd = bytecode[pc++] & 0xFF;
int immediate = readInt(bytecode, pc);
pc += 4;
registers[rd] = MathOperators.add((RuntimeScalar) registers[rd], immediate);
break;
}
case Opcodes.PRE_AUTOINCREMENT: {
// Pre-increment: ++rd
int rd = bytecode[pc++] & 0xFF;
((RuntimeScalar) registers[rd]).preAutoIncrement();
break;
}
case Opcodes.POST_AUTOINCREMENT: {
// Post-increment: rd++
int rd = bytecode[pc++] & 0xFF;
((RuntimeScalar) registers[rd]).postAutoIncrement();
break;
}
case Opcodes.PRE_AUTODECREMENT: {
// Pre-decrement: --rd
int rd = bytecode[pc++] & 0xFF;
((RuntimeScalar) registers[rd]).preAutoDecrement();
break;
}
case Opcodes.POST_AUTODECREMENT: {
// Post-decrement: rd--
int rd = bytecode[pc++] & 0xFF;
((RuntimeScalar) registers[rd]).postAutoDecrement();
break;
}
// =================================================================
// ERROR HANDLING
// =================================================================
case Opcodes.DIE: {
// Die with message: die(rs)
int dieRs = bytecode[pc++] & 0xFF;
RuntimeBase message = registers[dieRs];
// Get token index for this die location if available
Integer tokenIndex = code.pcToTokenIndex != null
? code.pcToTokenIndex.get(pc - 2) // PC before we read register
: null;
// Call WarnDie.die() with proper parameters
// die(RuntimeBase message, RuntimeScalar where, String fileName, int lineNumber)
RuntimeScalar where = new RuntimeScalar(" at " + code.sourceName + " line " + code.sourceLine);
WarnDie.die(message, where, code.sourceName, code.sourceLine);
// Should never reach here (die throws exception)
throw new RuntimeException("die() did not throw exception");
}
case Opcodes.WARN: {
// Warn with message: warn(rs)
int warnRs = bytecode[pc++] & 0xFF;
RuntimeBase message = registers[warnRs];
// Get token index for this warn location if available
Integer tokenIndex = code.pcToTokenIndex != null
? code.pcToTokenIndex.get(pc - 2) // PC before we read register
: null;
// Call WarnDie.warn() with proper parameters
RuntimeScalar where = new RuntimeScalar(" at " + code.sourceName + " line " + code.sourceLine);
WarnDie.warn(message, where, code.sourceName, code.sourceLine);
break;
}
// =================================================================
// REFERENCE OPERATIONS
// =================================================================
case Opcodes.CREATE_REF: {
// Create reference: rd = rs.createReference()
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
RuntimeBase value = registers[rs];
registers[rd] = value.createReference();
break;
}
case Opcodes.DEREF: {
// Dereference: rd = rs (dereferencing depends on context)
// For now, just copy the reference - proper dereferencing
// is context-dependent and handled by specific operators
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
registers[rd] = registers[rs];
break;
}
case Opcodes.GET_TYPE: {
// Get type: rd = new RuntimeScalar(rs.type)
int rd = bytecode[pc++] & 0xFF;
int rs = bytecode[pc++] & 0xFF;
RuntimeScalar value = (RuntimeScalar) registers[rs];
// RuntimeScalar.type is an int constant from RuntimeScalarType
registers[rd] = new RuntimeScalar(value.type);
break;
}
// =================================================================
// EVAL BLOCK SUPPORT
// =================================================================
case Opcodes.EVAL_TRY: {
// Start of eval block with exception handling
// Format: [EVAL_TRY] [catch_offset_high] [catch_offset_low]
int catchOffsetHigh = bytecode[pc++] & 0xFF;
int catchOffsetLow = bytecode[pc++] & 0xFF;
int catchOffset = (catchOffsetHigh << 8) | catchOffsetLow;
int tryStartPc = pc - 3; // PC where EVAL_TRY opcode is
int catchPc = tryStartPc + catchOffset;
// Push catch PC onto eval stack
evalCatchStack.push(catchPc);
// Clear $@ at start of eval block
GlobalVariable.setGlobalVariable("main::@", "");
// Continue execution - if exception occurs, outer catch handler
// will check evalCatchStack and jump to catchPc
break;
}
case Opcodes.EVAL_END: {
// End of successful eval block - clear $@ and pop catch stack
GlobalVariable.setGlobalVariable("main::@", "");
// Pop the catch PC from eval stack (we didn't need it)
if (!evalCatchStack.isEmpty()) {
evalCatchStack.pop();
}
break;
}
case Opcodes.EVAL_CATCH: {
// Exception handler for eval block
// Format: [EVAL_CATCH] [rd]
// This is only reached when an exception is caught
int rd = bytecode[pc++] & 0xFF;
// WarnDie.catchEval() should have already been called to set $@
// Just store undef as the eval result
registers[rd] = RuntimeScalarCache.scalarUndef;
break;
}
// =================================================================
// LIST OPERATIONS
// =================================================================
case Opcodes.CREATE_LIST: {
// Create RuntimeList from registers
// Format: [CREATE_LIST] [rd] [count] [rs1] [rs2] ... [rsN]
int rd = bytecode[pc++] & 0xFF;
int count = bytecode[pc++] & 0xFF;
// Optimize for common cases
if (count == 0) {
// Empty list - fastest path
registers[rd] = new RuntimeList();
} else if (count == 1) {
// Single element - avoid loop overhead
int rs = bytecode[pc++] & 0xFF;
RuntimeList list = new RuntimeList();
list.add(registers[rs]);
registers[rd] = list;
} else {
// Multiple elements - preallocate and populate
RuntimeList list = new RuntimeList();
// Read all register indices and add elements
for (int i = 0; i < count; i++) {
int rs = bytecode[pc++] & 0xFF;
list.add(registers[rs]);
}
registers[rd] = list;
}
break;
}
// =================================================================
// STRING OPERATIONS
// =================================================================
case Opcodes.JOIN: {
// String join: rd = join(separator, list)
int rd = bytecode[pc++] & 0xFF;
int separatorReg = bytecode[pc++] & 0xFF;
int listReg = bytecode[pc++] & 0xFF;
RuntimeScalar separator = (RuntimeScalar) registers[separatorReg];
RuntimeBase list = registers[listReg];
// Call StringOperators.joinForInterpolation (doesn't warn on undef)
registers[rd] = org.perlonjava.operators.StringOperators.joinForInterpolation(separator, list);
break;
}
case Opcodes.SELECT: {
// Select default output filehandle: rd = IOOperator.select(list, SCALAR)
int rd = bytecode[pc++] & 0xFF;
int listReg = bytecode[pc++] & 0xFF;
RuntimeList list = (RuntimeList) registers[listReg];
RuntimeScalar result = org.perlonjava.operators.IOOperator.select(list, RuntimeContextType.SCALAR);
registers[rd] = result;
break;
}
case Opcodes.RANGE: {
// Create range: rd = PerlRange.createRange(rs_start, rs_end)
int rd = bytecode[pc++] & 0xFF;
int startReg = bytecode[pc++] & 0xFF;
int endReg = bytecode[pc++] & 0xFF;
RuntimeBase startBase = registers[startReg];
RuntimeBase endBase = registers[endReg];
// Handle null registers by creating undef scalars
RuntimeScalar start = (startBase instanceof RuntimeScalar) ? (RuntimeScalar) startBase :
(startBase == null) ? new RuntimeScalar() : startBase.scalar();
RuntimeScalar end = (endBase instanceof RuntimeScalar) ? (RuntimeScalar) endBase :
(endBase == null) ? new RuntimeScalar() : endBase.scalar();