-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCompileOperator.java
More file actions
2814 lines (2539 loc) · 138 KB
/
CompileOperator.java
File metadata and controls
2814 lines (2539 loc) · 138 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.frontend.astnode.*;
import org.perlonjava.runtime.operators.ScalarGlobOperator;
import org.perlonjava.runtime.runtimetypes.*;
import java.util.ArrayList;
import java.util.List;
public class CompileOperator {
private static void compileScalarOperand(BytecodeCompiler bc, OperatorNode node, String opName) {
if (node.operand instanceof ListNode list) {
if (!list.elements.isEmpty()) {
bc.compileNode(list.elements.get(0), -1, RuntimeContextType.SCALAR);
} else {
bc.throwCompilerException(opName + " requires an argument");
}
} else {
bc.compileNode(node.operand, -1, RuntimeContextType.SCALAR);
}
}
private static int compileArrayForExistsDelete(BytecodeCompiler bc, BinaryOperatorNode arrayAccess, int tokenIndex) {
if (!(arrayAccess.left instanceof OperatorNode leftOp) || !leftOp.operator.equals("$")
|| !(leftOp.operand instanceof IdentifierNode)) {
bc.throwCompilerException("Array exists/delete requires simple array variable");
return -1;
}
String varName = ((IdentifierNode) leftOp.operand).name;
String arrayVarName = "@" + varName;
if (bc.currentSubroutineBeginId != 0 && bc.currentSubroutineClosureVars != null
&& bc.currentSubroutineClosureVars.contains(arrayVarName)) {
int arrayReg = bc.allocateRegister();
int nameIdx = bc.addToStringPool(arrayVarName);
bc.emitWithToken(Opcodes.RETRIEVE_BEGIN_ARRAY, tokenIndex);
bc.emitReg(arrayReg);
bc.emit(nameIdx);
bc.emit(bc.currentSubroutineBeginId);
return arrayReg;
} else if (bc.hasVariable(arrayVarName)) {
return bc.getVariableRegister(arrayVarName);
} else {
int arrayReg = bc.allocateRegister();
String globalArrayName = NameNormalizer.normalizeVariableName(varName, bc.getCurrentPackage());
int nameIdx = bc.addToStringPool(globalArrayName);
bc.emit(Opcodes.LOAD_GLOBAL_ARRAY);
bc.emitReg(arrayReg);
bc.emit(nameIdx);
return arrayReg;
}
}
private static int compileArrayIndex(BytecodeCompiler bc, BinaryOperatorNode arrayAccess) {
if (!(arrayAccess.right instanceof ArrayLiteralNode indexNode) || indexNode.elements.isEmpty()) {
bc.throwCompilerException("Array exists/delete requires index");
return -1;
}
indexNode.elements.get(0).accept(bc);
return bc.lastResultReg;
}
public static void visitOperator(BytecodeCompiler bytecodeCompiler, OperatorNode node) {
// Track token index for error reporting
bytecodeCompiler.currentTokenIndex = node.getIndex();
String op = node.operator;
// Group 1: Variable declarations (my, our, local, state)
if (op.equals("my") || op.equals("our") || op.equals("local") || op.equals("state")) {
bytecodeCompiler.compileVariableDeclaration(node, op);
return;
}
// Group 2: Variable reference operators ($, @, %, *, &, \)
if (op.equals("$") || op.equals("@") || op.equals("%") || op.equals("*") || op.equals("&") || op.equals("\\")) {
bytecodeCompiler.compileVariableReference(node, op);
return;
}
// Handle remaining operators
if (op.equals("scalar")) {
// Force scalar context: scalar(expr)
// Evaluates the operand and converts the result to scalar
if (node.operand != null) {
bytecodeCompiler.compileNode(node.operand, -1, RuntimeContextType.SCALAR);
int operandReg = bytecodeCompiler.lastResultReg;
// Emit ARRAY_SIZE to convert to scalar
// This handles arrays/hashes (converts to size) and passes through scalars
int rd = bytecodeCompiler.allocateOutputRegister();
bytecodeCompiler.emit(Opcodes.ARRAY_SIZE);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(operandReg);
bytecodeCompiler.lastResultReg = rd;
} else {
bytecodeCompiler.throwCompilerException("scalar operator requires an operand");
}
} else if (op.equals("package") || op.equals("class")) {
// Package/Class declaration: package Foo; or class Foo;
// This updates the current package context for subsequent variable declarations
if (node.operand instanceof IdentifierNode) {
String packageName = ((IdentifierNode) node.operand).name;
// Check if this is a class declaration (either "class" operator or isClass annotation)
Boolean isClassAnnotation = (Boolean) node.getAnnotation("isClass");
boolean isClass = op.equals("class") || (isClassAnnotation != null && isClassAnnotation);
// Check if there's a version associated with this package and set $Package::VERSION
String version = bytecodeCompiler.symbolTable.getPackageVersion(packageName);
if (version != null) {
// Set $PackageName::VERSION at compile time using GlobalVariable
String versionVarName = packageName + "::VERSION";
GlobalVariable.getGlobalVariable(versionVarName)
.set(new RuntimeScalar(version));
}
// Update the current package/class in symbol table (compile-time tracking)
bytecodeCompiler.symbolTable.setCurrentPackage(packageName, isClass);
// Register as Perl 5.38+ class for proper stringification if needed
if (isClass) {
ClassRegistry.registerClass(packageName);
}
// Emit runtime package tracking opcode so caller() and eval STRING work.
// Scoped blocks (package Foo { }) use PUSH_PACKAGE so DynamicVariableManager
// can restore the previous package when the scope exits.
// Non-scoped (package Foo;) use SET_PACKAGE which just overwrites.
boolean isScoped = Boolean.TRUE.equals(node.getAnnotation("isScoped"));
int nameIdx = bytecodeCompiler.addToStringPool(packageName);
if (isScoped) {
bytecodeCompiler.emit(Opcodes.PUSH_PACKAGE);
} else {
bytecodeCompiler.emit(Opcodes.SET_PACKAGE);
}
bytecodeCompiler.emit(nameIdx);
bytecodeCompiler.lastResultReg = -1; // No runtime value
} else {
bytecodeCompiler.throwCompilerException(op + " operator requires an identifier");
}
} else if (op.equals("say") || op.equals("print")) {
// say/print $x
if (node.operand != null) {
node.operand.accept(bytecodeCompiler);
int rs = bytecodeCompiler.lastResultReg;
bytecodeCompiler.emit(op.equals("say") ? Opcodes.SAY : Opcodes.PRINT);
bytecodeCompiler.emitReg(rs);
}
} else if (op.equals("not") || op.equals("!")) {
// Logical NOT operator: not $x or !$x
// Evaluate operand in scalar context (need boolean value)
if (node.operand != null) {
bytecodeCompiler.compileNode(node.operand, -1, RuntimeContextType.SCALAR);
int rs = bytecodeCompiler.lastResultReg;
// Allocate result register
int rd = bytecodeCompiler.allocateOutputRegister();
// Emit NOT opcode
bytecodeCompiler.emit(Opcodes.NOT);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(rs);
bytecodeCompiler.lastResultReg = rd;
} else {
bytecodeCompiler.throwCompilerException("NOT operator requires operand");
}
} else if (op.equals("~") || op.equals("binary~")) {
// Bitwise NOT operator: ~$x or binary~$x
// Evaluate operand and emit BITWISE_NOT_BINARY opcode
if (node.operand != null) {
node.operand.accept(bytecodeCompiler);
int rs = bytecodeCompiler.lastResultReg;
// Allocate result register
int rd = bytecodeCompiler.allocateOutputRegister();
// Emit BITWISE_NOT_BINARY opcode
bytecodeCompiler.emit(Opcodes.BITWISE_NOT_BINARY);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(rs);
bytecodeCompiler.lastResultReg = rd;
} else {
bytecodeCompiler.throwCompilerException("Bitwise NOT operator requires operand");
}
} else if (op.equals("~.")) {
// String bitwise NOT operator: ~.$x
// Evaluate operand and emit BITWISE_NOT_STRING opcode
if (node.operand != null) {
node.operand.accept(bytecodeCompiler);
int rs = bytecodeCompiler.lastResultReg;
// Allocate result register
int rd = bytecodeCompiler.allocateOutputRegister();
// Emit BITWISE_NOT_STRING opcode
bytecodeCompiler.emit(Opcodes.BITWISE_NOT_STRING);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(rs);
bytecodeCompiler.lastResultReg = rd;
} else {
bytecodeCompiler.throwCompilerException("String bitwise NOT operator requires operand");
}
} else if (op.equals("defined")) {
// Defined operator: defined($x)
// Check if value is defined (not undef)
if (node.operand != null) {
node.operand.accept(bytecodeCompiler);
int rs = bytecodeCompiler.lastResultReg;
// Allocate result register
int rd = bytecodeCompiler.allocateOutputRegister();
// Emit DEFINED opcode
bytecodeCompiler.emit(Opcodes.DEFINED);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(rs);
bytecodeCompiler.lastResultReg = rd;
} else {
bytecodeCompiler.throwCompilerException("defined operator requires operand");
}
} else if (op.equals("ref")) {
// Ref operator: ref($x)
// Get reference type (blessed class name or base type)
if (node.operand == null) {
bytecodeCompiler.throwCompilerException("ref requires an argument");
}
// Compile the operand
if (node.operand instanceof ListNode list) {
if (list.elements.isEmpty()) {
bytecodeCompiler.throwCompilerException("ref requires an argument");
}
// Get first element
list.elements.get(0).accept(bytecodeCompiler);
} else {
node.operand.accept(bytecodeCompiler);
}
int argReg = bytecodeCompiler.lastResultReg;
// Allocate result register
int rd = bytecodeCompiler.allocateOutputRegister();
// Emit REF opcode
bytecodeCompiler.emit(Opcodes.REF);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(argReg);
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("prototype")) {
// Prototype operator: prototype(\&func) or prototype("func_name")
// Returns the prototype string for a subroutine
if (node.operand == null) {
bytecodeCompiler.throwCompilerException("prototype requires an argument");
}
// Compile the operand (code reference or function name)
if (node.operand instanceof ListNode list) {
if (list.elements.isEmpty()) {
bytecodeCompiler.throwCompilerException("prototype requires an argument");
}
// Get first element
list.elements.get(0).accept(bytecodeCompiler);
} else {
node.operand.accept(bytecodeCompiler);
}
int argReg = bytecodeCompiler.lastResultReg;
// Allocate result register
int rd = bytecodeCompiler.allocateOutputRegister();
// Add current package to string pool
int packageIdx = bytecodeCompiler.addToStringPool(bytecodeCompiler.getCurrentPackage());
// Emit PROTOTYPE opcode
bytecodeCompiler.emit(Opcodes.PROTOTYPE);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(argReg);
bytecodeCompiler.emitInt(packageIdx);
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("quoteRegex")) {
// Quote regex operator: qr{pattern}flags
// operand is a ListNode with [pattern, flags]
if (node.operand == null || !(node.operand instanceof ListNode)) {
bytecodeCompiler.throwCompilerException("quoteRegex requires pattern and flags");
}
ListNode operand = (ListNode) node.operand;
if (operand.elements.size() < 2) {
bytecodeCompiler.throwCompilerException("quoteRegex requires pattern and flags");
}
// Check if /o modifier is used (flags are typically a StringNode)
boolean hasOModifier = false;
Node flagsNode = operand.elements.get(1);
if (flagsNode instanceof StringNode) {
hasOModifier = ((StringNode) flagsNode).value.contains("o");
}
// Compile pattern and flags
operand.elements.get(0).accept(bytecodeCompiler); // Pattern
int patternReg = bytecodeCompiler.lastResultReg;
flagsNode.accept(bytecodeCompiler); // Flags
int flagsReg = bytecodeCompiler.lastResultReg;
// Allocate result register
int rd = bytecodeCompiler.allocateOutputRegister();
// Emit appropriate opcode based on /o modifier
if (hasOModifier) {
// Use QUOTE_REGEX_O with callsite ID for /o modifier
int callsiteId = bytecodeCompiler.allocateCallsiteId();
bytecodeCompiler.emit(Opcodes.QUOTE_REGEX_O);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(patternReg);
bytecodeCompiler.emitReg(flagsReg);
bytecodeCompiler.emitReg(callsiteId);
} else {
// Normal QUOTE_REGEX
bytecodeCompiler.emit(Opcodes.QUOTE_REGEX);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(patternReg);
bytecodeCompiler.emitReg(flagsReg);
}
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("++") || op.equals("--") || op.equals("++postfix") || op.equals("--postfix")) {
// Pre/post increment/decrement - recursive approach with fast path optimization
boolean isPostfix = op.endsWith("postfix");
boolean isIncrement = op.startsWith("++");
if (node.operand != null) {
// Fast path: simple lexical variable (most common case)
if (node.operand instanceof IdentifierNode) {
String varName = ((IdentifierNode) node.operand).name;
if (bytecodeCompiler.hasVariable(varName)) {
int varReg = bytecodeCompiler.getVariableRegister(varName);
if (isPostfix) {
int resultReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(isIncrement ? Opcodes.POST_AUTOINCREMENT : Opcodes.POST_AUTODECREMENT);
bytecodeCompiler.emitReg(resultReg);
bytecodeCompiler.emitReg(varReg);
bytecodeCompiler.lastResultReg = resultReg;
} else {
bytecodeCompiler.emit(isIncrement ? Opcodes.PRE_AUTOINCREMENT : Opcodes.PRE_AUTODECREMENT);
bytecodeCompiler.emitReg(varReg);
bytecodeCompiler.lastResultReg = varReg;
}
return;
}
}
// General case: recursively compile the lvalue
// Handles: $x++, $x[0]++, $x{key}++, $_[0]++, $obj->{field}++, etc.
node.operand.accept(bytecodeCompiler);
int operandReg = bytecodeCompiler.lastResultReg;
if (isPostfix) {
int resultReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(isIncrement ? Opcodes.POST_AUTOINCREMENT : Opcodes.POST_AUTODECREMENT);
bytecodeCompiler.emitReg(resultReg);
bytecodeCompiler.emitReg(operandReg);
bytecodeCompiler.lastResultReg = resultReg;
} else {
bytecodeCompiler.emit(isIncrement ? Opcodes.PRE_AUTOINCREMENT : Opcodes.PRE_AUTODECREMENT);
bytecodeCompiler.emitReg(operandReg);
bytecodeCompiler.lastResultReg = operandReg;
}
} else {
bytecodeCompiler.throwCompilerException("Increment/decrement operator requires operand");
}
} else if (op.equals("return")) {
// return $expr;
// Also handles 'goto &NAME' tail calls (parsed as 'return (coderef(@_))')
// Check if this is a 'goto &NAME' or 'goto EXPR' tail call
// Pattern: return with ListNode containing single BinaryOperatorNode("(")
// where left is OperatorNode("&") and right is @_
if (node.operand instanceof ListNode list && list.elements.size() == 1) {
Node firstElement = list.elements.getFirst();
if (firstElement instanceof BinaryOperatorNode callNode && callNode.operator.equals("(")) {
Node callTarget = callNode.left;
// Handle &sub syntax (goto &foo)
if (callTarget instanceof OperatorNode opNode && opNode.operator.equals("&")) {
// This is a tail call: goto &sub
int outerContext = bytecodeCompiler.currentCallContext;
// Evaluate the code reference in scalar context
bytecodeCompiler.compileNode(callTarget, -1, RuntimeContextType.SCALAR);
int codeRefReg = bytecodeCompiler.lastResultReg;
// Evaluate the arguments in list context (usually @_)
bytecodeCompiler.compileNode(callNode.right, -1, RuntimeContextType.LIST);
int argsReg = bytecodeCompiler.lastResultReg;
// Allocate register for call result
int rd = bytecodeCompiler.allocateOutputRegister();
// Emit CALL_SUB to invoke the code reference with proper context
bytecodeCompiler.emit(Opcodes.CALL_SUB);
bytecodeCompiler.emitReg(rd); // Result register
bytecodeCompiler.emitReg(codeRefReg); // Code reference register
bytecodeCompiler.emitReg(argsReg); // Arguments register
bytecodeCompiler.emit(outerContext); // Use outer calling context for the tail call
// Then return the result
bytecodeCompiler.emitWithToken(Opcodes.RETURN, node.getIndex());
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.lastResultReg = -1;
return;
}
}
}
if (node.operand != null) {
// Regular return with expression
node.operand.accept(bytecodeCompiler);
int exprReg = bytecodeCompiler.lastResultReg;
// Emit RETURN with expression register
bytecodeCompiler.emitWithToken(Opcodes.RETURN, node.getIndex());
bytecodeCompiler.emitReg(exprReg);
} else {
// return; (no value - return empty list/undef)
int undefReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_UNDEF);
bytecodeCompiler.emitReg(undefReg);
bytecodeCompiler.emitWithToken(Opcodes.RETURN, node.getIndex());
bytecodeCompiler.emitReg(undefReg);
}
bytecodeCompiler.lastResultReg = -1; // No result after return
} else if (op.equals("last") || op.equals("next") || op.equals("redo")) {
// Loop control operators: last/next/redo [LABEL]
bytecodeCompiler.handleLoopControlOperator(node, op);
bytecodeCompiler.lastResultReg = -1; // No result after control flow
} else if (op.equals("rand")) {
// rand() or rand($max)
// Calls Random.rand(max) where max defaults to 1
int rd = bytecodeCompiler.allocateOutputRegister();
if (node.operand != null) {
// rand($max) - evaluate operand
node.operand.accept(bytecodeCompiler);
int maxReg = bytecodeCompiler.lastResultReg;
// Emit RAND opcode
bytecodeCompiler.emit(Opcodes.RAND);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(maxReg);
} else {
// rand() with no argument - defaults to 1
int oneReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_INT);
bytecodeCompiler.emitReg(oneReg);
bytecodeCompiler.emitInt(1);
// Emit RAND opcode
bytecodeCompiler.emit(Opcodes.RAND);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(oneReg);
}
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("sleep")) {
// sleep $seconds
// Calls Time.sleep(seconds)
int rd = bytecodeCompiler.allocateOutputRegister();
if (node.operand != null) {
// sleep($seconds) - evaluate operand
node.operand.accept(bytecodeCompiler);
int secondsReg = bytecodeCompiler.lastResultReg;
// Emit direct opcode SLEEP_OP
bytecodeCompiler.emit(Opcodes.SLEEP_OP);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(secondsReg);
} else {
// sleep with no argument - defaults to infinity (but we'll use a large number)
int maxReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_INT);
bytecodeCompiler.emitReg(maxReg);
bytecodeCompiler.emitInt(Integer.MAX_VALUE);
bytecodeCompiler.emit(Opcodes.SLEEP_OP);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(maxReg);
}
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("alarm")) {
int rd = bytecodeCompiler.allocateOutputRegister();
if (node.operand != null) {
node.operand.accept(bytecodeCompiler);
int argReg = bytecodeCompiler.lastResultReg;
bytecodeCompiler.emit(Opcodes.ALARM_OP);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(argReg);
} else {
int zeroReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_INT);
bytecodeCompiler.emitReg(zeroReg);
bytecodeCompiler.emitInt(0);
bytecodeCompiler.emit(Opcodes.ALARM_OP);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(zeroReg);
}
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("study")) {
// study $var
// In modern Perl, study is a no-op that always returns true
// We evaluate the operand for side effects, then return 1
if (node.operand != null) {
// Evaluate operand for side effects (though typically there are none)
node.operand.accept(bytecodeCompiler);
}
// Return 1 (true)
int rd = bytecodeCompiler.allocateOutputRegister();
bytecodeCompiler.emit(Opcodes.LOAD_INT);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitInt(1);
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("require")) {
// require MODULE_NAME or require VERSION
bytecodeCompiler.compileNode(node.operand, -1, RuntimeContextType.SCALAR);
int operandReg = bytecodeCompiler.lastResultReg;
int rd = bytecodeCompiler.allocateOutputRegister();
bytecodeCompiler.emit(Opcodes.REQUIRE);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(operandReg);
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("pos")) {
// pos($var) - get or set regex match position
bytecodeCompiler.compileNode(node.operand, -1, RuntimeContextType.SCALAR);
int operandReg = bytecodeCompiler.lastResultReg;
int rd = bytecodeCompiler.allocateOutputRegister();
bytecodeCompiler.emit(Opcodes.POS);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(operandReg);
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("index") || op.equals("rindex")) {
// index(str, substr, pos?) or rindex(str, substr, pos?)
if (node.operand instanceof ListNode args) {
if (args.elements.isEmpty()) {
bytecodeCompiler.throwCompilerException("Not enough arguments for " + op);
}
bytecodeCompiler.compileNode(args.elements.get(0), -1, RuntimeContextType.SCALAR);
int strReg = bytecodeCompiler.lastResultReg;
if (args.elements.size() < 2) {
bytecodeCompiler.throwCompilerException("Not enough arguments for " + op);
}
bytecodeCompiler.compileNode(args.elements.get(1), -1, RuntimeContextType.SCALAR);
int substrReg = bytecodeCompiler.lastResultReg;
int posReg;
if (args.elements.size() >= 3) {
bytecodeCompiler.compileNode(args.elements.get(2), -1, RuntimeContextType.SCALAR);
posReg = bytecodeCompiler.lastResultReg;
} else {
posReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_UNDEF);
bytecodeCompiler.emitReg(posReg);
}
int rd = bytecodeCompiler.allocateOutputRegister();
bytecodeCompiler.emit(op.equals("index") ? Opcodes.INDEX : Opcodes.RINDEX);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(strReg);
bytecodeCompiler.emitReg(substrReg);
bytecodeCompiler.emitReg(posReg);
bytecodeCompiler.lastResultReg = rd;
} else {
bytecodeCompiler.throwCompilerException(op + " requires a list of arguments");
}
} else if (op.equals("stat") || op.equals("lstat")) {
// stat FILE or lstat FILE
boolean isUnderscoreOperand = (node.operand instanceof IdentifierNode)
&& ((IdentifierNode) node.operand).name.equals("_");
if (isUnderscoreOperand) {
int rd = bytecodeCompiler.allocateOutputRegister();
bytecodeCompiler.emit(op.equals("stat") ? Opcodes.STAT_LASTHANDLE : Opcodes.LSTAT_LASTHANDLE);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emit(bytecodeCompiler.currentCallContext);
bytecodeCompiler.lastResultReg = rd;
} else {
int outerContext = bytecodeCompiler.currentCallContext;
bytecodeCompiler.compileNode(node.operand, -1, RuntimeContextType.SCALAR);
int operandReg = bytecodeCompiler.lastResultReg;
int rd = bytecodeCompiler.allocateOutputRegister();
bytecodeCompiler.emit(op.equals("stat") ? Opcodes.STAT : Opcodes.LSTAT);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(operandReg);
bytecodeCompiler.emit(outerContext);
bytecodeCompiler.lastResultReg = rd;
}
} else if (op.startsWith("-") && op.length() == 2) {
// File test operators: -r, -w, -x, etc.
// Check if operand is the special filehandle "_"
boolean isUnderscoreOperand = (node.operand instanceof IdentifierNode)
&& ((IdentifierNode) node.operand).name.equals("_");
if (isUnderscoreOperand) {
// Special case: -r _ uses cached file handle
// Call FileTestOperator.fileTestLastHandle(String)
int rd = bytecodeCompiler.allocateOutputRegister();
int operatorStrIndex = bytecodeCompiler.addToStringPool(op);
// Emit FILETEST_LASTHANDLE opcode
bytecodeCompiler.emit(Opcodes.FILETEST_LASTHANDLE);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emit(operatorStrIndex);
bytecodeCompiler.lastResultReg = rd;
} else {
// Normal case: evaluate operand and test it
bytecodeCompiler.compileNode(node.operand, -1, RuntimeContextType.SCALAR);
int operandReg = bytecodeCompiler.lastResultReg;
int rd = bytecodeCompiler.allocateOutputRegister();
// Map operator to opcode
char testChar = op.charAt(1);
short opcode;
switch (testChar) {
case 'r':
opcode = Opcodes.FILETEST_R;
break;
case 'w':
opcode = Opcodes.FILETEST_W;
break;
case 'x':
opcode = Opcodes.FILETEST_X;
break;
case 'o':
opcode = Opcodes.FILETEST_O;
break;
case 'R':
opcode = Opcodes.FILETEST_R_REAL;
break;
case 'W':
opcode = Opcodes.FILETEST_W_REAL;
break;
case 'X':
opcode = Opcodes.FILETEST_X_REAL;
break;
case 'O':
opcode = Opcodes.FILETEST_O_REAL;
break;
case 'e':
opcode = Opcodes.FILETEST_E;
break;
case 'z':
opcode = Opcodes.FILETEST_Z;
break;
case 's':
opcode = Opcodes.FILETEST_S;
break;
case 'f':
opcode = Opcodes.FILETEST_F;
break;
case 'd':
opcode = Opcodes.FILETEST_D;
break;
case 'l':
opcode = Opcodes.FILETEST_L;
break;
case 'p':
opcode = Opcodes.FILETEST_P;
break;
case 'S':
opcode = Opcodes.FILETEST_S_UPPER;
break;
case 'b':
opcode = Opcodes.FILETEST_B;
break;
case 'c':
opcode = Opcodes.FILETEST_C;
break;
case 't':
opcode = Opcodes.FILETEST_T;
break;
case 'u':
opcode = Opcodes.FILETEST_U;
break;
case 'g':
opcode = Opcodes.FILETEST_G;
break;
case 'k':
opcode = Opcodes.FILETEST_K;
break;
case 'T':
opcode = Opcodes.FILETEST_T_UPPER;
break;
case 'B':
opcode = Opcodes.FILETEST_B_UPPER;
break;
case 'M':
opcode = Opcodes.FILETEST_M;
break;
case 'A':
opcode = Opcodes.FILETEST_A;
break;
case 'C':
opcode = Opcodes.FILETEST_C_UPPER;
break;
default:
bytecodeCompiler.throwCompilerException("Unsupported file test operator: " + op);
return;
}
bytecodeCompiler.emit(opcode);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(operandReg);
bytecodeCompiler.lastResultReg = rd;
}
} else if (op.equals("die")) {
// die $message;
if (node.operand != null) {
// Evaluate die message
node.operand.accept(bytecodeCompiler);
int msgReg = bytecodeCompiler.lastResultReg;
// Precompute location message at compile time (zero overhead!)
String locationMsg;
// Use annotation from AST node which has the correct line number
Object lineObj = node.getAnnotation("line");
Object fileObj = node.getAnnotation("file");
if (lineObj != null && fileObj != null) {
String fileName = fileObj.toString();
int lineNumber = Integer.parseInt(lineObj.toString());
locationMsg = " at " + fileName + " line " + lineNumber;
} else if (bytecodeCompiler.errorUtil != null) {
// Fallback to errorUtil if annotations not available
String fileName = bytecodeCompiler.errorUtil.getFileName();
int lineNumber = bytecodeCompiler.errorUtil.getLineNumberAccurate(node.getIndex());
locationMsg = " at " + fileName + " line " + lineNumber;
} else {
// Final fallback if neither available
locationMsg = " at " + bytecodeCompiler.sourceName + " line " + bytecodeCompiler.sourceLine;
}
int locationReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_STRING);
bytecodeCompiler.emitReg(locationReg);
bytecodeCompiler.emit(bytecodeCompiler.addToStringPool(locationMsg));
// Emit DIE with both message and precomputed location
bytecodeCompiler.emitWithToken(Opcodes.DIE, node.getIndex());
bytecodeCompiler.emitReg(msgReg);
bytecodeCompiler.emitReg(locationReg);
} else {
// die; (no message - use $@)
// For now, emit with undef register
int undefReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_UNDEF);
bytecodeCompiler.emitReg(undefReg);
// Precompute location message for bare die
String locationMsg;
if (bytecodeCompiler.errorUtil != null) {
String fileName = bytecodeCompiler.errorUtil.getFileName();
int lineNumber = bytecodeCompiler.errorUtil.getLineNumber(node.getIndex());
locationMsg = " at " + fileName + " line " + lineNumber;
} else {
locationMsg = " at " + bytecodeCompiler.sourceName + " line " + bytecodeCompiler.sourceLine;
}
int locationReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_STRING);
bytecodeCompiler.emitReg(locationReg);
bytecodeCompiler.emitInt(bytecodeCompiler.addToStringPool(locationMsg));
bytecodeCompiler.emitWithToken(Opcodes.DIE, node.getIndex());
bytecodeCompiler.emitReg(undefReg);
bytecodeCompiler.emitReg(locationReg);
}
bytecodeCompiler.lastResultReg = -1; // No result after die
} else if (op.equals("warn")) {
// warn $message;
if (node.operand != null) {
// Evaluate warn message
node.operand.accept(bytecodeCompiler);
int msgReg = bytecodeCompiler.lastResultReg;
// Precompute location message at compile time
String locationMsg;
// Use annotation from AST node which has the correct line number
Object lineObj = node.getAnnotation("line");
Object fileObj = node.getAnnotation("file");
if (lineObj != null && fileObj != null) {
String fileName = fileObj.toString();
int lineNumber = Integer.parseInt(lineObj.toString());
locationMsg = " at " + fileName + " line " + lineNumber;
} else if (bytecodeCompiler.errorUtil != null) {
// Fallback to errorUtil if annotations not available
String fileName = bytecodeCompiler.errorUtil.getFileName();
int lineNumber = bytecodeCompiler.errorUtil.getLineNumberAccurate(node.getIndex());
locationMsg = " at " + fileName + " line " + lineNumber;
} else {
// Final fallback if neither available
locationMsg = " at " + bytecodeCompiler.sourceName + " line " + bytecodeCompiler.sourceLine;
}
int locationReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_STRING);
bytecodeCompiler.emitReg(locationReg);
bytecodeCompiler.emit(bytecodeCompiler.addToStringPool(locationMsg));
// Emit WARN with both message and precomputed location
bytecodeCompiler.emitWithToken(Opcodes.WARN, node.getIndex());
bytecodeCompiler.emitReg(msgReg);
bytecodeCompiler.emitReg(locationReg);
} else {
// warn; (no message - use $@)
int undefReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_UNDEF);
bytecodeCompiler.emitReg(undefReg);
// Precompute location message for bare warn
String locationMsg;
if (bytecodeCompiler.errorUtil != null) {
String fileName = bytecodeCompiler.errorUtil.getFileName();
int lineNumber = bytecodeCompiler.errorUtil.getLineNumber(node.getIndex());
locationMsg = " at " + fileName + " line " + lineNumber;
} else {
locationMsg = " at " + bytecodeCompiler.sourceName + " line " + bytecodeCompiler.sourceLine;
}
int locationReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_STRING);
bytecodeCompiler.emitReg(locationReg);
bytecodeCompiler.emitInt(bytecodeCompiler.addToStringPool(locationMsg));
bytecodeCompiler.emitWithToken(Opcodes.WARN, node.getIndex());
bytecodeCompiler.emitReg(undefReg);
bytecodeCompiler.emitReg(locationReg);
}
// warn returns 1 (true) in Perl
int resultReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_INT);
bytecodeCompiler.emitReg(resultReg);
bytecodeCompiler.emitInt(1);
bytecodeCompiler.lastResultReg = resultReg;
} else if (op.equals("eval") || op.equals("evalbytes")) {
// eval $string; / evalbytes $string;
if (node.operand != null) {
node.operand.accept(bytecodeCompiler);
int stringReg = bytecodeCompiler.lastResultReg;
int rd = bytecodeCompiler.allocateOutputRegister();
// Snapshot visible variables and pragma flags for this eval site
int evalSiteIndex = bytecodeCompiler.evalSiteRegistries.size();
bytecodeCompiler.evalSiteRegistries.add(
bytecodeCompiler.symbolTable.getVisibleVariableRegistry());
bytecodeCompiler.evalSitePragmaFlags.add(new int[]{
bytecodeCompiler.symbolTable.strictOptionsStack.peek(),
bytecodeCompiler.symbolTable.featureFlagsStack.peek()
});
bytecodeCompiler.emitWithToken(Opcodes.EVAL_STRING, node.getIndex());
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(stringReg);
bytecodeCompiler.emit(bytecodeCompiler.currentCallContext);
bytecodeCompiler.emit(evalSiteIndex);
bytecodeCompiler.lastResultReg = rd;
} else {
// eval; (no operand - return undef)
int undefReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_UNDEF);
bytecodeCompiler.emitReg(undefReg);
bytecodeCompiler.lastResultReg = undefReg;
}
} else if (op.equals("select")) {
// select FILEHANDLE or select()
// SELECT is a fast opcode (used in every print statement)
// Format: [SELECT] [rd] [rs_list]
// Effect: rd = IOOperator.select(registers[rs_list], SCALAR)
int rd = bytecodeCompiler.allocateOutputRegister();
boolean hasArgs = node.operand instanceof ListNode ln && !ln.elements.isEmpty();
if (hasArgs) {
// select FILEHANDLE or select(RBITS,WBITS,EBITS,TIMEOUT) with arguments
node.operand.accept(bytecodeCompiler);
int listReg = bytecodeCompiler.lastResultReg;
bytecodeCompiler.emitWithToken(Opcodes.SELECT, node.getIndex());
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(listReg);
} else {
// select() with no arguments (or empty ListNode from print-without-filehandle)
// Must emit CREATE_LIST so SELECT receives a RuntimeList, not a RuntimeScalar
int listReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.CREATE_LIST);
bytecodeCompiler.emitReg(listReg);
bytecodeCompiler.emit(0); // count = 0
bytecodeCompiler.emitWithToken(Opcodes.SELECT, node.getIndex());
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(listReg);
}
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("undef")) {
if (node.operand != null) {
node.operand.accept(bytecodeCompiler);
int operandReg = bytecodeCompiler.lastResultReg;
bytecodeCompiler.emit(Opcodes.UNDEFINE_SCALAR);
bytecodeCompiler.emitReg(operandReg);
int undefReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_UNDEF);
bytecodeCompiler.emitReg(undefReg);
bytecodeCompiler.lastResultReg = undefReg;
} else {
int undefReg = bytecodeCompiler.allocateRegister();
bytecodeCompiler.emit(Opcodes.LOAD_UNDEF);
bytecodeCompiler.emitReg(undefReg);
bytecodeCompiler.lastResultReg = undefReg;
}
} else if (op.equals("unaryMinus")) {
// Unary minus: -$x
// Compile operand in scalar context (negation always produces a scalar)
bytecodeCompiler.compileNode(node.operand, -1, RuntimeContextType.SCALAR);
int operandReg = bytecodeCompiler.lastResultReg;
int rd = bytecodeCompiler.allocateOutputRegister();
bytecodeCompiler.emit(Opcodes.NEG_SCALAR);
bytecodeCompiler.emitReg(rd);
bytecodeCompiler.emitReg(operandReg);
bytecodeCompiler.lastResultReg = rd;
} else if (op.equals("pop")) {
// Array pop: $x = pop @array or $x = pop @$ref
// operand: OperatorNode("@", ...) directly (default @_/@ARGV injected by parser)
// or ListNode containing OperatorNode("@", IdentifierNode or OperatorNode)
if (node.operand == null) {
bytecodeCompiler.throwCompilerException("pop requires array argument");
}
OperatorNode arrayOp;
if (node.operand instanceof OperatorNode directOp && directOp.operator.equals("@")) {
// Direct OperatorNode("@", ...) - default array case
arrayOp = directOp;
} else if (node.operand instanceof ListNode list && !list.elements.isEmpty()
&& list.elements.get(0) instanceof OperatorNode listOp
&& listOp.operator.equals("@")) {
// ListNode-wrapped OperatorNode("@", ...) - explicit array case
arrayOp = listOp;
} else {
bytecodeCompiler.throwCompilerException("pop requires array variable: pop @array");
return;
}
int arrayReg = -1; // Will be assigned in if/else blocks
if (arrayOp.operand instanceof IdentifierNode) {
// pop @array
String varName = "@" + ((IdentifierNode) arrayOp.operand).name;
// Get the array - check lexical first, then global
if (bytecodeCompiler.hasVariable(varName)) {
// Lexical array
arrayReg = bytecodeCompiler.getVariableRegister(varName);
} else {
// Global array - load it
arrayReg = bytecodeCompiler.allocateRegister();
String globalArrayName = NameNormalizer.normalizeVariableName(((IdentifierNode) arrayOp.operand).name, bytecodeCompiler.getCurrentPackage());
int nameIdx = bytecodeCompiler.addToStringPool(globalArrayName);
bytecodeCompiler.emit(Opcodes.LOAD_GLOBAL_ARRAY);
bytecodeCompiler.emitReg(arrayReg);
bytecodeCompiler.emit(nameIdx);
}
} else if (arrayOp.operand instanceof OperatorNode) {
// pop @$ref - dereference first
arrayOp.operand.accept(bytecodeCompiler);
int refReg = bytecodeCompiler.lastResultReg;