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