Warning: That file was not part of the compilation database. It may have many parsing errors.

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

Warning: That file was not part of the compilation database. It may have many parsing errors.