regex.h 25 KB

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