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