-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStringSegmentParser.java
More file actions
1319 lines (1179 loc) · 57.2 KB
/
StringSegmentParser.java
File metadata and controls
1319 lines (1179 loc) · 57.2 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.regex.CaptureNameEncoder;
import org.perlonjava.runtime.regex.RegexMarkers;
import org.perlonjava.runtime.regex.UnicodeResolver;
import org.perlonjava.runtime.runtimetypes.PerlCompilerException;
import org.perlonjava.runtime.runtimetypes.RuntimeScalar;
import org.perlonjava.runtime.runtimetypes.RuntimeScalarCache;
import org.perlonjava.runtime.runtimetypes.ScalarUtils;
import java.util.ArrayList;
import java.util.List;
import static org.perlonjava.frontend.parser.ParseBlock.parseBlock;
import static org.perlonjava.frontend.parser.Variable.parseArrayHashAccess;
/**
* 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
*/
private static int codeBlockCaptureCounter = 0;
/**
* 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;
/**
* Buffer for accumulating literal text segments
*/
protected final StringBuilder currentSegment;
/**
* List of AST nodes representing string segments (literals and interpolated expressions)
*/
protected final List<Node> segments;
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 = 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;
}
/**
* 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);
}
/**
* 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()) {
addStringSegment(new StringNode(currentSegment.toString(), tokenIndex));
currentSegment.setLength(0);
}
}
/**
* 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();
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("str sigil");
Node operand;
var isArray = "@".equals(sigil);
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);
// 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 {
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) {
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);
}
}
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();
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);
};
}
/**
* 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
appendToCurrentSegment(token.text);
}
continue;
}
var text = token.text;
if (handleSpecialToken(text)) {
continue;
}
// Default: append literal text to current segment
appendToCurrentSegment(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 && isRegexCodeBlock()) {
parseRegexCodeBlock(false); // (?{...}) - code execution
yield true;
} else if (isRegex && isRegexRecursiveBlock()) {
parseRegexCodeBlock(true); // (??{...}) - recursive pattern
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;
}
/**
* 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, ")");
// Try to apply constant folding to the block
Node folded = ConstantFoldingVisitor.foldConstants(block);
// If it's a BlockNode with a single element, extract it
// This handles both empty blocks (BlockNode with empty ListNode) and single-expression blocks
if (folded instanceof BlockNode blockNode) {
if (blockNode.elements.size() == 1) {
folded = blockNode.elements.get(0);
}
}
// Check if the result is a simple constant using the visitor pattern
RuntimeScalar constantValue =
ConstantFoldingVisitor.getConstantValue(folded);
if (constantValue != null) {
if (isRecursive) {
// For (??{...}), the constant becomes a pattern to match
// Extract the string value and insert it directly as a pattern
String patternString = constantValue.toString();
// Insert the pattern string directly - it will be compiled as a regex
segments.add(new StringNode(patternString, savedTokenIndex));
} else {
// For (?{...}), encode the value in a capture group for $^R
String captureName;
// Check if it's undef (needs special encoding)
if (constantValue == RuntimeScalarCache.scalarUndef) {
captureName = String.format("cb%03du", codeBlockCaptureCounter++);
} else {
// Use CaptureNameEncoder to encode the value in the capture name
captureName = CaptureNameEncoder.encodeCodeBlockValue(
codeBlockCaptureCounter++, constantValue
);
}
if (captureName == null) {
// Encoding failed (e.g., name too long) - use fallback
segments.add(new StringNode(RegexMarkers.CODE_BLOCK, savedTokenIndex));
} else {
// Encoding succeeded - create capture group
StringNode captureNode = new StringNode("(?<" + captureName + ">)", savedTokenIndex);
segments.add(captureNode);
}
}
} else {
// Not a constant - use unimplemented marker
if (isRecursive) {
segments.add(new StringNode(RegexMarkers.RECURSIVE_PATTERN, savedTokenIndex));
} else {
segments.add(new StringNode(RegexMarkers.CODE_BLOCK, savedTokenIndex));
}
}
}
/**
* Gets a string context around the specified position for error reporting.
* This shows the actual string content around where the error occurred.
*/
private String getStringContextAt(int position) {
try {
// Build context from the string tokens around the specified position
StringBuilder context = new StringBuilder();
int start = Math.max(0, position - 2);
int end = Math.min(tokens.size(), position + 3);
for (int i = start; i < end; i++) {
if (i < tokens.size()) {
context.append(tokens.get(i).text);
}
}
// Quote and escape the context for error message display
String contextStr = context.toString();
if (contextStr.length() > 50) {
contextStr = contextStr.substring(0, 47) + "...";
}
return "\"" + contextStr.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"";
} catch (Exception e) {
// Fallback to a generic message if context extraction fails
return "\"string interpolation\"";
}
}
/**
* Sets the original token offset and string content for mapping string positions back to source.
* This enables proper error reporting that shows the actual string content.
*/
public void setOriginalTokenOffset(int offset) {
this.originalTokenOffset = offset;
}
/**
* Gets the original string content.
*/
protected String getOriginalStringContent() {
return originalStringContent;
}
/**
* Sets the original string content for better error context.
*/
public void setOriginalStringContent(String content) {
this.originalStringContent = content;
}
/**
* Creates and throws an offset-aware error with correct context.
* Matches Perl's actual error format for string interpolation errors.
* Based on Test::More analysis: string errors are single line, no stack traces, no "near" context.
*/
private void createOffsetAwareError(int stringTokenIndex, String message) {
// Extract core message without "Syntax error in braced variable:" prefix
String coreMessage = message;
if (coreMessage.startsWith("Syntax error in braced variable: ")) {
coreMessage = coreMessage.substring("Syntax error in braced variable: ".length());
}
// Create error message matching Perl's exact format: "[ERROR] at [FILE] line [N]."
String fileName = ctx.errorUtil.getFileName();
int lineNumber = ctx.errorUtil.getLineNumber(originalTokenOffset);
String perlStyleMessage = coreMessage + " at " + fileName + " line " + lineNumber + ".";
// Create a custom exception that produces clean output like Perl
RuntimeException cleanError = new RuntimeException(perlStyleMessage) {
@Override
public void printStackTrace() {
// Print only the clean message, no stack trace
System.err.println(getMessage());
}
@Override
public void printStackTrace(java.io.PrintStream s) {
// Print only the clean message, no stack trace
s.println(getMessage());
}
@Override
public void printStackTrace(java.io.PrintWriter s) {
// Print only the clean message, no stack trace
s.println(getMessage());
}
};
throw cleanError;
}
/**
* Gets error context from the original string content around the specified position.
*/
private String getStringErrorContext(int stringTokenIndex) {
try {
if (originalStringContent.isEmpty()) {
return "\"string interpolation\"";
}
// Try to estimate character position from token index
// Look for variable interpolation patterns like ${...} to get better positioning
int estimatedCharPos = findBestErrorPosition(stringTokenIndex);
// Show a larger context window around the estimated position
int contextWindow = 25; // Increased from 10 to show more context
int start = Math.max(0, estimatedCharPos - contextWindow);
int end = Math.min(originalStringContent.length(), estimatedCharPos + contextWindow);
String context = originalStringContent.substring(start, end);
// Escape special characters for display
context = context.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\t", "\\t");
return "\"" + context + "\"";
} catch (Exception e) {
return "\"string interpolation\"";
}
}
/**
* Finds the best error position by looking for variable interpolation patterns.
*/
private int findBestErrorPosition(int stringTokenIndex) {
// Simple heuristic: look for ${...} patterns in the string
int dollarIndex = originalStringContent.indexOf("${");
if (dollarIndex >= 0) {
// If we found a ${...} pattern, position the error around it
return Math.max(0, dollarIndex - 5);
}
// Fallback to simple token-based estimation
return Math.min(stringTokenIndex * 4, originalStringContent.length() - 1);
}
/**
* Determines whether a variable sigil should trigger interpolation.
*
* <p>Variable interpolation is suppressed in certain contexts:
* <ul>
* <li>When followed by whitespace or newlines</li>
* <li>When followed by certain punctuation that doesn't start valid variable names</li>
* <li>At the end of the string (EOF)</li>
* </ul></p>
*
* <p>This prevents false interpolation of literal $ and @ characters that
* aren't intended as variable references.</p>
*
* @param sigil the variable sigil ("$", "@", or "$#")
* @return true if the sigil should trigger variable interpolation
*/
private boolean shouldInterpolateVariable(String sigil) {
if (!interpolateVariable) {
return false;
}
var nextToken = tokens.get(parser.tokenIndex);
if (nextToken.type == LexerTokenType.EOF) {
// Special case: $ at EOF in double-quoted string should generate error
// But only for StringDoubleQuoted, not for other contexts like regex
return "$".equals(sigil) && interpolateVariable && !isRegex && !isRegexReplacement;
}
// Regex: don't interpolate "$" if followed by whitespace or newlines
// "@" sigil: never interpolate if immediately followed by whitespace or newlines
// "$#" sigil: don't interpolate if followed by whitespace or newlines
if ((isRegex || "@".equals(sigil) || "$#".equals(sigil)) && (nextToken.type == LexerTokenType.WHITESPACE || nextToken.type == LexerTokenType.NEWLINE)) {
return false;
}
// In regex patterns, $ followed by certain regex metacharacters should NOT be
// interpolated as special variables. Instead, $ is the end-of-string anchor:
// $) = anchor + closing group (not $EGID)
// $( = anchor + opening group (not $GID)
// $| = anchor + alternation (not $OUTPUT_AUTOFLUSH)
// In double-quoted strings, these SHOULD interpolate to their variable values.
if (isRegex && "$".equals(sigil)
&& (")".equals(nextToken.text) || "(".equals(nextToken.text) || "|".equals(nextToken.text))) {
return false;
}