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