regexp-compiler-tonode.cc 65.7 KB
Newer Older
1 2 3 4 5 6
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/regexp/regexp-compiler.h"

7
#include "src/execution/isolate.h"
8
#include "src/regexp/regexp.h"
9 10 11 12
#include "src/strings/unicode-inl.h"
#include "src/zone/zone-list-inl.h"

#ifdef V8_INTL_SUPPORT
13
#include "src/base/strings.h"
14
#include "src/regexp/special-case.h"
15 16 17 18 19 20 21 22 23 24
#include "unicode/locid.h"
#include "unicode/uniset.h"
#include "unicode/utypes.h"
#endif  // V8_INTL_SUPPORT

namespace v8 {
namespace internal {

using namespace regexp_compiler_constants;  // NOLINT(build/namespaces)

25 26 27 28 29
constexpr base::uc32 kMaxCodePoint = 0x10ffff;
constexpr int kMaxUtf16CodeUnit = 0xffff;
constexpr uint32_t kMaxUtf16CodeUnitU = 0xffff;
constexpr int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;

30 31 32 33 34 35
// -------------------------------------------------------------------
// Tree to graph conversion

RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
                               RegExpNode* on_success) {
  ZoneList<TextElement>* elms =
36
      compiler->zone()->New<ZoneList<TextElement>>(1, compiler->zone());
37
  elms->Add(TextElement::Atom(this), compiler->zone());
38 39
  return compiler->zone()->New<TextNode>(elms, compiler->read_backward(),
                                         on_success);
40 41 42 43
}

RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
                               RegExpNode* on_success) {
44 45
  return compiler->zone()->New<TextNode>(elements(), compiler->read_backward(),
                                         on_success);
46 47
}

Jakob Gruber's avatar
Jakob Gruber committed
48 49 50 51
namespace {

bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
                          const int* special_class, int length) {
52
  length--;  // Remove final marker.
53

54 55 56 57
  DCHECK_EQ(kRangeEndMarker, special_class[length]);
  DCHECK_NE(0, ranges->length());
  DCHECK_NE(0, length);
  DCHECK_NE(0, special_class[0]);
58 59 60

  if (ranges->length() != (length >> 1) + 1) return false;

61
  CharacterRange range = ranges->at(0);
62 63
  if (range.from() != 0) return false;

64
  for (int i = 0; i < length; i += 2) {
65
    if (static_cast<base::uc32>(special_class[i]) != (range.to() + 1)) {
66 67 68
      return false;
    }
    range = ranges->at((i >> 1) + 1);
69
    if (static_cast<base::uc32>(special_class[i + 1]) != range.from()) {
70 71 72
      return false;
    }
  }
73 74

  return range.to() == kMaxCodePoint;
75 76
}

Jakob Gruber's avatar
Jakob Gruber committed
77 78
bool CompareRanges(ZoneList<CharacterRange>* ranges, const int* special_class,
                   int length) {
79
  length--;  // Remove final marker.
80

81
  DCHECK_EQ(kRangeEndMarker, special_class[length]);
82 83
  if (ranges->length() * 2 != length) return false;

84 85
  for (int i = 0; i < length; i += 2) {
    CharacterRange range = ranges->at(i >> 1);
86 87
    if (range.from() != static_cast<base::uc32>(special_class[i]) ||
        range.to() != static_cast<base::uc32>(special_class[i + 1] - 1)) {
88 89 90 91 92 93
      return false;
    }
  }
  return true;
}

Jakob Gruber's avatar
Jakob Gruber committed
94 95
}  // namespace

96 97 98 99 100 101 102 103 104 105
bool RegExpCharacterClass::is_standard(Zone* zone) {
  // TODO(lrn): Remove need for this function, by not throwing away information
  // along the way.
  if (is_negated()) {
    return false;
  }
  if (set_.is_standard()) {
    return true;
  }
  if (CompareRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
106
    set_.set_standard_set_type(StandardCharacterSet::kWhitespace);
107 108 109
    return true;
  }
  if (CompareInverseRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
110
    set_.set_standard_set_type(StandardCharacterSet::kNotWhitespace);
111 112 113 114
    return true;
  }
  if (CompareInverseRanges(set_.ranges(zone), kLineTerminatorRanges,
                           kLineTerminatorRangeCount)) {
115
    set_.set_standard_set_type(StandardCharacterSet::kNotLineTerminator);
116 117 118 119
    return true;
  }
  if (CompareRanges(set_.ranges(zone), kLineTerminatorRanges,
                    kLineTerminatorRangeCount)) {
120
    set_.set_standard_set_type(StandardCharacterSet::kLineTerminator);
121 122 123
    return true;
  }
  if (CompareRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
124
    set_.set_standard_set_type(StandardCharacterSet::kWord);
125 126 127
    return true;
  }
  if (CompareInverseRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
128
    set_.set_standard_set_type(StandardCharacterSet::kNotWord);
129 130 131 132 133
    return true;
  }
  return false;
}

134
UnicodeRangeSplitter::UnicodeRangeSplitter(ZoneList<CharacterRange>* base) {
135 136 137 138 139 140 141
  // The unicode range splitter categorizes given character ranges into:
  // - Code points from the BMP representable by one code unit.
  // - Code points outside the BMP that need to be split into surrogate pairs.
  // - Lone lead surrogates.
  // - Lone trail surrogates.
  // Lone surrogates are valid code points, even though no actual characters.
  // They require special matching to make sure we do not split surrogate pairs.
142 143 144 145 146

  for (int i = 0; i < base->length(); i++) AddRange(base->at(i));
}

void UnicodeRangeSplitter::AddRange(CharacterRange range) {
147 148 149 150
  static constexpr base::uc32 kBmp1Start = 0;
  static constexpr base::uc32 kBmp1End = kLeadSurrogateStart - 1;
  static constexpr base::uc32 kBmp2Start = kTrailSurrogateEnd + 1;
  static constexpr base::uc32 kBmp2End = kNonBmpStart - 1;
151 152 153 154 155 156 157 158 159 160 161 162 163

  // Ends are all inclusive.
  STATIC_ASSERT(kBmp1Start == 0);
  STATIC_ASSERT(kBmp1Start < kBmp1End);
  STATIC_ASSERT(kBmp1End + 1 == kLeadSurrogateStart);
  STATIC_ASSERT(kLeadSurrogateStart < kLeadSurrogateEnd);
  STATIC_ASSERT(kLeadSurrogateEnd + 1 == kTrailSurrogateStart);
  STATIC_ASSERT(kTrailSurrogateStart < kTrailSurrogateEnd);
  STATIC_ASSERT(kTrailSurrogateEnd + 1 == kBmp2Start);
  STATIC_ASSERT(kBmp2Start < kBmp2End);
  STATIC_ASSERT(kBmp2End + 1 == kNonBmpStart);
  STATIC_ASSERT(kNonBmpStart < kNonBmpEnd);

164
  static constexpr base::uc32 kStarts[] = {
165 166 167 168
      kBmp1Start, kLeadSurrogateStart, kTrailSurrogateStart,
      kBmp2Start, kNonBmpStart,
  };

169
  static constexpr base::uc32 kEnds[] = {
170 171 172 173 174 175 176 177 178 179 180 181 182
      kBmp1End, kLeadSurrogateEnd, kTrailSurrogateEnd, kBmp2End, kNonBmpEnd,
  };

  CharacterRangeVector* const kTargets[] = {
      &bmp_, &lead_surrogates_, &trail_surrogates_, &bmp_, &non_bmp_,
  };

  static constexpr int kCount = arraysize(kStarts);
  STATIC_ASSERT(kCount == arraysize(kEnds));
  STATIC_ASSERT(kCount == arraysize(kTargets));

  for (int i = 0; i < kCount; i++) {
    if (kStarts[i] > range.to()) break;
183 184
    const base::uc32 from = std::max(kStarts[i], range.from());
    const base::uc32 to = std::min(kEnds[i], range.to());
185 186
    if (from > to) continue;
    kTargets[i]->emplace_back(CharacterRange::Range(from, to));
187 188 189
  }
}

190 191 192 193 194 195 196 197
namespace {

// Translates between new and old V8-isms (SmallVector, ZoneList).
ZoneList<CharacterRange>* ToCanonicalZoneList(
    const UnicodeRangeSplitter::CharacterRangeVector* v, Zone* zone) {
  if (v->empty()) return nullptr;

  ZoneList<CharacterRange>* result =
198
      zone->New<ZoneList<CharacterRange>>(static_cast<int>(v->size()), zone);
199 200
  for (size_t i = 0; i < v->size(); i++) {
    result->Add(v->at(i), zone);
201
  }
202 203 204

  CharacterRange::Canonicalize(result);
  return result;
205 206 207
}

void AddBmpCharacters(RegExpCompiler* compiler, ChoiceNode* result,
208
                      RegExpNode* on_success, UnicodeRangeSplitter* splitter) {
209 210
  ZoneList<CharacterRange>* bmp =
      ToCanonicalZoneList(splitter->bmp(), compiler->zone());
211 212
  if (bmp == nullptr) return;
  result->AddAlternative(GuardedAlternative(TextNode::CreateForCharacterRanges(
213
      compiler->zone(), bmp, compiler->read_backward(), on_success)));
214 215
}

216 217 218 219 220 221 222 223 224 225 226
using UC16Range = uint32_t;  // {from, to} packed into one uint32_t.
constexpr UC16Range ToUC16Range(base::uc16 from, base::uc16 to) {
  return (static_cast<uint32_t>(from) << 16) | to;
}
constexpr base::uc16 ExtractFrom(UC16Range r) {
  return static_cast<base::uc16>(r >> 16);
}
constexpr base::uc16 ExtractTo(UC16Range r) {
  return static_cast<base::uc16>(r);
}

227 228
void AddNonBmpSurrogatePairs(RegExpCompiler* compiler, ChoiceNode* result,
                             RegExpNode* on_success,
229
                             UnicodeRangeSplitter* splitter) {
230 231
  DCHECK(!compiler->one_byte());
  Zone* const zone = compiler->zone();
232
  ZoneList<CharacterRange>* non_bmp =
233
      ToCanonicalZoneList(splitter->non_bmp(), zone);
234
  if (non_bmp == nullptr) return;
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

  // Translate each 32-bit code point range into the corresponding 16-bit code
  // unit representation consisting of the lead- and trail surrogate.
  //
  // The generated alternatives are grouped by the leading surrogate to avoid
  // emitting excessive code. For example, for
  //
  //  { \ud800[\udc00-\udc01]
  //  , \ud800[\udc05-\udc06]
  //  }
  //
  // there's no need to emit matching code for the leading surrogate \ud800
  // twice. We also create a dedicated grouping for full trailing ranges, i.e.
  // [dc00-dfff].
  ZoneUnorderedMap<UC16Range, ZoneList<CharacterRange>*> grouped_by_leading(
      zone);
  ZoneList<CharacterRange>* leading_with_full_trailing_range =
      zone->New<ZoneList<CharacterRange>>(1, zone);
  const auto AddRange = [&](base::uc16 from_l, base::uc16 to_l,
                            base::uc16 from_t, base::uc16 to_t) {
    const UC16Range leading_range = ToUC16Range(from_l, to_l);
    if (grouped_by_leading.count(leading_range) == 0) {
      if (from_t == kTrailSurrogateStart && to_t == kTrailSurrogateEnd) {
        leading_with_full_trailing_range->Add(
            CharacterRange::Range(from_l, to_l), zone);
        return;
      }
      grouped_by_leading[leading_range] =
          zone->New<ZoneList<CharacterRange>>(2, zone);
    }
    grouped_by_leading[leading_range]->Add(CharacterRange::Range(from_t, to_t),
                                           zone);
  };

  // First, create the grouped ranges.
270 271 272 273 274 275 276
  CharacterRange::Canonicalize(non_bmp);
  for (int i = 0; i < non_bmp->length(); i++) {
    // Match surrogate pair.
    // E.g. [\u10005-\u11005] becomes
    //      \ud800[\udc05-\udfff]|
    //      [\ud801-\ud803][\udc00-\udfff]|
    //      \ud804[\udc00-\udc05]
277 278 279 280 281 282
    base::uc32 from = non_bmp->at(i).from();
    base::uc32 to = non_bmp->at(i).to();
    base::uc16 from_l = unibrow::Utf16::LeadSurrogate(from);
    base::uc16 from_t = unibrow::Utf16::TrailSurrogate(from);
    base::uc16 to_l = unibrow::Utf16::LeadSurrogate(to);
    base::uc16 to_t = unibrow::Utf16::TrailSurrogate(to);
283

284 285
    if (from_l == to_l) {
      // The lead surrogate is the same.
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
      AddRange(from_l, to_l, from_t, to_t);
      continue;
    }

    if (from_t != kTrailSurrogateStart) {
      // Add [from_l][from_t-\udfff].
      AddRange(from_l, from_l, from_t, kTrailSurrogateEnd);
      from_l++;
    }
    if (to_t != kTrailSurrogateEnd) {
      // Add [to_l][\udc00-to_t].
      AddRange(to_l, to_l, kTrailSurrogateStart, to_t);
      to_l--;
    }
    if (from_l <= to_l) {
      // Add [from_l-to_l][\udc00-\udfff].
      AddRange(from_l, to_l, kTrailSurrogateStart, kTrailSurrogateEnd);
303 304
    }
  }
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

  // Create the actual TextNode now that ranges are fully grouped.
  if (!leading_with_full_trailing_range->is_empty()) {
    CharacterRange::Canonicalize(leading_with_full_trailing_range);
    result->AddAlternative(GuardedAlternative(TextNode::CreateForSurrogatePair(
        zone, leading_with_full_trailing_range,
        CharacterRange::Range(kTrailSurrogateStart, kTrailSurrogateEnd),
        compiler->read_backward(), on_success)));
  }
  for (const auto& it : grouped_by_leading) {
    CharacterRange leading_range =
        CharacterRange::Range(ExtractFrom(it.first), ExtractTo(it.first));
    ZoneList<CharacterRange>* trailing_ranges = it.second;
    CharacterRange::Canonicalize(trailing_ranges);
    result->AddAlternative(GuardedAlternative(TextNode::CreateForSurrogatePair(
        zone, leading_range, trailing_ranges, compiler->read_backward(),
        on_success)));
  }
323 324 325 326
}

RegExpNode* NegativeLookaroundAgainstReadDirectionAndMatch(
    RegExpCompiler* compiler, ZoneList<CharacterRange>* lookbehind,
327 328
    ZoneList<CharacterRange>* match, RegExpNode* on_success,
    bool read_backward) {
329 330
  Zone* zone = compiler->zone();
  RegExpNode* match_node = TextNode::CreateForCharacterRanges(
331
      zone, match, read_backward, on_success);
332 333 334 335 336
  int stack_register = compiler->UnicodeLookaroundStackRegister();
  int position_register = compiler->UnicodeLookaroundPositionRegister();
  RegExpLookaround::Builder lookaround(false, match_node, stack_register,
                                       position_register);
  RegExpNode* negative_match = TextNode::CreateForCharacterRanges(
337
      zone, lookbehind, !read_backward, lookaround.on_match_success());
338 339 340 341 342 343
  return lookaround.ForMatch(negative_match);
}

RegExpNode* MatchAndNegativeLookaroundInReadDirection(
    RegExpCompiler* compiler, ZoneList<CharacterRange>* match,
    ZoneList<CharacterRange>* lookahead, RegExpNode* on_success,
344
    bool read_backward) {
345 346 347 348 349 350
  Zone* zone = compiler->zone();
  int stack_register = compiler->UnicodeLookaroundStackRegister();
  int position_register = compiler->UnicodeLookaroundPositionRegister();
  RegExpLookaround::Builder lookaround(false, on_success, stack_register,
                                       position_register);
  RegExpNode* negative_match = TextNode::CreateForCharacterRanges(
351
      zone, lookahead, read_backward, lookaround.on_match_success());
352
  return TextNode::CreateForCharacterRanges(
353
      zone, match, read_backward, lookaround.ForMatch(negative_match));
354 355 356 357
}

void AddLoneLeadSurrogates(RegExpCompiler* compiler, ChoiceNode* result,
                           RegExpNode* on_success,
358
                           UnicodeRangeSplitter* splitter) {
359 360
  ZoneList<CharacterRange>* lead_surrogates =
      ToCanonicalZoneList(splitter->lead_surrogates(), compiler->zone());
361 362 363 364 365 366 367 368 369 370 371
  if (lead_surrogates == nullptr) return;
  Zone* zone = compiler->zone();
  // E.g. \ud801 becomes \ud801(?![\udc00-\udfff]).
  ZoneList<CharacterRange>* trail_surrogates = CharacterRange::List(
      zone, CharacterRange::Range(kTrailSurrogateStart, kTrailSurrogateEnd));

  RegExpNode* match;
  if (compiler->read_backward()) {
    // Reading backward. Assert that reading forward, there is no trail
    // surrogate, and then backward match the lead surrogate.
    match = NegativeLookaroundAgainstReadDirectionAndMatch(
372
        compiler, trail_surrogates, lead_surrogates, on_success, true);
373 374 375 376
  } else {
    // Reading forward. Forward match the lead surrogate and assert that
    // no trail surrogate follows.
    match = MatchAndNegativeLookaroundInReadDirection(
377
        compiler, lead_surrogates, trail_surrogates, on_success, false);
378 379 380 381 382 383
  }
  result->AddAlternative(GuardedAlternative(match));
}

void AddLoneTrailSurrogates(RegExpCompiler* compiler, ChoiceNode* result,
                            RegExpNode* on_success,
384
                            UnicodeRangeSplitter* splitter) {
385 386
  ZoneList<CharacterRange>* trail_surrogates =
      ToCanonicalZoneList(splitter->trail_surrogates(), compiler->zone());
387 388 389 390 391 392 393 394 395 396 397
  if (trail_surrogates == nullptr) return;
  Zone* zone = compiler->zone();
  // E.g. \udc01 becomes (?<![\ud800-\udbff])\udc01
  ZoneList<CharacterRange>* lead_surrogates = CharacterRange::List(
      zone, CharacterRange::Range(kLeadSurrogateStart, kLeadSurrogateEnd));

  RegExpNode* match;
  if (compiler->read_backward()) {
    // Reading backward. Backward match the trail surrogate and assert that no
    // lead surrogate precedes it.
    match = MatchAndNegativeLookaroundInReadDirection(
398
        compiler, trail_surrogates, lead_surrogates, on_success, true);
399 400 401 402
  } else {
    // Reading forward. Assert that reading backward, there is no lead
    // surrogate, and then forward match the trail surrogate.
    match = NegativeLookaroundAgainstReadDirectionAndMatch(
403
        compiler, lead_surrogates, trail_surrogates, on_success, false);
404 405 406 407 408 409 410 411 412 413 414 415 416
  }
  result->AddAlternative(GuardedAlternative(match));
}

RegExpNode* UnanchoredAdvance(RegExpCompiler* compiler,
                              RegExpNode* on_success) {
  // This implements ES2015 21.2.5.2.3, AdvanceStringIndex.
  DCHECK(!compiler->read_backward());
  Zone* zone = compiler->zone();
  // Advance any character. If the character happens to be a lead surrogate and
  // we advanced into the middle of a surrogate pair, it will work out, as
  // nothing will match from there. We will have to advance again, consuming
  // the associated trail surrogate.
417 418
  ZoneList<CharacterRange>* range =
      CharacterRange::List(zone, CharacterRange::Range(0, kMaxUtf16CodeUnit));
419
  return TextNode::CreateForCharacterRanges(zone, range, false, on_success);
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
}

void AddUnicodeCaseEquivalents(ZoneList<CharacterRange>* ranges, Zone* zone) {
#ifdef V8_INTL_SUPPORT
  DCHECK(CharacterRange::IsCanonical(ranges));

  // Micro-optimization to avoid passing large ranges to UnicodeSet::closeOver.
  // See also https://crbug.com/v8/6727.
  // TODO(jgruber): This only covers the special case of the {0,0x10FFFF} range,
  // which we use frequently internally. But large ranges can also easily be
  // created by the user. We might want to have a more general caching mechanism
  // for such ranges.
  if (ranges->length() == 1 && ranges->at(0).IsEverything(kNonBmpEnd)) return;

  // Use ICU to compute the case fold closure over the ranges.
  icu::UnicodeSet set;
  for (int i = 0; i < ranges->length(); i++) {
    set.add(ranges->at(i).from(), ranges->at(i).to());
  }
439 440
  // Clear the ranges list without freeing the backing store.
  ranges->Rewind(0);
441 442 443 444 445 446 447 448 449 450 451 452 453 454
  set.closeOver(USET_CASE_INSENSITIVE);
  // Full case mapping map single characters to multiple characters.
  // Those are represented as strings in the set. Remove them so that
  // we end up with only simple and common case mappings.
  set.removeAllStrings();
  for (int i = 0; i < set.getRangeCount(); i++) {
    ranges->Add(CharacterRange::Range(set.getRangeStart(i), set.getRangeEnd(i)),
                zone);
  }
  // No errors and everything we collected have been ranges.
  CharacterRange::Canonicalize(ranges);
#endif  // V8_INTL_SUPPORT
}

455 456
}  // namespace

457 458 459
RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
                                         RegExpNode* on_success) {
  set_.Canonicalize();
460
  Zone* const zone = compiler->zone();
461
  ZoneList<CharacterRange>* ranges = this->ranges(zone);
462

463
  if (NeedsUnicodeCaseEquivalents(compiler->flags())) {
464 465
    AddUnicodeCaseEquivalents(ranges, zone);
  }
466 467 468

  if (!IsUnicode(compiler->flags()) || compiler->one_byte() ||
      contains_split_surrogate()) {
469
    return zone->New<TextNode>(this, compiler->read_backward(), on_success);
470
  }
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

  if (is_negated()) {
    ZoneList<CharacterRange>* negated =
        zone->New<ZoneList<CharacterRange>>(2, zone);
    CharacterRange::Negate(ranges, negated, zone);
    ranges = negated;
  }

  if (ranges->length() == 0) {
    // The empty character class is used as a 'fail' node.
    RegExpCharacterClass* fail = zone->New<RegExpCharacterClass>(zone, ranges);
    return zone->New<TextNode>(fail, compiler->read_backward(), on_success);
  }

  if (set_.is_standard() &&
      standard_type() == StandardCharacterSet::kEverything) {
    return UnanchoredAdvance(compiler, on_success);
  }

  // Split ranges in order to handle surrogates correctly:
  // - Surrogate pairs: translate the 32-bit code point into two uc16 code
  //   units (irregexp operates only on code units).
  // - Lone surrogates: these require lookarounds to ensure we don't match in
  //   the middle of a surrogate pair.
  ChoiceNode* result = zone->New<ChoiceNode>(2, zone);
  UnicodeRangeSplitter splitter(ranges);
  AddBmpCharacters(compiler, result, on_success, &splitter);
  AddNonBmpSurrogatePairs(compiler, result, on_success, &splitter);
  AddLoneLeadSurrogates(compiler, result, on_success, &splitter);
  AddLoneTrailSurrogates(compiler, result, on_success, &splitter);

  static constexpr int kMaxRangesToInline = 32;  // Arbitrary.
  if (ranges->length() > kMaxRangesToInline) result->SetDoNotInline();

  return result;
506 507
}

Jakob Gruber's avatar
Jakob Gruber committed
508 509
namespace {

510 511 512
int CompareFirstChar(RegExpTree* const* a, RegExpTree* const* b) {
  RegExpAtom* atom1 = (*a)->AsAtom();
  RegExpAtom* atom2 = (*b)->AsAtom();
513 514
  base::uc16 character1 = atom1->data().at(0);
  base::uc16 character2 = atom2->data().at(0);
515 516 517 518 519 520 521
  if (character1 < character2) return -1;
  if (character1 > character2) return 1;
  return 0;
}

#ifdef V8_INTL_SUPPORT

522 523 524 525 526 527 528
int CompareCaseInsensitive(const icu::UnicodeString& a,
                           const icu::UnicodeString& b) {
  return a.caseCompare(b, U_FOLD_CASE_DEFAULT);
}

int CompareFirstCharCaseInsensitive(RegExpTree* const* a,
                                    RegExpTree* const* b) {
529 530
  RegExpAtom* atom1 = (*a)->AsAtom();
  RegExpAtom* atom2 = (*b)->AsAtom();
531 532 533 534 535 536 537 538 539 540 541 542 543 544
  return CompareCaseInsensitive(icu::UnicodeString{atom1->data().at(0)},
                                icu::UnicodeString{atom2->data().at(0)});
}

bool Equals(bool ignore_case, const icu::UnicodeString& a,
            const icu::UnicodeString& b) {
  if (a == b) return true;
  if (ignore_case) return CompareCaseInsensitive(a, b) == 0;
  return false;  // Case-sensitive equality already checked above.
}

bool CharAtEquals(bool ignore_case, int index, const RegExpAtom* a,
                  const RegExpAtom* b) {
  return Equals(ignore_case, a->data().at(index), b->data().at(index));
545 546 547 548
}

#else

Jakob Gruber's avatar
Jakob Gruber committed
549
unibrow::uchar Canonical(
550 551 552 553 554 555 556 557 558 559
    unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize,
    unibrow::uchar c) {
  unibrow::uchar chars[unibrow::Ecma262Canonicalize::kMaxWidth];
  int length = canonicalize->get(c, '\0', chars);
  DCHECK_LE(length, 1);
  unibrow::uchar canonical = c;
  if (length == 1) canonical = chars[0];
  return canonical;
}

560 561 562 563 564 565 566 567 568 569 570 571
int CompareCaseInsensitive(
    unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize,
    unibrow::uchar a, unibrow::uchar b) {
  if (a == b) return 0;
  if (a >= 'a' || b >= 'a') {
    a = Canonical(canonicalize, a);
    b = Canonical(canonicalize, b);
  }
  return static_cast<int>(a) - static_cast<int>(b);
}

int CompareFirstCharCaseInsensitive(
572 573 574 575
    unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize,
    RegExpTree* const* a, RegExpTree* const* b) {
  RegExpAtom* atom1 = (*a)->AsAtom();
  RegExpAtom* atom2 = (*b)->AsAtom();
576 577 578 579 580 581 582 583 584 585
  return CompareCaseInsensitive(canonicalize, atom1->data().at(0),
                                atom2->data().at(0));
}

bool Equals(bool ignore_case,
            unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize,
            unibrow::uchar a, unibrow::uchar b) {
  if (a == b) return true;
  if (ignore_case) {
    return CompareCaseInsensitive(canonicalize, a, b) == 0;
586
  }
587 588 589 590 591 592 593 594
  return false;  // Case-sensitive equality already checked above.
}

bool CharAtEquals(bool ignore_case,
                  unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize,
                  int index, const RegExpAtom* a, const RegExpAtom* b) {
  return Equals(ignore_case, canonicalize, a->data().at(index),
                b->data().at(index));
595
}
596

597 598
#endif  // V8_INTL_SUPPORT

Jakob Gruber's avatar
Jakob Gruber committed
599 600
}  // namespace

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
// We can stable sort runs of atoms, since the order does not matter if they
// start with different characters.
// Returns true if any consecutive atoms were found.
bool RegExpDisjunction::SortConsecutiveAtoms(RegExpCompiler* compiler) {
  ZoneList<RegExpTree*>* alternatives = this->alternatives();
  int length = alternatives->length();
  bool found_consecutive_atoms = false;
  for (int i = 0; i < length; i++) {
    while (i < length) {
      RegExpTree* alternative = alternatives->at(i);
      if (alternative->IsAtom()) break;
      i++;
    }
    // i is length or it is the index of an atom.
    if (i == length) break;
    int first_atom = i;
    i++;
    while (i < length) {
      RegExpTree* alternative = alternatives->at(i);
      if (!alternative->IsAtom()) break;
      i++;
    }
    // Sort atoms to get ones with common prefixes together.
    // This step is more tricky if we are in a case-independent regexp,
    // because it would change /is|I/ to /I|is/, and order matters when
    // the regexp parts don't match only disjoint starting points. To fix
    // this we have a version of CompareFirstChar that uses case-
    // independent character classes for comparison.
    DCHECK_LT(first_atom, alternatives->length());
    DCHECK_LE(i, alternatives->length());
    DCHECK_LE(first_atom, i);
632
    if (IsIgnoreCase(compiler->flags())) {
633
#ifdef V8_INTL_SUPPORT
634
      alternatives->StableSort(CompareFirstCharCaseInsensitive, first_atom,
635 636 637 638 639 640
                               i - first_atom);
#else
      unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize =
          compiler->isolate()->regexp_macro_assembler_canonicalize();
      auto compare_closure = [canonicalize](RegExpTree* const* a,
                                            RegExpTree* const* b) {
641
        return CompareFirstCharCaseInsensitive(canonicalize, a, b);
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
      };
      alternatives->StableSort(compare_closure, first_atom, i - first_atom);
#endif  // V8_INTL_SUPPORT
    } else {
      alternatives->StableSort(CompareFirstChar, first_atom, i - first_atom);
    }
    if (i - first_atom > 1) found_consecutive_atoms = true;
  }
  return found_consecutive_atoms;
}

// Optimizes ab|ac|az to a(?:b|c|d).
void RegExpDisjunction::RationalizeConsecutiveAtoms(RegExpCompiler* compiler) {
  Zone* zone = compiler->zone();
  ZoneList<RegExpTree*>* alternatives = this->alternatives();
  int length = alternatives->length();
658
  const bool ignore_case = IsIgnoreCase(compiler->flags());
659 660 661 662 663 664 665 666 667 668 669 670 671 672

  int write_posn = 0;
  int i = 0;
  while (i < length) {
    RegExpTree* alternative = alternatives->at(i);
    if (!alternative->IsAtom()) {
      alternatives->at(write_posn++) = alternatives->at(i);
      i++;
      continue;
    }
    RegExpAtom* const atom = alternative->AsAtom();
#ifdef V8_INTL_SUPPORT
    icu::UnicodeString common_prefix(atom->data().at(0));
#else
673 674
    unibrow::Mapping<unibrow::Ecma262Canonicalize>* const canonicalize =
        compiler->isolate()->regexp_macro_assembler_canonicalize();
675
    unibrow::uchar common_prefix = atom->data().at(0);
676 677 678
    if (ignore_case) {
      common_prefix = Canonical(canonicalize, common_prefix);
    }
679 680 681 682 683 684 685
#endif  // V8_INTL_SUPPORT
    int first_with_prefix = i;
    int prefix_length = atom->length();
    i++;
    while (i < length) {
      alternative = alternatives->at(i);
      if (!alternative->IsAtom()) break;
686
      RegExpAtom* const alt_atom = alternative->AsAtom();
687
#ifdef V8_INTL_SUPPORT
688
      icu::UnicodeString new_prefix(alt_atom->data().at(0));
689
      if (!Equals(ignore_case, new_prefix, common_prefix)) break;
690
#else
691
      unibrow::uchar new_prefix = alt_atom->data().at(0);
692
      if (!Equals(ignore_case, canonicalize, new_prefix, common_prefix)) break;
693
#endif  // V8_INTL_SUPPORT
694
      prefix_length = std::min(prefix_length, alt_atom->length());
695 696 697 698 699 700 701 702 703
      i++;
    }
    if (i > first_with_prefix + 2) {
      // Found worthwhile run of alternatives with common prefix of at least one
      // character.  The sorting function above did not sort on more than one
      // character for reasons of correctness, but there may still be a longer
      // common prefix if the terms were similar or presorted in the input.
      // Find out how long the common prefix is.
      int run_length = i - first_with_prefix;
704 705
      RegExpAtom* const alt_atom =
          alternatives->at(first_with_prefix)->AsAtom();
706 707 708 709
      for (int j = 1; j < run_length && prefix_length > 1; j++) {
        RegExpAtom* old_atom =
            alternatives->at(j + first_with_prefix)->AsAtom();
        for (int k = 1; k < prefix_length; k++) {
710 711 712 713 714
#ifdef V8_INTL_SUPPORT
          if (!CharAtEquals(ignore_case, k, alt_atom, old_atom)) {
#else
          if (!CharAtEquals(ignore_case, canonicalize, k, alt_atom, old_atom)) {
#endif  // V8_INTL_SUPPORT
715 716 717 718 719
            prefix_length = k;
            break;
          }
        }
      }
720
      RegExpAtom* prefix =
721
          zone->New<RegExpAtom>(alt_atom->data().SubVector(0, prefix_length));
722
      ZoneList<RegExpTree*>* pair = zone->New<ZoneList<RegExpTree*>>(2, zone);
723 724
      pair->Add(prefix, zone);
      ZoneList<RegExpTree*>* suffixes =
725
          zone->New<ZoneList<RegExpTree*>>(run_length, zone);
726 727 728 729 730
      for (int j = 0; j < run_length; j++) {
        RegExpAtom* old_atom =
            alternatives->at(j + first_with_prefix)->AsAtom();
        int len = old_atom->length();
        if (len == prefix_length) {
731
          suffixes->Add(zone->New<RegExpEmpty>(), zone);
732
        } else {
733
          RegExpTree* suffix = zone->New<RegExpAtom>(
734
              old_atom->data().SubVector(prefix_length, old_atom->length()));
735 736 737
          suffixes->Add(suffix, zone);
        }
      }
738 739
      pair->Add(zone->New<RegExpDisjunction>(suffixes), zone);
      alternatives->at(write_posn++) = zone->New<RegExpAlternative>(pair);
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
    } else {
      // Just copy any non-worthwhile alternatives.
      for (int j = first_with_prefix; j < i; j++) {
        alternatives->at(write_posn++) = alternatives->at(j);
      }
    }
  }
  alternatives->Rewind(write_posn);  // Trim end of array.
}

// Optimizes b|c|z to [bcz].
void RegExpDisjunction::FixSingleCharacterDisjunctions(
    RegExpCompiler* compiler) {
  Zone* zone = compiler->zone();
  ZoneList<RegExpTree*>* alternatives = this->alternatives();
  int length = alternatives->length();

  int write_posn = 0;
  int i = 0;
  while (i < length) {
    RegExpTree* alternative = alternatives->at(i);
    if (!alternative->IsAtom()) {
      alternatives->at(write_posn++) = alternatives->at(i);
      i++;
      continue;
    }
    RegExpAtom* const atom = alternative->AsAtom();
    if (atom->length() != 1) {
      alternatives->at(write_posn++) = alternatives->at(i);
      i++;
      continue;
    }
772
    const RegExpFlags flags = compiler->flags();
773 774 775 776 777 778 779 780 781 782 783
    DCHECK_IMPLIES(IsUnicode(flags),
                   !unibrow::Utf16::IsLeadSurrogate(atom->data().at(0)));
    bool contains_trail_surrogate =
        unibrow::Utf16::IsTrailSurrogate(atom->data().at(0));
    int first_in_run = i;
    i++;
    // Find a run of single-character atom alternatives that have identical
    // flags (case independence and unicode-ness).
    while (i < length) {
      alternative = alternatives->at(i);
      if (!alternative->IsAtom()) break;
784 785
      RegExpAtom* const alt_atom = alternative->AsAtom();
      if (alt_atom->length() != 1) break;
786
      DCHECK_IMPLIES(IsUnicode(flags),
787
                     !unibrow::Utf16::IsLeadSurrogate(alt_atom->data().at(0)));
788
      contains_trail_surrogate |=
789
          unibrow::Utf16::IsTrailSurrogate(alt_atom->data().at(0));
790 791 792 793 794 795
      i++;
    }
    if (i > first_in_run + 1) {
      // Found non-trivial run of single-character alternatives.
      int run_length = i - first_in_run;
      ZoneList<CharacterRange>* ranges =
796
          zone->New<ZoneList<CharacterRange>>(2, zone);
797 798 799 800 801 802 803 804 805
      for (int j = 0; j < run_length; j++) {
        RegExpAtom* old_atom = alternatives->at(j + first_in_run)->AsAtom();
        DCHECK_EQ(old_atom->length(), 1);
        ranges->Add(CharacterRange::Singleton(old_atom->data().at(0)), zone);
      }
      RegExpCharacterClass::CharacterClassFlags character_class_flags;
      if (IsUnicode(flags) && contains_trail_surrogate) {
        character_class_flags = RegExpCharacterClass::CONTAINS_SPLIT_SURROGATE;
      }
806 807
      alternatives->at(write_posn++) =
          zone->New<RegExpCharacterClass>(zone, ranges, character_class_flags);
808 809 810 811 812 813 814 815 816 817 818 819
    } else {
      // Just copy any trivial alternatives.
      for (int j = first_in_run; j < i; j++) {
        alternatives->at(write_posn++) = alternatives->at(j);
      }
    }
  }
  alternatives->Rewind(write_posn);  // Trim end of array.
}

RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
                                      RegExpNode* on_success) {
820 821
  compiler->ToNodeMaybeCheckForStackOverflow();

822 823 824 825 826 827 828 829 830 831 832 833 834 835
  ZoneList<RegExpTree*>* alternatives = this->alternatives();

  if (alternatives->length() > 2) {
    bool found_consecutive_atoms = SortConsecutiveAtoms(compiler);
    if (found_consecutive_atoms) RationalizeConsecutiveAtoms(compiler);
    FixSingleCharacterDisjunctions(compiler);
    if (alternatives->length() == 1) {
      return alternatives->at(0)->ToNode(compiler, on_success);
    }
  }

  int length = alternatives->length();

  ChoiceNode* result =
836
      compiler->zone()->New<ChoiceNode>(length, compiler->zone());
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
  for (int i = 0; i < length; i++) {
    GuardedAlternative alternative(
        alternatives->at(i)->ToNode(compiler, on_success));
    result->AddAlternative(alternative);
  }
  return result;
}

RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
                                     RegExpNode* on_success) {
  return ToNode(min(), max(), is_greedy(), body(), compiler, on_success);
}

namespace {
// Desugar \b to (?<=\w)(?=\W)|(?<=\W)(?=\w) and
//         \B to (?<=\w)(?=\w)|(?<=\W)(?=\W)
RegExpNode* BoundaryAssertionAsLookaround(RegExpCompiler* compiler,
                                          RegExpNode* on_success,
855
                                          RegExpAssertion::Type type,
856
                                          RegExpFlags flags) {
857
  CHECK(NeedsUnicodeCaseEquivalents(flags));
858 859
  Zone* zone = compiler->zone();
  ZoneList<CharacterRange>* word_range =
860
      zone->New<ZoneList<CharacterRange>>(2, zone);
861 862
  CharacterRange::AddClassEscape(StandardCharacterSet::kWord, word_range, true,
                                 zone);
863 864
  int stack_register = compiler->UnicodeLookaroundStackRegister();
  int position_register = compiler->UnicodeLookaroundPositionRegister();
865
  ChoiceNode* result = zone->New<ChoiceNode>(2, zone);
866 867 868 869 870
  // Add two choices. The (non-)boundary could start with a word or
  // a non-word-character.
  for (int i = 0; i < 2; i++) {
    bool lookbehind_for_word = i == 0;
    bool lookahead_for_word =
871
        (type == RegExpAssertion::Type::BOUNDARY) ^ lookbehind_for_word;
872 873 874 875
    // Look to the left.
    RegExpLookaround::Builder lookbehind(lookbehind_for_word, on_success,
                                         stack_register, position_register);
    RegExpNode* backward = TextNode::CreateForCharacterRanges(
876
        zone, word_range, true, lookbehind.on_match_success());
877 878 879 880 881
    // Look to the right.
    RegExpLookaround::Builder lookahead(lookahead_for_word,
                                        lookbehind.ForMatch(backward),
                                        stack_register, position_register);
    RegExpNode* forward = TextNode::CreateForCharacterRanges(
882
        zone, word_range, false, lookahead.on_match_success());
883 884 885 886 887 888 889 890 891 892 893 894
    result->AddAlternative(GuardedAlternative(lookahead.ForMatch(forward)));
  }
  return result;
}
}  // anonymous namespace

RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
                                    RegExpNode* on_success) {
  NodeInfo info;
  Zone* zone = compiler->zone();

  switch (assertion_type()) {
895
    case Type::START_OF_LINE:
896
      return AssertionNode::AfterNewline(on_success);
897
    case Type::START_OF_INPUT:
898
      return AssertionNode::AtStart(on_success);
899
    case Type::BOUNDARY:
900
      return NeedsUnicodeCaseEquivalents(compiler->flags())
901 902
                 ? BoundaryAssertionAsLookaround(
                       compiler, on_success, Type::BOUNDARY, compiler->flags())
903
                 : AssertionNode::AtBoundary(on_success);
904
    case Type::NON_BOUNDARY:
905
      return NeedsUnicodeCaseEquivalents(compiler->flags())
906 907 908
                 ? BoundaryAssertionAsLookaround(compiler, on_success,
                                                 Type::NON_BOUNDARY,
                                                 compiler->flags())
909
                 : AssertionNode::AtNonBoundary(on_success);
910
    case Type::END_OF_INPUT:
911
      return AssertionNode::AtEnd(on_success);
912
    case Type::END_OF_LINE: {
913 914 915 916 917 918
      // Compile $ in multiline regexps as an alternation with a positive
      // lookahead in one side and an end-of-input on the other side.
      // We need two registers for the lookahead.
      int stack_pointer_register = compiler->AllocateRegister();
      int position_register = compiler->AllocateRegister();
      // The ChoiceNode to distinguish between a newline and end-of-input.
919
      ChoiceNode* result = zone->New<ChoiceNode>(2, zone);
920 921
      // Create a newline atom.
      ZoneList<CharacterRange>* newline_ranges =
922
          zone->New<ZoneList<CharacterRange>>(3, zone);
923 924 925 926
      CharacterRange::AddClassEscape(StandardCharacterSet::kLineTerminator,
                                     newline_ranges, false, zone);
      RegExpCharacterClass* newline_atom = zone->New<RegExpCharacterClass>(
          StandardCharacterSet::kLineTerminator);
927
      TextNode* newline_matcher =
928
          zone->New<TextNode>(newline_atom, false,
929 930 931 932 933 934
                              ActionNode::PositiveSubmatchSuccess(
                                  stack_pointer_register, position_register,
                                  0,   // No captures inside.
                                  -1,  // Ignored if no captures.
                                  on_success));
      // Create an end-of-input matcher.
935
      RegExpNode* end_of_line = ActionNode::BeginPositiveSubmatch(
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
          stack_pointer_register, position_register, newline_matcher);
      // Add the two alternatives to the ChoiceNode.
      GuardedAlternative eol_alternative(end_of_line);
      result->AddAlternative(eol_alternative);
      GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
      result->AddAlternative(end_alternative);
      return result;
    }
    default:
      UNREACHABLE();
  }
}

RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
                                        RegExpNode* on_success) {
951 952 953 954
  return compiler->zone()->New<BackReferenceNode>(
      RegExpCapture::StartRegister(index()),
      RegExpCapture::EndRegister(index()), flags_, compiler->read_backward(),
      on_success);
955 956 957 958 959 960 961
}

RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
                                RegExpNode* on_success) {
  return on_success;
}

962 963 964 965 966
RegExpNode* RegExpGroup::ToNode(RegExpCompiler* compiler,
                                RegExpNode* on_success) {
  return body_->ToNode(compiler, on_success);
}

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
RegExpLookaround::Builder::Builder(bool is_positive, RegExpNode* on_success,
                                   int stack_pointer_register,
                                   int position_register,
                                   int capture_register_count,
                                   int capture_register_start)
    : is_positive_(is_positive),
      on_success_(on_success),
      stack_pointer_register_(stack_pointer_register),
      position_register_(position_register) {
  if (is_positive_) {
    on_match_success_ = ActionNode::PositiveSubmatchSuccess(
        stack_pointer_register, position_register, capture_register_count,
        capture_register_start, on_success_);
  } else {
    Zone* zone = on_success_->zone();
982
    on_match_success_ = zone->New<NegativeSubmatchSuccess>(
983 984 985 986 987 988 989
        stack_pointer_register, position_register, capture_register_count,
        capture_register_start, zone);
  }
}

RegExpNode* RegExpLookaround::Builder::ForMatch(RegExpNode* match) {
  if (is_positive_) {
990 991
    return ActionNode::BeginPositiveSubmatch(stack_pointer_register_,
                                             position_register_, match);
992 993 994 995 996 997 998
  } else {
    Zone* zone = on_success_->zone();
    // We use a ChoiceNode to represent the negative lookaround. The first
    // alternative is the negative match. On success, the end node backtracks.
    // On failure, the second alternative is tried and leads to success.
    // NegativeLookaheadChoiceNode is a special ChoiceNode that ignores the
    // first exit when calculating quick checks.
999
    ChoiceNode* choice_node = zone->New<NegativeLookaroundChoiceNode>(
1000
        GuardedAlternative(match), GuardedAlternative(on_success_), zone);
1001 1002
    return ActionNode::BeginNegativeSubmatch(stack_pointer_register_,
                                             position_register_, choice_node);
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
  }
}

RegExpNode* RegExpLookaround::ToNode(RegExpCompiler* compiler,
                                     RegExpNode* on_success) {
  int stack_pointer_register = compiler->AllocateRegister();
  int position_register = compiler->AllocateRegister();

  const int registers_per_capture = 2;
  const int register_of_first_capture = 2;
  int register_count = capture_count_ * registers_per_capture;
  int register_start =
      register_of_first_capture + capture_from_ * registers_per_capture;

  RegExpNode* result;
  bool was_reading_backward = compiler->read_backward();
  compiler->set_read_backward(type() == LOOKBEHIND);
  Builder builder(is_positive(), on_success, stack_pointer_register,
                  position_register, register_count, register_start);
  RegExpNode* match = body_->ToNode(compiler, builder.on_match_success());
  result = builder.ForMatch(match);
  compiler->set_read_backward(was_reading_backward);
  return result;
}

RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
                                  RegExpNode* on_success) {
  return ToNode(body(), index(), compiler, on_success);
}

RegExpNode* RegExpCapture::ToNode(RegExpTree* body, int index,
                                  RegExpCompiler* compiler,
                                  RegExpNode* on_success) {
  DCHECK_NOT_NULL(body);
  int start_reg = RegExpCapture::StartRegister(index);
  int end_reg = RegExpCapture::EndRegister(index);
  if (compiler->read_backward()) std::swap(start_reg, end_reg);
  RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
  RegExpNode* body_node = body->ToNode(compiler, store_end);
  return ActionNode::StorePosition(start_reg, true, body_node);
}

1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
namespace {

class AssertionSequenceRewriter final {
 public:
  // TODO(jgruber): Consider moving this to a separate AST tree rewriter pass
  // instead of sprinkling rewrites into the AST->Node conversion process.
  static void MaybeRewrite(ZoneList<RegExpTree*>* terms, Zone* zone) {
    AssertionSequenceRewriter rewriter(terms, zone);

    static constexpr int kNoIndex = -1;
    int from = kNoIndex;

    for (int i = 0; i < terms->length(); i++) {
      RegExpTree* t = terms->at(i);
      if (from == kNoIndex && t->IsAssertion()) {
        from = i;  // Start a sequence.
      } else if (from != kNoIndex && !t->IsAssertion()) {
        // Terminate and process the sequence.
        if (i - from > 1) rewriter.Rewrite(from, i);
        from = kNoIndex;
      }
    }

    if (from != kNoIndex && terms->length() - from > 1) {
      rewriter.Rewrite(from, terms->length());
    }
  }

  // All assertions are zero width. A consecutive sequence of assertions is
  // order-independent. There's two ways we can optimize here:
  // 1. fold all identical assertions.
  // 2. if any assertion combinations are known to fail (e.g. \b\B), the entire
  //    sequence fails.
  void Rewrite(int from, int to) {
    DCHECK_GT(to, from + 1);

    // Bitfield of all seen assertions.
    uint32_t seen_assertions = 0;
1083 1084
    STATIC_ASSERT(static_cast<int>(RegExpAssertion::Type::LAST_ASSERTION_TYPE) <
                  kUInt32Size * kBitsPerByte);
1085 1086 1087

    for (int i = from; i < to; i++) {
      RegExpAssertion* t = terms_->at(i)->AsAssertion();
1088
      const uint32_t bit = 1 << static_cast<int>(t->assertion_type());
1089

1090
      if (seen_assertions & bit) {
1091
        // Fold duplicates.
1092
        terms_->Set(i, zone_->New<RegExpEmpty>());
1093 1094 1095 1096 1097 1098 1099
      }

      seen_assertions |= bit;
    }

    // Collapse failures.
    const uint32_t always_fails_mask =
1100 1101
        1 << static_cast<int>(RegExpAssertion::Type::BOUNDARY) |
        1 << static_cast<int>(RegExpAssertion::Type::NON_BOUNDARY);
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    if ((seen_assertions & always_fails_mask) == always_fails_mask) {
      ReplaceSequenceWithFailure(from, to);
    }
  }

  void ReplaceSequenceWithFailure(int from, int to) {
    // Replace the entire sequence with a single node that always fails.
    // TODO(jgruber): Consider adding an explicit Fail kind. Until then, the
    // negated '*' (everything) range serves the purpose.
    ZoneList<CharacterRange>* ranges =
1112
        zone_->New<ZoneList<CharacterRange>>(0, zone_);
1113
    RegExpCharacterClass* cc = zone_->New<RegExpCharacterClass>(zone_, ranges);
1114 1115 1116
    terms_->Set(from, cc);

    // Zero out the rest.
1117
    RegExpEmpty* empty = zone_->New<RegExpEmpty>();
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    for (int i = from + 1; i < to; i++) terms_->Set(i, empty);
  }

 private:
  AssertionSequenceRewriter(ZoneList<RegExpTree*>* terms, Zone* zone)
      : zone_(zone), terms_(terms) {}

  Zone* zone_;
  ZoneList<RegExpTree*>* terms_;
};

}  // namespace

1131 1132
RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
                                      RegExpNode* on_success) {
1133 1134
  compiler->ToNodeMaybeCheckForStackOverflow();

1135
  ZoneList<RegExpTree*>* children = nodes();
1136 1137 1138

  AssertionSequenceRewriter::MaybeRewrite(children, compiler->zone());

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
  RegExpNode* current = on_success;
  if (compiler->read_backward()) {
    for (int i = 0; i < children->length(); i++) {
      current = children->at(i)->ToNode(compiler, current);
    }
  } else {
    for (int i = children->length() - 1; i >= 0; i--) {
      current = children->at(i)->ToNode(compiler, current);
    }
  }
  return current;
}

Jakob Gruber's avatar
Jakob Gruber committed
1152 1153 1154 1155
namespace {

void AddClass(const int* elmv, int elmc, ZoneList<CharacterRange>* ranges,
              Zone* zone) {
1156 1157 1158 1159 1160 1161 1162 1163
  elmc--;
  DCHECK_EQ(kRangeEndMarker, elmv[elmc]);
  for (int i = 0; i < elmc; i += 2) {
    DCHECK(elmv[i] < elmv[i + 1]);
    ranges->Add(CharacterRange::Range(elmv[i], elmv[i + 1] - 1), zone);
  }
}

Jakob Gruber's avatar
Jakob Gruber committed
1164 1165
void AddClassNegated(const int* elmv, int elmc,
                     ZoneList<CharacterRange>* ranges, Zone* zone) {
1166 1167 1168
  elmc--;
  DCHECK_EQ(kRangeEndMarker, elmv[elmc]);
  DCHECK_NE(0x0000, elmv[0]);
1169
  DCHECK_NE(kMaxCodePoint, elmv[elmc - 1]);
1170
  base::uc16 last = 0x0000;
1171 1172 1173 1174 1175 1176
  for (int i = 0; i < elmc; i += 2) {
    DCHECK(last <= elmv[i] - 1);
    DCHECK(elmv[i] < elmv[i + 1]);
    ranges->Add(CharacterRange::Range(last, elmv[i] - 1), zone);
    last = elmv[i + 1];
  }
1177
  ranges->Add(CharacterRange::Range(last, kMaxCodePoint), zone);
1178 1179
}

Jakob Gruber's avatar
Jakob Gruber committed
1180 1181
}  // namespace

1182 1183
void CharacterRange::AddClassEscape(StandardCharacterSet standard_character_set,
                                    ZoneList<CharacterRange>* ranges,
1184 1185
                                    bool add_unicode_case_equivalents,
                                    Zone* zone) {
1186 1187 1188
  if (add_unicode_case_equivalents &&
      (standard_character_set == StandardCharacterSet::kWord ||
       standard_character_set == StandardCharacterSet::kNotWord)) {
1189 1190 1191 1192
    // See #sec-runtime-semantics-wordcharacters-abstract-operation
    // In case of unicode and ignore_case, we need to create the closure over
    // case equivalent characters before negating.
    ZoneList<CharacterRange>* new_ranges =
1193
        zone->New<ZoneList<CharacterRange>>(2, zone);
1194 1195
    AddClass(kWordRanges, kWordRangeCount, new_ranges, zone);
    AddUnicodeCaseEquivalents(new_ranges, zone);
1196
    if (standard_character_set == StandardCharacterSet::kNotWord) {
1197
      ZoneList<CharacterRange>* negated =
1198
          zone->New<ZoneList<CharacterRange>>(2, zone);
1199 1200 1201 1202 1203 1204 1205
      CharacterRange::Negate(new_ranges, negated, zone);
      new_ranges = negated;
    }
    ranges->AddAll(*new_ranges, zone);
    return;
  }

1206 1207
  switch (standard_character_set) {
    case StandardCharacterSet::kWhitespace:
1208 1209
      AddClass(kSpaceRanges, kSpaceRangeCount, ranges, zone);
      break;
1210
    case StandardCharacterSet::kNotWhitespace:
1211 1212
      AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges, zone);
      break;
1213
    case StandardCharacterSet::kWord:
1214 1215
      AddClass(kWordRanges, kWordRangeCount, ranges, zone);
      break;
1216
    case StandardCharacterSet::kNotWord:
1217 1218
      AddClassNegated(kWordRanges, kWordRangeCount, ranges, zone);
      break;
1219
    case StandardCharacterSet::kDigit:
1220 1221
      AddClass(kDigitRanges, kDigitRangeCount, ranges, zone);
      break;
1222
    case StandardCharacterSet::kNotDigit:
1223 1224
      AddClassNegated(kDigitRanges, kDigitRangeCount, ranges, zone);
      break;
1225 1226 1227 1228 1229 1230
    // This is the set of characters matched by the $ and ^ symbols
    // in multiline mode.
    case StandardCharacterSet::kLineTerminator:
      AddClass(kLineTerminatorRanges, kLineTerminatorRangeCount, ranges, zone);
      break;
    case StandardCharacterSet::kNotLineTerminator:
1231 1232 1233 1234 1235 1236
      AddClassNegated(kLineTerminatorRanges, kLineTerminatorRangeCount, ranges,
                      zone);
      break;
    // This is not a character range as defined by the spec but a
    // convenient shorthand for a character class that matches any
    // character.
1237
    case StandardCharacterSet::kEverything:
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
      ranges->Add(CharacterRange::Everything(), zone);
      break;
  }
}

// static
void CharacterRange::AddCaseEquivalents(Isolate* isolate, Zone* zone,
                                        ZoneList<CharacterRange>* ranges,
                                        bool is_one_byte) {
  CharacterRange::Canonicalize(ranges);
  int range_count = ranges->length();
#ifdef V8_INTL_SUPPORT
  icu::UnicodeSet others;
  for (int i = 0; i < range_count; i++) {
    CharacterRange range = ranges->at(i);
1253
    base::uc32 from = range.from();
1254 1255
    if (from > kMaxUtf16CodeUnit) continue;
    base::uc32 to = std::min({range.to(), kMaxUtf16CodeUnitU});
1256
    // Nothing to be done for surrogates.
1257
    if (from >= kLeadSurrogateStart && to <= kTrailSurrogateEnd) continue;
1258
    if (is_one_byte && !RangeContainsLatin1Equivalents(range)) {
1259 1260
      if (from > kMaxOneByteCharCode) continue;
      if (to > kMaxOneByteCharCode) to = kMaxOneByteCharCode;
1261 1262 1263 1264
    }
    others.add(from, to);
  }

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
  // Compute the set of additional characters that should be added,
  // using UnicodeSet::closeOver. ECMA 262 defines slightly different
  // case-folding rules than Unicode, so some characters that are
  // added by closeOver do not match anything other than themselves in
  // JS. For example, 'ſ' (U+017F LATIN SMALL LETTER LONG S) is the
  // same case-insensitive character as 's' or 'S' according to
  // Unicode, but does not match any other character in JS. To handle
  // this case, we add such characters to the IgnoreSet and filter
  // them out. We filter twice: once before calling closeOver (to
  // prevent 'ſ' from adding 's'), and once after calling closeOver
  // (to prevent 's' from adding 'ſ'). See regexp/special-case.h for
  // more information.
1277
  icu::UnicodeSet already_added(others);
1278
  others.removeAll(RegExpCaseFolding::IgnoreSet());
1279
  others.closeOver(USET_CASE_INSENSITIVE);
1280
  others.removeAll(RegExpCaseFolding::IgnoreSet());
1281
  others.removeAll(already_added);
1282 1283

  // Add others to the ranges
1284
  for (int32_t i = 0; i < others.getRangeCount(); i++) {
1285 1286 1287 1288
    UChar32 from = others.getRangeStart(i);
    UChar32 to = others.getRangeEnd(i);
    if (from == to) {
      ranges->Add(CharacterRange::Singleton(from), zone);
1289
    } else {
1290
      ranges->Add(CharacterRange::Range(from, to), zone);
1291 1292 1293 1294 1295
    }
  }
#else
  for (int i = 0; i < range_count; i++) {
    CharacterRange range = ranges->at(i);
1296
    base::uc32 bottom = range.from();
1297 1298
    if (bottom > kMaxUtf16CodeUnit) continue;
    base::uc32 top = std::min({range.to(), kMaxUtf16CodeUnitU});
1299 1300 1301
    // Nothing to be done for surrogates.
    if (bottom >= kLeadSurrogateStart && top <= kTrailSurrogateEnd) continue;
    if (is_one_byte && !RangeContainsLatin1Equivalents(range)) {
1302 1303
      if (bottom > kMaxOneByteCharCode) continue;
      if (top > kMaxOneByteCharCode) top = kMaxOneByteCharCode;
1304 1305 1306 1307 1308 1309
    }
    unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
    if (top == bottom) {
      // If this is a singleton we just expand the one character.
      int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
      for (int i = 0; i < length; i++) {
1310
        base::uc32 chr = chars[i];
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
        if (chr != bottom) {
          ranges->Add(CharacterRange::Singleton(chars[i]), zone);
        }
      }
    } else {
      // If this is a range we expand the characters block by block, expanding
      // contiguous subranges (blocks) one at a time.  The approach is as
      // follows.  For a given start character we look up the remainder of the
      // block that contains it (represented by the end point), for instance we
      // find 'z' if the character is 'c'.  A block is characterized by the
      // property that all characters uncanonicalize in the same way, except
      // that each entry in the result is incremented by the distance from the
      // first element.  So a-z is a block because 'a' uncanonicalizes to ['a',
      // 'A'] and the k'th letter uncanonicalizes to ['a' + k, 'A' + k].  Once
      // we've found the end point we look up its uncanonicalization and
      // produce a range for each element.  For instance for [c-f] we look up
      // ['z', 'Z'] and produce [c-f] and [C-F].  We then only add a range if
      // it is not already contained in the input, so [c-f] will be skipped but
      // [C-F] will be added.  If this range is not completely contained in a
      // block we do this for all the blocks covered by the range (handling
      // characters that is not in a block as a "singleton block").
      unibrow::uchar equivalents[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1333
      base::uc32 pos = bottom;
1334 1335 1336
      while (pos <= top) {
        int length =
            isolate->jsregexp_canonrange()->get(pos, '\0', equivalents);
1337
        base::uc32 block_end;
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
        if (length == 0) {
          block_end = pos;
        } else {
          DCHECK_EQ(1, length);
          block_end = equivalents[0];
        }
        int end = (block_end > top) ? top : block_end;
        length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0',
                                                         equivalents);
        for (int i = 0; i < length; i++) {
1348 1349 1350
          base::uc32 c = equivalents[i];
          base::uc32 range_from = c - (block_end - pos);
          base::uc32 range_to = c - (block_end - end);
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
          if (!(bottom <= range_from && range_to <= top)) {
            ranges->Add(CharacterRange::Range(range_from, range_to), zone);
          }
        }
        pos = end + 1;
      }
    }
  }
#endif  // V8_INTL_SUPPORT
}

bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
  DCHECK_NOT_NULL(ranges);
  int n = ranges->length();
  if (n <= 1) return true;
1366
  base::uc32 max = ranges->at(0).to();
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
  for (int i = 1; i < n; i++) {
    CharacterRange next_range = ranges->at(i);
    if (next_range.from() <= max + 1) return false;
    max = next_range.to();
  }
  return true;
}

ZoneList<CharacterRange>* CharacterSet::ranges(Zone* zone) {
  if (ranges_ == nullptr) {
1377
    ranges_ = zone->New<ZoneList<CharacterRange>>(2, zone);
1378 1379
    CharacterRange::AddClassEscape(standard_set_type_.value(), ranges_, false,
                                   zone);
1380 1381 1382 1383
  }
  return ranges_;
}

Jakob Gruber's avatar
Jakob Gruber committed
1384 1385
namespace {

1386 1387
// Move a number of elements in a zonelist to another position
// in the same list. Handles overlapping source and target areas.
Jakob Gruber's avatar
Jakob Gruber committed
1388
void MoveRanges(ZoneList<CharacterRange>* list, int from, int to, int count) {
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
  // Ranges are potentially overlapping.
  if (from < to) {
    for (int i = count - 1; i >= 0; i--) {
      list->at(to + i) = list->at(from + i);
    }
  } else {
    for (int i = 0; i < count; i++) {
      list->at(to + i) = list->at(from + i);
    }
  }
}

Jakob Gruber's avatar
Jakob Gruber committed
1401 1402
int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list, int count,
                               CharacterRange insert) {
1403 1404 1405 1406 1407
  // Inserts a range into list[0..count[, which must be sorted
  // by from value and non-overlapping and non-adjacent, using at most
  // list[0..count] for the result. Returns the number of resulting
  // canonicalized ranges. Inserting a range may collapse existing ranges into
  // fewer ranges, so the return value can be anything in the range 1..count+1.
1408 1409
  base::uc32 from = insert.from();
  base::uc32 to = insert.to();
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
  int start_pos = 0;
  int end_pos = count;
  for (int i = count - 1; i >= 0; i--) {
    CharacterRange current = list->at(i);
    if (current.from() > to + 1) {
      end_pos = i;
    } else if (current.to() + 1 < from) {
      start_pos = i + 1;
      break;
    }
  }

  // Inserted range overlaps, or is adjacent to, ranges at positions
  // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
  // not affected by the insertion.
  // If start_pos == end_pos, the range must be inserted before start_pos.
  // if start_pos < end_pos, the entire range from start_pos to end_pos
  // must be merged with the insert range.

  if (start_pos == end_pos) {
    // Insert between existing ranges at position start_pos.
    if (start_pos < count) {
      MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
    }
    list->at(start_pos) = insert;
    return count + 1;
  }
  if (start_pos + 1 == end_pos) {
    // Replace single existing range at position start_pos.
    CharacterRange to_replace = list->at(start_pos);
1440 1441
    int new_from = std::min(to_replace.from(), from);
    int new_to = std::max(to_replace.to(), to);
1442 1443 1444 1445 1446 1447
    list->at(start_pos) = CharacterRange::Range(new_from, new_to);
    return count;
  }
  // Replace a number of existing ranges from start_pos to end_pos - 1.
  // Move the remaining ranges down.

1448 1449
  int new_from = std::min(list->at(start_pos).from(), from);
  int new_to = std::max(list->at(end_pos - 1).to(), to);
1450 1451 1452 1453 1454 1455 1456
  if (end_pos < count) {
    MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
  }
  list->at(start_pos) = CharacterRange::Range(new_from, new_to);
  return count - (end_pos - start_pos) + 1;
}

Jakob Gruber's avatar
Jakob Gruber committed
1457 1458
}  // namespace

1459 1460 1461 1462 1463 1464 1465
void CharacterSet::Canonicalize() {
  // Special/default classes are always considered canonical. The result
  // of calling ranges() will be sorted.
  if (ranges_ == nullptr) return;
  CharacterRange::Canonicalize(ranges_);
}

1466
// static
1467 1468 1469 1470 1471
void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
  if (character_ranges->length() <= 1) return;
  // Check whether ranges are already canonical (increasing, non-overlapping,
  // non-adjacent).
  int n = character_ranges->length();
1472
  base::uc32 max = character_ranges->at(0).to();
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
  int i = 1;
  while (i < n) {
    CharacterRange current = character_ranges->at(i);
    if (current.from() <= max + 1) {
      break;
    }
    max = current.to();
    i++;
  }
  // Canonical until the i'th range. If that's all of them, we are done.
  if (i == n) return;

  // The ranges at index i and forward are not canonicalized. Make them so by
  // doing the equivalent of insertion sort (inserting each into the previous
  // list, in order).
  // Notice that inserting a range can reduce the number of ranges in the
  // result due to combining of adjacent and overlapping ranges.
  int read = i;           // Range to insert.
  int num_canonical = i;  // Length of canonicalized part of list.
  do {
    num_canonical = InsertRangeInCanonicalList(character_ranges, num_canonical,
                                               character_ranges->at(read));
    read++;
  } while (read < n);
  character_ranges->Rewind(num_canonical);

  DCHECK(CharacterRange::IsCanonical(character_ranges));
}

1502
// static
1503 1504 1505 1506 1507 1508
void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
                            ZoneList<CharacterRange>* negated_ranges,
                            Zone* zone) {
  DCHECK(CharacterRange::IsCanonical(ranges));
  DCHECK_EQ(0, negated_ranges->length());
  int range_count = ranges->length();
1509
  base::uc32 from = 0;
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
  int i = 0;
  if (range_count > 0 && ranges->at(0).from() == 0) {
    from = ranges->at(0).to() + 1;
    i = 1;
  }
  while (i < range_count) {
    CharacterRange range = ranges->at(i);
    negated_ranges->Add(CharacterRange::Range(from, range.from() - 1), zone);
    from = range.to() + 1;
    i++;
  }
1521 1522
  if (from < kMaxCodePoint) {
    negated_ranges->Add(CharacterRange::Range(from, kMaxCodePoint), zone);
1523 1524 1525
  }
}

1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
// static
void CharacterRange::ClampToOneByte(ZoneList<CharacterRange>* ranges) {
  DCHECK(IsCanonical(ranges));

  // Drop all ranges that don't contain one-byte code units, and clamp the last
  // range s.t. it likewise only contains one-byte code units. Note this relies
  // on `ranges` being canonicalized, i.e. sorted and non-overlapping.

  static constexpr base::uc32 max_char = String::kMaxOneByteCharCodeU;
  int n = ranges->length();
  for (; n > 0; n--) {
    CharacterRange& r = ranges->at(n - 1);
    if (r.from() <= max_char) {
      r.to_ = std::min(r.to_, max_char);
      break;
    }
  }

  ranges->Rewind(n);
}

Jakob Gruber's avatar
Jakob Gruber committed
1547 1548
namespace {

1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
// Scoped object to keep track of how much we unroll quantifier loops in the
// regexp graph generator.
class RegExpExpansionLimiter {
 public:
  static const int kMaxExpansionFactor = 6;
  RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
      : compiler_(compiler),
        saved_expansion_factor_(compiler->current_expansion_factor()),
        ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
    DCHECK_LT(0, factor);
    if (ok_to_expand_) {
      if (factor > kMaxExpansionFactor) {
        // Avoid integer overflow of the current expansion factor.
        ok_to_expand_ = false;
        compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
      } else {
        int new_factor = saved_expansion_factor_ * factor;
        ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
        compiler->set_current_expansion_factor(new_factor);
      }
    }
  }

  ~RegExpExpansionLimiter() {
    compiler_->set_current_expansion_factor(saved_expansion_factor_);
  }

  bool ok_to_expand() { return ok_to_expand_; }

 private:
  RegExpCompiler* compiler_;
  int saved_expansion_factor_;
  bool ok_to_expand_;

  DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
};

Jakob Gruber's avatar
Jakob Gruber committed
1586 1587
}  // namespace

1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
RegExpNode* RegExpQuantifier::ToNode(int min, int max, bool is_greedy,
                                     RegExpTree* body, RegExpCompiler* compiler,
                                     RegExpNode* on_success,
                                     bool not_at_start) {
  // x{f, t} becomes this:
  //
  //             (r++)<-.
  //               |     `
  //               |     (x)
  //               v     ^
  //      (r=0)-->(?)---/ [if r < t]
  //               |
  //   [if r >= f] \----> ...
  //

  // 15.10.2.5 RepeatMatcher algorithm.
  // The parser has already eliminated the case where max is 0.  In the case
  // where max_match is zero the parser has removed the quantifier if min was
  // > 0 and removed the atom if min was 0.  See AddQuantifierToAtom.

  // If we know that we cannot match zero length then things are a little
  // simpler since we don't need to make the special zero length match check
  // from step 2.1.  If the min and max are small we can unroll a little in
  // this case.
  static const int kMaxUnrolledMinMatches = 3;  // Unroll (foo)+ and (foo){3,}
  static const int kMaxUnrolledMaxMatches = 3;  // Unroll (foo)? and (foo){x,3}
  if (max == 0) return on_success;  // This can happen due to recursion.
  bool body_can_be_empty = (body->min_match() == 0);
  int body_start_reg = RegExpCompiler::kNoRegister;
  Interval capture_registers = body->CaptureRegisters();
  bool needs_capture_clearing = !capture_registers.is_empty();
  Zone* zone = compiler->zone();

  if (body_can_be_empty) {
    body_start_reg = compiler->AllocateRegister();
  } else if (compiler->optimize() && !needs_capture_clearing) {
    // Only unroll if there are no captures and the body can't be
    // empty.
    {
      RegExpExpansionLimiter limiter(compiler, min + ((max != min) ? 1 : 0));
      if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
        int new_max = (max == kInfinity) ? max : max - min;
        // Recurse once to get the loop or optional matches after the fixed
        // ones.
        RegExpNode* answer =
            ToNode(0, new_max, is_greedy, body, compiler, on_success, true);
        // Unroll the forced matches from 0 to min.  This can cause chains of
        // TextNodes (which the parser does not generate).  These should be
        // combined if it turns out they hinder good code generation.
        for (int i = 0; i < min; i++) {
          answer = body->ToNode(compiler, answer);
        }
        return answer;
      }
    }
    if (max <= kMaxUnrolledMaxMatches && min == 0) {
      DCHECK_LT(0, max);  // Due to the 'if' above.
      RegExpExpansionLimiter limiter(compiler, max);
      if (limiter.ok_to_expand()) {
        // Unroll the optional matches up to max.
        RegExpNode* answer = on_success;
        for (int i = 0; i < max; i++) {
1650
          ChoiceNode* alternation = zone->New<ChoiceNode>(2, zone);
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
          if (is_greedy) {
            alternation->AddAlternative(
                GuardedAlternative(body->ToNode(compiler, answer)));
            alternation->AddAlternative(GuardedAlternative(on_success));
          } else {
            alternation->AddAlternative(GuardedAlternative(on_success));
            alternation->AddAlternative(
                GuardedAlternative(body->ToNode(compiler, answer)));
          }
          answer = alternation;
          if (not_at_start && !compiler->read_backward()) {
            alternation->set_not_at_start();
          }
        }
        return answer;
      }
    }
  }
  bool has_min = min > 0;
  bool has_max = max < RegExpTree::kInfinity;
  bool needs_counter = has_min || has_max;
  int reg_ctr = needs_counter ? compiler->AllocateRegister()
                              : RegExpCompiler::kNoRegister;
1674
  LoopChoiceNode* center = zone->New<LoopChoiceNode>(
1675
      body->min_match() == 0, compiler->read_backward(), min, zone);
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
  if (not_at_start && !compiler->read_backward()) center->set_not_at_start();
  RegExpNode* loop_return =
      needs_counter ? static_cast<RegExpNode*>(
                          ActionNode::IncrementRegister(reg_ctr, center))
                    : static_cast<RegExpNode*>(center);
  if (body_can_be_empty) {
    // If the body can be empty we need to check if it was and then
    // backtrack.
    loop_return =
        ActionNode::EmptyMatchCheck(body_start_reg, reg_ctr, min, loop_return);
  }
  RegExpNode* body_node = body->ToNode(compiler, loop_return);
  if (body_can_be_empty) {
    // If the body can be empty we need to store the start position
    // so we can bail out if it was empty.
    body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
  }
  if (needs_capture_clearing) {
    // Before entering the body of this loop we need to clear captures.
    body_node = ActionNode::ClearCaptures(capture_registers, body_node);
  }
  GuardedAlternative body_alt(body_node);
  if (has_max) {
1699
    Guard* body_guard = zone->New<Guard>(reg_ctr, Guard::LT, max);
1700 1701 1702 1703
    body_alt.AddGuard(body_guard, zone);
  }
  GuardedAlternative rest_alt(on_success);
  if (has_min) {
1704
    Guard* rest_guard = compiler->zone()->New<Guard>(reg_ctr, Guard::GEQ, min);
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
    rest_alt.AddGuard(rest_guard, zone);
  }
  if (is_greedy) {
    center->AddLoopAlternative(body_alt);
    center->AddContinueAlternative(rest_alt);
  } else {
    center->AddContinueAlternative(rest_alt);
    center->AddLoopAlternative(body_alt);
  }
  if (needs_counter) {
1715
    return ActionNode::SetRegisterForLoop(reg_ctr, 0, center);
1716 1717 1718 1719 1720 1721 1722
  } else {
    return center;
  }
}

}  // namespace internal
}  // namespace v8