-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBytecodeInterpreter.java
More file actions
3329 lines (2953 loc) · 160 KB
/
BytecodeInterpreter.java
File metadata and controls
3329 lines (2953 loc) · 160 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.operators.*;
import org.perlonjava.runtime.perlmodule.Universal;
import org.perlonjava.runtime.regex.RuntimeRegex;
import org.perlonjava.runtime.runtimetypes.*;
/**
* 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.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";
String frameSubName = subroutineName != null ? subroutineName : (code.subName != null ? code.subName : "(eval)");
InterpreterState.push(code, framePackageName, frameSubName);
// 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
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
java.util.Stack<Integer> evalCatchStack = new java.util.Stack<>();
// 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.
java.util.Stack<int[]> labeledBlockStack = new java.util.Stack<>();
// Each entry is [labelStringPoolIdx, exitPc]
java.util.Stack<RegexState> regexStateStack = new java.util.Stack<>();
// Record DVM level so the finally block can clean up everything pushed
// by this subroutine (local variables AND regex state snapshot).
int savedLocalLevel = DynamicVariableManager.getLocalLevel();
RegexState.save();
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.
InterpreterState.setCurrentPc(pc);
int 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++];
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!)
break;
}
case Opcodes.LAST:
case Opcodes.NEXT:
case Opcodes.REDO: {
// Loop control: jump to target PC
// Format: opcode, target (absolute PC as int)
int target = readInt(bytecode, pc);
pc = target;
break;
}
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!
}
break;
}
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;
}
break;
}
// =================================================================
// 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;
break;
}
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];
break;
}
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);
break;
}
case Opcodes.LOAD_STRING: {
// Load string: rd = new RuntimeScalar(stringPool[index])
int rd = bytecode[pc++];
int strIndex = bytecode[pc++];
registers[rd] = new RuntimeScalar(code.stringPool[strIndex]);
break;
}
case Opcodes.LOAD_VSTRING: {
// Load v-string literal with VSTRING type (e.g. v5.5.640)
// Mirrors JVM EmitLiteral isVString handling.
int rd = bytecode[pc++];
int strIndex = bytecode[pc++];
RuntimeScalar vs = new RuntimeScalar(code.stringPool[strIndex]);
vs.type = RuntimeScalarType.VSTRING;
registers[rd] = vs;
break;
}
case Opcodes.GLOB_OP: {
// File glob: ScalarGlobOperator.evaluate(globId, pattern, ctx)
// Mirrors JVM EmitOperator.handleGlobBuiltin.
int rd = bytecode[pc++];
int globId = bytecode[pc++];
int patternReg = bytecode[pc++];
int ctx = bytecode[pc++];
registers[rd] = ScalarGlobOperator.evaluate(globId, (RuntimeScalar) registers[patternReg], ctx);
break;
}
case Opcodes.LOAD_UNDEF: {
// Load undef: rd = new RuntimeScalar()
int rd = bytecode[pc++];
registers[rd] = new RuntimeScalar();
break;
}
case Opcodes.UNDEFINE_SCALAR: {
// Undefine variable in-place: rd.undefine()
int rd = bytecode[pc++];
if (isImmutableProxy(registers[rd])) {
registers[rd] = ensureMutableScalar(registers[rd]);
}
registers[rd].undefine();
break;
}
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;
break;
}
// =================================================================
// 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);
break;
}
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);
break;
}
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);
break;
}
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);
break;
}
case Opcodes.SAVE_REGEX_STATE: {
pc++;
regexStateStack.push(new RegexState());
break;
}
case Opcodes.RESTORE_REGEX_STATE: {
pc++;
if (!regexStateStack.isEmpty()) {
regexStateStack.pop().restore();
}
break;
}
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();
}
break;
}
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 = code.disassemble();
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());
}
break;
}
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());
}
break;
}
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);
break;
}
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);
break;
}
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];
registers[rd] = GlobalVariable.getGlobalCodeRef(name);
break;
}
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);
break;
}
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);
break;
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);
break;
}
// =================================================================
// ARITHMETIC OPERATORS
// =================================================================
case Opcodes.ADD_SCALAR: {
// Addition: rd = rs1 + rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
// Convert to scalar if needed
RuntimeBase val1 = registers[rs1];
RuntimeBase val2 = registers[rs2];
RuntimeScalar s1 = (val1 instanceof RuntimeScalar) ? (RuntimeScalar) val1 : val1.scalar();
RuntimeScalar s2 = (val2 instanceof RuntimeScalar) ? (RuntimeScalar) val2 : val2.scalar();
// Calls SAME method as compiled code
registers[rd] = MathOperators.add(s1, s2);
break;
}
case Opcodes.SUB_SCALAR: {
// Subtraction: rd = rs1 - rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
// Convert to scalar if needed
RuntimeBase val1 = registers[rs1];
RuntimeBase val2 = registers[rs2];
RuntimeScalar s1 = (val1 instanceof RuntimeScalar) ? (RuntimeScalar) val1 : val1.scalar();
RuntimeScalar s2 = (val2 instanceof RuntimeScalar) ? (RuntimeScalar) val2 : val2.scalar();
registers[rd] = MathOperators.subtract(s1, s2);
break;
}
case Opcodes.MUL_SCALAR: {
// Multiplication: rd = rs1 * rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
// Convert to scalar if needed
RuntimeBase val1 = registers[rs1];
RuntimeBase val2 = registers[rs2];
RuntimeScalar s1 = (val1 instanceof RuntimeScalar) ? (RuntimeScalar) val1 : val1.scalar();
RuntimeScalar s2 = (val2 instanceof RuntimeScalar) ? (RuntimeScalar) val2 : val2.scalar();
registers[rd] = MathOperators.multiply(s1, s2);
break;
}
case Opcodes.DIV_SCALAR: {
// Division: rd = rs1 / rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
// Convert to scalar if needed
RuntimeBase val1 = registers[rs1];
RuntimeBase val2 = registers[rs2];
RuntimeScalar s1 = (val1 instanceof RuntimeScalar) ? (RuntimeScalar) val1 : val1.scalar();
RuntimeScalar s2 = (val2 instanceof RuntimeScalar) ? (RuntimeScalar) val2 : val2.scalar();
registers[rd] = MathOperators.divide(s1, s2);
break;
}
case Opcodes.MOD_SCALAR: {
// Modulus: rd = rs1 % rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
// Convert to scalar if needed
RuntimeBase val1 = registers[rs1];
RuntimeBase val2 = registers[rs2];
RuntimeScalar s1 = (val1 instanceof RuntimeScalar) ? (RuntimeScalar) val1 : val1.scalar();
RuntimeScalar s2 = (val2 instanceof RuntimeScalar) ? (RuntimeScalar) val2 : val2.scalar();
registers[rd] = MathOperators.modulus(s1, s2);
break;
}
case Opcodes.POW_SCALAR: {
// Exponentiation: rd = rs1 ** rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
// Convert to scalar if needed
RuntimeBase val1 = registers[rs1];
RuntimeBase val2 = registers[rs2];
RuntimeScalar s1 = (val1 instanceof RuntimeScalar) ? (RuntimeScalar) val1 : val1.scalar();
RuntimeScalar s2 = (val2 instanceof RuntimeScalar) ? (RuntimeScalar) val2 : val2.scalar();
registers[rd] = MathOperators.pow(s1, s2);
break;
}
case Opcodes.NEG_SCALAR: {
// Negation: rd = -rs
int rd = bytecode[pc++];
int rs = bytecode[pc++];
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++];
int rs = bytecode[pc++];
int immediate = readInt(bytecode, pc);
pc += 1;
// 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++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
RuntimeBase concatLeft = registers[rs1];
RuntimeBase concatRight = registers[rs2];
registers[rd] = StringOperators.stringConcat(
concatLeft instanceof RuntimeScalar ? (RuntimeScalar) concatLeft : concatLeft.scalar(),
concatRight instanceof RuntimeScalar ? (RuntimeScalar) concatRight : concatRight.scalar()
);
break;
}
case Opcodes.REPEAT: {
// String/list repetition: rd = rs1 x rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
RuntimeBase countVal = registers[rs2];
RuntimeScalar count = (countVal instanceof RuntimeScalar)
? (RuntimeScalar) countVal
: ((RuntimeList) countVal).scalar();
registers[rd] = Operator.repeat(registers[rs1], count, 1);
break;
}
case Opcodes.LENGTH: {
// String length: rd = length(rs)
int rd = bytecode[pc++];
int rs = bytecode[pc++];
registers[rd] = StringOperators.length((RuntimeScalar) registers[rs]);
break;
}
// =================================================================
// COMPARISON AND LOGICAL OPERATORS (opcodes 31-39) - Delegated
// =================================================================
case Opcodes.COMPARE_NUM:
case Opcodes.COMPARE_STR:
case Opcodes.EQ_NUM:
case Opcodes.NE_NUM:
case Opcodes.LT_NUM:
case Opcodes.GT_NUM:
case Opcodes.LE_NUM:
case Opcodes.GE_NUM:
case Opcodes.EQ_STR:
case Opcodes.NE_STR:
case Opcodes.NOT:
pc = executeComparisons(opcode, bytecode, pc, registers);
break;
// =================================================================
// TYPE AND REFERENCE OPERATORS (opcodes 102-105) - Delegated
// =================================================================
case Opcodes.DEFINED:
case Opcodes.REF:
case Opcodes.BLESS:
case Opcodes.ISA:
case Opcodes.PROTOTYPE:
case Opcodes.QUOTE_REGEX:
pc = executeTypeOps(opcode, bytecode, pc, registers, code);
break;
// =================================================================
// 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);
break;
case Opcodes.ITERATOR_HAS_NEXT:
// Check iterator: rd = iterator.hasNext()
// Format: ITERATOR_HAS_NEXT rd iterReg
pc = OpcodeHandlerExtended.executeIteratorHasNext(bytecode, pc, registers);
break;
case Opcodes.ITERATOR_NEXT:
// Get next element: rd = iterator.next()
// Format: ITERATOR_NEXT rd iterReg
pc = OpcodeHandlerExtended.executeIteratorNext(bytecode, pc, registers);
break;
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();
}
break;
}
// =================================================================
// 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);
break;
case Opcodes.MULTIPLY_ASSIGN:
// Compound assignment: rd *= rs
// Format: MULTIPLY_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeMultiplyAssign(bytecode, pc, registers);
break;
case Opcodes.DIVIDE_ASSIGN:
// Compound assignment: rd /= rs
// Format: DIVIDE_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeDivideAssign(bytecode, pc, registers);
break;
case Opcodes.MODULUS_ASSIGN:
// Compound assignment: rd %= rs
// Format: MODULUS_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeModulusAssign(bytecode, pc, registers);
break;
case Opcodes.REPEAT_ASSIGN:
// Compound assignment: rd x= rs
// Format: REPEAT_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeRepeatAssign(bytecode, pc, registers);
break;
case Opcodes.POW_ASSIGN:
// Compound assignment: rd **= rs
// Format: POW_ASSIGN rd rs
pc = OpcodeHandlerExtended.executePowAssign(bytecode, pc, registers);
break;
case Opcodes.LEFT_SHIFT_ASSIGN:
// Compound assignment: rd <<= rs
// Format: LEFT_SHIFT_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeLeftShiftAssign(bytecode, pc, registers);
break;
case Opcodes.RIGHT_SHIFT_ASSIGN:
pc = OpcodeHandlerExtended.executeRightShiftAssign(bytecode, pc, registers);
break;
case Opcodes.INTEGER_LEFT_SHIFT_ASSIGN: {
int rd = bytecode[pc++];
int rs = bytecode[pc++];
RuntimeScalar s1 = (RuntimeScalar) registers[rd];
s1.set(BitwiseOperators.integerShiftLeft(s1, (RuntimeScalar) registers[rs]));
break;
}
case Opcodes.INTEGER_RIGHT_SHIFT_ASSIGN: {
int rd = bytecode[pc++];
int rs = bytecode[pc++];
RuntimeScalar s1 = (RuntimeScalar) registers[rd];
s1.set(BitwiseOperators.integerShiftRight(s1, (RuntimeScalar) registers[rs]));
break;
}
case Opcodes.INTEGER_DIV_ASSIGN: {
int rd = bytecode[pc++];
int rs = bytecode[pc++];
RuntimeScalar s1 = (RuntimeScalar) registers[rd];
s1.set(MathOperators.integerDivide(s1, (RuntimeScalar) registers[rs]));
break;
}
case Opcodes.INTEGER_MOD_ASSIGN: {
int rd = bytecode[pc++];
int rs = bytecode[pc++];
RuntimeScalar s1 = (RuntimeScalar) registers[rd];
s1.set(MathOperators.integerModulus(s1, (RuntimeScalar) registers[rs]));
break;
}
case Opcodes.LOGICAL_AND_ASSIGN:
// Compound assignment: rd &&= rs (short-circuit)
// Format: LOGICAL_AND_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeLogicalAndAssign(bytecode, pc, registers);
break;
case Opcodes.LOGICAL_OR_ASSIGN:
// Compound assignment: rd ||= rs (short-circuit)
// Format: LOGICAL_OR_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeLogicalOrAssign(bytecode, pc, registers);
break;
case Opcodes.DEFINED_OR_ASSIGN:
// Compound assignment: rd //= rs (short-circuit)
// Format: DEFINED_OR_ASSIGN rd rs
pc = OpcodeHandlerExtended.executeDefinedOrAssign(bytecode, pc, registers);
break;
// =================================================================
// SHIFT OPERATIONS
// =================================================================
case Opcodes.LEFT_SHIFT: {
// Left shift: rd = rs1 << rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
RuntimeScalar s1 = (RuntimeScalar) registers[rs1];
RuntimeScalar s2 = (RuntimeScalar) registers[rs2];
registers[rd] = BitwiseOperators.shiftLeft(s1, s2);
break;
}
case Opcodes.RIGHT_SHIFT: {
// Right shift: rd = rs1 >> rs2
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
RuntimeScalar s1 = (RuntimeScalar) registers[rs1];
RuntimeScalar s2 = (RuntimeScalar) registers[rs2];
registers[rd] = BitwiseOperators.shiftRight(s1, s2);
break;
}
case Opcodes.INTEGER_LEFT_SHIFT: {
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
RuntimeScalar s1 = (registers[rs1] instanceof RuntimeScalar) ? (RuntimeScalar) registers[rs1] : registers[rs1].scalar();
RuntimeScalar s2 = (registers[rs2] instanceof RuntimeScalar) ? (RuntimeScalar) registers[rs2] : registers[rs2].scalar();
registers[rd] = BitwiseOperators.integerShiftLeft(s1, s2);
break;
}
case Opcodes.INTEGER_RIGHT_SHIFT: {
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
RuntimeScalar s1 = (registers[rs1] instanceof RuntimeScalar) ? (RuntimeScalar) registers[rs1] : registers[rs1].scalar();
RuntimeScalar s2 = (registers[rs2] instanceof RuntimeScalar) ? (RuntimeScalar) registers[rs2] : registers[rs2].scalar();
registers[rd] = BitwiseOperators.integerShiftRight(s1, s2);
break;
}
case Opcodes.INTEGER_DIV: {
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
RuntimeScalar s1 = (registers[rs1] instanceof RuntimeScalar) ? (RuntimeScalar) registers[rs1] : registers[rs1].scalar();
RuntimeScalar s2 = (registers[rs2] instanceof RuntimeScalar) ? (RuntimeScalar) registers[rs2] : registers[rs2].scalar();
registers[rd] = MathOperators.integerDivide(s1, s2);
break;
}
case Opcodes.INTEGER_MOD: {
int rd = bytecode[pc++];
int rs1 = bytecode[pc++];
int rs2 = bytecode[pc++];
RuntimeScalar s1 = (registers[rs1] instanceof RuntimeScalar) ? (RuntimeScalar) registers[rs1] : registers[rs1].scalar();
RuntimeScalar s2 = (registers[rs2] instanceof RuntimeScalar) ? (RuntimeScalar) registers[rs2] : registers[rs2].scalar();
registers[rd] = MathOperators.integerModulus(s1, s2);
break;
}
// =================================================================
// ARRAY OPERATIONS
// =================================================================
case Opcodes.ARRAY_GET: {
// Array element access: rd = array[index]
int rd = bytecode[pc++];
int arrayReg = bytecode[pc++];
int indexReg = bytecode[pc++];
RuntimeBase arrayBase = registers[arrayReg];
RuntimeScalar idx = (RuntimeScalar) registers[indexReg];
if (arrayBase instanceof RuntimeArray) {
RuntimeArray arr = (RuntimeArray) arrayBase;
registers[rd] = arr.get(idx.getInt());
} else if (arrayBase instanceof RuntimeList) {
RuntimeList list = (RuntimeList) arrayBase;
int index = idx.getInt();
if (index < 0) index = list.elements.size() + index;
registers[rd] = (index >= 0 && index < list.elements.size())
? list.elements.get(index)
: new RuntimeScalar();
} else {
throw new RuntimeException("ARRAY_GET: register " + arrayReg + " contains " +
(arrayBase == null ? "null" : arrayBase.getClass().getName()) +
" instead of RuntimeArray or RuntimeList");
}
break;
}
case Opcodes.ARRAY_SET: {
// Array element store: array[index] = value
int arrayReg = bytecode[pc++];
int indexReg = bytecode[pc++];
int valueReg = bytecode[pc++];
RuntimeArray arr = (RuntimeArray) registers[arrayReg];
RuntimeScalar idx = (RuntimeScalar) registers[indexReg];
RuntimeBase valueBase = registers[valueReg];
RuntimeScalar val = (valueBase instanceof RuntimeScalar)
? (RuntimeScalar) valueBase : valueBase.scalar();
arr.get(idx.getInt()).set(val);
break;
}
case Opcodes.ARRAY_PUSH: {
// Array push: push(@array, value)
int arrayReg = bytecode[pc++];
int valueReg = bytecode[pc++];
RuntimeArray arr = (RuntimeArray) registers[arrayReg];
RuntimeBase val = registers[valueReg];
arr.push(val);
break;
}
case Opcodes.ARRAY_POP: {
// Array pop: rd = pop(@array)
int rd = bytecode[pc++];
int arrayReg = bytecode[pc++];
RuntimeArray arr = (RuntimeArray) registers[arrayReg];
registers[rd] = RuntimeArray.pop(arr);
break;
}
case Opcodes.ARRAY_SHIFT: {
// Array shift: rd = shift(@array)
int rd = bytecode[pc++];
int arrayReg = bytecode[pc++];
RuntimeArray arr = (RuntimeArray) registers[arrayReg];
registers[rd] = RuntimeArray.shift(arr);
break;
}
case Opcodes.ARRAY_UNSHIFT: {
// Array unshift: unshift(@array, value)
int arrayReg = bytecode[pc++];
int valueReg = bytecode[pc++];
RuntimeArray arr = (RuntimeArray) registers[arrayReg];
RuntimeBase val = registers[valueReg];
RuntimeArray.unshift(arr, val);
break;
}
case Opcodes.ARRAY_SIZE: {
// Array size: rd = scalar(@array) or scalar(value)
// Use polymorphic scalar() method - arrays return size, scalars return themselves
// Special case for RuntimeList: return size, not last element
int rd = bytecode[pc++];
int operandReg = bytecode[pc++];
RuntimeBase operand = registers[operandReg];
if (operand instanceof RuntimeList) {
// For RuntimeList in list assignment context, return the count
registers[rd] = new RuntimeScalar(((RuntimeList) operand).size());
} else {
registers[rd] = operand.scalar();
}
break;
}
case Opcodes.SET_ARRAY_LAST_INDEX: {
int arrayReg = bytecode[pc++];
int valueReg = bytecode[pc++];
RuntimeArray.indexLastElem((RuntimeArray) registers[arrayReg])