| 1 |
// Copyright 2019 the V8 project authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style license that can be |
| 3 |
// found in the LICENSE file. |
| 4 |
|
| 5 |
#include "irregexp/imported/regexp-compiler.h" |
| 6 |
#include "irregexp/imported/regexp.h" |
| 7 |
|
| 8 |
#ifdef V8_INTL_SUPPORT |
| 9 |
#include "irregexp/imported/special-case.h" |
| 10 |
#include "unicode/locid.h" |
| 11 |
#include "unicode/uniset.h" |
| 12 |
#include "unicode/utypes.h" |
| 13 |
#endif // V8_INTL_SUPPORT |
| 14 |
|
| 15 |
namespace v8 { |
| 16 |
namespace internal { |
| 17 |
|
| 18 |
using namespace regexp_compiler_constants; // NOLINT(build/namespaces) |
| 19 |
|
| 20 |
constexpr base::uc32 kMaxCodePoint = 0x10ffff; |
| 21 |
constexpr int kMaxUtf16CodeUnit = 0xffff; |
| 22 |
constexpr uint32_t kMaxUtf16CodeUnitU = 0xffff; |
| 23 |
|
| 24 |
// ------------------------------------------------------------------- |
| 25 |
// Tree to graph conversion |
| 26 |
|
| 27 |
RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler, |
| 28 |
RegExpNode* on_success) { |
| 29 |
ZoneList<TextElement>* elms = |
| 30 |
compiler->zone()->New<ZoneList<TextElement>>(1, compiler->zone()); |
| 31 |
elms->Add(TextElement::Atom(this), compiler->zone()); |
| 32 |
return compiler->zone()->New<TextNode>(elms, compiler->read_backward(), |
| 33 |
on_success); |
| 34 |
} |
| 35 |
|
| 36 |
RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler, |
| 37 |
RegExpNode* on_success) { |
| 38 |
return compiler->zone()->New<TextNode>(elements(), compiler->read_backward(), |
| 39 |
on_success); |
| 40 |
} |
| 41 |
|
| 42 |
namespace { |
| 43 |
|
| 44 |
bool CompareInverseRanges(ZoneList<CharacterRange>* ranges, |
| 45 |
const int* special_class, int length) { |
| 46 |
length--; // Remove final marker. |
| 47 |
|
| 48 |
DCHECK_EQ(kRangeEndMarker, special_class[length]); |
| 49 |
DCHECK_NE(0, ranges->length()); |
| 50 |
DCHECK_NE(0, length); |
| 51 |
DCHECK_NE(0, special_class[0]); |
| 52 |
|
| 53 |
if (ranges->length() != (length >> 1) + 1) return false; |
| 54 |
|
| 55 |
CharacterRange range = ranges->at(0); |
| 56 |
if (range.from() != 0) return false; |
| 57 |
|
| 58 |
for (int i = 0; i < length; i += 2) { |
| 59 |
if (static_cast<base::uc32>(special_class[i]) != (range.to() + 1)) { |
| 60 |
return false; |
| 61 |
} |
| 62 |
range = ranges->at((i >> 1) + 1); |
| 63 |
if (static_cast<base::uc32>(special_class[i + 1]) != range.from()) { |
| 64 |
return false; |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
return range.to() == kMaxCodePoint; |
| 69 |
} |
| 70 |
|
| 71 |
bool CompareRanges(ZoneList<CharacterRange>* ranges, const int* special_class, |
| 72 |
int length) { |
| 73 |
length--; // Remove final marker. |
| 74 |
|
| 75 |
DCHECK_EQ(kRangeEndMarker, special_class[length]); |
| 76 |
if (ranges->length() * 2 != length) return false; |
| 77 |
|
| 78 |
for (int i = 0; i < length; i += 2) { |
| 79 |
CharacterRange range = ranges->at(i >> 1); |
| 80 |
if (range.from() != static_cast<base::uc32>(special_class[i]) || |
| 81 |
range.to() != static_cast<base::uc32>(special_class[i + 1] - 1)) { |
| 82 |
return false; |
| 83 |
} |
| 84 |
} |
| 85 |
return true; |
| 86 |
} |
| 87 |
|
| 88 |
} // namespace |
| 89 |
|
| 90 |
bool RegExpClassRanges::is_standard(Zone* zone) { |
| 91 |
// TODO(lrn): Remove need for this function, by not throwing away information |
| 92 |
// along the way. |
| 93 |
if (is_negated()) { |
| 94 |
return false; |
| 95 |
} |
| 96 |
if (set_.is_standard()) { |
| 97 |
return true; |
| 98 |
} |
| 99 |
if (CompareRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) { |
| 100 |
set_.set_standard_set_type(StandardCharacterSet::kWhitespace); |
| 101 |
return true; |
| 102 |
} |
| 103 |
if (CompareInverseRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) { |
| 104 |
set_.set_standard_set_type(StandardCharacterSet::kNotWhitespace); |
| 105 |
return true; |
| 106 |
} |
| 107 |
if (CompareInverseRanges(set_.ranges(zone), kLineTerminatorRanges, |
| 108 |
kLineTerminatorRangeCount)) { |
| 109 |
set_.set_standard_set_type(StandardCharacterSet::kNotLineTerminator); |
| 110 |
return true; |
| 111 |
} |
| 112 |
if (CompareRanges(set_.ranges(zone), kLineTerminatorRanges, |
| 113 |
kLineTerminatorRangeCount)) { |
| 114 |
set_.set_standard_set_type(StandardCharacterSet::kLineTerminator); |
| 115 |
return true; |
| 116 |
} |
| 117 |
if (CompareRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) { |
| 118 |
set_.set_standard_set_type(StandardCharacterSet::kWord); |
| 119 |
return true; |
| 120 |
} |
| 121 |
if (CompareInverseRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) { |
| 122 |
set_.set_standard_set_type(StandardCharacterSet::kNotWord); |
| 123 |
return true; |
| 124 |
} |
| 125 |
return false; |
| 126 |
} |
| 127 |
|
| 128 |
UnicodeRangeSplitter::UnicodeRangeSplitter(ZoneList<CharacterRange>* base) { |
| 129 |
// The unicode range splitter categorizes given character ranges into: |
| 130 |
// - Code points from the BMP representable by one code unit. |
| 131 |
// - Code points outside the BMP that need to be split into |
| 132 |
// surrogate pairs. |
| 133 |
// - Lone lead surrogates. |
| 134 |
// - Lone trail surrogates. |
| 135 |
// Lone surrogates are valid code points, even though no actual characters. |
| 136 |
// They require special matching to make sure we do not split surrogate pairs. |
| 137 |
|
| 138 |
for (int i = 0; i < base->length(); i++) AddRange(base->at(i)); |
| 139 |
} |
| 140 |
|
| 141 |
void UnicodeRangeSplitter::AddRange(CharacterRange range) { |
| 142 |
static constexpr base::uc32 kBmp1Start = 0; |
| 143 |
static constexpr base::uc32 kBmp1End = kLeadSurrogateStart - 1; |
| 144 |
static constexpr base::uc32 kBmp2Start = kTrailSurrogateEnd + 1; |
| 145 |
static constexpr base::uc32 kBmp2End = kNonBmpStart - 1; |
| 146 |
|
| 147 |
// Ends are all inclusive. |
| 148 |
static_assert(kBmp1Start == 0); |
| 149 |
static_assert(kBmp1Start < kBmp1End); |
| 150 |
static_assert(kBmp1End + 1 == kLeadSurrogateStart); |
| 151 |
static_assert(kLeadSurrogateStart < kLeadSurrogateEnd); |
| 152 |
static_assert(kLeadSurrogateEnd + 1 == kTrailSurrogateStart); |
| 153 |
static_assert(kTrailSurrogateStart < kTrailSurrogateEnd); |
| 154 |
static_assert(kTrailSurrogateEnd + 1 == kBmp2Start); |
| 155 |
static_assert(kBmp2Start < kBmp2End); |
| 156 |
static_assert(kBmp2End + 1 == kNonBmpStart); |
| 157 |
static_assert(kNonBmpStart < kNonBmpEnd); |
| 158 |
|
| 159 |
static constexpr base::uc32 kStarts[] = { |
| 160 |
kBmp1Start, kLeadSurrogateStart, kTrailSurrogateStart, |
| 161 |
kBmp2Start, kNonBmpStart, |
| 162 |
}; |
| 163 |
|
| 164 |
static constexpr base::uc32 kEnds[] = { |
| 165 |
kBmp1End, kLeadSurrogateEnd, kTrailSurrogateEnd, kBmp2End, kNonBmpEnd, |
| 166 |
}; |
| 167 |
|
| 168 |
CharacterRangeVector* const kTargets[] = { |
| 169 |
&bmp_, &lead_surrogates_, &trail_surrogates_, &bmp_, &non_bmp_, |
| 170 |
}; |
| 171 |
|
| 172 |
static constexpr int kCount = arraysize(kStarts); |
| 173 |
static_assert(kCount == arraysize(kEnds)); |
| 174 |
static_assert(kCount == arraysize(kTargets)); |
| 175 |
|
| 176 |
for (int i = 0; i < kCount; i++) { |
| 177 |
if (kStarts[i] > range.to()) break; |
| 178 |
const base::uc32 from = std::max(kStarts[i], range.from()); |
| 179 |
const base::uc32 to = std::min(kEnds[i], range.to()); |
| 180 |
if (from > to) continue; |
| 181 |
kTargets[i]->emplace_back(CharacterRange::Range(from, to)); |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
namespace { |
| 186 |
|
| 187 |
// Translates between new and old V8-isms (SmallVector, ZoneList). |
| 188 |
ZoneList<CharacterRange>* ToCanonicalZoneList( |
| 189 |
const UnicodeRangeSplitter::CharacterRangeVector* v, Zone* zone) { |
| 190 |
if (v->empty()) return nullptr; |
| 191 |
|
| 192 |
ZoneList<CharacterRange>* result = |
| 193 |
zone->New<ZoneList<CharacterRange>>(static_cast<int>(v->size()), zone); |
| 194 |
for (size_t i = 0; i < v->size(); i++) { |
| 195 |
result->Add(v->at(i), zone); |
| 196 |
} |
| 197 |
|
| 198 |
CharacterRange::Canonicalize(result); |
| 199 |
return result; |
| 200 |
} |
| 201 |
|
| 202 |
void AddBmpCharacters(RegExpCompiler* compiler, ChoiceNode* result, |
| 203 |
RegExpNode* on_success, UnicodeRangeSplitter* splitter) { |
| 204 |
ZoneList<CharacterRange>* bmp = |
| 205 |
ToCanonicalZoneList(splitter->bmp(), compiler->zone()); |
| 206 |
if (bmp == nullptr) return; |
| 207 |
result->AddAlternative(GuardedAlternative(TextNode::CreateForCharacterRanges( |
| 208 |
compiler->zone(), bmp, compiler->read_backward(), on_success))); |
| 209 |
} |
| 210 |
|
| 211 |
using UC16Range = uint32_t; // {from, to} packed into one uint32_t. |
| 212 |
constexpr UC16Range ToUC16Range(base::uc16 from, base::uc16 to) { |
| 213 |
return (static_cast<uint32_t>(from) << 16) | to; |
| 214 |
} |
| 215 |
constexpr base::uc16 ExtractFrom(UC16Range r) { |
| 216 |
return static_cast<base::uc16>(r >> 16); |
| 217 |
} |
| 218 |
constexpr base::uc16 ExtractTo(UC16Range r) { |
| 219 |
return static_cast<base::uc16>(r); |
| 220 |
} |
| 221 |
|
| 222 |
void AddNonBmpSurrogatePairs(RegExpCompiler* compiler, ChoiceNode* result, |
| 223 |
RegExpNode* on_success, |
| 224 |
UnicodeRangeSplitter* splitter) { |
| 225 |
DCHECK(!compiler->one_byte()); |
| 226 |
Zone* const zone = compiler->zone(); |
| 227 |
ZoneList<CharacterRange>* non_bmp = |
| 228 |
ToCanonicalZoneList(splitter->non_bmp(), zone); |
| 229 |
if (non_bmp == nullptr) return; |
| 230 |
|
| 231 |
// Translate each 32-bit code point range into the corresponding 16-bit code |
| 232 |
// unit representation consisting of the lead- and trail surrogate. |
| 233 |
// |
| 234 |
// The generated alternatives are grouped by the leading surrogate to avoid |
| 235 |
// emitting excessive code. For example, for |
| 236 |
// |
| 237 |
// { \ud800[\udc00-\udc01] |
| 238 |
// , \ud800[\udc05-\udc06] |
| 239 |
// } |
| 240 |
// |
| 241 |
// there's no need to emit matching code for the leading surrogate \ud800 |
| 242 |
// twice. We also create a dedicated grouping for full trailing ranges, i.e. |
| 243 |
// [dc00-dfff]. |
| 244 |
ZoneUnorderedMap<UC16Range, ZoneList<CharacterRange>*> grouped_by_leading( |
| 245 |
zone); |
| 246 |
ZoneList<CharacterRange>* leading_with_full_trailing_range = |
| 247 |
zone->New<ZoneList<CharacterRange>>(1, zone); |
| 248 |
const auto AddRange = [&](base::uc16 from_l, base::uc16 to_l, |
| 249 |
base::uc16 from_t, base::uc16 to_t) { |
| 250 |
const UC16Range leading_range = ToUC16Range(from_l, to_l); |
| 251 |
if (grouped_by_leading.count(leading_range) == 0) { |
| 252 |
if (from_t == kTrailSurrogateStart && to_t == kTrailSurrogateEnd) { |
| 253 |
leading_with_full_trailing_range->Add( |
| 254 |
CharacterRange::Range(from_l, to_l), zone); |
| 255 |
return; |
| 256 |
} |
| 257 |
grouped_by_leading[leading_range] = |
| 258 |
zone->New<ZoneList<CharacterRange>>(2, zone); |
| 259 |
} |
| 260 |
grouped_by_leading[leading_range]->Add(CharacterRange::Range(from_t, to_t), |
| 261 |
zone); |
| 262 |
}; |
| 263 |
|
| 264 |
// First, create the grouped ranges. |
| 265 |
CharacterRange::Canonicalize(non_bmp); |
| 266 |
for (int i = 0; i < non_bmp->length(); i++) { |
| 267 |
// Match surrogate pair. |
| 268 |
// E.g. [\u10005-\u11005] becomes |
| 269 |
// \ud800[\udc05-\udfff]| |
| 270 |
// [\ud801-\ud803][\udc00-\udfff]| |
| 271 |
// \ud804[\udc00-\udc05] |
| 272 |
base::uc32 from = non_bmp->at(i).from(); |
| 273 |
base::uc32 to = non_bmp->at(i).to(); |
| 274 |
base::uc16 from_l = unibrow::Utf16::LeadSurrogate(from); |
| 275 |
base::uc16 from_t = unibrow::Utf16::TrailSurrogate(from); |
| 276 |
base::uc16 to_l = unibrow::Utf16::LeadSurrogate(to); |
| 277 |
base::uc16 to_t = unibrow::Utf16::TrailSurrogate(to); |
| 278 |
|
| 279 |
if (from_l == to_l) { |
| 280 |
// The lead surrogate is the same. |
| 281 |
AddRange(from_l, to_l, from_t, to_t); |
| 282 |
continue; |
| 283 |
} |
| 284 |
|
| 285 |
if (from_t != kTrailSurrogateStart) { |
| 286 |
// Add [from_l][from_t-\udfff]. |
| 287 |
AddRange(from_l, from_l, from_t, kTrailSurrogateEnd); |
| 288 |
from_l++; |
| 289 |
} |
| 290 |
if (to_t != kTrailSurrogateEnd) { |
| 291 |
// Add [to_l][\udc00-to_t]. |
| 292 |
AddRange(to_l, to_l, kTrailSurrogateStart, to_t); |
| 293 |
to_l--; |
| 294 |
} |
| 295 |
if (from_l <= to_l) { |
| 296 |
// Add [from_l-to_l][\udc00-\udfff]. |
| 297 |
AddRange(from_l, to_l, kTrailSurrogateStart, kTrailSurrogateEnd); |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
// Create the actual TextNode now that ranges are fully grouped. |
| 302 |
if (!leading_with_full_trailing_range->is_empty()) { |
| 303 |
CharacterRange::Canonicalize(leading_with_full_trailing_range); |
| 304 |
result->AddAlternative(GuardedAlternative(TextNode::CreateForSurrogatePair( |
| 305 |
zone, leading_with_full_trailing_range, |
| 306 |
CharacterRange::Range(kTrailSurrogateStart, kTrailSurrogateEnd), |
| 307 |
compiler->read_backward(), on_success))); |
| 308 |
} |
| 309 |
for (const auto& it : grouped_by_leading) { |
| 310 |
CharacterRange leading_range = |
| 311 |
CharacterRange::Range(ExtractFrom(it.first), ExtractTo(it.first)); |
| 312 |
ZoneList<CharacterRange>* trailing_ranges = it.second; |
| 313 |
CharacterRange::Canonicalize(trailing_ranges); |
| 314 |
result->AddAlternative(GuardedAlternative(TextNode::CreateForSurrogatePair( |
| 315 |
zone, leading_range, trailing_ranges, compiler->read_backward(), |
| 316 |
on_success))); |
| 317 |
} |
| 318 |
} |
| 319 |
|
| 320 |
RegExpNode* NegativeLookaroundAgainstReadDirectionAndMatch( |
| 321 |
RegExpCompiler* compiler, ZoneList<CharacterRange>* lookbehind, |
| 322 |
ZoneList<CharacterRange>* match, RegExpNode* on_success, |
| 323 |
bool read_backward) { |
| 324 |
Zone* zone = compiler->zone(); |
| 325 |
RegExpNode* match_node = TextNode::CreateForCharacterRanges( |
| 326 |
zone, match, read_backward, on_success); |
| 327 |
int stack_register = compiler->UnicodeLookaroundStackRegister(); |
| 328 |
int position_register = compiler->UnicodeLookaroundPositionRegister(); |
| 329 |
RegExpLookaround::Builder lookaround(false, match_node, stack_register, |
| 330 |
position_register); |
| 331 |
RegExpNode* negative_match = TextNode::CreateForCharacterRanges( |
| 332 |
zone, lookbehind, !read_backward, lookaround.on_match_success()); |
| 333 |
return lookaround.ForMatch(negative_match); |
| 334 |
} |
| 335 |
|
| 336 |
RegExpNode* MatchAndNegativeLookaroundInReadDirection( |
| 337 |
RegExpCompiler* compiler, ZoneList<CharacterRange>* match, |
| 338 |
ZoneList<CharacterRange>* lookahead, RegExpNode* on_success, |
| 339 |
bool read_backward) { |
| 340 |
Zone* zone = compiler->zone(); |
| 341 |
int stack_register = compiler->UnicodeLookaroundStackRegister(); |
| 342 |
int position_register = compiler->UnicodeLookaroundPositionRegister(); |
| 343 |
RegExpLookaround::Builder lookaround(false, on_success, stack_register, |
| 344 |
position_register); |
| 345 |
RegExpNode* negative_match = TextNode::CreateForCharacterRanges( |
| 346 |
zone, lookahead, read_backward, lookaround.on_match_success()); |
| 347 |
return TextNode::CreateForCharacterRanges( |
| 348 |
zone, match, read_backward, lookaround.ForMatch(negative_match)); |
| 349 |
} |
| 350 |
|
| 351 |
void AddLoneLeadSurrogates(RegExpCompiler* compiler, ChoiceNode* result, |
| 352 |
RegExpNode* on_success, |
| 353 |
UnicodeRangeSplitter* splitter) { |
| 354 |
ZoneList<CharacterRange>* lead_surrogates = |
| 355 |
ToCanonicalZoneList(splitter->lead_surrogates(), compiler->zone()); |
| 356 |
if (lead_surrogates == nullptr) return; |
| 357 |
Zone* zone = compiler->zone(); |
| 358 |
// E.g. \ud801 becomes \ud801(?![\udc00-\udfff]). |
| 359 |
ZoneList<CharacterRange>* trail_surrogates = CharacterRange::List( |
| 360 |
zone, CharacterRange::Range(kTrailSurrogateStart, kTrailSurrogateEnd)); |
| 361 |
|
| 362 |
RegExpNode* match; |
| 363 |
if (compiler->read_backward()) { |
| 364 |
// Reading backward. Assert that reading forward, there is no trail |
| 365 |
// surrogate, and then backward match the lead surrogate. |
| 366 |
match = NegativeLookaroundAgainstReadDirectionAndMatch( |
| 367 |
compiler, trail_surrogates, lead_surrogates, on_success, true); |
| 368 |
} else { |
| 369 |
// Reading forward. Forward match the lead surrogate and assert that |
| 370 |
// no trail surrogate follows. |
| 371 |
match = MatchAndNegativeLookaroundInReadDirection( |
| 372 |
compiler, lead_surrogates, trail_surrogates, on_success, false); |
| 373 |
} |
| 374 |
result->AddAlternative(GuardedAlternative(match)); |
| 375 |
} |
| 376 |
|
| 377 |
void AddLoneTrailSurrogates(RegExpCompiler* compiler, ChoiceNode* result, |
| 378 |
RegExpNode* on_success, |
| 379 |
UnicodeRangeSplitter* splitter) { |
| 380 |
ZoneList<CharacterRange>* trail_surrogates = |
| 381 |
ToCanonicalZoneList(splitter->trail_surrogates(), compiler->zone()); |
| 382 |
if (trail_surrogates == nullptr) return; |
| 383 |
Zone* zone = compiler->zone(); |
| 384 |
// E.g. \udc01 becomes (?<![\ud800-\udbff])\udc01 |
| 385 |
ZoneList<CharacterRange>* lead_surrogates = CharacterRange::List( |
| 386 |
zone, CharacterRange::Range(kLeadSurrogateStart, kLeadSurrogateEnd)); |
| 387 |
|
| 388 |
RegExpNode* match; |
| 389 |
if (compiler->read_backward()) { |
| 390 |
// Reading backward. Backward match the trail surrogate and assert that no |
| 391 |
// lead surrogate precedes it. |
| 392 |
match = MatchAndNegativeLookaroundInReadDirection( |
| 393 |
compiler, trail_surrogates, lead_surrogates, on_success, true); |
| 394 |
} else { |
| 395 |
// Reading forward. Assert that reading backward, there is no lead |
| 396 |
// surrogate, and then forward match the trail surrogate. |
| 397 |
match = NegativeLookaroundAgainstReadDirectionAndMatch( |
| 398 |
compiler, lead_surrogates, trail_surrogates, on_success, false); |
| 399 |
} |
| 400 |
result->AddAlternative(GuardedAlternative(match)); |
| 401 |
} |
| 402 |
|
| 403 |
RegExpNode* UnanchoredAdvance(RegExpCompiler* compiler, |
| 404 |
RegExpNode* on_success) { |
| 405 |
// This implements ES2015 21.2.5.2.3, AdvanceStringIndex. |
| 406 |
DCHECK(!compiler->read_backward()); |
| 407 |
Zone* zone = compiler->zone(); |
| 408 |
// Advance any character. If the character happens to be a lead surrogate and |
| 409 |
// we advanced into the middle of a surrogate pair, it will work out, as |
| 410 |
// nothing will match from there. We will have to advance again, consuming |
| 411 |
// the associated trail surrogate. |
| 412 |
ZoneList<CharacterRange>* range = |
| 413 |
CharacterRange::List(zone, CharacterRange::Range(0, kMaxUtf16CodeUnit)); |
| 414 |
return TextNode::CreateForCharacterRanges(zone, range, false, on_success); |
| 415 |
} |
| 416 |
|
| 417 |
} // namespace |
| 418 |
|
| 419 |
// static |
| 420 |
// Only for /ui and /vi, not for /i regexps. |
| 421 |
void CharacterRange::AddUnicodeCaseEquivalents(ZoneList<CharacterRange>* ranges, |
| 422 |
Zone* zone) { |
| 423 |
#ifdef V8_INTL_SUPPORT |
| 424 |
DCHECK(IsCanonical(ranges)); |
| 425 |
|
| 426 |
// Micro-optimization to avoid passing large ranges to UnicodeSet::closeOver. |
| 427 |
// See also https://crbug.com/v8/6727. |
| 428 |
// TODO(jgruber): This only covers the special case of the {0,0x10FFFF} range, |
| 429 |
// which we use frequently internally. But large ranges can also easily be |
| 430 |
// created by the user. We might want to have a more general caching mechanism |
| 431 |
// for such ranges. |
| 432 |
if (ranges->length() == 1 && ranges->at(0).IsEverything(kNonBmpEnd)) return; |
| 433 |
|
| 434 |
// Use ICU to compute the case fold closure over the ranges. |
| 435 |
icu::UnicodeSet set; |
| 436 |
for (int i = 0; i < ranges->length(); i++) { |
| 437 |
set.add(ranges->at(i).from(), ranges->at(i).to()); |
| 438 |
} |
| 439 |
// Clear the ranges list without freeing the backing store. |
| 440 |
ranges->Rewind(0); |
| 441 |
set.closeOver(USET_SIMPLE_CASE_INSENSITIVE); |
| 442 |
for (int i = 0; i < set.getRangeCount(); i++) { |
| 443 |
ranges->Add(Range(set.getRangeStart(i), set.getRangeEnd(i)), zone); |
| 444 |
} |
| 445 |
// No errors and everything we collected have been ranges. |
| 446 |
Canonicalize(ranges); |
| 447 |
#endif // V8_INTL_SUPPORT |
| 448 |
} |
| 449 |
|
| 450 |
RegExpNode* RegExpClassRanges::ToNode(RegExpCompiler* compiler, |
| 451 |
RegExpNode* on_success) { |
| 452 |
set_.Canonicalize(); |
| 453 |
Zone* const zone = compiler->zone(); |
| 454 |
ZoneList<CharacterRange>* ranges = this->ranges(zone); |
| 455 |
|
| 456 |
const bool needs_case_folding = |
| 457 |
NeedsUnicodeCaseEquivalents(compiler->flags()) && !is_case_folded(); |
| 458 |
if (needs_case_folding) { |
| 459 |
CharacterRange::AddUnicodeCaseEquivalents(ranges, zone); |
| 460 |
} |
| 461 |
|
| 462 |
if (!IsEitherUnicode(compiler->flags()) || compiler->one_byte() || |
| 463 |
contains_split_surrogate()) { |
| 464 |
return zone->New<TextNode>(this, compiler->read_backward(), on_success); |
| 465 |
} |
| 466 |
|
| 467 |
if (is_negated()) { |
| 468 |
// With /v, character classes are never negated. |
| 469 |
// https://tc39.es/ecma262/#sec-compileatom |
| 470 |
// Atom :: CharacterClass |
| 471 |
// 4. Assert: cc.[[Invert]] is false. |
| 472 |
// Instead the complement is created when evaluating the class set. |
| 473 |
// The only exception is the "nothing range" (negated everything), which is |
| 474 |
// internally created for an empty set. |
| 475 |
DCHECK_IMPLIES( |
| 476 |
IsUnicodeSets(compiler->flags()), |
| 477 |
ranges->length() == 1 && ranges->first().IsEverything(kMaxCodePoint)); |
| 478 |
ZoneList<CharacterRange>* negated = |
| 479 |
zone->New<ZoneList<CharacterRange>>(2, zone); |
| 480 |
CharacterRange::Negate(ranges, negated, zone); |
| 481 |
ranges = negated; |
| 482 |
} |
| 483 |
|
| 484 |
if (ranges->length() == 0) { |
| 485 |
// The empty character class is used as a 'fail' node. |
| 486 |
RegExpClassRanges* fail = zone->New<RegExpClassRanges>(zone, ranges); |
| 487 |
return zone->New<TextNode>(fail, compiler->read_backward(), on_success); |
| 488 |
} |
| 489 |
|
| 490 |
if (set_.is_standard() && |
| 491 |
standard_type() == StandardCharacterSet::kEverything) { |
| 492 |
return UnanchoredAdvance(compiler, on_success); |
| 493 |
} |
| 494 |
|
| 495 |
// Split ranges in order to handle surrogates correctly: |
| 496 |
// - Surrogate pairs: translate the 32-bit code point into two uc16 code |
| 497 |
// units (irregexp operates only on code units). |
| 498 |
// - Lone surrogates: these require lookarounds to ensure we don't match in |
| 499 |
// the middle of a surrogate pair. |
| 500 |
ChoiceNode* result = zone->New<ChoiceNode>(2, zone); |
| 501 |
UnicodeRangeSplitter splitter(ranges); |
| 502 |
AddBmpCharacters(compiler, result, on_success, &splitter); |
| 503 |
AddNonBmpSurrogatePairs(compiler, result, on_success, &splitter); |
| 504 |
AddLoneLeadSurrogates(compiler, result, on_success, &splitter); |
| 505 |
AddLoneTrailSurrogates(compiler, result, on_success, &splitter); |
| 506 |
|
| 507 |
static constexpr int kMaxRangesToInline = 32; // Arbitrary. |
| 508 |
if (ranges->length() > kMaxRangesToInline) result->SetDoNotInline(); |
| 509 |
|
| 510 |
return result; |
| 511 |
} |
| 512 |
|
| 513 |
RegExpNode* RegExpClassSetOperand::ToNode(RegExpCompiler* compiler, |
| 514 |
RegExpNode* on_success) { |
| 515 |
Zone* zone = compiler->zone(); |
| 516 |
const int size = (has_strings() ? static_cast<int>(strings()->size()) : 0) + |
| 517 |
(ranges()->is_empty() ? 0 : 1); |
| 518 |
if (size == 0) { |
| 519 |
// If neither ranges nor strings are present, the operand is equal to an |
| 520 |
// empty range (matching nothing). |
| 521 |
ZoneList<CharacterRange>* empty = |
| 522 |
zone->template New<ZoneList<CharacterRange>>(0, zone); |
| 523 |
return zone->template New<RegExpClassRanges>(zone, empty) |
| 524 |
->ToNode(compiler, on_success); |
| 525 |
} |
| 526 |
ZoneList<RegExpTree*>* alternatives = |
| 527 |
zone->template New<ZoneList<RegExpTree*>>(size, zone); |
| 528 |
// Strings are sorted by length first (larger strings before shorter ones). |
| 529 |
// See the comment on CharacterClassStrings. |
| 530 |
// Empty strings (if present) are added after character ranges. |
| 531 |
RegExpTree* empty_string = nullptr; |
| 532 |
if (has_strings()) { |
| 533 |
for (auto string : *strings()) { |
| 534 |
if (string.second->IsEmpty()) { |
| 535 |
empty_string = string.second; |
| 536 |
} else { |
| 537 |
alternatives->Add(string.second, zone); |
| 538 |
} |
| 539 |
} |
| 540 |
} |
| 541 |
if (!ranges()->is_empty()) { |
| 542 |
// In unicode sets mode case folding has to be done at precise locations |
| 543 |
// (e.g. before building complements). |
| 544 |
// It is therefore the parsers responsibility to case fold (sub-) ranges |
| 545 |
// before creating ClassSetOperands. |
| 546 |
alternatives->Add(zone->template New<RegExpClassRanges>( |
| 547 |
zone, ranges(), RegExpClassRanges::IS_CASE_FOLDED), |
| 548 |
zone); |
| 549 |
} |
| 550 |
if (empty_string != nullptr) { |
| 551 |
alternatives->Add(empty_string, zone); |
| 552 |
} |
| 553 |
|
| 554 |
RegExpTree* node = nullptr; |
| 555 |
if (size == 1) { |
| 556 |
DCHECK_EQ(alternatives->length(), 1); |
| 557 |
node = alternatives->first(); |
| 558 |
} else { |
| 559 |
node = zone->template New<RegExpDisjunction>(alternatives); |
| 560 |
} |
| 561 |
return node->ToNode(compiler, on_success); |
| 562 |
} |
| 563 |
|
| 564 |
RegExpNode* RegExpClassSetExpression::ToNode(RegExpCompiler* compiler, |
| 565 |
RegExpNode* on_success) { |
| 566 |
Zone* zone = compiler->zone(); |
| 567 |
ZoneList<CharacterRange>* temp_ranges = |
| 568 |
zone->template New<ZoneList<CharacterRange>>(4, zone); |
| 569 |
RegExpClassSetOperand* root = ComputeExpression(this, temp_ranges, zone); |
| 570 |
return root->ToNode(compiler, on_success); |
| 571 |
} |
| 572 |
|
| 573 |
void RegExpClassSetOperand::Union(RegExpClassSetOperand* other, Zone* zone) { |
| 574 |
ranges()->AddAll(*other->ranges(), zone); |
| 575 |
if (other->has_strings()) { |
| 576 |
if (strings_ == nullptr) { |
| 577 |
strings_ = zone->template New<CharacterClassStrings>(zone); |
| 578 |
} |
| 579 |
strings()->insert(other->strings()->begin(), other->strings()->end()); |
| 580 |
} |
| 581 |
} |
| 582 |
|
| 583 |
void RegExpClassSetOperand::Intersect(RegExpClassSetOperand* other, |
| 584 |
ZoneList<CharacterRange>* temp_ranges, |
| 585 |
Zone* zone) { |
| 586 |
CharacterRange::Intersect(ranges(), other->ranges(), temp_ranges, zone); |
| 587 |
std::swap(*ranges(), *temp_ranges); |
| 588 |
temp_ranges->Rewind(0); |
| 589 |
if (has_strings()) { |
| 590 |
if (!other->has_strings()) { |
| 591 |
strings()->clear(); |
| 592 |
} else { |
| 593 |
for (auto iter = strings()->begin(); iter != strings()->end();) { |
| 594 |
if (other->strings()->find(iter->first) == other->strings()->end()) { |
| 595 |
iter = strings()->erase(iter); |
| 596 |
} else { |
| 597 |
iter++; |
| 598 |
} |
| 599 |
} |
| 600 |
} |
| 601 |
} |
| 602 |
} |
| 603 |
|
| 604 |
void RegExpClassSetOperand::Subtract(RegExpClassSetOperand* other, |
| 605 |
ZoneList<CharacterRange>* temp_ranges, |
| 606 |
Zone* zone) { |
| 607 |
CharacterRange::Subtract(ranges(), other->ranges(), temp_ranges, zone); |
| 608 |
std::swap(*ranges(), *temp_ranges); |
| 609 |
temp_ranges->Rewind(0); |
| 610 |
if (has_strings() && other->has_strings()) { |
| 611 |
for (auto iter = strings()->begin(); iter != strings()->end();) { |
| 612 |
if (other->strings()->find(iter->first) != other->strings()->end()) { |
| 613 |
iter = strings()->erase(iter); |
| 614 |
} else { |
| 615 |
iter++; |
| 616 |
} |
| 617 |
} |
| 618 |
} |
| 619 |
} |
| 620 |
|
| 621 |
// static |
| 622 |
RegExpClassSetOperand* RegExpClassSetExpression::ComputeExpression( |
| 623 |
RegExpTree* root, ZoneList<CharacterRange>* temp_ranges, Zone* zone) { |
| 624 |
DCHECK(temp_ranges->is_empty()); |
| 625 |
if (root->IsClassSetOperand()) { |
| 626 |
return root->AsClassSetOperand(); |
| 627 |
} |
| 628 |
DCHECK(root->IsClassSetExpression()); |
| 629 |
RegExpClassSetExpression* node = root->AsClassSetExpression(); |
| 630 |
RegExpClassSetOperand* result = |
| 631 |
ComputeExpression(node->operands()->at(0), temp_ranges, zone); |
| 632 |
switch (node->operation()) { |
| 633 |
case OperationType::kUnion: { |
| 634 |
for (int i = 1; i < node->operands()->length(); i++) { |
| 635 |
RegExpClassSetOperand* op = |
| 636 |
ComputeExpression(node->operands()->at(i), temp_ranges, zone); |
| 637 |
result->Union(op, zone); |
| 638 |
} |
| 639 |
CharacterRange::Canonicalize(result->ranges()); |
| 640 |
break; |
| 641 |
} |
| 642 |
case OperationType::kIntersection: { |
| 643 |
for (int i = 1; i < node->operands()->length(); i++) { |
| 644 |
RegExpClassSetOperand* op = |
| 645 |
ComputeExpression(node->operands()->at(i), temp_ranges, zone); |
| 646 |
result->Intersect(op, temp_ranges, zone); |
| 647 |
} |
| 648 |
break; |
| 649 |
} |
| 650 |
case OperationType::kSubtraction: { |
| 651 |
for (int i = 1; i < node->operands()->length(); i++) { |
| 652 |
RegExpClassSetOperand* op = |
| 653 |
ComputeExpression(node->operands()->at(i), temp_ranges, zone); |
| 654 |
result->Subtract(op, temp_ranges, zone); |
| 655 |
} |
| 656 |
break; |
| 657 |
} |
| 658 |
} |
| 659 |
if (node->is_negated()) { |
| 660 |
DCHECK(!result->has_strings()); |
| 661 |
CharacterRange::Negate(result->ranges(), temp_ranges, zone); |
| 662 |
std::swap(*result->ranges(), *temp_ranges); |
| 663 |
temp_ranges->Rewind(0); |
| 664 |
node->is_negated_ = false; |
| 665 |
} |
| 666 |
// Store the result as single operand of the current node. |
| 667 |
node->operands()->Set(0, result); |
| 668 |
node->operands()->Rewind(1); |
| 669 |
|
| 670 |
return result; |
| 671 |
} |
| 672 |
|
| 673 |
namespace { |
| 674 |
|
| 675 |
int CompareFirstChar(RegExpTree* const* a, RegExpTree* const* b) { |
| 676 |
RegExpAtom* atom1 = (*a)->AsAtom(); |
| 677 |
RegExpAtom* atom2 = (*b)->AsAtom(); |
| 678 |
base::uc16 character1 = atom1->data().at(0); |
| 679 |
base::uc16 character2 = atom2->data().at(0); |
| 680 |
if (character1 < character2) return -1; |
| 681 |
if (character1 > character2) return 1; |
| 682 |
return 0; |
| 683 |
} |
| 684 |
|
| 685 |
#ifdef V8_INTL_SUPPORT |
| 686 |
|
| 687 |
int CompareCaseInsensitive(const icu::UnicodeString& a, |
| 688 |
const icu::UnicodeString& b) { |
| 689 |
return a.caseCompare(b, U_FOLD_CASE_DEFAULT); |
| 690 |
} |
| 691 |
|
| 692 |
int CompareFirstCharCaseInsensitive(RegExpTree* const* a, |
| 693 |
RegExpTree* const* b) { |
| 694 |
RegExpAtom* atom1 = (*a)->AsAtom(); |
| 695 |
RegExpAtom* atom2 = (*b)->AsAtom(); |
| 696 |
return CompareCaseInsensitive(icu::UnicodeString{atom1->data().at(0)}, |
| 697 |
icu::UnicodeString{atom2->data().at(0)}); |
| 698 |
} |
| 699 |
|
| 700 |
bool Equals(bool ignore_case, const icu::UnicodeString& a, |
| 701 |
const icu::UnicodeString& b) { |
| 702 |
if (a == b) return true; |
| 703 |
if (ignore_case) return CompareCaseInsensitive(a, b) == 0; |
| 704 |
return false; // Case-sensitive equality already checked above. |
| 705 |
} |
| 706 |
|
| 707 |
bool CharAtEquals(bool ignore_case, int index, const RegExpAtom* a, |
| 708 |
const RegExpAtom* b) { |
| 709 |
return Equals(ignore_case, a->data().at(index), b->data().at(index)); |
| 710 |
} |
| 711 |
|
| 712 |
#else |
| 713 |
|
| 714 |
unibrow::uchar Canonical( |
| 715 |
unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize, |
| 716 |
unibrow::uchar c) { |
| 717 |
unibrow::uchar chars[unibrow::Ecma262Canonicalize::kMaxWidth]; |
| 718 |
int length = canonicalize->get(c, '\0', chars); |
| 719 |
DCHECK_LE(length, 1); |
| 720 |
unibrow::uchar canonical = c; |
| 721 |
if (length == 1) canonical = chars[0]; |
| 722 |
return canonical; |
| 723 |
} |
| 724 |
|
| 725 |
int CompareCaseInsensitive( |
| 726 |
unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize, |
| 727 |
unibrow::uchar a, unibrow::uchar b) { |
| 728 |
if (a == b) return 0; |
| 729 |
if (a >= 'a' || b >= 'a') { |
| 730 |
a = Canonical(canonicalize, a); |
| 731 |
b = Canonical(canonicalize, b); |
| 732 |
} |
| 733 |
return static_cast<int>(a) - static_cast<int>(b); |
| 734 |
} |
| 735 |
|
| 736 |
int CompareFirstCharCaseInsensitive( |
| 737 |
unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize, |
| 738 |
RegExpTree* const* a, RegExpTree* const* b) { |
| 739 |
RegExpAtom* atom1 = (*a)->AsAtom(); |
| 740 |
RegExpAtom* atom2 = (*b)->AsAtom(); |
| 741 |
return CompareCaseInsensitive(canonicalize, atom1->data().at(0), |
| 742 |
atom2->data().at(0)); |
| 743 |
} |
| 744 |
|
| 745 |
bool Equals(bool ignore_case, |
| 746 |
unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize, |
| 747 |
unibrow::uchar a, unibrow::uchar b) { |
| 748 |
if (a == b) return true; |
| 749 |
if (ignore_case) { |
| 750 |
return CompareCaseInsensitive(canonicalize, a, b) == 0; |
| 751 |
} |
| 752 |
return false; // Case-sensitive equality already checked above. |
| 753 |
} |
| 754 |
|
| 755 |
bool CharAtEquals(bool ignore_case, |
| 756 |
unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize, |
| 757 |
int index, const RegExpAtom* a, const RegExpAtom* b) { |
| 758 |
return Equals(ignore_case, canonicalize, a->data().at(index), |
| 759 |
b->data().at(index)); |
| 760 |
} |
| 761 |
|
| 762 |
#endif // V8_INTL_SUPPORT |
| 763 |
|
| 764 |
} // namespace |
| 765 |
|
| 766 |
// We can stable sort runs of atoms, since the order does not matter if they |
| 767 |
// start with different characters. |
| 768 |
// Returns true if any consecutive atoms were found. |
| 769 |
bool RegExpDisjunction::SortConsecutiveAtoms(RegExpCompiler* compiler) { |
| 770 |
ZoneList<RegExpTree*>* alternatives = this->alternatives(); |
| 771 |
int length = alternatives->length(); |
| 772 |
bool found_consecutive_atoms = false; |
| 773 |
for (int i = 0; i < length; i++) { |
| 774 |
while (i < length) { |
| 775 |
RegExpTree* alternative = alternatives->at(i); |
| 776 |
if (alternative->IsAtom()) break; |
| 777 |
i++; |
| 778 |
} |
| 779 |
// i is length or it is the index of an atom. |
| 780 |
if (i == length) break; |
| 781 |
int first_atom = i; |
| 782 |
i++; |
| 783 |
while (i < length) { |
| 784 |
RegExpTree* alternative = alternatives->at(i); |
| 785 |
if (!alternative->IsAtom()) break; |
| 786 |
i++; |
| 787 |
} |
| 788 |
// Sort atoms to get ones with common prefixes together. |
| 789 |
// This step is more tricky if we are in a case-independent regexp, |
| 790 |
// because it would change /is|I/ to /I|is/, and order matters when |
| 791 |
// the regexp parts don't match only disjoint starting points. To fix |
| 792 |
// this we have a version of CompareFirstChar that uses case- |
| 793 |
// independent character classes for comparison. |
| 794 |
DCHECK_LT(first_atom, alternatives->length()); |
| 795 |
DCHECK_LE(i, alternatives->length()); |
| 796 |
DCHECK_LE(first_atom, i); |
| 797 |
if (IsIgnoreCase(compiler->flags())) { |
| 798 |
#ifdef V8_INTL_SUPPORT |
| 799 |
alternatives->StableSort(CompareFirstCharCaseInsensitive, first_atom, |
| 800 |
i - first_atom); |
| 801 |
#else |
| 802 |
unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize = |
| 803 |
compiler->isolate()->regexp_macro_assembler_canonicalize(); |
| 804 |
auto compare_closure = [canonicalize](RegExpTree* const* a, |
| 805 |
RegExpTree* const* b) { |
| 806 |
return CompareFirstCharCaseInsensitive(canonicalize, a, b); |
| 807 |
}; |
| 808 |
alternatives->StableSort(compare_closure, first_atom, i - first_atom); |
| 809 |
#endif // V8_INTL_SUPPORT |
| 810 |
} else { |
| 811 |
alternatives->StableSort(CompareFirstChar, first_atom, i - first_atom); |
| 812 |
} |
| 813 |
if (i - first_atom > 1) found_consecutive_atoms = true; |
| 814 |
} |
| 815 |
return found_consecutive_atoms; |
| 816 |
} |
| 817 |
|
| 818 |
// Optimizes ab|ac|az to a(?:b|c|d). |
| 819 |
void RegExpDisjunction::RationalizeConsecutiveAtoms(RegExpCompiler* compiler) { |
| 820 |
Zone* zone = compiler->zone(); |
| 821 |
ZoneList<RegExpTree*>* alternatives = this->alternatives(); |
| 822 |
int length = alternatives->length(); |
| 823 |
const bool ignore_case = IsIgnoreCase(compiler->flags()); |
| 824 |
|
| 825 |
int write_posn = 0; |
| 826 |
int i = 0; |
| 827 |
while (i < length) { |
| 828 |
RegExpTree* alternative = alternatives->at(i); |
| 829 |
if (!alternative->IsAtom()) { |
| 830 |
alternatives->at(write_posn++) = alternatives->at(i); |
| 831 |
i++; |
| 832 |
continue; |
| 833 |
} |
| 834 |
RegExpAtom* const atom = alternative->AsAtom(); |
| 835 |
#ifdef V8_INTL_SUPPORT |
| 836 |
icu::UnicodeString common_prefix(atom->data().at(0)); |
| 837 |
#else |
| 838 |
unibrow::Mapping<unibrow::Ecma262Canonicalize>* const canonicalize = |
| 839 |
compiler->isolate()->regexp_macro_assembler_canonicalize(); |
| 840 |
unibrow::uchar common_prefix = atom->data().at(0); |
| 841 |
if (ignore_case) { |
| 842 |
common_prefix = Canonical(canonicalize, common_prefix); |
| 843 |
} |
| 844 |
#endif // V8_INTL_SUPPORT |
| 845 |
int first_with_prefix = i; |
| 846 |
int prefix_length = atom->length(); |
| 847 |
i++; |
| 848 |
while (i < length) { |
| 849 |
alternative = alternatives->at(i); |
| 850 |
if (!alternative->IsAtom()) break; |
| 851 |
RegExpAtom* const alt_atom = alternative->AsAtom(); |
| 852 |
#ifdef V8_INTL_SUPPORT |
| 853 |
icu::UnicodeString new_prefix(alt_atom->data().at(0)); |
| 854 |
if (!Equals(ignore_case, new_prefix, common_prefix)) break; |
| 855 |
#else |
| 856 |
unibrow::uchar new_prefix = alt_atom->data().at(0); |
| 857 |
if (!Equals(ignore_case, canonicalize, new_prefix, common_prefix)) break; |
| 858 |
#endif // V8_INTL_SUPPORT |
| 859 |
prefix_length = std::min(prefix_length, alt_atom->length()); |
| 860 |
i++; |
| 861 |
} |
| 862 |
if (i > first_with_prefix + 2) { |
| 863 |
// Found worthwhile run of alternatives with common prefix of at least one |
| 864 |
// character. The sorting function above did not sort on more than one |
| 865 |
// character for reasons of correctness, but there may still be a longer |
| 866 |
// common prefix if the terms were similar or presorted in the input. |
| 867 |
// Find out how long the common prefix is. |
| 868 |
int run_length = i - first_with_prefix; |
| 869 |
RegExpAtom* const alt_atom = |
| 870 |
alternatives->at(first_with_prefix)->AsAtom(); |
| 871 |
for (int j = 1; j < run_length && prefix_length > 1; j++) { |
| 872 |
RegExpAtom* old_atom = |
| 873 |
alternatives->at(j + first_with_prefix)->AsAtom(); |
| 874 |
for (int k = 1; k < prefix_length; k++) { |
| 875 |
#ifdef V8_INTL_SUPPORT |
| 876 |
if (!CharAtEquals(ignore_case, k, alt_atom, old_atom)) { |
| 877 |
#else |
| 878 |
if (!CharAtEquals(ignore_case, canonicalize, k, alt_atom, old_atom)) { |
| 879 |
#endif // V8_INTL_SUPPORT |
| 880 |
prefix_length = k; |
| 881 |
break; |
| 882 |
} |
| 883 |
} |
| 884 |
} |
| 885 |
RegExpAtom* prefix = |
| 886 |
zone->New<RegExpAtom>(alt_atom->data().SubVector(0, prefix_length)); |
| 887 |
ZoneList<RegExpTree*>* pair = zone->New<ZoneList<RegExpTree*>>(2, zone); |
| 888 |
pair->Add(prefix, zone); |
| 889 |
ZoneList<RegExpTree*>* suffixes = |
| 890 |
zone->New<ZoneList<RegExpTree*>>(run_length, zone); |
| 891 |
for (int j = 0; j < run_length; j++) { |
| 892 |
RegExpAtom* old_atom = |
| 893 |
alternatives->at(j + first_with_prefix)->AsAtom(); |
| 894 |
int len = old_atom->length(); |
| 895 |
if (len == prefix_length) { |
| 896 |
suffixes->Add(zone->New<RegExpEmpty>(), zone); |
| 897 |
} else { |
| 898 |
RegExpTree* suffix = zone->New<RegExpAtom>( |
| 899 |
old_atom->data().SubVector(prefix_length, old_atom->length())); |
| 900 |
suffixes->Add(suffix, zone); |
| 901 |
} |
| 902 |
} |
| 903 |
pair->Add(zone->New<RegExpDisjunction>(suffixes), zone); |
| 904 |
alternatives->at(write_posn++) = zone->New<RegExpAlternative>(pair); |
| 905 |
} else { |
| 906 |
// Just copy any non-worthwhile alternatives. |
| 907 |
for (int j = first_with_prefix; j < i; j++) { |
| 908 |
alternatives->at(write_posn++) = alternatives->at(j); |
| 909 |
} |
| 910 |
} |
| 911 |
} |
| 912 |
alternatives->Rewind(write_posn); // Trim end of array. |
| 913 |
} |
| 914 |
|
| 915 |
// Optimizes b|c|z to [bcz]. |
| 916 |
void RegExpDisjunction::FixSingleCharacterDisjunctions( |
| 917 |
RegExpCompiler* compiler) { |
| 918 |
Zone* zone = compiler->zone(); |
| 919 |
ZoneList<RegExpTree*>* alternatives = this->alternatives(); |
| 920 |
int length = alternatives->length(); |
| 921 |
|
| 922 |
int write_posn = 0; |
| 923 |
int i = 0; |
| 924 |
while (i < length) { |
| 925 |
RegExpTree* alternative = alternatives->at(i); |
| 926 |
if (!alternative->IsAtom()) { |
| 927 |
alternatives->at(write_posn++) = alternatives->at(i); |
| 928 |
i++; |
| 929 |
continue; |
| 930 |
} |
| 931 |
RegExpAtom* const atom = alternative->AsAtom(); |
| 932 |
if (atom->length() != 1) { |
| 933 |
alternatives->at(write_posn++) = alternatives->at(i); |
| 934 |
i++; |
| 935 |
continue; |
| 936 |
} |
| 937 |
const RegExpFlags flags = compiler->flags(); |
| 938 |
DCHECK_IMPLIES(IsEitherUnicode(flags), |
| 939 |
!unibrow::Utf16::IsLeadSurrogate(atom->data().at(0))); |
| 940 |
bool contains_trail_surrogate = |
| 941 |
unibrow::Utf16::IsTrailSurrogate(atom->data().at(0)); |
| 942 |
int first_in_run = i; |
| 943 |
i++; |
| 944 |
// Find a run of single-character atom alternatives that have identical |
| 945 |
// flags (case independence and unicode-ness). |
| 946 |
while (i < length) { |
| 947 |
alternative = alternatives->at(i); |
| 948 |
if (!alternative->IsAtom()) break; |
| 949 |
RegExpAtom* const alt_atom = alternative->AsAtom(); |
| 950 |
if (alt_atom->length() != 1) break; |
| 951 |
DCHECK_IMPLIES(IsEitherUnicode(flags), |
| 952 |
!unibrow::Utf16::IsLeadSurrogate(alt_atom->data().at(0))); |
| 953 |
contains_trail_surrogate |= |
| 954 |
unibrow::Utf16::IsTrailSurrogate(alt_atom->data().at(0)); |
| 955 |
i++; |
| 956 |
} |
| 957 |
if (i > first_in_run + 1) { |
| 958 |
// Found non-trivial run of single-character alternatives. |
| 959 |
int run_length = i - first_in_run; |
| 960 |
ZoneList<CharacterRange>* ranges = |
| 961 |
zone->New<ZoneList<CharacterRange>>(2, zone); |
| 962 |
for (int j = 0; j < run_length; j++) { |
| 963 |
RegExpAtom* old_atom = alternatives->at(j + first_in_run)->AsAtom(); |
| 964 |
DCHECK_EQ(old_atom->length(), 1); |
| 965 |
ranges->Add(CharacterRange::Singleton(old_atom->data().at(0)), zone); |
| 966 |
} |
| 967 |
RegExpClassRanges::ClassRangesFlags class_ranges_flags; |
| 968 |
if (IsEitherUnicode(flags) && contains_trail_surrogate) { |
| 969 |
class_ranges_flags = RegExpClassRanges::CONTAINS_SPLIT_SURROGATE; |
| 970 |
} |
| 971 |
alternatives->at(write_posn++) = |
| 972 |
zone->New<RegExpClassRanges>(zone, ranges, class_ranges_flags); |
| 973 |
} else { |
| 974 |
// Just copy any trivial alternatives. |
| 975 |
for (int j = first_in_run; j < i; j++) { |
| 976 |
alternatives->at(write_posn++) = alternatives->at(j); |
| 977 |
} |
| 978 |
} |
| 979 |
} |
| 980 |
alternatives->Rewind(write_posn); // Trim end of array. |
| 981 |
} |
| 982 |
|
| 983 |
RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler, |
| 984 |
RegExpNode* on_success) { |
| 985 |
compiler->ToNodeMaybeCheckForStackOverflow(); |
| 986 |
|
| 987 |
ZoneList<RegExpTree*>* alternatives = this->alternatives(); |
| 988 |
|
| 989 |
if (alternatives->length() > 2) { |
| 990 |
bool found_consecutive_atoms = SortConsecutiveAtoms(compiler); |
| 991 |
if (found_consecutive_atoms) RationalizeConsecutiveAtoms(compiler); |
| 992 |
FixSingleCharacterDisjunctions(compiler); |
| 993 |
if (alternatives->length() == 1) { |
| 994 |
return alternatives->at(0)->ToNode(compiler, on_success); |
| 995 |
} |
| 996 |
} |
| 997 |
|
| 998 |
int length = alternatives->length(); |
| 999 |
|
| 1000 |
ChoiceNode* result = |
| 1001 |
compiler->zone()->New<ChoiceNode>(length, compiler->zone()); |
| 1002 |
for (int i = 0; i < length; i++) { |
| 1003 |
GuardedAlternative alternative( |
| 1004 |
alternatives->at(i)->ToNode(compiler, on_success)); |
| 1005 |
result->AddAlternative(alternative); |
| 1006 |
} |
| 1007 |
return result; |
| 1008 |
} |
| 1009 |
|
| 1010 |
RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler, |
| 1011 |
RegExpNode* on_success) { |
| 1012 |
return ToNode(min(), max(), is_greedy(), body(), compiler, on_success); |
| 1013 |
} |
| 1014 |
|
| 1015 |
namespace { |
| 1016 |
// Desugar \b to (?<=\w)(?=\W)|(?<=\W)(?=\w) and |
| 1017 |
// \B to (?<=\w)(?=\w)|(?<=\W)(?=\W) |
| 1018 |
RegExpNode* BoundaryAssertionAsLookaround(RegExpCompiler* compiler, |
| 1019 |
RegExpNode* on_success, |
| 1020 |
RegExpAssertion::Type type) { |
| 1021 |
CHECK(NeedsUnicodeCaseEquivalents(compiler->flags())); |
| 1022 |
Zone* zone = compiler->zone(); |
| 1023 |
ZoneList<CharacterRange>* word_range = |
| 1024 |
zone->New<ZoneList<CharacterRange>>(2, zone); |
| 1025 |
CharacterRange::AddClassEscape(StandardCharacterSet::kWord, word_range, true, |
| 1026 |
zone); |
| 1027 |
int stack_register = compiler->UnicodeLookaroundStackRegister(); |
| 1028 |
int position_register = compiler->UnicodeLookaroundPositionRegister(); |
| 1029 |
ChoiceNode* result = zone->New<ChoiceNode>(2, zone); |
| 1030 |
// Add two choices. The (non-)boundary could start with a word or |
| 1031 |
// a non-word-character. |
| 1032 |
for (int i = 0; i < 2; i++) { |
| 1033 |
bool lookbehind_for_word = i == 0; |
| 1034 |
bool lookahead_for_word = |
| 1035 |
(type == RegExpAssertion::Type::BOUNDARY) ^ lookbehind_for_word; |
| 1036 |
// Look to the left. |
| 1037 |
RegExpLookaround::Builder lookbehind(lookbehind_for_word, on_success, |
| 1038 |
stack_register, position_register); |
| 1039 |
RegExpNode* backward = TextNode::CreateForCharacterRanges( |
| 1040 |
zone, word_range, true, lookbehind.on_match_success()); |
| 1041 |
// Look to the right. |
| 1042 |
RegExpLookaround::Builder lookahead(lookahead_for_word, |
| 1043 |
lookbehind.ForMatch(backward), |
| 1044 |
stack_register, position_register); |
| 1045 |
RegExpNode* forward = TextNode::CreateForCharacterRanges( |
| 1046 |
zone, word_range, false, lookahead.on_match_success()); |
| 1047 |
result->AddAlternative(GuardedAlternative(lookahead.ForMatch(forward))); |
| 1048 |
} |
| 1049 |
return result; |
| 1050 |
} |
| 1051 |
} // anonymous namespace |
| 1052 |
|
| 1053 |
RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler, |
| 1054 |
RegExpNode* on_success) { |
| 1055 |
NodeInfo info; |
| 1056 |
Zone* zone = compiler->zone(); |
| 1057 |
|
| 1058 |
switch (assertion_type()) { |
| 1059 |
case Type::START_OF_LINE: |
| 1060 |
return AssertionNode::AfterNewline(on_success); |
| 1061 |
case Type::START_OF_INPUT: |
| 1062 |
return AssertionNode::AtStart(on_success); |
| 1063 |
case Type::BOUNDARY: |
| 1064 |
return NeedsUnicodeCaseEquivalents(compiler->flags()) |
| 1065 |
? BoundaryAssertionAsLookaround(compiler, on_success, |
| 1066 |
Type::BOUNDARY) |
| 1067 |
: AssertionNode::AtBoundary(on_success); |
| 1068 |
case Type::NON_BOUNDARY: |
| 1069 |
return NeedsUnicodeCaseEquivalents(compiler->flags()) |
| 1070 |
? BoundaryAssertionAsLookaround(compiler, on_success, |
| 1071 |
Type::NON_BOUNDARY) |
| 1072 |
: AssertionNode::AtNonBoundary(on_success); |
| 1073 |
case Type::END_OF_INPUT: |
| 1074 |
return AssertionNode::AtEnd(on_success); |
| 1075 |
case Type::END_OF_LINE: { |
| 1076 |
// Compile $ in multiline regexps as an alternation with a positive |
| 1077 |
// lookahead in one side and an end-of-input on the other side. |
| 1078 |
// We need two registers for the lookahead. |
| 1079 |
int stack_pointer_register = compiler->AllocateRegister(); |
| 1080 |
int position_register = compiler->AllocateRegister(); |
| 1081 |
// The ChoiceNode to distinguish between a newline and end-of-input. |
| 1082 |
ChoiceNode* result = zone->New<ChoiceNode>(2, zone); |
| 1083 |
// Create a newline atom. |
| 1084 |
ZoneList<CharacterRange>* newline_ranges = |
| 1085 |
zone->New<ZoneList<CharacterRange>>(3, zone); |
| 1086 |
CharacterRange::AddClassEscape(StandardCharacterSet::kLineTerminator, |
| 1087 |
newline_ranges, false, zone); |
| 1088 |
RegExpClassRanges* newline_atom = |
| 1089 |
zone->New<RegExpClassRanges>(StandardCharacterSet::kLineTerminator); |
| 1090 |
ActionNode* submatch_success = ActionNode::PositiveSubmatchSuccess( |
| 1091 |
stack_pointer_register, position_register, |
| 1092 |
0, // No captures inside. |
| 1093 |
-1, // Ignored if no captures. |
| 1094 |
on_success); |
| 1095 |
TextNode* newline_matcher = |
| 1096 |
zone->New<TextNode>(newline_atom, false, submatch_success); |
| 1097 |
// Create an end-of-input matcher. |
| 1098 |
RegExpNode* end_of_line = ActionNode::BeginPositiveSubmatch( |
| 1099 |
stack_pointer_register, position_register, newline_matcher, |
| 1100 |
submatch_success); |
| 1101 |
// Add the two alternatives to the ChoiceNode. |
| 1102 |
GuardedAlternative eol_alternative(end_of_line); |
| 1103 |
result->AddAlternative(eol_alternative); |
| 1104 |
GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success)); |
| 1105 |
result->AddAlternative(end_alternative); |
| 1106 |
return result; |
| 1107 |
} |
| 1108 |
default: |
| 1109 |
UNREACHABLE(); |
| 1110 |
} |
| 1111 |
} |
| 1112 |
|
| 1113 |
RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler, |
| 1114 |
RegExpNode* on_success) { |
| 1115 |
RegExpNode* backref_node = on_success; |
| 1116 |
// Only one of the captures in the list can actually match. Since |
| 1117 |
// back-references to unmatched captures are treated as empty, we can simply |
| 1118 |
// create back-references to all possible captures. |
| 1119 |
for (auto capture : *captures()) { |
| 1120 |
backref_node = compiler->zone()->New<BackReferenceNode>( |
| 1121 |
RegExpCapture::StartRegister(capture->index()), |
| 1122 |
RegExpCapture::EndRegister(capture->index()), compiler->read_backward(), |
| 1123 |
backref_node); |
| 1124 |
} |
| 1125 |
return backref_node; |
| 1126 |
} |
| 1127 |
|
| 1128 |
RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler, |
| 1129 |
RegExpNode* on_success) { |
| 1130 |
return on_success; |
| 1131 |
} |
| 1132 |
|
| 1133 |
namespace { |
| 1134 |
|
| 1135 |
class V8_NODISCARD ModifiersScope { |
| 1136 |
public: |
| 1137 |
ModifiersScope(RegExpCompiler* compiler, RegExpFlags flags) |
| 1138 |
: compiler_(compiler), previous_flags_(compiler->flags()) { |
| 1139 |
compiler->set_flags(flags); |
| 1140 |
} |
| 1141 |
~ModifiersScope() { compiler_->set_flags(previous_flags_); } |
| 1142 |
|
| 1143 |
private: |
| 1144 |
RegExpCompiler* compiler_; |
| 1145 |
const RegExpFlags previous_flags_; |
| 1146 |
}; |
| 1147 |
|
| 1148 |
} // namespace |
| 1149 |
|
| 1150 |
RegExpNode* RegExpGroup::ToNode(RegExpCompiler* compiler, |
| 1151 |
RegExpNode* on_success) { |
| 1152 |
// If no flags are modified, simply convert and return the body. |
| 1153 |
if (flags() == compiler->flags()) { |
| 1154 |
return body_->ToNode(compiler, on_success); |
| 1155 |
} |
| 1156 |
// Reset flags for successor node. |
| 1157 |
const RegExpFlags old_flags = compiler->flags(); |
| 1158 |
on_success = ActionNode::ModifyFlags(old_flags, on_success); |
| 1159 |
|
| 1160 |
// Convert body using modifier. |
| 1161 |
ModifiersScope modifiers_scope(compiler, flags()); |
| 1162 |
RegExpNode* body = body_->ToNode(compiler, on_success); |
| 1163 |
|
| 1164 |
// Wrap body into modifier node. |
| 1165 |
RegExpNode* modified_body = ActionNode::ModifyFlags(flags(), body); |
| 1166 |
return modified_body; |
| 1167 |
} |
| 1168 |
|
| 1169 |
RegExpLookaround::Builder::Builder(bool is_positive, RegExpNode* on_success, |
| 1170 |
int stack_pointer_register, |
| 1171 |
int position_register, |
| 1172 |
int capture_register_count, |
| 1173 |
int capture_register_start) |
| 1174 |
: is_positive_(is_positive), |
| 1175 |
on_success_(on_success), |
| 1176 |
stack_pointer_register_(stack_pointer_register), |
| 1177 |
position_register_(position_register) { |
| 1178 |
if (is_positive_) { |
| 1179 |
on_match_success_ = ActionNode::PositiveSubmatchSuccess( |
| 1180 |
stack_pointer_register, position_register, capture_register_count, |
| 1181 |
capture_register_start, on_success_); |
| 1182 |
} else { |
| 1183 |
Zone* zone = on_success_->zone(); |
| 1184 |
on_match_success_ = zone->New<NegativeSubmatchSuccess>( |
| 1185 |
stack_pointer_register, position_register, capture_register_count, |
| 1186 |
capture_register_start, zone); |
| 1187 |
} |
| 1188 |
} |
| 1189 |
|
| 1190 |
RegExpNode* RegExpLookaround::Builder::ForMatch(RegExpNode* match) { |
| 1191 |
if (is_positive_) { |
| 1192 |
ActionNode* on_match_success = on_match_success_->AsActionNode(); |
| 1193 |
return ActionNode::BeginPositiveSubmatch( |
| 1194 |
stack_pointer_register_, position_register_, match, on_match_success); |
| 1195 |
} else { |
| 1196 |
Zone* zone = on_success_->zone(); |
| 1197 |
// We use a ChoiceNode to represent the negative lookaround. The first |
| 1198 |
// alternative is the negative match. On success, the end node backtracks. |
| 1199 |
// On failure, the second alternative is tried and leads to success. |
| 1200 |
// NegativeLookaroundChoiceNode is a special ChoiceNode that ignores the |
| 1201 |
// first exit when calculating quick checks. |
| 1202 |
ChoiceNode* choice_node = zone->New<NegativeLookaroundChoiceNode>( |
| 1203 |
GuardedAlternative(match), GuardedAlternative(on_success_), zone); |
| 1204 |
return ActionNode::BeginNegativeSubmatch(stack_pointer_register_, |
| 1205 |
position_register_, choice_node); |
| 1206 |
} |
| 1207 |
} |
| 1208 |
|
| 1209 |
RegExpNode* RegExpLookaround::ToNode(RegExpCompiler* compiler, |
| 1210 |
RegExpNode* on_success) { |
| 1211 |
compiler->ToNodeMaybeCheckForStackOverflow(); |
| 1212 |
|
| 1213 |
int stack_pointer_register = compiler->AllocateRegister(); |
| 1214 |
int position_register = compiler->AllocateRegister(); |
| 1215 |
|
| 1216 |
const int registers_per_capture = 2; |
| 1217 |
const int register_of_first_capture = 2; |
| 1218 |
int register_count = capture_count_ * registers_per_capture; |
| 1219 |
int register_start = |
| 1220 |
register_of_first_capture + capture_from_ * registers_per_capture; |
| 1221 |
|
| 1222 |
RegExpNode* result; |
| 1223 |
bool was_reading_backward = compiler->read_backward(); |
| 1224 |
compiler->set_read_backward(type() == LOOKBEHIND); |
| 1225 |
Builder builder(is_positive(), on_success, stack_pointer_register, |
| 1226 |
position_register, register_count, register_start); |
| 1227 |
RegExpNode* match = body_->ToNode(compiler, builder.on_match_success()); |
| 1228 |
result = builder.ForMatch(match); |
| 1229 |
compiler->set_read_backward(was_reading_backward); |
| 1230 |
return result; |
| 1231 |
} |
| 1232 |
|
| 1233 |
RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler, |
| 1234 |
RegExpNode* on_success) { |
| 1235 |
return ToNode(body(), index(), compiler, on_success); |
| 1236 |
} |
| 1237 |
|
| 1238 |
RegExpNode* RegExpCapture::ToNode(RegExpTree* body, int index, |
| 1239 |
RegExpCompiler* compiler, |
| 1240 |
RegExpNode* on_success) { |
| 1241 |
DCHECK_NOT_NULL(body); |
| 1242 |
int start_reg = RegExpCapture::StartRegister(index); |
| 1243 |
int end_reg = RegExpCapture::EndRegister(index); |
| 1244 |
if (compiler->read_backward()) std::swap(start_reg, end_reg); |
| 1245 |
RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success); |
| 1246 |
RegExpNode* body_node = body->ToNode(compiler, store_end); |
| 1247 |
return ActionNode::StorePosition(start_reg, true, body_node); |
| 1248 |
} |
| 1249 |
|
| 1250 |
namespace { |
| 1251 |
|
| 1252 |
class AssertionSequenceRewriter final { |
| 1253 |
public: |
| 1254 |
// TODO(jgruber): Consider moving this to a separate AST tree rewriter pass |
| 1255 |
// instead of sprinkling rewrites into the AST->Node conversion process. |
| 1256 |
static void MaybeRewrite(ZoneList<RegExpTree*>* terms, Zone* zone) { |
| 1257 |
AssertionSequenceRewriter rewriter(terms, zone); |
| 1258 |
|
| 1259 |
static constexpr int kNoIndex = -1; |
| 1260 |
int from = kNoIndex; |
| 1261 |
|
| 1262 |
for (int i = 0; i < terms->length(); i++) { |
| 1263 |
RegExpTree* t = terms->at(i); |
| 1264 |
if (from == kNoIndex && t->IsAssertion()) { |
| 1265 |
from = i; // Start a sequence. |
| 1266 |
} else if (from != kNoIndex && !t->IsAssertion()) { |
| 1267 |
// Terminate and process the sequence. |
| 1268 |
if (i - from > 1) rewriter.Rewrite(from, i); |
| 1269 |
from = kNoIndex; |
| 1270 |
} |
| 1271 |
} |
| 1272 |
|
| 1273 |
if (from != kNoIndex && terms->length() - from > 1) { |
| 1274 |
rewriter.Rewrite(from, terms->length()); |
| 1275 |
} |
| 1276 |
} |
| 1277 |
|
| 1278 |
// All assertions are zero width. A consecutive sequence of assertions is |
| 1279 |
// order-independent. There's two ways we can optimize here: |
| 1280 |
// 1. fold all identical assertions. |
| 1281 |
// 2. if any assertion combinations are known to fail (e.g. \b\B), the entire |
| 1282 |
// sequence fails. |
| 1283 |
void Rewrite(int from, int to) { |
| 1284 |
DCHECK_GT(to, from + 1); |
| 1285 |
|
| 1286 |
// Bitfield of all seen assertions. |
| 1287 |
uint32_t seen_assertions = 0; |
| 1288 |
static_assert(static_cast<int>(RegExpAssertion::Type::LAST_ASSERTION_TYPE) < |
| 1289 |
kUInt32Size * kBitsPerByte); |
| 1290 |
|
| 1291 |
for (int i = from; i < to; i++) { |
| 1292 |
RegExpAssertion* t = terms_->at(i)->AsAssertion(); |
| 1293 |
const uint32_t bit = 1 << static_cast<int>(t->assertion_type()); |
| 1294 |
|
| 1295 |
if (seen_assertions & bit) { |
| 1296 |
// Fold duplicates. |
| 1297 |
terms_->Set(i, zone_->New<RegExpEmpty>()); |
| 1298 |
} |
| 1299 |
|
| 1300 |
seen_assertions |= bit; |
| 1301 |
} |
| 1302 |
|
| 1303 |
// Collapse failures. |
| 1304 |
const uint32_t always_fails_mask = |
| 1305 |
1 << static_cast<int>(RegExpAssertion::Type::BOUNDARY) | |
| 1306 |
1 << static_cast<int>(RegExpAssertion::Type::NON_BOUNDARY); |
| 1307 |
if ((seen_assertions & always_fails_mask) == always_fails_mask) { |
| 1308 |
ReplaceSequenceWithFailure(from, to); |
| 1309 |
} |
| 1310 |
} |
| 1311 |
|
| 1312 |
void ReplaceSequenceWithFailure(int from, int to) { |
| 1313 |
// Replace the entire sequence with a single node that always fails. |
| 1314 |
// TODO(jgruber): Consider adding an explicit Fail kind. Until then, the |
| 1315 |
// negated '*' (everything) range serves the purpose. |
| 1316 |
ZoneList<CharacterRange>* ranges = |
| 1317 |
zone_->New<ZoneList<CharacterRange>>(0, zone_); |
| 1318 |
RegExpClassRanges* cc = zone_->New<RegExpClassRanges>(zone_, ranges); |
| 1319 |
terms_->Set(from, cc); |
| 1320 |
|
| 1321 |
// Zero out the rest. |
| 1322 |
RegExpEmpty* empty = zone_->New<RegExpEmpty>(); |
| 1323 |
for (int i = from + 1; i < to; i++) terms_->Set(i, empty); |
| 1324 |
} |
| 1325 |
|
| 1326 |
private: |
| 1327 |
AssertionSequenceRewriter(ZoneList<RegExpTree*>* terms, Zone* zone) |
| 1328 |
: zone_(zone), terms_(terms) {} |
| 1329 |
|
| 1330 |
Zone* zone_; |
| 1331 |
ZoneList<RegExpTree*>* terms_; |
| 1332 |
}; |
| 1333 |
|
| 1334 |
} // namespace |
| 1335 |
|
| 1336 |
RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler, |
| 1337 |
RegExpNode* on_success) { |
| 1338 |
compiler->ToNodeMaybeCheckForStackOverflow(); |
| 1339 |
|
| 1340 |
ZoneList<RegExpTree*>* children = nodes(); |
| 1341 |
|
| 1342 |
AssertionSequenceRewriter::MaybeRewrite(children, compiler->zone()); |
| 1343 |
|
| 1344 |
RegExpNode* current = on_success; |
| 1345 |
if (compiler->read_backward()) { |
| 1346 |
for (int i = 0; i < children->length(); i++) { |
| 1347 |
current = children->at(i)->ToNode(compiler, current); |
| 1348 |
} |
| 1349 |
} else { |
| 1350 |
for (int i = children->length() - 1; i >= 0; i--) { |
| 1351 |
current = children->at(i)->ToNode(compiler, current); |
| 1352 |
} |
| 1353 |
} |
| 1354 |
return current; |
| 1355 |
} |
| 1356 |
|
| 1357 |
namespace { |
| 1358 |
|
| 1359 |
void AddClass(const int* elmv, int elmc, ZoneList<CharacterRange>* ranges, |
| 1360 |
Zone* zone) { |
| 1361 |
elmc--; |
| 1362 |
DCHECK_EQ(kRangeEndMarker, elmv[elmc]); |
| 1363 |
for (int i = 0; i < elmc; i += 2) { |
| 1364 |
DCHECK(elmv[i] < elmv[i + 1]); |
| 1365 |
ranges->Add(CharacterRange::Range(elmv[i], elmv[i + 1] - 1), zone); |
| 1366 |
} |
| 1367 |
} |
| 1368 |
|
| 1369 |
void AddClassNegated(const int* elmv, int elmc, |
| 1370 |
ZoneList<CharacterRange>* ranges, Zone* zone) { |
| 1371 |
elmc--; |
| 1372 |
DCHECK_EQ(kRangeEndMarker, elmv[elmc]); |
| 1373 |
DCHECK_NE(0x0000, elmv[0]); |
| 1374 |
DCHECK_NE(kMaxCodePoint, elmv[elmc - 1]); |
| 1375 |
base::uc16 last = 0x0000; |
| 1376 |
for (int i = 0; i < elmc; i += 2) { |
| 1377 |
DCHECK(last <= elmv[i] - 1); |
| 1378 |
DCHECK(elmv[i] < elmv[i + 1]); |
| 1379 |
ranges->Add(CharacterRange::Range(last, elmv[i] - 1), zone); |
| 1380 |
last = elmv[i + 1]; |
| 1381 |
} |
| 1382 |
ranges->Add(CharacterRange::Range(last, kMaxCodePoint), zone); |
| 1383 |
} |
| 1384 |
|
| 1385 |
} // namespace |
| 1386 |
|
| 1387 |
void CharacterRange::AddClassEscape(StandardCharacterSet standard_character_set, |
| 1388 |
ZoneList<CharacterRange>* ranges, |
| 1389 |
bool add_unicode_case_equivalents, |
| 1390 |
Zone* zone) { |
| 1391 |
if (add_unicode_case_equivalents && |
| 1392 |
(standard_character_set == StandardCharacterSet::kWord || |
| 1393 |
standard_character_set == StandardCharacterSet::kNotWord)) { |
| 1394 |
// See #sec-runtime-semantics-wordcharacters-abstract-operation |
| 1395 |
// In case of unicode and ignore_case, we need to create the closure over |
| 1396 |
// case equivalent characters before negating. |
| 1397 |
ZoneList<CharacterRange>* new_ranges = |
| 1398 |
zone->New<ZoneList<CharacterRange>>(2, zone); |
| 1399 |
AddClass(kWordRanges, kWordRangeCount, new_ranges, zone); |
| 1400 |
AddUnicodeCaseEquivalents(new_ranges, zone); |
| 1401 |
if (standard_character_set == StandardCharacterSet::kNotWord) { |
| 1402 |
ZoneList<CharacterRange>* negated = |
| 1403 |
zone->New<ZoneList<CharacterRange>>(2, zone); |
| 1404 |
CharacterRange::Negate(new_ranges, negated, zone); |
| 1405 |
new_ranges = negated; |
| 1406 |
} |
| 1407 |
ranges->AddAll(*new_ranges, zone); |
| 1408 |
return; |
| 1409 |
} |
| 1410 |
|
| 1411 |
switch (standard_character_set) { |
| 1412 |
case StandardCharacterSet::kWhitespace: |
| 1413 |
AddClass(kSpaceRanges, kSpaceRangeCount, ranges, zone); |
| 1414 |
break; |
| 1415 |
case StandardCharacterSet::kNotWhitespace: |
| 1416 |
AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges, zone); |
| 1417 |
break; |
| 1418 |
case StandardCharacterSet::kWord: |
| 1419 |
AddClass(kWordRanges, kWordRangeCount, ranges, zone); |
| 1420 |
break; |
| 1421 |
case StandardCharacterSet::kNotWord: |
| 1422 |
AddClassNegated(kWordRanges, kWordRangeCount, ranges, zone); |
| 1423 |
break; |
| 1424 |
case StandardCharacterSet::kDigit: |
| 1425 |
AddClass(kDigitRanges, kDigitRangeCount, ranges, zone); |
| 1426 |
break; |
| 1427 |
case StandardCharacterSet::kNotDigit: |
| 1428 |
AddClassNegated(kDigitRanges, kDigitRangeCount, ranges, zone); |
| 1429 |
break; |
| 1430 |
// This is the set of characters matched by the $ and ^ symbols |
| 1431 |
// in multiline mode. |
| 1432 |
case StandardCharacterSet::kLineTerminator: |
| 1433 |
AddClass(kLineTerminatorRanges, kLineTerminatorRangeCount, ranges, zone); |
| 1434 |
break; |
| 1435 |
case StandardCharacterSet::kNotLineTerminator: |
| 1436 |
AddClassNegated(kLineTerminatorRanges, kLineTerminatorRangeCount, ranges, |
| 1437 |
zone); |
| 1438 |
break; |
| 1439 |
// This is not a character range as defined by the spec but a |
| 1440 |
// convenient shorthand for a character class that matches any |
| 1441 |
// character. |
| 1442 |
case StandardCharacterSet::kEverything: |
| 1443 |
ranges->Add(CharacterRange::Everything(), zone); |
| 1444 |
break; |
| 1445 |
} |
| 1446 |
} |
| 1447 |
|
| 1448 |
// static |
| 1449 |
// Only for /i, not for /ui or /vi. |
| 1450 |
void CharacterRange::AddCaseEquivalents(Isolate* isolate, Zone* zone, |
| 1451 |
ZoneList<CharacterRange>* ranges, |
| 1452 |
bool is_one_byte) { |
| 1453 |
CharacterRange::Canonicalize(ranges); |
| 1454 |
int range_count = ranges->length(); |
| 1455 |
#ifdef V8_INTL_SUPPORT |
| 1456 |
icu::UnicodeSet others; |
| 1457 |
for (int i = 0; i < range_count; i++) { |
| 1458 |
CharacterRange range = ranges->at(i); |
| 1459 |
base::uc32 from = range.from(); |
| 1460 |
if (from > kMaxUtf16CodeUnit) continue; |
| 1461 |
base::uc32 to = std::min({range.to(), kMaxUtf16CodeUnitU}); |
| 1462 |
// Nothing to be done for surrogates. |
| 1463 |
if (from >= kLeadSurrogateStart && to <= kTrailSurrogateEnd) continue; |
| 1464 |
if (is_one_byte && !RangeContainsLatin1Equivalents(range)) { |
| 1465 |
if (from > String::kMaxOneByteCharCode) continue; |
| 1466 |
if (to > String::kMaxOneByteCharCode) to = String::kMaxOneByteCharCode; |
| 1467 |
} |
| 1468 |
others.add(from, to); |
| 1469 |
} |
| 1470 |
|
| 1471 |
// Compute the set of additional characters that should be added, |
| 1472 |
// using UnicodeSet::closeOver. ECMA 262 defines slightly different |
| 1473 |
// case-folding rules than Unicode, so some characters that are |
| 1474 |
// added by closeOver do not match anything other than themselves in |
| 1475 |
// JS. For example, 'ſ' (U+017F LATIN SMALL LETTER LONG S) is the |
| 1476 |
// same case-insensitive character as 's' or 'S' according to |
| 1477 |
// Unicode, but does not match any other character in JS. To handle |
| 1478 |
// this case, we add such characters to the IgnoreSet and filter |
| 1479 |
// them out. We filter twice: once before calling closeOver (to |
| 1480 |
// prevent 'ſ' from adding 's'), and once after calling closeOver |
| 1481 |
// (to prevent 's' from adding 'ſ'). See regexp/special-case.h for |
| 1482 |
// more information. |
| 1483 |
icu::UnicodeSet already_added(others); |
| 1484 |
others.removeAll(RegExpCaseFolding::IgnoreSet()); |
| 1485 |
others.closeOver(USET_CASE_INSENSITIVE); |
| 1486 |
others.removeAll(RegExpCaseFolding::IgnoreSet()); |
| 1487 |
others.removeAll(already_added); |
| 1488 |
|
| 1489 |
// Add others to the ranges |
| 1490 |
for (int32_t i = 0; i < others.getRangeCount(); i++) { |
| 1491 |
UChar32 from = others.getRangeStart(i); |
| 1492 |
UChar32 to = others.getRangeEnd(i); |
| 1493 |
if (from == to) { |
| 1494 |
ranges->Add(CharacterRange::Singleton(from), zone); |
| 1495 |
} else { |
| 1496 |
ranges->Add(CharacterRange::Range(from, to), zone); |
| 1497 |
} |
| 1498 |
} |
| 1499 |
#else |
| 1500 |
for (int i = 0; i < range_count; i++) { |
| 1501 |
CharacterRange range = ranges->at(i); |
| 1502 |
base::uc32 bottom = range.from(); |
| 1503 |
if (bottom > kMaxUtf16CodeUnit) continue; |
| 1504 |
base::uc32 top = std::min({range.to(), kMaxUtf16CodeUnitU}); |
| 1505 |
// Nothing to be done for surrogates. |
| 1506 |
if (bottom >= kLeadSurrogateStart && top <= kTrailSurrogateEnd) continue; |
| 1507 |
if (is_one_byte && !RangeContainsLatin1Equivalents(range)) { |
| 1508 |
if (bottom > String::kMaxOneByteCharCode) continue; |
| 1509 |
if (top > String::kMaxOneByteCharCode) top = String::kMaxOneByteCharCode; |
| 1510 |
} |
| 1511 |
unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| 1512 |
if (top == bottom) { |
| 1513 |
// If this is a singleton we just expand the one character. |
| 1514 |
int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars); |
| 1515 |
for (int j = 0; j < length; j++) { |
| 1516 |
base::uc32 chr = chars[j]; |
| 1517 |
if (chr != bottom) { |
| 1518 |
ranges->Add(CharacterRange::Singleton(chars[j]), zone); |
| 1519 |
} |
| 1520 |
} |
| 1521 |
} else { |
| 1522 |
// If this is a range we expand the characters block by block, expanding |
| 1523 |
// contiguous subranges (blocks) one at a time. The approach is as |
| 1524 |
// follows. For a given start character we look up the remainder of the |
| 1525 |
// block that contains it (represented by the end point), for instance we |
| 1526 |
// find 'z' if the character is 'c'. A block is characterized by the |
| 1527 |
// property that all characters uncanonicalize in the same way, except |
| 1528 |
// that each entry in the result is incremented by the distance from the |
| 1529 |
// first element. So a-z is a block because 'a' uncanonicalizes to ['a', |
| 1530 |
// 'A'] and the k'th letter uncanonicalizes to ['a' + k, 'A' + k]. Once |
| 1531 |
// we've found the end point we look up its uncanonicalization and |
| 1532 |
// produce a range for each element. For instance for [c-f] we look up |
| 1533 |
// ['z', 'Z'] and produce [c-f] and [C-F]. We then only add a range if |
| 1534 |
// it is not already contained in the input, so [c-f] will be skipped but |
| 1535 |
// [C-F] will be added. If this range is not completely contained in a |
| 1536 |
// block we do this for all the blocks covered by the range (handling |
| 1537 |
// characters that is not in a block as a "singleton block"). |
| 1538 |
unibrow::uchar equivalents[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| 1539 |
base::uc32 pos = bottom; |
| 1540 |
while (pos <= top) { |
| 1541 |
int length = |
| 1542 |
isolate->jsregexp_canonrange()->get(pos, '\0', equivalents); |
| 1543 |
base::uc32 block_end; |
| 1544 |
if (length == 0) { |
| 1545 |
block_end = pos; |
| 1546 |
} else { |
| 1547 |
DCHECK_EQ(1, length); |
| 1548 |
block_end = equivalents[0]; |
| 1549 |
} |
| 1550 |
int end = (block_end > top) ? top : block_end; |
| 1551 |
length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', |
| 1552 |
equivalents); |
| 1553 |
for (int j = 0; j < length; j++) { |
| 1554 |
base::uc32 c = equivalents[j]; |
| 1555 |
base::uc32 range_from = c - (block_end - pos); |
| 1556 |
base::uc32 range_to = c - (block_end - end); |
| 1557 |
if (!(bottom <= range_from && range_to <= top)) { |
| 1558 |
ranges->Add(CharacterRange::Range(range_from, range_to), zone); |
| 1559 |
} |
| 1560 |
} |
| 1561 |
pos = end + 1; |
| 1562 |
} |
| 1563 |
} |
| 1564 |
} |
| 1565 |
#endif // V8_INTL_SUPPORT |
| 1566 |
} |
| 1567 |
|
| 1568 |
bool CharacterRange::IsCanonical(const ZoneList<CharacterRange>* ranges) { |
| 1569 |
DCHECK_NOT_NULL(ranges); |
| 1570 |
int n = ranges->length(); |
| 1571 |
if (n <= 1) return true; |
| 1572 |
base::uc32 max = ranges->at(0).to(); |
| 1573 |
for (int i = 1; i < n; i++) { |
| 1574 |
CharacterRange next_range = ranges->at(i); |
| 1575 |
if (next_range.from() <= max + 1) return false; |
| 1576 |
max = next_range.to(); |
| 1577 |
} |
| 1578 |
return true; |
| 1579 |
} |
| 1580 |
|
| 1581 |
ZoneList<CharacterRange>* CharacterSet::ranges(Zone* zone) { |
| 1582 |
if (ranges_ == nullptr) { |
| 1583 |
ranges_ = zone->New<ZoneList<CharacterRange>>(2, zone); |
| 1584 |
CharacterRange::AddClassEscape(standard_set_type_.value(), ranges_, false, |
| 1585 |
zone); |
| 1586 |
} |
| 1587 |
return ranges_; |
| 1588 |
} |
| 1589 |
|
| 1590 |
namespace { |
| 1591 |
|
| 1592 |
// Move a number of elements in a zonelist to another position |
| 1593 |
// in the same list. Handles overlapping source and target areas. |
| 1594 |
void MoveRanges(ZoneList<CharacterRange>* list, int from, int to, int count) { |
| 1595 |
// Ranges are potentially overlapping. |
| 1596 |
if (from < to) { |
| 1597 |
for (int i = count - 1; i >= 0; i--) { |
| 1598 |
list->at(to + i) = list->at(from + i); |
| 1599 |
} |
| 1600 |
} else { |
| 1601 |
for (int i = 0; i < count; i++) { |
| 1602 |
list->at(to + i) = list->at(from + i); |
| 1603 |
} |
| 1604 |
} |
| 1605 |
} |
| 1606 |
|
| 1607 |
int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list, int count, |
| 1608 |
CharacterRange insert) { |
| 1609 |
// Inserts a range into list[0..count[, which must be sorted |
| 1610 |
// by from value and non-overlapping and non-adjacent, using at most |
| 1611 |
// list[0..count] for the result. Returns the number of resulting |
| 1612 |
// canonicalized ranges. Inserting a range may collapse existing ranges into |
| 1613 |
// fewer ranges, so the return value can be anything in the range 1..count+1. |
| 1614 |
base::uc32 from = insert.from(); |
| 1615 |
base::uc32 to = insert.to(); |
| 1616 |
int start_pos = 0; |
| 1617 |
int end_pos = count; |
| 1618 |
for (int i = count - 1; i >= 0; i--) { |
| 1619 |
CharacterRange current = list->at(i); |
| 1620 |
if (current.from() > to + 1) { |
| 1621 |
end_pos = i; |
| 1622 |
} else if (current.to() + 1 < from) { |
| 1623 |
start_pos = i + 1; |
| 1624 |
break; |
| 1625 |
} |
| 1626 |
} |
| 1627 |
|
| 1628 |
// Inserted range overlaps, or is adjacent to, ranges at positions |
| 1629 |
// [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are |
| 1630 |
// not affected by the insertion. |
| 1631 |
// If start_pos == end_pos, the range must be inserted before start_pos. |
| 1632 |
// if start_pos < end_pos, the entire range from start_pos to end_pos |
| 1633 |
// must be merged with the insert range. |
| 1634 |
|
| 1635 |
if (start_pos == end_pos) { |
| 1636 |
// Insert between existing ranges at position start_pos. |
| 1637 |
if (start_pos < count) { |
| 1638 |
MoveRanges(list, start_pos, start_pos + 1, count - start_pos); |
| 1639 |
} |
| 1640 |
list->at(start_pos) = insert; |
| 1641 |
return count + 1; |
| 1642 |
} |
| 1643 |
if (start_pos + 1 == end_pos) { |
| 1644 |
// Replace single existing range at position start_pos. |
| 1645 |
CharacterRange to_replace = list->at(start_pos); |
| 1646 |
int new_from = std::min(to_replace.from(), from); |
| 1647 |
int new_to = std::max(to_replace.to(), to); |
| 1648 |
list->at(start_pos) = CharacterRange::Range(new_from, new_to); |
| 1649 |
return count; |
| 1650 |
} |
| 1651 |
// Replace a number of existing ranges from start_pos to end_pos - 1. |
| 1652 |
// Move the remaining ranges down. |
| 1653 |
|
| 1654 |
int new_from = std::min(list->at(start_pos).from(), from); |
| 1655 |
int new_to = std::max(list->at(end_pos - 1).to(), to); |
| 1656 |
if (end_pos < count) { |
| 1657 |
MoveRanges(list, end_pos, start_pos + 1, count - end_pos); |
| 1658 |
} |
| 1659 |
list->at(start_pos) = CharacterRange::Range(new_from, new_to); |
| 1660 |
return count - (end_pos - start_pos) + 1; |
| 1661 |
} |
| 1662 |
|
| 1663 |
} // namespace |
| 1664 |
|
| 1665 |
void CharacterSet::Canonicalize() { |
| 1666 |
// Special/default classes are always considered canonical. The result |
| 1667 |
// of calling ranges() will be sorted. |
| 1668 |
if (ranges_ == nullptr) return; |
| 1669 |
CharacterRange::Canonicalize(ranges_); |
| 1670 |
} |
| 1671 |
|
| 1672 |
// static |
| 1673 |
void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) { |
| 1674 |
if (character_ranges->length() <= 1) return; |
| 1675 |
// Check whether ranges are already canonical (increasing, non-overlapping, |
| 1676 |
// non-adjacent). |
| 1677 |
int n = character_ranges->length(); |
| 1678 |
base::uc32 max = character_ranges->at(0).to(); |
| 1679 |
int i = 1; |
| 1680 |
while (i < n) { |
| 1681 |
CharacterRange current = character_ranges->at(i); |
| 1682 |
if (current.from() <= max + 1) { |
| 1683 |
break; |
| 1684 |
} |
| 1685 |
max = current.to(); |
| 1686 |
i++; |
| 1687 |
} |
| 1688 |
// Canonical until the i'th range. If that's all of them, we are done. |
| 1689 |
if (i == n) return; |
| 1690 |
|
| 1691 |
// The ranges at index i and forward are not canonicalized. Make them so by |
| 1692 |
// doing the equivalent of insertion sort (inserting each into the previous |
| 1693 |
// list, in order). |
| 1694 |
// Notice that inserting a range can reduce the number of ranges in the |
| 1695 |
// result due to combining of adjacent and overlapping ranges. |
| 1696 |
int read = i; // Range to insert. |
| 1697 |
int num_canonical = i; // Length of canonicalized part of list. |
| 1698 |
do { |
| 1699 |
num_canonical = InsertRangeInCanonicalList(character_ranges, num_canonical, |
| 1700 |
character_ranges->at(read)); |
| 1701 |
read++; |
| 1702 |
} while (read < n); |
| 1703 |
character_ranges->Rewind(num_canonical); |
| 1704 |
|
| 1705 |
DCHECK(CharacterRange::IsCanonical(character_ranges)); |
| 1706 |
} |
| 1707 |
|
| 1708 |
// static |
| 1709 |
void CharacterRange::Negate(const ZoneList<CharacterRange>* ranges, |
| 1710 |
ZoneList<CharacterRange>* negated_ranges, |
| 1711 |
Zone* zone) { |
| 1712 |
DCHECK(CharacterRange::IsCanonical(ranges)); |
| 1713 |
DCHECK_EQ(0, negated_ranges->length()); |
| 1714 |
int range_count = ranges->length(); |
| 1715 |
base::uc32 from = 0; |
| 1716 |
int i = 0; |
| 1717 |
if (range_count > 0 && ranges->at(0).from() == 0) { |
| 1718 |
from = ranges->at(0).to() + 1; |
| 1719 |
i = 1; |
| 1720 |
} |
| 1721 |
while (i < range_count) { |
| 1722 |
CharacterRange range = ranges->at(i); |
| 1723 |
negated_ranges->Add(CharacterRange::Range(from, range.from() - 1), zone); |
| 1724 |
from = range.to() + 1; |
| 1725 |
i++; |
| 1726 |
} |
| 1727 |
if (from < kMaxCodePoint) { |
| 1728 |
negated_ranges->Add(CharacterRange::Range(from, kMaxCodePoint), zone); |
| 1729 |
} |
| 1730 |
} |
| 1731 |
|
| 1732 |
// static |
| 1733 |
void CharacterRange::Intersect(const ZoneList<CharacterRange>* lhs, |
| 1734 |
const ZoneList<CharacterRange>* rhs, |
| 1735 |
ZoneList<CharacterRange>* intersection, |
| 1736 |
Zone* zone) { |
| 1737 |
DCHECK(CharacterRange::IsCanonical(lhs)); |
| 1738 |
DCHECK(CharacterRange::IsCanonical(rhs)); |
| 1739 |
DCHECK_EQ(0, intersection->length()); |
| 1740 |
int lhs_index = 0; |
| 1741 |
int rhs_index = 0; |
| 1742 |
while (lhs_index < lhs->length() && rhs_index < rhs->length()) { |
| 1743 |
// Skip non-overlapping ranges. |
| 1744 |
if (lhs->at(lhs_index).to() < rhs->at(rhs_index).from()) { |
| 1745 |
lhs_index++; |
| 1746 |
continue; |
| 1747 |
} |
| 1748 |
if (rhs->at(rhs_index).to() < lhs->at(lhs_index).from()) { |
| 1749 |
rhs_index++; |
| 1750 |
continue; |
| 1751 |
} |
| 1752 |
|
| 1753 |
base::uc32 from = |
| 1754 |
std::max(lhs->at(lhs_index).from(), rhs->at(rhs_index).from()); |
| 1755 |
base::uc32 to = std::min(lhs->at(lhs_index).to(), rhs->at(rhs_index).to()); |
| 1756 |
intersection->Add(CharacterRange::Range(from, to), zone); |
| 1757 |
if (to == lhs->at(lhs_index).to()) { |
| 1758 |
lhs_index++; |
| 1759 |
} else { |
| 1760 |
rhs_index++; |
| 1761 |
} |
| 1762 |
} |
| 1763 |
|
| 1764 |
DCHECK(IsCanonical(intersection)); |
| 1765 |
} |
| 1766 |
|
| 1767 |
namespace { |
| 1768 |
|
| 1769 |
// Advance |index| and set |from| and |to| to the new range, if not out of |
| 1770 |
// bounds of |range|, otherwise |from| is set to a code point beyond the legal |
| 1771 |
// unicode character range. |
| 1772 |
void SafeAdvanceRange(const ZoneList<CharacterRange>* range, int* index, |
| 1773 |
base::uc32* from, base::uc32* to) { |
| 1774 |
++(*index); |
| 1775 |
if (*index < range->length()) { |
| 1776 |
*from = range->at(*index).from(); |
| 1777 |
*to = range->at(*index).to(); |
| 1778 |
} else { |
| 1779 |
*from = kMaxCodePoint + 1; |
| 1780 |
} |
| 1781 |
} |
| 1782 |
|
| 1783 |
} // namespace |
| 1784 |
|
| 1785 |
// static |
| 1786 |
void CharacterRange::Subtract(const ZoneList<CharacterRange>* src, |
| 1787 |
const ZoneList<CharacterRange>* to_remove, |
| 1788 |
ZoneList<CharacterRange>* result, Zone* zone) { |
| 1789 |
DCHECK(CharacterRange::IsCanonical(src)); |
| 1790 |
DCHECK(CharacterRange::IsCanonical(to_remove)); |
| 1791 |
DCHECK_EQ(0, result->length()); |
| 1792 |
|
| 1793 |
if (src->is_empty()) return; |
| 1794 |
|
| 1795 |
int src_index = 0; |
| 1796 |
int to_remove_index = 0; |
| 1797 |
base::uc32 from = src->at(src_index).from(); |
| 1798 |
base::uc32 to = src->at(src_index).to(); |
| 1799 |
while (src_index < src->length() && to_remove_index < to_remove->length()) { |
| 1800 |
CharacterRange remove_range = to_remove->at(to_remove_index); |
| 1801 |
if (remove_range.to() < from) { |
| 1802 |
// (a) Non-overlapping case, ignore current to_remove range. |
| 1803 |
// |-------| |
| 1804 |
// |-------| |
| 1805 |
to_remove_index++; |
| 1806 |
} else if (to < remove_range.from()) { |
| 1807 |
// (b) Non-overlapping case, add full current range to result. |
| 1808 |
// |-------| |
| 1809 |
// |-------| |
| 1810 |
result->Add(CharacterRange::Range(from, to), zone); |
| 1811 |
SafeAdvanceRange(src, &src_index, &from, &to); |
| 1812 |
} else if (from >= remove_range.from() && to <= remove_range.to()) { |
| 1813 |
// (c) Current to_remove range fully covers current range. |
| 1814 |
// |---| |
| 1815 |
// |-------| |
| 1816 |
SafeAdvanceRange(src, &src_index, &from, &to); |
| 1817 |
} else if (from < remove_range.from() && to > remove_range.to()) { |
| 1818 |
// (d) Split current range. |
| 1819 |
// |-------| |
| 1820 |
// |---| |
| 1821 |
result->Add(CharacterRange::Range(from, remove_range.from() - 1), zone); |
| 1822 |
from = remove_range.to() + 1; |
| 1823 |
to_remove_index++; |
| 1824 |
} else if (from < remove_range.from()) { |
| 1825 |
// (e) End current range. |
| 1826 |
// |-------| |
| 1827 |
// |-------| |
| 1828 |
to = remove_range.from() - 1; |
| 1829 |
result->Add(CharacterRange::Range(from, to), zone); |
| 1830 |
SafeAdvanceRange(src, &src_index, &from, &to); |
| 1831 |
} else if (to > remove_range.to()) { |
| 1832 |
// (f) Modify start of current range. |
| 1833 |
// |-------| |
| 1834 |
// |-------| |
| 1835 |
from = remove_range.to() + 1; |
| 1836 |
to_remove_index++; |
| 1837 |
} else { |
| 1838 |
UNREACHABLE(); |
| 1839 |
} |
| 1840 |
} |
| 1841 |
// The last range needs special treatment after |to_remove| is exhausted, as |
| 1842 |
// |from| might have been modified by the last |to_remove| range and |to| was |
| 1843 |
// not yet known (i.e. cases d and f). |
| 1844 |
if (from <= to) { |
| 1845 |
result->Add(CharacterRange::Range(from, to), zone); |
| 1846 |
} |
| 1847 |
src_index++; |
| 1848 |
|
| 1849 |
// Add remaining ranges after |to_remove| is exhausted. |
| 1850 |
for (; src_index < src->length(); src_index++) { |
| 1851 |
result->Add(src->at(src_index), zone); |
| 1852 |
} |
| 1853 |
|
| 1854 |
DCHECK(IsCanonical(result)); |
| 1855 |
} |
| 1856 |
|
| 1857 |
// static |
| 1858 |
void CharacterRange::ClampToOneByte(ZoneList<CharacterRange>* ranges) { |
| 1859 |
DCHECK(IsCanonical(ranges)); |
| 1860 |
|
| 1861 |
// Drop all ranges that don't contain one-byte code units, and clamp the last |
| 1862 |
// range s.t. it likewise only contains one-byte code units. Note this relies |
| 1863 |
// on `ranges` being canonicalized, i.e. sorted and non-overlapping. |
| 1864 |
|
| 1865 |
static constexpr base::uc32 max_char = String::kMaxOneByteCharCodeU; |
| 1866 |
int n = ranges->length(); |
| 1867 |
for (; n > 0; n--) { |
| 1868 |
CharacterRange& r = ranges->at(n - 1); |
| 1869 |
if (r.from() <= max_char) { |
| 1870 |
r.to_ = std::min(r.to_, max_char); |
| 1871 |
break; |
| 1872 |
} |
| 1873 |
} |
| 1874 |
|
| 1875 |
ranges->Rewind(n); |
| 1876 |
} |
| 1877 |
|
| 1878 |
// static |
| 1879 |
bool CharacterRange::Equals(const ZoneList<CharacterRange>* lhs, |
| 1880 |
const ZoneList<CharacterRange>* rhs) { |
| 1881 |
DCHECK(IsCanonical(lhs)); |
| 1882 |
DCHECK(IsCanonical(rhs)); |
| 1883 |
if (lhs->length() != rhs->length()) return false; |
| 1884 |
|
| 1885 |
for (int i = 0; i < lhs->length(); i++) { |
| 1886 |
if (lhs->at(i) != rhs->at(i)) return false; |
| 1887 |
} |
| 1888 |
|
| 1889 |
return true; |
| 1890 |
} |
| 1891 |
|
| 1892 |
namespace { |
| 1893 |
|
| 1894 |
// Scoped object to keep track of how much we unroll quantifier loops in the |
| 1895 |
// regexp graph generator. |
| 1896 |
class RegExpExpansionLimiter { |
| 1897 |
public: |
| 1898 |
static const int kMaxExpansionFactor = 6; |
| 1899 |
RegExpExpansionLimiter(RegExpCompiler* compiler, int factor) |
| 1900 |
: compiler_(compiler), |
| 1901 |
saved_expansion_factor_(compiler->current_expansion_factor()), |
| 1902 |
ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) { |
| 1903 |
DCHECK_LT(0, factor); |
| 1904 |
if (ok_to_expand_) { |
| 1905 |
if (factor > kMaxExpansionFactor) { |
| 1906 |
// Avoid integer overflow of the current expansion factor. |
| 1907 |
ok_to_expand_ = false; |
| 1908 |
compiler->set_current_expansion_factor(kMaxExpansionFactor + 1); |
| 1909 |
} else { |
| 1910 |
int new_factor = saved_expansion_factor_ * factor; |
| 1911 |
ok_to_expand_ = (new_factor <= kMaxExpansionFactor); |
| 1912 |
compiler->set_current_expansion_factor(new_factor); |
| 1913 |
} |
| 1914 |
} |
| 1915 |
} |
| 1916 |
|
| 1917 |
~RegExpExpansionLimiter() { |
| 1918 |
compiler_->set_current_expansion_factor(saved_expansion_factor_); |
| 1919 |
} |
| 1920 |
|
| 1921 |
bool ok_to_expand() { return ok_to_expand_; } |
| 1922 |
|
| 1923 |
private: |
| 1924 |
RegExpCompiler* compiler_; |
| 1925 |
int saved_expansion_factor_; |
| 1926 |
bool ok_to_expand_; |
| 1927 |
|
| 1928 |
DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter); |
| 1929 |
}; |
| 1930 |
|
| 1931 |
} // namespace |
| 1932 |
|
| 1933 |
RegExpNode* RegExpQuantifier::ToNode(int min, int max, bool is_greedy, |
| 1934 |
RegExpTree* body, RegExpCompiler* compiler, |
| 1935 |
RegExpNode* on_success, |
| 1936 |
bool not_at_start) { |
| 1937 |
// x{f, t} becomes this: |
| 1938 |
// |
| 1939 |
// (r++)<-. |
| 1940 |
// | ` |
| 1941 |
// | (x) |
| 1942 |
// v ^ |
| 1943 |
// (r=0)-->(?)---/ [if r < t] |
| 1944 |
// | |
| 1945 |
// [if r >= f] \----> ... |
| 1946 |
// |
| 1947 |
|
| 1948 |
// 15.10.2.5 RepeatMatcher algorithm. |
| 1949 |
// The parser has already eliminated the case where max is 0. In the case |
| 1950 |
// where max_match is zero the parser has removed the quantifier if min was |
| 1951 |
// > 0 and removed the atom if min was 0. See AddQuantifierToAtom. |
| 1952 |
|
| 1953 |
// If we know that we cannot match zero length then things are a little |
| 1954 |
// simpler since we don't need to make the special zero length match check |
| 1955 |
// from step 2.1. If the min and max are small we can unroll a little in |
| 1956 |
// this case. |
| 1957 |
static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,} |
| 1958 |
static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3} |
| 1959 |
if (max == 0) return on_success; // This can happen due to recursion. |
| 1960 |
bool body_can_be_empty = (body->min_match() == 0); |
| 1961 |
int body_start_reg = RegExpCompiler::kNoRegister; |
| 1962 |
Interval capture_registers = body->CaptureRegisters(); |
| 1963 |
bool needs_capture_clearing = !capture_registers.is_empty(); |
| 1964 |
Zone* zone = compiler->zone(); |
| 1965 |
|
| 1966 |
if (body_can_be_empty) { |
| 1967 |
body_start_reg = compiler->AllocateRegister(); |
| 1968 |
} else if (compiler->optimize() && !needs_capture_clearing) { |
| 1969 |
// Only unroll if there are no captures and the body can't be |
| 1970 |
// empty. |
| 1971 |
{ |
| 1972 |
RegExpExpansionLimiter limiter(compiler, min + ((max != min) ? 1 : 0)); |
| 1973 |
if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) { |
| 1974 |
int new_max = (max == kInfinity) ? max : max - min; |
| 1975 |
// Recurse once to get the loop or optional matches after the fixed |
| 1976 |
// ones. |
| 1977 |
RegExpNode* answer = |
| 1978 |
ToNode(0, new_max, is_greedy, body, compiler, on_success, true); |
| 1979 |
// Unroll the forced matches from 0 to min. This can cause chains of |
| 1980 |
// TextNodes (which the parser does not generate). These should be |
| 1981 |
// combined if it turns out they hinder good code generation. |
| 1982 |
for (int i = 0; i < min; i++) { |
| 1983 |
answer = body->ToNode(compiler, answer); |
| 1984 |
} |
| 1985 |
return answer; |
| 1986 |
} |
| 1987 |
} |
| 1988 |
if (max <= kMaxUnrolledMaxMatches && min == 0) { |
| 1989 |
DCHECK_LT(0, max); // Due to the 'if' above. |
| 1990 |
RegExpExpansionLimiter limiter(compiler, max); |
| 1991 |
if (limiter.ok_to_expand()) { |
| 1992 |
// Unroll the optional matches up to max. |
| 1993 |
RegExpNode* answer = on_success; |
| 1994 |
for (int i = 0; i < max; i++) { |
| 1995 |
ChoiceNode* alternation = zone->New<ChoiceNode>(2, zone); |
| 1996 |
if (is_greedy) { |
| 1997 |
alternation->AddAlternative( |
| 1998 |
GuardedAlternative(body->ToNode(compiler, answer))); |
| 1999 |
alternation->AddAlternative(GuardedAlternative(on_success)); |
| 2000 |
} else { |
| 2001 |
alternation->AddAlternative(GuardedAlternative(on_success)); |
| 2002 |
alternation->AddAlternative( |
| 2003 |
GuardedAlternative(body->ToNode(compiler, answer))); |
| 2004 |
} |
| 2005 |
answer = alternation; |
| 2006 |
if (not_at_start && !compiler->read_backward()) { |
| 2007 |
alternation->set_not_at_start(); |
| 2008 |
} |
| 2009 |
} |
| 2010 |
return answer; |
| 2011 |
} |
| 2012 |
} |
| 2013 |
} |
| 2014 |
bool has_min = min > 0; |
| 2015 |
bool has_max = max < RegExpTree::kInfinity; |
| 2016 |
bool needs_counter = has_min || has_max; |
| 2017 |
int reg_ctr = needs_counter ? compiler->AllocateRegister() |
| 2018 |
: RegExpCompiler::kNoRegister; |
| 2019 |
LoopChoiceNode* center = zone->New<LoopChoiceNode>( |
| 2020 |
body->min_match() == 0, compiler->read_backward(), min, zone); |
| 2021 |
if (not_at_start && !compiler->read_backward()) center->set_not_at_start(); |
| 2022 |
RegExpNode* loop_return = |
| 2023 |
needs_counter ? static_cast<RegExpNode*>( |
| 2024 |
ActionNode::IncrementRegister(reg_ctr, center)) |
| 2025 |
: static_cast<RegExpNode*>(center); |
| 2026 |
if (body_can_be_empty) { |
| 2027 |
// If the body can be empty we need to check if it was and then |
| 2028 |
// backtrack. |
| 2029 |
loop_return = |
| 2030 |
ActionNode::EmptyMatchCheck(body_start_reg, reg_ctr, min, loop_return); |
| 2031 |
} |
| 2032 |
RegExpNode* body_node = body->ToNode(compiler, loop_return); |
| 2033 |
if (body_can_be_empty) { |
| 2034 |
// If the body can be empty we need to store the start position |
| 2035 |
// so we can bail out if it was empty. |
| 2036 |
body_node = ActionNode::StorePosition(body_start_reg, false, body_node); |
| 2037 |
} |
| 2038 |
if (needs_capture_clearing) { |
| 2039 |
// Before entering the body of this loop we need to clear captures. |
| 2040 |
body_node = ActionNode::ClearCaptures(capture_registers, body_node); |
| 2041 |
} |
| 2042 |
GuardedAlternative body_alt(body_node); |
| 2043 |
if (has_max) { |
| 2044 |
Guard* body_guard = zone->New<Guard>(reg_ctr, Guard::LT, max); |
| 2045 |
body_alt.AddGuard(body_guard, zone); |
| 2046 |
} |
| 2047 |
GuardedAlternative rest_alt(on_success); |
| 2048 |
if (has_min) { |
| 2049 |
Guard* rest_guard = compiler->zone()->New<Guard>(reg_ctr, Guard::GEQ, min); |
| 2050 |
rest_alt.AddGuard(rest_guard, zone); |
| 2051 |
} |
| 2052 |
if (is_greedy) { |
| 2053 |
center->AddLoopAlternative(body_alt); |
| 2054 |
center->AddContinueAlternative(rest_alt); |
| 2055 |
} else { |
| 2056 |
center->AddContinueAlternative(rest_alt); |
| 2057 |
center->AddLoopAlternative(body_alt); |
| 2058 |
} |
| 2059 |
if (needs_counter) { |
| 2060 |
return ActionNode::SetRegisterForLoop(reg_ctr, 0, center); |
| 2061 |
} else { |
| 2062 |
return center; |
| 2063 |
} |
| 2064 |
} |
| 2065 |
|
| 2066 |
} // namespace internal |
| 2067 |
} // namespace v8 |