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