forked from google/re2j
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.java
More file actions
1730 lines (1585 loc) · 52.3 KB
/
Copy pathParser.java
File metadata and controls
1730 lines (1585 loc) · 52.3 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 (c) 2020 The Go Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
// Original Go source here:
// http://code.google.com/p/go/source/browse/src/pkg/regexp/syntax/parse.go
// TODO(adonovan):
// - Eliminate allocations (new int[], new Regexp[], new ArrayList) by
// recycling old arrays on a freelist.
package com.google.re2j;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* A parser of regular expression patterns.
*
* The only public entry point is {@link #parse(String pattern, int flags)}.
*/
class Parser {
// Unexpected error
private static final String ERR_INTERNAL_ERROR = "regexp/syntax: internal error";
// Parse errors
private static final String ERR_INVALID_CHAR_RANGE = "invalid character class range";
private static final String ERR_INVALID_ESCAPE = "invalid escape sequence";
private static final String ERR_INVALID_NAMED_CAPTURE = "invalid named capture";
private static final String ERR_INVALID_PERL_OP = "invalid or unsupported Perl syntax";
private static final String ERR_INVALID_REPEAT_OP = "invalid nested repetition operator";
private static final String ERR_INVALID_REPEAT_SIZE = "invalid repeat count";
private static final String ERR_MISSING_BRACKET = "missing closing ]";
private static final String ERR_MISSING_PAREN = "missing closing )";
private static final String ERR_MISSING_REPEAT_ARGUMENT =
"missing argument to repetition operator";
private static final String ERR_TRAILING_BACKSLASH = "trailing backslash at end of expression";
private static final String ERR_DUPLICATE_NAMED_CAPTURE = "duplicate capture group name";
// Hack to expose ArrayList.removeRange().
private static class Stack extends ArrayList<Regexp> {
@Override
public void removeRange(int fromIndex, int toIndex) {
super.removeRange(fromIndex, toIndex);
}
}
private final String wholeRegexp;
// Flags control the behavior of the parser and record information about
// regexp context.
private int flags; // parse mode flags
// Stack of parsed expressions.
private final Stack stack = new Stack();
private Regexp free;
private int numCap = 0; // number of capturing groups seen
private final Map<String, Integer> namedGroups = new HashMap<String, Integer>();
Parser(String wholeRegexp, int flags) {
this.wholeRegexp = wholeRegexp;
this.flags = flags;
}
// Allocate a Regexp, from the free list if possible.
private Regexp newRegexp(Regexp.Op op) {
Regexp re = free;
if (re != null && re.subs != null && re.subs.length > 0) {
free = re.subs[0];
re.reinit();
re.op = op;
} else {
re = new Regexp(op);
}
return re;
}
private void reuse(Regexp re) {
if (re.subs != null && re.subs.length > 0) {
re.subs[0] = free;
}
free = re;
}
// Parse stack manipulation.
private Regexp pop() {
return stack.remove(stack.size() - 1);
}
private Regexp[] popToPseudo() {
int n = stack.size(), i = n;
while (i > 0 && !stack.get(i - 1).op.isPseudo()) {
i--;
}
Regexp[] r = stack.subList(i, n).toArray(new Regexp[n - i]);
stack.removeRange(i, n);
return r;
}
// push pushes the regexp re onto the parse stack and returns the regexp.
// Returns null for a CHAR_CLASS that can be merged with the top-of-stack.
private Regexp push(Regexp re) {
if (re.op == Regexp.Op.CHAR_CLASS && re.runes.length == 2 && re.runes[0] == re.runes[1]) {
// Collapse range [x-x] -> single rune x.
if (maybeConcat(re.runes[0], flags & ~RE2.FOLD_CASE)) {
return null;
}
re.op = Regexp.Op.LITERAL;
re.runes = new int[] {re.runes[0]};
re.flags = flags & ~RE2.FOLD_CASE;
} else if ((re.op == Regexp.Op.CHAR_CLASS
&& re.runes.length == 4
&& re.runes[0] == re.runes[1]
&& re.runes[2] == re.runes[3]
&& Unicode.simpleFold(re.runes[0]) == re.runes[2]
&& Unicode.simpleFold(re.runes[2]) == re.runes[0])
|| (re.op == Regexp.Op.CHAR_CLASS
&& re.runes.length == 2
&& re.runes[0] + 1 == re.runes[1]
&& Unicode.simpleFold(re.runes[0]) == re.runes[1]
&& Unicode.simpleFold(re.runes[1]) == re.runes[0])) {
//
if (maybeConcat(re.runes[0], flags | RE2.FOLD_CASE)) {
return null;
}
// Rewrite as (case-insensitive) literal.
re.op = Regexp.Op.LITERAL;
re.runes = new int[] {re.runes[0]};
re.flags = flags | RE2.FOLD_CASE;
} else {
// Incremental concatenation.
maybeConcat(-1, 0);
}
stack.add(re);
return re;
}
// maybeConcat implements incremental concatenation
// of literal runes into string nodes. The parser calls this
// before each push, so only the top fragment of the stack
// might need processing. Since this is called before a push,
// the topmost literal is no longer subject to operators like *
// (Otherwise ab* would turn into (ab)*.)
// If (r >= 0 and there's a node left over, maybeConcat uses it
// to push r with the given flags.
// maybeConcat reports whether r was pushed.
private boolean maybeConcat(int r, int flags) {
int n = stack.size();
if (n < 2) {
return false;
}
Regexp re1 = stack.get(n - 1);
Regexp re2 = stack.get(n - 2);
if (re1.op != Regexp.Op.LITERAL
|| re2.op != Regexp.Op.LITERAL
|| (re1.flags & RE2.FOLD_CASE) != (re2.flags & RE2.FOLD_CASE)) {
return false;
}
// Push re1 into re2.
re2.runes = concatRunes(re2.runes, re1.runes);
// Reuse re1 if possible.
if (r >= 0) {
re1.runes = new int[] {r};
re1.flags = flags;
return true;
}
pop();
reuse(re1);
return false; // did not push r
}
// newLiteral returns a new LITERAL Regexp with the given flags
private Regexp newLiteral(int r, int flags) {
Regexp re = newRegexp(Regexp.Op.LITERAL);
re.flags = flags;
if ((flags & RE2.FOLD_CASE) != 0) {
r = minFoldRune(r);
}
re.runes = new int[] {r};
return re;
}
// minFoldRune returns the minimum rune fold-equivalent to r.
private static int minFoldRune(int r) {
if (r < Unicode.MIN_FOLD || r > Unicode.MAX_FOLD) {
return r;
}
int min = r;
int r0 = r;
for (r = Unicode.simpleFold(r); r != r0; r = Unicode.simpleFold(r)) {
if (min > r) {
min = r;
}
}
return min;
}
// literal pushes a literal regexp for the rune r on the stack
// and returns that regexp.
private void literal(int r) {
push(newLiteral(r, flags));
}
// op pushes a regexp with the given op onto the stack
// and returns that regexp.
private Regexp op(Regexp.Op op) {
Regexp re = newRegexp(op);
re.flags = flags;
return push(re);
}
// repeat replaces the top stack element with itself repeated according to
// op, min, max. beforePos is the start position of the repetition operator.
// Pre: t is positioned after the initial repetition operator.
// Post: t advances past an optional perl-mode '?', or stays put.
// Or, it fails with PatternSyntaxException.
private void repeat(
Regexp.Op op, int min, int max, int beforePos, StringIterator t, int lastRepeatPos)
throws PatternSyntaxException {
int flags = this.flags;
if ((flags & RE2.PERL_X) != 0) {
if (t.more() && t.lookingAt('?')) {
t.skip(1); // '?'
flags ^= RE2.NON_GREEDY;
}
if (lastRepeatPos != -1) {
// In Perl it is not allowed to stack repetition operators:
// a** is a syntax error, not a doubled star, and a++ means
// something else entirely, which we don't support!
throw new PatternSyntaxException(ERR_INVALID_REPEAT_OP, t.from(lastRepeatPos));
}
}
int n = stack.size();
if (n == 0) {
throw new PatternSyntaxException(ERR_MISSING_REPEAT_ARGUMENT, t.from(beforePos));
}
Regexp sub = stack.get(n - 1);
if (sub.op.isPseudo()) {
throw new PatternSyntaxException(ERR_MISSING_REPEAT_ARGUMENT, t.from(beforePos));
}
Regexp re = newRegexp(op);
re.min = min;
re.max = max;
re.flags = flags;
re.subs = new Regexp[] {sub};
stack.set(n - 1, re);
}
// concat replaces the top of the stack (above the topmost '|' or '(') with
// its concatenation.
private Regexp concat() {
maybeConcat(-1, 0);
// Scan down to find pseudo-operator | or (.
Regexp[] subs = popToPseudo();
// Empty concatenation is special case.
if (subs.length == 0) {
return push(newRegexp(Regexp.Op.EMPTY_MATCH));
}
return push(collapse(subs, Regexp.Op.CONCAT));
}
// alternate replaces the top of the stack (above the topmost '(') with its
// alternation.
private Regexp alternate() {
// Scan down to find pseudo-operator (.
// There are no | above (.
Regexp[] subs = popToPseudo();
// Make sure top class is clean.
// All the others already are (see swapVerticalBar).
if (subs.length > 0) {
cleanAlt(subs[subs.length - 1]);
}
// Empty alternate is special case
// (shouldn't happen but easy to handle).
if (subs.length == 0) {
return push(newRegexp(Regexp.Op.NO_MATCH));
}
return push(collapse(subs, Regexp.Op.ALTERNATE));
}
// cleanAlt cleans re for eventual inclusion in an alternation.
private void cleanAlt(Regexp re) {
if (re.op == Regexp.Op.CHAR_CLASS) {
re.runes = new CharClass(re.runes).cleanClass().toArray();
if (re.runes.length == 2 && re.runes[0] == 0 && re.runes[1] == Unicode.MAX_RUNE) {
re.runes = null;
re.op = Regexp.Op.ANY_CHAR;
} else if (re.runes.length == 4
&& re.runes[0] == 0
&& re.runes[1] == '\n' - 1
&& re.runes[2] == '\n' + 1
&& re.runes[3] == Unicode.MAX_RUNE) {
re.runes = null;
re.op = Regexp.Op.ANY_CHAR_NOT_NL;
}
}
}
// collapse returns the result of applying op to subs[start:end].
// If (sub contains op nodes, they all get hoisted up
// so that there is never a concat of a concat or an
// alternate of an alternate.
private Regexp collapse(Regexp[] subs, Regexp.Op op) {
if (subs.length == 1) {
return subs[0];
}
// Concatenate subs iff op is same.
// Compute length in first pass.
int len = 0;
for (Regexp sub : subs) {
len += (sub.op == op) ? sub.subs.length : 1;
}
Regexp[] newsubs = new Regexp[len];
int i = 0;
for (Regexp sub : subs) {
if (sub.op == op) {
System.arraycopy(sub.subs, 0, newsubs, i, sub.subs.length);
i += sub.subs.length;
reuse(sub);
} else {
newsubs[i++] = sub;
}
}
Regexp re = newRegexp(op);
re.subs = newsubs;
if (op == Regexp.Op.ALTERNATE) {
re.subs = factor(re.subs, re.flags);
if (re.subs.length == 1) {
Regexp old = re;
re = re.subs[0];
reuse(old);
}
}
return re;
}
// factor factors common prefixes from the alternation list sub. It
// returns a replacement list that reuses the same storage and frees
// (passes to p.reuse) any removed *Regexps.
//
// For example,
// ABC|ABD|AEF|BCX|BCY
// simplifies by literal prefix extraction to
// A(B(C|D)|EF)|BC(X|Y)
// which simplifies by character class introduction to
// A(B[CD]|EF)|BC[XY]
//
private Regexp[] factor(Regexp[] array, int flags) {
if (array.length < 2) {
return array;
}
// The following code is subtle, because it's a literal Java
// translation of code that makes clever use of Go "slices".
// A slice is a triple (array, offset, length), and the Go
// implementation uses two slices, |sub| and |out| backed by the
// same array. In Java, we have to be explicit about all of these
// variables, so:
//
// Go Java
// sub (array, s, lensub)
// out (array, 0, lenout) // (always a prefix of |array|)
//
// In the comments we'll use the logical notation of go slices, e.g. sub[i]
// even though the Java code will read array[s + i].
int s = 0; // offset of first |sub| within array.
int lensub = array.length; // = len(sub)
int lenout = 0; // = len(out)
// Round 1: Factor out common literal prefixes.
// Note: (str, strlen) and (istr, istrlen) are like Go slices
// onto a prefix of some Regexp's runes array (hence offset=0).
int[] str = null;
int strlen = 0;
int strflags = 0;
int start = 0;
for (int i = 0; i <= lensub; i++) {
// Invariant: the Regexps that were in sub[0:start] have been
// used or marked for reuse, and the slice space has been reused
// for out (len <= start).
//
// Invariant: sub[start:i] consists of regexps that all begin
// with str as modified by strflags.
int[] istr = null;
int istrlen = 0;
int iflags = 0;
if (i < lensub) {
// NB, we inlined Go's leadingString() since Java has no pair return.
Regexp re = array[s + i];
if (re.op == Regexp.Op.CONCAT && re.subs.length > 0) {
re = re.subs[0];
}
if (re.op == Regexp.Op.LITERAL) {
istr = re.runes;
istrlen = re.runes.length;
iflags = re.flags & RE2.FOLD_CASE;
}
// istr is the leading literal string that re begins with.
// The string refers to storage in re or its children.
if (iflags == strflags) {
int same = 0;
while (same < strlen && same < istrlen && str[same] == istr[same]) {
same++;
}
if (same > 0) {
// Matches at least one rune in current range.
// Keep going around.
strlen = same;
continue;
}
}
}
// Found end of a run with common leading literal string:
// sub[start:i] all begin with str[0:strlen], but sub[i]
// does not even begin with str[0].
//
// Factor out common string and append factored expression to out.
if (i == start) {
// Nothing to do - run of length 0.
} else if (i == start + 1) {
// Just one: don't bother factoring.
array[lenout++] = array[s + start];
} else {
// Construct factored form: prefix(suffix1|suffix2|...)
Regexp prefix = newRegexp(Regexp.Op.LITERAL);
prefix.flags = strflags;
prefix.runes = Utils.subarray(str, 0, strlen);
for (int j = start; j < i; j++) {
array[s + j] = removeLeadingString(array[s + j], strlen);
}
// Recurse.
Regexp suffix = collapse(subarray(array, s + start, s + i), Regexp.Op.ALTERNATE);
Regexp re = newRegexp(Regexp.Op.CONCAT);
re.subs = new Regexp[] {prefix, suffix};
array[lenout++] = re;
}
// Prepare for next iteration.
start = i;
str = istr;
strlen = istrlen;
strflags = iflags;
}
// In Go: sub = out
lensub = lenout;
s = 0;
// Round 2: Factor out common complex prefixes,
// just the first piece of each concatenation,
// whatever it is. This is good enough a lot of the time.
start = 0;
lenout = 0;
Regexp first = null;
for (int i = 0; i <= lensub; i++) {
// Invariant: the Regexps that were in sub[0:start] have been
// used or marked for reuse, and the slice space has been reused
// for out (lenout <= start).
//
// Invariant: sub[start:i] consists of regexps that all begin with
// ifirst.
Regexp ifirst = null;
if (i < lensub) {
ifirst = leadingRegexp(array[s + i]);
if (first != null
&& first.equals(ifirst)
&& (isCharClass(first)
|| (first.op == Regexp.Op.REPEAT
&& first.min == first.max
&& isCharClass(first.subs[0])))) {
continue;
}
}
// Found end of a run with common leading regexp:
// sub[start:i] all begin with first but sub[i] does not.
//
// Factor out common regexp and append factored expression to out.
if (i == start) {
// Nothing to do - run of length 0.
} else if (i == start + 1) {
// Just one: don't bother factoring.
array[lenout++] = array[s + start];
} else {
// Construct factored form: prefix(suffix1|suffix2|...)
Regexp prefix = first;
for (int j = start; j < i; j++) {
boolean reuse = j != start; // prefix came from sub[start]
array[s + j] = removeLeadingRegexp(array[s + j], reuse);
}
// recurse
Regexp suffix = collapse(subarray(array, s + start, s + i), Regexp.Op.ALTERNATE);
Regexp re = newRegexp(Regexp.Op.CONCAT);
re.subs = new Regexp[] {prefix, suffix};
array[lenout++] = re;
}
// Prepare for next iteration.
start = i;
first = ifirst;
}
// In Go: sub = out
lensub = lenout;
s = 0;
// Round 3: Collapse runs of single literals into character classes.
start = 0;
lenout = 0;
for (int i = 0; i <= lensub; i++) {
// Invariant: the Regexps that were in sub[0:start] have been
// used or marked for reuse, and the slice space has been reused
// for out (lenout <= start).
//
// Invariant: sub[start:i] consists of regexps that are either
// literal runes or character classes.
if (i < lensub && isCharClass(array[s + i])) {
continue;
}
// sub[i] is not a char or char class;
// emit char class for sub[start:i]...
if (i == start) {
// Nothing to do - run of length 0.
} else if (i == start + 1) {
array[lenout++] = array[s + start];
} else {
// Make new char class.
// Start with most complex regexp in sub[start].
int max = start;
for (int j = start + 1; j < i; j++) {
Regexp subMax = array[s + max], subJ = array[s + j];
if (subMax.op.ordinal() < subJ.op.ordinal()
|| (subMax.op == subJ.op
&& (subMax.runes != null ? subMax.runes.length : 0)
< (subJ.runes != null ? subJ.runes.length : 0))) {
max = j;
}
}
// swap sub[start], sub[max].
Regexp tmp = array[s + start];
array[s + start] = array[s + max];
array[s + max] = tmp;
for (int j = start + 1; j < i; j++) {
mergeCharClass(array[s + start], array[s + j]);
reuse(array[s + j]);
}
cleanAlt(array[s + start]);
array[lenout++] = array[s + start];
}
// ... and then emit sub[i].
if (i < lensub) {
array[lenout++] = array[s + i];
}
start = i + 1;
}
// In Go: sub = out
lensub = lenout;
s = 0;
// Round 4: Collapse runs of empty matches into a single empty match.
start = 0;
lenout = 0;
for (int i = 0; i < lensub; ++i) {
if (i + 1 < lensub
&& array[s + i].op == Regexp.Op.EMPTY_MATCH
&& array[s + i + 1].op == Regexp.Op.EMPTY_MATCH) {
continue;
}
array[lenout++] = array[s + i];
}
// In Go: sub = out
lensub = lenout;
s = 0;
return subarray(array, s, lensub);
}
// removeLeadingString removes the first n leading runes
// from the beginning of re. It returns the replacement for re.
private Regexp removeLeadingString(Regexp re, int n) {
if (re.op == Regexp.Op.CONCAT && re.subs.length > 0) {
// Removing a leading string in a concatenation
// might simplify the concatenation.
Regexp sub = removeLeadingString(re.subs[0], n);
re.subs[0] = sub;
if (sub.op == Regexp.Op.EMPTY_MATCH) {
reuse(sub);
switch (re.subs.length) {
case 0:
case 1:
// Impossible but handle.
re.op = Regexp.Op.EMPTY_MATCH;
re.subs = null;
break;
case 2:
{
Regexp old = re;
re = re.subs[1];
reuse(old);
break;
}
default:
re.subs = subarray(re.subs, 1, re.subs.length);
break;
}
}
return re;
}
if (re.op == Regexp.Op.LITERAL) {
re.runes = Utils.subarray(re.runes, n, re.runes.length);
if (re.runes.length == 0) {
re.op = Regexp.Op.EMPTY_MATCH;
}
}
return re;
}
// leadingRegexp returns the leading regexp that re begins with.
// The regexp refers to storage in re or its children.
private static Regexp leadingRegexp(Regexp re) {
if (re.op == Regexp.Op.EMPTY_MATCH) {
return null;
}
if (re.op == Regexp.Op.CONCAT && re.subs.length > 0) {
Regexp sub = re.subs[0];
if (sub.op == Regexp.Op.EMPTY_MATCH) {
return null;
}
return sub;
}
return re;
}
// removeLeadingRegexp removes the leading regexp in re.
// It returns the replacement for re.
// If reuse is true, it passes the removed regexp (if no longer needed) to
// reuse.
private Regexp removeLeadingRegexp(Regexp re, boolean reuse) {
if (re.op == Regexp.Op.CONCAT && re.subs.length > 0) {
if (reuse) {
reuse(re.subs[0]);
}
re.subs = subarray(re.subs, 1, re.subs.length);
switch (re.subs.length) {
case 0:
re.op = Regexp.Op.EMPTY_MATCH;
re.subs = Regexp.EMPTY_SUBS;
break;
case 1:
Regexp old = re;
re = re.subs[0];
reuse(old);
break;
}
return re;
}
if (reuse) {
reuse(re);
}
return newRegexp(Regexp.Op.EMPTY_MATCH);
}
private static Regexp literalRegexp(String s, int flags) {
Regexp re = new Regexp(Regexp.Op.LITERAL);
re.flags = flags;
re.runes = Utils.stringToRunes(s);
return re;
}
// Parsing.
// StringIterator: a stream of runes with an opaque cursor, permitting
// rewinding. The units of the cursor are not specified beyond the
// fact that ASCII characters are single width. (Cursor positions
// could be UTF-8 byte indices, UTF-16 code indices or rune indices.)
//
// In particular, be careful with:
// - skip(int): only use this to advance over ASCII characters
// since these always have a width of 1.
// - skip(String): only use this to advance over strings which are
// known to be at the current position, e.g. due to prior call to
// lookingAt().
// Only use pop() to advance over possibly non-ASCII runes.
private static class StringIterator {
private final String str; // a stream of UTF-16 codes
private int pos = 0; // current position in UTF-16 string
StringIterator(String str) {
this.str = str;
}
// Returns the cursor position. Do not interpret the result!
int pos() {
return pos;
}
// Resets the cursor position to a previous value returned by pos().
void rewindTo(int pos) {
this.pos = pos;
}
// Returns true unless the stream is exhausted.
boolean more() {
return pos < str.length();
}
// Returns the rune at the cursor position.
// Precondition: |more()|.
int peek() {
return str.codePointAt(pos);
}
// Advances the cursor by |n| positions, which must be ASCII runes.
//
// (In practise, this is only ever used to skip over regexp
// metacharacters that are ASCII, so there is no numeric difference
// between indices into UTF-8 bytes, UTF-16 codes and runes.)
void skip(int n) {
pos += n;
}
// Advances the cursor by the number of cursor positions in |s|.
void skipString(String s) {
pos += s.length();
}
// Returns the rune at the cursor position, and advances the cursor
// past it. Precondition: |more()|.
int pop() {
int r = str.codePointAt(pos);
pos += Character.charCount(r);
return r;
}
// Equivalent to both peek() == c but more efficient because we
// don't support surrogates. Precondition: |more()|.
boolean lookingAt(char c) {
return str.charAt(pos) == c;
}
// Equivalent to rest().startsWith(s).
boolean lookingAt(String s) {
return rest().startsWith(s);
}
// Returns the rest of the pattern as a Java UTF-16 string.
String rest() {
return str.substring(pos);
}
// Returns the substring from |beforePos| to the current position.
// |beforePos| must have been previously returned by |pos()|.
String from(int beforePos) {
return str.substring(beforePos, pos);
}
@Override
public String toString() {
return rest();
}
}
/**
* Parse regular expression pattern {@code pattern} with mode flags {@code flags}.
*/
static Regexp parse(String pattern, int flags) throws PatternSyntaxException {
return new Parser(pattern, flags).parseInternal();
}
private Regexp parseInternal() throws PatternSyntaxException {
if ((flags & RE2.LITERAL) != 0) {
// Trivial parser for literal string.
return literalRegexp(wholeRegexp, flags);
}
// Otherwise, must do real work.
int lastRepeatPos = -1, min = -1, max = -1;
StringIterator t = new StringIterator(wholeRegexp);
while (t.more()) {
int repeatPos = -1;
bigswitch:
switch (t.peek()) {
default:
literal(t.pop());
break;
case '(':
if ((flags & RE2.PERL_X) != 0 && t.lookingAt("(?")) {
// Flag changes and non-capturing groups.
parsePerlFlags(t);
break;
}
op(Regexp.Op.LEFT_PAREN).cap = ++numCap;
t.skip(1); // '('
break;
case '|':
parseVerticalBar();
t.skip(1); // '|'
break;
case ')':
parseRightParen();
t.skip(1); // ')'
break;
case '^':
if ((flags & RE2.ONE_LINE) != 0) {
op(Regexp.Op.BEGIN_TEXT);
} else {
op(Regexp.Op.BEGIN_LINE);
}
t.skip(1); // '^'
break;
case '$':
if ((flags & RE2.ONE_LINE) != 0) {
op(Regexp.Op.END_TEXT).flags |= RE2.WAS_DOLLAR;
} else {
op(Regexp.Op.END_LINE);
}
t.skip(1); // '$'
break;
case '.':
if ((flags & RE2.DOT_NL) != 0) {
op(Regexp.Op.ANY_CHAR);
} else {
op(Regexp.Op.ANY_CHAR_NOT_NL);
}
t.skip(1); // '.'
break;
case '[':
parseClass(t);
break;
case '*':
case '+':
case '?':
{
repeatPos = t.pos();
Regexp.Op op = null;
switch (t.pop()) {
case '*':
op = Regexp.Op.STAR;
break;
case '+':
op = Regexp.Op.PLUS;
break;
case '?':
op = Regexp.Op.QUEST;
break;
}
repeat(op, min, max, repeatPos, t, lastRepeatPos);
// (min and max are now dead.)
break;
}
case '{':
{
repeatPos = t.pos();
int minMax = parseRepeat(t);
if (minMax < 0) {
// If the repeat cannot be parsed, { is a literal.
t.rewindTo(repeatPos);
literal(t.pop()); // '{'
break;
}
min = minMax >> 16;
max = (short) (minMax & 0xffff); // sign extend
repeat(Regexp.Op.REPEAT, min, max, repeatPos, t, lastRepeatPos);
break;
}
case '\\':
{
int savedPos = t.pos();
t.skip(1); // '\\'
if ((flags & RE2.PERL_X) != 0 && t.more()) {
int c = t.pop();
switch (c) {
case 'A':
op(Regexp.Op.BEGIN_TEXT);
break bigswitch;
case 'b':
op(Regexp.Op.WORD_BOUNDARY);
break bigswitch;
case 'B':
op(Regexp.Op.NO_WORD_BOUNDARY);
break bigswitch;
case 'C':
// any byte; not supported
throw new PatternSyntaxException(ERR_INVALID_ESCAPE, "\\C");
case 'Q':
{
// \Q ... \E: the ... is always literals
String lit = t.rest();
int i = lit.indexOf("\\E");
if (i >= 0) {
lit = lit.substring(0, i);
}
t.skipString(lit);
t.skipString("\\E");
for (int j = 0; j < lit.length(); ) {
int codepoint = lit.codePointAt(j);
literal(codepoint);
j += Character.charCount(codepoint);
}
break bigswitch;
}
case 'z':
op(Regexp.Op.END_TEXT);
break bigswitch;
default:
t.rewindTo(savedPos);
break;
}
}
Regexp re = newRegexp(Regexp.Op.CHAR_CLASS);
re.flags = flags;
// Look for Unicode character group like \p{Han}
if (t.lookingAt("\\p") || t.lookingAt("\\P")) {
CharClass cc = new CharClass();
if (parseUnicodeClass(t, cc)) {
re.runes = cc.toArray();
push(re);
break bigswitch;
}
}
// Perl character class escape.
CharClass cc = new CharClass();
if (parsePerlClassEscape(t, cc)) {
re.runes = cc.toArray();
push(re);
break bigswitch;
}
t.rewindTo(savedPos);
reuse(re);
// Ordinary single-character escape.
literal(parseEscape(t));
break;
}
}
lastRepeatPos = repeatPos;
}
concat();
if (swapVerticalBar()) {
pop(); // pop vertical bar
}
alternate();
int n = stack.size();
if (n != 1) {
throw new PatternSyntaxException(ERR_MISSING_PAREN, wholeRegexp);
}
stack.get(0).namedGroups = namedGroups;
return stack.get(0);
}
// parseRepeat parses {min} (max=min) or {min,} (max=-1) or {min,max}.
// If |t| is not of that form, it returns -1.
// If |t| has the right form but the values are negative or too big,
// it returns -2.
// On success, returns a nonnegative number encoding min/max in the
// high/low signed halfwords of the result. (Note: min >= 0; max may
// be -1.)
//
// On success, advances |t| beyond the repeat; otherwise |t.pos()| is
// undefined.
private static int parseRepeat(StringIterator t) throws PatternSyntaxException {
int start = t.pos();
if (!t.more() || !t.lookingAt('{')) {