regex.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifndef RAPIDJSON_INTERNAL_REGEX_H_
  15. #define RAPIDJSON_INTERNAL_REGEX_H_
  16. #include "../allocators.h"
  17. #include "../stream.h"
  18. #include "stack.h"
  19. #ifdef __clang__
  20. RAPIDJSON_DIAG_PUSH
  21. RAPIDJSON_DIAG_OFF(padded)
  22. RAPIDJSON_DIAG_OFF(switch-enum)
  23. RAPIDJSON_DIAG_OFF(implicit-fallthrough)
  24. #elif defined(_MSC_VER)
  25. RAPIDJSON_DIAG_PUSH
  26. RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
  27. #endif
  28. #ifdef __GNUC__
  29. RAPIDJSON_DIAG_PUSH
  30. RAPIDJSON_DIAG_OFF(effc++)
  31. #if __GNUC__ >= 7
  32. RAPIDJSON_DIAG_OFF(implicit-fallthrough)
  33. #endif
  34. #endif
  35. #ifndef RAPIDJSON_REGEX_VERBOSE
  36. #define RAPIDJSON_REGEX_VERBOSE 0
  37. #endif
  38. RAPIDJSON_NAMESPACE_BEGIN
  39. namespace internal {
  40. ///////////////////////////////////////////////////////////////////////////////
  41. // DecodedStream
  42. template <typename SourceStream, typename Encoding>
  43. class DecodedStream {
  44. public:
  45. DecodedStream(SourceStream& ss) : ss_(ss), codepoint_() { Decode(); }
  46. unsigned Peek() { return codepoint_; }
  47. unsigned Take() {
  48. unsigned c = codepoint_;
  49. if (c) // No further decoding when '\0'
  50. Decode();
  51. return c;
  52. }
  53. private:
  54. void Decode() {
  55. if (!Encoding::Decode(ss_, &codepoint_))
  56. codepoint_ = 0;
  57. }
  58. SourceStream& ss_;
  59. unsigned codepoint_;
  60. };
  61. ///////////////////////////////////////////////////////////////////////////////
  62. // GenericRegex
  63. static const SizeType kRegexInvalidState = ~SizeType(0); //!< Represents an invalid index in GenericRegex::State::out, out1
  64. static const SizeType kRegexInvalidRange = ~SizeType(0);
  65. template <typename Encoding, typename Allocator>
  66. class GenericRegexSearch;
  67. //! Regular expression engine with subset of ECMAscript grammar.
  68. /*!
  69. Supported regular expression syntax:
  70. - \c ab Concatenation
  71. - \c a|b Alternation
  72. - \c a? Zero or one
  73. - \c a* Zero or more
  74. - \c a+ One or more
  75. - \c a{3} Exactly 3 times
  76. - \c a{3,} At least 3 times
  77. - \c a{3,5} 3 to 5 times
  78. - \c (ab) Grouping
  79. - \c ^a At the beginning
  80. - \c a$ At the end
  81. - \c . Any character
  82. - \c [abc] Character classes
  83. - \c [a-c] Character class range
  84. - \c [a-z0-9_] Character class combination
  85. - \c [^abc] Negated character classes
  86. - \c [^a-c] Negated character class range
  87. - \c [\b] Backspace (U+0008)
  88. - \c \\| \\\\ ... Escape characters
  89. - \c \\f Form feed (U+000C)
  90. - \c \\n Line feed (U+000A)
  91. - \c \\r Carriage return (U+000D)
  92. - \c \\t Tab (U+0009)
  93. - \c \\v Vertical tab (U+000B)
  94. \note This is a Thompson NFA engine, implemented with reference to
  95. Cox, Russ. "Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby,...).",
  96. https://swtch.com/~rsc/regexp/regexp1.html
  97. */
  98. template <typename Encoding, typename Allocator = CrtAllocator>
  99. class GenericRegex {
  100. public:
  101. typedef Encoding EncodingType;
  102. typedef typename Encoding::Ch Ch;
  103. template <typename, typename> friend class GenericRegexSearch;
  104. GenericRegex(const Ch* source, Allocator* allocator = 0) :
  105. states_(allocator, 256), ranges_(allocator, 256), root_(kRegexInvalidState), stateCount_(), rangeCount_(),
  106. anchorBegin_(), anchorEnd_()
  107. {
  108. GenericStringStream<Encoding> ss(source);
  109. DecodedStream<GenericStringStream<Encoding>, Encoding> ds(ss);
  110. Parse(ds);
  111. }
  112. ~GenericRegex() {}
  113. bool IsValid() const {
  114. return root_ != kRegexInvalidState;
  115. }
  116. private:
  117. enum Operator {
  118. kZeroOrOne,
  119. kZeroOrMore,
  120. kOneOrMore,
  121. kConcatenation,
  122. kAlternation,
  123. kLeftParenthesis
  124. };
  125. static const unsigned kAnyCharacterClass = 0xFFFFFFFF; //!< For '.'
  126. static const unsigned kRangeCharacterClass = 0xFFFFFFFE;
  127. static const unsigned kRangeNegationFlag = 0x80000000;
  128. struct Range {
  129. unsigned start; //
  130. unsigned end;
  131. SizeType next;
  132. };
  133. struct State {
  134. SizeType out; //!< Equals to kInvalid for matching state
  135. SizeType out1; //!< Equals to non-kInvalid for split
  136. SizeType rangeStart;
  137. unsigned codepoint;
  138. };
  139. struct Frag {
  140. Frag(SizeType s, SizeType o, SizeType m) : start(s), out(o), minIndex(m) {}
  141. SizeType start;
  142. SizeType out; //!< link-list of all output states
  143. SizeType minIndex;
  144. };
  145. State& GetState(SizeType index) {
  146. RAPIDJSON_ASSERT(index < stateCount_);
  147. return states_.template Bottom<State>()[index];
  148. }
  149. const State& GetState(SizeType index) const {
  150. RAPIDJSON_ASSERT(index < stateCount_);
  151. return states_.template Bottom<State>()[index];
  152. }
  153. Range& GetRange(SizeType index) {
  154. RAPIDJSON_ASSERT(index < rangeCount_);
  155. return ranges_.template Bottom<Range>()[index];
  156. }
  157. const Range& GetRange(SizeType index) const {
  158. RAPIDJSON_ASSERT(index < rangeCount_);
  159. return ranges_.template Bottom<Range>()[index];
  160. }
  161. template <typename InputStream>
  162. void Parse(DecodedStream<InputStream, Encoding>& ds) {
  163. Allocator allocator;
  164. Stack<Allocator> operandStack(&allocator, 256); // Frag
  165. Stack<Allocator> operatorStack(&allocator, 256); // Operator
  166. Stack<Allocator> atomCountStack(&allocator, 256); // unsigned (Atom per parenthesis)
  167. *atomCountStack.template Push<unsigned>() = 0;
  168. unsigned codepoint;
  169. while (ds.Peek() != 0) {
  170. switch (codepoint = ds.Take()) {
  171. case '^':
  172. anchorBegin_ = true;
  173. break;
  174. case '$':
  175. anchorEnd_ = true;
  176. break;
  177. case '|':
  178. while (!operatorStack.Empty() && *operatorStack.template Top<Operator>() < kAlternation)
  179. if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
  180. return;
  181. *operatorStack.template Push<Operator>() = kAlternation;
  182. *atomCountStack.template Top<unsigned>() = 0;
  183. break;
  184. case '(':
  185. *operatorStack.template Push<Operator>() = kLeftParenthesis;
  186. *atomCountStack.template Push<unsigned>() = 0;
  187. break;
  188. case ')':
  189. while (!operatorStack.Empty() && *operatorStack.template Top<Operator>() != kLeftParenthesis)
  190. if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
  191. return;
  192. if (operatorStack.Empty())
  193. return;
  194. operatorStack.template Pop<Operator>(1);
  195. atomCountStack.template Pop<unsigned>(1);
  196. ImplicitConcatenation(atomCountStack, operatorStack);
  197. break;
  198. case '?':
  199. if (!Eval(operandStack, kZeroOrOne))
  200. return;
  201. break;
  202. case '*':
  203. if (!Eval(operandStack, kZeroOrMore))
  204. return;
  205. break;
  206. case '+':
  207. if (!Eval(operandStack, kOneOrMore))
  208. return;
  209. break;
  210. case '{':
  211. {
  212. unsigned n, m;
  213. if (!ParseUnsigned(ds, &n))
  214. return;
  215. if (ds.Peek() == ',') {
  216. ds.Take();
  217. if (ds.Peek() == '}')
  218. m = kInfinityQuantifier;
  219. else if (!ParseUnsigned(ds, &m) || m < n)
  220. return;
  221. }
  222. else
  223. m = n;
  224. if (!EvalQuantifier(operandStack, n, m) || ds.Peek() != '}')
  225. return;
  226. ds.Take();
  227. }
  228. break;
  229. case '.':
  230. PushOperand(operandStack, kAnyCharacterClass);
  231. ImplicitConcatenation(atomCountStack, operatorStack);
  232. break;
  233. case '[':
  234. {
  235. SizeType range;
  236. if (!ParseRange(ds, &range))
  237. return;
  238. SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, kRangeCharacterClass);
  239. GetState(s).rangeStart = range;
  240. *operandStack.template Push<Frag>() = Frag(s, s, s);
  241. }
  242. ImplicitConcatenation(atomCountStack, operatorStack);
  243. break;
  244. case '\\': // Escape character
  245. if (!CharacterEscape(ds, &codepoint))
  246. return; // Unsupported escape character
  247. // fall through to default
  248. default: // Pattern character
  249. PushOperand(operandStack, codepoint);
  250. ImplicitConcatenation(atomCountStack, operatorStack);
  251. }
  252. }
  253. while (!operatorStack.Empty())
  254. if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
  255. return;
  256. // Link the operand to matching state.
  257. if (operandStack.GetSize() == sizeof(Frag)) {
  258. Frag* e = operandStack.template Pop<Frag>(1);
  259. Patch(e->out, NewState(kRegexInvalidState, kRegexInvalidState, 0));
  260. root_ = e->start;
  261. #if RAPIDJSON_REGEX_VERBOSE
  262. printf("root: %d\n", root_);
  263. for (SizeType i = 0; i < stateCount_ ; i++) {
  264. State& s = GetState(i);
  265. printf("[%2d] out: %2d out1: %2d c: '%c'\n", i, s.out, s.out1, (char)s.codepoint);
  266. }
  267. printf("\n");
  268. #endif
  269. }
  270. }
  271. SizeType NewState(SizeType out, SizeType out1, unsigned codepoint) {
  272. State* s = states_.template Push<State>();
  273. s->out = out;
  274. s->out1 = out1;
  275. s->codepoint = codepoint;
  276. s->rangeStart = kRegexInvalidRange;
  277. return stateCount_++;
  278. }
  279. void PushOperand(Stack<Allocator>& operandStack, unsigned codepoint) {
  280. SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, codepoint);
  281. *operandStack.template Push<Frag>() = Frag(s, s, s);
  282. }
  283. void ImplicitConcatenation(Stack<Allocator>& atomCountStack, Stack<Allocator>& operatorStack) {
  284. if (*atomCountStack.template Top<unsigned>())
  285. *operatorStack.template Push<Operator>() = kConcatenation;
  286. (*atomCountStack.template Top<unsigned>())++;
  287. }
  288. SizeType Append(SizeType l1, SizeType l2) {
  289. SizeType old = l1;
  290. while (GetState(l1).out != kRegexInvalidState)
  291. l1 = GetState(l1).out;
  292. GetState(l1).out = l2;
  293. return old;
  294. }
  295. void Patch(SizeType l, SizeType s) {
  296. for (SizeType next; l != kRegexInvalidState; l = next) {
  297. next = GetState(l).out;
  298. GetState(l).out = s;
  299. }
  300. }
  301. bool Eval(Stack<Allocator>& operandStack, Operator op) {
  302. switch (op) {
  303. case kConcatenation:
  304. RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag) * 2);
  305. {
  306. Frag e2 = *operandStack.template Pop<Frag>(1);
  307. Frag e1 = *operandStack.template Pop<Frag>(1);
  308. Patch(e1.out, e2.start);
  309. *operandStack.template Push<Frag>() = Frag(e1.start, e2.out, Min(e1.minIndex, e2.minIndex));
  310. }
  311. return true;
  312. case kAlternation:
  313. if (operandStack.GetSize() >= sizeof(Frag) * 2) {
  314. Frag e2 = *operandStack.template Pop<Frag>(1);
  315. Frag e1 = *operandStack.template Pop<Frag>(1);
  316. SizeType s = NewState(e1.start, e2.start, 0);
  317. *operandStack.template Push<Frag>() = Frag(s, Append(e1.out, e2.out), Min(e1.minIndex, e2.minIndex));
  318. return true;
  319. }
  320. return false;
  321. case kZeroOrOne:
  322. if (operandStack.GetSize() >= sizeof(Frag)) {
  323. Frag e = *operandStack.template Pop<Frag>(1);
  324. SizeType s = NewState(kRegexInvalidState, e.start, 0);
  325. *operandStack.template Push<Frag>() = Frag(s, Append(e.out, s), e.minIndex);
  326. return true;
  327. }
  328. return false;
  329. case kZeroOrMore:
  330. if (operandStack.GetSize() >= sizeof(Frag)) {
  331. Frag e = *operandStack.template Pop<Frag>(1);
  332. SizeType s = NewState(kRegexInvalidState, e.start, 0);
  333. Patch(e.out, s);
  334. *operandStack.template Push<Frag>() = Frag(s, s, e.minIndex);
  335. return true;
  336. }
  337. return false;
  338. default:
  339. RAPIDJSON_ASSERT(op == kOneOrMore);
  340. if (operandStack.GetSize() >= sizeof(Frag)) {
  341. Frag e = *operandStack.template Pop<Frag>(1);
  342. SizeType s = NewState(kRegexInvalidState, e.start, 0);
  343. Patch(e.out, s);
  344. *operandStack.template Push<Frag>() = Frag(e.start, s, e.minIndex);
  345. return true;
  346. }
  347. return false;
  348. }
  349. }
  350. bool EvalQuantifier(Stack<Allocator>& operandStack, unsigned n, unsigned m) {
  351. RAPIDJSON_ASSERT(n <= m);
  352. RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag));
  353. if (n == 0) {
  354. if (m == 0) // a{0} not support
  355. return false;
  356. else if (m == kInfinityQuantifier)
  357. Eval(operandStack, kZeroOrMore); // a{0,} -> a*
  358. else {
  359. Eval(operandStack, kZeroOrOne); // a{0,5} -> a?
  360. for (unsigned i = 0; i < m - 1; i++)
  361. CloneTopOperand(operandStack); // a{0,5} -> a? a? a? a? a?
  362. for (unsigned i = 0; i < m - 1; i++)
  363. Eval(operandStack, kConcatenation); // a{0,5} -> a?a?a?a?a?
  364. }
  365. return true;
  366. }
  367. for (unsigned i = 0; i < n - 1; i++) // a{3} -> a a a
  368. CloneTopOperand(operandStack);
  369. if (m == kInfinityQuantifier)
  370. Eval(operandStack, kOneOrMore); // a{3,} -> a a a+
  371. else if (m > n) {
  372. CloneTopOperand(operandStack); // a{3,5} -> a a a a
  373. Eval(operandStack, kZeroOrOne); // a{3,5} -> a a a a?
  374. for (unsigned i = n; i < m - 1; i++)
  375. CloneTopOperand(operandStack); // a{3,5} -> a a a a? a?
  376. for (unsigned i = n; i < m; i++)
  377. Eval(operandStack, kConcatenation); // a{3,5} -> a a aa?a?
  378. }
  379. for (unsigned i = 0; i < n - 1; i++)
  380. Eval(operandStack, kConcatenation); // a{3} -> aaa, a{3,} -> aaa+, a{3.5} -> aaaa?a?
  381. return true;
  382. }
  383. static SizeType Min(SizeType a, SizeType b) { return a < b ? a : b; }
  384. void CloneTopOperand(Stack<Allocator>& operandStack) {
  385. const Frag src = *operandStack.template Top<Frag>(); // Copy constructor to prevent invalidation
  386. SizeType count = stateCount_ - src.minIndex; // Assumes top operand contains states in [src->minIndex, stateCount_)
  387. State* s = states_.template Push<State>(count);
  388. memcpy(s, &GetState(src.minIndex), count * sizeof(State));
  389. for (SizeType j = 0; j < count; j++) {
  390. if (s[j].out != kRegexInvalidState)
  391. s[j].out += count;
  392. if (s[j].out1 != kRegexInvalidState)
  393. s[j].out1 += count;
  394. }
  395. *operandStack.template Push<Frag>() = Frag(src.start + count, src.out + count, src.minIndex + count);
  396. stateCount_ += count;
  397. }
  398. template <typename InputStream>
  399. bool ParseUnsigned(DecodedStream<InputStream, Encoding>& ds, unsigned* u) {
  400. unsigned r = 0;
  401. if (ds.Peek() < '0' || ds.Peek() > '9')
  402. return false;
  403. while (ds.Peek() >= '0' && ds.Peek() <= '9') {
  404. if (r >= 429496729 && ds.Peek() > '5') // 2^32 - 1 = 4294967295
  405. return false; // overflow
  406. r = r * 10 + (ds.Take() - '0');
  407. }
  408. *u = r;
  409. return true;
  410. }
  411. template <typename InputStream>
  412. bool ParseRange(DecodedStream<InputStream, Encoding>& ds, SizeType* range) {
  413. bool isBegin = true;
  414. bool negate = false;
  415. int step = 0;
  416. SizeType start = kRegexInvalidRange;
  417. SizeType current = kRegexInvalidRange;
  418. unsigned codepoint;
  419. while ((codepoint = ds.Take()) != 0) {
  420. if (isBegin) {
  421. isBegin = false;
  422. if (codepoint == '^') {
  423. negate = true;
  424. continue;
  425. }
  426. }
  427. switch (codepoint) {
  428. case ']':
  429. if (start == kRegexInvalidRange)
  430. return false; // Error: nothing inside []
  431. if (step == 2) { // Add trailing '-'
  432. SizeType r = NewRange('-');
  433. RAPIDJSON_ASSERT(current != kRegexInvalidRange);
  434. GetRange(current).next = r;
  435. }
  436. if (negate)
  437. GetRange(start).start |= kRangeNegationFlag;
  438. *range = start;
  439. return true;
  440. case '\\':
  441. if (ds.Peek() == 'b') {
  442. ds.Take();
  443. codepoint = 0x0008; // Escape backspace character
  444. }
  445. else if (!CharacterEscape(ds, &codepoint))
  446. return false;
  447. // fall through to default
  448. default:
  449. switch (step) {
  450. case 1:
  451. if (codepoint == '-') {
  452. step++;
  453. break;
  454. }
  455. // fall through to step 0 for other characters
  456. case 0:
  457. {
  458. SizeType r = NewRange(codepoint);
  459. if (current != kRegexInvalidRange)
  460. GetRange(current).next = r;
  461. if (start == kRegexInvalidRange)
  462. start = r;
  463. current = r;
  464. }
  465. step = 1;
  466. break;
  467. default:
  468. RAPIDJSON_ASSERT(step == 2);
  469. GetRange(current).end = codepoint;
  470. step = 0;
  471. }
  472. }
  473. }
  474. return false;
  475. }
  476. SizeType NewRange(unsigned codepoint) {
  477. Range* r = ranges_.template Push<Range>();
  478. r->start = r->end = codepoint;
  479. r->next = kRegexInvalidRange;
  480. return rangeCount_++;
  481. }
  482. template <typename InputStream>
  483. bool CharacterEscape(DecodedStream<InputStream, Encoding>& ds, unsigned* escapedCodepoint) {
  484. unsigned codepoint;
  485. switch (codepoint = ds.Take()) {
  486. case '^':
  487. case '$':
  488. case '|':
  489. case '(':
  490. case ')':
  491. case '?':
  492. case '*':
  493. case '+':
  494. case '.':
  495. case '[':
  496. case ']':
  497. case '{':
  498. case '}':
  499. case '\\':
  500. *escapedCodepoint = codepoint; return true;
  501. case 'f': *escapedCodepoint = 0x000C; return true;
  502. case 'n': *escapedCodepoint = 0x000A; return true;
  503. case 'r': *escapedCodepoint = 0x000D; return true;
  504. case 't': *escapedCodepoint = 0x0009; return true;
  505. case 'v': *escapedCodepoint = 0x000B; return true;
  506. default:
  507. return false; // Unsupported escape character
  508. }
  509. }
  510. Stack<Allocator> states_;
  511. Stack<Allocator> ranges_;
  512. SizeType root_;
  513. SizeType stateCount_;
  514. SizeType rangeCount_;
  515. static const unsigned kInfinityQuantifier = ~0u;
  516. // For SearchWithAnchoring()
  517. bool anchorBegin_;
  518. bool anchorEnd_;
  519. };
  520. template <typename RegexType, typename Allocator = CrtAllocator>
  521. class GenericRegexSearch {
  522. public:
  523. typedef typename RegexType::EncodingType Encoding;
  524. typedef typename Encoding::Ch Ch;
  525. GenericRegexSearch(const RegexType& regex, Allocator* allocator = 0) :
  526. regex_(regex), allocator_(allocator), ownAllocator_(0),
  527. state0_(allocator, 0), state1_(allocator, 0), stateSet_()
  528. {
  529. RAPIDJSON_ASSERT(regex_.IsValid());
  530. if (!allocator_)
  531. ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
  532. stateSet_ = static_cast<unsigned*>(allocator_->Malloc(GetStateSetSize()));
  533. state0_.template Reserve<SizeType>(regex_.stateCount_);
  534. state1_.template Reserve<SizeType>(regex_.stateCount_);
  535. }
  536. ~GenericRegexSearch() {
  537. Allocator::Free(stateSet_);
  538. RAPIDJSON_DELETE(ownAllocator_);
  539. }
  540. template <typename InputStream>
  541. bool Match(InputStream& is) {
  542. return SearchWithAnchoring(is, true, true);
  543. }
  544. bool Match(const Ch* s) {
  545. GenericStringStream<Encoding> is(s);
  546. return Match(is);
  547. }
  548. template <typename InputStream>
  549. bool Search(InputStream& is) {
  550. return SearchWithAnchoring(is, regex_.anchorBegin_, regex_.anchorEnd_);
  551. }
  552. bool Search(const Ch* s) {
  553. GenericStringStream<Encoding> is(s);
  554. return Search(is);
  555. }
  556. private:
  557. typedef typename RegexType::State State;
  558. typedef typename RegexType::Range Range;
  559. template <typename InputStream>
  560. bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) {
  561. DecodedStream<InputStream, Encoding> ds(is);
  562. state0_.Clear();
  563. Stack<Allocator> *current = &state0_, *next = &state1_;
  564. const size_t stateSetSize = GetStateSetSize();
  565. std::memset(stateSet_, 0, stateSetSize);
  566. bool matched = AddState(*current, regex_.root_);
  567. unsigned codepoint;
  568. while (!current->Empty() && (codepoint = ds.Take()) != 0) {
  569. std::memset(stateSet_, 0, stateSetSize);
  570. next->Clear();
  571. matched = false;
  572. for (const SizeType* s = current->template Bottom<SizeType>(); s != current->template End<SizeType>(); ++s) {
  573. const State& sr = regex_.GetState(*s);
  574. if (sr.codepoint == codepoint ||
  575. sr.codepoint == RegexType::kAnyCharacterClass ||
  576. (sr.codepoint == RegexType::kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint)))
  577. {
  578. matched = AddState(*next, sr.out) || matched;
  579. if (!anchorEnd && matched)
  580. return true;
  581. }
  582. if (!anchorBegin)
  583. AddState(*next, regex_.root_);
  584. }
  585. internal::Swap(current, next);
  586. }
  587. return matched;
  588. }
  589. size_t GetStateSetSize() const {
  590. return (regex_.stateCount_ + 31) / 32 * 4;
  591. }
  592. // Return whether the added states is a match state
  593. bool AddState(Stack<Allocator>& l, SizeType index) {
  594. RAPIDJSON_ASSERT(index != kRegexInvalidState);
  595. const State& s = regex_.GetState(index);
  596. if (s.out1 != kRegexInvalidState) { // Split
  597. bool matched = AddState(l, s.out);
  598. return AddState(l, s.out1) || matched;
  599. }
  600. else if (!(stateSet_[index >> 5] & (1u << (index & 31)))) {
  601. stateSet_[index >> 5] |= (1u << (index & 31));
  602. *l.template PushUnsafe<SizeType>() = index;
  603. }
  604. return s.out == kRegexInvalidState; // by using PushUnsafe() above, we can ensure s is not validated due to reallocation.
  605. }
  606. bool MatchRange(SizeType rangeIndex, unsigned codepoint) const {
  607. bool yes = (regex_.GetRange(rangeIndex).start & RegexType::kRangeNegationFlag) == 0;
  608. while (rangeIndex != kRegexInvalidRange) {
  609. const Range& r = regex_.GetRange(rangeIndex);
  610. if (codepoint >= (r.start & ~RegexType::kRangeNegationFlag) && codepoint <= r.end)
  611. return yes;
  612. rangeIndex = r.next;
  613. }
  614. return !yes;
  615. }
  616. const RegexType& regex_;
  617. Allocator* allocator_;
  618. Allocator* ownAllocator_;
  619. Stack<Allocator> state0_;
  620. Stack<Allocator> state1_;
  621. uint32_t* stateSet_;
  622. };
  623. typedef GenericRegex<UTF8<> > Regex;
  624. typedef GenericRegexSearch<Regex> RegexSearch;
  625. } // namespace internal
  626. RAPIDJSON_NAMESPACE_END
  627. #ifdef __GNUC__
  628. RAPIDJSON_DIAG_POP
  629. #endif
  630. #if defined(__clang__) || defined(_MSC_VER)
  631. RAPIDJSON_DIAG_POP
  632. #endif
  633. #endif // RAPIDJSON_INTERNAL_REGEX_H_