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