re2.h 39 KB

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