Coverage Report

Created: 2025-12-31 06:56

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