-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRegexPreprocessor.java
More file actions
2366 lines (2097 loc) · 95.2 KB
/
RegexPreprocessor.java
File metadata and controls
2366 lines (2097 loc) · 95.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.runtime.regex;
import com.ibm.icu.lang.UCharacter;
import org.perlonjava.runtime.operators.WarnDie;
import org.perlonjava.runtime.runtimetypes.GlobalVariable;
import org.perlonjava.runtime.runtimetypes.PerlCompilerException;
import org.perlonjava.runtime.runtimetypes.PerlJavaUnimplementedException;
import org.perlonjava.runtime.runtimetypes.RuntimeScalar;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Character.isAlphabetic;
/**
* The RegexPreprocessor class provides functionality to preprocess regular expressions
* to make them compatible with Java's regex engine. It handles various regex constructs
* and modifies them as necessary to adhere to Java's regex syntax requirements.
*/
public class RegexPreprocessor {
// Regex escape rules:
//
// \[ as-is
// \120 becomes: \0120 - Java requires octal sequences to start with zero
// \0 becomes: \00 - Java requires the extra zero
// (?#...) inline comment is removed
// \N{name} named Unicode character or character sequence
// \N{U+263D} Unicode character
// \G \G is removed, it is handled separately
//
// inside [ ... ]
// space becomes: "\ " unless the /xx flag is used (flag_xx)
// \120 becomes: \0120 - Java requires octal sequences to start with zero
// \0 becomes: \00 - Java requires the extra zero
// \N{name} named Unicode character or character sequence
// \N{U+263D} Unicode character
// [:ascii:] becomes: \p{ASCII}
// [:^ascii:] becomes: \P{ASCII}
// \b is moved, Java doesn't support \b inside [...]
// [xx \b xx] becomes: (?:[xx xx]|\b) - Java doesn't support \b as a character
//
// WIP:
// named capture (?<one> ... ) replace underscore in name
private static final Map<Integer, Integer> SPECIAL_SINGLE_CHAR_FOLDS = Map.of(
0x00B5, 0x03BC,
0x212A, 0x006B,
0x212B, 0x00E5
);
private static final Map<Integer, Integer> SPECIAL_SINGLE_CHAR_REVERSE_FOLDS = Map.of(
0x03BC, 0x00B5,
0x006B, 0x212A,
0x00E5, 0x212B
);
static int captureGroupCount;
static boolean deferredUnicodePropertyEncountered;
static boolean inlinePFlagEncountered;
static boolean branchResetEncountered;
static boolean backslashKEncountered;
static void markDeferredUnicodePropertyEncountered() {
deferredUnicodePropertyEncountered = true;
}
static boolean hadDeferredUnicodePropertyEncountered() {
return deferredUnicodePropertyEncountered;
}
static boolean hadInlinePFlag() {
return inlinePFlagEncountered;
}
static boolean hadBranchReset() {
return branchResetEncountered;
}
static void markBackslashK() {
backslashKEncountered = true;
}
static boolean hadBackslashK() {
return backslashKEncountered;
}
/**
* Preprocesses a given regex string to make it compatible with Java's regex engine.
* This involves handling various constructs and escape sequences that Java does not
* natively support or requires in a different format.
*
* @param s The regex string to preprocess.
* @param regexFlags The regex flags to use.
* @return A preprocessed regex string compatible with Java's regex engine.
* @throws PerlCompilerException If there are unmatched parentheses in the regex.
*/
static String preProcessRegex(String s, RegexFlags regexFlags) {
if (s == null) {
s = "";
}
captureGroupCount = 0;
deferredUnicodePropertyEncountered = false;
inlinePFlagEncountered = false;
branchResetEncountered = false;
backslashKEncountered = false;
// First, escape invalid quantifier braces (Perl compatibility)
// DISABLED: Causes test regressions - needs more work
// s = escapeInvalidQuantifierBraces(s);
s = convertPythonStyleGroups(s);
s = transformSimpleConditionals(s);
s = removeUnderscoresFromEscapes(s);
s = normalizeQuantifiers(s);
// Expand multi-character case folds when case-insensitive flag is set
if (regexFlags.isCaseInsensitive()) {
s = expandMultiCharFolds(s);
}
StringBuilder sb = new StringBuilder();
handleRegex(s, 0, sb, regexFlags, false);
String result = sb.toString();
return result;
}
/**
* Escape unescaped braces that don't form valid quantifiers.
* Perl allows invalid quantifier braces and treats them as literals.
* Java Pattern.compile() rejects them, so we must escape them.
* <p>
* Valid quantifiers: {n}, {n,}, {n,m} where n and m are non-negative integers
* Invalid quantifiers: {(.*?)}, {abc}, {}, {,5}, etc.
* <p>
* IMPORTANT: This is a high-risk preprocessing step that modifies brace characters.
* Known edge cases that must be handled correctly:
* <p>
* 1. ESCAPE SEQUENCES WITH BRACES (must NOT be escaped):
* - \N{name} - Named Unicode character (e.g., \N{LATIN SMALL LETTER A})
* - \x{...} - Hexadecimal character code (e.g., \x{1F600})
* - \o{...} - Octal character code (e.g., \o{777})
* - \p{...} - Unicode property (e.g., \p{Letter})
* - \P{...} - Negated Unicode property (e.g., \P{Number})
* - \g{...} - Named or relative backreference (e.g., \g{name}, \g{-1})
* Currently handled: N, x, o, p, P, g
* <p>
* 2. CHARACTER CLASSES (braces inside [...] are always literal):
* - [a{3}] means "match 'a', '{', '3', or '}'" not "match 'aaa'"
* - Nested classes like [a-z[0-9]{3}] must track nesting depth
* <p>
* 3. VALID QUANTIFIERS (must NOT be escaped):
* - {n} - exactly n times (e.g., a{3})
* - {n,} - n or more times (e.g., a{2,})
* - {n,m} - between n and m times (e.g., a{2,5})
* <p>
* 4. ALREADY ESCAPED BRACES (must NOT be double-escaped):
* - \{ and \} should remain as-is
* - Track backslash escaping carefully to avoid double-escaping
* <p>
* 5. POSSESSIVE AND LAZY QUANTIFIERS:
* - {n}+ (possessive) and {n}? (lazy) should work with valid quantifiers
* <p>
* POTENTIAL ISSUES NOT YET HANDLED:
* - Extended bracketed character classes: (?[...]) may contain braces
* - Conditional patterns: (?(condition){yes}{no}) uses braces for branches
* - Subroutine definitions: (?(DEFINE)(?<name>...)) may have complex nesting
* - Code blocks: (?{...}) and (??{...}) use braces but are handled elsewhere
* - Named capture definitions: (?<name{suffix}>...) - are braces allowed in names?
* - Unicode named sequences: \N{...} may contain nested braces in some contexts
* <p>
* If new regex features are added that use braces, this function MUST be updated.
* Test changes thoroughly with unit/regex/unescaped_braces.t and regex test suite.
*/
private static String escapeInvalidQuantifierBraces(String pattern) {
StringBuilder result = new StringBuilder();
boolean inCharClass = false;
boolean escaped = false;
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
// Handle escape sequences
if (escaped) {
result.append(c);
// Check if this is an escape sequence that uses braces: \N{...}, \x{...}, \o{...}, \p{...}, \P{...}, \g{...}
if ((c == 'N' || c == 'x' || c == 'o' || c == 'p' || c == 'P' || c == 'g') &&
i + 1 < pattern.length() && pattern.charAt(i + 1) == '{') {
// Skip the entire escape sequence with braces
result.append('{');
i++; // Move past '{'
int braceDepth = 1;
i++; // Move to first character inside braces
while (i < pattern.length() && braceDepth > 0) {
char ch = pattern.charAt(i);
result.append(ch);
if (ch == '\\' && i + 1 < pattern.length()) {
// Skip escaped character inside the escape sequence
i++;
if (i < pattern.length()) {
result.append(pattern.charAt(i));
}
} else if (ch == '{') {
braceDepth++;
} else if (ch == '}') {
braceDepth--;
}
i++;
}
i--; // Back up one since the loop will increment
}
escaped = false;
continue;
}
if (c == '\\') {
result.append(c);
escaped = true;
continue;
}
// Track character class boundaries (braces inside [...] are always literal)
if (c == '[') {
inCharClass = true;
result.append(c);
continue;
}
if (c == ']') {
inCharClass = false;
result.append(c);
continue;
}
// Only process braces outside character classes
if (!inCharClass && c == '{') {
// Look ahead to check if this is a valid quantifier
int closePos = findMatchingCloseBraceForEscape(pattern, i);
if (closePos > 0 && isValidQuantifierContent(pattern, i + 1, closePos)) {
result.append(c); // Keep valid quantifier as-is
} else {
result.append("\\{"); // Escape invalid quantifier
}
} else if (!inCharClass && c == '}') {
// Check if this closes a quantifier that we kept unescaped
if (!closesValidQuantifier(result, pattern, i)) {
result.append("\\}"); // Escape unmatched closing brace
} else {
result.append(c);
}
} else {
result.append(c);
}
}
return result.toString();
}
/**
* Find the position of closing brace that matches opening brace at pos.
* Returns -1 if no matching brace found.
*/
private static int findMatchingCloseBraceForEscape(String pattern, int openPos) {
for (int i = openPos + 1; i < pattern.length(); i++) {
char c = pattern.charAt(i);
if (c == '\\') {
i++; // Skip escaped character
continue;
}
if (c == '}') {
return i;
}
}
return -1; // No closing brace found
}
/**
* Check if content between braces forms a valid quantifier.
* Valid: {n}, {n,}, {n,m} where n and m are non-negative integers
* Invalid: {(.*?)}, {abc}, {}, {,5}, etc.
*/
private static boolean isValidQuantifierContent(String pattern, int start, int end) {
if (start >= end) {
return false; // Empty braces {}
}
String content = pattern.substring(start, end);
// Check for {n}, {n,}, or {n,m} pattern
if (content.matches("\\d+")) {
return true; // {n}
}
if (content.matches("\\d+,")) {
return true; // {n,}
}
return content.matches("\\d+,\\d+"); // {n,m}
}
/**
* Check if closing brace at position closePos closes a valid quantifier
* that we kept unescaped in the result buffer.
*/
private static boolean closesValidQuantifier(StringBuilder result, String pattern, int closePos) {
// Find the most recent unescaped opening brace in result
int openPos = -1;
for (int i = result.length() - 1; i >= 0; i--) {
if (result.charAt(i) == '{') {
// Check if it's escaped
int backslashCount = 0;
for (int j = i - 1; j >= 0 && result.charAt(j) == '\\'; j--) {
backslashCount++;
}
if (backslashCount % 2 == 0) {
// Even number of backslashes (or zero) means { is not escaped
openPos = i;
break;
}
}
}
if (openPos < 0) {
return false; // No unescaped opening brace found
}
// Extract content and validate
String content = result.substring(openPos + 1);
return content.matches("\\d+") || content.matches("\\d+,") || content.matches("\\d+,\\d+");
}
/**
* Expand characters with multi-character case folds into alternations.
* For example: ß → (?:ß|ss|SS|Ss|sS)
* This is needed because Java's UNICODE_CASE flag doesn't handle multi-char folds.
*/
private static String expandMultiCharFolds(String pattern) {
StringBuilder result = new StringBuilder();
int i = 0;
int len = pattern.length();
boolean inCharClass = false;
boolean escaped = false;
while (i < len) {
char ch = pattern.charAt(i);
// Skip extended character classes (?[...]]) entirely - they handle their own case folding
if (!escaped && ch == '(' && i + 2 < len && pattern.charAt(i + 1) == '?' && pattern.charAt(i + 2) == '[') {
// Find the end of the extended char class
int depth = 1;
int j = i + 3; // Start after (?[
while (j < len && depth > 0) {
char c = pattern.charAt(j);
if (c == '\\' && j + 1 < len) {
// Skip escaped character
j += 2;
continue;
}
if (c == ']' && j + 1 < len && pattern.charAt(j + 1) == ')') {
depth--;
if (depth == 0) {
break;
}
}
if (c == '(' && j + 2 < len && pattern.charAt(j + 1) == '?' && pattern.charAt(j + 2) == '[') {
depth++;
}
j++;
}
// Append (?[ ... ]) - the whole extended char class unchanged
result.append(pattern, i, j + 2);
i = j + 2;
continue;
}
// Track if we're inside a character class [...]
if (!escaped) {
if (ch == '[') {
inCharClass = true;
} else if (ch == ']') {
inCharClass = false;
}
}
// Handle escape sequences
if (ch == '\\' && !escaped) {
escaped = true;
result.append(ch);
i++;
continue;
}
// If this is an escaped character or we're in a char class, don't expand
if (escaped || inCharClass) {
if (!escaped && inCharClass) {
int codePoint = pattern.codePointAt(i);
String specialClassExpansion = expandSpecialSingleCharFoldInCharClass(codePoint);
if (specialClassExpansion != null) {
result.append(specialClassExpansion);
i += Character.charCount(codePoint);
continue;
}
}
// Skip over \p{...}, \P{...}, \x{...}, \o{...} constructs without case folding
// Note: \N{...} is handled separately below - it needs case-folding for special chars
if (escaped && (ch == 'p' || ch == 'P' || ch == 'x' || ch == 'o')
&& i + 1 < len && pattern.charAt(i + 1) == '{') {
result.append(ch);
i++;
// Now append everything up to and including the closing '}'
while (i < len && pattern.charAt(i) != '}') {
result.append(pattern.charAt(i));
i++;
}
if (i < len) {
result.append(pattern.charAt(i)); // append '}'
i++;
}
escaped = false;
continue;
}
// Handle \N{...} specially - resolve and apply case-folding if needed
if (escaped && ch == 'N' && i + 1 < len && pattern.charAt(i + 1) == '{') {
int endBrace = pattern.indexOf('}', i + 2);
if (endBrace != -1) {
String charName = pattern.substring(i + 2, endBrace).trim();
try {
int codePoint = UnicodeResolver.getCodePointFromName(charName);
// Check if this character needs special case-fold expansion
String charClassExpansion = expandSpecialSingleCharFoldInCharClass(codePoint);
if (charClassExpansion != null) {
// Remove the backslash that was already appended
result.setLength(result.length() - 1);
if (inCharClass) {
// Inside regular [...], append chars directly
result.append(charClassExpansion);
} else {
// Not inside [...], wrap in character class
// This handles extended char class context like (?[ \N{KELVIN SIGN} ])
result.append('[').append(charClassExpansion).append(']');
}
} else {
// No special expansion needed, keep the original \N{...}
result.append(ch);
for (int j = i + 1; j <= endBrace; j++) {
result.append(pattern.charAt(j));
}
}
i = endBrace + 1;
escaped = false;
continue;
} catch (IllegalArgumentException e) {
// Unknown character name, pass through as-is
result.append(ch);
i++;
escaped = false;
continue;
}
}
}
result.append(ch);
escaped = false;
i++;
continue;
}
// Check if this character has a multi-char fold
int codePoint = pattern.codePointAt(i);
if (MultiCharFoldMapper.hasMultiCharFold(codePoint)) {
// Expand it (e.g., ß → (?:ß|ss|SS|Ss|sS))
String expansion = MultiCharFoldMapper.expandToAlternation(codePoint);
result.append(expansion);
i += Character.charCount(codePoint);
} else {
// Check if we're at the start of a reverse fold sequence (e.g., ss → ß)
boolean foundReverseFold = false;
// Try longest sequences first (3, then 2 characters)
for (int seqLen = 3; seqLen >= 2 && !foundReverseFold; seqLen--) {
if (i + seqLen <= len) {
String sequence = pattern.substring(i, i + seqLen);
if (MultiCharFoldMapper.hasReverseFold(sequence)) {
Integer reverseFoldChar = MultiCharFoldMapper.getReverseFold(sequence);
// Expand to include both the sequence and its reverse fold
result.append("(?:");
result.append(sequence);
result.append("|");
result.appendCodePoint(reverseFoldChar);
result.append(")");
i += seqLen;
foundReverseFold = true;
}
}
}
if (!foundReverseFold) {
String specialExpansion = expandSpecialSingleCharFold(codePoint);
if (specialExpansion != null) {
result.append(specialExpansion);
} else {
result.appendCodePoint(codePoint);
}
i += Character.charCount(codePoint);
}
}
escaped = false;
}
return result.toString();
}
private static String expandSpecialSingleCharFold(int codePoint) {
// Compute full case fold for this code point.
int folded = UCharacter.foldCase(codePoint, true);
// Trigger expansion only if this code point participates in one of the known problematic folds.
// We key off the folded form so that e.g. 'k' and 'K' will match Kelvin sign under /i.
if (!SPECIAL_SINGLE_CHAR_FOLDS.containsKey(codePoint)
&& !SPECIAL_SINGLE_CHAR_REVERSE_FOLDS.containsKey(folded)
&& !SPECIAL_SINGLE_CHAR_REVERSE_FOLDS.containsKey(codePoint)) {
return null;
}
LinkedHashSet<Integer> variants = new LinkedHashSet<>();
variants.add(codePoint);
variants.add(folded);
Integer reverse = SPECIAL_SINGLE_CHAR_REVERSE_FOLDS.get(folded);
if (reverse != null) {
variants.add(reverse);
}
Integer reverse2 = SPECIAL_SINGLE_CHAR_REVERSE_FOLDS.get(codePoint);
if (reverse2 != null) {
variants.add(reverse2);
}
// Include upper/lower variants of all participating code points.
// This keeps behavior stable even if the Java regex engine doesn't map the special ones.
LinkedHashSet<Integer> expanded = new LinkedHashSet<>();
for (Integer cp : variants) {
expanded.add(cp);
expanded.add(UCharacter.toLowerCase(cp));
expanded.add(UCharacter.toUpperCase(cp));
expanded.add(UCharacter.foldCase(cp, true));
}
StringBuilder sb = new StringBuilder("(?:");
boolean first = true;
for (Integer cp : expanded) {
if (!first) {
sb.append("|");
}
first = false;
sb.append(Pattern.quote(new String(Character.toChars(cp))));
}
sb.append(")");
return sb.toString();
}
private static String expandSpecialSingleCharFoldInCharClass(int codePoint) {
int folded = UCharacter.foldCase(codePoint, true);
if (!SPECIAL_SINGLE_CHAR_FOLDS.containsKey(codePoint)
&& !SPECIAL_SINGLE_CHAR_REVERSE_FOLDS.containsKey(folded)
&& !SPECIAL_SINGLE_CHAR_REVERSE_FOLDS.containsKey(codePoint)) {
return null;
}
LinkedHashSet<Integer> variants = new LinkedHashSet<>();
variants.add(codePoint);
variants.add(folded);
Integer reverse = SPECIAL_SINGLE_CHAR_REVERSE_FOLDS.get(folded);
if (reverse != null) {
variants.add(reverse);
}
Integer reverse2 = SPECIAL_SINGLE_CHAR_REVERSE_FOLDS.get(codePoint);
if (reverse2 != null) {
variants.add(reverse2);
}
LinkedHashSet<Integer> expanded = new LinkedHashSet<>();
for (Integer cp : variants) {
expanded.add(cp);
expanded.add(UCharacter.toLowerCase(cp));
expanded.add(UCharacter.toUpperCase(cp));
expanded.add(UCharacter.foldCase(cp, true));
}
StringBuilder sb = new StringBuilder();
for (Integer cp : expanded) {
appendCharClassLiteral(sb, cp);
}
return sb.toString();
}
private static void appendCharClassLiteral(StringBuilder sb, int codePoint) {
// Escape only the few metacharacters with special meaning inside [...].
if (codePoint == '\\' || codePoint == ']' || codePoint == '-') {
sb.append('\\');
}
sb.appendCodePoint(codePoint);
}
/**
* Remove underscores from \x{...} and \o{...} escape sequences.
* Perl allows underscores in numeric literals for readability, but Java doesn't.
* Example: \x{_1_0000} becomes \x{10000}
*/
private static String removeUnderscoresFromEscapes(String pattern) {
StringBuilder result = new StringBuilder();
int i = 0;
int len = pattern.length();
while (i < len) {
if (i + 2 < len && pattern.charAt(i) == '\\' &&
(pattern.charAt(i + 1) == 'x' || pattern.charAt(i + 1) == 'o') &&
pattern.charAt(i + 2) == '{') {
// Found \x{ or \o{
result.append(pattern.charAt(i)); // \
result.append(pattern.charAt(i + 1)); // x or o
result.append('{');
i += 3;
// Copy content until }, removing underscores
while (i < len && pattern.charAt(i) != '}') {
char ch = pattern.charAt(i);
if (ch != '_') {
result.append(ch);
}
i++;
}
if (i < len) {
result.append('}'); // Closing brace
i++;
}
} else {
result.append(pattern.charAt(i));
i++;
}
}
return result.toString();
}
/**
* Normalize quantifiers to Java regex format.
* Perl allows {,n} to mean {0,n} (omitting minimum).
* Perl allows spaces inside quantifiers like {2, 5} or { , 2 }.
* Java requires explicit {0,n} and no spaces (unless in /x mode).
* Example: {,2} becomes {0,2}, { , 2 } becomes {0,2}
*/
private static String normalizeQuantifiers(String pattern) {
StringBuilder result = new StringBuilder();
int i = 0;
int len = pattern.length();
boolean inCharClass = false;
boolean escaped = false;
while (i < len) {
char ch = pattern.charAt(i);
if (escaped) {
result.append(ch);
escaped = false;
i++;
continue;
}
if (ch == '\\') {
result.append(ch);
escaped = true;
i++;
continue;
}
if (ch == '[') {
inCharClass = true;
result.append(ch);
i++;
continue;
}
if (ch == ']' && inCharClass) {
inCharClass = false;
result.append(ch);
i++;
continue;
}
if (ch == '{' && !inCharClass) {
// Potential quantifier
int start = i;
i++;
StringBuilder quantifier = new StringBuilder();
// Read the quantifier content
while (i < len && pattern.charAt(i) != '}') {
quantifier.append(pattern.charAt(i));
i++;
}
if (i < len && pattern.charAt(i) == '}') {
// We have a complete quantifier
String content = quantifier.toString().trim();
// Check if it's a {,n} pattern or has spaces
if (content.matches("\\s*,\\s*\\d+\\s*")) {
// {,n} pattern - add 0 at the start
content = content.replaceAll("\\s*,\\s*(\\d+)\\s*", "0,$1");
result.append('{').append(content).append('}');
i++;
} else if (content.contains(",") && content.matches(".*\\s+.*")) {
// Has comma and spaces - remove spaces
content = content.replaceAll("\\s+", "");
result.append('{').append(content).append('}');
i++;
} else {
// Normal quantifier, keep as-is
result.append('{').append(quantifier).append('}');
i++;
}
} else {
// Unclosed {, not a quantifier - keep as-is
result.append('{').append(quantifier);
}
} else {
result.append(ch);
i++;
}
}
return result.toString();
}
/**
* Preprocesses a given regex string to make it compatible with Java's regex engine.
* This involves handling various constructs and escape sequences that Java does not
* natively support or requires in a different format.
*
* @param s The regex string to preprocess.
* @param offset The position in the string.
* @param sb The string builder to append the preprocessed regex to.
* @param regexFlags The regex flags to use.
* @param stopAtClosingParen A flag indicating whether to stop processing at the first closing parenthesis.
* @return The position in the string after the preprocessed regex.
* @throws PerlCompilerException If there are unmatched parentheses in the regex.
*/
static int handleRegex(String s, int offset, StringBuilder sb, RegexFlags regexFlags, boolean stopAtClosingParen) {
final int length = s.length();
boolean lastWasQuantifiable = false; // Track if the last thing can be quantified
// Remove \G from the pattern string for Java compilation
if (s.startsWith("\\G", offset)) {
offset += 2;
// Also strip any quantifier that followed \G (e.g. \G? in (\G?[ac])?)
// Since \G is a zero-width assertion, \G? is effectively nothing
if (offset < length) {
char next = s.charAt(offset);
if (next == '?' || next == '*' || next == '+') {
offset++;
}
}
}
while (offset < length) {
final int c = s.codePointAt(offset);
boolean isQuantifier = false;
switch (c) {
case '*':
case '+':
case '?':
// Check if the previous item can be quantified
if (!lastWasQuantifiable) {
// Distinguish "Nested quantifiers" from "Quantifier follows nothing":
// If the last char in sb is a quantifier, this is a nested quantifier
if (sb.length() > 0) {
char lc = sb.charAt(sb.length() - 1);
boolean esc = sb.length() >= 2 && sb.charAt(sb.length() - 2) == '\\';
if (!esc && (lc == '*' || lc == '+' || lc == '?' || lc == '}')) {
regexError(s, offset + 1, "Nested quantifiers");
}
}
regexError(s, offset + 1, "Quantifier follows nothing");
}
// Check if this might be a possessive quantifier
boolean isPossessive = offset + 1 < length && s.charAt(offset + 1) == '+';
// Check if this might be a non-greedy quantifier
boolean isNonGreedy = offset + 1 < length && s.charAt(offset + 1) == '?';
// Check for nested quantifiers (but not possessive or non-greedy)
if (!isPossessive && !isNonGreedy && sb.length() > 0) {
char lastChar = sb.charAt(sb.length() - 1);
// Also check if the previous character was a backslash (escaped)
boolean isEscaped = sb.length() >= 2 && sb.charAt(sb.length() - 2) == '\\';
if (!isEscaped && (lastChar == '*' || lastChar == '+' || lastChar == '?')) {
regexError(s, offset + 1, "Nested quantifiers");
}
}
sb.append(Character.toChars(c));
// If possessive or non-greedy, also append the following character
if (isPossessive) {
sb.append('+');
offset++; // Skip the extra +
lastWasQuantifiable = false; // Can't quantify a possessive quantifier
} else if (isNonGreedy) {
sb.append('?');
offset++; // Skip the extra ?
lastWasQuantifiable = false; // Can't quantify a non-greedy quantifier
} else {
lastWasQuantifiable = false; // Regular quantifier
}
break;
case '\\': // Handle escape sequences
offset = RegexPreprocessorHelper.handleEscapeSequences(s, sb, c, offset, regexFlags);
lastWasQuantifiable = true;
break;
case '[': // Handle character classes
offset = handleCharacterClass(s, regexFlags.isExtendedWhitespace(), sb, c, offset);
lastWasQuantifiable = true; // Character classes can be quantified
break;
case '(':
offset = handleParentheses(s, offset, length, sb, c, regexFlags, stopAtClosingParen);
lastWasQuantifiable = true;
break;
case ')':
if (stopAtClosingParen) {
return offset;
}
regexError(s, offset, "Unmatched ) in regex");
break;
case '#':
if (regexFlags.isExtended() || regexFlags.isExtendedWhitespace()) {
// Consume comment to end of line
while (offset < length) {
if (s.codePointAt(offset) == '\n') {
break;
}
offset++;
}
break;
} else {
sb.append(Character.toChars(c));
lastWasQuantifiable = true;
break;
}
case '{':
// Only treat '{' as a quantifier if the previous item is quantifiable.
// Otherwise, '{' must be a literal (Perl allows literal braces).
if (!lastWasQuantifiable) {
// Literal '{' (not a quantifier), escape for Java regex
sb.append("\\{");
lastWasQuantifiable = true;
} else {
// Parse as quantifier (may return literal braces if invalid quantifier)
int[] quantResult = handleQuantifier(s, offset, sb);
offset = quantResult[0];
boolean wasLiteral = quantResult[1] != 0;
if (wasLiteral) {
// Braces were treated as literal (e.g., {} or {,})
// The escaped \} is quantifiable
lastWasQuantifiable = true;
} else {
// Valid quantifier
// Check for possessive quantifier {n,m}+
if (offset + 1 < length && s.charAt(offset + 1) == '+') {
sb.append('+');
offset++; // Skip the extra +
}
// Check for non-greedy quantifier {n,m}?
else if (offset + 1 < length && s.charAt(offset + 1) == '?') {
sb.append('?');
offset++; // Skip the extra ?
}
isQuantifier = true;
lastWasQuantifiable = false; // Can't quantify a quantifier
}
}
break;
case '^':
sb.append(Character.toChars(c));
lastWasQuantifiable = false; // Can't quantify anchors
break;
case '|':
sb.append(Character.toChars(c));
lastWasQuantifiable = false; // Next item starts fresh
break;
default: // Append normal characters
sb.append(Character.toChars(c));
lastWasQuantifiable = true;
break;
}
// Check for nested quantifiers
if (isQuantifier && offset + 1 < length) {
char nextChar = s.charAt(offset + 1);
// Don't flag *+, ++, ?+ as nested quantifiers (they're possessive)
// Don't flag *?, +?, ??, }? as nested quantifiers (they're non-greedy)
boolean isModifier = (nextChar == '+' || nextChar == '?');
if (!isModifier && (nextChar == '*' || nextChar == '+' || nextChar == '?')) {
regexError(s, offset + 2, "Nested quantifiers");
}
// For '{', only flag as nested if it's actually a valid quantifier
if (nextChar == '{' && isValidQuantifierAt(s, offset + 1)) {
regexError(s, offset + 2, "Nested quantifiers");
}
}
offset++;
}
return offset;
}
static void regexError(String s, int offset, String errMsg) {
if (offset > s.length()) {
offset = s.length();
}
// "Error message in regex; marked by <-- HERE in m/regex <-- HERE remaining/"
String before = s.substring(0, offset);
String after = s.substring(offset);
// When marker is at the end, no space before <-- HERE
String marker = after.isEmpty() ? " <-- HERE" : " <-- HERE ";
throw new PerlCompilerException(errMsg + " in regex; marked by <-- HERE in m/" +
before + marker + after + "/");
}
private static int handleParentheses(String s, int offset, int length, StringBuilder sb, int c, RegexFlags regexFlags, boolean stopAtClosingParen) {
// Check for incomplete (?
if (offset + 1 >= length) {
regexError(s, offset + 1, "Sequence (? incomplete");
}
int c2 = s.codePointAt(offset + 1);
// Check for (*...) verb patterns FIRST, before checking (?
if (c2 == '*') {
// (*...) control verbs like (*ACCEPT), (*FAIL), (*COMMIT), etc.
// Also handles alpha assertion aliases: (*pla:...), (*plb:...), etc.
// Find the verb name (up to ':' or ')')
int verbNameEnd = offset + 2;
while (verbNameEnd < length) {
int cp = s.codePointAt(verbNameEnd);
if (cp == ':' || cp == ')') break;
verbNameEnd++;
}
String verbName = s.substring(offset + 2, verbNameEnd);
// Check for alpha assertion aliases (Perl 5.28+)
String replacement = switch (verbName) {
case "pla", "positive_lookahead" -> "(?=";
case "plb", "positive_lookbehind" -> "(?<=";
case "nla", "negative_lookahead" -> "(?!";
case "nlb", "negative_lookbehind" -> "(?<!";
case "atomic" -> "(?>";
default -> null;
};
if (replacement != null && verbNameEnd < length && s.codePointAt(verbNameEnd) == ':') {
// Alpha assertion with content: (*pla:...) -> (?=...)
sb.append(replacement);
offset = handleRegex(s, verbNameEnd + 1, sb, regexFlags, true);
// Fall through to common ')' handling at end of handleParentheses
} else {
// Find the end of the verb for error reporting
int verbEnd = offset + 2;
while (verbEnd < length && s.codePointAt(verbEnd) != ')') {
verbEnd++;
}
if (verbEnd < length) {
verbEnd++; // Include the closing paren
}
// Extract the verb name for error reporting
String verb = s.substring(offset, Math.min(verbEnd, length));