-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBytecodeInterpreter.java
More file actions
2815 lines (2461 loc) · 152 KB
/
BytecodeInterpreter.java
File metadata and controls
2815 lines (2461 loc) · 152 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.perlonjava.backend.bytecode;
import org.perlonjava.runtime.debugger.DebugHooks;
import org.perlonjava.runtime.operators.CompareOperators;
import org.perlonjava.runtime.operators.ReferenceOperators;
import org.perlonjava.runtime.operators.WarnDie;
import org.perlonjava.runtime.regex.RuntimeRegex;
import org.perlonjava.runtime.runtimetypes.*;
/**
* Bytecode interpreter with switch-based dispatch and pure register architecture.
* <p>
* 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.runtime.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 {
// Debug flag for regex compilation (set at class load time)
private static final boolean DEBUG_REGEX = System.getenv("DEBUG_REGEX") != null;
static RuntimeScalar ensureMutableScalar(RuntimeBase val) {
if (val instanceof RuntimeScalarReadOnly ro) {
RuntimeScalar copy = new RuntimeScalar();
copy.type = ro.type;
copy.value = ro.value;
return copy;
}
if (val instanceof ScalarSpecialVariable sv) {
RuntimeScalar src = sv.getValueAsScalar();
RuntimeScalar copy = new RuntimeScalar();
copy.type = src.type;
copy.value = src.value;
return copy;
}
return (RuntimeScalar) val;
}
static boolean isImmutableProxy(RuntimeBase val) {
return val instanceof RuntimeScalarReadOnly || val instanceof ScalarSpecialVariable;
}
/**
* 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) {
// Track interpreter state for stack traces
String framePackageName = code.packageName != null ? code.packageName : "main";
// Prefer code.subName (set by set_subname) over passed subroutineName
// This ensures caller() returns the name set by set_subname()
String frameSubName = code.subName != null ? code.subName : (subroutineName != null ? subroutineName : "(eval)");
// Get PC holder for direct updates (avoids ThreadLocal lookups in hot loop)
int[] pcHolder = InterpreterState.push(code, framePackageName, frameSubName);
// Get register array from cache (avoids allocation for non-recursive calls)
RuntimeBase[] registers = code.getRegisters();
// 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
final int[] 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
// Use ArrayDeque instead of Stack for better performance (no synchronization)
java.util.ArrayDeque<Integer> evalCatchStack = new java.util.ArrayDeque<>();
// Labeled block stack for non-local last/next/redo handling.
// When a function call returns a RuntimeControlFlowList, we check this stack
// to see if the label matches an enclosing labeled block.
// Uses ArrayList for O(1) indexed access when searching for labels
java.util.ArrayList<int[]> labeledBlockStack = new java.util.ArrayList<>();
// Each entry is [labelStringPoolIdx, exitPc]
java.util.ArrayDeque<RegexState> regexStateStack = new java.util.ArrayDeque<>();
// Optimization: only save/restore DynamicVariableManager state if the code uses localization.
// This avoids overhead for simple subroutines that don't use `local`.
boolean usesLocalization = code.usesLocalization;
// Record DVM level so the finally block can clean up everything pushed
// by this subroutine (local variables AND regex state snapshot).
int savedLocalLevel = usesLocalization ? DynamicVariableManager.getLocalLevel() : 0;
// Cache the currentPackage RuntimeScalar to avoid ThreadLocal lookups in hot loop
RuntimeScalar currentPackageScalar = InterpreterState.currentPackage.get();
String savedPackage = currentPackageScalar.toString();
currentPackageScalar.set(framePackageName);
if (usesLocalization) {
RegexState.save();
}
// Structure: try { while(true) { try { ...dispatch... } catch { handle eval/die } } } finally { cleanup }
//
// Outer try/finally — cleanup only, no catch.
// Restores local variables, package name, and call stack on ANY exit (return, throw, etc.)
//
// Inner try/catch — implements Perl's eval { BLOCK } / die semantics.
// When Perl code calls `die` inside `eval { ... }`, the catch block sets $@ and
// uses `continue outer` to jump back to the top of the while(true) loop, resuming
// the bytecode dispatch at the eval's catch target PC. Without the while(true),
// `continue` would have nowhere to go after the catch block.
try {
outer:
while (true) {
try {
// Main dispatch loop - JVM JIT optimizes switch to tableswitch (O(1) jump)
while (pc < bytecode.length) {
// Update current PC for caller()/stack trace reporting.
// This allows ExceptionFormatter to map pc->tokenIndex->line using code.errorUtil,
// which also honors #line directives inside eval strings.
// Uses cached pcHolder to avoid ThreadLocal lookups in hot loop.
pcHolder[0] = pc;
int opcode = bytecode[pc++];
switch (opcode) {
// =================================================================
// CONTROL FLOW
// =================================================================
case Opcodes.NOP -> {
// No operation
}
case Opcodes.RETURN -> {
// Return from subroutine: return rd
int retReg = bytecode[pc++];
RuntimeBase retVal = registers[retReg];
if (retVal == null) {
return new RuntimeList();
}
RuntimeList retList = retVal.getList();
RuntimeCode.materializeSpecialVarsInResult(retList);
return retList;
}
case Opcodes.GOTO -> {
// Unconditional jump: pc = offset
int offset = readInt(bytecode, pc);
pc = offset; // Registers persist across jump (unlike stack-based!)
}
case Opcodes.GOTO_DYNAMIC -> {
// Dynamic goto: evaluate register to get label name, look up PC
int rs = bytecode[pc++];
RuntimeScalar target = (RuntimeScalar) registers[rs];
// Dereference if target is a reference to CODE (e.g., goto \&sub)
if (target.type == RuntimeScalarType.REFERENCE) {
RuntimeScalar deref = (RuntimeScalar) target.value;
if (deref.type == RuntimeScalarType.CODE) {
target = deref;
}
}
// If target is a CODE reference, treat as goto &sub (tail call)
if (target.type == RuntimeScalarType.CODE) {
// Create a TAILCALL marker - pass current @_ (register 1)
RuntimeArray currentArgs = (registers[1] instanceof RuntimeArray)
? (RuntimeArray) registers[1]
: new RuntimeArray();
RuntimeControlFlowList marker = new RuntimeControlFlowList(
target, currentArgs, code.sourceName, code.sourceLine);
return marker;
}
String labelName = target.toString();
if (labelName.isEmpty()) {
// Bare `goto` without label - runtime error like Perl 5
throw new PerlCompilerException("goto must have label");
}
if (code.gotoLabelPcs != null) {
Integer targetPc = code.gotoLabelPcs.get(labelName);
if (targetPc != null) {
pc = targetPc;
break;
}
}
// Label not found locally - create GOTO marker and propagate
RuntimeControlFlowList marker = new RuntimeControlFlowList(
ControlFlowType.GOTO, labelName, code.sourceName, code.sourceLine);
return marker;
}
case Opcodes.LAST, Opcodes.NEXT, Opcodes.REDO -> {
// Loop control: jump to target PC
// Format: opcode, target (absolute PC as int)
int target = readInt(bytecode, pc);
pc = target;
}
case Opcodes.GOTO_IF_FALSE -> {
// Conditional jump: if (!rs) pc = offset
int condReg = bytecode[pc++];
int target = readInt(bytecode, pc);
pc += 1;
// Convert to scalar if needed for boolean test
RuntimeBase condBase = registers[condReg];
RuntimeScalar cond = (condBase instanceof RuntimeScalar)
? (RuntimeScalar) condBase
: condBase.scalar();
if (!cond.getBoolean()) {
pc = target; // Jump - all registers stay valid!
}
}
case Opcodes.GOTO_IF_TRUE -> {
// Conditional jump: if (rs) pc = offset
int condReg = bytecode[pc++];
int target = readInt(bytecode, pc);
pc += 1;
// Convert to scalar if needed for boolean test
RuntimeBase condBase = registers[condReg];
RuntimeScalar cond = (condBase instanceof RuntimeScalar)
? (RuntimeScalar) condBase
: condBase.scalar();
if (cond.getBoolean()) {
pc = target;
}
}
// =================================================================
// REGISTER OPERATIONS
// =================================================================
case Opcodes.ALIAS -> {
// Register alias: rd = rs (shares reference, does NOT copy value)
// Must unwrap RuntimeScalarReadOnly to prevent read-only values in variable registers
int dest = bytecode[pc++];
int src = bytecode[pc++];
RuntimeBase srcVal = registers[src];
registers[dest] = isImmutableProxy(srcVal) ? ensureMutableScalar(srcVal) : srcVal;
}
case Opcodes.LOAD_CONST -> {
// Load from constant pool: rd = constants[index]
int rd = bytecode[pc++];
int constIndex = bytecode[pc++];
registers[rd] = (RuntimeBase) code.constants[constIndex];
}
case Opcodes.LOAD_INT -> {
// Load integer: rd = immediate (create NEW mutable scalar, not cached)
int rd = bytecode[pc++];
int value = readInt(bytecode, pc);
pc += 1;
// Create NEW RuntimeScalar (mutable) instead of using cache
// This is needed for local variables that may be modified (++/--)
registers[rd] = new RuntimeScalar(value);
}
case Opcodes.LOAD_STRING -> {
int rd = bytecode[pc++];
int strIndex = bytecode[pc++];
registers[rd] = new RuntimeScalar(code.stringPool[strIndex]);
}
case Opcodes.LOAD_BYTE_STRING -> {
int rd = bytecode[pc++];
int strIndex = bytecode[pc++];
RuntimeScalar bs = new RuntimeScalar(code.stringPool[strIndex]);
bs.type = RuntimeScalarType.BYTE_STRING;
registers[rd] = bs;
}
case Opcodes.LOAD_VSTRING -> {
int rd = bytecode[pc++];
int strIndex = bytecode[pc++];
RuntimeScalar vs = new RuntimeScalar(code.stringPool[strIndex]);
vs.type = RuntimeScalarType.VSTRING;
registers[rd] = vs;
}
case Opcodes.GLOB_OP -> {
pc = InlineOpcodeHandler.executeGlobOp(bytecode, pc, registers);
}
case Opcodes.LOAD_UNDEF -> {
// Load undef: rd = new RuntimeScalar()
int rd = bytecode[pc++];
registers[rd] = new RuntimeScalar();
}
case Opcodes.UNDEFINE_SCALAR -> {
pc = InlineOpcodeHandler.executeUndefineScalar(bytecode, pc, registers);
}
case Opcodes.MY_SCALAR -> {
// Lexical scalar assignment: rd = new RuntimeScalar(); rd.set(rs)
int rd = bytecode[pc++];
int rs = bytecode[pc++];
RuntimeScalar newScalar = new RuntimeScalar();
registers[rs].addToScalar(newScalar);
registers[rd] = newScalar;
}
// =================================================================
// VARIABLE ACCESS - GLOBAL
// =================================================================
case Opcodes.LOAD_GLOBAL_SCALAR -> {
// Load global scalar: rd = GlobalVariable.getGlobalVariable(name)
int rd = bytecode[pc++];
int nameIdx = bytecode[pc++];
String name = code.stringPool[nameIdx];
// Uses SAME GlobalVariable as compiled code
registers[rd] = GlobalVariable.getGlobalVariable(name);
}
case Opcodes.STORE_GLOBAL_SCALAR -> {
// Store global scalar: GlobalVariable.getGlobalVariable(name).set(rs)
int nameIdx = bytecode[pc++];
int srcReg = bytecode[pc++];
String name = code.stringPool[nameIdx];
// Convert to scalar if needed
RuntimeBase value = registers[srcReg];
RuntimeScalar scalarValue = (value instanceof RuntimeScalar)
? (RuntimeScalar) value
: value.scalar();
GlobalVariable.getGlobalVariable(name).set(scalarValue);
}
case Opcodes.LOCAL_SCALAR_SAVE_LEVEL -> {
// Superinstruction: save dynamic level BEFORE makeLocal, then localize.
// Atomically: levelReg = getLocalLevel(), rd = makeLocal(name).
// The pre-push level in levelReg is used by POP_LOCAL_LEVEL after the loop.
int rd = bytecode[pc++];
int levelReg = bytecode[pc++];
int nameIdx = bytecode[pc++];
String name = code.stringPool[nameIdx];
registers[levelReg] = new RuntimeScalar(DynamicVariableManager.getLocalLevel());
registers[rd] = GlobalRuntimeScalar.makeLocal(name);
}
case Opcodes.POP_LOCAL_LEVEL -> {
// Restore DynamicVariableManager to a previously saved local level.
// Matches JVM compiler's DynamicVariableManager.popToLocalLevel(savedLevel) call.
int rs = bytecode[pc++];
int savedLevel = ((RuntimeScalar) registers[rs]).getInt();
DynamicVariableManager.popToLocalLevel(savedLevel);
}
case Opcodes.SAVE_REGEX_STATE -> {
pc++;
regexStateStack.push(new RegexState());
}
case Opcodes.RESTORE_REGEX_STATE -> {
pc++;
if (!regexStateStack.isEmpty()) {
regexStateStack.pop().restore();
}
}
case Opcodes.FOREACH_GLOBAL_NEXT_OR_EXIT -> {
// Superinstruction: foreach loop step for a global loop variable (e.g. $_).
// Combines: hasNext check, next() into varReg, aliasGlobalVariable, conditional jump.
// Do-while layout: if hasNext jump to bodyTarget, else fall through to exit.
int rd = bytecode[pc++];
int iterReg = bytecode[pc++];
int nameIdx = bytecode[pc++];
int bodyTarget = readInt(bytecode, pc);
pc += 1;
String name = code.stringPool[nameIdx];
RuntimeScalar iterScalar = (RuntimeScalar) registers[iterReg];
@SuppressWarnings("unchecked")
java.util.Iterator<RuntimeScalar> iterator =
(java.util.Iterator<RuntimeScalar>) iterScalar.value;
if (iterator.hasNext()) {
RuntimeScalar element = iterator.next();
if (isImmutableProxy(element)) {
element = ensureMutableScalar(element);
}
registers[rd] = element;
GlobalVariable.aliasGlobalVariable(name, element);
pc = bodyTarget; // ABSOLUTE jump back to body start
} else {
registers[rd] = new RuntimeScalar();
}
}
case Opcodes.STORE_GLOBAL_ARRAY -> {
// Store global array: GlobalVariable.getGlobalArray(name).setFromList(list)
int nameIdx = bytecode[pc++];
int srcReg = bytecode[pc++];
String name = code.stringPool[nameIdx];
RuntimeArray globalArray = GlobalVariable.getGlobalArray(name);
RuntimeBase value = registers[srcReg];
if (value == null) {
// Output disassembly around the error
String disasm = Disassemble.disassemble(code);
throw new PerlCompilerException("STORE_GLOBAL_ARRAY: Register r" + srcReg +
" is null when storing to @" + name + " at pc=" + (pc - 3) + "\n\nDisassembly:\n" + disasm);
}
// Clear and populate the global array from the source
if (value instanceof RuntimeArray) {
globalArray.elements.clear();
globalArray.elements.addAll(((RuntimeArray) value).elements);
} else if (value instanceof RuntimeList) {
globalArray.setFromList((RuntimeList) value);
} else {
globalArray.setFromList(value.getList());
}
}
case Opcodes.STORE_GLOBAL_HASH -> {
// Store global hash: GlobalVariable.getGlobalHash(name).setFromList(list)
int nameIdx = bytecode[pc++];
int srcReg = bytecode[pc++];
String name = code.stringPool[nameIdx];
RuntimeHash globalHash = GlobalVariable.getGlobalHash(name);
RuntimeBase value = registers[srcReg];
// Clear and populate the global hash from the source
if (value instanceof RuntimeHash) {
globalHash.elements.clear();
globalHash.elements.putAll(((RuntimeHash) value).elements);
} else if (value instanceof RuntimeList) {
globalHash.setFromList((RuntimeList) value);
} else {
globalHash.setFromList(value.getList());
}
}
case Opcodes.LOAD_GLOBAL_ARRAY -> {
// Load global array: rd = GlobalVariable.getGlobalArray(name)
int rd = bytecode[pc++];
int nameIdx = bytecode[pc++];
String name = code.stringPool[nameIdx];
registers[rd] = GlobalVariable.getGlobalArray(name);
}
case Opcodes.LOAD_GLOBAL_HASH -> {
// Load global hash: rd = GlobalVariable.getGlobalHash(name)
int rd = bytecode[pc++];
int nameIdx = bytecode[pc++];
String name = code.stringPool[nameIdx];
registers[rd] = GlobalVariable.getGlobalHash(name);
}
case Opcodes.LOAD_GLOBAL_CODE -> {
// Load global code: rd = GlobalVariable.getGlobalCodeRef(name)
int rd = bytecode[pc++];
int nameIdx = bytecode[pc++];
String name = code.stringPool[nameIdx];
if (name.equals("__SUB__")) {
// __SUB__ returns the current subroutine being executed
registers[rd] = RuntimeCode.selfReferenceMaybeNull(code.__SUB__);
} else {
registers[rd] = GlobalVariable.getGlobalCodeRef(name);
}
}
case Opcodes.STORE_GLOBAL_CODE -> {
// Store global code: GlobalVariable.globalCodeRefs.put(name, codeRef)
int nameIdx = bytecode[pc++];
int codeReg = bytecode[pc++];
String name = code.stringPool[nameIdx];
RuntimeScalar codeRef = (RuntimeScalar) registers[codeReg];
// Store the code reference in the global namespace
GlobalVariable.globalCodeRefs.put(name, codeRef);
}
case Opcodes.CREATE_CLOSURE -> {
// Create closure with captured variables
// Format: CREATE_CLOSURE rd template_idx num_captures reg1 reg2 ...
pc = OpcodeHandlerExtended.executeCreateClosure(bytecode, pc, registers, code);
}
case Opcodes.SET_SCALAR -> {
// Set scalar value: registers[rd] = registers[rs]
// Use addToScalar which properly handles special variables like $&
// addToScalar calls getValueAsScalar() for ScalarSpecialVariable
int rd = bytecode[pc++];
int rs = bytecode[pc++];
RuntimeBase rdVal = registers[rd];
RuntimeScalar rdScalar;
if (isImmutableProxy(rdVal)) {
rdScalar = new RuntimeScalar();
registers[rd] = rdScalar;
} else if (rdVal instanceof RuntimeScalar) {
rdScalar = (RuntimeScalar) rdVal;
} else {
rdScalar = rdVal.scalar();
}
registers[rs].addToScalar(rdScalar);
}
// =================================================================
// ARITHMETIC OPERATORS
// =================================================================
case Opcodes.ADD_SCALAR -> {
pc = InlineOpcodeHandler.executeAddScalar(bytecode, pc, registers);
}
case Opcodes.SUB_SCALAR -> {
pc = InlineOpcodeHandler.executeSubScalar(bytecode, pc, registers);
}
case Opcodes.MUL_SCALAR -> {
pc = InlineOpcodeHandler.executeMulScalar(bytecode, pc, registers);
}
case Opcodes.DIV_SCALAR -> {
pc = InlineOpcodeHandler.executeDivScalar(bytecode, pc, registers);
}
case Opcodes.MOD_SCALAR -> {
pc = InlineOpcodeHandler.executeModScalar(bytecode, pc, registers);
}
case Opcodes.POW_SCALAR -> {
pc = InlineOpcodeHandler.executePowScalar(bytecode, pc, registers);
}
case Opcodes.NEG_SCALAR -> {
pc = InlineOpcodeHandler.executeNegScalar(bytecode, pc, registers);
}
// Specialized unboxed operations (rare optimizations)
case Opcodes.ADD_SCALAR_INT -> {
pc = InlineOpcodeHandler.executeAddScalarInt(bytecode, pc, registers);
}
// =================================================================
// STRING OPERATORS
// =================================================================
case Opcodes.CONCAT -> {
pc = InlineOpcodeHandler.executeConcat(bytecode, pc, registers);
}
case Opcodes.REPEAT -> {
pc = InlineOpcodeHandler.executeRepeat(bytecode, pc, registers);
}
case Opcodes.LENGTH -> {
pc = InlineOpcodeHandler.executeLength(bytecode, pc, registers);
}
// =================================================================
// COMPARISON AND LOGICAL OPERATORS (opcodes 31-39) - Delegated
// =================================================================
case Opcodes.COMPARE_NUM, Opcodes.COMPARE_STR, Opcodes.EQ_NUM, Opcodes.NE_NUM,
Opcodes.LT_NUM, Opcodes.GT_NUM, Opcodes.LE_NUM, Opcodes.GE_NUM, Opcodes.EQ_STR,
Opcodes.NE_STR, Opcodes.NOT -> {
pc = executeComparisons(opcode, bytecode, pc, registers);
}
// =================================================================
// TYPE AND REFERENCE OPERATORS (opcodes 102-105) - Delegated
// =================================================================
case Opcodes.DEFINED, Opcodes.DEFINED_GLOB, Opcodes.REF, Opcodes.BLESS, Opcodes.ISA, Opcodes.SMARTMATCH, Opcodes.PROTOTYPE,
Opcodes.QUOTE_REGEX, Opcodes.QUOTE_REGEX_O -> {
pc = executeTypeOps(opcode, bytecode, pc, registers, code);
}
// =================================================================
// ITERATOR OPERATIONS - For efficient foreach loops
// =================================================================
case Opcodes.ITERATOR_CREATE -> {
// Create iterator: rd = rs.iterator()
// Format: ITERATOR_CREATE rd rs
pc = OpcodeHandlerExtended.executeIteratorCreate(bytecode, pc, registers);
}
case Opcodes.ITERATOR_HAS_NEXT -> {
// Check iterator: rd = iterator.hasNext()
// Format: ITERATOR_HAS_NEXT rd iterReg
pc = OpcodeHandlerExtended.executeIteratorHasNext(bytecode, pc, registers);
}
case Opcodes.ITERATOR_NEXT -> {
// Get next element: rd = iterator.next()
// Format: ITERATOR_NEXT rd iterReg
pc = OpcodeHandlerExtended.executeIteratorNext(bytecode, pc, registers);
}
case Opcodes.FOREACH_NEXT_OR_EXIT -> {
// Superinstruction for foreach loops (do-while layout).
// Combines: hasNext check, next() call, and conditional jump to body.
// Format: FOREACH_NEXT_OR_EXIT rd, iterReg, bodyTarget
// If hasNext: rd = iterator.next(), jump to bodyTarget (backward)
// Else: fall through to exit (iterator exhausted)
int rd = bytecode[pc++];
int iterReg = bytecode[pc++];
int bodyTarget = readInt(bytecode, pc); // Absolute target address
pc += 1; // Skip the int we just read
RuntimeScalar iterScalar = (RuntimeScalar) registers[iterReg];
@SuppressWarnings("unchecked")
java.util.Iterator<RuntimeScalar> iterator =
(java.util.Iterator<RuntimeScalar>) iterScalar.value;
if (iterator.hasNext()) {
// Get next element and jump back to body
RuntimeScalar elem = iterator.next();
registers[rd] = (isImmutableProxy(elem)) ? ensureMutableScalar(elem) : elem;
pc = bodyTarget; // ABSOLUTE jump back to body start
} else {
registers[rd] = new RuntimeScalar();
}
}
// =================================================================
// COMPOUND ASSIGNMENT OPERATORS (with overload support)
// =================================================================
case Opcodes.SUBTRACT_ASSIGN -> {
// Compound assignment: rd -= rs
// Format: SUBTRACT_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeSubtractAssign(bytecode, pc, registers);
}
case Opcodes.MULTIPLY_ASSIGN -> {
// Compound assignment: rd *= rs
// Format: MULTIPLY_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeMultiplyAssign(bytecode, pc, registers);
}
case Opcodes.DIVIDE_ASSIGN -> {
// Compound assignment: rd /= rs
// Format: DIVIDE_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeDivideAssign(bytecode, pc, registers);
}
case Opcodes.MODULUS_ASSIGN -> {
// Compound assignment: rd %= rs
// Format: MODULUS_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeModulusAssign(bytecode, pc, registers);
}
case Opcodes.REPEAT_ASSIGN -> {
// Compound assignment: rd x= rs
// Format: REPEAT_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeRepeatAssign(bytecode, pc, registers);
}
case Opcodes.POW_ASSIGN -> {
// Compound assignment: rd **= rs
// Format: POW_ASSIGN rd rs
pc = OpcodeHandlerExtended.executePowAssign(bytecode, pc, registers);
}
case Opcodes.LEFT_SHIFT_ASSIGN -> {
// Compound assignment: rd <<= rs
// Format: LEFT_SHIFT_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeLeftShiftAssign(bytecode, pc, registers);
}
case Opcodes.RIGHT_SHIFT_ASSIGN -> {
pc = OpcodeHandlerExtended.executeRightShiftAssign(bytecode, pc, registers);
}
case Opcodes.INTEGER_LEFT_SHIFT_ASSIGN -> {
pc = InlineOpcodeHandler.executeIntegerLeftShiftAssign(bytecode, pc, registers);
}
case Opcodes.INTEGER_RIGHT_SHIFT_ASSIGN -> {
pc = InlineOpcodeHandler.executeIntegerRightShiftAssign(bytecode, pc, registers);
}
case Opcodes.INTEGER_DIV_ASSIGN -> {
pc = InlineOpcodeHandler.executeIntegerDivAssign(bytecode, pc, registers);
}
case Opcodes.INTEGER_MOD_ASSIGN -> {
pc = InlineOpcodeHandler.executeIntegerModAssign(bytecode, pc, registers);
}
case Opcodes.LOGICAL_AND_ASSIGN -> {
// Compound assignment: rd &&= rs (short-circuit)
// Format: LOGICAL_AND_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeLogicalAndAssign(bytecode, pc, registers);
}
case Opcodes.LOGICAL_OR_ASSIGN -> {
// Compound assignment: rd ||= rs (short-circuit)
// Format: LOGICAL_OR_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeLogicalOrAssign(bytecode, pc, registers);
}
case Opcodes.DEFINED_OR_ASSIGN -> {
// Compound assignment: rd //= rs (short-circuit)
// Format: DEFINED_OR_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeDefinedOrAssign(bytecode, pc, registers);
}
// =================================================================
// SHIFT OPERATIONS
// =================================================================
case Opcodes.LEFT_SHIFT -> {
pc = InlineOpcodeHandler.executeLeftShift(bytecode, pc, registers);
}
case Opcodes.RIGHT_SHIFT -> {
pc = InlineOpcodeHandler.executeRightShift(bytecode, pc, registers);
}
case Opcodes.INTEGER_LEFT_SHIFT -> {
pc = InlineOpcodeHandler.executeIntegerLeftShift(bytecode, pc, registers);
}
case Opcodes.INTEGER_RIGHT_SHIFT -> {
pc = InlineOpcodeHandler.executeIntegerRightShift(bytecode, pc, registers);
}
case Opcodes.INTEGER_DIV -> {
pc = InlineOpcodeHandler.executeIntegerDiv(bytecode, pc, registers);
}
case Opcodes.INTEGER_MOD -> {
pc = InlineOpcodeHandler.executeIntegerMod(bytecode, pc, registers);
}
// =================================================================
// ARRAY OPERATIONS
// =================================================================
case Opcodes.ARRAY_GET -> {
pc = InlineOpcodeHandler.executeArrayGet(bytecode, pc, registers);
}
case Opcodes.ARRAY_SET -> {
pc = InlineOpcodeHandler.executeArraySet(bytecode, pc, registers);
}
case Opcodes.ARRAY_PUSH -> {
pc = InlineOpcodeHandler.executeArrayPush(bytecode, pc, registers);
}
case Opcodes.ARRAY_POP -> {
pc = InlineOpcodeHandler.executeArrayPop(bytecode, pc, registers);
}
case Opcodes.ARRAY_SHIFT -> {
pc = InlineOpcodeHandler.executeArrayShift(bytecode, pc, registers);
}
case Opcodes.ARRAY_UNSHIFT -> {
pc = InlineOpcodeHandler.executeArrayUnshift(bytecode, pc, registers);
}
case Opcodes.ARRAY_SIZE -> {
pc = InlineOpcodeHandler.executeArraySize(bytecode, pc, registers);
}
case Opcodes.SET_ARRAY_LAST_INDEX -> {
pc = InlineOpcodeHandler.executeSetArrayLastIndex(bytecode, pc, registers);
}
case Opcodes.CREATE_ARRAY -> {
pc = InlineOpcodeHandler.executeCreateArray(bytecode, pc, registers);
}
// =================================================================
// HASH OPERATIONS
// =================================================================
case Opcodes.HASH_GET -> {
pc = InlineOpcodeHandler.executeHashGet(bytecode, pc, registers);
}
case Opcodes.HASH_SET -> {
pc = InlineOpcodeHandler.executeHashSet(bytecode, pc, registers);
}
case Opcodes.HASH_EXISTS -> {
pc = InlineOpcodeHandler.executeHashExists(bytecode, pc, registers);
}
case Opcodes.HASH_DELETE -> {
pc = InlineOpcodeHandler.executeHashDelete(bytecode, pc, registers);
}
case Opcodes.ARRAY_EXISTS -> {
pc = InlineOpcodeHandler.executeArrayExists(bytecode, pc, registers);
}
case Opcodes.ARRAY_DELETE -> {
pc = InlineOpcodeHandler.executeArrayDelete(bytecode, pc, registers);
}
case Opcodes.HASH_DELETE_LOCAL -> {
pc = InlineOpcodeHandler.executeHashDeleteLocal(bytecode, pc, registers);
}
case Opcodes.ARRAY_DELETE_LOCAL -> {
pc = InlineOpcodeHandler.executeArrayDeleteLocal(bytecode, pc, registers);
}
case Opcodes.HASH_KEYS -> {
pc = InlineOpcodeHandler.executeHashKeys(bytecode, pc, registers);
}
case Opcodes.HASH_VALUES -> {
pc = InlineOpcodeHandler.executeHashValues(bytecode, pc, registers);
}
// =================================================================
// SUBROUTINE CALLS
// =================================================================
case Opcodes.CALL_SUB, Opcodes.CALL_SUB_SHARE_ARGS -> {
// Call subroutine: rd = coderef->(args)
// CALL_SUB_SHARE_ARGS: &func (no parens) shares caller's @_ by alias
// May return RuntimeControlFlowList!
// pcHolder[0] contains the PC of this opcode (set before opcode read)
boolean shareArgs = (opcode == Opcodes.CALL_SUB_SHARE_ARGS);
// pcHolder[0] contains the PC of this opcode (set before opcode read)
int callSitePc = pcHolder[0];
int rd = bytecode[pc++];
int coderefReg = bytecode[pc++];
int argsReg = bytecode[pc++];
int context = bytecode[pc++];
// Resolve RUNTIME context from register 2 (wantarray).
// When a subroutine body is compiled by the interpreter,
// the calling context is not known at compile time, so
// RUNTIME is baked into the bytecode. At execution time,
// resolve it from the actual calling context in register 2.
if (context == RuntimeContextType.RUNTIME) {
context = ((RuntimeScalar) registers[2]).getInt();
}
// Auto-convert coderef to scalar if needed
RuntimeBase codeRefBase = registers[coderefReg];
RuntimeScalar codeRef = (codeRefBase instanceof RuntimeScalar)
? (RuntimeScalar) codeRefBase
: codeRefBase.scalar();
// Dereference symbolic code references using current package
// This matches the JVM backend's call to codeDerefNonStrict()
// Only call for STRING/BYTE_STRING types (symbolic references)
// For CODE, REFERENCE, etc. let RuntimeCode.apply() handle errors
// Use cached RuntimeScalar to avoid ThreadLocal lookup
if (codeRef.type == RuntimeScalarType.STRING || codeRef.type == RuntimeScalarType.BYTE_STRING) {
codeRef = codeRef.codeDerefNonStrict(currentPackageScalar.toString());
}
RuntimeBase argsBase = registers[argsReg];
RuntimeArray callArgs;
if (argsBase instanceof RuntimeArray) {
callArgs = (RuntimeArray) argsBase;
} else if (argsBase instanceof RuntimeList) {
callArgs = new RuntimeArray();
argsBase.setArrayOfAlias(callArgs);
} else {
callArgs = new RuntimeArray((RuntimeScalar) argsBase);
}
// Push lazy call site info to CallerStack for caller() to see the correct location
// The actual line number computation is deferred until caller() is called
// Capture variables needed for lazy resolution
final String lazyPkg = currentPackageScalar.toString();
final int lazyPc = callSitePc;
CallerStack.pushLazy(lazyPkg, () -> getCallSiteInfo(code, lazyPc, lazyPkg));
RuntimeList result;
try {
// Fast path for InterpretedCode: call execute() directly,
// bypassing RuntimeCode.apply() indirection chain
if (codeRef.type == RuntimeScalarType.CODE && codeRef.value instanceof InterpretedCode interpCode) {
// Direct call to interpreter - skip RuntimeCode.apply overhead
// Push args to argsStack for getCallerArgs() support (used by List::Util::any/all/etc.)
RuntimeCode.pushArgs(callArgs);
try {
// Pass null for subroutineName to enable frame caching
result = BytecodeInterpreter.execute(interpCode, callArgs, context, null);
} finally {
RuntimeCode.popArgs();
}
} else {
// Slow path for JVM-compiled code, symbolic references, etc.
// For &func (shareArgs), use the apply overload that shares @_
if (shareArgs) {
result = RuntimeCode.apply(codeRef, callArgs, context);
} else {
result = RuntimeCode.apply(codeRef, "", callArgs, context);
}
}
// Handle TAILCALL with trampoline loop (same as JVM backend)
while (result.isNonLocalGoto()) {
RuntimeControlFlowList flow = (RuntimeControlFlowList) result;
if (flow.getControlFlowType() == ControlFlowType.TAILCALL) {
// Extract codeRef and args, call target
codeRef = flow.getTailCallCodeRef();
callArgs = flow.getTailCallArgs();
// Use fast path for InterpretedCode
if (codeRef.type == RuntimeScalarType.CODE && codeRef.value instanceof InterpretedCode interpCode) {
// Push args for tail call too
RuntimeCode.pushArgs(callArgs);
try {
result = BytecodeInterpreter.execute(interpCode, callArgs, context, null);
} finally {
RuntimeCode.popArgs();
}
} else {
result = RuntimeCode.apply(codeRef, "tailcall", callArgs, context);
}
// Loop to handle chained tail calls
} else {
// Not TAILCALL - check labeled blocks or propagate
break;
}
}
} finally {
CallerStack.pop();
}
// Convert to scalar if called in scalar context
if (context == RuntimeContextType.SCALAR) {
RuntimeBase scalarResult = result.scalar();
registers[rd] = (isImmutableProxy(scalarResult)) ? ensureMutableScalar(scalarResult) : scalarResult;
} else {
registers[rd] = result;
}
// Check for control flow (last/next/redo/goto) - TAILCALL already handled above
if (result.isNonLocalGoto()) {
RuntimeControlFlowList flow = (RuntimeControlFlowList) result;
// Check labeled block stack for a matching label
boolean handled = false;
for (int i = labeledBlockStack.size() - 1; i >= 0; i--) {
int[] entry = labeledBlockStack.get(i);
String blockLabel = code.stringPool[entry[0]];
if (flow.matchesLabel(blockLabel)) {
// Pop entries down to and including the match
while (labeledBlockStack.size() > i) {
labeledBlockStack.removeLast();
}
pc = entry[1]; // jump to block exit
handled = true;
break;
}
}
if (!handled) {
// GOTO/TAILCALL markers inside eval should be caught
// (same as JVM backend's EmitEval: ordinal > 2 means not LAST/NEXT/REDO)
ControlFlowType cfType = flow.getControlFlowType();
if ((cfType == ControlFlowType.GOTO || cfType == ControlFlowType.TAILCALL)
&& !evalCatchStack.isEmpty()) {
// Set $@ to the error message
String errorMsg = flow.marker.buildErrorMessage();
GlobalVariable.setGlobalVariable("main::@", errorMsg);
// Jump to eval catch handler
pc = evalCatchStack.pop();
RuntimeCode.evalDepth--;
break;
}
return result;
}
}
}
case Opcodes.CALL_METHOD -> {
// Call method: rd = RuntimeCode.call(invocant, method, currentSub, args, context)
// May return RuntimeControlFlowList!