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