You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

re2.h 45 kB

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