-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathOperatorParser.java
More file actions
1388 lines (1241 loc) · 66.1 KB
/
OperatorParser.java
File metadata and controls
1388 lines (1241 loc) · 66.1 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.frontend.parser;
import org.perlonjava.app.cli.CompilerOptions;
import org.perlonjava.backend.jvm.EmitterContext;
import org.perlonjava.backend.jvm.EmitterMethodCreator;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.frontend.lexer.LexerToken;
import org.perlonjava.runtime.operators.WarnDie;
import org.perlonjava.runtime.perlmodule.Strict;
import org.perlonjava.runtime.mro.InheritanceResolver;
import org.perlonjava.runtime.perlmodule.Universal;
import org.perlonjava.runtime.runtimetypes.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.perlonjava.frontend.lexer.LexerTokenType.*;
import static org.perlonjava.frontend.parser.NumberParser.parseNumber;
import static org.perlonjava.frontend.parser.ParserNodeUtils.*;
import static org.perlonjava.frontend.parser.SubroutineParser.consumeAttributes;
import static org.perlonjava.frontend.parser.TokenUtils.consume;
import static org.perlonjava.frontend.parser.TokenUtils.peek;
/**
* This class provides methods for parsing various Perl operators and constructs.
*/
public class OperatorParser {
/**
* Parses the 'do' operator.
*
* @param parser The Parser instance.
* @return A Node representing the parsed 'do' operator.
*/
static Node parseDoOperator(Parser parser) {
LexerToken token;
Node block;
// Handle 'do' keyword which can be followed by a block or filename
token = TokenUtils.peek(parser);
if (token.type == OPERATOR && token.text.equals("{")) {
TokenUtils.consume(parser, OPERATOR, "{");
boolean parsingTakeReference = parser.parsingTakeReference;
parser.parsingTakeReference = false;
block = ParseBlock.parseBlock(parser);
parser.parsingTakeReference = parsingTakeReference;
TokenUtils.consume(parser, OPERATOR, "}");
return block;
}
// `do` file
Node operand = ListParser.parseZeroOrOneList(parser, 1);
return new OperatorNode("doFile", operand, parser.tokenIndex);
}
/**
* Parses the 'eval' operator.
*
* @param parser The Parser instance.
* @return An AbstractNode representing the parsed 'eval' operator.
*/
static AbstractNode parseEval(Parser parser, String operator) {
Node block;
Node operand;
LexerToken token;
// Handle 'eval' keyword which can be followed by a block or an expression
token = TokenUtils.peek(parser);
var index = parser.tokenIndex;
if (token.type == OPERATOR && token.text.equals("{")) {
// If the next token is '{', parse a block
TokenUtils.consume(parser, OPERATOR, "{");
// Set subroutine context to "(eval)" BEFORE parsing the block
// This ensures source locations are saved with the correct context
String previousSubroutine = parser.ctx.symbolTable.getCurrentSubroutine();
parser.ctx.symbolTable.setCurrentSubroutine("(eval)");
try {
block = ParseBlock.parseBlock(parser);
} finally {
parser.ctx.symbolTable.setCurrentSubroutine(previousSubroutine);
}
TokenUtils.consume(parser, OPERATOR, "}");
// Perl semantics: eval BLOCK behaves like a bare block for loop control.
// `last/next/redo` inside the eval block must target the eval block itself,
// not escape as non-local control flow.
if (block instanceof BlockNode blockNode) {
blockNode.isLoop = true;
}
// transform: eval { 123 }
// into: sub { 123 }->() with useTryCatch flag
// Use name "(eval)" so caller() reports this as an eval block (Perl behavior)
return new BinaryOperatorNode("->",
new SubroutineNode("(eval)", null, null, block, true, parser.tokenIndex), ParserNodeUtils.atUnderscoreArgs(parser), index);
} else {
// Otherwise, parse an expression, and default to $_
operand = ListParser.parseZeroOrOneList(parser, 0);
if (((ListNode) operand).elements.isEmpty()) {
// create `$_` variable
operand = ParserNodeUtils.scalarUnderscore(parser);
}
}
return new EvalOperatorNode(
operator,
operand,
parser.ctx.symbolTable.snapShot(), // Freeze the scoped symbol table for the eval context
index);
}
/**
* Parses the diamond operator (<>).
*
* @param parser The Parser instance.
* @param token The current LexerToken.
* @return A Node representing the parsed diamond operator.
*/
static Node parseDiamondOperator(Parser parser, LexerToken token) {
// Save the current token index to restore later if needed
int currentTokenIndex = parser.tokenIndex;
if (token.text.equals("<")) {
LexerToken operand = parser.tokens.get(parser.tokenIndex);
String tokenText = operand.text;
// Check if the token looks like a Bareword file handle
if (operand.type == IDENTIFIER) {
Node fileHandle = FileHandle.parseFileHandle(parser);
if (fileHandle != null) {
if (parser.tokens.get(parser.tokenIndex).text.equals(">")) {
TokenUtils.consume(parser); // Consume the '>' token
// Return a BinaryOperatorNode representing a readline operation
return new BinaryOperatorNode("readline",
fileHandle,
new ListNode(parser.tokenIndex), parser.tokenIndex);
}
}
}
// Check if the token is a dollar sign, indicating a variable
if (tokenText.equals("$")) {
// Handle the case for <$fh>
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("diamond operator " + token.text + parser.tokens.get(parser.tokenIndex));
parser.tokenIndex++;
Node var = Variable.parseVariable(parser, "$"); // Parse the variable following the dollar sign
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("diamond operator var " + var);
// Check if the next token is a closing angle bracket
if (parser.tokens.get(parser.tokenIndex).text.equals(">")) {
TokenUtils.consume(parser); // Consume the '>' token
// Return a BinaryOperatorNode representing a readline operation
return new BinaryOperatorNode("readline",
var,
new ListNode(parser.tokenIndex), parser.tokenIndex);
}
}
// Restore the token index
parser.tokenIndex = currentTokenIndex;
// Check if the token is one of the standard input sources
if (tokenText.equals("STDIN") || tokenText.equals("DATA") || tokenText.equals("ARGV")) {
// Handle the case for <STDIN>, <DATA>, or <ARGV>
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("diamond operator " + token.text + parser.tokens.get(parser.tokenIndex));
parser.tokenIndex++;
// Check if the next token is a closing angle bracket
if (parser.tokens.get(parser.tokenIndex).text.equals(">")) {
TokenUtils.consume(parser); // Consume the '>' token
// Return a BinaryOperatorNode representing a readline operation
return new BinaryOperatorNode("readline",
new IdentifierNode("main::" + tokenText, currentTokenIndex),
new ListNode(parser.tokenIndex), parser.tokenIndex);
}
}
}
// Restore the token index
parser.tokenIndex = currentTokenIndex;
if (token.text.equals("<<")) {
String tokenText = parser.tokens.get(parser.tokenIndex).text;
if (!tokenText.equals(">>")) {
return ParseHeredoc.parseHeredoc(parser, tokenText);
}
}
// Handle other cases like <>, <<>>, or <*.*> by parsing as a raw string
return StringParser.parseRawString(parser, token.text);
}
static BinaryOperatorNode parsePrint(Parser parser, LexerToken token, int currentIndex) {
Node handle;
ListNode operand;
parser.debugHeredocState("PRINT_START");
try {
operand = ListParser.parseZeroOrMoreList(parser, 0, false, true, true, false);
parser.debugHeredocState("PRINT_PARSE_SUCCESS");
} catch (PerlCompilerException e) {
parser.debugHeredocState("PRINT_BEFORE_BACKTRACK");
// print $fh (1,2,3)
parser.tokenIndex = currentIndex;
parser.debugHeredocState("PRINT_AFTER_BACKTRACK");
boolean paren = false;
if (peek(parser).text.equals("(")) {
TokenUtils.consume(parser);
paren = true;
}
parser.parsingForLoopVariable = true;
Node var = ParsePrimary.parsePrimary(parser);
parser.parsingForLoopVariable = false;
operand = ListParser.parseZeroOrMoreList(parser, 1, false, false, false, false);
operand.handle = var;
if (paren) {
TokenUtils.consume(parser, OPERATOR, ")");
}
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("parsePrint: " + operand.handle + " : " + operand);
}
handle = operand.handle;
operand.handle = null;
if (handle == null) {
// `print` without arguments means `print to last selected filehandle`
handle = new OperatorNode("select", new ListNode(currentIndex), currentIndex);
}
if (operand.elements.isEmpty()) {
// `print` without arguments means `print $_`
operand.elements.add(
ParserNodeUtils.scalarUnderscore(parser)
);
}
return new BinaryOperatorNode(token.text, handle, operand, currentIndex);
}
private static void addVariableToScope(EmitterContext ctx, String operator, OperatorNode node) {
String sigil = node.operator;
if ("$@%".contains(sigil)) {
// not "undef"
Node identifierNode = node.operand;
if (identifierNode instanceof IdentifierNode) { // my $a
String name = ((IdentifierNode) identifierNode).name;
String var = sigil + name;
// Check for redeclaration warnings
if (operator.equals("our")) {
// For 'our', only warn if redeclared in the same package (matching Perl behavior)
if (ctx.symbolTable.isOurVariableRedeclaredInSamePackage(var)) {
System.err.println(
ctx.errorUtil.errorMessage(node.getIndex(),
"\"our\" variable " + var + " redeclared"));
}
} else {
// For 'my'/'local', warn if redeclared in the same scope
if (ctx.symbolTable.getVariableIndexInCurrentScope(var) != -1) {
System.err.println(
ctx.errorUtil.errorMessage(node.getIndex(),
"\"" + operator + "\" variable " + var + " masks earlier declaration in same scope"));
}
}
int varIndex = ctx.symbolTable.addVariable(var, operator, node);
// Note: the isDeclaredReference flag is stored in node.annotations
// and will be used during code generation
}
}
}
static OperatorNode parseVariableDeclaration(Parser parser, String operator, int currentIndex) {
String varType = null;
if (peek(parser).type == IDENTIFIER) {
String tokenText = peek(parser).text;
// Handle 'my __PACKAGE__ $var' and 'my __CLASS__ $var' syntax.
// __PACKAGE__ is a compile-time constant that resolves to the current
// package name when used as a type annotation in variable declarations.
if (tokenText.equals("__PACKAGE__") || tokenText.equals("__CLASS__")) {
TokenUtils.consume(parser); // consume __PACKAGE__/__CLASS__
varType = parser.ctx.symbolTable.getCurrentPackage();
} else {
// If a package name follows, then it is a type declaration
int currentIndex2 = parser.tokenIndex;
String packageName = IdentifierParser.parseSubroutineIdentifier(parser);
boolean packageExists = GlobalVariable.isPackageLoaded(packageName);
// System.out.println("maybe type: " + packageName + " " + packageExists);
if (packageExists) {
varType = packageName;
} else {
// Backtrack
parser.tokenIndex = currentIndex2;
}
}
}
// Check if this is a declared reference (my \$x, our \@array, etc.)
boolean isDeclaredReference = false;
if (peek(parser).type == OPERATOR && peek(parser).text.equals("\\")) {
isDeclaredReference = true;
// Check if declared_refs feature is enabled
if (!parser.ctx.symbolTable.isFeatureCategoryEnabled("declared_refs")) {
throw new PerlCompilerException(
currentIndex,
"The experimental declared_refs feature is not enabled",
parser.ctx.errorUtil
);
}
// Emit experimental warning if warnings are enabled
if (parser.ctx.symbolTable.isWarningCategoryEnabled("experimental::declared_refs")) {
// Use WarnDie.warn to respect $SIG{__WARN__} handler
try {
WarnDie.warn(
new RuntimeScalar("Declaring references is experimental"),
new RuntimeScalar(parser.ctx.errorUtil.warningLocation(currentIndex))
);
} catch (Exception e) {
// If warning system isn't initialized yet, fall back to System.err
System.err.println("Declaring references is experimental" + parser.ctx.errorUtil.warningLocation(currentIndex) + ".");
}
}
TokenUtils.consume(parser, OPERATOR, "\\");
}
// Create OperatorNode ($, @, %), ListNode (includes undef), SubroutineNode
// Suppress strict vars check while parsing the variable being declared
boolean savedParsingDeclaration = parser.parsingDeclaration;
parser.parsingDeclaration = true;
Node operand = ParsePrimary.parsePrimary(parser);
parser.parsingDeclaration = savedParsingDeclaration;
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("parseVariableDeclaration " + operator + ": " + operand + " (ref=" + isDeclaredReference + ")");
// Add variables to the scope
if (operand instanceof ListNode listNode) { // my ($a, $b) our ($a, $b)
// process each item of the list; then returns the list
List<Node> transformedElements = new ArrayList<>();
boolean hasTransformation = false;
for (int i = 0; i < listNode.elements.size(); i++) {
Node element = listNode.elements.get(i);
if (element instanceof OperatorNode operandNode) {
// Check if this element is a reference operator (backslash)
// This handles cases like my(\$x) where the backslash is inside the parentheses
if (operandNode.operator.equals("\\") && operandNode.operand instanceof OperatorNode varNode) {
// This is a declared reference inside parentheses: my(\$x), my(\@arr), my(\%hash)
// Check if declared_refs feature is enabled
if (!parser.ctx.symbolTable.isFeatureCategoryEnabled("declared_refs")) {
throw new PerlCompilerException(
operandNode.tokenIndex,
"The experimental declared_refs feature is not enabled",
parser.ctx.errorUtil
);
}
// Emit experimental warning if warnings are enabled
if (parser.ctx.symbolTable.isWarningCategoryEnabled("experimental::declared_refs")) {
// Use WarnDie.warn to respect $SIG{__WARN__} handler
try {
WarnDie.warn(
new RuntimeScalar("Declaring references is experimental"),
new RuntimeScalar(parser.ctx.errorUtil.warningLocation(operandNode.tokenIndex))
);
} catch (Exception e) {
// If warning system isn't initialized yet, fall back to System.err
System.err.println("Declaring references is experimental" + parser.ctx.errorUtil.warningLocation(operandNode.tokenIndex) + ".");
}
}
// Declared references always create scalar variables
// Convert the variable to a scalar if it's an array or hash
OperatorNode scalarVarNode = varNode;
if (varNode.operator.equals("@") || varNode.operator.equals("%")) {
// Create a scalar version of the variable
scalarVarNode = new OperatorNode("$", varNode.operand, varNode.tokenIndex);
}
scalarVarNode.setAnnotation("isDeclaredReference", true);
scalarVarNode.setAnnotation("declaredReferenceOriginalSigil", varNode.operator);
addVariableToScope(parser.ctx, operator, scalarVarNode);
// Also mark the original nodes
varNode.setAnnotation("isDeclaredReference", true);
operandNode.setAnnotation("isDeclaredReference", true);
// Transform the AST: replace \@arr with $arr in the list
transformedElements.add(scalarVarNode);
hasTransformation = true;
} else {
if (isDeclaredReference) {
operandNode.setAnnotation("isDeclaredReference", true);
}
addVariableToScope(parser.ctx, operator, operandNode);
transformedElements.add(element);
}
} else {
transformedElements.add(element);
}
}
// If we transformed any elements, replace the list elements
if (hasTransformation) {
listNode.elements.clear();
listNode.elements.addAll(transformedElements);
}
} else if (operand instanceof OperatorNode operandNode) {
if (operator.equals("state")) {
// Give the variable a persistent id (See: PersistentVariable.java)
if (operandNode.id == 0) {
operandNode.id = EmitterMethodCreator.classCounter++;
}
}
if (isDeclaredReference) {
operandNode.setAnnotation("isDeclaredReference", true);
}
addVariableToScope(parser.ctx, operator, operandNode);
}
OperatorNode decl = new OperatorNode(operator, operand, currentIndex);
if (isDeclaredReference) {
decl.setAnnotation("isDeclaredReference", true);
}
// Initialize a list to store any attributes the declaration might have.
List<String> attributes = new ArrayList<>();
// While there are attributes (denoted by a colon ':'), we keep parsing them.
while (peek(parser).text.equals(":")) {
consumeAttributes(parser, attributes);
}
// Detect scalar/array/hash dereferences in my/our/state declarations.
// E.g., "our ${""}", "my $$foo" — these are dereferences, not simple variables.
// Perl 5: "Can't declare scalar dereference in 'our'" etc.
if (!attributes.isEmpty() || peek(parser).text.equals("=") || peek(parser).text.equals(";")) {
checkForDereference(parser, operator, operand);
}
if (!attributes.isEmpty()) {
// Determine the package for MODIFY_*_ATTRIBUTES lookup
String attrPackage = varType != null ? varType : parser.ctx.symbolTable.getCurrentPackage();
// Validate and dispatch variable attributes.
// For 'our': dispatch at compile time (global vars already exist).
// For 'my'/'state': validate at compile time, dispatch at runtime
// (the actual lexical variable doesn't exist yet during parsing).
callModifyVariableAttributes(parser, attrPackage, operator, operand, attributes);
// Add the attributes and package to the operand annotations
// so the emitter can dispatch at runtime for my/state variables.
java.util.Map<String, Object> newAnnotations;
if (decl.annotations != null) {
newAnnotations = new java.util.HashMap<>(decl.annotations);
} else {
newAnnotations = new java.util.HashMap<>();
}
newAnnotations.put("attributes", attributes);
newAnnotations.put("attributePackage", attrPackage);
decl.annotations = newAnnotations;
}
return decl;
}
/**
* Check if a variable in a my/our/state declaration is actually a dereference.
* E.g., "our ${""}", "my $$foo" — Perl 5 errors with:
* "Can't declare scalar dereference in 'our'" etc.
*/
private static void checkForDereference(Parser parser, String operator, Node operand) {
if (!(operand instanceof OperatorNode opNode)) return;
String sigil = opNode.operator;
if (!"$@%".contains(sigil)) return;
// A simple variable has IdentifierNode as operand.
// A dereference has OperatorNode, BlockNode, etc.
if (opNode.operand instanceof IdentifierNode) return;
String typeName = switch (sigil) {
case "$" -> "scalar";
case "@" -> "array";
case "%" -> "hash";
default -> "scalar";
};
throw new PerlCompilerException(
opNode.tokenIndex,
"Can't declare " + typeName + " dereference in \"" + operator + "\"",
parser.ctx.errorUtil
);
}
static OperatorNode parseOperatorWithOneOptionalArgument(Parser parser, LexerToken token) {
Node operand;
// Handle operators with one optional argument
String text = token.text;
operand = ListParser.parseZeroOrOneList(parser, 0);
if (((ListNode) operand).elements.isEmpty()) {
switch (text) {
case "sleep":
operand = new NumberNode(Long.toString(Long.MAX_VALUE), parser.tokenIndex);
break;
case "pop":
case "shift":
// create `@_` variable
// in main program, use `@ARGV`
boolean isSub = parser.ctx.symbolTable.isInSubroutineBody();
operand = isSub ? atUnderscore(parser) : atArgv(parser);
break;
case "localtime":
case "gmtime":
case "caller":
case "reset":
case "select":
// default to empty list
break;
case "srand":
operand = new OperatorNode("undef", null, parser.tokenIndex);
break;
case "exit":
// create "0"
operand = new NumberNode("0", parser.tokenIndex);
break;
case "undef":
operand = null;
break; // leave it empty
case "rand":
// create "1"
operand = new NumberNode("1", parser.tokenIndex);
break;
default:
// create `$_` variable
operand = ParserNodeUtils.scalarUnderscore(parser);
break;
}
}
return new OperatorNode(text, operand, parser.tokenIndex);
}
public static OperatorNode parseSelect(Parser parser, LexerToken token, int currentIndex) {
// Handle 'select' operator with two different syntaxes:
// 1. select FILEHANDLE or select (returns/sets current filehandle)
// 2. select RBITS,WBITS,EBITS,TIMEOUT (syscall)
ListNode listNode1 = ListParser.parseZeroOrMoreList(parser, 0, false, true, false, false);
int argCount = listNode1.elements.size();
if (argCount == 1) {
// select FILEHANDLE
if (listNode1.elements.getFirst() instanceof IdentifierNode identifierNode) {
// Autovivify the filehandle IO slot so parseBarewordHandle succeeds
GlobalVariable.getGlobalIO(FileHandle.normalizeBarewordHandle(parser, identifierNode.name));
Node handle = FileHandle.parseBarewordHandle(parser, identifierNode.name);
if (handle != null) {
// handle is Bareword
listNode1.elements.set(0, handle);
}
}
return new OperatorNode(token.text, listNode1, currentIndex);
} else if (argCount == 0 || argCount == 4) {
// select or
// select RBITS,WBITS,EBITS,TIMEOUT (syscall version)
return new OperatorNode(token.text, listNode1, currentIndex);
} else {
throw new PerlCompilerException(parser.tokenIndex,
"Wrong number of arguments for select: expected 0, 1, or 4, got " + argCount,
parser.ctx.errorUtil);
}
}
static OperatorNode parseKeys(Parser parser, LexerToken token, int currentIndex) {
String operator = token.text;
Node operand;
// Handle operators with a single operand
// For scalar, values, keys, each: parse with precedence that includes postfix operators ([], {}, ->)
// Named unary operators have precedence between 20 and 21 in Perl
// This allows expressions like: values $hashref->%* or keys $hashref->%* or scalar((nil) x 3, 1)
if (operator.equals("scalar") || operator.equals("values") || operator.equals("keys") || operator.equals("each")) {
operand = parser.parseExpression(parser.getPrecedence("=~")); // precedence 20
// Check if operand is null (no argument provided)
if (operand == null) {
throw new PerlCompilerException(currentIndex, "Not enough arguments for " + operator, parser.ctx.errorUtil);
}
// scalar can accept comma expressions like scalar((nil) x 3, 1)
// but values/keys/each need single operand check
if (!operator.equals("scalar")) {
operand = ensureOneOperand(parser, token, operand);
}
} else {
operand = ParsePrimary.parsePrimary(parser);
// Check if operand is null (no argument provided)
if (operand == null) {
throw new PerlCompilerException(currentIndex, "Not enough arguments for " + operator, parser.ctx.errorUtil);
}
operand = ensureOneOperand(parser, token, operand);
}
return new OperatorNode(operator, operand, currentIndex);
}
public static Node ensureOneOperand(Parser parser, LexerToken token, Node operand) {
if (operand instanceof ListNode listNode) {
if (listNode.elements.size() != 1) {
throw new PerlCompilerException(parser.tokenIndex, "Too many arguments for " + token.text, parser.ctx.errorUtil);
}
operand = listNode.elements.getFirst();
}
return operand;
}
static OperatorNode parseDelete(Parser parser, LexerToken token, int currentIndex) {
Node operand;
// Check for 'delete local' syntax
LexerToken nextToken = peek(parser);
if (nextToken.text.equals("local")) {
TokenUtils.consume(parser); // consume 'local'
parser.parsingTakeReference = true;
operand = ListParser.parseZeroOrOneList(parser, 1);
parser.parsingTakeReference = false;
if (operand instanceof ListNode listNode) {
transformCodeRefPatterns(parser, listNode, token.text);
}
return new OperatorNode("delete_local", operand, currentIndex);
}
// Handle 'delete' and 'exists' operators with special parsing context
parser.parsingTakeReference = true; // don't call `&subr` while parsing "Take reference"
operand = ListParser.parseZeroOrOneList(parser, 1);
parser.parsingTakeReference = false;
// Handle &{string} patterns for delete/exists operators (no transformation, direct handling)
if (operand instanceof ListNode listNode) {
transformCodeRefPatterns(parser, listNode, token.text);
}
return new OperatorNode(token.text, operand, currentIndex);
}
static BinaryOperatorNode parseBless(Parser parser, int currentIndex) {
// Handle 'bless' operator with special handling for class name
Node ref;
Node className;
// Parse the first argument (the reference to bless)
ListNode operand1 = ListParser.parseZeroOrMoreList(parser, 1, false, true, false, false);
ref = operand1.elements.get(0);
if (operand1.elements.size() > 1) {
// Second argument provided
className = operand1.elements.get(1);
// Handle bareword class names
if (className instanceof IdentifierNode identifierNode) {
// Convert bareword to string (like "Moo" -> StringNode("Moo"))
className = new StringNode(identifierNode.name, currentIndex);
} else if (className instanceof StringNode stringNode && stringNode.value.isEmpty()) {
// default to main package if empty class name is provided
className = new StringNode("main", currentIndex);
}
} else {
// No class name provided - default to current package
className = new StringNode(parser.ctx.symbolTable.getCurrentPackage(), currentIndex);
}
return new BinaryOperatorNode("bless", ref, className, currentIndex);
}
/**
* Transforms &{string} patterns for defined/exists/delete operators based on standard Perl behavior.
* - defined: transforms &{string} to \&{string} (both patterns supported)
* - exists: keeps &{string} as-is (only &{string} supported, \&{string} should error)
* - delete: keeps &{string} as-is (only &{string} supported, \&{string} should error)
*/
private static void transformCodeRefPatterns(Parser parser, ListNode operand, String operator) {
for (int i = 0; i < operand.elements.size(); i++) {
Node element = operand.elements.get(i);
// Check for \&{string} patterns - these should error for exists/delete
if (element instanceof OperatorNode backslashOp &&
backslashOp.operator.equals("\\") &&
backslashOp.operand instanceof OperatorNode ampOp &&
ampOp.operator.equals("&") &&
ampOp.operand instanceof BlockNode blockNode &&
blockNode.elements.size() == 1 &&
blockNode.elements.get(0) instanceof StringNode) {
if (operator.equals("exists") || operator.equals("delete")) {
throw new PerlCompilerException(operator + " argument is not a HASH or ARRAY element" +
(operator.equals("exists") ? " or a subroutine" : ""));
}
// For defined, \&{string} is allowed as-is
}
// Look for &{string} pattern: OperatorNode with "&" operator and BlockNode operand
if (element instanceof OperatorNode operatorNode &&
operatorNode.operator.equals("&") &&
operatorNode.operand instanceof BlockNode blockNode &&
blockNode.elements.size() == 1 &&
blockNode.elements.get(0) instanceof StringNode stringNode) {
// Check strict refs at parse time - but only for defined operator
// Standard Perl allows &{string} with strict refs for exists/delete
if (operator.equals("defined") && parser.ctx.symbolTable.isStrictOptionEnabled(Strict.HINT_STRICT_REFS)) {
throw new PerlCompilerException("Can't use string (\"" + stringNode.value + "\") as a subroutine ref while \"strict refs\" in use");
}
// Don't transform &{string} patterns - handle them directly in emitter
// This preserves the semantic difference between &{string} and \&{string}
// For all operators (defined/exists/delete), keep &{string} as-is and handle in emitter
// The emitter has proper logic to handle these patterns correctly
}
}
}
static OperatorNode parseDefined(Parser parser, LexerToken token, int currentIndex) {
ListNode operand;
// Handle 'defined' operator with special parsing context
boolean parsingTakeReference = parser.parsingTakeReference;
parser.parsingTakeReference = true; // don't call `&subr` while parsing "Take reference"
operand = ListParser.parseZeroOrOneList(parser, 0);
parser.parsingTakeReference = parsingTakeReference;
if (operand.elements.isEmpty()) {
// `defined` without arguments means `defined $_`
operand.elements.add(
ParserNodeUtils.scalarUnderscore(parser)
);
}
// Transform &{string} patterns to \&{string} patterns for defined operator
transformCodeRefPatterns(parser, operand, "defined");
return new OperatorNode(token.text, operand, currentIndex);
}
static OperatorNode parseUndef(Parser parser, LexerToken token, int currentIndex) {
ListNode operand;
// Handle 'undef' operator with special parsing context
// Similar to 'defined', we need to prevent &subr from being auto-called
boolean parsingTakeReference = parser.parsingTakeReference;
parser.parsingTakeReference = true; // don't call `&subr` while parsing "Take reference"
operand = ListParser.parseZeroOrOneList(parser, 0);
parser.parsingTakeReference = parsingTakeReference;
if (operand.elements.isEmpty()) {
// `undef` without arguments returns undef
return new OperatorNode(token.text, null, currentIndex);
}
return new OperatorNode(token.text, operand, currentIndex);
}
static Node parseSpecialQuoted(Parser parser, LexerToken token, int startIndex) {
// Handle special-quoted domain-specific arguments
String operator = token.text;
// Skip whitespace, but not `#`
parser.tokenIndex = startIndex;
consume(parser);
while (parser.tokenIndex < parser.tokens.size()) {
LexerToken token1 = parser.tokens.get(parser.tokenIndex);
if (token1.type == WHITESPACE || token1.type == NEWLINE) {
parser.tokenIndex++;
} else {
break;
}
}
return StringParser.parseRawString(parser, token.text);
}
static OperatorNode parseNot(Parser parser, LexerToken token, int currentIndex) {
Node operand;
// Handle 'not' keyword as a unary operator with an operand
if (TokenUtils.peek(parser).text.equals("(")) {
TokenUtils.consume(parser);
if (TokenUtils.peek(parser).text.equals(")")) {
operand = new OperatorNode("undef", null, currentIndex);
} else {
// Parentheses group a full expression; allow low-precedence operators like `and`/`or`.
operand = parser.parseExpression(0);
}
TokenUtils.consume(parser, OPERATOR, ")");
return new OperatorNode(token.text, operand, currentIndex);
}
operand = parser.parseExpression(parser.getPrecedence(token.text) + 1);
return new OperatorNode(token.text, operand, currentIndex);
}
static OperatorNode parseStat(Parser parser, LexerToken token, int currentIndex) {
// Handle 'stat' and 'lstat' operators with special handling for `stat _`
LexerToken nextToken = peek(parser);
boolean paren = false;
if (nextToken.text.equals("(")) {
TokenUtils.consume(parser);
nextToken = peek(parser);
paren = true;
}
if (nextToken.text.equals("_")) {
TokenUtils.consume(parser);
if (paren) {
TokenUtils.consume(parser, OPERATOR, ")");
}
return new OperatorNode(token.text,
new IdentifierNode("_", parser.tokenIndex), parser.tokenIndex);
}
// stat/lstat: bareword filehandle (typically ALLCAPS) should be treated as a typeglob.
// Consume it here, before generic expression parsing can turn it into a subroutine call.
if (nextToken.type == IDENTIFIER) {
String name = nextToken.text;
if (name.matches("^[A-Z_][A-Z0-9_]*$")) {
TokenUtils.consume(parser);
// autovivify filehandle and convert to globref
GlobalVariable.getGlobalIO(FileHandle.normalizeBarewordHandle(parser, name));
Node fh = FileHandle.parseBarewordHandle(parser, name);
Node operand = fh != null ? fh : new IdentifierNode(name, parser.tokenIndex);
if (paren) {
TokenUtils.consume(parser, OPERATOR, ")");
}
return new OperatorNode(token.text, operand, currentIndex);
}
}
// Parse optional single argument (or default to $_)
// If we've already consumed '(', we must parse a full expression up to ')'.
// Using parseZeroOrOneList here would parse without parentheses and may stop
// at low-precedence operators like the ternary ?:, leading to parse errors.
ListNode listNode;
if (paren) {
listNode = new ListNode(ListParser.parseList(parser, ")", 0), parser.tokenIndex);
} else {
listNode = ListParser.parseZeroOrOneList(parser, 0);
}
Node operand;
if (listNode.elements.isEmpty()) {
// No arg: default to $_ (matches existing behavior of parseOperatorWithOneOptionalArgument)
operand = ParserNodeUtils.scalarUnderscore(parser);
} else if (listNode.elements.size() == 1) {
operand = listNode.elements.getFirst();
} else {
parser.throwError("syntax error");
return null; // unreachable
}
return new OperatorNode(token.text, operand, currentIndex);
}
static BinaryOperatorNode parseReadline(Parser parser, LexerToken token, int currentIndex) {
String operator = token.text;
// Handle file-related operators with special handling for default handles
ListNode operand = ListParser.parseZeroOrMoreList(parser, 0, false, true, false, false);
Node handle;
if (operand.elements.isEmpty()) {
String defaultHandle = switch (operator) {
case "readline" -> "main::ARGV";
case "eof", "tell" -> null;
case "truncate" ->
throw new PerlCompilerException(parser.tokenIndex, "Not enough arguments for " + token.text, parser.ctx.errorUtil);
default ->
throw new PerlCompilerException(parser.tokenIndex, "Unexpected value: " + token.text, parser.ctx.errorUtil);
};
if (defaultHandle == null) {
handle = new OperatorNode("undef", null, currentIndex);
} else {
handle = new IdentifierNode(defaultHandle, currentIndex);
}
} else {
handle = operand.elements.removeFirst();
if (handle instanceof IdentifierNode idNode) {
String name = idNode.name;
if (name.matches("^[A-Z_][A-Z0-9_]*$")) {
GlobalVariable.getGlobalIO(FileHandle.normalizeBarewordHandle(parser, name));
Node fh = FileHandle.parseBarewordHandle(parser, name);
if (fh != null) {
handle = fh;
}
}
}
}
return new BinaryOperatorNode(operator, handle, operand, currentIndex);
}
static BinaryOperatorNode parseSplit(Parser parser, LexerToken token, int currentIndex) {
ListNode operand;
// Handle 'split' operator with special handling for separator
operand = ListParser.parseZeroOrMoreList(parser, 0, false, true, false, true);
Node separator =
operand.elements.isEmpty()
? new StringNode(" ", currentIndex)
: operand.elements.removeFirst();
if (separator instanceof OperatorNode) {
if (((OperatorNode) separator).operator.equals("matchRegex")) {
((OperatorNode) separator).operator = "quoteRegex";
}
}
return new BinaryOperatorNode(token.text, separator, operand, currentIndex);
}
static BinaryOperatorNode parseJoin(Parser parser, LexerToken token, String operatorName, int currentIndex) {
Node separator;
ListNode operand;
int firstArgIndex = parser.tokenIndex;
// Handle operators with a RuntimeList operand
operand = ListParser.parseZeroOrMoreList(parser, 1, false, true, false, false);
separator = operand.elements.removeFirst();
if (token.text.equals("push") || token.text.equals("unshift")) {
var op = separator;
// Unwrap my/our/local declarations to get to the underlying array
if (op instanceof OperatorNode operatorNode &&
(operatorNode.operator.equals("my") ||
operatorNode.operator.equals("our") ||
operatorNode.operator.equals("local"))) {
op = operatorNode.operand;
}
if (!(op instanceof OperatorNode operatorNode && operatorNode.operator.equals("@"))) {
// Perl 5.24+: pushing/unshifting onto scalar variable or expression is forbidden
// But literals get a different error message
if (op instanceof OperatorNode || op instanceof BinaryOperatorNode) {
parser.throwError(firstArgIndex, "Experimental " + operatorName + " on scalar is now forbidden");
}
parser.throwError(firstArgIndex, "Type of arg 1 to " + operatorName + " must be array (not constant item)");
}
}
return new BinaryOperatorNode(token.text, separator, operand, currentIndex);
}
static OperatorNode parseLast(Parser parser, LexerToken token, int currentIndex) {
Node operand;
// Handle loop control operators
operand = ListParser.parseZeroOrMoreList(parser, 0, false, false, false, false);
return new OperatorNode(token.text, operand, currentIndex);
}
static OperatorNode parseReturn(Parser parser, int currentIndex) {
Node operand;
// Handle 'return' keyword as a unary operator with an operand
operand = ListParser.parseZeroOrMoreList(parser, 0, false, false, false, false);
return new OperatorNode("return", operand, currentIndex);
}
static OperatorNode parseGoto(Parser parser, int currentIndex) {
Node operand;
// Handle 'goto' keyword - operand is optional (bare `goto` is a runtime error)
operand = ListParser.parseZeroOrMoreList(parser, 0, false, false, false, false);
// Always return a goto operator - the emitter handles &sub vs LABEL distinction
return new OperatorNode("goto", operand, currentIndex);
}
static OperatorNode parseLocal(Parser parser, LexerToken token, int currentIndex) {
// Check if this is a declared reference (local \$x, local \@array, etc.)
boolean isDeclaredReference = false;
if (peek(parser).type == OPERATOR && peek(parser).text.equals("\\")) {
isDeclaredReference = true;
// Check if declared_refs feature is enabled
if (!parser.ctx.symbolTable.isFeatureCategoryEnabled("declared_refs")) {
throw new PerlCompilerException(
currentIndex,
"The experimental declared_refs feature is not enabled",
parser.ctx.errorUtil
);
}
// Emit experimental warning if warnings are enabled
if (parser.ctx.symbolTable.isWarningCategoryEnabled("experimental::declared_refs")) {
// Use WarnDie.warn to respect $SIG{__WARN__} handler
try {
WarnDie.warn(
new RuntimeScalar("Declaring references is experimental"),
new RuntimeScalar(parser.ctx.errorUtil.warningLocation(currentIndex))
);
} catch (Exception e) {
// If warning system isn't initialized yet, fall back to System.err
System.err.println("Declaring references is experimental" + parser.ctx.errorUtil.warningLocation(currentIndex) + ".");
}
}
TokenUtils.consume(parser, OPERATOR, "\\");
}
Node operand;
// Handle 'local' keyword as a unary operator with an operand
if (peek(parser).text.equals("(")) {
operand = ParsePrimary.parsePrimary(parser);
} else {
operand = parser.parseExpression(parser.getPrecedence("++"));
}
// Check for declared references inside parentheses: local(\$x)
if (operand instanceof ListNode listNode) {
for (Node element : listNode.elements) {
if (element instanceof OperatorNode operandNode) {
// Check if this element is a reference operator (backslash)
// This handles cases like local(\$x) where the backslash is inside the parentheses
if (operandNode.operator.equals("\\") && operandNode.operand instanceof OperatorNode) {
// This is a declared reference inside parentheses: local(\$x), local(\@arr), local(\%hash)
// Check if declared_refs feature is enabled
if (!parser.ctx.symbolTable.isFeatureCategoryEnabled("declared_refs")) {