• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2003-2009 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 #ifndef RE2_RE2_H_
6 #define RE2_RE2_H_
7 
8 // C++ interface to the re2 regular-expression library.
9 // RE2 supports Perl-style regular expressions (with extensions like
10 // \d, \w, \s, ...).
11 //
12 // -----------------------------------------------------------------------
13 // REGEXP SYNTAX:
14 //
15 // This module uses the re2 library and hence supports
16 // its syntax for regular expressions, which is similar to Perl's with
17 // some of the more complicated things thrown away.  In particular,
18 // backreferences and generalized assertions are not available, nor is \Z.
19 //
20 // See https://github.com/google/re2/wiki/Syntax for the syntax
21 // supported by RE2, and a comparison with PCRE and PERL regexps.
22 //
23 // For those not familiar with Perl's regular expressions,
24 // here are some examples of the most commonly used extensions:
25 //
26 //   "hello (\\w+) world"  -- \w matches a "word" character
27 //   "version (\\d+)"      -- \d matches a digit
28 //   "hello\\s+world"      -- \s matches any whitespace character
29 //   "\\b(\\w+)\\b"        -- \b matches non-empty string at word boundary
30 //   "(?i)hello"           -- (?i) turns on case-insensitive matching
31 //   "/\\*(.*?)\\*/"       -- .*? matches . minimum no. of times possible
32 //
33 // -----------------------------------------------------------------------
34 // MATCHING INTERFACE:
35 //
36 // The "FullMatch" operation checks that supplied text matches a
37 // supplied pattern exactly.
38 //
39 // Example: successful match
40 //    CHECK(RE2::FullMatch("hello", "h.*o"));
41 //
42 // Example: unsuccessful match (requires full match):
43 //    CHECK(!RE2::FullMatch("hello", "e"));
44 //
45 // -----------------------------------------------------------------------
46 // UTF-8 AND THE MATCHING INTERFACE:
47 //
48 // By default, the pattern and input text are interpreted as UTF-8.
49 // The RE2::Latin1 option causes them to be interpreted as Latin-1.
50 //
51 // Example:
52 //    CHECK(RE2::FullMatch(utf8_string, RE2(utf8_pattern)));
53 //    CHECK(RE2::FullMatch(latin1_string, RE2(latin1_pattern, RE2::Latin1)));
54 //
55 // -----------------------------------------------------------------------
56 // MATCHING WITH SUBSTRING EXTRACTION:
57 //
58 // You can supply extra pointer arguments to extract matched substrings.
59 // On match failure, none of the pointees will have been modified.
60 // On match success, the substrings will be converted (as necessary) and
61 // their values will be assigned to their pointees until all conversions
62 // have succeeded or one conversion has failed.
63 // On conversion failure, the pointees will be in an indeterminate state
64 // because the caller has no way of knowing which conversion failed.
65 // However, conversion cannot fail for types like string and StringPiece
66 // that do not inspect the substring contents. Hence, in the common case
67 // where all of the pointees are of such types, failure is always due to
68 // match failure and thus none of the pointees will have been modified.
69 //
70 // Example: extracts "ruby" into "s" and 1234 into "i"
71 //    int i;
72 //    std::string s;
73 //    CHECK(RE2::FullMatch("ruby:1234", "(\\w+):(\\d+)", &s, &i));
74 //
75 // Example: fails because string cannot be stored in integer
76 //    CHECK(!RE2::FullMatch("ruby", "(.*)", &i));
77 //
78 // Example: fails because there aren't enough sub-patterns
79 //    CHECK(!RE2::FullMatch("ruby:1234", "\\w+:\\d+", &s));
80 //
81 // Example: does not try to extract any extra sub-patterns
82 //    CHECK(RE2::FullMatch("ruby:1234", "(\\w+):(\\d+)", &s));
83 //
84 // Example: does not try to extract into NULL
85 //    CHECK(RE2::FullMatch("ruby:1234", "(\\w+):(\\d+)", NULL, &i));
86 //
87 // Example: integer overflow causes failure
88 //    CHECK(!RE2::FullMatch("ruby:1234567891234", "\\w+:(\\d+)", &i));
89 //
90 // NOTE(rsc): Asking for substrings slows successful matches quite a bit.
91 // This may get a little faster in the future, but right now is slower
92 // than PCRE.  On the other hand, failed matches run *very* fast (faster
93 // than PCRE), as do matches without substring extraction.
94 //
95 // -----------------------------------------------------------------------
96 // PARTIAL MATCHES
97 //
98 // You can use the "PartialMatch" operation when you want the pattern
99 // to match any substring of the text.
100 //
101 // Example: simple search for a string:
102 //      CHECK(RE2::PartialMatch("hello", "ell"));
103 //
104 // Example: find first number in a string
105 //      int number;
106 //      CHECK(RE2::PartialMatch("x*100 + 20", "(\\d+)", &number));
107 //      CHECK_EQ(number, 100);
108 //
109 // -----------------------------------------------------------------------
110 // PRE-COMPILED REGULAR EXPRESSIONS
111 //
112 // RE2 makes it easy to use any string as a regular expression, without
113 // requiring a separate compilation step.
114 //
115 // If speed is of the essence, you can create a pre-compiled "RE2"
116 // object from the pattern and use it multiple times.  If you do so,
117 // you can typically parse text faster than with sscanf.
118 //
119 // Example: precompile pattern for faster matching:
120 //    RE2 pattern("h.*o");
121 //    while (ReadLine(&str)) {
122 //      if (RE2::FullMatch(str, pattern)) ...;
123 //    }
124 //
125 // -----------------------------------------------------------------------
126 // SCANNING TEXT INCREMENTALLY
127 //
128 // The "Consume" operation may be useful if you want to repeatedly
129 // match regular expressions at the front of a string and skip over
130 // them as they match.  This requires use of the "StringPiece" type,
131 // which represents a sub-range of a real string.
132 //
133 // Example: read lines of the form "var = value" from a string.
134 //      std::string contents = ...;     // Fill string somehow
135 //      StringPiece input(contents);    // Wrap a StringPiece around it
136 //
137 //      std::string var;
138 //      int value;
139 //      while (RE2::Consume(&input, "(\\w+) = (\\d+)\n", &var, &value)) {
140 //        ...;
141 //      }
142 //
143 // Each successful call to "Consume" will set "var/value", and also
144 // advance "input" so it points past the matched text.  Note that if the
145 // regular expression matches an empty string, input will advance
146 // by 0 bytes.  If the regular expression being used might match
147 // an empty string, the loop body must check for this case and either
148 // advance the string or break out of the loop.
149 //
150 // The "FindAndConsume" operation is similar to "Consume" but does not
151 // anchor your match at the beginning of the string.  For example, you
152 // could extract all words from a string by repeatedly calling
153 //     RE2::FindAndConsume(&input, "(\\w+)", &word)
154 //
155 // -----------------------------------------------------------------------
156 // USING VARIABLE NUMBER OF ARGUMENTS
157 //
158 // The above operations require you to know the number of arguments
159 // when you write the code.  This is not always possible or easy (for
160 // example, the regular expression may be calculated at run time).
161 // You can use the "N" version of the operations when the number of
162 // match arguments are determined at run time.
163 //
164 // Example:
165 //   const RE2::Arg* args[10];
166 //   int n;
167 //   // ... populate args with pointers to RE2::Arg values ...
168 //   // ... set n to the number of RE2::Arg objects ...
169 //   bool match = RE2::FullMatchN(input, pattern, args, n);
170 //
171 // The last statement is equivalent to
172 //
173 //   bool match = RE2::FullMatch(input, pattern,
174 //                               *args[0], *args[1], ..., *args[n - 1]);
175 //
176 // -----------------------------------------------------------------------
177 // PARSING HEX/OCTAL/C-RADIX NUMBERS
178 //
179 // By default, if you pass a pointer to a numeric value, the
180 // corresponding text is interpreted as a base-10 number.  You can
181 // instead wrap the pointer with a call to one of the operators Hex(),
182 // Octal(), or CRadix() to interpret the text in another base.  The
183 // CRadix operator interprets C-style "0" (base-8) and "0x" (base-16)
184 // prefixes, but defaults to base-10.
185 //
186 // Example:
187 //   int a, b, c, d;
188 //   CHECK(RE2::FullMatch("100 40 0100 0x40", "(.*) (.*) (.*) (.*)",
189 //         RE2::Octal(&a), RE2::Hex(&b), RE2::CRadix(&c), RE2::CRadix(&d));
190 // will leave 64 in a, b, c, and d.
191 
192 #include <stddef.h>
193 #include <stdint.h>
194 #include <algorithm>
195 #include <map>
196 #include <mutex>
197 #include <string>
198 
199 #include "re2/stringpiece.h"
200 
201 namespace re2 {
202 class Prog;
203 class Regexp;
204 }  // namespace re2
205 
206 namespace re2 {
207 
208 // Interface for regular expression matching.  Also corresponds to a
209 // pre-compiled regular expression.  An "RE2" object is safe for
210 // concurrent use by multiple threads.
211 class RE2 {
212  public:
213   // We convert user-passed pointers into special Arg objects
214   class Arg;
215   class Options;
216 
217   // Defined in set.h.
218   class Set;
219 
220   enum ErrorCode {
221     NoError = 0,
222 
223     // Unexpected error
224     ErrorInternal,
225 
226     // Parse errors
227     ErrorBadEscape,          // bad escape sequence
228     ErrorBadCharClass,       // bad character class
229     ErrorBadCharRange,       // bad character class range
230     ErrorMissingBracket,     // missing closing ]
231     ErrorMissingParen,       // missing closing )
232     ErrorTrailingBackslash,  // trailing \ at end of regexp
233     ErrorRepeatArgument,     // repeat argument missing, e.g. "*"
234     ErrorRepeatSize,         // bad repetition argument
235     ErrorRepeatOp,           // bad repetition operator
236     ErrorBadPerlOp,          // bad perl operator
237     ErrorBadUTF8,            // invalid UTF-8 in regexp
238     ErrorBadNamedCapture,    // bad named capture group
239     ErrorPatternTooLarge     // pattern too large (compile failed)
240   };
241 
242   // Predefined common options.
243   // If you need more complicated things, instantiate
244   // an Option class, possibly passing one of these to
245   // the Option constructor, change the settings, and pass that
246   // Option class to the RE2 constructor.
247   enum CannedOptions {
248     DefaultOptions = 0,
249     Latin1, // treat input as Latin-1 (default UTF-8)
250     POSIX, // POSIX syntax, leftmost-longest match
251     Quiet // do not log about regexp parse errors
252   };
253 
254   // Need to have the const char* and const std::string& forms for implicit
255   // conversions when passing string literals to FullMatch and PartialMatch.
256   // Otherwise the StringPiece form would be sufficient.
257 #ifndef SWIG
258   RE2(const char* pattern);
259   RE2(const std::string& pattern);
260 #endif
261   RE2(const StringPiece& pattern);
262   RE2(const StringPiece& pattern, const Options& options);
263   ~RE2();
264 
265   // Returns whether RE2 was created properly.
ok()266   bool ok() const { return error_code() == NoError; }
267 
268   // The string specification for this RE2.  E.g.
269   //   RE2 re("ab*c?d+");
270   //   re.pattern();    // "ab*c?d+"
pattern()271   const std::string& pattern() const { return pattern_; }
272 
273   // If RE2 could not be created properly, returns an error string.
274   // Else returns the empty string.
error()275   const std::string& error() const { return *error_; }
276 
277   // If RE2 could not be created properly, returns an error code.
278   // Else returns RE2::NoError (== 0).
error_code()279   ErrorCode error_code() const { return error_code_; }
280 
281   // If RE2 could not be created properly, returns the offending
282   // portion of the regexp.
error_arg()283   const std::string& error_arg() const { return error_arg_; }
284 
285   // Returns the program size, a very approximate measure of a regexp's "cost".
286   // Larger numbers are more expensive than smaller numbers.
287   int ProgramSize() const;
288   int ReverseProgramSize() const;
289 
290   // EXPERIMENTAL! SUBJECT TO CHANGE!
291   // Outputs the program fanout as a histogram bucketed by powers of 2.
292   // Returns the number of the largest non-empty bucket.
293   int ProgramFanout(std::map<int, int>* histogram) const;
294   int ReverseProgramFanout(std::map<int, int>* histogram) const;
295 
296   // Returns the underlying Regexp; not for general use.
297   // Returns entire_regexp_ so that callers don't need
298   // to know about prefix_ and prefix_foldcase_.
Regexp()299   re2::Regexp* Regexp() const { return entire_regexp_; }
300 
301   /***** The array-based matching interface ******/
302 
303   // The functions here have names ending in 'N' and are used to implement
304   // the functions whose names are the prefix before the 'N'. It is sometimes
305   // useful to invoke them directly, but the syntax is awkward, so the 'N'-less
306   // versions should be preferred.
307   static bool FullMatchN(const StringPiece& text, const RE2& re,
308                          const Arg* const args[], int n);
309   static bool PartialMatchN(const StringPiece& text, const RE2& re,
310                             const Arg* const args[], int n);
311   static bool ConsumeN(StringPiece* input, const RE2& re,
312                        const Arg* const args[], int n);
313   static bool FindAndConsumeN(StringPiece* input, const RE2& re,
314                               const Arg* const args[], int n);
315 
316 #ifndef SWIG
317  private:
318   template <typename F, typename SP>
Apply(F f,SP sp,const RE2 & re)319   static inline bool Apply(F f, SP sp, const RE2& re) {
320     return f(sp, re, NULL, 0);
321   }
322 
323   template <typename F, typename SP, typename... A>
Apply(F f,SP sp,const RE2 & re,const A &...a)324   static inline bool Apply(F f, SP sp, const RE2& re, const A&... a) {
325     const Arg* const args[] = {&a...};
326     const int n = sizeof...(a);
327     return f(sp, re, args, n);
328   }
329 
330  public:
331   // In order to allow FullMatch() et al. to be called with a varying number
332   // of arguments of varying types, we use two layers of variadic templates.
333   // The first layer constructs the temporary Arg objects. The second layer
334   // (above) constructs the array of pointers to the temporary Arg objects.
335 
336   /***** The useful part: the matching interface *****/
337 
338   // Matches "text" against "re".  If pointer arguments are
339   // supplied, copies matched sub-patterns into them.
340   //
341   // You can pass in a "const char*" or a "std::string" for "text".
342   // You can pass in a "const char*" or a "std::string" or a "RE2" for "re".
343   //
344   // The provided pointer arguments can be pointers to any scalar numeric
345   // type, or one of:
346   //    std::string     (matched piece is copied to string)
347   //    StringPiece     (StringPiece is mutated to point to matched piece)
348   //    T               (where "bool T::ParseFrom(const char*, size_t)" exists)
349   //    (void*)NULL     (the corresponding matched sub-pattern is not copied)
350   //
351   // Returns true iff all of the following conditions are satisfied:
352   //   a. "text" matches "re" exactly
353   //   b. The number of matched sub-patterns is >= number of supplied pointers
354   //   c. The "i"th argument has a suitable type for holding the
355   //      string captured as the "i"th sub-pattern.  If you pass in
356   //      NULL for the "i"th argument, or pass fewer arguments than
357   //      number of sub-patterns, "i"th captured sub-pattern is
358   //      ignored.
359   //
360   // CAVEAT: An optional sub-pattern that does not exist in the
361   // matched string is assigned the empty string.  Therefore, the
362   // following will return false (because the empty string is not a
363   // valid number):
364   //    int number;
365   //    RE2::FullMatch("abc", "[a-z]+(\\d+)?", &number);
366   template <typename... A>
FullMatch(const StringPiece & text,const RE2 & re,A &&...a)367   static bool FullMatch(const StringPiece& text, const RE2& re, A&&... a) {
368     return Apply(FullMatchN, text, re, Arg(std::forward<A>(a))...);
369   }
370 
371   // Exactly like FullMatch(), except that "re" is allowed to match
372   // a substring of "text".
373   template <typename... A>
PartialMatch(const StringPiece & text,const RE2 & re,A &&...a)374   static bool PartialMatch(const StringPiece& text, const RE2& re, A&&... a) {
375     return Apply(PartialMatchN, text, re, Arg(std::forward<A>(a))...);
376   }
377 
378   // Like FullMatch() and PartialMatch(), except that "re" has to match
379   // a prefix of the text, and "input" is advanced past the matched
380   // text.  Note: "input" is modified iff this routine returns true
381   // and "re" matched a non-empty substring of "text".
382   template <typename... A>
Consume(StringPiece * input,const RE2 & re,A &&...a)383   static bool Consume(StringPiece* input, const RE2& re, A&&... a) {
384     return Apply(ConsumeN, input, re, Arg(std::forward<A>(a))...);
385   }
386 
387   // Like Consume(), but does not anchor the match at the beginning of
388   // the text.  That is, "re" need not start its match at the beginning
389   // of "input".  For example, "FindAndConsume(s, "(\\w+)", &word)" finds
390   // the next word in "s" and stores it in "word".
391   template <typename... A>
FindAndConsume(StringPiece * input,const RE2 & re,A &&...a)392   static bool FindAndConsume(StringPiece* input, const RE2& re, A&&... a) {
393     return Apply(FindAndConsumeN, input, re, Arg(std::forward<A>(a))...);
394   }
395 #endif
396 
397   // Replace the first match of "re" in "str" with "rewrite".
398   // Within "rewrite", backslash-escaped digits (\1 to \9) can be
399   // used to insert text matching corresponding parenthesized group
400   // from the pattern.  \0 in "rewrite" refers to the entire matching
401   // text.  E.g.,
402   //
403   //   std::string s = "yabba dabba doo";
404   //   CHECK(RE2::Replace(&s, "b+", "d"));
405   //
406   // will leave "s" containing "yada dabba doo"
407   //
408   // Returns true if the pattern matches and a replacement occurs,
409   // false otherwise.
410   static bool Replace(std::string* str,
411                       const RE2& re,
412                       const StringPiece& rewrite);
413 
414   // Like Replace(), except replaces successive non-overlapping occurrences
415   // of the pattern in the string with the rewrite. E.g.
416   //
417   //   std::string s = "yabba dabba doo";
418   //   CHECK(RE2::GlobalReplace(&s, "b+", "d"));
419   //
420   // will leave "s" containing "yada dada doo"
421   // Replacements are not subject to re-matching.
422   //
423   // Because GlobalReplace only replaces non-overlapping matches,
424   // replacing "ana" within "banana" makes only one replacement, not two.
425   //
426   // Returns the number of replacements made.
427   static int GlobalReplace(std::string* str,
428                            const RE2& re,
429                            const StringPiece& rewrite);
430 
431   // Like Replace, except that if the pattern matches, "rewrite"
432   // is copied into "out" with substitutions.  The non-matching
433   // portions of "text" are ignored.
434   //
435   // Returns true iff a match occurred and the extraction happened
436   // successfully;  if no match occurs, the string is left unaffected.
437   //
438   // REQUIRES: "text" must not alias any part of "*out".
439   static bool Extract(const StringPiece& text,
440                       const RE2& re,
441                       const StringPiece& rewrite,
442                       std::string* out);
443 
444   // Escapes all potentially meaningful regexp characters in
445   // 'unquoted'.  The returned string, used as a regular expression,
446   // will exactly match the original string.  For example,
447   //           1.5-2.0?
448   // may become:
449   //           1\.5\-2\.0\?
450   static std::string QuoteMeta(const StringPiece& unquoted);
451 
452   // Computes range for any strings matching regexp. The min and max can in
453   // some cases be arbitrarily precise, so the caller gets to specify the
454   // maximum desired length of string returned.
455   //
456   // Assuming PossibleMatchRange(&min, &max, N) returns successfully, any
457   // string s that is an anchored match for this regexp satisfies
458   //   min <= s && s <= max.
459   //
460   // Note that PossibleMatchRange() will only consider the first copy of an
461   // infinitely repeated element (i.e., any regexp element followed by a '*' or
462   // '+' operator). Regexps with "{N}" constructions are not affected, as those
463   // do not compile down to infinite repetitions.
464   //
465   // Returns true on success, false on error.
466   bool PossibleMatchRange(std::string* min, std::string* max,
467                           int maxlen) const;
468 
469   // Generic matching interface
470 
471   // Type of match.
472   enum Anchor {
473     UNANCHORED,         // No anchoring
474     ANCHOR_START,       // Anchor at start only
475     ANCHOR_BOTH         // Anchor at start and end
476   };
477 
478   // Return the number of capturing subpatterns, or -1 if the
479   // regexp wasn't valid on construction.  The overall match ($0)
480   // does not count: if the regexp is "(a)(b)", returns 2.
NumberOfCapturingGroups()481   int NumberOfCapturingGroups() const { return num_captures_; }
482 
483   // Return a map from names to capturing indices.
484   // The map records the index of the leftmost group
485   // with the given name.
486   // Only valid until the re is deleted.
487   const std::map<std::string, int>& NamedCapturingGroups() const;
488 
489   // Return a map from capturing indices to names.
490   // The map has no entries for unnamed groups.
491   // Only valid until the re is deleted.
492   const std::map<int, std::string>& CapturingGroupNames() const;
493 
494   // General matching routine.
495   // Match against text starting at offset startpos
496   // and stopping the search at offset endpos.
497   // Returns true if match found, false if not.
498   // On a successful match, fills in submatch[] (up to nsubmatch entries)
499   // with information about submatches.
500   // I.e. matching RE2("(foo)|(bar)baz") on "barbazbla" will return true, with
501   // submatch[0] = "barbaz", submatch[1].data() = NULL, submatch[2] = "bar",
502   // submatch[3].data() = NULL, ..., up to submatch[nsubmatch-1].data() = NULL.
503   // Caveat: submatch[] may be clobbered even on match failure.
504   //
505   // Don't ask for more match information than you will use:
506   // runs much faster with nsubmatch == 1 than nsubmatch > 1, and
507   // runs even faster if nsubmatch == 0.
508   // Doesn't make sense to use nsubmatch > 1 + NumberOfCapturingGroups(),
509   // but will be handled correctly.
510   //
511   // Passing text == StringPiece(NULL, 0) will be handled like any other
512   // empty string, but note that on return, it will not be possible to tell
513   // whether submatch i matched the empty string or did not match:
514   // either way, submatch[i].data() == NULL.
515   bool Match(const StringPiece& text,
516              size_t startpos,
517              size_t endpos,
518              Anchor re_anchor,
519              StringPiece* submatch,
520              int nsubmatch) const;
521 
522   // Check that the given rewrite string is suitable for use with this
523   // regular expression.  It checks that:
524   //   * The regular expression has enough parenthesized subexpressions
525   //     to satisfy all of the \N tokens in rewrite
526   //   * The rewrite string doesn't have any syntax errors.  E.g.,
527   //     '\' followed by anything other than a digit or '\'.
528   // A true return value guarantees that Replace() and Extract() won't
529   // fail because of a bad rewrite string.
530   bool CheckRewriteString(const StringPiece& rewrite,
531                           std::string* error) const;
532 
533   // Returns the maximum submatch needed for the rewrite to be done by
534   // Replace(). E.g. if rewrite == "foo \\2,\\1", returns 2.
535   static int MaxSubmatch(const StringPiece& rewrite);
536 
537   // Append the "rewrite" string, with backslash subsitutions from "vec",
538   // to string "out".
539   // Returns true on success.  This method can fail because of a malformed
540   // rewrite string.  CheckRewriteString guarantees that the rewrite will
541   // be sucessful.
542   bool Rewrite(std::string* out,
543                const StringPiece& rewrite,
544                const StringPiece* vec,
545                int veclen) const;
546 
547   // Constructor options
548   class Options {
549    public:
550     // The options are (defaults in parentheses):
551     //
552     //   utf8             (true)  text and pattern are UTF-8; otherwise Latin-1
553     //   posix_syntax     (false) restrict regexps to POSIX egrep syntax
554     //   longest_match    (false) search for longest match, not first match
555     //   log_errors       (true)  log syntax and execution errors to ERROR
556     //   max_mem          (see below)  approx. max memory footprint of RE2
557     //   literal          (false) interpret string as literal, not regexp
558     //   never_nl         (false) never match \n, even if it is in regexp
559     //   dot_nl           (false) dot matches everything including new line
560     //   never_capture    (false) parse all parens as non-capturing
561     //   case_sensitive   (true)  match is case-sensitive (regexp can override
562     //                              with (?i) unless in posix_syntax mode)
563     //
564     // The following options are only consulted when posix_syntax == true.
565     // When posix_syntax == false, these features are always enabled and
566     // cannot be turned off; to perform multi-line matching in that case,
567     // begin the regexp with (?m).
568     //   perl_classes     (false) allow Perl's \d \s \w \D \S \W
569     //   word_boundary    (false) allow Perl's \b \B (word boundary and not)
570     //   one_line         (false) ^ and $ only match beginning and end of text
571     //
572     // The max_mem option controls how much memory can be used
573     // to hold the compiled form of the regexp (the Prog) and
574     // its cached DFA graphs.  Code Search placed limits on the number
575     // of Prog instructions and DFA states: 10,000 for both.
576     // In RE2, those limits would translate to about 240 KB per Prog
577     // and perhaps 2.5 MB per DFA (DFA state sizes vary by regexp; RE2 does a
578     // better job of keeping them small than Code Search did).
579     // Each RE2 has two Progs (one forward, one reverse), and each Prog
580     // can have two DFAs (one first match, one longest match).
581     // That makes 4 DFAs:
582     //
583     //   forward, first-match    - used for UNANCHORED or ANCHOR_START searches
584     //                               if opt.longest_match() == false
585     //   forward, longest-match  - used for all ANCHOR_BOTH searches,
586     //                               and the other two kinds if
587     //                               opt.longest_match() == true
588     //   reverse, first-match    - never used
589     //   reverse, longest-match  - used as second phase for unanchored searches
590     //
591     // The RE2 memory budget is statically divided between the two
592     // Progs and then the DFAs: two thirds to the forward Prog
593     // and one third to the reverse Prog.  The forward Prog gives half
594     // of what it has left over to each of its DFAs.  The reverse Prog
595     // gives it all to its longest-match DFA.
596     //
597     // Once a DFA fills its budget, it flushes its cache and starts over.
598     // If this happens too often, RE2 falls back on the NFA implementation.
599 
600     // For now, make the default budget something close to Code Search.
601     static const int kDefaultMaxMem = 8<<20;
602 
603     enum Encoding {
604       EncodingUTF8 = 1,
605       EncodingLatin1
606     };
607 
Options()608     Options() :
609       encoding_(EncodingUTF8),
610       posix_syntax_(false),
611       longest_match_(false),
612       log_errors_(true),
613       max_mem_(kDefaultMaxMem),
614       literal_(false),
615       never_nl_(false),
616       dot_nl_(false),
617       never_capture_(false),
618       case_sensitive_(true),
619       perl_classes_(false),
620       word_boundary_(false),
621       one_line_(false) {
622     }
623 
624     /*implicit*/ Options(CannedOptions);
625 
encoding()626     Encoding encoding() const { return encoding_; }
set_encoding(Encoding encoding)627     void set_encoding(Encoding encoding) { encoding_ = encoding; }
628 
629     // Legacy interface to encoding.
630     // TODO(rsc): Remove once clients have been converted.
utf8()631     bool utf8() const { return encoding_ == EncodingUTF8; }
set_utf8(bool b)632     void set_utf8(bool b) {
633       if (b) {
634         encoding_ = EncodingUTF8;
635       } else {
636         encoding_ = EncodingLatin1;
637       }
638     }
639 
posix_syntax()640     bool posix_syntax() const { return posix_syntax_; }
set_posix_syntax(bool b)641     void set_posix_syntax(bool b) { posix_syntax_ = b; }
642 
longest_match()643     bool longest_match() const { return longest_match_; }
set_longest_match(bool b)644     void set_longest_match(bool b) { longest_match_ = b; }
645 
log_errors()646     bool log_errors() const { return log_errors_; }
set_log_errors(bool b)647     void set_log_errors(bool b) { log_errors_ = b; }
648 
max_mem()649     int64_t max_mem() const { return max_mem_; }
set_max_mem(int64_t m)650     void set_max_mem(int64_t m) { max_mem_ = m; }
651 
literal()652     bool literal() const { return literal_; }
set_literal(bool b)653     void set_literal(bool b) { literal_ = b; }
654 
never_nl()655     bool never_nl() const { return never_nl_; }
set_never_nl(bool b)656     void set_never_nl(bool b) { never_nl_ = b; }
657 
dot_nl()658     bool dot_nl() const { return dot_nl_; }
set_dot_nl(bool b)659     void set_dot_nl(bool b) { dot_nl_ = b; }
660 
never_capture()661     bool never_capture() const { return never_capture_; }
set_never_capture(bool b)662     void set_never_capture(bool b) { never_capture_ = b; }
663 
case_sensitive()664     bool case_sensitive() const { return case_sensitive_; }
set_case_sensitive(bool b)665     void set_case_sensitive(bool b) { case_sensitive_ = b; }
666 
perl_classes()667     bool perl_classes() const { return perl_classes_; }
set_perl_classes(bool b)668     void set_perl_classes(bool b) { perl_classes_ = b; }
669 
word_boundary()670     bool word_boundary() const { return word_boundary_; }
set_word_boundary(bool b)671     void set_word_boundary(bool b) { word_boundary_ = b; }
672 
one_line()673     bool one_line() const { return one_line_; }
set_one_line(bool b)674     void set_one_line(bool b) { one_line_ = b; }
675 
Copy(const Options & src)676     void Copy(const Options& src) {
677       *this = src;
678     }
679 
680     int ParseFlags() const;
681 
682    private:
683     Encoding encoding_;
684     bool posix_syntax_;
685     bool longest_match_;
686     bool log_errors_;
687     int64_t max_mem_;
688     bool literal_;
689     bool never_nl_;
690     bool dot_nl_;
691     bool never_capture_;
692     bool case_sensitive_;
693     bool perl_classes_;
694     bool word_boundary_;
695     bool one_line_;
696   };
697 
698   // Returns the options set in the constructor.
options()699   const Options& options() const { return options_; }
700 
701   // Argument converters; see below.
702   static inline Arg CRadix(short* x);
703   static inline Arg CRadix(unsigned short* x);
704   static inline Arg CRadix(int* x);
705   static inline Arg CRadix(unsigned int* x);
706   static inline Arg CRadix(long* x);
707   static inline Arg CRadix(unsigned long* x);
708   static inline Arg CRadix(long long* x);
709   static inline Arg CRadix(unsigned long long* x);
710 
711   static inline Arg Hex(short* x);
712   static inline Arg Hex(unsigned short* x);
713   static inline Arg Hex(int* x);
714   static inline Arg Hex(unsigned int* x);
715   static inline Arg Hex(long* x);
716   static inline Arg Hex(unsigned long* x);
717   static inline Arg Hex(long long* x);
718   static inline Arg Hex(unsigned long long* x);
719 
720   static inline Arg Octal(short* x);
721   static inline Arg Octal(unsigned short* x);
722   static inline Arg Octal(int* x);
723   static inline Arg Octal(unsigned int* x);
724   static inline Arg Octal(long* x);
725   static inline Arg Octal(unsigned long* x);
726   static inline Arg Octal(long long* x);
727   static inline Arg Octal(unsigned long long* x);
728 
729  private:
730   void Init(const StringPiece& pattern, const Options& options);
731 
732   bool DoMatch(const StringPiece& text,
733                Anchor re_anchor,
734                size_t* consumed,
735                const Arg* const args[],
736                int n) const;
737 
738   re2::Prog* ReverseProg() const;
739 
740   std::string   pattern_;          // string regular expression
741   Options       options_;          // option flags
742   std::string   prefix_;           // required prefix (before regexp_)
743   bool          prefix_foldcase_;  // prefix is ASCII case-insensitive
744   re2::Regexp*  entire_regexp_;    // parsed regular expression
745   re2::Regexp*  suffix_regexp_;    // parsed regular expression, prefix removed
746   re2::Prog*    prog_;             // compiled program for regexp
747   int           num_captures_;     // Number of capturing groups
748   bool          is_one_pass_;      // can use prog_->SearchOnePass?
749 
750   mutable re2::Prog*          rprog_;    // reverse program for regexp
751   mutable const std::string*  error_;    // Error indicator
752                                          // (or points to empty string)
753   mutable ErrorCode      error_code_;    // Error code
754   mutable std::string    error_arg_;     // Fragment of regexp showing error
755 
756   // Map from capture names to indices
757   mutable const std::map<std::string, int>* named_groups_;
758 
759   // Map from capture indices to names
760   mutable const std::map<int, std::string>* group_names_;
761 
762   // Onces for lazy computations.
763   mutable std::once_flag rprog_once_;
764   mutable std::once_flag named_groups_once_;
765   mutable std::once_flag group_names_once_;
766 
767   RE2(const RE2&) = delete;
768   RE2& operator=(const RE2&) = delete;
769 };
770 
771 /***** Implementation details *****/
772 
773 // Hex/Octal/Binary?
774 
775 // Special class for parsing into objects that define a ParseFrom() method
776 template <class T>
777 class _RE2_MatchObject {
778  public:
Parse(const char * str,size_t n,void * dest)779   static inline bool Parse(const char* str, size_t n, void* dest) {
780     if (dest == NULL) return true;
781     T* object = reinterpret_cast<T*>(dest);
782     return object->ParseFrom(str, n);
783   }
784 };
785 
786 class RE2::Arg {
787  public:
788   // Empty constructor so we can declare arrays of RE2::Arg
789   Arg();
790 
791   // Constructor specially designed for NULL arguments
792   Arg(void*);
793   Arg(std::nullptr_t);
794 
795   typedef bool (*Parser)(const char* str, size_t n, void* dest);
796 
797 // Type-specific parsers
798 #define MAKE_PARSER(type, name)            \
799   Arg(type* p) : arg_(p), parser_(name) {} \
800   Arg(type* p, Parser parser) : arg_(p), parser_(parser) {}
801 
MAKE_PARSER(char,parse_char)802   MAKE_PARSER(char,               parse_char)
803   MAKE_PARSER(signed char,        parse_schar)
804   MAKE_PARSER(unsigned char,      parse_uchar)
805   MAKE_PARSER(float,              parse_float)
806   MAKE_PARSER(double,             parse_double)
807   MAKE_PARSER(std::string,        parse_string)
808   MAKE_PARSER(StringPiece,        parse_stringpiece)
809 
810   MAKE_PARSER(short,              parse_short)
811   MAKE_PARSER(unsigned short,     parse_ushort)
812   MAKE_PARSER(int,                parse_int)
813   MAKE_PARSER(unsigned int,       parse_uint)
814   MAKE_PARSER(long,               parse_long)
815   MAKE_PARSER(unsigned long,      parse_ulong)
816   MAKE_PARSER(long long,          parse_longlong)
817   MAKE_PARSER(unsigned long long, parse_ulonglong)
818 
819 #undef MAKE_PARSER
820 
821   // Generic constructor templates
822   template <class T> Arg(T* p)
823       : arg_(p), parser_(_RE2_MatchObject<T>::Parse) { }
Arg(T * p,Parser parser)824   template <class T> Arg(T* p, Parser parser)
825       : arg_(p), parser_(parser) { }
826 
827   // Parse the data
828   bool Parse(const char* str, size_t n) const;
829 
830  private:
831   void*         arg_;
832   Parser        parser_;
833 
834   static bool parse_null          (const char* str, size_t n, void* dest);
835   static bool parse_char          (const char* str, size_t n, void* dest);
836   static bool parse_schar         (const char* str, size_t n, void* dest);
837   static bool parse_uchar         (const char* str, size_t n, void* dest);
838   static bool parse_float         (const char* str, size_t n, void* dest);
839   static bool parse_double        (const char* str, size_t n, void* dest);
840   static bool parse_string        (const char* str, size_t n, void* dest);
841   static bool parse_stringpiece   (const char* str, size_t n, void* dest);
842 
843 #define DECLARE_INTEGER_PARSER(name)                                       \
844  private:                                                                  \
845   static bool parse_##name(const char* str, size_t n, void* dest);         \
846   static bool parse_##name##_radix(const char* str, size_t n, void* dest,  \
847                                    int radix);                             \
848                                                                            \
849  public:                                                                   \
850   static bool parse_##name##_hex(const char* str, size_t n, void* dest);   \
851   static bool parse_##name##_octal(const char* str, size_t n, void* dest); \
852   static bool parse_##name##_cradix(const char* str, size_t n, void* dest);
853 
854   DECLARE_INTEGER_PARSER(short)
855   DECLARE_INTEGER_PARSER(ushort)
856   DECLARE_INTEGER_PARSER(int)
857   DECLARE_INTEGER_PARSER(uint)
858   DECLARE_INTEGER_PARSER(long)
859   DECLARE_INTEGER_PARSER(ulong)
860   DECLARE_INTEGER_PARSER(longlong)
861   DECLARE_INTEGER_PARSER(ulonglong)
862 
863 #undef DECLARE_INTEGER_PARSER
864 
865 };
866 
Arg()867 inline RE2::Arg::Arg() : arg_(NULL), parser_(parse_null) { }
Arg(void * p)868 inline RE2::Arg::Arg(void* p) : arg_(p), parser_(parse_null) { }
Arg(std::nullptr_t p)869 inline RE2::Arg::Arg(std::nullptr_t p) : arg_(p), parser_(parse_null) { }
870 
Parse(const char * str,size_t n)871 inline bool RE2::Arg::Parse(const char* str, size_t n) const {
872   return (*parser_)(str, n, arg_);
873 }
874 
875 // This part of the parser, appropriate only for ints, deals with bases
876 #define MAKE_INTEGER_PARSER(type, name)                    \
877   inline RE2::Arg RE2::Hex(type* ptr) {                    \
878     return RE2::Arg(ptr, RE2::Arg::parse_##name##_hex);    \
879   }                                                        \
880   inline RE2::Arg RE2::Octal(type* ptr) {                  \
881     return RE2::Arg(ptr, RE2::Arg::parse_##name##_octal);  \
882   }                                                        \
883   inline RE2::Arg RE2::CRadix(type* ptr) {                 \
884     return RE2::Arg(ptr, RE2::Arg::parse_##name##_cradix); \
885   }
886 
MAKE_INTEGER_PARSER(short,short)887 MAKE_INTEGER_PARSER(short,              short)
888 MAKE_INTEGER_PARSER(unsigned short,     ushort)
889 MAKE_INTEGER_PARSER(int,                int)
890 MAKE_INTEGER_PARSER(unsigned int,       uint)
891 MAKE_INTEGER_PARSER(long,               long)
892 MAKE_INTEGER_PARSER(unsigned long,      ulong)
893 MAKE_INTEGER_PARSER(long long,          longlong)
894 MAKE_INTEGER_PARSER(unsigned long long, ulonglong)
895 
896 #undef MAKE_INTEGER_PARSER
897 
898 #ifndef SWIG
899 
900 // Silence warnings about missing initializers for members of LazyRE2.
901 // Note that we test for Clang first because it defines __GNUC__ as well.
902 #if defined(__clang__)
903 #elif defined(__GNUC__) && __GNUC__ >= 6
904 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
905 #endif
906 
907 // Helper for writing global or static RE2s safely.
908 // Write
909 //     static LazyRE2 re = {".*"};
910 // and then use *re instead of writing
911 //     static RE2 re(".*");
912 // The former is more careful about multithreaded
913 // situations than the latter.
914 //
915 // N.B. This class never deletes the RE2 object that
916 // it constructs: that's a feature, so that it can be used
917 // for global and function static variables.
918 class LazyRE2 {
919  private:
920   struct NoArg {};
921 
922  public:
923   typedef RE2 element_type;  // support std::pointer_traits
924 
925   // Constructor omitted to preserve braced initialization in C++98.
926 
927   // Pretend to be a pointer to Type (never NULL due to on-demand creation):
928   RE2& operator*() const { return *get(); }
929   RE2* operator->() const { return get(); }
930 
931   // Named accessor/initializer:
932   RE2* get() const {
933     std::call_once(once_, &LazyRE2::Init, this);
934     return ptr_;
935   }
936 
937   // All data fields must be public to support {"foo"} initialization.
938   const char* pattern_;
939   RE2::CannedOptions options_;
940   NoArg barrier_against_excess_initializers_;
941 
942   mutable RE2* ptr_;
943   mutable std::once_flag once_;
944 
945  private:
946   static void Init(const LazyRE2* lazy_re2) {
947     lazy_re2->ptr_ = new RE2(lazy_re2->pattern_, lazy_re2->options_);
948   }
949 
950   void operator=(const LazyRE2&);  // disallowed
951 };
952 #endif  // SWIG
953 
954 }  // namespace re2
955 
956 using re2::RE2;
957 using re2::LazyRE2;
958 
959 #endif  // RE2_RE2_H_
960