-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathStringSegmentParser.java
More file actions
1516 lines (1366 loc) · 66.7 KB
/
Copy pathStringSegmentParser.java
File metadata and controls
1516 lines (1366 loc) · 66.7 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.frontend.analysis.ConstantFoldingVisitor;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.frontend.lexer.LexerToken;
import org.perlonjava.frontend.lexer.LexerTokenType;
import org.perlonjava.runtime.operators.PerlUtfString;
import org.perlonjava.runtime.regex.UnicodeResolver;
import org.perlonjava.runtime.runtimetypes.PerlCompilerException;
import org.perlonjava.runtime.runtimetypes.RuntimeScalar;
import org.perlonjava.runtime.runtimetypes.ScalarUtils;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import static org.perlonjava.frontend.parser.ParseBlock.parseBlock;
import static org.perlonjava.frontend.parser.Variable.parseArrayHashAccess;
import static org.perlonjava.runtime.perlmodule.Strict.HINT_UTF8;
/**
* Base class for parsing strings with segments and variable interpolation.
*
* <p>This abstract class provides the foundation for parsing Perl-style strings that may contain
* variable interpolation (like $var, @array) and escape sequences. It handles the segmentation
* of strings into literal text parts and interpolated expressions, which are then combined
* into a single AST node representing the complete string.</p>
*
* <p>The parser works by tokenizing the string content and identifying special sequences:
* <ul>
* <li>Variable interpolation: $scalar, @array, ${expression}</li>
* <li>Escape sequences: \n, \t, \x{hex}, \N{unicode_name}, etc.</li>
* <li>Control characters: \cA, \cZ, etc.</li>
* </ul></p>
*
* <p>Subclasses can override specific methods to customize behavior for different string types
* (e.g., quoted strings vs regex patterns, case modification, quotemeta application).</p>
*
* @see StringParser
*/
public abstract class StringSegmentParser {
/**
* Static counter for generating globally unique capture group names for regex code blocks
* Must be static to ensure names don't collide across different patterns that share
* the same pendingCodeBlockConstants map
*/
/**
* The emitter context for logging and error handling
*/
protected final EmitterContext ctx;
/**
* The list of tokens representing the string content
*/
protected final List<LexerToken> tokens;
/**
* The parser instance for parsing embedded expressions
*/
protected final Parser parser;
/**
* The token index in the original source for error reporting
*/
protected final int tokenIndex;
/**
* Flag indicating if this is parsing a regex pattern (affects bracket handling)
*/
protected final boolean isRegex;
protected final boolean isRegexReplacement;
protected final boolean isRegexQuoteConstruction;
/**
* Buffer for accumulating literal text segments
*/
protected final StringBuilder currentSegment;
private boolean currentSegmentHasSourceNonAscii = false;
private boolean inRegexCharClass = false;
private boolean regexCharClassFirst = false;
/**
* List of AST nodes representing string segments (literals and interpolated expressions)
*/
protected final List<Node> segments;
protected boolean hasExecutableRegexCallbacks;
protected boolean hasRuntimeInterpolation;
protected final boolean interpolateVariable;
protected final boolean parseEscapes;
/**
* Original token offset for mapping string positions back to source
*/
private int originalTokenOffset = 0;
/**
* Original string content for better error context
*/
private String originalStringContent = "";
/**
* Constructs a new StringSegmentParser with the specified parameters.
*
* @param ctx the emitter context for logging and error handling
* @param tokens the list of tokens representing the string content
* @param parser the parser instance for parsing embedded expressions
* @param tokenIndex the token index in the original source for error reporting
* @param isRegex flag indicating if this is parsing a regex pattern
*/
public StringSegmentParser(EmitterContext ctx, List<LexerToken> tokens, Parser parser, int tokenIndex, boolean isRegex, boolean parseEscapes, boolean interpolateVariable, boolean isRegexReplacement) {
this(ctx, tokens, parser, tokenIndex, isRegex, parseEscapes, interpolateVariable, isRegexReplacement, false);
}
public StringSegmentParser(EmitterContext ctx, List<LexerToken> tokens, Parser parser, int tokenIndex, boolean isRegex, boolean parseEscapes, boolean interpolateVariable, boolean isRegexReplacement, boolean isRegexQuoteConstruction) {
this.ctx = ctx;
this.tokens = tokens;
this.parser = parser;
this.tokenIndex = tokenIndex;
this.isRegex = isRegex;
this.parseEscapes = parseEscapes;
this.currentSegment = new StringBuilder();
this.segments = new ArrayList<>();
this.interpolateVariable = interpolateVariable;
this.isRegexReplacement = isRegexReplacement;
this.isRegexQuoteConstruction = isRegexQuoteConstruction;
}
/**
* Appends text to the current literal segment buffer.
*
* <p>Subclasses can override this method to apply transformations such as:
* <ul>
* <li>Case modification (uppercase, lowercase, title case)</li>
* <li>Quote metacharacters for regex</li>
* <li>Other string transformations</li>
* </ul></p>
*
* @param text the text to append to the current segment
*/
protected void appendToCurrentSegment(String text) {
currentSegment.append(text);
}
protected void appendLiteralToCurrentSegment(String text) {
appendToCurrentSegment(text);
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
updateRegexCharClassState(c);
if (c > 127) {
currentSegmentHasSourceNonAscii = true;
}
}
}
protected boolean isInsideRegexCharClass() {
return isRegex && inRegexCharClass;
}
/**
* Whether regex code-block openers have their ordinary special meaning at the current point.
* Subclasses may suppress them while parsing a quoting region such as {@code \Q...\E}.
*/
protected boolean regexCodeBlocksAreActive() {
return true;
}
private void updateRegexCharClassState(char c) {
if (!isRegex) {
return;
}
if (c == '[' && !inRegexCharClass) {
inRegexCharClass = true;
regexCharClassFirst = true;
} else if (c == ']' && inRegexCharClass && !regexCharClassFirst) {
inRegexCharClass = false;
} else if (inRegexCharClass && regexCharClassFirst && c != '^') {
regexCharClassFirst = false;
}
}
/**
* Adds a string segment node to the segments list.
*
* <p>Subclasses can override this method to apply transformations to string nodes
* before adding them to the segments list. This is useful for applying operations
* like quotemeta or case modifications to literal string segments.</p>
*
* @param node the AST node representing a string segment
*/
protected void addStringSegment(Node node) {
segments.add(node);
}
/**
* Flushes the current segment buffer to the segments list if it contains content.
*
* <p>This method is called whenever we encounter an interpolated expression or
* reach the end of the string. It converts the accumulated literal text in
* {@code currentSegment} into a StringNode and adds it to the segments list.</p>
*/
protected void flushCurrentSegment() {
if (!currentSegment.isEmpty()) {
String value = currentSegment.toString();
if (currentSegmentHasSourceNonAscii
&& !ctx.symbolTable.isStrictOptionEnabled(HINT_UTF8)
&& !ctx.compilerOptions.isUnicodeSource
&& !ctx.compilerOptions.isByteStringSource) {
byte[] utf8 = value.getBytes(java.nio.charset.StandardCharsets.UTF_8);
StringBuilder octets = new StringBuilder(utf8.length);
for (byte b : utf8) {
octets.append((char) (b & 0xff));
}
value = octets.toString();
}
boolean forceByteString = shouldForceByteStringLiteral(value);
addStringSegment(new StringNode(value, false, forceByteString, tokenIndex));
currentSegment.setLength(0);
currentSegmentHasSourceNonAscii = false;
}
}
private boolean shouldForceByteStringLiteral(String value) {
if (!ctx.symbolTable.isStrictOptionEnabled(HINT_UTF8)
&& !ctx.compilerOptions.isUnicodeSource) {
return false;
}
if (currentSegmentHasSourceNonAscii) {
return false;
}
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) > 255) {
return false;
}
}
return true;
}
/**
* Parses variable interpolation sequences like $var, @var, ${...}, @{...}.
*
* <p>This method handles several forms of variable interpolation:
* <ul>
* <li>Simple variables: $var, @array</li>
* <li>Complex expressions: ${expr}, @{expr}</li>
* <li>Dereferenced variables: $var, $var</li>
* <li>Array/hash access: $var[0], $var{key}, $var->[0], $var->{key}</li>
* </ul></p>
*
* <p>For array variables (@var), the result is automatically joined with the
* current list separator ($").</p>
*
* @param sigil the variable sigil ("$" for scalars, "@" for arrays, "$#" for array length)
* @throws PerlCompilerException if the interpolation syntax is invalid
*/
protected void parseVariableInterpolation(String sigil) {
flushCurrentSegment();
hasRuntimeInterpolation = true;
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("str sigil");
Node operand;
var isArray = "@".equals(sigil);
var isArrayPostderef = false;
if (TokenUtils.peek(parser).text.equals("{")) {
// Handle block-like interpolation: ${...} or @{...}
// Check if this is an @{[...]} construct (array reference interpolation)
if (isArray) {
int savedIndex = parser.tokenIndex;
TokenUtils.consume(parser); // Consume the '{'
if (TokenUtils.peek(parser).text.equals("[")) {
// This is @{[...]} - create anonymous array reference and dereference
// Parse the entire {...} content as a block
// Restore to saved position (before '{') so parseBlock sees the '{'
// (can't just decrement by 1 because peek() may have skipped whitespace)
parser.tokenIndex = savedIndex;
TokenUtils.consume(parser); // Re-consume the '{'
try {
Node block = ParseBlock.parseBlock(parser); // Parse the block inside the curly brackets
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}"); // Consume the '}'
// Apply @ to dereference the block result
operand = new OperatorNode("@", block, tokenIndex);
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("str @{[...]} operand " + operand);
} catch (PerlCompilerException e) {
// Re-throw with offset-aware error reporting
createOffsetAwareError(tokenIndex, "Syntax error in @{[...]} block: " + e.getMessage());
return; // This line will never be reached, but satisfies compiler
}
} else {
// Not @{[...]}, restore position and use parseBracedVariable
parser.tokenIndex = savedIndex;
try {
operand = Variable.parseBracedVariable(parser, sigil, true);
} catch (PerlCompilerException e) {
// Extract the core error message, removing any existing "Syntax error in braced variable:" prefix
String coreMessage = e.getMessage();
if (coreMessage.startsWith("Syntax error in braced variable: ")) {
coreMessage = coreMessage.substring("Syntax error in braced variable: ".length());
}
// Re-throw with offset-aware error reporting
createOffsetAwareError(tokenIndex, "Syntax error in braced variable: " + coreMessage);
return; // This line will never be reached, but satisfies compiler
}
}
} else {
// Regular ${...} handling - let parseBracedVariable consume the '{'
try {
operand = Variable.parseBracedVariable(parser, sigil, true);
} catch (PerlCompilerException e) {
// Extract the core error message, removing any existing "Syntax error in braced variable:" prefix
String coreMessage = e.getMessage();
if (coreMessage.startsWith("Syntax error in braced variable: ")) {
coreMessage = coreMessage.substring("Syntax error in braced variable: ".length());
}
// Re-throw with offset-aware error reporting
createOffsetAwareError(tokenIndex, "Syntax error in braced variable: " + coreMessage);
return; // This line will never be reached, but satisfies compiler
}
}
// After ${...}, parse subscript access like ${$ref}{key} or ${$ref}[0]
// This matches Perl 5 where "${$hashref}{key}" = $hashref->{key}
//
// However, when ${var} uses explicit braces with a simple variable name,
// [...] and {...} should NOT be parsed as subscripts.
// Perl 5 rule: explicit braces terminate the variable name, so:
// In regex: ${var}[0] = scalar $var + char class [0]
// In string: "${var}[0]" = scalar $var + literal "[0]"
// vs: $var[0] = array element $var[0]
// Only deref expressions like ${$ref}[0] should parse subscripts after braces.
boolean isSimpleBracedVariable = !isArray
&& operand instanceof OperatorNode opNode
&& "$".equals(opNode.operator)
&& opNode.operand instanceof IdentifierNode;
if (!isSimpleBracedVariable) {
try {
operand = parseArrayHashAccess(parser, operand, isRegex);
} catch (Exception e) {
// If array/hash access parsing fails, use operand as-is
}
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("str operand " + operand);
} else {
// Parse simple variables using shared logic, but keep the exact same flow
operand = parseSimpleVariableInterpolation(sigil);
// Postfix array dereferences interpolate like ordinary arrays and
// therefore use $" between elements: "$ref->@*" and
// "$ref->@[...]" / "$ref->@{...}".
boolean dereferenceArrowFollows = "$".equals(sigil)
&& parser.tokenIndex + 1 < parser.tokens.size()
&& "->".equals(parser.tokens.get(parser.tokenIndex).text);
boolean postfixDerefFollows = false;
if (dereferenceArrowFollows) {
postfixDerefFollows = switch (parser.tokens.get(parser.tokenIndex + 1).text) {
case "@*", "$*", "%*", "&*", "$#", "@", "%" -> true;
default -> false;
};
}
boolean postfixDerefInterpolationEnabled = ctx.symbolTable != null
&& ctx.symbolTable.isFeatureCategoryEnabled("postderef_qq");
if (postfixDerefFollows && postfixDerefInterpolationEnabled) {
String postderef = parser.tokens.get(parser.tokenIndex + 1).text;
isArrayPostderef = postderef.equals("@") || postderef.equals("@*");
}
// Handle array/hash access: $var[0], $var{key}, $var->[0], etc.
// Wrap in try-catch to handle malformed access gracefully
try {
// In regex replacement context, check if $var{N} or $var{N,M} should be treated as quantifier
if ("$".equals(sigil) && isRegexReplacement && parser.tokens.get(parser.tokenIndex).text.equals("{") && shouldTreatAsQuantifier()) {
// Skip parsing as hash access - leave for regex engine to handle as quantifier
} else if (!postfixDerefFollows || postfixDerefInterpolationEnabled) {
operand = parseArrayHashAccess(parser, operand, isRegex);
}
} catch (Exception e) {
// If array/hash access parsing fails, throw a more descriptive error
throw new PerlCompilerException(tokenIndex, "syntax error: Unterminated array or hash access", ctx.errorUtil);
}
}
// For arrays, join elements with the list separator ($")
if (isArray || isArrayPostderef) {
operand = new BinaryOperatorNode("join",
new OperatorNode("$", new IdentifierNode("\"", tokenIndex), tokenIndex),
operand,
tokenIndex);
}
addStringSegment(operand);
}
/**
* Determines if the current position should be treated as a regex quantifier rather than hash access.
* This applies only in regex replacement context and when we see patterns like {3} or {2,5}.
*
* @return true if this should be treated as a regex quantifier
*/
private boolean shouldTreatAsQuantifier() {
// Save current position to look ahead
int savedIndex = parser.tokenIndex;
try {
TokenUtils.consume(parser); // consume '{'
String firstToken = TokenUtils.peek(parser).text;
// Check for {,N} pattern
if (",".equals(firstToken)) {
TokenUtils.consume(parser);
if (ScalarUtils.isInteger(TokenUtils.peek(parser).text)) {
TokenUtils.consume(parser);
return "}".equals(TokenUtils.peek(parser).text);
}
return false;
}
// Check for {N}, {N,}, {N,M} patterns
if (ScalarUtils.isInteger(firstToken)) {
TokenUtils.consume(parser);
String nextToken = TokenUtils.peek(parser).text;
if ("}".equals(nextToken)) {
return true; // {N}
}
if (",".equals(nextToken)) {
TokenUtils.consume(parser);
String afterComma = TokenUtils.peek(parser).text;
if ("}".equals(afterComma)) {
return true; // {N,}
}
if (ScalarUtils.isInteger(afterComma)) {
TokenUtils.consume(parser);
return "}".equals(TokenUtils.peek(parser).text); // {N,M}
}
}
}
return false;
} finally {
// Always restore position - we're just looking ahead
parser.tokenIndex = savedIndex;
}
}
/**
* Helper method to parse simple variable interpolation (non-braced forms).
* Uses shared logic from Variable class while maintaining string interpolation context.
*/
private Node parseSimpleVariableInterpolation(String sigil) {
// Store the current position before parsing the identifier
int startIndex = parser.tokenIndex;
// Check for ${...} pattern which should be parsed as ${${...}}
// This handles cases like $var, $ $var, etc.
if ("$".equals(sigil) && TokenUtils.peek(parser).text.equals("$")) {
// Save position to check what comes after the second $
int savedIndex = parser.tokenIndex;
TokenUtils.consume(parser); // Consume the second $
// Check if what follows the second $ is immediately a braced expression
if (parser.tokens.get(parser.tokenIndex).text.equals("{")) {
// This is ${...} pattern - parse as ${${...}}
// Restore position and consume the second $ properly
parser.tokenIndex = savedIndex;
TokenUtils.consume(parser); // Consume the second $
// Now parse ${...} where the content is ${...}
Node innerVariable = Variable.parseBracedVariable(parser, "$", true);
return new OperatorNode("$", innerVariable, tokenIndex);
} else {
// Not ${...}, restore position and continue with normal parsing
parser.tokenIndex = savedIndex;
}
}
// Continue with existing logic for other cases...
var identifier = IdentifierParser.parseComplexIdentifier(parser);
if (identifier != null) {
// Add validation that was missing - this fixes $01, $02 issues
IdentifierParser.validateIdentifier(parser, identifier, startIndex);
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("str Identifier: " + identifier);
// Check if this is a field that needs transformation to $self->{field}
// This mirrors the logic in Variable.parseVariable
if (parser.isInMethod && Variable.isFieldInClassHierarchy(parser, identifier)) {
String localVar = sigil + identifier;
// Only transform if not shadowed by a local variable
if (parser.ctx.symbolTable.getVariableIndexInCurrentScope(localVar) == -1) {
// Transform field access to $self->{field}
// Create $self
OperatorNode selfVar = new OperatorNode("$",
new IdentifierNode("self", tokenIndex), tokenIndex);
// Create hash subscript for field access
List<Node> keyList = new ArrayList<>();
keyList.add(new IdentifierNode(identifier, tokenIndex));
HashLiteralNode hashSubscript = new HashLiteralNode(keyList, tokenIndex);
// Create $self->{fieldname}
Node fieldAccess = new BinaryOperatorNode("->", selfVar, hashSubscript, tokenIndex);
// For array and hash fields, we need to dereference the reference
if (sigil.equals("@") || sigil.equals("%")) {
// @field becomes @{$self->{field}}
// %field becomes %{$self->{field}}
return new OperatorNode(sigil, fieldAccess, tokenIndex);
} else {
// Scalar fields: $field becomes $self->{field}
return fieldAccess;
}
}
}
// Special case: empty identifier for $ sigil (like $ at end of string)
if ("$".equals(sigil) && identifier.isEmpty()) {
// Check if we're at end of string
if (parser.tokenIndex >= parser.tokens.size() ||
parser.tokens.get(parser.tokenIndex).type == LexerTokenType.EOF) {
throw new PerlCompilerException(tokenIndex, "Final $ should be \\$ or $name", ctx.errorUtil);
}
}
return new OperatorNode(sigil, new IdentifierNode(identifier, tokenIndex), tokenIndex);
} else {
// No identifier found after sigil
// Check if we're at end of string for $ sigil
if ("$".equals(sigil) && (parser.tokenIndex >= parser.tokens.size() ||
parser.tokens.get(parser.tokenIndex).type == LexerTokenType.EOF)) {
throw new PerlCompilerException(tokenIndex, "Final $ should be \\$ or $name", ctx.errorUtil);
}
// For array sigils, check if next token starts with $ (e.g., @$b means array of $b)
if ("@".equals(sigil) && parser.tokenIndex < parser.tokens.size()) {
LexerToken nextToken = parser.tokens.get(parser.tokenIndex);
if (nextToken.text.startsWith("$")) {
// This is @$var or @${expr} - array dereference of scalar
// Consume the $ token
TokenUtils.consume(parser);
// Check if next is { for @${expr} pattern (e.g., @${$v})
if (parser.tokenIndex < parser.tokens.size() &&
parser.tokens.get(parser.tokenIndex).text.equals("{")) {
// @${...} - parse as ${...} then wrap in @
Node scalarExpr = Variable.parseBracedVariable(parser, "$", true);
return new OperatorNode("@", scalarExpr, tokenIndex);
}
// Now parse the rest of the identifier
identifier = IdentifierParser.parseComplexIdentifier(parser);
if (identifier == null || identifier.isEmpty()) {
throw new PerlCompilerException(tokenIndex, "Missing identifier after $", ctx.errorUtil);
}
// Return the array of scalar variable
return new OperatorNode(sigil, new OperatorNode("$", new IdentifierNode(identifier, tokenIndex), tokenIndex), tokenIndex);
}
}
// $#$var / $#${expr} — last index of the array referenced by the scalar.
// Operand must be the scalar $var (not @-wrapped): JVM codegen adds @ for $# (EmitOperatorNode).
if ("$#".equals(sigil) && parser.tokenIndex < parser.tokens.size()) {
LexerToken nextTok = parser.tokens.get(parser.tokenIndex);
if (nextTok.text.startsWith("$")) {
TokenUtils.consume(parser);
if (parser.tokenIndex < parser.tokens.size()
&& parser.tokens.get(parser.tokenIndex).text.equals("{")) {
Node scalarExpr = Variable.parseBracedVariable(parser, "$", true);
return new OperatorNode("$#", scalarExpr, tokenIndex);
}
identifier = IdentifierParser.parseComplexIdentifier(parser);
if (identifier == null || identifier.isEmpty()) {
throw new PerlCompilerException(tokenIndex, "Missing identifier after $", ctx.errorUtil);
}
IdentifierParser.validateIdentifier(parser, identifier, startIndex);
Node scalarVar =
new OperatorNode("$", new IdentifierNode(identifier, tokenIndex), tokenIndex);
return new OperatorNode("$#", scalarVar, tokenIndex);
}
}
if (!"$".equals(sigil)) {
throw new PerlCompilerException(tokenIndex, "Missing identifier after " + sigil, ctx.errorUtil);
}
// For $ sigil with no identifier, check if we're at end of string
if (parser.tokenIndex >= parser.tokens.size() ||
parser.tokens.get(parser.tokenIndex).type == LexerTokenType.EOF) {
throw new PerlCompilerException(tokenIndex, "Final $ should be \\$ or $name", ctx.errorUtil);
}
}
// Handle dereferenced variables: ${$var}, ${${$var}}, etc.
int dollarCount = 0;
while (TokenUtils.peek(parser).text.equals("$")) {
dollarCount++;
parser.tokenIndex++;
}
if (dollarCount > 0) {
identifier = IdentifierParser.parseComplexIdentifier(parser);
if (identifier == null) {
throw new PerlCompilerException(tokenIndex, "Unexpected value after $ in string", ctx.errorUtil);
}
// Add validation for dereferenced variables too
IdentifierParser.validateIdentifier(parser, identifier, startIndex);
Node operand = new IdentifierNode(identifier, tokenIndex);
// Apply dereference operators
for (int i = 0; i < dollarCount; i++) {
operand = new OperatorNode("$", operand, tokenIndex);
}
return new OperatorNode(sigil, operand, tokenIndex);
} else {
throw new PerlCompilerException(tokenIndex, "Unexpected value after " + sigil + " in string", ctx.errorUtil);
}
}
/**
* Builds the final AST node from all collected segments.
*
* <p>The result depends on the number of segments:
* <ul>
* <li>0 segments: Returns an empty StringNode</li>
* <li>1 segment: Returns the segment directly if it's a StringNode,
* otherwise wraps it in a join operation</li>
* <li>Multiple segments: Returns a join operation that concatenates all segments</li>
* </ul></p>
*
* <p>The join operation uses an empty string as the separator, effectively
* concatenating all segments together.</p>
*
* @return the final AST node representing the complete string
*/
protected Node buildResult() {
flushCurrentSegment();
if (needsStructuredRegexTemplate()) {
return new OperatorNode("regexTemplate", new ListNode(segments, tokenIndex), tokenIndex);
}
return switch (segments.size()) {
case 0 -> new StringNode("", tokenIndex);
case 1 -> {
var result = segments.getFirst();
if (result instanceof StringNode) {
yield result;
}
// Single non-string segment needs to be converted to string
yield new BinaryOperatorNode("join",
new StringNode("", tokenIndex),
new ListNode(segments, tokenIndex),
tokenIndex);
}
default ->
// Multiple segments: join them all together
new BinaryOperatorNode("join",
new StringNode("", tokenIndex),
new ListNode(segments, tokenIndex),
tokenIndex);
};
}
/** Preserve regex-valued interpolation so embedded callback tables are not stringified away. */
protected boolean needsStructuredRegexTemplate() {
return hasExecutableRegexCallbacks || (isRegex && hasRuntimeInterpolation);
}
/**
* Abstract method for parsing escape sequences.
*
* <p>Subclasses must implement this method to handle escape sequences
* appropriate for their string type. Common escape sequences include:
* <ul>
* <li>Standard escapes: \n, \t, \r, \\, \"</li>
* <li>Octal escapes: \123</li>
* <li>Hex escapes: \x41, \x{41}</li>
* <li>Unicode escapes: \N{LATIN CAPITAL LETTER A}</li>
* <li>Control characters: \cA, \cZ</li>
* </ul></p>
*/
protected abstract void parseEscapeSequence();
/**
* Template method for parsing the complete string.
*
* <p>This method implements the main parsing loop, processing tokens one by one
* and delegating to specialized methods for handling different token types.
* The overall structure is maintained while allowing subclasses to customize
* specific behaviors through method overrides.</p>
*
* @return the final AST node representing the parsed string
*/
public Node parse() {
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser.parse: Starting with " + tokens.size() + " tokens, heredoc count: " + parser.getHeredocNodes().size());
while (true) {
if (parser.tokenIndex >= tokens.size()) {
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser.parse: Reached end of tokens at index " + parser.tokenIndex);
break;
}
var token = tokens.get(parser.tokenIndex++);
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser.parse: Token at " + (parser.tokenIndex - 1) + ": type=" + token.type + ", text='" + token.text.replace("\n", "\\n") + "'");
if (token.type == LexerTokenType.EOF) {
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser.parse: Found EOF token");
break;
}
// Check for NEWLINE tokens to process pending heredocs
if (token.type == LexerTokenType.NEWLINE) {
// Check if there are pending heredocs to process
if (!parser.getHeredocNodes().isEmpty()) {
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser: Found NEWLINE with " + parser.getHeredocNodes().size() + " pending heredocs at index " + (parser.tokenIndex - 1));
// Log which heredocs are pending
for (OperatorNode heredoc : parser.getHeredocNodes()) {
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug(" Pending heredoc: " + heredoc.getAnnotation("identifier"));
}
// Flush current segment before processing heredocs
flushCurrentSegment();
// Adjust tokenIndex to point to the NEWLINE token for parseHeredocAfterNewline
parser.tokenIndex--; // Back up to the NEWLINE token
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser: Calling parseHeredocAfterNewline with tokenIndex=" + parser.tokenIndex);
// Process ALL heredocs after the newline
ParseHeredoc.parseHeredocAfterNewline(parser);
// Check if we've consumed all tokens
if (parser.tokenIndex >= tokens.size()) {
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser: Heredoc processing consumed all remaining tokens");
break;
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser: After heredoc processing, tokenIndex = " + parser.tokenIndex + ", remaining tokens = " + (tokens.size() - parser.tokenIndex));
// parseHeredocAfterNewline updates parser.tokenIndex, so continue from there
continue;
} else {
// No heredocs pending, append the newline normally
appendLiteralToCurrentSegment(token.text);
}
continue;
}
var text = token.text;
if (handleSpecialToken(text)) {
continue;
}
// Default: append literal text to current segment
appendLiteralToCurrentSegment(text);
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("StringSegmentParser.parse: Finished parsing, segments count: " + segments.size());
return buildResult();
}
/**
* Handles special tokens that require custom processing.
*
* <p>This method identifies and processes tokens that have special meaning
* in string contexts:
* <ul>
* <li>Backslash (\): Introduces escape sequences</li>
* <li>Dollar sign ($): Introduces scalar variable interpolation</li>
* <li>At sign (@): Introduces array variable interpolation</li>
* <li>Array length ($#): Introduces array length interpolation</li>
* </ul></p>
*
* @param text the token text to process
* @return true if the token was handled specially, false if it should be treated as literal text
*/
protected boolean handleSpecialToken(String text) {
return switch (text) {
case "\\" -> {
parseEscapeSequence();
yield true;
}
case "$", "@", "$#" -> {
if (shouldInterpolateVariable(text)) {
parseVariableInterpolation(text);
yield true;
}
yield false;
}
case "(" -> {
// Check for (?{...}) and (??{...}) regex code blocks - only in regex context
if (isRegex && regexCodeBlocksAreActive() && isRegexCallbackCondition()) {
parseRegexCallbackCondition();
yield true;
} else if (isRegex && regexCodeBlocksAreActive() && isRegexCodeBlock()) {
parseRegexCodeBlock(false); // (?{...}) - code execution
yield true;
} else if (isRegex && regexCodeBlocksAreActive() && isRegexRecursiveBlock()) {
parseRegexCodeBlock(true); // (??{...}) - recursive pattern
yield true;
} else if (isRegex && regexCodeBlocksAreActive() && isRegexOptimisticBlock()) {
parseRegexOptimisticBlock(); // (*{...}) - optimization-preserving callback
yield true;
}
yield false;
}
default -> false;
};
}
/**
* Checks if the current position is at the start of a (?{...}) regex code block.
* This method looks ahead to see if we have the pattern (?{
* Only called when isRegex=true to avoid false matches in regular strings.
*
* @return true if this is a regex code block, false otherwise
*/
private boolean isRegexCodeBlock() {
// Current token is "(", check if next tokens are "?" and "{"
int currentPos = parser.tokenIndex;
if (currentPos + 1 < parser.tokens.size() && currentPos + 2 < parser.tokens.size()) {
LexerToken nextToken = parser.tokens.get(currentPos);
LexerToken afterNextToken = parser.tokens.get(currentPos + 1);
return "?".equals(nextToken.text) && "{".equals(afterNextToken.text);
}
return false;
}
private boolean isRegexCallbackCondition() {
int currentPos = parser.tokenIndex;
return currentPos + 3 < parser.tokens.size()
&& "?".equals(parser.tokens.get(currentPos).text)
&& "(".equals(parser.tokens.get(currentPos + 1).text)
&& ("?".equals(parser.tokens.get(currentPos + 2).text)
|| "*".equals(parser.tokens.get(currentPos + 2).text))
&& "{".equals(parser.tokens.get(currentPos + 3).text);
}
private void parseRegexCallbackCondition() {
flushCurrentSegment();
int start = tokenIndex;
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "?");
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
LexerToken callbackType = TokenUtils.consume(parser);
if (!"?".equals(callbackType.text) && !"*".equals(callbackType.text)) {
throw new IllegalStateException("invalid regex callback condition marker");
}
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
Node block = parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
segments.add(new StringNode("(?(", start));
segments.add(regexCallback(block, "CONDITION", start));
}
private boolean isRegexOptimisticBlock() {
int currentPos = parser.tokenIndex;
return currentPos + 1 < parser.tokens.size()
&& "*".equals(parser.tokens.get(currentPos).text)
&& "{".equals(parser.tokens.get(currentPos + 1).text);
}
private void parseRegexOptimisticBlock() {
flushCurrentSegment();
int start = tokenIndex;
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "*");
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
Node block = parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
segments.add(regexCallback(block, "BLOCK", start));
}
/**
* Checks if the current tokens form a (??{...}) recursive regex pattern.
* This is similar to (?{...}) but uses the result as a regex pattern.
*
* @return true if this is a recursive regex pattern, false otherwise
*/
private boolean isRegexRecursiveBlock() {
// Current token is "(", check if next tokens are "?", "?" and "{"
int currentPos = parser.tokenIndex;
if (currentPos + 2 < parser.tokens.size() && currentPos + 3 < parser.tokens.size()) {
LexerToken token1 = parser.tokens.get(currentPos);
LexerToken token2 = parser.tokens.get(currentPos + 1);
LexerToken token3 = parser.tokens.get(currentPos + 2);
return "?".equals(token1.text) && "?".equals(token2.text) && "{".equals(token3.text);
}
return false;
}
/**
* Parses a (?{...}) regex code block by calling the Block parser and applying constant folding.
*
* <p>This method implements compile-time constant folding for regex code blocks to support
* the special variable $^R (last regex code block result). When a code block contains a
* simple constant expression, it is evaluated at compile time and the constant value is
* encoded in a named capture group for retrieval at runtime.</p>
*
* <p><strong>IMPORTANT LIMITATION:</strong> This approach only works for literal regex patterns
* in the source code (e.g., {@code /(?{ 42 })/}). It does NOT work for runtime-interpolated
* patterns (e.g., {@code $var = '(?{ 42 })'; /$var/}) because those patterns are constructed
* at runtime and never pass through the parser. This limitation affects approximately 1% of
* real-world use cases, with pack.t and most Perl code using literal patterns.</p>
*
* <p>Future enhancement: To support interpolated patterns, this processing would need to be
* moved to RegexPreprocessor.preProcessRegex() which sees the final pattern string regardless
* of how it was constructed.</p>
*
* <p>Only called when isRegex=true.</p>
*/
private void parseRegexCodeBlock(boolean isRecursive) {
// Flush any accumulated text before adding the code block capture group
// This ensures segments are added in the correct order (critical fix!)
flushCurrentSegment();
int savedTokenIndex = tokenIndex;
// Consume the "?" token(s)
TokenUtils.consume(parser); // consume first "?"
if (isRecursive) {
TokenUtils.consume(parser); // consume second "?" for (??{...})
}
// Consume the "{" token
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
// Parse the block content using the Block parser - this handles heredocs properly
Node block = parseBlock(parser);
// Consume the closing "}"
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// Consume the closing ")" that completes the (?{...}) construct
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
if (isRecursive) {
// Keep constant folding as the zero-overhead path, but preserve a
// runtime-dependent expression as a lexical dynamic-program closure.
Node folded = ConstantFoldingVisitor.foldConstants(block);
if (folded instanceof BlockNode blockNode && blockNode.elements.size() == 1) {
folded = blockNode.elements.getFirst();
}
RuntimeScalar constant = ConstantFoldingVisitor.getConstantValue(folded);
if (constant == null || !isSafeDynamicConstantFold(constant.toString())) {
segments.add(regexCallback(block, "DYNAMIC", savedTokenIndex));
} else {
segments.add(new StringNode(constant.toString(), savedTokenIndex));
}
} else {
segments.add(regexCallback(block, "BLOCK", savedTokenIndex));
}
}
private Node regexCallback(Node block, String kind, int index) {
SubroutineNode closure = new SubroutineNode(null, null, null, block, false, index);
closure.setAnnotation("inheritsSelfReference", true);
closure.setAnnotation("regexCallbackPseudoBlock", true);
if (block instanceof AbstractNode abstractBlock) {
// (?{ ... }) is a regex pseudo-block, not an ordinary anonymous-sub
// scope. Its top-level local() frames belong to the matcher path and
// must survive the Java callback return until Joni commits/unwinds it.
abstractBlock.setAnnotation("regexCallbackBody", true);
}
OperatorNode callback = new OperatorNode("regexCallback", closure, index);
callback.setAnnotation("regexCallbackKind", kind);
hasExecutableRegexCallbacks = true;
return callback;
}
/**
* Folding is safe only when textual insertion preserves the nested program's
* grouping and capture isolation. A top-level alternative could absorb the
* outer suffix, and a capturing group could consume an outer capture number.
*/
private static boolean isSafeDynamicConstantFold(String pattern) {
boolean escaped = false;
boolean inClass = false;
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
if (escaped) {
escaped = false;
} else if (ch == '\\') {
escaped = true;
} else if (ch == '[') {
inClass = true;
} else if (ch == ']' && inClass) {
inClass = false;
} else if (ch == '(' && !inClass) {
return false;
} else if (ch == '|' && !inClass) {
return false;