re2.carbon 40 KB

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