1 // Copyright 2006 The RE2 Authors. All Rights Reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Regular expression parser.
6
7 // The parser is a simple precedence-based parser with a
8 // manual stack. The parsing work is done by the methods
9 // of the ParseState class. The Regexp::Parse function is
10 // essentially just a lexer that calls the ParseState method
11 // for each token.
12
13 // The parser recognizes POSIX extended regular expressions
14 // excluding backreferences, collating elements, and collating
15 // classes. It also allows the empty string as a regular expression
16 // and recognizes the Perl escape sequences \d, \s, \w, \D, \S, and \W.
17 // See regexp.h for rationale.
18
19 #include <stddef.h>
20 #include <stdint.h>
21 #include <string.h>
22
23 #include <algorithm>
24 #include <string>
25 #include <vector>
26
27 #include "absl/base/attributes.h"
28 #include "absl/base/macros.h"
29 #include "absl/log/absl_log.h"
30 #include "absl/strings/ascii.h"
31 #include "absl/strings/string_view.h"
32 #include "re2/pod_array.h"
33 #include "re2/regexp.h"
34 #include "re2/unicode_casefold.h"
35 #include "re2/unicode_groups.h"
36 #include "re2/walker-inl.h"
37 #include "util/utf.h"
38
39 #if defined(RE2_USE_ICU)
40 #include "unicode/uniset.h"
41 #include "unicode/unistr.h"
42 #include "unicode/utypes.h"
43 #endif
44
45 namespace re2 {
46
47 // Controls the maximum repeat count permitted by the parser.
48 static int maximum_repeat_count = 1000;
49
FUZZING_ONLY_set_maximum_repeat_count(int i)50 void Regexp::FUZZING_ONLY_set_maximum_repeat_count(int i) {
51 maximum_repeat_count = i;
52 }
53
54 // Regular expression parse state.
55 // The list of parsed regexps so far is maintained as a vector of
56 // Regexp pointers called the stack. Left parenthesis and vertical
57 // bar markers are also placed on the stack, as Regexps with
58 // non-standard opcodes.
59 // Scanning a left parenthesis causes the parser to push a left parenthesis
60 // marker on the stack.
61 // Scanning a vertical bar causes the parser to pop the stack until it finds a
62 // vertical bar or left parenthesis marker (not popping the marker),
63 // concatenate all the popped results, and push them back on
64 // the stack (DoConcatenation).
65 // Scanning a right parenthesis causes the parser to act as though it
66 // has seen a vertical bar, which then leaves the top of the stack in the
67 // form LeftParen regexp VerticalBar regexp VerticalBar ... regexp VerticalBar.
68 // The parser pops all this off the stack and creates an alternation of the
69 // regexps (DoAlternation).
70
71 class Regexp::ParseState {
72 public:
73 ParseState(ParseFlags flags, absl::string_view whole_regexp,
74 RegexpStatus* status);
75 ~ParseState();
76
flags()77 ParseFlags flags() { return flags_; }
rune_max()78 int rune_max() { return rune_max_; }
79
80 // Parse methods. All public methods return a bool saying
81 // whether parsing should continue. If a method returns
82 // false, it has set fields in *status_, and the parser
83 // should return NULL.
84
85 // Pushes the given regular expression onto the stack.
86 // Could check for too much memory used here.
87 bool PushRegexp(Regexp* re);
88
89 // Pushes the literal rune r onto the stack.
90 bool PushLiteral(Rune r);
91
92 // Pushes a regexp with the given op (and no args) onto the stack.
93 bool PushSimpleOp(RegexpOp op);
94
95 // Pushes a ^ onto the stack.
96 bool PushCaret();
97
98 // Pushes a \b (word == true) or \B (word == false) onto the stack.
99 bool PushWordBoundary(bool word);
100
101 // Pushes a $ onto the stack.
102 bool PushDollar();
103
104 // Pushes a . onto the stack
105 bool PushDot();
106
107 // Pushes a repeat operator regexp onto the stack.
108 // A valid argument for the operator must already be on the stack.
109 // s is the name of the operator, for use in error messages.
110 bool PushRepeatOp(RegexpOp op, absl::string_view s, bool nongreedy);
111
112 // Pushes a repetition regexp onto the stack.
113 // A valid argument for the operator must already be on the stack.
114 bool PushRepetition(int min, int max, absl::string_view s, bool nongreedy);
115
116 // Checks whether a particular regexp op is a marker.
117 bool IsMarker(RegexpOp op);
118
119 // Processes a left parenthesis in the input.
120 // Pushes a marker onto the stack.
121 bool DoLeftParen(absl::string_view name);
122 bool DoLeftParenNoCapture();
123
124 // Processes a vertical bar in the input.
125 bool DoVerticalBar();
126
127 // Processes a right parenthesis in the input.
128 bool DoRightParen();
129
130 // Processes the end of input, returning the final regexp.
131 Regexp* DoFinish();
132
133 // Finishes the regexp if necessary, preparing it for use
134 // in a more complicated expression.
135 // If it is a CharClassBuilder, converts into a CharClass.
136 Regexp* FinishRegexp(Regexp*);
137
138 // These routines don't manipulate the parse stack
139 // directly, but they do need to look at flags_.
140 // ParseCharClass also manipulates the internals of Regexp
141 // while creating *out_re.
142
143 // Parse a character class into *out_re.
144 // Removes parsed text from s.
145 bool ParseCharClass(absl::string_view* s, Regexp** out_re,
146 RegexpStatus* status);
147
148 // Parse a character class character into *rp.
149 // Removes parsed text from s.
150 bool ParseCCCharacter(absl::string_view* s, Rune* rp,
151 absl::string_view whole_class,
152 RegexpStatus* status);
153
154 // Parse a character class range into rr.
155 // Removes parsed text from s.
156 bool ParseCCRange(absl::string_view* s, RuneRange* rr,
157 absl::string_view whole_class,
158 RegexpStatus* status);
159
160 // Parse a Perl flag set or non-capturing group from s.
161 bool ParsePerlFlags(absl::string_view* s);
162
163 // Finishes the current concatenation,
164 // collapsing it into a single regexp on the stack.
165 void DoConcatenation();
166
167 // Finishes the current alternation,
168 // collapsing it to a single regexp on the stack.
169 void DoAlternation();
170
171 // Generalized DoAlternation/DoConcatenation.
172 void DoCollapse(RegexpOp op);
173
174 // Maybe concatenate Literals into LiteralString.
175 bool MaybeConcatString(int r, ParseFlags flags);
176
177 private:
178 ParseFlags flags_;
179 absl::string_view whole_regexp_;
180 RegexpStatus* status_;
181 Regexp* stacktop_;
182 int ncap_; // number of capturing parens seen
183 int rune_max_; // maximum char value for this encoding
184
185 ParseState(const ParseState&) = delete;
186 ParseState& operator=(const ParseState&) = delete;
187 };
188
189 // Pseudo-operators - only on parse stack.
190 const RegexpOp kLeftParen = static_cast<RegexpOp>(kMaxRegexpOp+1);
191 const RegexpOp kVerticalBar = static_cast<RegexpOp>(kMaxRegexpOp+2);
192
ParseState(ParseFlags flags,absl::string_view whole_regexp,RegexpStatus * status)193 Regexp::ParseState::ParseState(ParseFlags flags,
194 absl::string_view whole_regexp,
195 RegexpStatus* status)
196 : flags_(flags), whole_regexp_(whole_regexp),
197 status_(status), stacktop_(NULL), ncap_(0) {
198 if (flags_ & Latin1)
199 rune_max_ = 0xFF;
200 else
201 rune_max_ = Runemax;
202 }
203
204 // Cleans up by freeing all the regexps on the stack.
~ParseState()205 Regexp::ParseState::~ParseState() {
206 Regexp* next;
207 for (Regexp* re = stacktop_; re != NULL; re = next) {
208 next = re->down_;
209 re->down_ = NULL;
210 if (re->op() == kLeftParen)
211 delete re->name_;
212 re->Decref();
213 }
214 }
215
216 // Finishes the regexp if necessary, preparing it for use in
217 // a more complex expression.
218 // If it is a CharClassBuilder, converts into a CharClass.
FinishRegexp(Regexp * re)219 Regexp* Regexp::ParseState::FinishRegexp(Regexp* re) {
220 if (re == NULL)
221 return NULL;
222 re->down_ = NULL;
223
224 if (re->op_ == kRegexpCharClass && re->ccb_ != NULL) {
225 CharClassBuilder* ccb = re->ccb_;
226 re->ccb_ = NULL;
227 re->cc_ = ccb->GetCharClass();
228 delete ccb;
229 }
230
231 return re;
232 }
233
234 // Pushes the given regular expression onto the stack.
235 // Could check for too much memory used here.
PushRegexp(Regexp * re)236 bool Regexp::ParseState::PushRegexp(Regexp* re) {
237 MaybeConcatString(-1, NoParseFlags);
238
239 // Special case: a character class of one character is just
240 // a literal. This is a common idiom for escaping
241 // single characters (e.g., [.] instead of \.), and some
242 // analysis does better with fewer character classes.
243 // Similarly, [Aa] can be rewritten as a literal A with ASCII case folding.
244 if (re->op_ == kRegexpCharClass && re->ccb_ != NULL) {
245 re->ccb_->RemoveAbove(rune_max_);
246 if (re->ccb_->size() == 1) {
247 Rune r = re->ccb_->begin()->lo;
248 re->Decref();
249 re = new Regexp(kRegexpLiteral, flags_);
250 re->rune_ = r;
251 } else if (re->ccb_->size() == 2) {
252 Rune r = re->ccb_->begin()->lo;
253 if ('A' <= r && r <= 'Z' && re->ccb_->Contains(r + 'a' - 'A')) {
254 re->Decref();
255 re = new Regexp(kRegexpLiteral, flags_ | FoldCase);
256 re->rune_ = r + 'a' - 'A';
257 }
258 }
259 }
260
261 if (!IsMarker(re->op()))
262 re->simple_ = re->ComputeSimple();
263 re->down_ = stacktop_;
264 stacktop_ = re;
265 return true;
266 }
267
268 // Searches the case folding tables and returns the CaseFold* that contains r.
269 // If there isn't one, returns the CaseFold* with smallest f->lo bigger than r.
270 // If there isn't one, returns NULL.
LookupCaseFold(const CaseFold * f,int n,Rune r)271 const CaseFold* LookupCaseFold(const CaseFold* f, int n, Rune r) {
272 const CaseFold* ef = f + n;
273
274 // Binary search for entry containing r.
275 while (n > 0) {
276 int m = n/2;
277 if (f[m].lo <= r && r <= f[m].hi)
278 return &f[m];
279 if (r < f[m].lo) {
280 n = m;
281 } else {
282 f += m+1;
283 n -= m+1;
284 }
285 }
286
287 // There is no entry that contains r, but f points
288 // where it would have been. Unless f points at
289 // the end of the array, it points at the next entry
290 // after r.
291 if (f < ef)
292 return f;
293
294 // No entry contains r; no entry contains runes > r.
295 return NULL;
296 }
297
298 // Returns the result of applying the fold f to the rune r.
ApplyFold(const CaseFold * f,Rune r)299 Rune ApplyFold(const CaseFold* f, Rune r) {
300 switch (f->delta) {
301 default:
302 return r + f->delta;
303
304 case EvenOddSkip: // even <-> odd but only applies to every other
305 if ((r - f->lo) % 2)
306 return r;
307 ABSL_FALLTHROUGH_INTENDED;
308 case EvenOdd: // even <-> odd
309 if (r%2 == 0)
310 return r + 1;
311 return r - 1;
312
313 case OddEvenSkip: // odd <-> even but only applies to every other
314 if ((r - f->lo) % 2)
315 return r;
316 ABSL_FALLTHROUGH_INTENDED;
317 case OddEven: // odd <-> even
318 if (r%2 == 1)
319 return r + 1;
320 return r - 1;
321 }
322 }
323
324 // Returns the next Rune in r's folding cycle (see unicode_casefold.h).
325 // Examples:
326 // CycleFoldRune('A') = 'a'
327 // CycleFoldRune('a') = 'A'
328 //
329 // CycleFoldRune('K') = 'k'
330 // CycleFoldRune('k') = 0x212A (Kelvin)
331 // CycleFoldRune(0x212A) = 'K'
332 //
333 // CycleFoldRune('?') = '?'
CycleFoldRune(Rune r)334 Rune CycleFoldRune(Rune r) {
335 const CaseFold* f = LookupCaseFold(unicode_casefold, num_unicode_casefold, r);
336 if (f == NULL || r < f->lo)
337 return r;
338 return ApplyFold(f, r);
339 }
340
341 // Add lo-hi to the class, along with their fold-equivalent characters.
AddFoldedRangeLatin1(CharClassBuilder * cc,Rune lo,Rune hi)342 static void AddFoldedRangeLatin1(CharClassBuilder* cc, Rune lo, Rune hi) {
343 while (lo <= hi) {
344 cc->AddRange(lo, lo);
345 if ('A' <= lo && lo <= 'Z') {
346 cc->AddRange(lo - 'A' + 'a', lo - 'A' + 'a');
347 }
348 if ('a' <= lo && lo <= 'z') {
349 cc->AddRange(lo - 'a' + 'A', lo - 'a' + 'A');
350 }
351 lo++;
352 }
353 }
354
355 // Add lo-hi to the class, along with their fold-equivalent characters.
356 // If lo-hi is already in the class, assume that the fold-equivalent
357 // chars are there too, so there's no work to do.
AddFoldedRange(CharClassBuilder * cc,Rune lo,Rune hi,int depth)358 static void AddFoldedRange(CharClassBuilder* cc, Rune lo, Rune hi, int depth) {
359 // AddFoldedRange calls itself recursively for each rune in the fold cycle.
360 // Most folding cycles are small: there aren't any bigger than four in the
361 // current Unicode tables. make_unicode_casefold.py checks that
362 // the cycles are not too long, and we double-check here using depth.
363 if (depth > 10) {
364 ABSL_LOG(DFATAL) << "AddFoldedRange recurses too much.";
365 return;
366 }
367
368 if (!cc->AddRange(lo, hi)) // lo-hi was already there? we're done
369 return;
370
371 while (lo <= hi) {
372 const CaseFold* f = LookupCaseFold(unicode_casefold, num_unicode_casefold, lo);
373 if (f == NULL) // lo has no fold, nor does anything above lo
374 break;
375 if (lo < f->lo) { // lo has no fold; next rune with a fold is f->lo
376 lo = f->lo;
377 continue;
378 }
379
380 // Add in the result of folding the range lo - f->hi
381 // and that range's fold, recursively.
382 Rune lo1 = lo;
383 Rune hi1 = std::min<Rune>(hi, f->hi);
384 switch (f->delta) {
385 default:
386 lo1 += f->delta;
387 hi1 += f->delta;
388 break;
389 case EvenOdd:
390 if (lo1%2 == 1)
391 lo1--;
392 if (hi1%2 == 0)
393 hi1++;
394 break;
395 case OddEven:
396 if (lo1%2 == 0)
397 lo1--;
398 if (hi1%2 == 1)
399 hi1++;
400 break;
401 }
402 AddFoldedRange(cc, lo1, hi1, depth+1);
403
404 // Pick up where this fold left off.
405 lo = f->hi + 1;
406 }
407 }
408
409 // Pushes the literal rune r onto the stack.
PushLiteral(Rune r)410 bool Regexp::ParseState::PushLiteral(Rune r) {
411 // Do case folding if needed.
412 if (flags_ & FoldCase) {
413 if (flags_ & Latin1 && (('A' <= r && r <= 'Z') ||
414 ('a' <= r && r <= 'z'))) {
415 Regexp* re = new Regexp(kRegexpCharClass, flags_ & ~FoldCase);
416 re->ccb_ = new CharClassBuilder;
417 AddFoldedRangeLatin1(re->ccb_, r, r);
418 return PushRegexp(re);
419 }
420 if (!(flags_ & Latin1) && CycleFoldRune(r) != r) {
421 Regexp* re = new Regexp(kRegexpCharClass, flags_ & ~FoldCase);
422 re->ccb_ = new CharClassBuilder;
423 Rune r1 = r;
424 do {
425 if (!(flags_ & NeverNL) || r != '\n') {
426 re->ccb_->AddRange(r, r);
427 }
428 r = CycleFoldRune(r);
429 } while (r != r1);
430 return PushRegexp(re);
431 }
432 }
433
434 // Exclude newline if applicable.
435 if ((flags_ & NeverNL) && r == '\n')
436 return PushRegexp(new Regexp(kRegexpNoMatch, flags_));
437
438 // No fancy stuff worked. Ordinary literal.
439 if (MaybeConcatString(r, flags_))
440 return true;
441
442 Regexp* re = new Regexp(kRegexpLiteral, flags_);
443 re->rune_ = r;
444 return PushRegexp(re);
445 }
446
447 // Pushes a ^ onto the stack.
PushCaret()448 bool Regexp::ParseState::PushCaret() {
449 if (flags_ & OneLine) {
450 return PushSimpleOp(kRegexpBeginText);
451 }
452 return PushSimpleOp(kRegexpBeginLine);
453 }
454
455 // Pushes a \b or \B onto the stack.
PushWordBoundary(bool word)456 bool Regexp::ParseState::PushWordBoundary(bool word) {
457 if (word)
458 return PushSimpleOp(kRegexpWordBoundary);
459 return PushSimpleOp(kRegexpNoWordBoundary);
460 }
461
462 // Pushes a $ onto the stack.
PushDollar()463 bool Regexp::ParseState::PushDollar() {
464 if (flags_ & OneLine) {
465 // Clumsy marker so that MimicsPCRE() can tell whether
466 // this kRegexpEndText was a $ and not a \z.
467 Regexp::ParseFlags oflags = flags_;
468 flags_ = flags_ | WasDollar;
469 bool ret = PushSimpleOp(kRegexpEndText);
470 flags_ = oflags;
471 return ret;
472 }
473 return PushSimpleOp(kRegexpEndLine);
474 }
475
476 // Pushes a . onto the stack.
PushDot()477 bool Regexp::ParseState::PushDot() {
478 if ((flags_ & DotNL) && !(flags_ & NeverNL))
479 return PushSimpleOp(kRegexpAnyChar);
480 // Rewrite . into [^\n]
481 Regexp* re = new Regexp(kRegexpCharClass, flags_ & ~FoldCase);
482 re->ccb_ = new CharClassBuilder;
483 re->ccb_->AddRange(0, '\n' - 1);
484 re->ccb_->AddRange('\n' + 1, rune_max_);
485 return PushRegexp(re);
486 }
487
488 // Pushes a regexp with the given op (and no args) onto the stack.
PushSimpleOp(RegexpOp op)489 bool Regexp::ParseState::PushSimpleOp(RegexpOp op) {
490 Regexp* re = new Regexp(op, flags_);
491 return PushRegexp(re);
492 }
493
494 // Pushes a repeat operator regexp onto the stack.
495 // A valid argument for the operator must already be on the stack.
496 // The char c is the name of the operator, for use in error messages.
PushRepeatOp(RegexpOp op,absl::string_view s,bool nongreedy)497 bool Regexp::ParseState::PushRepeatOp(RegexpOp op, absl::string_view s,
498 bool nongreedy) {
499 if (stacktop_ == NULL || IsMarker(stacktop_->op())) {
500 status_->set_code(kRegexpRepeatArgument);
501 status_->set_error_arg(s);
502 return false;
503 }
504 Regexp::ParseFlags fl = flags_;
505 if (nongreedy)
506 fl = fl ^ NonGreedy;
507
508 // Squash **, ++ and ??. Regexp::Star() et al. handle this too, but
509 // they're mostly for use during simplification, not during parsing.
510 if (op == stacktop_->op() && fl == stacktop_->parse_flags())
511 return true;
512
513 // Squash *+, *?, +*, +?, ?* and ?+. They all squash to *, so because
514 // op is a repeat, we just have to check that stacktop_->op() is too,
515 // then adjust stacktop_.
516 if ((stacktop_->op() == kRegexpStar ||
517 stacktop_->op() == kRegexpPlus ||
518 stacktop_->op() == kRegexpQuest) &&
519 fl == stacktop_->parse_flags()) {
520 stacktop_->op_ = kRegexpStar;
521 return true;
522 }
523
524 Regexp* re = new Regexp(op, fl);
525 re->AllocSub(1);
526 re->down_ = stacktop_->down_;
527 re->sub()[0] = FinishRegexp(stacktop_);
528 re->simple_ = re->ComputeSimple();
529 stacktop_ = re;
530 return true;
531 }
532
533 // RepetitionWalker reports whether the repetition regexp is valid.
534 // Valid means that the combination of the top-level repetition
535 // and any inner repetitions does not exceed n copies of the
536 // innermost thing.
537 // This rewalks the regexp tree and is called for every repetition,
538 // so we have to worry about inducing quadratic behavior in the parser.
539 // We avoid this by only using RepetitionWalker when min or max >= 2.
540 // In that case the depth of any >= 2 nesting can only get to 9 without
541 // triggering a parse error, so each subtree can only be rewalked 9 times.
542 class RepetitionWalker : public Regexp::Walker<int> {
543 public:
RepetitionWalker()544 RepetitionWalker() {}
545 virtual int PreVisit(Regexp* re, int parent_arg, bool* stop);
546 virtual int PostVisit(Regexp* re, int parent_arg, int pre_arg,
547 int* child_args, int nchild_args);
548 virtual int ShortVisit(Regexp* re, int parent_arg);
549
550 private:
551 RepetitionWalker(const RepetitionWalker&) = delete;
552 RepetitionWalker& operator=(const RepetitionWalker&) = delete;
553 };
554
PreVisit(Regexp * re,int parent_arg,bool * stop)555 int RepetitionWalker::PreVisit(Regexp* re, int parent_arg, bool* stop) {
556 int arg = parent_arg;
557 if (re->op() == kRegexpRepeat) {
558 int m = re->max();
559 if (m < 0) {
560 m = re->min();
561 }
562 if (m > 0) {
563 arg /= m;
564 }
565 }
566 return arg;
567 }
568
PostVisit(Regexp * re,int parent_arg,int pre_arg,int * child_args,int nchild_args)569 int RepetitionWalker::PostVisit(Regexp* re, int parent_arg, int pre_arg,
570 int* child_args, int nchild_args) {
571 int arg = pre_arg;
572 for (int i = 0; i < nchild_args; i++) {
573 if (child_args[i] < arg) {
574 arg = child_args[i];
575 }
576 }
577 return arg;
578 }
579
ShortVisit(Regexp * re,int parent_arg)580 int RepetitionWalker::ShortVisit(Regexp* re, int parent_arg) {
581 // Should never be called: we use Walk(), not WalkExponential().
582 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
583 ABSL_LOG(DFATAL) << "RepetitionWalker::ShortVisit called";
584 #endif
585 return 0;
586 }
587
588 // Pushes a repetition regexp onto the stack.
589 // A valid argument for the operator must already be on the stack.
PushRepetition(int min,int max,absl::string_view s,bool nongreedy)590 bool Regexp::ParseState::PushRepetition(int min, int max, absl::string_view s,
591 bool nongreedy) {
592 if ((max != -1 && max < min) ||
593 min > maximum_repeat_count ||
594 max > maximum_repeat_count) {
595 status_->set_code(kRegexpRepeatSize);
596 status_->set_error_arg(s);
597 return false;
598 }
599 if (stacktop_ == NULL || IsMarker(stacktop_->op())) {
600 status_->set_code(kRegexpRepeatArgument);
601 status_->set_error_arg(s);
602 return false;
603 }
604 Regexp::ParseFlags fl = flags_;
605 if (nongreedy)
606 fl = fl ^ NonGreedy;
607 Regexp* re = new Regexp(kRegexpRepeat, fl);
608 re->min_ = min;
609 re->max_ = max;
610 re->AllocSub(1);
611 re->down_ = stacktop_->down_;
612 re->sub()[0] = FinishRegexp(stacktop_);
613 re->simple_ = re->ComputeSimple();
614 stacktop_ = re;
615 if (min >= 2 || max >= 2) {
616 RepetitionWalker w;
617 if (w.Walk(stacktop_, maximum_repeat_count) == 0) {
618 status_->set_code(kRegexpRepeatSize);
619 status_->set_error_arg(s);
620 return false;
621 }
622 }
623 return true;
624 }
625
626 // Checks whether a particular regexp op is a marker.
IsMarker(RegexpOp op)627 bool Regexp::ParseState::IsMarker(RegexpOp op) {
628 return op >= kLeftParen;
629 }
630
631 // Processes a left parenthesis in the input.
632 // Pushes a marker onto the stack.
DoLeftParen(absl::string_view name)633 bool Regexp::ParseState::DoLeftParen(absl::string_view name) {
634 Regexp* re = new Regexp(kLeftParen, flags_);
635 re->cap_ = ++ncap_;
636 if (name.data() != NULL)
637 re->name_ = new std::string(name);
638 return PushRegexp(re);
639 }
640
641 // Pushes a non-capturing marker onto the stack.
DoLeftParenNoCapture()642 bool Regexp::ParseState::DoLeftParenNoCapture() {
643 Regexp* re = new Regexp(kLeftParen, flags_);
644 re->cap_ = -1;
645 return PushRegexp(re);
646 }
647
648 // Processes a vertical bar in the input.
DoVerticalBar()649 bool Regexp::ParseState::DoVerticalBar() {
650 MaybeConcatString(-1, NoParseFlags);
651 DoConcatenation();
652
653 // Below the vertical bar is a list to alternate.
654 // Above the vertical bar is a list to concatenate.
655 // We just did the concatenation, so either swap
656 // the result below the vertical bar or push a new
657 // vertical bar on the stack.
658 Regexp* r1;
659 Regexp* r2;
660 if ((r1 = stacktop_) != NULL &&
661 (r2 = r1->down_) != NULL &&
662 r2->op() == kVerticalBar) {
663 Regexp* r3;
664 if ((r3 = r2->down_) != NULL &&
665 (r1->op() == kRegexpAnyChar || r3->op() == kRegexpAnyChar)) {
666 // AnyChar is above or below the vertical bar. Let it subsume
667 // the other when the other is Literal, CharClass or AnyChar.
668 if (r3->op() == kRegexpAnyChar &&
669 (r1->op() == kRegexpLiteral ||
670 r1->op() == kRegexpCharClass ||
671 r1->op() == kRegexpAnyChar)) {
672 // Discard r1.
673 stacktop_ = r2;
674 r1->Decref();
675 return true;
676 }
677 if (r1->op() == kRegexpAnyChar &&
678 (r3->op() == kRegexpLiteral ||
679 r3->op() == kRegexpCharClass ||
680 r3->op() == kRegexpAnyChar)) {
681 // Rearrange the stack and discard r3.
682 r1->down_ = r3->down_;
683 r2->down_ = r1;
684 stacktop_ = r2;
685 r3->Decref();
686 return true;
687 }
688 }
689 // Swap r1 below vertical bar (r2).
690 r1->down_ = r2->down_;
691 r2->down_ = r1;
692 stacktop_ = r2;
693 return true;
694 }
695 return PushSimpleOp(kVerticalBar);
696 }
697
698 // Processes a right parenthesis in the input.
DoRightParen()699 bool Regexp::ParseState::DoRightParen() {
700 // Finish the current concatenation and alternation.
701 DoAlternation();
702
703 // The stack should be: LeftParen regexp
704 // Remove the LeftParen, leaving the regexp,
705 // parenthesized.
706 Regexp* r1;
707 Regexp* r2;
708 if ((r1 = stacktop_) == NULL ||
709 (r2 = r1->down_) == NULL ||
710 r2->op() != kLeftParen) {
711 status_->set_code(kRegexpUnexpectedParen);
712 status_->set_error_arg(whole_regexp_);
713 return false;
714 }
715
716 // Pop off r1, r2. Will Decref or reuse below.
717 stacktop_ = r2->down_;
718
719 // Restore flags from when paren opened.
720 Regexp* re = r2;
721 flags_ = re->parse_flags();
722
723 // Rewrite LeftParen as capture if needed.
724 if (re->cap_ > 0) {
725 re->op_ = kRegexpCapture;
726 // re->cap_ is already set
727 re->AllocSub(1);
728 re->sub()[0] = FinishRegexp(r1);
729 re->simple_ = re->ComputeSimple();
730 } else {
731 re->Decref();
732 re = r1;
733 }
734 return PushRegexp(re);
735 }
736
737 // Processes the end of input, returning the final regexp.
DoFinish()738 Regexp* Regexp::ParseState::DoFinish() {
739 DoAlternation();
740 Regexp* re = stacktop_;
741 if (re != NULL && re->down_ != NULL) {
742 status_->set_code(kRegexpMissingParen);
743 status_->set_error_arg(whole_regexp_);
744 return NULL;
745 }
746 stacktop_ = NULL;
747 return FinishRegexp(re);
748 }
749
750 // Returns the leading regexp that re starts with.
751 // The returned Regexp* points into a piece of re,
752 // so it must not be used after the caller calls re->Decref().
LeadingRegexp(Regexp * re)753 Regexp* Regexp::LeadingRegexp(Regexp* re) {
754 if (re->op() == kRegexpEmptyMatch)
755 return NULL;
756 if (re->op() == kRegexpConcat && re->nsub() >= 2) {
757 Regexp** sub = re->sub();
758 if (sub[0]->op() == kRegexpEmptyMatch)
759 return NULL;
760 return sub[0];
761 }
762 return re;
763 }
764
765 // Removes LeadingRegexp(re) from re and returns what's left.
766 // Consumes the reference to re and may edit it in place.
767 // If caller wants to hold on to LeadingRegexp(re),
768 // must have already Incref'ed it.
RemoveLeadingRegexp(Regexp * re)769 Regexp* Regexp::RemoveLeadingRegexp(Regexp* re) {
770 if (re->op() == kRegexpEmptyMatch)
771 return re;
772 if (re->op() == kRegexpConcat && re->nsub() >= 2) {
773 Regexp** sub = re->sub();
774 if (sub[0]->op() == kRegexpEmptyMatch)
775 return re;
776 sub[0]->Decref();
777 sub[0] = NULL;
778 if (re->nsub() == 2) {
779 // Collapse concatenation to single regexp.
780 Regexp* nre = sub[1];
781 sub[1] = NULL;
782 re->Decref();
783 return nre;
784 }
785 // 3 or more -> 2 or more.
786 re->nsub_--;
787 memmove(sub, sub + 1, re->nsub_ * sizeof sub[0]);
788 return re;
789 }
790 Regexp::ParseFlags pf = re->parse_flags();
791 re->Decref();
792 return new Regexp(kRegexpEmptyMatch, pf);
793 }
794
795 // Returns the leading string that re starts with.
796 // The returned Rune* points into a piece of re,
797 // so it must not be used after the caller calls re->Decref().
LeadingString(Regexp * re,int * nrune,Regexp::ParseFlags * flags)798 Rune* Regexp::LeadingString(Regexp* re, int* nrune,
799 Regexp::ParseFlags* flags) {
800 while (re->op() == kRegexpConcat && re->nsub() > 0)
801 re = re->sub()[0];
802
803 *flags = static_cast<Regexp::ParseFlags>(re->parse_flags_ &
804 (Regexp::FoldCase | Regexp::Latin1));
805
806 if (re->op() == kRegexpLiteral) {
807 *nrune = 1;
808 return &re->rune_;
809 }
810
811 if (re->op() == kRegexpLiteralString) {
812 *nrune = re->nrunes_;
813 return re->runes_;
814 }
815
816 *nrune = 0;
817 return NULL;
818 }
819
820 // Removes the first n leading runes from the beginning of re.
821 // Edits re in place.
RemoveLeadingString(Regexp * re,int n)822 void Regexp::RemoveLeadingString(Regexp* re, int n) {
823 // Chase down concats to find first string.
824 // For regexps generated by parser, nested concats are
825 // flattened except when doing so would overflow the 16-bit
826 // limit on the size of a concatenation, so we should never
827 // see more than two here.
828 Regexp* stk[4];
829 size_t d = 0;
830 while (re->op() == kRegexpConcat) {
831 if (d < ABSL_ARRAYSIZE(stk))
832 stk[d++] = re;
833 re = re->sub()[0];
834 }
835
836 // Remove leading string from re.
837 if (re->op() == kRegexpLiteral) {
838 re->rune_ = 0;
839 re->op_ = kRegexpEmptyMatch;
840 } else if (re->op() == kRegexpLiteralString) {
841 if (n >= re->nrunes_) {
842 delete[] re->runes_;
843 re->runes_ = NULL;
844 re->nrunes_ = 0;
845 re->op_ = kRegexpEmptyMatch;
846 } else if (n == re->nrunes_ - 1) {
847 Rune rune = re->runes_[re->nrunes_ - 1];
848 delete[] re->runes_;
849 re->runes_ = NULL;
850 re->nrunes_ = 0;
851 re->rune_ = rune;
852 re->op_ = kRegexpLiteral;
853 } else {
854 re->nrunes_ -= n;
855 memmove(re->runes_, re->runes_ + n, re->nrunes_ * sizeof re->runes_[0]);
856 }
857 }
858
859 // If re is now empty, concatenations might simplify too.
860 while (d > 0) {
861 re = stk[--d];
862 Regexp** sub = re->sub();
863 if (sub[0]->op() == kRegexpEmptyMatch) {
864 sub[0]->Decref();
865 sub[0] = NULL;
866 // Delete first element of concat.
867 switch (re->nsub()) {
868 case 0:
869 case 1:
870 // Impossible.
871 ABSL_LOG(DFATAL) << "Concat of " << re->nsub();
872 re->submany_ = NULL;
873 re->op_ = kRegexpEmptyMatch;
874 break;
875
876 case 2: {
877 // Replace re with sub[1].
878 Regexp* old = sub[1];
879 sub[1] = NULL;
880 re->Swap(old);
881 old->Decref();
882 break;
883 }
884
885 default:
886 // Slide down.
887 re->nsub_--;
888 memmove(sub, sub + 1, re->nsub_ * sizeof sub[0]);
889 break;
890 }
891 }
892 }
893 }
894
895 // In the context of factoring alternations, a Splice is: a factored prefix or
896 // merged character class computed by one iteration of one round of factoring;
897 // the span of subexpressions of the alternation to be "spliced" (i.e. removed
898 // and replaced); and, for a factored prefix, the number of suffixes after any
899 // factoring that might have subsequently been performed on them. For a merged
900 // character class, there are no suffixes, of course, so the field is ignored.
901 struct Splice {
Splicere2::Splice902 Splice(Regexp* prefix, Regexp** sub, int nsub)
903 : prefix(prefix),
904 sub(sub),
905 nsub(nsub),
906 nsuffix(-1) {}
907
908 Regexp* prefix;
909 Regexp** sub;
910 int nsub;
911 int nsuffix;
912 };
913
914 // Named so because it is used to implement an explicit stack, a Frame is: the
915 // span of subexpressions of the alternation to be factored; the current round
916 // of factoring; any Splices computed; and, for a factored prefix, an iterator
917 // to the next Splice to be factored (i.e. in another Frame) because suffixes.
918 struct Frame {
Framere2::Frame919 Frame(Regexp** sub, int nsub)
920 : sub(sub),
921 nsub(nsub),
922 round(0) {}
923
924 Regexp** sub;
925 int nsub;
926 int round;
927 std::vector<Splice> splices;
928 int spliceidx;
929 };
930
931 // Bundled into a class for friend access to Regexp without needing to declare
932 // (or define) Splice in regexp.h.
933 class FactorAlternationImpl {
934 public:
935 static void Round1(Regexp** sub, int nsub,
936 Regexp::ParseFlags flags,
937 std::vector<Splice>* splices);
938 static void Round2(Regexp** sub, int nsub,
939 Regexp::ParseFlags flags,
940 std::vector<Splice>* splices);
941 static void Round3(Regexp** sub, int nsub,
942 Regexp::ParseFlags flags,
943 std::vector<Splice>* splices);
944 };
945
946 // Factors common prefixes from alternation.
947 // For example,
948 // ABC|ABD|AEF|BCX|BCY
949 // simplifies to
950 // A(B(C|D)|EF)|BC(X|Y)
951 // and thence to
952 // A(B[CD]|EF)|BC[XY]
953 //
954 // Rewrites sub to contain simplified list to alternate and returns
955 // the new length of sub. Adjusts reference counts accordingly
956 // (incoming sub[i] decremented, outgoing sub[i] incremented).
FactorAlternation(Regexp ** sub,int nsub,ParseFlags flags)957 int Regexp::FactorAlternation(Regexp** sub, int nsub, ParseFlags flags) {
958 std::vector<Frame> stk;
959 stk.emplace_back(sub, nsub);
960
961 for (;;) {
962 auto& sub = stk.back().sub;
963 auto& nsub = stk.back().nsub;
964 auto& round = stk.back().round;
965 auto& splices = stk.back().splices;
966 auto& spliceidx = stk.back().spliceidx;
967
968 if (splices.empty()) {
969 // Advance to the next round of factoring. Note that this covers
970 // the initialised state: when splices is empty and round is 0.
971 round++;
972 } else if (spliceidx < static_cast<int>(splices.size())) {
973 // We have at least one more Splice to factor. Recurse logically.
974 stk.emplace_back(splices[spliceidx].sub, splices[spliceidx].nsub);
975 continue;
976 } else {
977 // We have no more Splices to factor. Apply them.
978 auto iter = splices.begin();
979 int out = 0;
980 for (int i = 0; i < nsub; ) {
981 // Copy until we reach where the next Splice begins.
982 while (sub + i < iter->sub)
983 sub[out++] = sub[i++];
984 switch (round) {
985 case 1:
986 case 2: {
987 // Assemble the Splice prefix and the suffixes.
988 Regexp* re[2];
989 re[0] = iter->prefix;
990 re[1] = Regexp::AlternateNoFactor(iter->sub, iter->nsuffix, flags);
991 sub[out++] = Regexp::Concat(re, 2, flags);
992 i += iter->nsub;
993 break;
994 }
995 case 3:
996 // Just use the Splice prefix.
997 sub[out++] = iter->prefix;
998 i += iter->nsub;
999 break;
1000 default:
1001 ABSL_LOG(DFATAL) << "unknown round: " << round;
1002 break;
1003 }
1004 // If we are done, copy until the end of sub.
1005 if (++iter == splices.end()) {
1006 while (i < nsub)
1007 sub[out++] = sub[i++];
1008 }
1009 }
1010 splices.clear();
1011 nsub = out;
1012 // Advance to the next round of factoring.
1013 round++;
1014 }
1015
1016 switch (round) {
1017 case 1:
1018 FactorAlternationImpl::Round1(sub, nsub, flags, &splices);
1019 break;
1020 case 2:
1021 FactorAlternationImpl::Round2(sub, nsub, flags, &splices);
1022 break;
1023 case 3:
1024 FactorAlternationImpl::Round3(sub, nsub, flags, &splices);
1025 break;
1026 case 4:
1027 if (stk.size() == 1) {
1028 // We are at the top of the stack. Just return.
1029 return nsub;
1030 } else {
1031 // Pop the stack and set the number of suffixes.
1032 // (Note that references will be invalidated!)
1033 int nsuffix = nsub;
1034 stk.pop_back();
1035 stk.back().splices[stk.back().spliceidx].nsuffix = nsuffix;
1036 ++stk.back().spliceidx;
1037 continue;
1038 }
1039 default:
1040 ABSL_LOG(DFATAL) << "unknown round: " << round;
1041 break;
1042 }
1043
1044 // Set spliceidx depending on whether we have Splices to factor.
1045 if (splices.empty() || round == 3) {
1046 spliceidx = static_cast<int>(splices.size());
1047 } else {
1048 spliceidx = 0;
1049 }
1050 }
1051 }
1052
Round1(Regexp ** sub,int nsub,Regexp::ParseFlags flags,std::vector<Splice> * splices)1053 void FactorAlternationImpl::Round1(Regexp** sub, int nsub,
1054 Regexp::ParseFlags flags,
1055 std::vector<Splice>* splices) {
1056 // Round 1: Factor out common literal prefixes.
1057 int start = 0;
1058 Rune* rune = NULL;
1059 int nrune = 0;
1060 Regexp::ParseFlags runeflags = Regexp::NoParseFlags;
1061 for (int i = 0; i <= nsub; i++) {
1062 // Invariant: sub[start:i] consists of regexps that all
1063 // begin with rune[0:nrune].
1064 Rune* rune_i = NULL;
1065 int nrune_i = 0;
1066 Regexp::ParseFlags runeflags_i = Regexp::NoParseFlags;
1067 if (i < nsub) {
1068 rune_i = Regexp::LeadingString(sub[i], &nrune_i, &runeflags_i);
1069 if (runeflags_i == runeflags) {
1070 int same = 0;
1071 while (same < nrune && same < nrune_i && rune[same] == rune_i[same])
1072 same++;
1073 if (same > 0) {
1074 // Matches at least one rune in current range. Keep going around.
1075 nrune = same;
1076 continue;
1077 }
1078 }
1079 }
1080
1081 // Found end of a run with common leading literal string:
1082 // sub[start:i] all begin with rune[0:nrune],
1083 // but sub[i] does not even begin with rune[0].
1084 if (i == start) {
1085 // Nothing to do - first iteration.
1086 } else if (i == start+1) {
1087 // Just one: don't bother factoring.
1088 } else {
1089 Regexp* prefix = Regexp::LiteralString(rune, nrune, runeflags);
1090 for (int j = start; j < i; j++)
1091 Regexp::RemoveLeadingString(sub[j], nrune);
1092 splices->emplace_back(prefix, sub + start, i - start);
1093 }
1094
1095 // Prepare for next iteration (if there is one).
1096 if (i < nsub) {
1097 start = i;
1098 rune = rune_i;
1099 nrune = nrune_i;
1100 runeflags = runeflags_i;
1101 }
1102 }
1103 }
1104
Round2(Regexp ** sub,int nsub,Regexp::ParseFlags flags,std::vector<Splice> * splices)1105 void FactorAlternationImpl::Round2(Regexp** sub, int nsub,
1106 Regexp::ParseFlags flags,
1107 std::vector<Splice>* splices) {
1108 // Round 2: Factor out common simple prefixes,
1109 // just the first piece of each concatenation.
1110 // This will be good enough a lot of the time.
1111 //
1112 // Complex subexpressions (e.g. involving quantifiers)
1113 // are not safe to factor because that collapses their
1114 // distinct paths through the automaton, which affects
1115 // correctness in some cases.
1116 int start = 0;
1117 Regexp* first = NULL;
1118 for (int i = 0; i <= nsub; i++) {
1119 // Invariant: sub[start:i] consists of regexps that all
1120 // begin with first.
1121 Regexp* first_i = NULL;
1122 if (i < nsub) {
1123 first_i = Regexp::LeadingRegexp(sub[i]);
1124 if (first != NULL &&
1125 // first must be an empty-width op
1126 // OR a char class, any char or any byte
1127 // OR a fixed repeat of a literal, char class, any char or any byte.
1128 (first->op() == kRegexpBeginLine ||
1129 first->op() == kRegexpEndLine ||
1130 first->op() == kRegexpWordBoundary ||
1131 first->op() == kRegexpNoWordBoundary ||
1132 first->op() == kRegexpBeginText ||
1133 first->op() == kRegexpEndText ||
1134 first->op() == kRegexpCharClass ||
1135 first->op() == kRegexpAnyChar ||
1136 first->op() == kRegexpAnyByte ||
1137 (first->op() == kRegexpRepeat &&
1138 first->min() == first->max() &&
1139 (first->sub()[0]->op() == kRegexpLiteral ||
1140 first->sub()[0]->op() == kRegexpCharClass ||
1141 first->sub()[0]->op() == kRegexpAnyChar ||
1142 first->sub()[0]->op() == kRegexpAnyByte))) &&
1143 Regexp::Equal(first, first_i))
1144 continue;
1145 }
1146
1147 // Found end of a run with common leading regexp:
1148 // sub[start:i] all begin with first,
1149 // but sub[i] does not.
1150 if (i == start) {
1151 // Nothing to do - first iteration.
1152 } else if (i == start+1) {
1153 // Just one: don't bother factoring.
1154 } else {
1155 Regexp* prefix = first->Incref();
1156 for (int j = start; j < i; j++)
1157 sub[j] = Regexp::RemoveLeadingRegexp(sub[j]);
1158 splices->emplace_back(prefix, sub + start, i - start);
1159 }
1160
1161 // Prepare for next iteration (if there is one).
1162 if (i < nsub) {
1163 start = i;
1164 first = first_i;
1165 }
1166 }
1167 }
1168
Round3(Regexp ** sub,int nsub,Regexp::ParseFlags flags,std::vector<Splice> * splices)1169 void FactorAlternationImpl::Round3(Regexp** sub, int nsub,
1170 Regexp::ParseFlags flags,
1171 std::vector<Splice>* splices) {
1172 // Round 3: Merge runs of literals and/or character classes.
1173 int start = 0;
1174 Regexp* first = NULL;
1175 for (int i = 0; i <= nsub; i++) {
1176 // Invariant: sub[start:i] consists of regexps that all
1177 // are either literals (i.e. runes) or character classes.
1178 Regexp* first_i = NULL;
1179 if (i < nsub) {
1180 first_i = sub[i];
1181 if (first != NULL &&
1182 (first->op() == kRegexpLiteral ||
1183 first->op() == kRegexpCharClass) &&
1184 (first_i->op() == kRegexpLiteral ||
1185 first_i->op() == kRegexpCharClass))
1186 continue;
1187 }
1188
1189 // Found end of a run of Literal/CharClass:
1190 // sub[start:i] all are either one or the other,
1191 // but sub[i] is not.
1192 if (i == start) {
1193 // Nothing to do - first iteration.
1194 } else if (i == start+1) {
1195 // Just one: don't bother factoring.
1196 } else {
1197 CharClassBuilder ccb;
1198 for (int j = start; j < i; j++) {
1199 Regexp* re = sub[j];
1200 if (re->op() == kRegexpCharClass) {
1201 CharClass* cc = re->cc();
1202 for (CharClass::iterator it = cc->begin(); it != cc->end(); ++it)
1203 ccb.AddRangeFlags(it->lo, it->hi, re->parse_flags());
1204 } else if (re->op() == kRegexpLiteral) {
1205 if (re->parse_flags() & Regexp::FoldCase) {
1206 // AddFoldedRange() can terminate prematurely if the character class
1207 // already contains the rune. For example, if it contains 'a' and we
1208 // want to add folded 'a', it sees 'a' and stops without adding 'A'.
1209 // To avoid that, we use an empty character class and then merge it.
1210 CharClassBuilder tmp;
1211 tmp.AddRangeFlags(re->rune(), re->rune(), re->parse_flags());
1212 ccb.AddCharClass(&tmp);
1213 } else {
1214 ccb.AddRangeFlags(re->rune(), re->rune(), re->parse_flags());
1215 }
1216 } else {
1217 ABSL_LOG(DFATAL) << "RE2: unexpected op: " << re->op() << " "
1218 << re->ToString();
1219 }
1220 re->Decref();
1221 }
1222 Regexp* re = Regexp::NewCharClass(ccb.GetCharClass(), flags & ~Regexp::FoldCase);
1223 splices->emplace_back(re, sub + start, i - start);
1224 }
1225
1226 // Prepare for next iteration (if there is one).
1227 if (i < nsub) {
1228 start = i;
1229 first = first_i;
1230 }
1231 }
1232 }
1233
1234 // Collapse the regexps on top of the stack, down to the
1235 // first marker, into a new op node (op == kRegexpAlternate
1236 // or op == kRegexpConcat).
DoCollapse(RegexpOp op)1237 void Regexp::ParseState::DoCollapse(RegexpOp op) {
1238 // Scan backward to marker, counting children of composite.
1239 int n = 0;
1240 Regexp* next = NULL;
1241 Regexp* sub;
1242 for (sub = stacktop_; sub != NULL && !IsMarker(sub->op()); sub = next) {
1243 next = sub->down_;
1244 if (sub->op_ == op)
1245 n += sub->nsub_;
1246 else
1247 n++;
1248 }
1249
1250 // If there's just one child, leave it alone.
1251 // (Concat of one thing is that one thing; alternate of one thing is same.)
1252 if (stacktop_ != NULL && stacktop_->down_ == next)
1253 return;
1254
1255 // Construct op (alternation or concatenation), flattening op of op.
1256 PODArray<Regexp*> subs(n);
1257 next = NULL;
1258 int i = n;
1259 for (sub = stacktop_; sub != NULL && !IsMarker(sub->op()); sub = next) {
1260 next = sub->down_;
1261 if (sub->op_ == op) {
1262 Regexp** sub_subs = sub->sub();
1263 for (int k = sub->nsub_ - 1; k >= 0; k--)
1264 subs[--i] = sub_subs[k]->Incref();
1265 sub->Decref();
1266 } else {
1267 subs[--i] = FinishRegexp(sub);
1268 }
1269 }
1270
1271 Regexp* re = ConcatOrAlternate(op, subs.data(), n, flags_, true);
1272 re->simple_ = re->ComputeSimple();
1273 re->down_ = next;
1274 stacktop_ = re;
1275 }
1276
1277 // Finishes the current concatenation,
1278 // collapsing it into a single regexp on the stack.
DoConcatenation()1279 void Regexp::ParseState::DoConcatenation() {
1280 Regexp* r1 = stacktop_;
1281 if (r1 == NULL || IsMarker(r1->op())) {
1282 // empty concatenation is special case
1283 Regexp* re = new Regexp(kRegexpEmptyMatch, flags_);
1284 PushRegexp(re);
1285 }
1286 DoCollapse(kRegexpConcat);
1287 }
1288
1289 // Finishes the current alternation,
1290 // collapsing it to a single regexp on the stack.
DoAlternation()1291 void Regexp::ParseState::DoAlternation() {
1292 DoVerticalBar();
1293 // Now stack top is kVerticalBar.
1294 Regexp* r1 = stacktop_;
1295 stacktop_ = r1->down_;
1296 r1->Decref();
1297 DoCollapse(kRegexpAlternate);
1298 }
1299
1300 // Incremental conversion of concatenated literals into strings.
1301 // If top two elements on stack are both literal or string,
1302 // collapse into single string.
1303 // Don't walk down the stack -- the parser calls this frequently
1304 // enough that below the bottom two is known to be collapsed.
1305 // Only called when another regexp is about to be pushed
1306 // on the stack, so that the topmost literal is not being considered.
1307 // (Otherwise ab* would turn into (ab)*.)
1308 // If r >= 0, consider pushing a literal r on the stack.
1309 // Return whether that happened.
MaybeConcatString(int r,ParseFlags flags)1310 bool Regexp::ParseState::MaybeConcatString(int r, ParseFlags flags) {
1311 Regexp* re1;
1312 Regexp* re2;
1313 if ((re1 = stacktop_) == NULL || (re2 = re1->down_) == NULL)
1314 return false;
1315
1316 if (re1->op_ != kRegexpLiteral && re1->op_ != kRegexpLiteralString)
1317 return false;
1318 if (re2->op_ != kRegexpLiteral && re2->op_ != kRegexpLiteralString)
1319 return false;
1320 if ((re1->parse_flags_ & FoldCase) != (re2->parse_flags_ & FoldCase))
1321 return false;
1322
1323 if (re2->op_ == kRegexpLiteral) {
1324 // convert into string
1325 Rune rune = re2->rune_;
1326 re2->op_ = kRegexpLiteralString;
1327 re2->nrunes_ = 0;
1328 re2->runes_ = NULL;
1329 re2->AddRuneToString(rune);
1330 }
1331
1332 // push re1 into re2.
1333 if (re1->op_ == kRegexpLiteral) {
1334 re2->AddRuneToString(re1->rune_);
1335 } else {
1336 for (int i = 0; i < re1->nrunes_; i++)
1337 re2->AddRuneToString(re1->runes_[i]);
1338 re1->nrunes_ = 0;
1339 delete[] re1->runes_;
1340 re1->runes_ = NULL;
1341 }
1342
1343 // reuse re1 if possible
1344 if (r >= 0) {
1345 re1->op_ = kRegexpLiteral;
1346 re1->rune_ = r;
1347 re1->parse_flags_ = static_cast<uint16_t>(flags);
1348 return true;
1349 }
1350
1351 stacktop_ = re2;
1352 re1->Decref();
1353 return false;
1354 }
1355
1356 // Lexing routines.
1357
1358 // Parses a decimal integer, storing it in *np.
1359 // Sets *s to span the remainder of the string.
ParseInteger(absl::string_view * s,int * np)1360 static bool ParseInteger(absl::string_view* s, int* np) {
1361 if (s->empty() || !absl::ascii_isdigit((*s)[0] & 0xFF))
1362 return false;
1363 // Disallow leading zeros.
1364 if (s->size() >= 2 && (*s)[0] == '0' && absl::ascii_isdigit((*s)[1] & 0xFF))
1365 return false;
1366 int n = 0;
1367 int c;
1368 while (!s->empty() && absl::ascii_isdigit(c = (*s)[0] & 0xFF)) {
1369 // Avoid overflow.
1370 if (n >= 100000000)
1371 return false;
1372 n = n*10 + c - '0';
1373 s->remove_prefix(1); // digit
1374 }
1375 *np = n;
1376 return true;
1377 }
1378
1379 // Parses a repetition suffix like {1,2} or {2} or {2,}.
1380 // Sets *s to span the remainder of the string on success.
1381 // Sets *lo and *hi to the given range.
1382 // In the case of {2,}, the high number is unbounded;
1383 // sets *hi to -1 to signify this.
1384 // {,2} is NOT a valid suffix.
1385 // The Maybe in the name signifies that the regexp parse
1386 // doesn't fail even if ParseRepetition does, so the string_view
1387 // s must NOT be edited unless MaybeParseRepetition returns true.
MaybeParseRepetition(absl::string_view * sp,int * lo,int * hi)1388 static bool MaybeParseRepetition(absl::string_view* sp, int* lo, int* hi) {
1389 absl::string_view s = *sp;
1390 if (s.empty() || s[0] != '{')
1391 return false;
1392 s.remove_prefix(1); // '{'
1393 if (!ParseInteger(&s, lo))
1394 return false;
1395 if (s.empty())
1396 return false;
1397 if (s[0] == ',') {
1398 s.remove_prefix(1); // ','
1399 if (s.empty())
1400 return false;
1401 if (s[0] == '}') {
1402 // {2,} means at least 2
1403 *hi = -1;
1404 } else {
1405 // {2,4} means 2, 3, or 4.
1406 if (!ParseInteger(&s, hi))
1407 return false;
1408 }
1409 } else {
1410 // {2} means exactly two
1411 *hi = *lo;
1412 }
1413 if (s.empty() || s[0] != '}')
1414 return false;
1415 s.remove_prefix(1); // '}'
1416 *sp = s;
1417 return true;
1418 }
1419
1420 // Removes the next Rune from the string_view and stores it in *r.
1421 // Returns number of bytes removed from sp.
1422 // Behaves as though there is a terminating NUL at the end of sp.
1423 // Argument order is backwards from usual Google style
1424 // but consistent with chartorune.
StringViewToRune(Rune * r,absl::string_view * sp,RegexpStatus * status)1425 static int StringViewToRune(Rune* r, absl::string_view* sp,
1426 RegexpStatus* status) {
1427 // fullrune() takes int, not size_t. However, it just looks
1428 // at the leading byte and treats any length >= 4 the same.
1429 if (fullrune(sp->data(), static_cast<int>(std::min(size_t{4}, sp->size())))) {
1430 int n = chartorune(r, sp->data());
1431 // Some copies of chartorune have a bug that accepts
1432 // encodings of values in (10FFFF, 1FFFFF] as valid.
1433 // Those values break the character class algorithm,
1434 // which assumes Runemax is the largest rune.
1435 if (*r > Runemax) {
1436 n = 1;
1437 *r = Runeerror;
1438 }
1439 if (!(n == 1 && *r == Runeerror)) { // no decoding error
1440 sp->remove_prefix(n);
1441 return n;
1442 }
1443 }
1444
1445 if (status != NULL) {
1446 status->set_code(kRegexpBadUTF8);
1447 status->set_error_arg(absl::string_view());
1448 }
1449 return -1;
1450 }
1451
1452 // Returns whether name is valid UTF-8.
1453 // If not, sets status to kRegexpBadUTF8.
IsValidUTF8(absl::string_view s,RegexpStatus * status)1454 static bool IsValidUTF8(absl::string_view s, RegexpStatus* status) {
1455 absl::string_view t = s;
1456 Rune r;
1457 while (!t.empty()) {
1458 if (StringViewToRune(&r, &t, status) < 0)
1459 return false;
1460 }
1461 return true;
1462 }
1463
1464 // Is c a hex digit?
IsHex(int c)1465 static int IsHex(int c) {
1466 return ('0' <= c && c <= '9') ||
1467 ('A' <= c && c <= 'F') ||
1468 ('a' <= c && c <= 'f');
1469 }
1470
1471 // Convert hex digit to value.
UnHex(int c)1472 static int UnHex(int c) {
1473 if ('0' <= c && c <= '9')
1474 return c - '0';
1475 if ('A' <= c && c <= 'F')
1476 return c - 'A' + 10;
1477 if ('a' <= c && c <= 'f')
1478 return c - 'a' + 10;
1479 ABSL_LOG(DFATAL) << "Bad hex digit " << c;
1480 return 0;
1481 }
1482
1483 // Parse an escape sequence (e.g., \n, \{).
1484 // Sets *s to span the remainder of the string.
1485 // Sets *rp to the named character.
ParseEscape(absl::string_view * s,Rune * rp,RegexpStatus * status,int rune_max)1486 static bool ParseEscape(absl::string_view* s, Rune* rp,
1487 RegexpStatus* status, int rune_max) {
1488 const char* begin = s->data();
1489 if (s->empty() || (*s)[0] != '\\') {
1490 // Should not happen - caller always checks.
1491 status->set_code(kRegexpInternalError);
1492 status->set_error_arg(absl::string_view());
1493 return false;
1494 }
1495 if (s->size() == 1) {
1496 status->set_code(kRegexpTrailingBackslash);
1497 status->set_error_arg(absl::string_view());
1498 return false;
1499 }
1500 Rune c, c1;
1501 s->remove_prefix(1); // backslash
1502 if (StringViewToRune(&c, s, status) < 0)
1503 return false;
1504 int code;
1505 switch (c) {
1506 default:
1507 if (c < Runeself && !absl::ascii_isalnum(c)) {
1508 // Escaped non-word characters are always themselves.
1509 // PCRE is not quite so rigorous: it accepts things like
1510 // \q, but we don't. We once rejected \_, but too many
1511 // programs and people insist on using it, so allow \_.
1512 *rp = c;
1513 return true;
1514 }
1515 goto BadEscape;
1516
1517 // Octal escapes.
1518 case '1':
1519 case '2':
1520 case '3':
1521 case '4':
1522 case '5':
1523 case '6':
1524 case '7':
1525 // Single non-zero octal digit is a backreference; not supported.
1526 if (s->empty() || (*s)[0] < '0' || (*s)[0] > '7')
1527 goto BadEscape;
1528 ABSL_FALLTHROUGH_INTENDED;
1529 case '0':
1530 // consume up to three octal digits; already have one.
1531 code = c - '0';
1532 if (!s->empty() && '0' <= (c = (*s)[0]) && c <= '7') {
1533 code = code * 8 + c - '0';
1534 s->remove_prefix(1); // digit
1535 if (!s->empty()) {
1536 c = (*s)[0];
1537 if ('0' <= c && c <= '7') {
1538 code = code * 8 + c - '0';
1539 s->remove_prefix(1); // digit
1540 }
1541 }
1542 }
1543 if (code > rune_max)
1544 goto BadEscape;
1545 *rp = code;
1546 return true;
1547
1548 // Hexadecimal escapes
1549 case 'x':
1550 if (s->empty())
1551 goto BadEscape;
1552 if (StringViewToRune(&c, s, status) < 0)
1553 return false;
1554 if (c == '{') {
1555 // Any number of digits in braces.
1556 // Update n as we consume the string, so that
1557 // the whole thing gets shown in the error message.
1558 // Perl accepts any text at all; it ignores all text
1559 // after the first non-hex digit. We require only hex digits,
1560 // and at least one.
1561 if (StringViewToRune(&c, s, status) < 0)
1562 return false;
1563 int nhex = 0;
1564 code = 0;
1565 while (IsHex(c)) {
1566 nhex++;
1567 code = code * 16 + UnHex(c);
1568 if (code > rune_max)
1569 goto BadEscape;
1570 if (s->empty())
1571 goto BadEscape;
1572 if (StringViewToRune(&c, s, status) < 0)
1573 return false;
1574 }
1575 if (c != '}' || nhex == 0)
1576 goto BadEscape;
1577 *rp = code;
1578 return true;
1579 }
1580 // Easy case: two hex digits.
1581 if (s->empty())
1582 goto BadEscape;
1583 if (StringViewToRune(&c1, s, status) < 0)
1584 return false;
1585 if (!IsHex(c) || !IsHex(c1))
1586 goto BadEscape;
1587 *rp = UnHex(c) * 16 + UnHex(c1);
1588 return true;
1589
1590 // C escapes.
1591 case 'n':
1592 *rp = '\n';
1593 return true;
1594 case 'r':
1595 *rp = '\r';
1596 return true;
1597 case 't':
1598 *rp = '\t';
1599 return true;
1600
1601 // Less common C escapes.
1602 case 'a':
1603 *rp = '\a';
1604 return true;
1605 case 'f':
1606 *rp = '\f';
1607 return true;
1608 case 'v':
1609 *rp = '\v';
1610 return true;
1611
1612 // This code is disabled to avoid misparsing
1613 // the Perl word-boundary \b as a backspace
1614 // when in POSIX regexp mode. Surprisingly,
1615 // in Perl, \b means word-boundary but [\b]
1616 // means backspace. We don't support that:
1617 // if you want a backspace embed a literal
1618 // backspace character or use \x08.
1619 //
1620 // case 'b':
1621 // *rp = '\b';
1622 // return true;
1623 }
1624
1625 BadEscape:
1626 // Unrecognized escape sequence.
1627 status->set_code(kRegexpBadEscape);
1628 status->set_error_arg(
1629 absl::string_view(begin, static_cast<size_t>(s->data() - begin)));
1630 return false;
1631 }
1632
1633 // Add a range to the character class, but exclude newline if asked.
1634 // Also handle case folding.
AddRangeFlags(Rune lo,Rune hi,Regexp::ParseFlags parse_flags)1635 void CharClassBuilder::AddRangeFlags(
1636 Rune lo, Rune hi, Regexp::ParseFlags parse_flags) {
1637
1638 // Take out \n if the flags say so.
1639 bool cutnl = !(parse_flags & Regexp::ClassNL) ||
1640 (parse_flags & Regexp::NeverNL);
1641 if (cutnl && lo <= '\n' && '\n' <= hi) {
1642 if (lo < '\n')
1643 AddRangeFlags(lo, '\n' - 1, parse_flags);
1644 if (hi > '\n')
1645 AddRangeFlags('\n' + 1, hi, parse_flags);
1646 return;
1647 }
1648
1649 // If folding case, add fold-equivalent characters too.
1650 if (parse_flags & Regexp::FoldCase) {
1651 if (parse_flags & Regexp::Latin1) {
1652 AddFoldedRangeLatin1(this, lo, hi);
1653 } else {
1654 AddFoldedRange(this, lo, hi, 0);
1655 }
1656 } else {
1657 AddRange(lo, hi);
1658 }
1659 }
1660
1661 // Look for a group with the given name.
LookupGroup(absl::string_view name,const UGroup * groups,int ngroups)1662 static const UGroup* LookupGroup(absl::string_view name,
1663 const UGroup* groups, int ngroups) {
1664 // Simple name lookup.
1665 for (int i = 0; i < ngroups; i++)
1666 if (absl::string_view(groups[i].name) == name)
1667 return &groups[i];
1668 return NULL;
1669 }
1670
1671 // Look for a POSIX group with the given name (e.g., "[:^alpha:]")
LookupPosixGroup(absl::string_view name)1672 static const UGroup* LookupPosixGroup(absl::string_view name) {
1673 return LookupGroup(name, posix_groups, num_posix_groups);
1674 }
1675
LookupPerlGroup(absl::string_view name)1676 static const UGroup* LookupPerlGroup(absl::string_view name) {
1677 return LookupGroup(name, perl_groups, num_perl_groups);
1678 }
1679
1680 #if !defined(RE2_USE_ICU)
1681 // Fake UGroup containing all Runes
1682 static URange16 any16[] = { { 0, 65535 } };
1683 static URange32 any32[] = { { 65536, Runemax } };
1684 static UGroup anygroup = { "Any", +1, any16, 1, any32, 1 };
1685
1686 // Look for a Unicode group with the given name (e.g., "Han")
LookupUnicodeGroup(absl::string_view name)1687 static const UGroup* LookupUnicodeGroup(absl::string_view name) {
1688 // Special case: "Any" means any.
1689 if (name == absl::string_view("Any"))
1690 return &anygroup;
1691 return LookupGroup(name, unicode_groups, num_unicode_groups);
1692 }
1693 #endif
1694
1695 // Add a UGroup or its negation to the character class.
AddUGroup(CharClassBuilder * cc,const UGroup * g,int sign,Regexp::ParseFlags parse_flags)1696 static void AddUGroup(CharClassBuilder* cc, const UGroup* g, int sign,
1697 Regexp::ParseFlags parse_flags) {
1698 if (sign == +1) {
1699 for (int i = 0; i < g->nr16; i++) {
1700 cc->AddRangeFlags(g->r16[i].lo, g->r16[i].hi, parse_flags);
1701 }
1702 for (int i = 0; i < g->nr32; i++) {
1703 cc->AddRangeFlags(g->r32[i].lo, g->r32[i].hi, parse_flags);
1704 }
1705 } else {
1706 if (parse_flags & Regexp::FoldCase) {
1707 // Normally adding a case-folded group means
1708 // adding all the extra fold-equivalent runes too.
1709 // But if we're adding the negation of the group,
1710 // we have to exclude all the runes that are fold-equivalent
1711 // to what's already missing. Too hard, so do in two steps.
1712 CharClassBuilder ccb1;
1713 AddUGroup(&ccb1, g, +1, parse_flags);
1714 // If the flags say to take out \n, put it in, so that negating will take it out.
1715 // Normally AddRangeFlags does this, but we're bypassing AddRangeFlags.
1716 bool cutnl = !(parse_flags & Regexp::ClassNL) ||
1717 (parse_flags & Regexp::NeverNL);
1718 if (cutnl) {
1719 ccb1.AddRange('\n', '\n');
1720 }
1721 ccb1.Negate();
1722 cc->AddCharClass(&ccb1);
1723 return;
1724 }
1725 int next = 0;
1726 for (int i = 0; i < g->nr16; i++) {
1727 if (next < g->r16[i].lo)
1728 cc->AddRangeFlags(next, g->r16[i].lo - 1, parse_flags);
1729 next = g->r16[i].hi + 1;
1730 }
1731 for (int i = 0; i < g->nr32; i++) {
1732 if (next < g->r32[i].lo)
1733 cc->AddRangeFlags(next, g->r32[i].lo - 1, parse_flags);
1734 next = g->r32[i].hi + 1;
1735 }
1736 if (next <= Runemax)
1737 cc->AddRangeFlags(next, Runemax, parse_flags);
1738 }
1739 }
1740
1741 // Maybe parse a Perl character class escape sequence.
1742 // Only recognizes the Perl character classes (\d \s \w \D \S \W),
1743 // not the Perl empty-string classes (\b \B \A \Z \z).
1744 // On success, sets *s to span the remainder of the string
1745 // and returns the corresponding UGroup.
1746 // The string_view must *NOT* be edited unless the call succeeds.
MaybeParsePerlCCEscape(absl::string_view * s,Regexp::ParseFlags parse_flags)1747 const UGroup* MaybeParsePerlCCEscape(absl::string_view* s,
1748 Regexp::ParseFlags parse_flags) {
1749 if (!(parse_flags & Regexp::PerlClasses))
1750 return NULL;
1751 if (s->size() < 2 || (*s)[0] != '\\')
1752 return NULL;
1753 // Could use StringViewToRune, but there aren't
1754 // any non-ASCII Perl group names.
1755 absl::string_view name(s->data(), 2);
1756 const UGroup* g = LookupPerlGroup(name);
1757 if (g == NULL)
1758 return NULL;
1759 s->remove_prefix(name.size());
1760 return g;
1761 }
1762
1763 enum ParseStatus {
1764 kParseOk, // Did some parsing.
1765 kParseError, // Found an error.
1766 kParseNothing, // Decided not to parse.
1767 };
1768
1769 // Maybe parses a Unicode character group like \p{Han} or \P{Han}
1770 // (the latter is a negated group).
ParseUnicodeGroup(absl::string_view * s,Regexp::ParseFlags parse_flags,CharClassBuilder * cc,RegexpStatus * status)1771 ParseStatus ParseUnicodeGroup(absl::string_view* s,
1772 Regexp::ParseFlags parse_flags,
1773 CharClassBuilder* cc, RegexpStatus* status) {
1774 // Decide whether to parse.
1775 if (!(parse_flags & Regexp::UnicodeGroups))
1776 return kParseNothing;
1777 if (s->size() < 2 || (*s)[0] != '\\')
1778 return kParseNothing;
1779 Rune c = (*s)[1];
1780 if (c != 'p' && c != 'P')
1781 return kParseNothing;
1782
1783 // Committed to parse. Results:
1784 int sign = +1; // -1 = negated char class
1785 if (c == 'P')
1786 sign = -sign;
1787 absl::string_view seq = *s; // \p{Han} or \pL
1788 absl::string_view name; // Han or L
1789 s->remove_prefix(2); // '\\', 'p'
1790
1791 if (!StringViewToRune(&c, s, status))
1792 return kParseError;
1793 if (c != '{') {
1794 // Name is the bit of string we just skipped over for c.
1795 const char* p = seq.data() + 2;
1796 name = absl::string_view(p, static_cast<size_t>(s->data() - p));
1797 } else {
1798 // Name is in braces. Look for closing }
1799 size_t end = s->find('}', 0);
1800 if (end == absl::string_view::npos) {
1801 if (!IsValidUTF8(seq, status))
1802 return kParseError;
1803 status->set_code(kRegexpBadCharRange);
1804 status->set_error_arg(seq);
1805 return kParseError;
1806 }
1807 name = absl::string_view(s->data(), end); // without '}'
1808 s->remove_prefix(end + 1); // with '}'
1809 if (!IsValidUTF8(name, status))
1810 return kParseError;
1811 }
1812
1813 // Chop seq where s now begins.
1814 seq = absl::string_view(seq.data(), static_cast<size_t>(s->data() - seq.data()));
1815
1816 if (!name.empty() && name[0] == '^') {
1817 sign = -sign;
1818 name.remove_prefix(1); // '^'
1819 }
1820
1821 #if !defined(RE2_USE_ICU)
1822 // Look up the group in the RE2 Unicode data.
1823 const UGroup* g = LookupUnicodeGroup(name);
1824 if (g == NULL) {
1825 status->set_code(kRegexpBadCharRange);
1826 status->set_error_arg(seq);
1827 return kParseError;
1828 }
1829
1830 AddUGroup(cc, g, sign, parse_flags);
1831 #else
1832 // Look up the group in the ICU Unicode data. Because ICU provides full
1833 // Unicode properties support, this could be more than a lookup by name.
1834 ::icu::UnicodeString ustr = ::icu::UnicodeString::fromUTF8(
1835 std::string("\\p{") + std::string(name) + std::string("}"));
1836 UErrorCode uerr = U_ZERO_ERROR;
1837 ::icu::UnicodeSet uset(ustr, uerr);
1838 if (U_FAILURE(uerr)) {
1839 status->set_code(kRegexpBadCharRange);
1840 status->set_error_arg(seq);
1841 return kParseError;
1842 }
1843
1844 // Convert the UnicodeSet to a URange32 and UGroup that we can add.
1845 int nr = uset.getRangeCount();
1846 PODArray<URange32> r(nr);
1847 for (int i = 0; i < nr; i++) {
1848 r[i].lo = uset.getRangeStart(i);
1849 r[i].hi = uset.getRangeEnd(i);
1850 }
1851 UGroup g = {"", +1, 0, 0, r.data(), nr};
1852 AddUGroup(cc, &g, sign, parse_flags);
1853 #endif
1854
1855 return kParseOk;
1856 }
1857
1858 // Parses a character class name like [:alnum:].
1859 // Sets *s to span the remainder of the string.
1860 // Adds the ranges corresponding to the class to ranges.
ParseCCName(absl::string_view * s,Regexp::ParseFlags parse_flags,CharClassBuilder * cc,RegexpStatus * status)1861 static ParseStatus ParseCCName(absl::string_view* s,
1862 Regexp::ParseFlags parse_flags,
1863 CharClassBuilder* cc, RegexpStatus* status) {
1864 // Check begins with [:
1865 const char* p = s->data();
1866 const char* ep = s->data() + s->size();
1867 if (ep - p < 2 || p[0] != '[' || p[1] != ':')
1868 return kParseNothing;
1869
1870 // Look for closing :].
1871 const char* q;
1872 for (q = p+2; q <= ep-2 && (*q != ':' || *(q+1) != ']'); q++)
1873 ;
1874
1875 // If no closing :], then ignore.
1876 if (q > ep-2)
1877 return kParseNothing;
1878
1879 // Got it. Check that it's valid.
1880 q += 2;
1881 absl::string_view name(p, static_cast<size_t>(q - p));
1882
1883 const UGroup* g = LookupPosixGroup(name);
1884 if (g == NULL) {
1885 status->set_code(kRegexpBadCharRange);
1886 status->set_error_arg(name);
1887 return kParseError;
1888 }
1889
1890 s->remove_prefix(name.size());
1891 AddUGroup(cc, g, g->sign, parse_flags);
1892 return kParseOk;
1893 }
1894
1895 // Parses a character inside a character class.
1896 // There are fewer special characters here than in the rest of the regexp.
1897 // Sets *s to span the remainder of the string.
1898 // Sets *rp to the character.
ParseCCCharacter(absl::string_view * s,Rune * rp,absl::string_view whole_class,RegexpStatus * status)1899 bool Regexp::ParseState::ParseCCCharacter(absl::string_view* s, Rune* rp,
1900 absl::string_view whole_class,
1901 RegexpStatus* status) {
1902 if (s->empty()) {
1903 status->set_code(kRegexpMissingBracket);
1904 status->set_error_arg(whole_class);
1905 return false;
1906 }
1907
1908 // Allow regular escape sequences even though
1909 // many need not be escaped in this context.
1910 if ((*s)[0] == '\\')
1911 return ParseEscape(s, rp, status, rune_max_);
1912
1913 // Otherwise take the next rune.
1914 return StringViewToRune(rp, s, status) >= 0;
1915 }
1916
1917 // Parses a character class character, or, if the character
1918 // is followed by a hyphen, parses a character class range.
1919 // For single characters, rr->lo == rr->hi.
1920 // Sets *s to span the remainder of the string.
1921 // Sets *rp to the character.
ParseCCRange(absl::string_view * s,RuneRange * rr,absl::string_view whole_class,RegexpStatus * status)1922 bool Regexp::ParseState::ParseCCRange(absl::string_view* s, RuneRange* rr,
1923 absl::string_view whole_class,
1924 RegexpStatus* status) {
1925 absl::string_view os = *s;
1926 if (!ParseCCCharacter(s, &rr->lo, whole_class, status))
1927 return false;
1928 // [a-] means (a|-), so check for final ].
1929 if (s->size() >= 2 && (*s)[0] == '-' && (*s)[1] != ']') {
1930 s->remove_prefix(1); // '-'
1931 if (!ParseCCCharacter(s, &rr->hi, whole_class, status))
1932 return false;
1933 if (rr->hi < rr->lo) {
1934 status->set_code(kRegexpBadCharRange);
1935 status->set_error_arg(absl::string_view(
1936 os.data(), static_cast<size_t>(s->data() - os.data())));
1937 return false;
1938 }
1939 } else {
1940 rr->hi = rr->lo;
1941 }
1942 return true;
1943 }
1944
1945 // Parses a possibly-negated character class expression like [^abx-z[:digit:]].
1946 // Sets *s to span the remainder of the string.
1947 // Sets *out_re to the regexp for the class.
ParseCharClass(absl::string_view * s,Regexp ** out_re,RegexpStatus * status)1948 bool Regexp::ParseState::ParseCharClass(absl::string_view* s, Regexp** out_re,
1949 RegexpStatus* status) {
1950 absl::string_view whole_class = *s;
1951 if (s->empty() || (*s)[0] != '[') {
1952 // Caller checked this.
1953 status->set_code(kRegexpInternalError);
1954 status->set_error_arg(absl::string_view());
1955 return false;
1956 }
1957 bool negated = false;
1958 Regexp* re = new Regexp(kRegexpCharClass, flags_ & ~FoldCase);
1959 re->ccb_ = new CharClassBuilder;
1960 s->remove_prefix(1); // '['
1961 if (!s->empty() && (*s)[0] == '^') {
1962 s->remove_prefix(1); // '^'
1963 negated = true;
1964 if (!(flags_ & ClassNL) || (flags_ & NeverNL)) {
1965 // If NL can't match implicitly, then pretend
1966 // negated classes include a leading \n.
1967 re->ccb_->AddRange('\n', '\n');
1968 }
1969 }
1970 bool first = true; // ] is okay as first char in class
1971 while (!s->empty() && ((*s)[0] != ']' || first)) {
1972 // - is only okay unescaped as first or last in class.
1973 // Except that Perl allows - anywhere.
1974 if ((*s)[0] == '-' && !first && !(flags_&PerlX) &&
1975 (s->size() == 1 || (*s)[1] != ']')) {
1976 absl::string_view t = *s;
1977 t.remove_prefix(1); // '-'
1978 Rune r;
1979 int n = StringViewToRune(&r, &t, status);
1980 if (n < 0) {
1981 re->Decref();
1982 return false;
1983 }
1984 status->set_code(kRegexpBadCharRange);
1985 status->set_error_arg(absl::string_view(s->data(), 1+n));
1986 re->Decref();
1987 return false;
1988 }
1989 first = false;
1990
1991 // Look for [:alnum:] etc.
1992 if (s->size() > 2 && (*s)[0] == '[' && (*s)[1] == ':') {
1993 switch (ParseCCName(s, flags_, re->ccb_, status)) {
1994 case kParseOk:
1995 continue;
1996 case kParseError:
1997 re->Decref();
1998 return false;
1999 case kParseNothing:
2000 break;
2001 }
2002 }
2003
2004 // Look for Unicode character group like \p{Han}
2005 if (s->size() > 2 &&
2006 (*s)[0] == '\\' &&
2007 ((*s)[1] == 'p' || (*s)[1] == 'P')) {
2008 switch (ParseUnicodeGroup(s, flags_, re->ccb_, status)) {
2009 case kParseOk:
2010 continue;
2011 case kParseError:
2012 re->Decref();
2013 return false;
2014 case kParseNothing:
2015 break;
2016 }
2017 }
2018
2019 // Look for Perl character class symbols (extension).
2020 const UGroup* g = MaybeParsePerlCCEscape(s, flags_);
2021 if (g != NULL) {
2022 AddUGroup(re->ccb_, g, g->sign, flags_);
2023 continue;
2024 }
2025
2026 // Otherwise assume single character or simple range.
2027 RuneRange rr;
2028 if (!ParseCCRange(s, &rr, whole_class, status)) {
2029 re->Decref();
2030 return false;
2031 }
2032 // AddRangeFlags is usually called in response to a class like
2033 // \p{Foo} or [[:foo:]]; for those, it filters \n out unless
2034 // Regexp::ClassNL is set. In an explicit range or singleton
2035 // like we just parsed, we do not filter \n out, so set ClassNL
2036 // in the flags.
2037 re->ccb_->AddRangeFlags(rr.lo, rr.hi, flags_ | Regexp::ClassNL);
2038 }
2039 if (s->empty()) {
2040 status->set_code(kRegexpMissingBracket);
2041 status->set_error_arg(whole_class);
2042 re->Decref();
2043 return false;
2044 }
2045 s->remove_prefix(1); // ']'
2046
2047 if (negated)
2048 re->ccb_->Negate();
2049
2050 *out_re = re;
2051 return true;
2052 }
2053
2054 // Returns whether name is a valid capture name.
IsValidCaptureName(absl::string_view name)2055 static bool IsValidCaptureName(absl::string_view name) {
2056 if (name.empty())
2057 return false;
2058
2059 // Historically, we effectively used [0-9A-Za-z_]+ to validate; that
2060 // followed Python 2 except for not restricting the first character.
2061 // As of Python 3, Unicode characters beyond ASCII are also allowed;
2062 // accordingly, we permit the Lu, Ll, Lt, Lm, Lo, Nl, Mn, Mc, Nd and
2063 // Pc categories, but again without restricting the first character.
2064 // Also, Unicode normalization (e.g. NFKC) isn't performed: Python 3
2065 // performs it for identifiers, but seemingly not for capture names;
2066 // if they start doing that for capture names, we won't follow suit.
2067 static const CharClass* const cc = []() {
2068 CharClassBuilder ccb;
2069 for (absl::string_view group :
2070 {"Lu", "Ll", "Lt", "Lm", "Lo", "Nl", "Mn", "Mc", "Nd", "Pc"})
2071 AddUGroup(&ccb, LookupGroup(group, unicode_groups, num_unicode_groups),
2072 +1, Regexp::NoParseFlags);
2073 return ccb.GetCharClass();
2074 }();
2075
2076 absl::string_view t = name;
2077 Rune r;
2078 while (!t.empty()) {
2079 if (StringViewToRune(&r, &t, NULL) < 0)
2080 return false;
2081 if (cc->Contains(r))
2082 continue;
2083 return false;
2084 }
2085 return true;
2086 }
2087
2088 // Parses a Perl flag setting or non-capturing group or both,
2089 // like (?i) or (?: or (?i:. Removes from s, updates parse state.
2090 // The caller must check that s begins with "(?".
2091 // Returns true on success. If the Perl flag is not
2092 // well-formed or not supported, sets status_ and returns false.
ParsePerlFlags(absl::string_view * s)2093 bool Regexp::ParseState::ParsePerlFlags(absl::string_view* s) {
2094 absl::string_view t = *s;
2095
2096 // Caller is supposed to check this.
2097 if (!(flags_ & PerlX) || t.size() < 2 || t[0] != '(' || t[1] != '?') {
2098 status_->set_code(kRegexpInternalError);
2099 ABSL_LOG(DFATAL) << "Bad call to ParseState::ParsePerlFlags";
2100 return false;
2101 }
2102
2103 // Check for look-around assertions. This is NOT because we support them! ;)
2104 // As per https://github.com/google/re2/issues/468, we really want to report
2105 // kRegexpBadPerlOp (not kRegexpBadNamedCapture) for look-behind assertions.
2106 // Additionally, it would be nice to report not "(?<", but "(?<=" or "(?<!".
2107 if ((t.size() > 3 && (t[2] == '=' || t[2] == '!')) ||
2108 (t.size() > 4 && t[2] == '<' && (t[3] == '=' || t[3] == '!'))) {
2109 status_->set_code(kRegexpBadPerlOp);
2110 status_->set_error_arg(absl::string_view(t.data(), t[2] == '<' ? 4 : 3));
2111 return false;
2112 }
2113
2114 // Check for named captures, first introduced in Python's regexp library.
2115 // As usual, there are three slightly different syntaxes:
2116 //
2117 // (?P<name>expr) the original, introduced by Python
2118 // (?<name>expr) the .NET alteration, adopted by Perl 5.10
2119 // (?'name'expr) another .NET alteration, adopted by Perl 5.10
2120 //
2121 // Perl 5.10 gave in and implemented the Python version too,
2122 // but they claim that the last two are the preferred forms.
2123 // PCRE and languages based on it (specifically, PHP and Ruby)
2124 // support all three as well. EcmaScript 4 uses only the Python form.
2125 //
2126 // In both the open source world (via Code Search) and the
2127 // Google source tree, (?P<name>expr) and (?<name>expr) are the
2128 // dominant forms of named captures and both are supported.
2129 if ((t.size() > 4 && t[2] == 'P' && t[3] == '<') ||
2130 (t.size() > 3 && t[2] == '<')) {
2131 // Pull out name.
2132 size_t begin = t[2] == 'P' ? 4 : 3;
2133 size_t end = t.find('>', begin);
2134 if (end == absl::string_view::npos) {
2135 if (!IsValidUTF8(t, status_))
2136 return false;
2137 status_->set_code(kRegexpBadNamedCapture);
2138 status_->set_error_arg(t);
2139 return false;
2140 }
2141
2142 absl::string_view capture(t.data(), end+1);
2143 absl::string_view name(t.data()+begin, end-begin);
2144 if (!IsValidUTF8(name, status_))
2145 return false;
2146 if (!IsValidCaptureName(name)) {
2147 status_->set_code(kRegexpBadNamedCapture);
2148 status_->set_error_arg(capture);
2149 return false;
2150 }
2151
2152 if (!DoLeftParen(name)) {
2153 // DoLeftParen's failure set status_.
2154 return false;
2155 }
2156
2157 s->remove_prefix(capture.size());
2158 return true;
2159 }
2160
2161 t.remove_prefix(2); // "(?"
2162
2163 bool negated = false;
2164 bool sawflags = false;
2165 int nflags = flags_;
2166 Rune c;
2167 for (bool done = false; !done; ) {
2168 if (t.empty())
2169 goto BadPerlOp;
2170 if (StringViewToRune(&c, &t, status_) < 0)
2171 return false;
2172 switch (c) {
2173 default:
2174 goto BadPerlOp;
2175
2176 // Parse flags.
2177 case 'i':
2178 sawflags = true;
2179 if (negated)
2180 nflags &= ~FoldCase;
2181 else
2182 nflags |= FoldCase;
2183 break;
2184
2185 case 'm': // opposite of our OneLine
2186 sawflags = true;
2187 if (negated)
2188 nflags |= OneLine;
2189 else
2190 nflags &= ~OneLine;
2191 break;
2192
2193 case 's':
2194 sawflags = true;
2195 if (negated)
2196 nflags &= ~DotNL;
2197 else
2198 nflags |= DotNL;
2199 break;
2200
2201 case 'U':
2202 sawflags = true;
2203 if (negated)
2204 nflags &= ~NonGreedy;
2205 else
2206 nflags |= NonGreedy;
2207 break;
2208
2209 // Negation
2210 case '-':
2211 if (negated)
2212 goto BadPerlOp;
2213 negated = true;
2214 sawflags = false;
2215 break;
2216
2217 // Open new group.
2218 case ':':
2219 if (!DoLeftParenNoCapture()) {
2220 // DoLeftParenNoCapture's failure set status_.
2221 return false;
2222 }
2223 done = true;
2224 break;
2225
2226 // Finish flags.
2227 case ')':
2228 done = true;
2229 break;
2230 }
2231 }
2232
2233 if (negated && !sawflags)
2234 goto BadPerlOp;
2235
2236 flags_ = static_cast<Regexp::ParseFlags>(nflags);
2237 *s = t;
2238 return true;
2239
2240 BadPerlOp:
2241 status_->set_code(kRegexpBadPerlOp);
2242 status_->set_error_arg(
2243 absl::string_view(s->data(), static_cast<size_t>(t.data() - s->data())));
2244 return false;
2245 }
2246
2247 // Converts latin1 (assumed to be encoded as Latin1 bytes)
2248 // into UTF8 encoding in string.
2249 // Can't use EncodingUtils::EncodeLatin1AsUTF8 because it is
2250 // deprecated and because it rejects code points 0x80-0x9F.
ConvertLatin1ToUTF8(absl::string_view latin1,std::string * utf)2251 void ConvertLatin1ToUTF8(absl::string_view latin1, std::string* utf) {
2252 char buf[UTFmax];
2253
2254 utf->clear();
2255 for (size_t i = 0; i < latin1.size(); i++) {
2256 Rune r = latin1[i] & 0xFF;
2257 int n = runetochar(buf, &r);
2258 utf->append(buf, n);
2259 }
2260 }
2261
2262 // Parses the regular expression given by s,
2263 // returning the corresponding Regexp tree.
2264 // The caller must Decref the return value when done with it.
2265 // Returns NULL on error.
Parse(absl::string_view s,ParseFlags global_flags,RegexpStatus * status)2266 Regexp* Regexp::Parse(absl::string_view s, ParseFlags global_flags,
2267 RegexpStatus* status) {
2268 // Make status non-NULL (easier on everyone else).
2269 RegexpStatus xstatus;
2270 if (status == NULL)
2271 status = &xstatus;
2272
2273 ParseState ps(global_flags, s, status);
2274 absl::string_view t = s;
2275
2276 // Convert regexp to UTF-8 (easier on the rest of the parser).
2277 if (global_flags & Latin1) {
2278 std::string* tmp = new std::string;
2279 ConvertLatin1ToUTF8(t, tmp);
2280 status->set_tmp(tmp);
2281 t = *tmp;
2282 }
2283
2284 if (global_flags & Literal) {
2285 // Special parse loop for literal string.
2286 while (!t.empty()) {
2287 Rune r;
2288 if (StringViewToRune(&r, &t, status) < 0)
2289 return NULL;
2290 if (!ps.PushLiteral(r))
2291 return NULL;
2292 }
2293 return ps.DoFinish();
2294 }
2295
2296 absl::string_view lastunary = absl::string_view();
2297 while (!t.empty()) {
2298 absl::string_view isunary = absl::string_view();
2299 switch (t[0]) {
2300 default: {
2301 Rune r;
2302 if (StringViewToRune(&r, &t, status) < 0)
2303 return NULL;
2304 if (!ps.PushLiteral(r))
2305 return NULL;
2306 break;
2307 }
2308
2309 case '(':
2310 // "(?" introduces Perl escape.
2311 if ((ps.flags() & PerlX) && (t.size() >= 2 && t[1] == '?')) {
2312 // Flag changes and non-capturing groups.
2313 if (!ps.ParsePerlFlags(&t))
2314 return NULL;
2315 break;
2316 }
2317 if (ps.flags() & NeverCapture) {
2318 if (!ps.DoLeftParenNoCapture())
2319 return NULL;
2320 } else {
2321 if (!ps.DoLeftParen(absl::string_view()))
2322 return NULL;
2323 }
2324 t.remove_prefix(1); // '('
2325 break;
2326
2327 case '|':
2328 if (!ps.DoVerticalBar())
2329 return NULL;
2330 t.remove_prefix(1); // '|'
2331 break;
2332
2333 case ')':
2334 if (!ps.DoRightParen())
2335 return NULL;
2336 t.remove_prefix(1); // ')'
2337 break;
2338
2339 case '^': // Beginning of line.
2340 if (!ps.PushCaret())
2341 return NULL;
2342 t.remove_prefix(1); // '^'
2343 break;
2344
2345 case '$': // End of line.
2346 if (!ps.PushDollar())
2347 return NULL;
2348 t.remove_prefix(1); // '$'
2349 break;
2350
2351 case '.': // Any character (possibly except newline).
2352 if (!ps.PushDot())
2353 return NULL;
2354 t.remove_prefix(1); // '.'
2355 break;
2356
2357 case '[': { // Character class.
2358 Regexp* re;
2359 if (!ps.ParseCharClass(&t, &re, status))
2360 return NULL;
2361 if (!ps.PushRegexp(re))
2362 return NULL;
2363 break;
2364 }
2365
2366 case '*': { // Zero or more.
2367 RegexpOp op;
2368 op = kRegexpStar;
2369 goto Rep;
2370 case '+': // One or more.
2371 op = kRegexpPlus;
2372 goto Rep;
2373 case '?': // Zero or one.
2374 op = kRegexpQuest;
2375 goto Rep;
2376 Rep:
2377 absl::string_view opstr = t;
2378 bool nongreedy = false;
2379 t.remove_prefix(1); // '*' or '+' or '?'
2380 if (ps.flags() & PerlX) {
2381 if (!t.empty() && t[0] == '?') {
2382 nongreedy = true;
2383 t.remove_prefix(1); // '?'
2384 }
2385 if (!lastunary.empty()) {
2386 // In Perl it is not allowed to stack repetition operators:
2387 // a** is a syntax error, not a double-star.
2388 // (and a++ means something else entirely, which we don't support!)
2389 status->set_code(kRegexpRepeatOp);
2390 status->set_error_arg(absl::string_view(
2391 lastunary.data(),
2392 static_cast<size_t>(t.data() - lastunary.data())));
2393 return NULL;
2394 }
2395 }
2396 opstr = absl::string_view(opstr.data(),
2397 static_cast<size_t>(t.data() - opstr.data()));
2398 if (!ps.PushRepeatOp(op, opstr, nongreedy))
2399 return NULL;
2400 isunary = opstr;
2401 break;
2402 }
2403
2404 case '{': { // Counted repetition.
2405 int lo, hi;
2406 absl::string_view opstr = t;
2407 if (!MaybeParseRepetition(&t, &lo, &hi)) {
2408 // Treat like a literal.
2409 if (!ps.PushLiteral('{'))
2410 return NULL;
2411 t.remove_prefix(1); // '{'
2412 break;
2413 }
2414 bool nongreedy = false;
2415 if (ps.flags() & PerlX) {
2416 if (!t.empty() && t[0] == '?') {
2417 nongreedy = true;
2418 t.remove_prefix(1); // '?'
2419 }
2420 if (!lastunary.empty()) {
2421 // Not allowed to stack repetition operators.
2422 status->set_code(kRegexpRepeatOp);
2423 status->set_error_arg(absl::string_view(
2424 lastunary.data(),
2425 static_cast<size_t>(t.data() - lastunary.data())));
2426 return NULL;
2427 }
2428 }
2429 opstr = absl::string_view(opstr.data(),
2430 static_cast<size_t>(t.data() - opstr.data()));
2431 if (!ps.PushRepetition(lo, hi, opstr, nongreedy))
2432 return NULL;
2433 isunary = opstr;
2434 break;
2435 }
2436
2437 case '\\': { // Escaped character or Perl sequence.
2438 // \b and \B: word boundary or not
2439 if ((ps.flags() & Regexp::PerlB) &&
2440 t.size() >= 2 && (t[1] == 'b' || t[1] == 'B')) {
2441 if (!ps.PushWordBoundary(t[1] == 'b'))
2442 return NULL;
2443 t.remove_prefix(2); // '\\', 'b'
2444 break;
2445 }
2446
2447 if ((ps.flags() & Regexp::PerlX) && t.size() >= 2) {
2448 if (t[1] == 'A') {
2449 if (!ps.PushSimpleOp(kRegexpBeginText))
2450 return NULL;
2451 t.remove_prefix(2); // '\\', 'A'
2452 break;
2453 }
2454 if (t[1] == 'z') {
2455 if (!ps.PushSimpleOp(kRegexpEndText))
2456 return NULL;
2457 t.remove_prefix(2); // '\\', 'z'
2458 break;
2459 }
2460 // Do not recognize \Z, because this library can't
2461 // implement the exact Perl/PCRE semantics.
2462 // (This library treats "(?-m)$" as \z, even though
2463 // in Perl and PCRE it is equivalent to \Z.)
2464
2465 if (t[1] == 'C') { // \C: any byte [sic]
2466 if (!ps.PushSimpleOp(kRegexpAnyByte))
2467 return NULL;
2468 t.remove_prefix(2); // '\\', 'C'
2469 break;
2470 }
2471
2472 if (t[1] == 'Q') { // \Q ... \E: the ... is always literals
2473 t.remove_prefix(2); // '\\', 'Q'
2474 while (!t.empty()) {
2475 if (t.size() >= 2 && t[0] == '\\' && t[1] == 'E') {
2476 t.remove_prefix(2); // '\\', 'E'
2477 break;
2478 }
2479 Rune r;
2480 if (StringViewToRune(&r, &t, status) < 0)
2481 return NULL;
2482 if (!ps.PushLiteral(r))
2483 return NULL;
2484 }
2485 break;
2486 }
2487 }
2488
2489 if (t.size() >= 2 && (t[1] == 'p' || t[1] == 'P')) {
2490 Regexp* re = new Regexp(kRegexpCharClass, ps.flags() & ~FoldCase);
2491 re->ccb_ = new CharClassBuilder;
2492 switch (ParseUnicodeGroup(&t, ps.flags(), re->ccb_, status)) {
2493 case kParseOk:
2494 if (!ps.PushRegexp(re))
2495 return NULL;
2496 goto Break2;
2497 case kParseError:
2498 re->Decref();
2499 return NULL;
2500 case kParseNothing:
2501 re->Decref();
2502 break;
2503 }
2504 }
2505
2506 const UGroup* g = MaybeParsePerlCCEscape(&t, ps.flags());
2507 if (g != NULL) {
2508 Regexp* re = new Regexp(kRegexpCharClass, ps.flags() & ~FoldCase);
2509 re->ccb_ = new CharClassBuilder;
2510 AddUGroup(re->ccb_, g, g->sign, ps.flags());
2511 if (!ps.PushRegexp(re))
2512 return NULL;
2513 break;
2514 }
2515
2516 Rune r;
2517 if (!ParseEscape(&t, &r, status, ps.rune_max()))
2518 return NULL;
2519 if (!ps.PushLiteral(r))
2520 return NULL;
2521 break;
2522 }
2523 }
2524 Break2:
2525 lastunary = isunary;
2526 }
2527 return ps.DoFinish();
2528 }
2529
2530 } // namespace re2
2531