forked from google/closure-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegExpTree.java
More file actions
2320 lines (2089 loc) · 70.7 KB
/
Copy pathRegExpTree.java
File metadata and controls
2320 lines (2089 loc) · 70.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
/*
* Copyright 2011 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp.regex;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.Math.min;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* An AST for JavaScript regular expressions.
*/
public abstract class RegExpTree {
/**
* Returns a simpler regular expression that is semantically the same assuming
* the given flags.
* @param flags Regular expression flags, e.g. {@code "igm"}.
*/
public abstract RegExpTree simplify(String flags);
/**
* True if the presence or absence of an {@code "i"} flag would change the
* meaning of this regular expression.
*/
public abstract boolean isCaseSensitive();
/**
* True if the regular expression contains an anchor : {@code ^} or {@code $}.
*/
public abstract boolean containsAnchor();
/**
* True if the regular expression contains capturing groups.
*/
public final boolean hasCapturingGroup() {
return numCapturingGroups() != 0;
}
/**
* The number of capturing groups.
*/
public abstract int numCapturingGroups();
/**
* The children of this node.
*/
public abstract List<? extends RegExpTree> children();
/**
* Appends this regular expression source to the given buffer.
*/
protected abstract void appendSourceCode(StringBuilder sb);
protected abstract void appendDebugInfo(StringBuilder sb);
@Override
public final String toString() {
StringBuilder sb = new StringBuilder();
sb.append('/');
appendSourceCode(sb);
// Don't emit a regular expression that looks like a line comment start.
if (sb.length() == 1) {
sb.append("(?:)");
}
sb.append('/');
return sb.toString();
}
@Override
public abstract boolean equals(Object o);
@Override
public abstract int hashCode();
private enum ParentheticalType {
CAPTURING,
NONCAPTURING,
POSITIVE_LOOKAHEAD,
NEGATIVE_LOOKAHEAD,
POSITIVE_LOOKBEHIND,
NEGATIVE_LOOKBEHIND,
NAMED_GROUPS,
}
/**
* Parses a regular expression to an AST.
*
* @param pattern The {@code foo} From {@code /foo/i}.
* @param flags The {@code i} From {@code /foo/i}.
*/
public static RegExpTree parseRegExp(
final String pattern, final String flags) {
/** A recursive descent parser that closes over pattern and flags above. */
class Parser {
/** The number of characters in pattern consumed. */
int pos;
/** The number of capturing groups seen so far. */
int numCapturingGroups;
/** The names of capturing groups in the regex expression */
Set<String> capturingGroupNames = new HashSet<>();
/** The length of pattern. */
final int limit = pattern.length();
/** Boolean indicating whether we should look for named capture group backreferences */
boolean lookForNamedCaptureBackreferences;
RegExpTree parseTopLevel() {
// First assume there are no named capture backreferences,
// because the spec says they should only be recognized
// if the pattern contains at least one named capture group.
this.pos = 0;
this.numCapturingGroups = 0;
this.lookForNamedCaptureBackreferences = false;
RegExpTree out = parse();
// If there were named capture groups, we must parse the pattern string again
// so we can check for any backreferences to them.
if (!capturingGroupNames.isEmpty()) {
this.pos = 0;
this.numCapturingGroups = 0;
this.lookForNamedCaptureBackreferences = true;
out = parse();
}
if (pos < limit) { // Unmatched closed paren maybe.
throw new IllegalArgumentException(pattern.substring(pos));
}
return out;
}
RegExpTree parse() {
// Collects ["foo", "bar", "baz"] for /foo|bar|baz/.
ImmutableList.Builder<RegExpTree> alternatives = null;
// The last item parsed within an alternation.
RegExpTree preceder = null;
topLoop:
while (pos < limit) {
char ch = pattern.charAt(pos);
RegExpTree atom;
switch (ch) {
case '[':
atom = parseCharset();
break;
case '(':
atom = parseParenthetical();
break;
case ')':
break topLoop;
case '\\':
atom = parseEscape();
break;
case '^':
case '$':
atom = new Anchor(ch);
++pos;
break;
case '.':
// We represent . as a character set to make it easy to simplify
// things like /.|[\r\n]/.
atom = DOT_CHARSET;
++pos;
break;
case '|':
// An alternative may be empty as in /foo||bar/.
// The '|' is consumed below.
atom = Empty.INSTANCE;
break;
default:
// Find a run of concatenated characters to avoid building a
// tree node per literal character.
int start = pos;
int end = pos + 1;
charsLoop:
while (end < limit) {
switch (pattern.charAt(end)) {
case '[':
case '(':
case ')':
case '\\':
case '^':
case '$':
case '|':
case '.':
case '*':
case '+':
case '?':
case '{':
break charsLoop;
default:
// Repetition binds more tightly than concatenation.
// Only consume up to "foo" in /foob*/ so that the suffix
// operator parser below has the right precedence.
if (end + 1 >= limit
|| !isRepetitionStart(pattern.charAt(end + 1))) {
++end;
} else {
break charsLoop;
}
}
}
atom = new Text(pattern.substring(start, end));
pos = end;
break;
}
if (pos < limit && isRepetitionStart(pattern.charAt(pos))) {
atom = parseRepetition(atom);
}
if (preceder == null) {
preceder = atom;
} else {
preceder = new Concatenation(preceder, atom);
}
// If this is an alternative in a alternation, then add it to the
// list of complete alternatives, and reset the parser state for the
// next alternative.
if (pos < limit && pattern.charAt(pos) == '|') {
if (alternatives == null) {
alternatives = ImmutableList.builder();
}
alternatives.add(preceder);
preceder = null;
++pos;
}
}
// An alternative may have no parsed content blank as in /foo|/.
if (preceder == null) { preceder = Empty.INSTANCE; }
if (alternatives != null) {
alternatives.add(preceder);
return new Alternation(alternatives.build());
} else {
return preceder;
}
}
/**
* Handles capturing groups {@code (...)},
* non-capturing groups {@code (?:...)}, and lookahead assertions
* {@code (?=...)}.
*/
private RegExpTree parseParenthetical() {
checkState(pattern.charAt(pos) == '(');
int start = pos;
++pos;
ParentheticalType type;
String captureName = null;
if (pos < limit && pattern.charAt(pos) == '?') {
if (pos + 1 < limit) {
char ch = pattern.charAt(pos + 1);
switch (ch) {
// (?:...) Non-capturing groups.
case ':':
pos += 2;
type = ParentheticalType.NONCAPTURING;
break;
// (?=...) and (?!...) Lookahead Assertions
case '=':
pos += 2;
type = ParentheticalType.POSITIVE_LOOKAHEAD;
break;
case '!':
pos += 2;
type = ParentheticalType.NEGATIVE_LOOKAHEAD;
break;
// (?<=...) and (?<!...) Lookbehind Assertions, (?<name>) named groups
case '<':
if (pos + 2 < limit && pattern.charAt(pos + 2) == '=') {
pos += 3;
type = ParentheticalType.POSITIVE_LOOKBEHIND;
break;
} else if (pos + 2 < limit && pattern.charAt(pos + 2) == '!') {
pos += 3;
type = ParentheticalType.NEGATIVE_LOOKBEHIND;
break;
} else {
pos += 2;
captureName = scanNamedGroupName();
capturingGroupNames.add(captureName);
type = ParentheticalType.NAMED_GROUPS;
break;
}
default:
throw new IllegalArgumentException(
"Malformed parenthetical: " + pattern.substring(start));
}
} else {
throw new IllegalArgumentException(
"Malformed parenthetical: " + pattern.substring(start));
}
} else {
type = ParentheticalType.CAPTURING;
}
RegExpTree body = parse();
if (pos < limit && pattern.charAt(pos) == ')') {
++pos;
} else {
throw new IllegalArgumentException(
"Unclosed parenthetical group: " + pattern.substring(start));
}
switch (type) {
case CAPTURING:
++numCapturingGroups;
return new CapturingGroup(body);
case NONCAPTURING:
return body;
case POSITIVE_LOOKAHEAD:
return new LookaheadAssertion(body, true);
case NEGATIVE_LOOKAHEAD:
return new LookaheadAssertion(body, false);
case POSITIVE_LOOKBEHIND:
return new LookbehindAssertion(body, true);
case NEGATIVE_LOOKBEHIND:
return new LookbehindAssertion(body, false);
case NAMED_GROUPS:
if (captureName != null) {
++numCapturingGroups;
return new NamedCaptureGroup(body, captureName);
} else {
throw new IllegalArgumentException(
"Malformed named capture group: " + pattern.substring(start));
}
}
throw new AssertionError("Unrecognized ParentheticalType " + type);
}
/**
* Helper that scans the pattern for a named group name. Assumes that {@code pos} points to
* the character after '<'
*
* @return the group name
*/
private String scanNamedGroupName() {
int start = pos;
int end = pos;
if (!isIdentifierStart(pattern.charAt(start))) {
throw new IllegalArgumentException(
"Invalid capture group name: <" + pattern.substring(start));
}
++end;
while (end < limit) {
if (pattern.charAt(end) == '>') {
pos = end + 1;
return pattern.substring(start, end);
} else if (isIdentifierPart(pattern.charAt(end))) {
++end;
} else {
throw new IllegalArgumentException(
"Invalid capture group name: <" + pattern.substring(start));
}
}
throw new IllegalArgumentException(
"Malformed named capture group: <" + pattern.substring(start));
}
/**
* Parses a square bracketed character set.
* Standalone character groups (@code /\d/} are handled by
* {@link #parseEscape}.
*/
private RegExpTree parseCharset() {
checkState(pattern.charAt(pos) == '[');
++pos;
boolean isCaseInsensitive = flags.indexOf('i') >= 0;
boolean inverse = pos < limit && pattern.charAt(pos) == '^';
if (inverse) { ++pos; }
CharRanges ranges = CharRanges.EMPTY;
CharRanges ieExplicits = CharRanges.EMPTY;
while (pos < limit && pattern.charAt(pos) != ']') {
char ch = pattern.charAt(pos);
int start;
if (ch == '\\') {
++pos;
char possibleGroupName = pattern.charAt(pos);
CharRanges group = NAMED_CHAR_GROUPS.get(possibleGroupName);
if (group != null) {
++pos;
ranges = ranges.union(group);
continue;
}
start = parseEscapeChar();
} else {
start = ch;
++pos;
}
int end = start;
if (pos + 1 < limit && pattern.charAt(pos) == '-'
&& pattern.charAt(pos + 1) != ']') {
++pos;
ch = pattern.charAt(pos);
if (ch == '\\') {
++pos;
end = parseEscapeChar();
} else {
end = ch;
++pos;
}
}
CharRanges range = CharRanges.inclusive(start, end);
ranges = ranges.union(range);
if (IE_SPEC_ERRORS.contains(start) && IE_SPEC_ERRORS.contains(end)) {
ieExplicits = ieExplicits.union(range.intersection(IE_SPEC_ERRORS));
}
if (isCaseInsensitive) {
// If the flags contain the 'i' flag, then it is not correct to
// say that [^a-z] contains the letter 'A', or that [a-z] does not
// contain the letter 'A'.
// We expand out letter groups here so that parse returns something
// that is valid independent of flags.
// Calls to simplify(flags) may later reintroduce flag assumptions.
// but without this step, later steps might conflate
// /[a-z]/i
// and
// /[^\0-`{-\uffff]/i
// which matches nothing because the information about whether the
// ^ is present has been lost during optimizations and charset
// unionizing as in /[...]|[^...]/.
ranges = CaseCanonicalize.expandToAllMatched(ranges);
}
}
++pos; // Consume ']'
if (inverse) {
ranges = CharRanges.ALL_CODE_UNITS.difference(ranges);
}
return new Charset(ranges, ieExplicits);
}
/**
* Parses an escape to a code point.
* Some of the characters parsed here have special meanings in various
* contexts, so contexts must filter those instead.
* E.g. '\b' means a different thing inside a charset than without.
*/
private int parseEscapeChar() {
char ch = pattern.charAt(pos++);
switch (ch) {
case 'b': return '\b';
case 'f': return '\f';
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
case 'u':
if (flags.contains("u") && pos < limit && pattern.charAt(pos) == '{') {
return parseUnicodeEscape();
} else {
return parseHex(4);
}
case 'v': return '\u000b';
case 'x': return parseHex(2);
default:
if ('0' <= ch && ch <= '7') {
char codeUnit = (char) (ch - '0');
// Allow octal literals in the range \0-\377.
// \41 might be a group, but \041 is not a group.
// We read, but do not emit octal literals since they
// are deprecated in ES5.
int octLimit = min(limit, pos + (ch <= '3' ? 2 : 1) + (ch == '0' ? 1 : 0));
while (pos < octLimit) {
ch = pattern.charAt(pos);
if ('0' <= ch && ch <= '7') {
codeUnit = (char) ((codeUnit << 3) + (ch - '0'));
++pos;
} else {
break;
}
}
return codeUnit;
}
return ch;
}
}
/**
* Parses an escape that appears outside a charset.
*/
private RegExpTree parseEscape() {
checkState(pattern.charAt(pos) == '\\');
int start = pos;
++pos;
char ch = pattern.charAt(pos);
if (ch == 'b' || ch == 'B') {
++pos;
return new WordBoundary(ch);
} else if ((ch == 'p' || ch == 'P') && flags.contains("u")) {
// handle ES2018 unicode property tests, e.g.
// /\p{ASCII_Hex_Digit=true}/ only hex digits
// /\P{Script=Greek}/ no greek letters
boolean negated = ch == 'P';
++pos;
if (pos < limit && pattern.charAt(pos) == '{') {
StringBuilder lhs = new StringBuilder();
while (++pos < limit
&& ((ch = pattern.charAt(pos)) == '_'
|| ('a' <= ch && ch <= 'z')
|| ('A' <= ch && ch <= 'Z')
|| ('0' <= ch && ch <= '9'))) {
lhs.append(ch);
}
if (pos < limit && ch == '}') {
// Case of shorthand like /\p{ASCII_Hex_Digit}/u
++pos;
return new UnicodePropertyEscape(null, lhs.toString(), negated);
} else if (pos < limit && ch == '=') {
// Case of having '=' like /\p{Script=Greek}/u
StringBuilder rhs = new StringBuilder();
while (++pos < limit
&& ((ch = pattern.charAt(pos)) == '_'
|| ('a' <= ch && ch <= 'z')
|| ('A' <= ch && ch <= 'Z')
|| ('0' <= ch && ch <= '9'))) {
rhs.append(ch);
}
if (pos < limit && ch == '}') {
++pos;
return new UnicodePropertyEscape(lhs.toString(), rhs.toString(), negated);
} else {
throw new IllegalArgumentException(
"Malformed Unicode Property Escape: expected '}' after "
+ pattern.substring(start, pos));
}
} else {
throw new IllegalArgumentException(
"Malformed Unicode Property Escape: expected '=' or '}' after "
+ pattern.substring(start, pos));
}
} else {
throw new IllegalArgumentException(
"Malformed Unicode Property Escape: expected '{' after "
+ pattern.substring(start, pos));
}
} else if ('1' <= ch && ch <= '9') {
++pos;
int possibleGroupIndex = ch - '0';
if (numCapturingGroups >= possibleGroupIndex) {
if (pos < limit) {
char next = pattern.charAt(pos);
if ('0' <= next && next <= '9') {
int twoDigitGroupIndex = possibleGroupIndex * 10 + (next - '0');
if (numCapturingGroups >= twoDigitGroupIndex) {
++pos;
possibleGroupIndex = twoDigitGroupIndex;
}
}
}
return new BackReference(possibleGroupIndex);
} else {
// \1 - \7 are octal escapes if there is no such group.
// \8 and \9 are the literal characters '8' and '9' if there
// is no such group.
return new Text(Character.toString(
possibleGroupIndex <= 7 ? (char) possibleGroupIndex : ch));
}
} else if (lookForNamedCaptureBackreferences
&& ch == 'k'
&& pos + 1 < limit
&& pattern.charAt(pos + 1) == '<'
// According to the spec
// https://github.com/tc39/proposal-regexp-named-groups#backwards-compatibility-of-new-syntax
// we want to treat \k as a normal string if there are no named capturing groups present
&& !capturingGroupNames.isEmpty()) {
pos += 2;
String potentialName = scanNamedGroupName();
if (!capturingGroupNames.contains(potentialName)) {
throw new IllegalArgumentException(
"Invalid named capture referenced: " + pattern.substring(start));
}
return new NamedBackReference(potentialName);
} else {
CharRanges charGroup = NAMED_CHAR_GROUPS.get(ch);
if (charGroup != null) { // Handle \d, etc.
++pos;
return new Charset(charGroup, CharRanges.EMPTY);
}
return new Text(new String(Character.toChars(parseEscapeChar())));
}
}
/**
* Parses n hex digits to a code-unit.
*/
private char parseHex(int n) {
if (pos + n > limit) {
throw new IllegalArgumentException(
"Abbreviated hex escape " + pattern.substring(pos));
}
int result = 0;
while (--n >= 0) {
char ch = pattern.charAt(pos);
int digit;
if ('0' <= ch && ch <= '9') {
digit = ch - '0';
} else if ('a' <= ch && ch <= 'f') {
digit = ch + (10 - 'a');
} else if ('A' <= ch && ch <= 'F') {
digit = ch + (10 - 'A');
} else {
throw new IllegalArgumentException(pattern.substring(pos));
}
++pos;
result = (result << 4) | digit;
}
return (char) result;
}
private int parseUnicodeEscape() {
checkState(pattern.charAt(pos) == '{');
int start = pos++;
int result = 0;
char ch = pattern.charAt(pos);
if (ch == '}') {
throw new IllegalArgumentException("Invalid unicode escape: "
+ pattern.substring(start, ++pos));
}
while (pos < limit) {
int digit;
ch = pattern.charAt(pos++);
if ('0' <= ch && ch <= '9') {
digit = ch - '0';
} else if ('a' <= ch && ch <= 'f') {
digit = ch + (10 - 'a');
} else if ('A' <= ch && ch <= 'F') {
digit = ch + (10 - 'A');
} else if (ch == '}') {
break;
} else {
throw new IllegalArgumentException("Invalid character in unicode escape: " + ch);
}
result = (result << 4) | digit;
}
if (ch != '}') {
throw new IllegalArgumentException("Malformed unicode escape: expected '}' after "
+ pattern.substring(start, pos));
}
if (result > 0x10FFFF) {
throw new IllegalArgumentException("Unicode must not be greater than 0x10FFFF: "
+ pattern.substring(start, pos));
}
return result;
}
private boolean isRepetitionStart(char ch) {
switch (ch) {
case '?':
case '*':
case '+':
case '{':
return true;
default:
return false;
}
}
/**
* Parse a repetition. {@code x?} is treated as a repetition --
* an optional production can be matched 0 or 1 time.
*/
private RegExpTree parseRepetition(RegExpTree body) {
if (pos == limit) { return body; }
int min, max;
switch (pattern.charAt(pos)) {
case '+':
++pos;
min = 1;
max = Integer.MAX_VALUE;
break;
case '*':
++pos;
min = 0;
max = Integer.MAX_VALUE;
break;
case '?':
++pos;
min = 0;
max = 1;
break;
case '{':
++pos;
int start = pos;
int end = pattern.indexOf('}', start);
if (end < 0) {
pos = start - 1;
return body;
}
String counts = pattern.substring(start, end);
pos = end + 1;
int comma = counts.indexOf(',');
try {
min = Integer.parseInt(
comma >= 0 ? counts.substring(0, comma) : counts);
max = comma >= 0
? comma + 1 != counts.length()
? Integer.parseInt(counts.substring(comma + 1))
: Integer.MAX_VALUE
: min;
} catch (NumberFormatException ex) {
min = max = -1;
}
if (min < 0 || min > max) {
// Treat the open curly bracket literally.
pos = start - 1;
return body;
}
break;
default:
return body;
}
boolean greedy = true;
if (pos < limit && pattern.charAt(pos) == '?') {
greedy = false;
++pos;
}
return new Repetition(body, min, max, greedy);
}
}
return new Parser().parseTopLevel();
}
/**
* @param ch the character
* @return true if the character is a valid Javascript identifier start character.
*/
private static boolean isIdentifierStart(char ch) {
// TODO(yitingwang) This and the one in Scanner.java should share the same implementation
// Most code is written in pure ASCII create a fast path here.
if (ch <= 127) {
return ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch == '_' || ch == '$'));
}
// Workaround b/36459436
// When running under GWT, Character.isLetter only handles ASCII
// Angular relies heavily on U+0275 (Latin Barred O)
return ch == 0x0275
// TODO: UnicodeLetter also includes Letter Number (NI)
|| Character.isLetter(ch);
}
/**
* @param ch the character
* @return true if the character is allowed in Javascript identifiers.
*/
private static boolean isIdentifierPart(char ch) {
// TODO(yitingwang) This and the one in Scanner.java should share the same implementation
// Most code is written in pure ASCII create a fast path here.
if (ch <= 127) {
return ((ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')
|| (ch >= '0' && ch <= '9')
|| (ch == '_' || ch == '$')); // _ or $
}
// TODO: identifier part character classes
// CombiningMark
// Non-Spacing mark (Mn)
// Combining spacing mark(Mc)
// Connector punctuation (Pc)
// Zero Width Non-Joiner
// Zero Width Joiner
return isIdentifierStart(ch) || Character.isDigit(ch);
}
/**
* True if, but not necessarily always when the, given regular expression
* must match the whole input or none of it.
*/
public static boolean matchesWholeInput(RegExpTree t, String flags) {
if (flags.indexOf('m') >= 0) { return false; }
if (!(t instanceof Concatenation)) {
return false;
}
Concatenation c = (Concatenation) t;
if (c.elements.isEmpty()) { return false; }
RegExpTree first = c.elements.get(0), last = Iterables.getLast(c.elements);
if (!(first instanceof Anchor && last instanceof Anchor)) { return false; }
return ((Anchor) first).type == '^' && ((Anchor) last).type == '$';
}
/** Represents a node that never has children such as an anchor or charset. */
public abstract static class RegExpTreeAtom extends RegExpTree {
@Override
public boolean isCaseSensitive() {
return false;
}
@Override
public boolean containsAnchor() {
return false;
}
@Override
public final int numCapturingGroups() {
return 0;
}
@Override
public final ImmutableList<? extends RegExpTree> children() {
return ImmutableList.of();
}
}
/** Represents an empty portion of a RegExp such as the middle of "||" */
public static final class Empty extends RegExpTreeAtom {
static final Empty INSTANCE = new Empty();
@Override
public RegExpTree simplify(String flags) {
return this;
}
@Override
protected void appendSourceCode(StringBuilder sb) {
// No output
}
@Override
protected void appendDebugInfo(StringBuilder sb) {
// No output
}
@Override
public boolean equals(Object o) {
return o instanceof Empty;
}
@Override
public int hashCode() {
return 0x7ee06141;
}
}
/** Represents an anchor, namely ^ or $. */
public static final class Anchor extends RegExpTreeAtom {
final char type;
Anchor(char type) { this.type = type; }
@Override
public RegExpTree simplify(String flags) {
return this;
}
@Override
public boolean containsAnchor() {
return true;
}
@Override
protected void appendSourceCode(StringBuilder sb) {
sb.append(type);
}
@Override
protected void appendDebugInfo(StringBuilder sb) {
sb.append(type);
}
@Override
public boolean equals(Object o) {
return o instanceof Anchor && type == ((Anchor) o).type;
}
@Override
public int hashCode() {
return type ^ 0xe85317ff;
}
}
/** Represents \b or \B */
public static final class WordBoundary extends RegExpTreeAtom {
final char type;
WordBoundary(char type) {
this.type = type;
}
@Override
public RegExpTree simplify(String flags) {
return this;
}
@Override
protected void appendSourceCode(StringBuilder sb) {
sb.append('\\').append(type);
}
@Override
protected void appendDebugInfo(StringBuilder sb) {
sb.append(type);
}
@Override
public boolean equals(Object o) {
return o instanceof WordBoundary && type == ((WordBoundary) o).type;
}
@Override
public int hashCode() {
return 0x5673aa29 ^ type;
}
}
/** Represents a reference to a previous group such as \1 or \2 */
public static final class BackReference extends RegExpTreeAtom {
final int groupIndex;
BackReference(int groupIndex) {
checkArgument(groupIndex >= 0 && groupIndex <= 99);
this.groupIndex = groupIndex;
}
@Override
public RegExpTree simplify(String flags) {
return this;
}
@Override
protected void appendSourceCode(StringBuilder sb) {
sb.append('\\').append(groupIndex);
}
@Override
protected void appendDebugInfo(StringBuilder sb) {
sb.append(groupIndex);
}
@Override
public boolean equals(Object o) {
return o instanceof BackReference
&& groupIndex == ((BackReference) o).groupIndex;
}
@Override
public int hashCode() {
return 0xff072663 ^ groupIndex;
}
}
/** Represents a reference to a previous named group */
public static final class NamedBackReference extends RegExpTreeAtom {
final String groupName;
NamedBackReference(String groupName) {
this.groupName = groupName;
}
@Override
public RegExpTree simplify(String flags) {
return this;
}
@Override
protected void appendSourceCode(StringBuilder sb) {
sb.append("\\k<").append(groupName).append('>');
}
@Override
protected void appendDebugInfo(StringBuilder sb) {
sb.append(groupName);
}
@Override
public boolean equals(Object o) {
return o instanceof NamedBackReference
&& groupName.equals(((NamedBackReference) o).groupName);
}
@Override