1 // Tencent is pleased to support the open source community by making RapidJSON available.
3 // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
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
8 // http://opensource.org/licenses/MIT
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.
15 #ifndef RAPIDJSON_INTERNAL_REGEX_H_
16 #define RAPIDJSON_INTERNAL_REGEX_H_
18 #include "../allocators.h"
19 #include "../stream.h"
24 RAPIDJSON_DIAG_OFF(padded)
25 RAPIDJSON_DIAG_OFF(switch-enum)
26 #elif defined(_MSC_VER)
28 RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
33 RAPIDJSON_DIAG_OFF(effc++)
36 #ifndef RAPIDJSON_REGEX_VERBOSE
37 #define RAPIDJSON_REGEX_VERBOSE 0
40 RAPIDJSON_NAMESPACE_BEGIN
43 ///////////////////////////////////////////////////////////////////////////////
46 template <typename SourceStream, typename Encoding>
49 DecodedStream(SourceStream& ss) : ss_(ss), codepoint_() { Decode(); }
50 unsigned Peek() { return codepoint_; }
52 unsigned c = codepoint_;
53 if (c) // No further decoding when '\0'
60 if (!Encoding::Decode(ss_, &codepoint_))
68 ///////////////////////////////////////////////////////////////////////////////
71 static const SizeType kRegexInvalidState = ~SizeType(0); //!< Represents an invalid index in GenericRegex::State::out, out1
72 static const SizeType kRegexInvalidRange = ~SizeType(0);
74 template <typename Encoding, typename Allocator>
75 class GenericRegexSearch;
77 //! Regular expression engine with subset of ECMAscript grammar.
79 Supported regular expression syntax:
85 - \c a{3} Exactly 3 times
86 - \c a{3,} At least 3 times
87 - \c a{3,5} 3 to 5 times
89 - \c ^a At the beginning
92 - \c [abc] Character classes
93 - \c [a-c] Character class range
94 - \c [a-z0-9_] Character class combination
95 - \c [^abc] Negated character classes
96 - \c [^a-c] Negated character class range
97 - \c [\b] Backspace (U+0008)
98 - \c \\| \\\\ ... Escape characters
99 - \c \\f Form feed (U+000C)
100 - \c \\n Line feed (U+000A)
101 - \c \\r Carriage return (U+000D)
102 - \c \\t Tab (U+0009)
103 - \c \\v Vertical tab (U+000B)
105 \note This is a Thompson NFA engine, implemented with reference to
106 Cox, Russ. "Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby,...).",
107 https://swtch.com/~rsc/regexp/regexp1.html
109 template <typename Encoding, typename Allocator = CrtAllocator>
112 typedef Encoding EncodingType;
113 typedef typename Encoding::Ch Ch;
114 template <typename, typename> friend class GenericRegexSearch;
116 GenericRegex(const Ch* source, Allocator* allocator = 0) :
117 ownAllocator_(allocator ? 0 : RAPIDJSON_NEW(Allocator)()), allocator_(allocator ? allocator : ownAllocator_),
118 states_(allocator_, 256), ranges_(allocator_, 256), root_(kRegexInvalidState), stateCount_(), rangeCount_(),
119 anchorBegin_(), anchorEnd_()
121 GenericStringStream<Encoding> ss(source);
122 DecodedStream<GenericStringStream<Encoding>, Encoding> ds(ss);
128 RAPIDJSON_DELETE(ownAllocator_);
131 bool IsValid() const {
132 return root_ != kRegexInvalidState;
145 static const unsigned kAnyCharacterClass = 0xFFFFFFFF; //!< For '.'
146 static const unsigned kRangeCharacterClass = 0xFFFFFFFE;
147 static const unsigned kRangeNegationFlag = 0x80000000;
156 SizeType out; //!< Equals to kInvalid for matching state
157 SizeType out1; //!< Equals to non-kInvalid for split
163 Frag(SizeType s, SizeType o, SizeType m) : start(s), out(o), minIndex(m) {}
165 SizeType out; //!< link-list of all output states
169 State& GetState(SizeType index) {
170 RAPIDJSON_ASSERT(index < stateCount_);
171 return states_.template Bottom<State>()[index];
174 const State& GetState(SizeType index) const {
175 RAPIDJSON_ASSERT(index < stateCount_);
176 return states_.template Bottom<State>()[index];
179 Range& GetRange(SizeType index) {
180 RAPIDJSON_ASSERT(index < rangeCount_);
181 return ranges_.template Bottom<Range>()[index];
184 const Range& GetRange(SizeType index) const {
185 RAPIDJSON_ASSERT(index < rangeCount_);
186 return ranges_.template Bottom<Range>()[index];
189 template <typename InputStream>
190 void Parse(DecodedStream<InputStream, Encoding>& ds) {
191 Stack<Allocator> operandStack(allocator_, 256); // Frag
192 Stack<Allocator> operatorStack(allocator_, 256); // Operator
193 Stack<Allocator> atomCountStack(allocator_, 256); // unsigned (Atom per parenthesis)
195 *atomCountStack.template Push<unsigned>() = 0;
198 while (ds.Peek() != 0) {
199 switch (codepoint = ds.Take()) {
209 while (!operatorStack.Empty() && *operatorStack.template Top<Operator>() < kAlternation)
210 if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
212 *operatorStack.template Push<Operator>() = kAlternation;
213 *atomCountStack.template Top<unsigned>() = 0;
217 *operatorStack.template Push<Operator>() = kLeftParenthesis;
218 *atomCountStack.template Push<unsigned>() = 0;
222 while (!operatorStack.Empty() && *operatorStack.template Top<Operator>() != kLeftParenthesis)
223 if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
225 if (operatorStack.Empty())
227 operatorStack.template Pop<Operator>(1);
228 atomCountStack.template Pop<unsigned>(1);
229 ImplicitConcatenation(atomCountStack, operatorStack);
233 if (!Eval(operandStack, kZeroOrOne))
238 if (!Eval(operandStack, kZeroOrMore))
243 if (!Eval(operandStack, kOneOrMore))
250 if (!ParseUnsigned(ds, &n))
253 if (ds.Peek() == ',') {
255 if (ds.Peek() == '}')
256 m = kInfinityQuantifier;
257 else if (!ParseUnsigned(ds, &m) || m < n)
263 if (!EvalQuantifier(operandStack, n, m) || ds.Peek() != '}')
270 PushOperand(operandStack, kAnyCharacterClass);
271 ImplicitConcatenation(atomCountStack, operatorStack);
277 if (!ParseRange(ds, &range))
279 SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, kRangeCharacterClass);
280 GetState(s).rangeStart = range;
281 *operandStack.template Push<Frag>() = Frag(s, s, s);
283 ImplicitConcatenation(atomCountStack, operatorStack);
286 case '\\': // Escape character
287 if (!CharacterEscape(ds, &codepoint))
288 return; // Unsupported escape character
289 // fall through to default
290 RAPIDJSON_DELIBERATE_FALLTHROUGH;
292 default: // Pattern character
293 PushOperand(operandStack, codepoint);
294 ImplicitConcatenation(atomCountStack, operatorStack);
298 while (!operatorStack.Empty())
299 if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
302 // Link the operand to matching state.
303 if (operandStack.GetSize() == sizeof(Frag)) {
304 Frag* e = operandStack.template Pop<Frag>(1);
305 Patch(e->out, NewState(kRegexInvalidState, kRegexInvalidState, 0));
308 #if RAPIDJSON_REGEX_VERBOSE
309 printf("root: %d\n", root_);
310 for (SizeType i = 0; i < stateCount_ ; i++) {
311 State& s = GetState(i);
312 printf("[%2d] out: %2d out1: %2d c: '%c'\n", i, s.out, s.out1, (char)s.codepoint);
319 SizeType NewState(SizeType out, SizeType out1, unsigned codepoint) {
320 State* s = states_.template Push<State>();
323 s->codepoint = codepoint;
324 s->rangeStart = kRegexInvalidRange;
325 return stateCount_++;
328 void PushOperand(Stack<Allocator>& operandStack, unsigned codepoint) {
329 SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, codepoint);
330 *operandStack.template Push<Frag>() = Frag(s, s, s);
333 void ImplicitConcatenation(Stack<Allocator>& atomCountStack, Stack<Allocator>& operatorStack) {
334 if (*atomCountStack.template Top<unsigned>())
335 *operatorStack.template Push<Operator>() = kConcatenation;
336 (*atomCountStack.template Top<unsigned>())++;
339 SizeType Append(SizeType l1, SizeType l2) {
341 while (GetState(l1).out != kRegexInvalidState)
342 l1 = GetState(l1).out;
343 GetState(l1).out = l2;
347 void Patch(SizeType l, SizeType s) {
348 for (SizeType next; l != kRegexInvalidState; l = next) {
349 next = GetState(l).out;
354 bool Eval(Stack<Allocator>& operandStack, Operator op) {
357 RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag) * 2);
359 Frag e2 = *operandStack.template Pop<Frag>(1);
360 Frag e1 = *operandStack.template Pop<Frag>(1);
361 Patch(e1.out, e2.start);
362 *operandStack.template Push<Frag>() = Frag(e1.start, e2.out, Min(e1.minIndex, e2.minIndex));
367 if (operandStack.GetSize() >= sizeof(Frag) * 2) {
368 Frag e2 = *operandStack.template Pop<Frag>(1);
369 Frag e1 = *operandStack.template Pop<Frag>(1);
370 SizeType s = NewState(e1.start, e2.start, 0);
371 *operandStack.template Push<Frag>() = Frag(s, Append(e1.out, e2.out), Min(e1.minIndex, e2.minIndex));
377 if (operandStack.GetSize() >= sizeof(Frag)) {
378 Frag e = *operandStack.template Pop<Frag>(1);
379 SizeType s = NewState(kRegexInvalidState, e.start, 0);
380 *operandStack.template Push<Frag>() = Frag(s, Append(e.out, s), e.minIndex);
386 if (operandStack.GetSize() >= sizeof(Frag)) {
387 Frag e = *operandStack.template Pop<Frag>(1);
388 SizeType s = NewState(kRegexInvalidState, e.start, 0);
390 *operandStack.template Push<Frag>() = Frag(s, s, e.minIndex);
396 if (operandStack.GetSize() >= sizeof(Frag)) {
397 Frag e = *operandStack.template Pop<Frag>(1);
398 SizeType s = NewState(kRegexInvalidState, e.start, 0);
400 *operandStack.template Push<Frag>() = Frag(e.start, s, e.minIndex);
406 // syntax error (e.g. unclosed kLeftParenthesis)
411 bool EvalQuantifier(Stack<Allocator>& operandStack, unsigned n, unsigned m) {
412 RAPIDJSON_ASSERT(n <= m);
413 RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag));
416 if (m == 0) // a{0} not support
418 else if (m == kInfinityQuantifier)
419 Eval(operandStack, kZeroOrMore); // a{0,} -> a*
421 Eval(operandStack, kZeroOrOne); // a{0,5} -> a?
422 for (unsigned i = 0; i < m - 1; i++)
423 CloneTopOperand(operandStack); // a{0,5} -> a? a? a? a? a?
424 for (unsigned i = 0; i < m - 1; i++)
425 Eval(operandStack, kConcatenation); // a{0,5} -> a?a?a?a?a?
430 for (unsigned i = 0; i < n - 1; i++) // a{3} -> a a a
431 CloneTopOperand(operandStack);
433 if (m == kInfinityQuantifier)
434 Eval(operandStack, kOneOrMore); // a{3,} -> a a a+
436 CloneTopOperand(operandStack); // a{3,5} -> a a a a
437 Eval(operandStack, kZeroOrOne); // a{3,5} -> a a a a?
438 for (unsigned i = n; i < m - 1; i++)
439 CloneTopOperand(operandStack); // a{3,5} -> a a a a? a?
440 for (unsigned i = n; i < m; i++)
441 Eval(operandStack, kConcatenation); // a{3,5} -> a a aa?a?
444 for (unsigned i = 0; i < n - 1; i++)
445 Eval(operandStack, kConcatenation); // a{3} -> aaa, a{3,} -> aaa+, a{3.5} -> aaaa?a?
450 static SizeType Min(SizeType a, SizeType b) { return a < b ? a : b; }
452 void CloneTopOperand(Stack<Allocator>& operandStack) {
453 const Frag src = *operandStack.template Top<Frag>(); // Copy constructor to prevent invalidation
454 SizeType count = stateCount_ - src.minIndex; // Assumes top operand contains states in [src->minIndex, stateCount_)
455 State* s = states_.template Push<State>(count);
456 memcpy(s, &GetState(src.minIndex), count * sizeof(State));
457 for (SizeType j = 0; j < count; j++) {
458 if (s[j].out != kRegexInvalidState)
460 if (s[j].out1 != kRegexInvalidState)
463 *operandStack.template Push<Frag>() = Frag(src.start + count, src.out + count, src.minIndex + count);
464 stateCount_ += count;
467 template <typename InputStream>
468 bool ParseUnsigned(DecodedStream<InputStream, Encoding>& ds, unsigned* u) {
470 if (ds.Peek() < '0' || ds.Peek() > '9')
472 while (ds.Peek() >= '0' && ds.Peek() <= '9') {
473 if (r >= 429496729 && ds.Peek() > '5') // 2^32 - 1 = 4294967295
474 return false; // overflow
475 r = r * 10 + (ds.Take() - '0');
481 template <typename InputStream>
482 bool ParseRange(DecodedStream<InputStream, Encoding>& ds, SizeType* range) {
486 SizeType start = kRegexInvalidRange;
487 SizeType current = kRegexInvalidRange;
489 while ((codepoint = ds.Take()) != 0) {
492 if (codepoint == '^') {
500 if (start == kRegexInvalidRange)
501 return false; // Error: nothing inside []
502 if (step == 2) { // Add trailing '-'
503 SizeType r = NewRange('-');
504 RAPIDJSON_ASSERT(current != kRegexInvalidRange);
505 GetRange(current).next = r;
508 GetRange(start).start |= kRangeNegationFlag;
513 if (ds.Peek() == 'b') {
515 codepoint = 0x0008; // Escape backspace character
517 else if (!CharacterEscape(ds, &codepoint))
519 // fall through to default
520 RAPIDJSON_DELIBERATE_FALLTHROUGH;
525 if (codepoint == '-') {
529 // fall through to step 0 for other characters
530 RAPIDJSON_DELIBERATE_FALLTHROUGH;
534 SizeType r = NewRange(codepoint);
535 if (current != kRegexInvalidRange)
536 GetRange(current).next = r;
537 if (start == kRegexInvalidRange)
545 RAPIDJSON_ASSERT(step == 2);
546 GetRange(current).end = codepoint;
554 SizeType NewRange(unsigned codepoint) {
555 Range* r = ranges_.template Push<Range>();
556 r->start = r->end = codepoint;
557 r->next = kRegexInvalidRange;
558 return rangeCount_++;
561 template <typename InputStream>
562 bool CharacterEscape(DecodedStream<InputStream, Encoding>& ds, unsigned* escapedCodepoint) {
564 switch (codepoint = ds.Take()) {
579 *escapedCodepoint = codepoint; return true;
580 case 'f': *escapedCodepoint = 0x000C; return true;
581 case 'n': *escapedCodepoint = 0x000A; return true;
582 case 'r': *escapedCodepoint = 0x000D; return true;
583 case 't': *escapedCodepoint = 0x0009; return true;
584 case 'v': *escapedCodepoint = 0x000B; return true;
586 return false; // Unsupported escape character
590 Allocator* ownAllocator_;
591 Allocator* allocator_;
592 Stack<Allocator> states_;
593 Stack<Allocator> ranges_;
595 SizeType stateCount_;
596 SizeType rangeCount_;
598 static const unsigned kInfinityQuantifier = ~0u;
600 // For SearchWithAnchoring()
605 template <typename RegexType, typename Allocator = CrtAllocator>
606 class GenericRegexSearch {
608 typedef typename RegexType::EncodingType Encoding;
609 typedef typename Encoding::Ch Ch;
611 GenericRegexSearch(const RegexType& regex, Allocator* allocator = 0) :
612 regex_(regex), allocator_(allocator), ownAllocator_(0),
613 state0_(allocator, 0), state1_(allocator, 0), stateSet_()
615 RAPIDJSON_ASSERT(regex_.IsValid());
617 ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
618 stateSet_ = static_cast<unsigned*>(allocator_->Malloc(GetStateSetSize()));
619 state0_.template Reserve<SizeType>(regex_.stateCount_);
620 state1_.template Reserve<SizeType>(regex_.stateCount_);
623 ~GenericRegexSearch() {
624 Allocator::Free(stateSet_);
625 RAPIDJSON_DELETE(ownAllocator_);
628 template <typename InputStream>
629 bool Match(InputStream& is) {
630 return SearchWithAnchoring(is, true, true);
633 bool Match(const Ch* s) {
634 GenericStringStream<Encoding> is(s);
638 template <typename InputStream>
639 bool Search(InputStream& is) {
640 return SearchWithAnchoring(is, regex_.anchorBegin_, regex_.anchorEnd_);
643 bool Search(const Ch* s) {
644 GenericStringStream<Encoding> is(s);
649 typedef typename RegexType::State State;
650 typedef typename RegexType::Range Range;
652 template <typename InputStream>
653 bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) {
654 DecodedStream<InputStream, Encoding> ds(is);
657 Stack<Allocator> *current = &state0_, *next = &state1_;
658 const size_t stateSetSize = GetStateSetSize();
659 std::memset(stateSet_, 0, stateSetSize);
661 bool matched = AddState(*current, regex_.root_);
663 while (!current->Empty() && (codepoint = ds.Take()) != 0) {
664 std::memset(stateSet_, 0, stateSetSize);
667 for (const SizeType* s = current->template Bottom<SizeType>(); s != current->template End<SizeType>(); ++s) {
668 const State& sr = regex_.GetState(*s);
669 if (sr.codepoint == codepoint ||
670 sr.codepoint == RegexType::kAnyCharacterClass ||
671 (sr.codepoint == RegexType::kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint)))
673 matched = AddState(*next, sr.out) || matched;
674 if (!anchorEnd && matched)
678 AddState(*next, regex_.root_);
680 internal::Swap(current, next);
686 size_t GetStateSetSize() const {
687 return (regex_.stateCount_ + 31) / 32 * 4;
690 // Return whether the added states is a match state
691 bool AddState(Stack<Allocator>& l, SizeType index) {
692 RAPIDJSON_ASSERT(index != kRegexInvalidState);
694 const State& s = regex_.GetState(index);
695 if (s.out1 != kRegexInvalidState) { // Split
696 bool matched = AddState(l, s.out);
697 return AddState(l, s.out1) || matched;
699 else if (!(stateSet_[index >> 5] & (1u << (index & 31)))) {
700 stateSet_[index >> 5] |= (1u << (index & 31));
701 *l.template PushUnsafe<SizeType>() = index;
703 return s.out == kRegexInvalidState; // by using PushUnsafe() above, we can ensure s is not validated due to reallocation.
706 bool MatchRange(SizeType rangeIndex, unsigned codepoint) const {
707 bool yes = (regex_.GetRange(rangeIndex).start & RegexType::kRangeNegationFlag) == 0;
708 while (rangeIndex != kRegexInvalidRange) {
709 const Range& r = regex_.GetRange(rangeIndex);
710 if (codepoint >= (r.start & ~RegexType::kRangeNegationFlag) && codepoint <= r.end)
717 const RegexType& regex_;
718 Allocator* allocator_;
719 Allocator* ownAllocator_;
720 Stack<Allocator> state0_;
721 Stack<Allocator> state1_;
725 typedef GenericRegex<UTF8<> > Regex;
726 typedef GenericRegexSearch<Regex> RegexSearch;
728 } // namespace internal
729 RAPIDJSON_NAMESPACE_END
735 #if defined(__clang__) || defined(_MSC_VER)
739 #endif // RAPIDJSON_INTERNAL_REGEX_H_