-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathVariable.java
More file actions
1199 lines (1080 loc) · 60.4 KB
/
Variable.java
File metadata and controls
1199 lines (1080 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.perlonjava.frontend.parser;
import org.perlonjava.app.cli.CompilerOptions;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.frontend.lexer.LexerToken;
import org.perlonjava.frontend.lexer.LexerTokenType;
import org.perlonjava.frontend.semantic.SymbolTable;
import org.perlonjava.runtime.operators.WarnDie;
import org.perlonjava.runtime.perlmodule.Strict;
import org.perlonjava.runtime.runtimetypes.*;
import java.util.ArrayList;
import java.util.List;
import static org.perlonjava.frontend.parser.ParsePrimary.parsePrimary;
import static org.perlonjava.frontend.parser.ParserNodeUtils.atUnderscore;
import static org.perlonjava.frontend.parser.TokenUtils.peek;
/**
* Parser for Perl variables with sigils ($, @, %, &, *).
*
* <p>This class handles the parsing of Perl variables including:
* <ul>
* <li>Simple variables: {@code $var}, {@code @array}, {@code %hash}</li>
* <li>Braced variables: {@code ${var}}, {@code @{array}}</li>
* <li>Array/hash access: {@code $array[0]}, {@code $hash{key}}</li>
* <li>Dereferencing: {@code $ref->[0]}, {@code $ref->{key}}</li>
* <li>Typeglobs: {@code *name}</li>
* <li>Code references: {@code &sub}</li>
* <li>Class field access: automatic transformation of {@code $field} to {@code $self->{field}} in methods</li>
* </ul>
*
* <p>The parser also handles special cases like:
* <ul>
* <li>Special variables: {@code $@}, {@code $_}, {@code $!}, etc.</li>
* <li>Regex variables: {@code $1}, {@code $2}, etc.</li>
* <li>Array size: {@code $#array}</li>
* <li>Package-qualified names: {@code $Package::var}</li>
* </ul>
*/
public class Variable {
/**
* Check if a field exists in the current class or any parent class.
* Uses both the local symbol table (for current class) and the global
* FieldRegistry (for parent classes that have been parsed).
*
* @param parser The parser instance
* @param fieldName The name of the field to check (without sigil)
* @return true if the field exists in the class hierarchy
*/
public static boolean isFieldInClassHierarchy(Parser parser, String fieldName) {
// Get the current package/class name
String currentClass = parser.ctx.symbolTable.getCurrentPackage();
// First check field in current class via symbol table
// Use getVariableIndex (not InCurrentScope) to search all parent scopes
// Fields are in the class scope, methods create inner scopes
String fieldSymbol = "field:" + fieldName;
if (parser.ctx.symbolTable.getVariableIndex(fieldSymbol) != -1) {
return true;
}
// Check if we're in a class (not just a regular package)
if (!parser.ctx.symbolTable.currentPackageIsClass()) {
return false;
}
// Check the global FieldRegistry for inherited fields
// This works when parent classes were parsed before child classes
return FieldRegistry.hasFieldInHierarchy(currentClass, fieldName);
}
/**
* Parses a variable from the given lexer token.
*
* <p>This is the main entry point for parsing Perl variables. It handles various forms:
* <ul>
* <li>Simple variables: {@code $var}, {@code @array}, {@code %hash}</li>
* <li>Braced forms: {@code ${expr}}, {@code @{expr}}, {@code %{expr}}</li>
* <li>Dereferencing: {@code $$ref}, {@code @$ref}, {@code %$ref}</li>
* <li>Special cases: {@code $#array} (array size), {@code $#[...]} (empty string)</li>
* <li>Class fields: automatic transformation in method context</li>
* </ul>
*
* <p>The method also handles special parsing rules:
* <ul>
* <li>Validates variable names according to Perl rules</li>
* <li>Checks for syntax errors (e.g., parentheses after non-sub variables)</li>
* <li>Vivifies typeglobs when using {@code *name} syntax</li>
* <li>Transforms field access to {@code $self->{field}} in class methods</li>
* </ul>
*
* @param parser the parser instance containing the current parsing state
* @param sigil The sigil that starts the variable ($, @, %, &, *, or $#)
* @return The parsed variable node (OperatorNode, BinaryOperatorNode, or other AST node)
* @throws PerlCompilerException If there is a syntax error during parsing
*/
public static Node parseVariable(Parser parser, String sigil) {
Node operand;
LexerToken nextToken = parser.tokenIndex < parser.tokens.size()
? parser.tokens.get(parser.tokenIndex)
: new LexerToken(LexerTokenType.EOF, "");
// Special case 1: $${...} - nested scalar dereference
// Example: $${ref} means dereference $ref to get a scalar reference, then dereference that
int nextNonWsIndex = Whitespace.skipWhitespace(parser, parser.tokenIndex, parser.tokens);
LexerToken nextNonWsToken = nextNonWsIndex < parser.tokens.size()
? parser.tokens.get(nextNonWsIndex)
: new LexerToken(LexerTokenType.EOF, "");
if (nextNonWsToken.text.equals("$")) {
// Check if we have ${...} pattern
if (nextNonWsIndex + 1 < parser.tokens.size() && parser.tokens.get(nextNonWsIndex + 1).text.equals("{")) {
// This is ${...}, parse as dereference of ${...}
// Don't consume the $ token, let it be parsed as part of the variable
operand = parser.parseExpression(parser.getPrecedence("$") + 1);
return new OperatorNode(sigil, operand, parser.tokenIndex);
}
}
// Special case 2: $#[...] - deprecated syntax that returns empty string
// This is mentioned in t/base/lex.t as a special edge case
if (sigil.equals("$#") && nextNonWsToken.text.equals("[")) {
// This is $#[...] which is mentioned in t/base/lex.t and it returns an empty string
parsePrimary(parser);
return new StringNode("", parser.tokenIndex);
}
// Special case 3: ${...}, @{...}, %{...} - braced variable forms
// PRE-CHECK: If next token is '{', skip identifier parsing and go directly to parseBracedVariable
// This avoids backtracking and heredoc processing issues
if (nextToken.text.equals("{")) {
return parseBracedVariable(parser, sigil, false);
}
// Detect bare $# (no array name follows) — deprecated since Perl 5.30
if (sigil.equals("$#")) {
LexerToken afterSigil = nextNonWsToken;
if (afterSigil.type != LexerTokenType.IDENTIFIER
&& afterSigil.type != LexerTokenType.NUMBER
&& !afterSigil.text.equals("{")
&& !afterSigil.text.equals("[")
&& !afterSigil.text.equals("$")
&& !afterSigil.text.equals("'")
&& !afterSigil.text.equals("+")
&& !afterSigil.text.equals("-")
&& !afterSigil.text.equals("^")) {
parser.throwCleanError("$# is no longer supported as of Perl 5.30");
}
}
// Normal variable parsing: try to parse an identifier
// Store the current position before parsing the identifier
int startIndex = parser.tokenIndex;
String varName = IdentifierParser.parseComplexIdentifier(parser, sigil.equals("*"));
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("Parsing variable: " + varName);
if (varName != null) {
if (varName.isEmpty()) {
parser.throwError("syntax error");
}
IdentifierParser.validateIdentifier(parser, varName, startIndex);
// Variable name is valid.
// Check for illegal characters after a variable
if (!parser.parsingForLoopVariable && !parser.parsingIndirectObject && peek(parser).text.equals("(") && !sigil.equals("&")) {
// Parentheses are only allowed after a variable in specific cases:
// - `for my $v (...`
// - `&name(...`
// - `obj->$name(...`
parser.throwError("syntax error");
}
// Typeglob vivification: *name creates a glob entry if it doesn't exist
// This is important for distinguishing file handles from barewords
if (sigil.equals("*")) {
// Vivify the GLOB if it doesn't exist yet
// This helps distinguish between file handles and other barewords
String fullName = NameNormalizer.normalizeVariableName(varName, parser.ctx.symbolTable.getCurrentPackage());
GlobalVariable.getGlobalIO(fullName);
}
// ===== CLASS FIELD TRANSFORMATION =====
// In Perl's class system (use feature 'class'), field variables are automatically
// transformed to access $self->{field} when used inside methods.
//
// Example:
// class Point {
// field $x;
// method move($dx) {
// $x += $dx; # Automatically becomes: $self->{x} += $dx
// }
// }
//
// Transformation rules:
// 1. Only applies inside methods (not in regular subs or package code)
// 2. Only if the field exists in the current class or parent classes
// 3. Only if not shadowed by a local variable (my/our/state)
//
// Transformation by sigil:
// - $field -> $self->{field} (scalar field access)
// - @field -> @{$self->{field}} (array field dereference)
// - %field -> %{$self->{field}} (hash field dereference)
String localVar = sigil + varName;
// Check if this is a field (in current or parent class) and not a locally declared variable
// Note: We check if the variable is NOT defined locally (only in current scope)
// but we DO check for fields in all scopes (fields are in parent scope)
if (parser.isInMethod
&& isFieldInClassHierarchy(parser, varName)
&& parser.ctx.symbolTable.getVariableIndexInCurrentScope(localVar) == -1) {
// This is a field and not shadowed by a local variable
// Transform field access based on sigil type
// Create $self variable reference
OperatorNode selfVar = new OperatorNode("$",
new IdentifierNode("self", parser.tokenIndex), parser.tokenIndex);
// Create hash subscript for field access: {fieldname}
List<Node> keyList = new ArrayList<>();
keyList.add(new IdentifierNode(varName, parser.tokenIndex));
HashLiteralNode hashSubscript = new HashLiteralNode(keyList, parser.tokenIndex);
// Create $self->{fieldname} access
Node fieldAccess = new BinaryOperatorNode("->", selfVar, hashSubscript, parser.tokenIndex);
// For array and hash fields, we need to dereference the reference
// because fields are stored as references in the object hash
if (sigil.equals("@") || sigil.equals("%")) {
// @field becomes @{$self->{field}}
// %field becomes %{$self->{field}}
return new OperatorNode(sigil, fieldAccess, parser.tokenIndex);
} else {
// Scalar fields: $field becomes $self->{field}
return fieldAccess;
}
}
// Check strict vars at parse time — catches undeclared variables in
// lazily-compiled named sub bodies that would otherwise be missed
checkStrictVarsAtParseTime(parser, sigil, varName);
// Normal variable: create a simple variable reference node
return new OperatorNode(sigil, new IdentifierNode(varName, parser.tokenIndex), parser.tokenIndex);
} else if (peek(parser).text.equals("{")) {
// Handle curly brackets - use parseBracedVariable instead of parseBlock
return parseBracedVariable(parser, sigil, false);
}
// Not a variable name, not a block. This could be a dereference like @$a
// Parse the expression with the appropriate precedence
operand = parser.parseExpression(parser.getPrecedence("$") + 1);
return new OperatorNode(sigil, operand, parser.tokenIndex);
}
/**
* Check strict vars at parse time for an unqualified variable.
* This catches undeclared variables inside lazily-compiled named sub bodies
* that would otherwise only be detected at call time (or never).
* Mirrors the exemption logic from EmitVariable.java and BytecodeCompiler.java.
*/
private static void checkStrictVarsAtParseTime(Parser parser, String sigil, String varName) {
// Only check $, @, % sigils (not *, &, $#)
if (!sigil.equals("$") && !sigil.equals("@") && !sigil.equals("%")) return;
// Skip when parsing a my/our/state declaration — the variable is being declared
if (parser.parsingDeclaration) return;
// Only apply inside named subroutine bodies. Named subs are compiled
// lazily, so the existing code-generation strict check never fires at
// compile time for them. All other contexts (file-level, anonymous
// subs, eval STRING) are handled correctly by the code-generation check.
if (!parser.ctx.symbolTable.isInSubroutineBody()) return;
String currentSub = parser.ctx.symbolTable.getCurrentSubroutine();
if (currentSub == null || currentSub.isEmpty()) return;
// Check if strict vars is enabled in the current scope
if (!parser.ctx.symbolTable.isStrictOptionEnabled(Strict.HINT_STRICT_VARS)) return;
// Variable declared lexically (my, our, state) — always allowed
if (parser.ctx.symbolTable.getSymbolEntry(sigil + varName) != null) return;
// For $name{...} (hash element) or $name[...] (array element), check the
// container variable too: $hash{key} is valid if %hash is declared,
// and $array[0] is valid if @array is declared.
// Similarly, @name{...} is a hash slice (valid if %name is declared).
if (sigil.equals("$") || sigil.equals("@")) {
int peekIdx = Whitespace.skipWhitespace(parser, parser.tokenIndex, parser.tokens);
if (peekIdx < parser.tokens.size()) {
String nextText = parser.tokens.get(peekIdx).text;
if (nextText.equals("{") && parser.ctx.symbolTable.getSymbolEntry("%" + varName) != null) return;
if (nextText.equals("[") && parser.ctx.symbolTable.getSymbolEntry("@" + varName) != null) return;
}
}
// Qualified names (Pkg::var) — always allowed
if (varName.contains("::")) return;
// Regex capture variables ($1, $2, ...) but not $01, $02
if (ScalarUtils.isInteger(varName) && !varName.startsWith("0")) return;
// Sort variables $a and $b
if (sigil.equals("$") && (varName.equals("a") || varName.equals("b"))) return;
// Built-in special length-one vars ($_, $!, $;, $0, etc.)
if (sigil.equals("$") && varName.length() == 1 && !Character.isLetter(varName.charAt(0))) return;
// Built-in special scalar vars (${^GLOBAL_PHASE}, $ARGV, $STDIN, etc.)
if (sigil.equals("$") && !varName.isEmpty() && varName.charAt(0) < 32) return;
if (sigil.equals("$") && (varName.equals("ARGV") || varName.equals("ARGVOUT")
|| varName.equals("ENV") || varName.equals("INC") || varName.equals("SIG")
|| varName.equals("STDIN") || varName.equals("STDOUT") || varName.equals("STDERR"))) return;
// Built-in special container vars (%ENV, %SIG, @ARGV, @INC, etc.)
if (sigil.equals("%") && (varName.equals("SIG") || varName.equals("ENV")
|| varName.equals("INC") || varName.equals("+") || varName.equals("-")
|| varName.equals("_"))) return;
if (sigil.equals("@") && (varName.equals("ARGV") || varName.equals("INC")
|| varName.equals("_") || varName.equals("F"))) return;
// Non-ASCII length-1 scalars under 'no utf8' (Latin-1 range)
if (sigil.equals("$") && varName.length() == 1) {
char c = varName.charAt(0);
if (c > 127 && c <= 255
&& !parser.ctx.symbolTable.isStrictOptionEnabled(Strict.HINT_UTF8)) return;
}
// Check if variable already exists in the global registry (from use vars, etc.)
String normalizedName = NameNormalizer.normalizeVariableName(
varName, parser.ctx.symbolTable.getCurrentPackage());
boolean existsGlobally = false;
if (sigil.equals("$")) {
existsGlobally = GlobalVariable.existsGlobalVariable(normalizedName);
// For $hash{...} and $array[...], also check global container
if (!existsGlobally) {
int peekIdx = Whitespace.skipWhitespace(parser, parser.tokenIndex, parser.tokens);
if (peekIdx < parser.tokens.size()) {
String nextText = parser.tokens.get(peekIdx).text;
if (nextText.equals("{") && GlobalVariable.existsGlobalHash(normalizedName)) existsGlobally = true;
if (nextText.equals("[") && GlobalVariable.existsGlobalArray(normalizedName)) existsGlobally = true;
}
}
} else if (sigil.equals("@")) {
existsGlobally = GlobalVariable.existsGlobalArray(normalizedName);
// For @hash{...} (hash slice), also check global hash
if (!existsGlobally) {
int peekIdx = Whitespace.skipWhitespace(parser, parser.tokenIndex, parser.tokens);
if (peekIdx < parser.tokens.size()) {
String nextText = parser.tokens.get(peekIdx).text;
if (nextText.equals("{") && GlobalVariable.existsGlobalHash(normalizedName)) existsGlobally = true;
}
}
} else if (sigil.equals("%") && !normalizedName.endsWith("::"))
existsGlobally = GlobalVariable.existsGlobalHash(normalizedName);
// Single-letter scalars ($A-$Z) bypass strict only if explicitly declared
// (via use vars or Exporter import), not if merely auto-vivified under 'no strict'.
if (sigil.equals("$") && varName.length() == 1
&& Character.isLetter(varName.charAt(0))
&& !varName.equals("a") && !varName.equals("b")) {
if (!GlobalVariable.isDeclaredGlobalVariable(normalizedName)) {
existsGlobally = false;
}
}
if (existsGlobally) return;
// Undeclared variable under strict vars
throw new PerlCompilerException(parser.tokenIndex,
"Global symbol \"" + sigil + varName
+ "\" requires explicit package name (did you forget to declare \"my "
+ sigil + varName + "\"?)",
parser.ctx.errorUtil);
}
/**
* Parses array and hash access operations within braces (for ${...} constructs).
* This is similar to parseArrayHashAccess but stops at the closing brace.
*
* @param parser the parser instance
* @param operand the base variable node to which access operations are applied
* @param isRegex whether this is in a regex context (affects bracket handling)
* @return the modified operand with access operations applied
*/
static Node parseArrayHashAccessInBraces(Parser parser, Node operand, boolean isRegex) {
while (true) {
// Skip whitespace, comments, etc. inside braces
parser.tokenIndex = Whitespace.skipWhitespace(parser, parser.tokenIndex, parser.tokens);
if (parser.tokenIndex >= parser.tokens.size()) {
break;
}
var token = parser.tokens.get(parser.tokenIndex);
if (token.text.equals("}")) {
// Hit the closing brace, stop parsing
break;
}
var text = token.text;
try {
switch (text) {
case "[" -> {
if (isRegex) {
// In regex context, '[' might be a character class
// Need sophisticated lookahead to distinguish:
// $foo[$A] - array subscript (should interpolate)
// $foo[$A-Z] - character class (should NOT interpolate)
if (!isArraySubscriptInRegex(parser, parser.tokenIndex)) {
return operand; // Stop parsing, let caller handle as character class
}
}
operand = ParseInfix.parseInfixOperation(parser, operand, 0);
if (operand == null) {
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Missing closing bracket", parser.ctx.errorUtil);
}
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("str operand " + operand);
}
case "{" -> {
// Hash access
operand = ParseInfix.parseInfixOperation(parser, operand, 0);
if (operand == null) {
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Missing closing brace", parser.ctx.errorUtil);
}
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("str operand " + operand);
}
case "->" -> {
// Method call or dereference
var previousIndex = parser.tokenIndex;
parser.tokenIndex++;
if (parser.tokenIndex < parser.tokens.size()) {
text = parser.tokens.get(parser.tokenIndex).text;
switch (text) {
case "[", "{" -> {
// Dereference followed by access: $var->[0] or $var->{key}
parser.tokenIndex = previousIndex; // Re-parse "->"
operand = ParseInfix.parseInfixOperation(parser, operand, 0);
if (operand == null) {
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Unterminated dereference", parser.ctx.errorUtil);
}
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("str operand " + operand);
}
default -> {
// Not a dereference we can handle
parser.tokenIndex = previousIndex;
return operand; // Stop parsing
}
}
} else {
parser.tokenIndex = previousIndex;
return operand;
}
}
default -> {
// No more access operations we recognize
return operand;
}
}
} catch (Exception e) {
// If parsing fails, throw a more informative error
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Unterminated array or hash access", parser.ctx.errorUtil);
}
}
return operand;
}
/**
* Parses array and hash access operations following a variable.
*
* @param parser the parser instance
* @param operand the base variable node to which access operations are applied
* @param isRegex whether this is in a regex context (affects bracket handling)
* @return the modified operand with access operations applied
*/
static Node parseArrayHashAccess(Parser parser, Node operand, boolean isRegex) {
outerLoop:
while (true) {
if (parser.tokenIndex >= parser.tokens.size()) {
break;
}
var token = parser.tokens.get(parser.tokenIndex);
if (token.type == LexerTokenType.EOF) {
break;
}
var text = token.text;
try {
switch (text) {
case "[" -> {
if (isRegex) {
// In regex context, '[' might be a character class
// Critical distinction:
// 1. Scalar variables: $foo[$A-Z] -> character class (should NOT interpolate)
// 2. Array variables: $X[-1] -> array element (should interpolate)
// Enhanced parsing logic that considers strict mode context
// Key insight: Strict mode affects how $foo[...] is parsed
//
// In NON-STRICT mode (like t/base/lex.t):
// - $foo[$A-Z] works as character class (barewords allowed)
// - $X[-1] works as array element access
//
// In STRICT mode:
// - $foo[$A-Z] may cause parsing issues (barewords not allowed)
// - Need more careful disambiguation
boolean shouldTreatAsCharacterClass = false;
if (operand instanceof OperatorNode opNode && "$".equals(opNode.operator)) {
// This is a scalar variable access like $foo or $X
// Use enhanced logic to distinguish array subscripts from character classes
if (!isArraySubscriptInRegex(parser, parser.tokenIndex)) {
shouldTreatAsCharacterClass = true;
}
}
if (shouldTreatAsCharacterClass) {
// This is a character class pattern
break outerLoop; // Stop parsing, let caller handle as character class
}
}
// Check for malformed array access (unclosed bracket)
int savedIndex = parser.tokenIndex;
Node result = null;
try {
result = ParseInfix.parseInfixOperation(parser, operand, 0);
} catch (Exception e) {
parser.tokenIndex = savedIndex;
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Unterminated array access", parser.ctx.errorUtil);
}
if (result == null) {
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Missing closing bracket", parser.ctx.errorUtil);
}
operand = result;
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("str operand " + operand);
}
case "{" -> {
// Hash access
int savedIndex = parser.tokenIndex;
Node result = null;
try {
result = ParseInfix.parseInfixOperation(parser, operand, 0);
} catch (Exception e) {
parser.tokenIndex = savedIndex;
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Unterminated hash access", parser.ctx.errorUtil);
}
if (result == null) {
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Missing closing brace", parser.ctx.errorUtil);
}
operand = result;
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("str operand " + operand);
}
case "->" -> {
// Method call or dereference
var previousIndex = parser.tokenIndex;
parser.tokenIndex++;
if (parser.tokenIndex < parser.tokens.size()) {
text = parser.tokens.get(parser.tokenIndex).text;
switch (text) {
case "[", "{" -> {
// Dereference followed by access: $var->[0] or $var->{key}
parser.tokenIndex = previousIndex; // Re-parse "->"
Node result = ParseInfix.parseInfixOperation(parser, operand, 0);
if (result == null) {
throw new PerlCompilerException(parser.tokenIndex, "syntax error: Unterminated dereference", parser.ctx.errorUtil);
}
operand = result;
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("str operand " + operand);
}
default -> {
// Not a dereference we can handle
parser.tokenIndex = previousIndex;
break outerLoop;
}
}
} else {
parser.tokenIndex = previousIndex;
break outerLoop;
}
}
default -> {
// No more access operations
break outerLoop;
}
}
} catch (PerlCompilerException e) {
// Re-throw PerlCompilerExceptions as-is
throw e;
} catch (Exception e) {
// Convert other exceptions to PerlCompilerException
throw new PerlCompilerException(parser.tokenIndex, "syntax error: " + e.getMessage(), parser.ctx.errorUtil);
}
}
return operand;
}
/**
* Parses a code reference variable, handling Perl's `&` code reference parsing rules.
* This method is responsible for parsing expressions that start with `&`, which in Perl
* can be used to refer to subroutines or to call them.
*
* @param parser the parser instance
* @param token The lexer token representing the `&` operator.
* @return A Node representing the parsed code reference or subroutine call.
*/
static Node parseCoderefVariable(Parser parser, LexerToken token) {
int index = parser.tokenIndex;
// Special case: detect &{sub ...} and parse as code block
LexerToken nextToken = TokenUtils.peek(parser);
if (nextToken.text.equals("{")) {
// Look ahead to see if there's 'sub' after the brace (skipping whitespace)
int lookAheadIndex = parser.tokenIndex + 1;
while (lookAheadIndex < parser.tokens.size()) {
LexerToken afterBrace = parser.tokens.get(lookAheadIndex);
if (afterBrace.type == LexerTokenType.WHITESPACE) {
lookAheadIndex++;
continue;
}
if (afterBrace.type == LexerTokenType.IDENTIFIER && afterBrace.text.equals("sub")) {
// This is &{sub ...} - parse as code block
TokenUtils.consume(parser); // consume '{'
Node block = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
return new OperatorNode("&", block, index);
}
break; // Not whitespace and not 'sub', so exit
}
}
// IMPORTANT: Check for lexical subs BEFORE parsing as a variable
// This handles &foo where foo is "our sub foo" or "my sub foo"
LexerToken peeked = TokenUtils.peek(parser);
if (peeked.type == LexerTokenType.IDENTIFIER) {
String subName = peeked.text;
String lexicalKey = "&" + subName;
SymbolTable.SymbolEntry lexicalEntry = parser.ctx.symbolTable.getSymbolEntry(lexicalKey);
if (lexicalEntry != null && lexicalEntry.ast() instanceof OperatorNode varNode) {
// Check if this is an "our sub" - if so, replace with fully qualified name
Boolean isOurSub = (Boolean) varNode.getAnnotation("isOurSub");
if (isOurSub != null && isOurSub) {
String storedFullName = (String) varNode.getAnnotation("fullSubName");
if (storedFullName != null) {
// Consume the identifier token
TokenUtils.consume(parser);
// Create node with fully qualified name
Node qualifiedNode = new OperatorNode("&",
new IdentifierNode(storedFullName, index), index);
// Handle arguments if present
Node list;
boolean shareArgs = false;
if (!TokenUtils.peek(parser).text.equals("(")) {
list = atUnderscore(parser);
shareArgs = true; // &func shares caller's @_
} else {
list = ListParser.parseZeroOrMoreList(parser, 0, false, true, false, false);
}
BinaryOperatorNode callNode = new BinaryOperatorNode("(", qualifiedNode, list, index);
if (shareArgs) callNode.setAnnotation("shareCallerArgs", true);
return callNode;
}
}
// Check if this is a "my sub" or "state sub" - use hidden variable
String hiddenVarName = (String) varNode.getAnnotation("hiddenVarName");
if (hiddenVarName != null) {
// Consume the identifier token
TokenUtils.consume(parser);
// Get the package where this lexical sub was declared
String declaringPackage = (String) varNode.getAnnotation("declaringPackage");
// Make the hidden variable name fully qualified with the declaring package
String qualifiedHiddenVarName = hiddenVarName;
if (declaringPackage != null && !hiddenVarName.contains("::")) {
qualifiedHiddenVarName = declaringPackage + "::" + hiddenVarName;
}
// Create reference to hidden variable: &$hiddenVar
// IMPORTANT: For state variables, we need to preserve the ID from the declaration!
OperatorNode dollarOp = new OperatorNode("$",
new IdentifierNode(qualifiedHiddenVarName, index), index);
// Propagate hiddenVarName annotation so that emitters can detect lexical subs
// (e.g., for `undef &x` and `defined(&x)` special handling)
dollarOp.setAnnotation("hiddenVarName", hiddenVarName);
// Copy the ID from the original declaration if it's a state variable
if (varNode.operator.equals("state") && varNode.operand instanceof OperatorNode innerNode) {
dollarOp.id = innerNode.id;
}
// If we're taking a reference (\&foo), return &$hiddenVar
// This becomes \&$hiddenVar which calls createCodeReference
// createCodeReference will detect the CODE value and return it directly
// But if the next token is '(', this is a call, not a reference take
if (parser.parsingTakeReference && !TokenUtils.peek(parser).text.equals("(")) {
return new OperatorNode("&", dollarOp, index);
}
// Handle arguments for actual calls (&foo or &foo())
// Use $hiddenVar directly - the () operator will handle dereferencing
Node list;
boolean shareArgs = false;
if (!TokenUtils.peek(parser).text.equals("(")) {
list = atUnderscore(parser);
shareArgs = true; // &func shares caller's @_
} else {
list = ListParser.parseZeroOrMoreList(parser, 0, false, true, false, false);
}
BinaryOperatorNode callNode = new BinaryOperatorNode("(", dollarOp, list, index);
if (shareArgs) callNode.setAnnotation("shareCallerArgs", true);
return callNode;
}
}
}
// Set a flag to allow parentheses after a variable, as in &$sub(...)
parser.parsingForLoopVariable = true;
// Parse the variable following the `&` sigil
Node node = parseVariable(parser, token.text);
// Reset the flag after parsing
parser.parsingForLoopVariable = false;
// If we are parsing a reference (e.g., \&sub or defined(&sub)),
// return the node without adding parameters.
// But if the next token is '(', this is a call like defined(&$sub("args")),
// so we should parse the arguments and treat it as a call.
if (parser.parsingTakeReference && !peek(parser).text.equals("(")) {
return node;
}
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("parse & node: " + node);
// Check if the node is an OperatorNode with a BinaryOperatorNode operand
if (node instanceof OperatorNode operatorNode) {
if (operatorNode.operand instanceof IdentifierNode identifierNode
&& identifierNode.name.equals("CORE::__SUB__")
&& parser.ctx.symbolTable.isFeatureCategoryEnabled("current_sub")) {
// &CORE::__SUB__
return new OperatorNode("__SUB__", new ListNode(index), index);
}
if (operatorNode.operand instanceof BinaryOperatorNode binaryOperatorNode) {
// If the operator is `(`, return the BinaryOperatorNode directly
if (binaryOperatorNode.operator.equals("(")) {
return binaryOperatorNode;
}
}
}
Node list;
boolean shareArgs = false;
// If the next token is not `(`, handle auto-call by transforming `&subr` to `&subr(@_)`
if (!peek(parser).text.equals("(")) {
list = atUnderscore(parser);
shareArgs = true; // &func shares caller's @_
} else {
// Otherwise, parse the list of arguments
list = ListParser.parseZeroOrMoreList(parser,
0,
false,
true,
false,
false);
}
// Handle cases where the node is an OperatorNode
if (node instanceof OperatorNode operatorNode) {
// If the operand is another OperatorNode, transform &$sub to $sub(@_)
if (operatorNode.operand instanceof OperatorNode) {
node = operatorNode.operand;
} else if (operatorNode.operand instanceof BlockNode blockNode) {
// If the operand is a BlockNode, transform &{$sub} to $sub(@_)
node = blockNode;
}
}
// Return a new BinaryOperatorNode representing the function call with arguments
BinaryOperatorNode callNode = new BinaryOperatorNode("(", node, list, parser.tokenIndex);
if (shareArgs) callNode.setAnnotation("shareCallerArgs", true);
return callNode;
}
/**
* Parses a braced variable expression like {@code ${var}} or {@code ${expr}}.
*
* <p>This method handles various braced forms:
* <ul>
* <li>Simple braced variables: {@code ${var}}, {@code @{array}}, {@code %{hash}}</li>
* <li>Complex expressions: {@code ${$ref}}, {@code ${expr}}</li>
* <li>Array/hash access: {@code ${array[0]}}, {@code ${hash{key}}}</li>
* <li>Empty braces: {@code ${}} (returns empty string)</li>
* </ul>
*
* <p>The method is shared between regular variable parsing and string interpolation.
* When used in string interpolation context, it handles special escaping rules for
* quotes inside the braces (e.g., {@code "${\"quoted\"}"})</p>
*
* @param parser the parser instance
* @param sigil the sigil that precedes the braced expression ($, @, %, etc.)
* @param isStringInterpolation true if parsing within a string interpolation context
* @return A Node representing the parsed braced variable expression
* @throws PerlCompilerException if the braced expression is malformed or unterminated
*/
public static Node parseBracedVariable(Parser parser, String sigil, boolean isStringInterpolation) {
int startLineNumber = parser.ctx.errorUtil.getLineNumber(parser.tokenIndex - 1); // Save line number before peek() side effects
TokenUtils.consume(parser); // Consume the '{'
// Check if this is an empty ${} construct
if (TokenUtils.peek(parser).text.equals("}")) {
TokenUtils.consume(parser); // Consume the '}'
return new OperatorNode(sigil, new StringNode("", parser.tokenIndex), parser.tokenIndex);
}
// For string interpolation, preprocess \" sequences IN PLACE
if (isStringInterpolation) {
int startIndex = parser.tokenIndex;
int braceLevel = 1;
while (braceLevel > 0 && parser.tokenIndex < parser.tokens.size()) {
var token = parser.tokens.get(parser.tokenIndex);
if (token.type == LexerTokenType.EOF) {
break;
}
if (token.text.equals("{")) {
braceLevel++;
parser.tokenIndex++;
} else if (token.text.equals("}")) {
braceLevel--;
if (braceLevel == 0) {
break; // Don't consume the closing brace yet
}
parser.tokenIndex++;
} else if (token.text.equals("\\") && parser.tokenIndex + 1 < parser.tokens.size()) {
var nextToken = parser.tokens.get(parser.tokenIndex + 1);
if (nextToken.text.equals("\"")) {
// Just remove the backslash - the quote token will slide down to current position
parser.tokens.remove(parser.tokenIndex);
// DON'T increment tokenIndex - the quote is now at the current position
// and we want to move past it in the next iteration
} else {
parser.tokenIndex++;
}
} else {
parser.tokenIndex++;
}
}
// Reset to start position and continue with original parsing logic
parser.tokenIndex = startIndex;
}
// Continue with original parsing logic - this preserves context for special variables
int savedIndex = parser.tokenIndex;
// Check if this starts with ^ (control character variable)
String bracedVarName = null;
if (parser.tokens.get(parser.tokenIndex).text.equals("^")) {
// Save position before trying to parse ^ variable
int beforeCaret = parser.tokenIndex;
parser.tokenIndex++; // consume ^
// Now parse the identifier part after ^
String identifier = IdentifierParser.parseComplexIdentifierInner(parser, false);
if (identifier != null && !identifier.isEmpty()) {
// Convert ^X to control character as parseComplexIdentifier would do
char firstChar = identifier.charAt(0);
String ctrlChar;
if (firstChar >= 'A' && firstChar <= 'Z') {
ctrlChar = String.valueOf((char) (firstChar - 'A' + 1));
} else if (firstChar >= 'a' && firstChar <= 'z') {
ctrlChar = String.valueOf((char) (firstChar - 'a' + 1));
} else if (firstChar == '@') {
ctrlChar = String.valueOf((char) 0);
} else if (firstChar >= '[' && firstChar <= '_') {
ctrlChar = String.valueOf((char) (firstChar - '[' + 27));
} else if (firstChar == '?') {
ctrlChar = String.valueOf((char) 127);
} else {
ctrlChar = String.valueOf(firstChar);
}
bracedVarName = ctrlChar + identifier.substring(1);
} else {
// Failed to parse identifier after ^, restore position
parser.tokenIndex = beforeCaret;
}
}
// If we didn't parse a ^ variable, try normal parsing
if (bracedVarName == null) {
bracedVarName = IdentifierParser.parseComplexIdentifierInner(parser, true);
}
if (bracedVarName != null) {
// Check if this might be ambiguous with an operator
boolean isAmbiguous = isAmbiguousOperatorName(bracedVarName);
// Check if this is potentially an operator (s, m, q, etc.) followed by delimiter
if (isMaybeOperator(bracedVarName, parser)) {
// Reset and parse as expression
parser.tokenIndex = savedIndex;
} else if (isBuiltinFunctionFollowedByArrow(bracedVarName, parser)) {
// Built-in function followed by -> should be parsed as expression, not variable
// Example: @{ shift->{'pagers'} } should be @{ (shift)->{'pagers'} }
parser.tokenIndex = savedIndex;
} else {
Node operand = new OperatorNode(sigil, new IdentifierNode(bracedVarName, parser.tokenIndex), parser.tokenIndex);
try {
int beforeAccess = parser.tokenIndex;
operand = parseArrayHashAccessInBraces(parser, operand, isStringInterpolation);
// Check if we successfully parsed to the closing brace
if (TokenUtils.peek(parser).text.equals("}")) {
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// Issue ambiguity warning if needed (not inside string interpolation,
// matching Perl 5 which only warns in code context)
if (isAmbiguous && !isStringInterpolation) {
String accessType = "";
if (operand instanceof BinaryOperatorNode binOp) {
if (binOp.operator.equals("[")) {
accessType = "[...]";
} else if (binOp.operator.equals("{")) {
accessType = "{...}";
}
}
if (accessType.isEmpty()) {
// Simple variable like ${s}
WarnDie.warn(
new RuntimeScalar("Ambiguous use of ${" + bracedVarName + "} resolved to $" + bracedVarName),
new RuntimeScalar(parser.ctx.errorUtil.errorMessage(parser.tokenIndex, "")),
null, 0
);
} else {
// Array/hash access like ${tr[10]}
WarnDie.warn(
new RuntimeScalar("Ambiguous use of ${" + bracedVarName + accessType + "} resolved to $" + bracedVarName + accessType),
new RuntimeScalar(parser.ctx.errorUtil.errorMessage(parser.tokenIndex, "")),
null, 0
);
}
}
return operand;
} else {
// We didn't reach the closing brace, which means there's more content
// that couldn't be parsed as array/hash access. This might be an operator.
parser.tokenIndex = savedIndex;
}
} catch (Exception e) {
if (e instanceof PerlParserException) {
throw (PerlParserException) e;
}
parser.tokenIndex = savedIndex;
}
}
} else {
parser.tokenIndex = savedIndex;
}
// Check for heredoc constructs like ${<<END} which should evaluate to empty string
// The challenge is distinguishing ${<<END} from ${<...>} where $< is a special variable
if (parser.tokenIndex < parser.tokens.size()) {
var currentToken = parser.tokens.get(parser.tokenIndex);
if (currentToken.text.equals("<")) {
// Look ahead to see if this is <<IDENTIFIER (heredoc) vs <...> (angle brackets)
if (parser.tokenIndex + 1 < parser.tokens.size()) {
var nextToken = parser.tokens.get(parser.tokenIndex + 1);
// If the next token after < is an identifier (not another <), this could be <<IDENTIFIER
// We need to check if this pattern matches heredoc syntax
if (nextToken.type == LexerTokenType.IDENTIFIER) {
// This looks like <<IDENTIFIER - treat as heredoc in ${<<END} context
// Skip the < token
parser.tokenIndex++;
// Get the identifier
String identifier = nextToken.text;
parser.tokenIndex++; // Skip identifier
// Create a heredoc node and add it to the queue for later processing
OperatorNode heredocNode = new OperatorNode("HEREDOC", null, parser.tokenIndex);
heredocNode.setAnnotation("identifier", identifier);
heredocNode.setAnnotation("delimiter", "\""); // Default to double-quoted
parser.getHeredocNodes().add(heredocNode);
// Consume the closing brace