michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- michael@0: * vim: set ts=8 sts=4 et sw=4 tw=99: michael@0: * michael@0: * Copyright (C) 2009 Apple Inc. All rights reserved. michael@0: * Copyright (C) 2010 Peter Varga (pvarga@inf.u-szeged.hu), University of Szeged michael@0: * michael@0: * Redistribution and use in source and binary forms, with or without michael@0: * modification, are permitted provided that the following conditions michael@0: * are met: michael@0: * 1. Redistributions of source code must retain the above copyright michael@0: * notice, this list of conditions and the following disclaimer. michael@0: * 2. Redistributions in binary form must reproduce the above copyright michael@0: * notice, this list of conditions and the following disclaimer in the michael@0: * documentation and/or other materials provided with the distribution. michael@0: * michael@0: * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY michael@0: * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE michael@0: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR michael@0: * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR michael@0: * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, michael@0: * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, michael@0: * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR michael@0: * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY michael@0: * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT michael@0: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE michael@0: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: */ michael@0: michael@0: #include "yarr/YarrPattern.h" michael@0: michael@0: #include "yarr/Yarr.h" michael@0: #include "yarr/YarrCanonicalizeUCS2.h" michael@0: #include "yarr/YarrParser.h" michael@0: michael@0: using namespace WTF; michael@0: michael@0: namespace JSC { namespace Yarr { michael@0: michael@0: #include "yarr/RegExpJitTables.h" michael@0: michael@0: #if WTF_CPU_SPARC michael@0: # define BASE_FRAME_SIZE 24 michael@0: #else michael@0: # define BASE_FRAME_SIZE 0 michael@0: #endif michael@0: michael@0: // Thanks, windows.h! michael@0: #undef min michael@0: #undef max michael@0: michael@0: class CharacterClassConstructor { michael@0: public: michael@0: CharacterClassConstructor(bool isCaseInsensitive = false) michael@0: : m_isCaseInsensitive(isCaseInsensitive) michael@0: { michael@0: } michael@0: michael@0: void reset() michael@0: { michael@0: m_matches.clear(); michael@0: m_ranges.clear(); michael@0: m_matchesUnicode.clear(); michael@0: m_rangesUnicode.clear(); michael@0: } michael@0: michael@0: void append(const CharacterClass* other) michael@0: { michael@0: for (size_t i = 0; i < other->m_matches.size(); ++i) michael@0: addSorted(m_matches, other->m_matches[i]); michael@0: for (size_t i = 0; i < other->m_ranges.size(); ++i) michael@0: addSortedRange(m_ranges, other->m_ranges[i].begin, other->m_ranges[i].end); michael@0: for (size_t i = 0; i < other->m_matchesUnicode.size(); ++i) michael@0: addSorted(m_matchesUnicode, other->m_matchesUnicode[i]); michael@0: for (size_t i = 0; i < other->m_rangesUnicode.size(); ++i) michael@0: addSortedRange(m_rangesUnicode, other->m_rangesUnicode[i].begin, other->m_rangesUnicode[i].end); michael@0: } michael@0: michael@0: void putChar(UChar ch) michael@0: { michael@0: // Handle ascii cases. michael@0: if (ch <= 0x7f) { michael@0: if (m_isCaseInsensitive && isASCIIAlpha(ch)) { michael@0: addSorted(m_matches, toASCIIUpper(ch)); michael@0: addSorted(m_matches, toASCIILower(ch)); michael@0: } else michael@0: addSorted(m_matches, ch); michael@0: return; michael@0: } michael@0: michael@0: // Simple case, not a case-insensitive match. michael@0: if (!m_isCaseInsensitive) { michael@0: addSorted(m_matchesUnicode, ch); michael@0: return; michael@0: } michael@0: michael@0: // Add multiple matches, if necessary. michael@0: const UCS2CanonicalizationRange* info = rangeInfoFor(ch); michael@0: if (info->type == CanonicalizeUnique) michael@0: addSorted(m_matchesUnicode, ch); michael@0: else michael@0: putUnicodeIgnoreCase(ch, info); michael@0: } michael@0: michael@0: void putUnicodeIgnoreCase(UChar ch, const UCS2CanonicalizationRange* info) michael@0: { michael@0: ASSERT(m_isCaseInsensitive); michael@0: ASSERT(ch > 0x7f); michael@0: ASSERT(ch >= info->begin && ch <= info->end); michael@0: ASSERT(info->type != CanonicalizeUnique); michael@0: if (info->type == CanonicalizeSet) { michael@0: for (const uint16_t* set = characterSetInfo[info->value]; (ch = *set); ++set) michael@0: addSorted(m_matchesUnicode, ch); michael@0: } else { michael@0: addSorted(m_matchesUnicode, ch); michael@0: addSorted(m_matchesUnicode, getCanonicalPair(info, ch)); michael@0: } michael@0: } michael@0: michael@0: void putRange(UChar lo, UChar hi) michael@0: { michael@0: if (lo <= 0x7f) { michael@0: char asciiLo = lo; michael@0: char asciiHi = std::min(hi, (UChar)0x7f); michael@0: addSortedRange(m_ranges, lo, asciiHi); michael@0: michael@0: if (m_isCaseInsensitive) { michael@0: if ((asciiLo <= 'Z') && (asciiHi >= 'A')) michael@0: addSortedRange(m_ranges, std::max(asciiLo, 'A')+('a'-'A'), std::min(asciiHi, 'Z')+('a'-'A')); michael@0: if ((asciiLo <= 'z') && (asciiHi >= 'a')) michael@0: addSortedRange(m_ranges, std::max(asciiLo, 'a')+('A'-'a'), std::min(asciiHi, 'z')+('A'-'a')); michael@0: } michael@0: } michael@0: if (hi <= 0x7f) michael@0: return; michael@0: michael@0: lo = std::max(lo, (UChar)0x80); michael@0: addSortedRange(m_rangesUnicode, lo, hi); michael@0: michael@0: if (!m_isCaseInsensitive) michael@0: return; michael@0: michael@0: const UCS2CanonicalizationRange* info = rangeInfoFor(lo); michael@0: while (true) { michael@0: // Handle the range [lo .. end] michael@0: UChar end = std::min(info->end, hi); michael@0: michael@0: switch (info->type) { michael@0: case CanonicalizeUnique: michael@0: // Nothing to do - no canonical equivalents. michael@0: break; michael@0: case CanonicalizeSet: { michael@0: UChar ch; michael@0: for (const uint16_t* set = characterSetInfo[info->value]; (ch = *set); ++set) michael@0: addSorted(m_matchesUnicode, ch); michael@0: break; michael@0: } michael@0: case CanonicalizeRangeLo: michael@0: addSortedRange(m_rangesUnicode, lo + info->value, end + info->value); michael@0: break; michael@0: case CanonicalizeRangeHi: michael@0: addSortedRange(m_rangesUnicode, lo - info->value, end - info->value); michael@0: break; michael@0: case CanonicalizeAlternatingAligned: michael@0: // Use addSortedRange since there is likely an abutting range to combine with. michael@0: if (lo & 1) michael@0: addSortedRange(m_rangesUnicode, lo - 1, lo - 1); michael@0: if (!(end & 1)) michael@0: addSortedRange(m_rangesUnicode, end + 1, end + 1); michael@0: break; michael@0: case CanonicalizeAlternatingUnaligned: michael@0: // Use addSortedRange since there is likely an abutting range to combine with. michael@0: if (!(lo & 1)) michael@0: addSortedRange(m_rangesUnicode, lo - 1, lo - 1); michael@0: if (end & 1) michael@0: addSortedRange(m_rangesUnicode, end + 1, end + 1); michael@0: break; michael@0: } michael@0: michael@0: if (hi == end) michael@0: return; michael@0: michael@0: ++info; michael@0: lo = info->begin; michael@0: }; michael@0: michael@0: } michael@0: michael@0: CharacterClass* charClass() michael@0: { michael@0: CharacterClass* characterClass = newOrCrash(); michael@0: michael@0: characterClass->m_matches.swap(m_matches); michael@0: characterClass->m_ranges.swap(m_ranges); michael@0: characterClass->m_matchesUnicode.swap(m_matchesUnicode); michael@0: characterClass->m_rangesUnicode.swap(m_rangesUnicode); michael@0: michael@0: return characterClass; michael@0: } michael@0: michael@0: private: michael@0: void addSorted(Vector& matches, UChar ch) michael@0: { michael@0: unsigned pos = 0; michael@0: unsigned range = matches.size(); michael@0: michael@0: // binary chop, find position to insert char. michael@0: while (range) { michael@0: unsigned index = range >> 1; michael@0: michael@0: int val = matches[pos+index] - ch; michael@0: if (!val) michael@0: return; michael@0: else if (val > 0) michael@0: range = index; michael@0: else { michael@0: pos += (index+1); michael@0: range -= (index+1); michael@0: } michael@0: } michael@0: michael@0: if (pos == matches.size()) michael@0: matches.append(ch); michael@0: else michael@0: matches.insert(pos, ch); michael@0: } michael@0: michael@0: void addSortedRange(Vector& ranges, UChar lo, UChar hi) michael@0: { michael@0: unsigned end = ranges.size(); michael@0: michael@0: // Simple linear scan - I doubt there are that many ranges anyway... michael@0: // feel free to fix this with something faster (eg binary chop). michael@0: for (unsigned i = 0; i < end; ++i) { michael@0: // does the new range fall before the current position in the array michael@0: if (hi < ranges[i].begin) { michael@0: // optional optimization: concatenate appending ranges? - may not be worthwhile. michael@0: if (hi == (ranges[i].begin - 1)) { michael@0: ranges[i].begin = lo; michael@0: return; michael@0: } michael@0: ranges.insert(i, CharacterRange(lo, hi)); michael@0: return; michael@0: } michael@0: // Okay, since we didn't hit the last case, the end of the new range is definitely at or after the begining michael@0: // If the new range start at or before the end of the last range, then the overlap (if it starts one after the michael@0: // end of the last range they concatenate, which is just as good. michael@0: if (lo <= (ranges[i].end + 1)) { michael@0: // found an intersect! we'll replace this entry in the array. michael@0: ranges[i].begin = std::min(ranges[i].begin, lo); michael@0: ranges[i].end = std::max(ranges[i].end, hi); michael@0: michael@0: // now check if the new range can subsume any subsequent ranges. michael@0: unsigned next = i+1; michael@0: // each iteration of the loop we will either remove something from the list, or break the loop. michael@0: while (next < ranges.size()) { michael@0: if (ranges[next].begin <= (ranges[i].end + 1)) { michael@0: // the next entry now overlaps / concatenates this one. michael@0: ranges[i].end = std::max(ranges[i].end, ranges[next].end); michael@0: ranges.remove(next); michael@0: } else michael@0: break; michael@0: } michael@0: michael@0: return; michael@0: } michael@0: } michael@0: michael@0: // CharacterRange comes after all existing ranges. michael@0: ranges.append(CharacterRange(lo, hi)); michael@0: } michael@0: michael@0: bool m_isCaseInsensitive; michael@0: michael@0: Vector m_matches; michael@0: Vector m_ranges; michael@0: Vector m_matchesUnicode; michael@0: Vector m_rangesUnicode; michael@0: }; michael@0: michael@0: class YarrPatternConstructor { michael@0: public: michael@0: YarrPatternConstructor(YarrPattern& pattern) michael@0: : m_pattern(pattern) michael@0: , m_stackBase(nullptr) michael@0: , m_characterClassConstructor(pattern.m_ignoreCase) michael@0: , m_invertParentheticalAssertion(false) michael@0: { michael@0: m_pattern.m_body = newOrCrash(); michael@0: m_alternative = m_pattern.m_body->addNewAlternative(); michael@0: m_pattern.m_disjunctions.append(m_pattern.m_body); michael@0: } michael@0: michael@0: ~YarrPatternConstructor() michael@0: { michael@0: } michael@0: michael@0: void reset() michael@0: { michael@0: m_pattern.reset(); michael@0: m_characterClassConstructor.reset(); michael@0: michael@0: m_pattern.m_body = newOrCrash(); michael@0: m_alternative = m_pattern.m_body->addNewAlternative(); michael@0: m_pattern.m_disjunctions.append(m_pattern.m_body); michael@0: } michael@0: michael@0: void assertionBOL() michael@0: { michael@0: if (!m_alternative->m_terms.size() & !m_invertParentheticalAssertion) { michael@0: m_alternative->m_startsWithBOL = true; michael@0: m_alternative->m_containsBOL = true; michael@0: m_pattern.m_containsBOL = true; michael@0: } michael@0: m_alternative->m_terms.append(PatternTerm::BOL()); michael@0: } michael@0: void assertionEOL() michael@0: { michael@0: m_alternative->m_terms.append(PatternTerm::EOL()); michael@0: } michael@0: void assertionWordBoundary(bool invert) michael@0: { michael@0: m_alternative->m_terms.append(PatternTerm::WordBoundary(invert)); michael@0: } michael@0: michael@0: void atomPatternCharacter(UChar ch) michael@0: { michael@0: // We handle case-insensitive checking of unicode characters which do have both michael@0: // cases by handling them as if they were defined using a CharacterClass. michael@0: if (!m_pattern.m_ignoreCase || isASCII(ch)) { michael@0: m_alternative->m_terms.append(PatternTerm(ch)); michael@0: return; michael@0: } michael@0: michael@0: const UCS2CanonicalizationRange* info = rangeInfoFor(ch); michael@0: if (info->type == CanonicalizeUnique) { michael@0: m_alternative->m_terms.append(PatternTerm(ch)); michael@0: return; michael@0: } michael@0: michael@0: m_characterClassConstructor.putUnicodeIgnoreCase(ch, info); michael@0: CharacterClass* newCharacterClass = m_characterClassConstructor.charClass(); michael@0: m_pattern.m_userCharacterClasses.append(newCharacterClass); michael@0: m_alternative->m_terms.append(PatternTerm(newCharacterClass, false)); michael@0: } michael@0: michael@0: void atomBuiltInCharacterClass(BuiltInCharacterClassID classID, bool invert) michael@0: { michael@0: switch (classID) { michael@0: case DigitClassID: michael@0: m_alternative->m_terms.append(PatternTerm(m_pattern.digitsCharacterClass(), invert)); michael@0: break; michael@0: case SpaceClassID: michael@0: m_alternative->m_terms.append(PatternTerm(m_pattern.spacesCharacterClass(), invert)); michael@0: break; michael@0: case WordClassID: michael@0: m_alternative->m_terms.append(PatternTerm(m_pattern.wordcharCharacterClass(), invert)); michael@0: break; michael@0: case NewlineClassID: michael@0: m_alternative->m_terms.append(PatternTerm(m_pattern.newlineCharacterClass(), invert)); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: void atomCharacterClassBegin(bool invert = false) michael@0: { michael@0: m_invertCharacterClass = invert; michael@0: } michael@0: michael@0: void atomCharacterClassAtom(UChar ch) michael@0: { michael@0: m_characterClassConstructor.putChar(ch); michael@0: } michael@0: michael@0: void atomCharacterClassRange(UChar begin, UChar end) michael@0: { michael@0: m_characterClassConstructor.putRange(begin, end); michael@0: } michael@0: michael@0: void atomCharacterClassBuiltIn(BuiltInCharacterClassID classID, bool invert) michael@0: { michael@0: ASSERT(classID != NewlineClassID); michael@0: michael@0: switch (classID) { michael@0: case DigitClassID: michael@0: m_characterClassConstructor.append(invert ? m_pattern.nondigitsCharacterClass() : m_pattern.digitsCharacterClass()); michael@0: break; michael@0: michael@0: case SpaceClassID: michael@0: m_characterClassConstructor.append(invert ? m_pattern.nonspacesCharacterClass() : m_pattern.spacesCharacterClass()); michael@0: break; michael@0: michael@0: case WordClassID: michael@0: m_characterClassConstructor.append(invert ? m_pattern.nonwordcharCharacterClass() : m_pattern.wordcharCharacterClass()); michael@0: break; michael@0: michael@0: default: michael@0: ASSERT_NOT_REACHED(); michael@0: } michael@0: } michael@0: michael@0: void atomCharacterClassEnd() michael@0: { michael@0: CharacterClass* newCharacterClass = m_characterClassConstructor.charClass(); michael@0: m_pattern.m_userCharacterClasses.append(newCharacterClass); michael@0: m_alternative->m_terms.append(PatternTerm(newCharacterClass, m_invertCharacterClass)); michael@0: } michael@0: michael@0: void atomParenthesesSubpatternBegin(bool capture = true) michael@0: { michael@0: unsigned subpatternId = m_pattern.m_numSubpatterns + 1; michael@0: if (capture) michael@0: m_pattern.m_numSubpatterns++; michael@0: michael@0: PatternDisjunction* parenthesesDisjunction = newOrCrash(m_alternative); michael@0: m_pattern.m_disjunctions.append(parenthesesDisjunction); michael@0: m_alternative->m_terms.append(PatternTerm(PatternTerm::TypeParenthesesSubpattern, subpatternId, parenthesesDisjunction, capture, false)); michael@0: m_alternative = parenthesesDisjunction->addNewAlternative(); michael@0: } michael@0: michael@0: void atomParentheticalAssertionBegin(bool invert = false) michael@0: { michael@0: PatternDisjunction* parenthesesDisjunction = newOrCrash(m_alternative); michael@0: m_pattern.m_disjunctions.append(parenthesesDisjunction); michael@0: m_alternative->m_terms.append(PatternTerm(PatternTerm::TypeParentheticalAssertion, m_pattern.m_numSubpatterns + 1, parenthesesDisjunction, false, invert)); michael@0: m_alternative = parenthesesDisjunction->addNewAlternative(); michael@0: m_invertParentheticalAssertion = invert; michael@0: } michael@0: michael@0: void atomParenthesesEnd() michael@0: { michael@0: ASSERT(m_alternative->m_parent); michael@0: ASSERT(m_alternative->m_parent->m_parent); michael@0: michael@0: PatternDisjunction* parenthesesDisjunction = m_alternative->m_parent; michael@0: m_alternative = m_alternative->m_parent->m_parent; michael@0: michael@0: PatternTerm& lastTerm = m_alternative->lastTerm(); michael@0: michael@0: unsigned numParenAlternatives = parenthesesDisjunction->m_alternatives.size(); michael@0: unsigned numBOLAnchoredAlts = 0; michael@0: michael@0: for (unsigned i = 0; i < numParenAlternatives; i++) { michael@0: // Bubble up BOL flags michael@0: if (parenthesesDisjunction->m_alternatives[i]->m_startsWithBOL) michael@0: numBOLAnchoredAlts++; michael@0: } michael@0: michael@0: if (numBOLAnchoredAlts) { michael@0: m_alternative->m_containsBOL = true; michael@0: // If all the alternatives in parens start with BOL, then so does this one michael@0: if (numBOLAnchoredAlts == numParenAlternatives) michael@0: m_alternative->m_startsWithBOL = true; michael@0: } michael@0: michael@0: lastTerm.parentheses.lastSubpatternId = m_pattern.m_numSubpatterns; michael@0: m_invertParentheticalAssertion = false; michael@0: } michael@0: michael@0: void atomBackReference(unsigned subpatternId) michael@0: { michael@0: ASSERT(subpatternId); michael@0: m_pattern.m_containsBackreferences = true; michael@0: m_pattern.m_maxBackReference = std::max(m_pattern.m_maxBackReference, subpatternId); michael@0: michael@0: if (subpatternId > m_pattern.m_numSubpatterns) { michael@0: m_alternative->m_terms.append(PatternTerm::ForwardReference()); michael@0: return; michael@0: } michael@0: michael@0: PatternAlternative* currentAlternative = m_alternative; michael@0: ASSERT(currentAlternative); michael@0: michael@0: // Note to self: if we waited until the AST was baked, we could also remove forwards refs michael@0: while ((currentAlternative = currentAlternative->m_parent->m_parent)) { michael@0: PatternTerm& term = currentAlternative->lastTerm(); michael@0: ASSERT((term.type == PatternTerm::TypeParenthesesSubpattern) || (term.type == PatternTerm::TypeParentheticalAssertion)); michael@0: michael@0: if ((term.type == PatternTerm::TypeParenthesesSubpattern) && term.capture() && (subpatternId == term.parentheses.subpatternId)) { michael@0: m_alternative->m_terms.append(PatternTerm::ForwardReference()); michael@0: return; michael@0: } michael@0: } michael@0: michael@0: m_alternative->m_terms.append(PatternTerm(subpatternId)); michael@0: } michael@0: michael@0: // deep copy the argument disjunction. If filterStartsWithBOL is true, michael@0: // skip alternatives with m_startsWithBOL set true. michael@0: PatternDisjunction* copyDisjunction(PatternDisjunction* disjunction, bool filterStartsWithBOL = false) michael@0: { michael@0: PatternDisjunction* newDisjunction = 0; michael@0: for (unsigned alt = 0; alt < disjunction->m_alternatives.size(); ++alt) { michael@0: PatternAlternative* alternative = disjunction->m_alternatives[alt]; michael@0: if (!filterStartsWithBOL || !alternative->m_startsWithBOL) { michael@0: if (!newDisjunction) { michael@0: newDisjunction = newOrCrash(); michael@0: newDisjunction->m_parent = disjunction->m_parent; michael@0: } michael@0: PatternAlternative* newAlternative = newDisjunction->addNewAlternative(); michael@0: newAlternative->m_terms.reserve(alternative->m_terms.size()); michael@0: for (unsigned i = 0; i < alternative->m_terms.size(); ++i) michael@0: newAlternative->m_terms.append(copyTerm(alternative->m_terms[i], filterStartsWithBOL)); michael@0: } michael@0: } michael@0: michael@0: if (newDisjunction) michael@0: m_pattern.m_disjunctions.append(newDisjunction); michael@0: return newDisjunction; michael@0: } michael@0: michael@0: PatternTerm copyTerm(PatternTerm& term, bool filterStartsWithBOL = false) michael@0: { michael@0: if ((term.type != PatternTerm::TypeParenthesesSubpattern) && (term.type != PatternTerm::TypeParentheticalAssertion)) michael@0: return PatternTerm(term); michael@0: michael@0: PatternTerm termCopy = term; michael@0: termCopy.parentheses.disjunction = copyDisjunction(termCopy.parentheses.disjunction, filterStartsWithBOL); michael@0: return termCopy; michael@0: } michael@0: michael@0: void quantifyAtom(unsigned min, unsigned max, bool greedy) michael@0: { michael@0: ASSERT(min <= max); michael@0: ASSERT(m_alternative->m_terms.size()); michael@0: michael@0: if (!max) { michael@0: m_alternative->removeLastTerm(); michael@0: return; michael@0: } michael@0: michael@0: PatternTerm& term = m_alternative->lastTerm(); michael@0: ASSERT(term.type > PatternTerm::TypeAssertionWordBoundary); michael@0: ASSERT((term.quantityCount == 1) && (term.quantityType == QuantifierFixedCount)); michael@0: michael@0: if (term.type == PatternTerm::TypeParentheticalAssertion) { michael@0: // If an assertion is quantified with a minimum count of zero, it can simply be removed. michael@0: // This arises from the RepeatMatcher behaviour in the spec. Matching an assertion never michael@0: // results in any input being consumed, however the continuation passed to the assertion michael@0: // (called in steps, 8c and 9 of the RepeatMatcher definition, ES5.1 15.10.2.5) will michael@0: // reject all zero length matches (see step 2.1). A match from the continuation of the michael@0: // expression will still be accepted regardless (via steps 8a and 11) - the upshot of all michael@0: // this is that matches from the assertion are not required, and won't be accepted anyway, michael@0: // so no need to ever run it. michael@0: if (!min) michael@0: m_alternative->removeLastTerm(); michael@0: // We never need to run an assertion more than once. Subsequent interations will be run michael@0: // with the same start index (since assertions are non-capturing) and the same captures michael@0: // (per step 4 of RepeatMatcher in ES5.1 15.10.2.5), and as such will always produce the michael@0: // same result and captures. If the first match succeeds then the subsequent (min - 1) michael@0: // matches will too. Any additional optional matches will fail (on the same basis as the michael@0: // minimum zero quantified assertions, above), but this will still result in a match. michael@0: return; michael@0: } michael@0: michael@0: if (min == 0) michael@0: term.quantify(max, greedy ? QuantifierGreedy : QuantifierNonGreedy); michael@0: else if (min == max) michael@0: term.quantify(min, QuantifierFixedCount); michael@0: else { michael@0: term.quantify(min, QuantifierFixedCount); michael@0: m_alternative->m_terms.append(copyTerm(term)); michael@0: // NOTE: this term is interesting from an analysis perspective, in that it can be ignored..... michael@0: m_alternative->lastTerm().quantify((max == quantifyInfinite) ? max : max - min, greedy ? QuantifierGreedy : QuantifierNonGreedy); michael@0: if (m_alternative->lastTerm().type == PatternTerm::TypeParenthesesSubpattern) michael@0: m_alternative->lastTerm().parentheses.isCopy = true; michael@0: } michael@0: } michael@0: michael@0: void disjunction() michael@0: { michael@0: m_alternative = m_alternative->m_parent->addNewAlternative(); michael@0: } michael@0: michael@0: ErrorCode setupAlternativeOffsets(PatternAlternative* alternative, unsigned currentCallFrameSize, unsigned initialInputPosition, michael@0: unsigned *callFrameSizeOut) michael@0: { michael@0: /* michael@0: * Attempt detection of over-recursion: michael@0: * "1MB should be enough stack for anyone." michael@0: */ michael@0: uint8_t stackDummy_; michael@0: if (m_stackBase - &stackDummy_ > 1024*1024) michael@0: return PatternTooLarge; michael@0: michael@0: alternative->m_hasFixedSize = true; michael@0: Checked currentInputPosition = initialInputPosition; michael@0: michael@0: for (unsigned i = 0; i < alternative->m_terms.size(); ++i) { michael@0: PatternTerm& term = alternative->m_terms[i]; michael@0: michael@0: switch (term.type) { michael@0: case PatternTerm::TypeAssertionBOL: michael@0: case PatternTerm::TypeAssertionEOL: michael@0: case PatternTerm::TypeAssertionWordBoundary: michael@0: if (Checked(currentInputPosition).safeGet(term.inputPosition)) michael@0: return RuntimeError; michael@0: break; michael@0: michael@0: case PatternTerm::TypeBackReference: michael@0: if (Checked(currentInputPosition).safeGet(term.inputPosition)) michael@0: return RuntimeError; michael@0: term.frameLocation = currentCallFrameSize; michael@0: currentCallFrameSize += YarrStackSpaceForBackTrackInfoBackReference; michael@0: alternative->m_hasFixedSize = false; michael@0: break; michael@0: michael@0: case PatternTerm::TypeForwardReference: michael@0: break; michael@0: michael@0: case PatternTerm::TypePatternCharacter: michael@0: if (Checked(currentInputPosition).safeGet(term.inputPosition)) michael@0: return RuntimeError; michael@0: if (term.quantityType != QuantifierFixedCount) { michael@0: term.frameLocation = currentCallFrameSize; michael@0: currentCallFrameSize += YarrStackSpaceForBackTrackInfoPatternCharacter; michael@0: alternative->m_hasFixedSize = false; michael@0: } else michael@0: currentInputPosition += term.quantityCount; michael@0: break; michael@0: michael@0: case PatternTerm::TypeCharacterClass: michael@0: if (Checked(currentInputPosition).safeGet(term.inputPosition)) michael@0: return RuntimeError; michael@0: if (term.quantityType != QuantifierFixedCount) { michael@0: term.frameLocation = currentCallFrameSize; michael@0: currentCallFrameSize += YarrStackSpaceForBackTrackInfoCharacterClass; michael@0: alternative->m_hasFixedSize = false; michael@0: } else michael@0: currentInputPosition += term.quantityCount; michael@0: break; michael@0: michael@0: case PatternTerm::TypeParenthesesSubpattern: michael@0: // Note: for fixed once parentheses we will ensure at least the minimum is available; others are on their own. michael@0: term.frameLocation = currentCallFrameSize; michael@0: unsigned position; michael@0: if (currentInputPosition.safeGet(position)) michael@0: return RuntimeError; michael@0: if (term.quantityCount == 1 && !term.parentheses.isCopy) { michael@0: if (term.quantityType != QuantifierFixedCount) michael@0: currentCallFrameSize += YarrStackSpaceForBackTrackInfoParenthesesOnce; michael@0: if (ErrorCode error = setupDisjunctionOffsets(term.parentheses.disjunction, currentCallFrameSize, position, ¤tCallFrameSize)) michael@0: return error; michael@0: // If quantity is fixed, then pre-check its minimum size. michael@0: if (term.quantityType == QuantifierFixedCount) michael@0: currentInputPosition += term.parentheses.disjunction->m_minimumSize; michael@0: if (Checked(currentInputPosition).safeGet(term.inputPosition)) michael@0: return RuntimeError; michael@0: } else if (term.parentheses.isTerminal) { michael@0: currentCallFrameSize += YarrStackSpaceForBackTrackInfoParenthesesTerminal; michael@0: if (ErrorCode error = setupDisjunctionOffsets(term.parentheses.disjunction, currentCallFrameSize, position, ¤tCallFrameSize)) michael@0: return error; michael@0: if (Checked(currentInputPosition).safeGet(term.inputPosition)) michael@0: return RuntimeError; michael@0: } else { michael@0: if (Checked(currentInputPosition).safeGet(term.inputPosition)) michael@0: return RuntimeError; michael@0: unsigned dummy; michael@0: if (ErrorCode error = setupDisjunctionOffsets(term.parentheses.disjunction, BASE_FRAME_SIZE, position, &dummy)) michael@0: return error; michael@0: currentCallFrameSize += YarrStackSpaceForBackTrackInfoParentheses; michael@0: } michael@0: // Fixed count of 1 could be accepted, if they have a fixed size *AND* if all alternatives are of the same length. michael@0: alternative->m_hasFixedSize = false; michael@0: break; michael@0: michael@0: case PatternTerm::TypeParentheticalAssertion: michael@0: if (Checked(currentInputPosition).safeGet(term.inputPosition)) michael@0: return RuntimeError; michael@0: term.frameLocation = currentCallFrameSize; michael@0: if (ErrorCode error = setupDisjunctionOffsets(term.parentheses.disjunction, currentCallFrameSize + YarrStackSpaceForBackTrackInfoParentheticalAssertion, term.inputPosition, ¤tCallFrameSize)) michael@0: return error; michael@0: break; michael@0: michael@0: case PatternTerm::TypeDotStarEnclosure: michael@0: alternative->m_hasFixedSize = false; michael@0: term.inputPosition = initialInputPosition; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if ((currentInputPosition - initialInputPosition).safeGet(alternative->m_minimumSize)) michael@0: return RuntimeError; michael@0: *callFrameSizeOut = currentCallFrameSize; michael@0: return NoError; michael@0: } michael@0: michael@0: ErrorCode setupDisjunctionOffsets(PatternDisjunction* disjunction, unsigned initialCallFrameSize, unsigned initialInputPosition, unsigned *maximumCallFrameSizeOut) michael@0: { michael@0: if ((disjunction != m_pattern.m_body) && (disjunction->m_alternatives.size() > 1)) michael@0: initialCallFrameSize += YarrStackSpaceForBackTrackInfoAlternative; michael@0: michael@0: unsigned minimumInputSize = UINT_MAX; michael@0: unsigned maximumCallFrameSize = 0; michael@0: bool hasFixedSize = true; michael@0: michael@0: for (unsigned alt = 0; alt < disjunction->m_alternatives.size(); ++alt) { michael@0: PatternAlternative* alternative = disjunction->m_alternatives[alt]; michael@0: unsigned currentAlternativeCallFrameSize; michael@0: if (ErrorCode error = setupAlternativeOffsets(alternative, initialCallFrameSize, initialInputPosition, ¤tAlternativeCallFrameSize)) michael@0: return error; michael@0: minimumInputSize = std::min(minimumInputSize, alternative->m_minimumSize); michael@0: maximumCallFrameSize = std::max(maximumCallFrameSize, currentAlternativeCallFrameSize); michael@0: hasFixedSize &= alternative->m_hasFixedSize; michael@0: } michael@0: michael@0: ASSERT(minimumInputSize != UINT_MAX); michael@0: if (minimumInputSize == UINT_MAX) michael@0: return PatternTooLarge; michael@0: michael@0: ASSERT(minimumInputSize != UINT_MAX); michael@0: ASSERT(maximumCallFrameSize >= initialCallFrameSize); michael@0: michael@0: disjunction->m_hasFixedSize = hasFixedSize; michael@0: disjunction->m_minimumSize = minimumInputSize; michael@0: disjunction->m_callFrameSize = maximumCallFrameSize; michael@0: *maximumCallFrameSizeOut = maximumCallFrameSize; michael@0: return NoError; michael@0: } michael@0: michael@0: ErrorCode setupOffsets() michael@0: { michael@0: unsigned dummy; michael@0: return setupDisjunctionOffsets(m_pattern.m_body, BASE_FRAME_SIZE, 0, &dummy); michael@0: } michael@0: michael@0: // This optimization identifies sets of parentheses that we will never need to backtrack. michael@0: // In these cases we do not need to store state from prior iterations. michael@0: // We can presently avoid backtracking for: michael@0: // * where the parens are at the end of the regular expression (last term in any of the michael@0: // alternatives of the main body disjunction). michael@0: // * where the parens are non-capturing, and quantified unbounded greedy (*). michael@0: // * where the parens do not contain any capturing subpatterns. michael@0: void checkForTerminalParentheses() michael@0: { michael@0: // This check is much too crude; should be just checking whether the candidate michael@0: // node contains nested capturing subpatterns, not the whole expression! michael@0: if (m_pattern.m_numSubpatterns) michael@0: return; michael@0: michael@0: Vector& alternatives = m_pattern.m_body->m_alternatives; michael@0: for (size_t i = 0; i < alternatives.size(); ++i) { michael@0: Vector& terms = alternatives[i]->m_terms; michael@0: if (terms.size()) { michael@0: PatternTerm& term = terms.last(); michael@0: if (term.type == PatternTerm::TypeParenthesesSubpattern michael@0: && term.quantityType == QuantifierGreedy michael@0: && term.quantityCount == quantifyInfinite michael@0: && !term.capture()) michael@0: term.parentheses.isTerminal = true; michael@0: } michael@0: } michael@0: } michael@0: michael@0: void optimizeBOL() michael@0: { michael@0: // Look for expressions containing beginning of line (^) anchoring and unroll them. michael@0: // e.g. /^a|^b|c/ becomes /^a|^b|c/ which is executed once followed by /c/ which loops michael@0: // This code relies on the parsing code tagging alternatives with m_containsBOL and michael@0: // m_startsWithBOL and rolling those up to containing alternatives. michael@0: // At this point, this is only valid for non-multiline expressions. michael@0: PatternDisjunction* disjunction = m_pattern.m_body; michael@0: michael@0: if (!m_pattern.m_containsBOL || m_pattern.m_multiline) michael@0: return; michael@0: michael@0: PatternDisjunction* loopDisjunction = copyDisjunction(disjunction, true); michael@0: michael@0: // Set alternatives in disjunction to "onceThrough" michael@0: for (unsigned alt = 0; alt < disjunction->m_alternatives.size(); ++alt) michael@0: disjunction->m_alternatives[alt]->setOnceThrough(); michael@0: michael@0: if (loopDisjunction) { michael@0: // Move alternatives from loopDisjunction to disjunction michael@0: for (unsigned alt = 0; alt < loopDisjunction->m_alternatives.size(); ++alt) michael@0: disjunction->m_alternatives.append(loopDisjunction->m_alternatives[alt]); michael@0: michael@0: loopDisjunction->m_alternatives.clear(); michael@0: } michael@0: } michael@0: michael@0: bool containsCapturingTerms(PatternAlternative* alternative, size_t firstTermIndex, size_t lastTermIndex) michael@0: { michael@0: Vector& terms = alternative->m_terms; michael@0: michael@0: for (size_t termIndex = firstTermIndex; termIndex <= lastTermIndex; ++termIndex) { michael@0: PatternTerm& term = terms[termIndex]; michael@0: michael@0: if (term.m_capture) michael@0: return true; michael@0: michael@0: if (term.type == PatternTerm::TypeParenthesesSubpattern) { michael@0: PatternDisjunction* nestedDisjunction = term.parentheses.disjunction; michael@0: for (unsigned alt = 0; alt < nestedDisjunction->m_alternatives.size(); ++alt) { michael@0: PatternAlternative *pattern = nestedDisjunction->m_alternatives[alt]; michael@0: if (pattern->m_terms.size() == 0) michael@0: continue; michael@0: if (containsCapturingTerms(pattern, 0, pattern->m_terms.size() - 1)) michael@0: return true; michael@0: } michael@0: } michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: // This optimization identifies alternatives in the form of michael@0: // [^].*[?].*[$] for expressions that don't have any michael@0: // capturing terms. The alternative is changed to michael@0: // followed by processing of the dot stars to find and adjust the michael@0: // beginning and the end of the match. michael@0: void optimizeDotStarWrappedExpressions() michael@0: { michael@0: Vector& alternatives = m_pattern.m_body->m_alternatives; michael@0: if (alternatives.size() != 1) michael@0: return; michael@0: michael@0: PatternAlternative* alternative = alternatives[0]; michael@0: Vector& terms = alternative->m_terms; michael@0: if (terms.size() >= 3) { michael@0: bool startsWithBOL = false; michael@0: bool endsWithEOL = false; michael@0: size_t termIndex, firstExpressionTerm, lastExpressionTerm; michael@0: michael@0: termIndex = 0; michael@0: if (terms[termIndex].type == PatternTerm::TypeAssertionBOL) { michael@0: startsWithBOL = true; michael@0: ++termIndex; michael@0: } michael@0: michael@0: PatternTerm& firstNonAnchorTerm = terms[termIndex]; michael@0: if ((firstNonAnchorTerm.type != PatternTerm::TypeCharacterClass) || (firstNonAnchorTerm.characterClass != m_pattern.newlineCharacterClass()) || !((firstNonAnchorTerm.quantityType == QuantifierGreedy) || (firstNonAnchorTerm.quantityType == QuantifierNonGreedy))) michael@0: return; michael@0: michael@0: firstExpressionTerm = termIndex + 1; michael@0: michael@0: termIndex = terms.size() - 1; michael@0: if (terms[termIndex].type == PatternTerm::TypeAssertionEOL) { michael@0: endsWithEOL = true; michael@0: --termIndex; michael@0: } michael@0: michael@0: PatternTerm& lastNonAnchorTerm = terms[termIndex]; michael@0: if ((lastNonAnchorTerm.type != PatternTerm::TypeCharacterClass) || (lastNonAnchorTerm.characterClass != m_pattern.newlineCharacterClass()) || (lastNonAnchorTerm.quantityType != QuantifierGreedy)) michael@0: return; michael@0: michael@0: lastExpressionTerm = termIndex - 1; michael@0: michael@0: if (firstExpressionTerm > lastExpressionTerm) michael@0: return; michael@0: michael@0: if (!containsCapturingTerms(alternative, firstExpressionTerm, lastExpressionTerm)) { michael@0: for (termIndex = terms.size() - 1; termIndex > lastExpressionTerm; --termIndex) michael@0: terms.remove(termIndex); michael@0: michael@0: for (termIndex = firstExpressionTerm; termIndex > 0; --termIndex) michael@0: terms.remove(termIndex - 1); michael@0: michael@0: terms.append(PatternTerm(startsWithBOL, endsWithEOL)); michael@0: michael@0: m_pattern.m_containsBOL = false; michael@0: } michael@0: } michael@0: } michael@0: michael@0: void setStackBase(uint8_t *stackBase) { michael@0: m_stackBase = stackBase; michael@0: } michael@0: michael@0: private: michael@0: YarrPattern& m_pattern; michael@0: uint8_t * m_stackBase; michael@0: PatternAlternative* m_alternative; michael@0: CharacterClassConstructor m_characterClassConstructor; michael@0: bool m_invertCharacterClass; michael@0: bool m_invertParentheticalAssertion; michael@0: }; michael@0: michael@0: ErrorCode YarrPattern::compile(const String& patternString) michael@0: { michael@0: YarrPatternConstructor constructor(*this); michael@0: michael@0: if (ErrorCode error = parse(constructor, patternString)) michael@0: return error; michael@0: michael@0: // If the pattern contains illegal backreferences reset & reparse. michael@0: // Quoting Netscape's "What's new in JavaScript 1.2", michael@0: // "Note: if the number of left parentheses is less than the number specified michael@0: // in \#, the \# is taken as an octal escape as described in the next row." michael@0: if (containsIllegalBackReference()) { michael@0: unsigned numSubpatterns = m_numSubpatterns; michael@0: michael@0: constructor.reset(); michael@0: #if !ASSERT_DISABLED michael@0: ErrorCode error = michael@0: #endif michael@0: parse(constructor, patternString, numSubpatterns); michael@0: michael@0: ASSERT(!error); michael@0: ASSERT(numSubpatterns == m_numSubpatterns); michael@0: } michael@0: michael@0: uint8_t stackDummy_; michael@0: constructor.setStackBase(&stackDummy_); michael@0: michael@0: constructor.checkForTerminalParentheses(); michael@0: constructor.optimizeDotStarWrappedExpressions(); michael@0: constructor.optimizeBOL(); michael@0: michael@0: if (ErrorCode error = constructor.setupOffsets()) michael@0: return error; michael@0: michael@0: return NoError; michael@0: } michael@0: michael@0: YarrPattern::YarrPattern(const String& pattern, bool ignoreCase, bool multiline, ErrorCode* error) michael@0: : m_ignoreCase(ignoreCase) michael@0: , m_multiline(multiline) michael@0: , m_containsBackreferences(false) michael@0: , m_containsBOL(false) michael@0: , m_numSubpatterns(0) michael@0: , m_maxBackReference(0) michael@0: , newlineCached(0) michael@0: , digitsCached(0) michael@0: , spacesCached(0) michael@0: , wordcharCached(0) michael@0: , nondigitsCached(0) michael@0: , nonspacesCached(0) michael@0: , nonwordcharCached(0) michael@0: { michael@0: *error = compile(pattern); michael@0: } michael@0: michael@0: } }