regexp-parser.cc 75.9 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 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-parser.h"

7
#include "src/base/small-vector.h"
8
#include "src/execution/isolate.h"
9
#include "src/objects/string-inl.h"
10
#include "src/regexp/property-sequences.h"
11
#include "src/regexp/regexp-ast.h"
12
#include "src/regexp/regexp-macro-assembler.h"
13
#include "src/regexp/regexp.h"
14
#include "src/strings/char-predicates-inl.h"
15 16
#include "src/utils/ostreams.h"
#include "src/utils/utils.h"
17
#include "src/zone/zone-allocator.h"
18
#include "src/zone/zone-list-inl.h"
19

20
#ifdef V8_INTL_SUPPORT
21
#include "unicode/uniset.h"
22
#endif  // V8_INTL_SUPPORT
23

24 25 26
namespace v8 {
namespace internal {

27 28
namespace {

29 30 31 32 33 34 35
// Whether we're currently inside the ClassEscape production
// (tc39.es/ecma262/#prod-annexB-CharacterEscape).
enum class InClassEscapeState {
  kInClass,
  kNotInClass,
};

36
// Accumulates RegExp atoms and assertions into lists of terms and alternatives.
37
class RegExpBuilder {
38
 public:
39 40 41
  RegExpBuilder(Zone* zone, RegExpFlags flags)
      : zone_(zone),
        flags_(flags),
42 43 44
        terms_(ZoneAllocator<RegExpTree*>{zone}),
        text_(ZoneAllocator<RegExpTree*>{zone}),
        alternatives_(ZoneAllocator<RegExpTree*>{zone}) {}
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
  void AddCharacter(base::uc16 character);
  void AddUnicodeCharacter(base::uc32 character);
  void AddEscapedUnicodeCharacter(base::uc32 character);
  // "Adds" an empty expression. Does nothing except consume a
  // following quantifier
  void AddEmpty();
  void AddCharacterClass(RegExpCharacterClass* cc);
  void AddCharacterClassForDesugaring(base::uc32 c);
  void AddAtom(RegExpTree* tree);
  void AddTerm(RegExpTree* tree);
  void AddAssertion(RegExpTree* tree);
  void NewAlternative();  // '|'
  bool AddQuantifierToAtom(int min, int max,
                           RegExpQuantifier::QuantifierType type);
  void FlushText();
  RegExpTree* ToRegExp();
61
  RegExpFlags flags() const { return flags_; }
62

63 64 65
  bool ignore_case() const { return IsIgnoreCase(flags_); }
  bool multiline() const { return IsMultiline(flags_); }
  bool dotall() const { return IsDotAll(flags_); }
66 67 68 69 70 71 72 73 74 75 76

 private:
  static const base::uc16 kNoPendingSurrogate = 0;
  void AddLeadSurrogate(base::uc16 lead_surrogate);
  void AddTrailSurrogate(base::uc16 trail_surrogate);
  void FlushPendingSurrogate();
  void FlushCharacters();
  void FlushTerms();
  bool NeedsDesugaringForUnicode(RegExpCharacterClass* cc);
  bool NeedsDesugaringForIgnoreCase(base::uc32 c);
  Zone* zone() const { return zone_; }
77
  bool unicode() const { return IsUnicode(flags_); }
78

79
  Zone* const zone_;
80
  bool pending_empty_ = false;
81
  const RegExpFlags flags_;
82 83
  ZoneList<base::uc16>* characters_ = nullptr;
  base::uc16 pending_surrogate_ = kNoPendingSurrogate;
84 85 86 87 88 89

  using SmallRegExpTreeVector =
      base::SmallVector<RegExpTree*, 8, ZoneAllocator<RegExpTree*>>;
  SmallRegExpTreeVector terms_;
  SmallRegExpTreeVector text_;
  SmallRegExpTreeVector alternatives_;
90
#ifdef DEBUG
91 92 93 94 95 96 97
  enum {
    ADD_NONE,
    ADD_CHAR,
    ADD_TERM,
    ADD_ASSERT,
    ADD_ATOM
  } last_added_ = ADD_NONE;
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
#define LAST(x) last_added_ = x;
#else
#define LAST(x)
#endif
};

enum SubexpressionType {
  INITIAL,
  CAPTURE,  // All positive values represent captures.
  POSITIVE_LOOKAROUND,
  NEGATIVE_LOOKAROUND,
  GROUPING
};

class RegExpParserState : public ZoneObject {
 public:
  // Push a state on the stack.
  RegExpParserState(RegExpParserState* previous_state,
                    SubexpressionType group_type,
                    RegExpLookaround::Type lookaround_type,
                    int disjunction_capture_index,
                    const ZoneVector<base::uc16>* capture_name,
120
                    RegExpFlags flags, Zone* zone)
121
      : previous_state_(previous_state),
122
        builder_(zone, flags),
123 124 125 126 127 128 129 130
        group_type_(group_type),
        lookaround_type_(lookaround_type),
        disjunction_capture_index_(disjunction_capture_index),
        capture_name_(capture_name) {}
  // Parser state of containing expression, if any.
  RegExpParserState* previous_state() const { return previous_state_; }
  bool IsSubexpression() { return previous_state_ != nullptr; }
  // RegExpBuilder building this regexp's AST.
131
  RegExpBuilder* builder() { return &builder_; }
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
  // Type of regexp being parsed (parenthesized group or entire regexp).
  SubexpressionType group_type() const { return group_type_; }
  // Lookahead or Lookbehind.
  RegExpLookaround::Type lookaround_type() const { return lookaround_type_; }
  // Index in captures array of first capture in this sub-expression, if any.
  // Also the capture index of this sub-expression itself, if group_type
  // is CAPTURE.
  int capture_index() const { return disjunction_capture_index_; }
  // The name of the current sub-expression, if group_type is CAPTURE. Only
  // used for named captures.
  const ZoneVector<base::uc16>* capture_name() const { return capture_name_; }

  bool IsNamedCapture() const { return capture_name_ != nullptr; }

  // Check whether the parser is inside a capture group with the given index.
  bool IsInsideCaptureGroup(int index) const {
    for (const RegExpParserState* s = this; s != nullptr;
         s = s->previous_state()) {
      if (s->group_type() != CAPTURE) continue;
      // Return true if we found the matching capture index.
      if (index == s->capture_index()) return true;
      // Abort if index is larger than what has been parsed up till this state.
      if (index > s->capture_index()) return false;
    }
    return false;
  }

  // Check whether the parser is inside a capture group with the given name.
  bool IsInsideCaptureGroup(const ZoneVector<base::uc16>* name) const {
    DCHECK_NOT_NULL(name);
    for (const RegExpParserState* s = this; s != nullptr;
         s = s->previous_state()) {
      if (s->capture_name() == nullptr) continue;
      if (*s->capture_name() == *name) return true;
    }
    return false;
  }

 private:
  // Linked list implementation of stack of states.
  RegExpParserState* const previous_state_;
  // Builder for the stored disjunction.
174
  RegExpBuilder builder_;
175 176 177 178 179 180 181 182 183 184 185 186 187
  // Stored disjunction type (capture, look-ahead or grouping), if any.
  const SubexpressionType group_type_;
  // Stored read direction.
  const RegExpLookaround::Type lookaround_type_;
  // Stored disjunction's capture index (if any).
  const int disjunction_capture_index_;
  // Stored capture name (if any).
  const ZoneVector<base::uc16>* const capture_name_;
};

template <class CharT>
class RegExpParserImpl final {
 private:
188
  RegExpParserImpl(const CharT* input, int input_length, RegExpFlags flags,
189
                   uintptr_t stack_limit, Zone* zone,
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
                   const DisallowGarbageCollection& no_gc);

  bool Parse(RegExpCompileData* result);

  RegExpTree* ParsePattern();
  RegExpTree* ParseDisjunction();
  RegExpTree* ParseGroup();

  // Parses a {...,...} quantifier and stores the range in the given
  // out parameters.
  bool ParseIntervalQuantifier(int* min_out, int* max_out);

  // Checks whether the following is a length-digit hexadecimal number,
  // and sets the value if it is.
  bool ParseHexEscape(int length, base::uc32* value);
  bool ParseUnicodeEscape(base::uc32* value);
  bool ParseUnlimitedLengthHexNumber(int max_value, base::uc32* value);

  bool ParsePropertyClassName(ZoneVector<char>* name_1,
                              ZoneVector<char>* name_2);
  bool AddPropertyClassRange(ZoneList<CharacterRange>* add_to, bool negate,
                             const ZoneVector<char>& name_1,
                             const ZoneVector<char>& name_2);

  RegExpTree* ParseCharacterClass(const RegExpBuilder* state);

  base::uc32 ParseOctalLiteral();

  // Tries to parse the input as a back reference.  If successful it
  // stores the result in the output parameter and returns true.  If
  // it fails it will push back the characters read so the same characters
  // can be reparsed.
  bool ParseBackReferenceIndex(int* index_out);

  // Parse inside a class. Either add escaped class to the range, or return
  // false and pass parsed single character through |char_out|.
  void ParseClassEscape(ZoneList<CharacterRange>* ranges, Zone* zone,
                        bool add_unicode_case_equivalents, base::uc32* char_out,
                        bool* is_class_escape);
229 230 231 232 233 234 235 236 237
  // Returns true iff parsing was successful.
  bool TryParseCharacterClassEscape(base::uc32 next,
                                    InClassEscapeState in_class_escape_state,
                                    ZoneList<CharacterRange>* ranges,
                                    Zone* zone,
                                    bool add_unicode_case_equivalents);
  // Parses and returns a single escaped character.
  base::uc32 ParseCharacterEscape(InClassEscapeState in_class_escape_state,
                                  bool* is_escaped_unicode_character);
238 239 240 241

  RegExpTree* ReportError(RegExpError error);
  void Advance();
  void Advance(int dist);
242
  void RewindByOneCodepoint();  // Rewinds to before the previous Advance().
243 244 245 246
  void Reset(int pos);

  // Reports whether the pattern might be used as a literal search string.
  // Only use if the result of the parse is a single atom node.
247 248
  bool simple() const { return simple_; }
  bool contains_anchor() const { return contains_anchor_; }
249
  void set_contains_anchor() { contains_anchor_ = true; }
250 251 252 253
  int captures_started() const { return captures_started_; }
  int position() const { return next_pos_ - 1; }
  bool failed() const { return failed_; }
  bool unicode() const { return IsUnicode(top_level_flags_) || force_unicode_; }
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284

  static bool IsSyntaxCharacterOrSlash(base::uc32 c);

  static const base::uc32 kEndMarker = (1 << 21);

 private:
  // Return the 1-indexed RegExpCapture object, allocate if necessary.
  RegExpCapture* GetCapture(int index);

  // Creates a new named capture at the specified index. Must be called exactly
  // once for each named capture. Fails if a capture with the same name is
  // encountered.
  bool CreateNamedCaptureAtIndex(const ZoneVector<base::uc16>* name, int index);

  // Parses the name of a capture group (?<name>pattern). The name must adhere
  // to IdentifierName in the ECMAScript standard.
  const ZoneVector<base::uc16>* ParseCaptureGroupName();

  bool ParseNamedBackReference(RegExpBuilder* builder,
                               RegExpParserState* state);
  RegExpParserState* ParseOpenParenthesis(RegExpParserState* state);

  // After the initial parsing pass, patch corresponding RegExpCapture objects
  // into all RegExpBackReferences. This is done after initial parsing in order
  // to avoid complicating cases in which references comes before the capture.
  void PatchNamedBackReferences();

  ZoneVector<RegExpCapture*>* GetNamedCaptures() const;

  // Returns true iff the pattern contains named captures. May call
  // ScanForCaptures to look ahead at the remaining pattern.
285
  bool HasNamedCaptures(InClassEscapeState in_class_escape_state);
286 287 288

  Zone* zone() const { return zone_; }

289 290 291
  base::uc32 current() const { return current_; }
  bool has_more() const { return has_more_; }
  bool has_next() const { return next_pos_ < input_length(); }
292 293 294 295 296 297 298 299
  base::uc32 Next();
  template <bool update_position>
  base::uc32 ReadNext();
  CharT InputAt(int index) const {
    DCHECK(0 <= index && index < input_length());
    return input_[index];
  }
  int input_length() const { return input_length_; }
300
  void ScanForCaptures(InClassEscapeState in_class_escape_state);
301 302 303 304 305 306 307 308 309

  struct RegExpCaptureNameLess {
    bool operator()(const RegExpCapture* lhs, const RegExpCapture* rhs) const {
      DCHECK_NOT_NULL(lhs);
      DCHECK_NOT_NULL(rhs);
      return *lhs->name() < *rhs->name();
    }
  };

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  class ForceUnicodeScope final {
   public:
    explicit ForceUnicodeScope(RegExpParserImpl<CharT>* parser)
        : parser_(parser) {
      DCHECK(!parser_->force_unicode_);
      parser_->force_unicode_ = true;
    }
    ~ForceUnicodeScope() {
      DCHECK(parser_->force_unicode_);
      parser_->force_unicode_ = false;
    }

   private:
    RegExpParserImpl<CharT>* const parser_;
  };

326 327 328 329 330 331 332 333 334 335
  const DisallowGarbageCollection no_gc_;
  Zone* const zone_;
  RegExpError error_ = RegExpError::kNone;
  int error_pos_ = 0;
  ZoneList<RegExpCapture*>* captures_;
  ZoneSet<RegExpCapture*, RegExpCaptureNameLess>* named_captures_;
  ZoneList<RegExpBackReference*>* named_back_references_;
  const CharT* const input_;
  const int input_length_;
  base::uc32 current_;
336
  const RegExpFlags top_level_flags_;
337
  bool force_unicode_ = false;  // Force parser to act as if unicode were set.
338 339 340 341 342 343 344 345 346
  int next_pos_;
  int captures_started_;
  int capture_count_;  // Only valid after we have scanned for captures.
  bool has_more_;
  bool simple_;
  bool contains_anchor_;
  bool is_scanned_for_captures_;
  bool has_named_captures_;  // Only valid after we have scanned for captures.
  bool failed_;
347
  const uintptr_t stack_limit_;
348 349 350

  friend bool RegExpParser::ParseRegExpFromHeapString(Isolate*, Zone*,
                                                      Handle<String>,
351
                                                      RegExpFlags,
352
                                                      RegExpCompileData*);
353 354 355
  friend bool RegExpParser::VerifyRegExpSyntax<CharT>(
      Zone*, uintptr_t, const CharT*, int, RegExpFlags, RegExpCompileData*,
      const DisallowGarbageCollection&);
356 357 358 359
};

template <class CharT>
RegExpParserImpl<CharT>::RegExpParserImpl(
360 361 362
    const CharT* input, int input_length, RegExpFlags flags,
    uintptr_t stack_limit, Zone* zone, const DisallowGarbageCollection& no_gc)
    : zone_(zone),
363 364 365
      captures_(nullptr),
      named_captures_(nullptr),
      named_back_references_(nullptr),
366 367
      input_(input),
      input_length_(input_length),
368
      current_(kEndMarker),
369
      top_level_flags_(flags),
370 371 372 373 374 375 376
      next_pos_(0),
      captures_started_(0),
      capture_count_(0),
      has_more_(true),
      simple_(false),
      contains_anchor_(false),
      is_scanned_for_captures_(false),
377
      has_named_captures_(false),
378 379
      failed_(false),
      stack_limit_(stack_limit) {
380 381 382
  Advance();
}

383 384 385 386 387 388 389 390 391 392 393 394
template <>
template <bool update_position>
inline base::uc32 RegExpParserImpl<uint8_t>::ReadNext() {
  int position = next_pos_;
  base::uc16 c0 = InputAt(position);
  position++;
  DCHECK(!unibrow::Utf16::IsLeadSurrogate(c0));
  if (update_position) next_pos_ = position;
  return c0;
}

template <>
395
template <bool update_position>
396
inline base::uc32 RegExpParserImpl<base::uc16>::ReadNext() {
397
  int position = next_pos_;
398 399
  base::uc16 c0 = InputAt(position);
  base::uc32 result = c0;
400
  position++;
401
  // Read the whole surrogate pair in case of unicode flag, if possible.
402 403 404
  if (unicode() && position < input_length() &&
      unibrow::Utf16::IsLeadSurrogate(c0)) {
    base::uc16 c1 = InputAt(position);
405
    if (unibrow::Utf16::IsTrailSurrogate(c1)) {
406
      result = unibrow::Utf16::CombineSurrogatePair(c0, c1);
407 408 409 410
      position++;
    }
  }
  if (update_position) next_pos_ = position;
411
  return result;
412 413
}

414 415
template <class CharT>
base::uc32 RegExpParserImpl<CharT>::Next() {
416
  if (has_next()) {
417
    return ReadNext<false>();
418 419 420 421 422
  } else {
    return kEndMarker;
  }
}

423 424
template <class CharT>
void RegExpParserImpl<CharT>::Advance() {
425
  if (has_next()) {
426
    if (GetCurrentStackPosition() < stack_limit_) {
427
      if (FLAG_correctness_fuzzer_suppressions) {
428 429
        FATAL("Aborting on stack overflow");
      }
430
      ReportError(RegExpError::kStackOverflow);
431
    } else {
432
      current_ = ReadNext<true>();
433 434 435 436 437
    }
  } else {
    current_ = kEndMarker;
    // Advance so that position() points to 1-after-the-last-character. This is
    // important so that Reset() to this position works correctly.
438
    next_pos_ = input_length() + 1;
439 440 441 442
    has_more_ = false;
  }
}

443 444 445 446 447 448 449 450 451 452 453
template <class CharT>
void RegExpParserImpl<CharT>::RewindByOneCodepoint() {
  if (current() == kEndMarker) return;
  // Rewinds by one code point, i.e.: two code units if `current` is outside
  // the basic multilingual plane (= composed of a lead and trail surrogate),
  // or one code unit otherwise.
  const int rewind_by =
      current() > unibrow::Utf16::kMaxNonSurrogateCharCode ? -2 : -1;
  Advance(rewind_by);  // Undo the last Advance.
}

454 455
template <class CharT>
void RegExpParserImpl<CharT>::Reset(int pos) {
456
  next_pos_ = pos;
457
  has_more_ = (pos < input_length());
458 459 460
  Advance();
}

461 462
template <class CharT>
void RegExpParserImpl<CharT>::Advance(int dist) {
463
  next_pos_ += dist - 1;
464
  Advance();
465 466
}

467 468
template <class CharT>
bool RegExpParserImpl<CharT>::IsSyntaxCharacterOrSlash(base::uc32 c) {
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  switch (c) {
    case '^':
    case '$':
    case '\\':
    case '.':
    case '*':
    case '+':
    case '?':
    case '(':
    case ')':
    case '[':
    case ']':
    case '{':
    case '}':
    case '|':
    case '/':
      return true;
    default:
      break;
  }
  return false;
490 491
}

492 493
template <class CharT>
RegExpTree* RegExpParserImpl<CharT>::ReportError(RegExpError error) {
494
  if (failed_) return nullptr;  // Do not overwrite any existing error.
495
  failed_ = true;
496 497 498
  error_ = error;
  error_pos_ = position();
  // Zip to the end to make sure no more input is read.
499
  current_ = kEndMarker;
500
  next_pos_ = input_length();
501
  return nullptr;
502 503
}

504 505
#define CHECK_FAILED /**/);    \
  if (failed_) return nullptr; \
506 507 508 509
  ((void)0

// Pattern ::
//   Disjunction
510 511
template <class CharT>
RegExpTree* RegExpParserImpl<CharT>::ParsePattern() {
512
  RegExpTree* result = ParseDisjunction(CHECK_FAILED);
513
  PatchNamedBackReferences(CHECK_FAILED);
514 515 516
  DCHECK(!has_more());
  // If the result of parsing is a literal string atom, and it has the
  // same length as the input, then the atom is identical to the input.
517
  if (result->IsAtom() && result->AsAtom()->length() == input_length()) {
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    simple_ = true;
  }
  return result;
}

// Disjunction ::
//   Alternative
//   Alternative | Disjunction
// Alternative ::
//   [empty]
//   Term Alternative
// Term ::
//   Assertion
//   Atom
//   Atom Quantifier
533 534
template <class CharT>
RegExpTree* RegExpParserImpl<CharT>::ParseDisjunction() {
535
  // Used to store current state while parsing subexpressions.
536
  RegExpParserState initial_state(nullptr, INITIAL, RegExpLookaround::LOOKAHEAD,
537
                                  0, nullptr, top_level_flags_, zone());
538 539 540 541 542 543
  RegExpParserState* state = &initial_state;
  // Cache the builder in a local variable for quick access.
  RegExpBuilder* builder = initial_state.builder();
  while (true) {
    switch (current()) {
      case kEndMarker:
544
        if (failed()) return nullptr;  // E.g. the initial Advance failed.
545 546
        if (state->IsSubexpression()) {
          // Inside a parenthesized group when hitting end of input.
547
          return ReportError(RegExpError::kUnterminatedGroup);
548 549 550 551 552 553
        }
        DCHECK_EQ(INITIAL, state->group_type());
        // Parsing completed successfully.
        return builder->ToRegExp();
      case ')': {
        if (!state->IsSubexpression()) {
554
          return ReportError(RegExpError::kUnmatchedParen);
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
        }
        DCHECK_NE(INITIAL, state->group_type());

        Advance();
        // End disjunction parsing and convert builder content to new single
        // regexp atom.
        RegExpTree* body = builder->ToRegExp();

        int end_capture_index = captures_started();

        int capture_index = state->capture_index();
        SubexpressionType group_type = state->group_type();

        // Build result of subexpression.
        if (group_type == CAPTURE) {
570 571 572 573
          if (state->IsNamedCapture()) {
            CreateNamedCaptureAtIndex(state->capture_name(),
                                      capture_index CHECK_FAILED);
          }
574 575 576
          RegExpCapture* capture = GetCapture(capture_index);
          capture->set_body(body);
          body = capture;
577
        } else if (group_type == GROUPING) {
578
          body = zone()->template New<RegExpGroup>(body);
579
        } else {
580 581 582
          DCHECK(group_type == POSITIVE_LOOKAROUND ||
                 group_type == NEGATIVE_LOOKAROUND);
          bool is_positive = (group_type == POSITIVE_LOOKAROUND);
583
          body = zone()->template New<RegExpLookaround>(
584 585 586 587 588 589 590 591 592
              body, is_positive, end_capture_index - capture_index,
              capture_index, state->lookaround_type());
        }

        // Restore previous state.
        state = state->previous_state();
        builder = state->builder();

        builder->AddAtom(body);
593
        // For compatibility with JSC and ES3, we allow quantifiers after
594 595 596 597 598 599 600 601 602 603 604
        // lookaheads, and break in all cases.
        break;
      }
      case '|': {
        Advance();
        builder->NewAlternative();
        continue;
      }
      case '*':
      case '+':
      case '?':
605
        return ReportError(RegExpError::kNothingToRepeat);
606 607
      case '^': {
        Advance();
608
        builder->AddAssertion(zone()->template New<RegExpAssertion>(
609 610
            builder->multiline() ? RegExpAssertion::Type::START_OF_LINE
                                 : RegExpAssertion::Type::START_OF_INPUT));
611
        set_contains_anchor();
612 613 614 615
        continue;
      }
      case '$': {
        Advance();
616 617 618
        RegExpAssertion::Type assertion_type =
            builder->multiline() ? RegExpAssertion::Type::END_OF_LINE
                                 : RegExpAssertion::Type::END_OF_INPUT;
619 620
        builder->AddAssertion(
            zone()->template New<RegExpAssertion>(assertion_type));
621 622 623 624 625
        continue;
      }
      case '.': {
        Advance();
        ZoneList<CharacterRange>* ranges =
626
            zone()->template New<ZoneList<CharacterRange>>(2, zone());
627

628
        if (builder->dotall()) {
629
          // Everything.
630 631
          CharacterRange::AddClassEscape(StandardCharacterSet::kEverything,
                                         ranges, false, zone());
632
        } else {
633 634 635
          // Everything except \x0A, \x0D, \u2028 and \u2029.
          CharacterRange::AddClassEscape(
              StandardCharacterSet::kNotLineTerminator, ranges, false, zone());
636 637
        }

638
        RegExpCharacterClass* cc =
639
            zone()->template New<RegExpCharacterClass>(zone(), ranges);
640
        builder->AddCharacterClass(cc);
641 642 643
        break;
      }
      case '(': {
644
        state = ParseOpenParenthesis(state CHECK_FAILED);
645 646 647 648
        builder = state->builder();
        continue;
      }
      case '[': {
649
        RegExpTree* cc = ParseCharacterClass(builder CHECK_FAILED);
650
        builder->AddCharacterClass(cc->AsCharacterClass());
651 652 653 654 655 656 657
        break;
      }
      // Atom ::
      //   \ AtomEscape
      case '\\':
        switch (Next()) {
          case kEndMarker:
658
            return ReportError(RegExpError::kEscapeAtEndOfPattern);
659
          // AtomEscape ::
660 661 662 663
          //   [+UnicodeMode] DecimalEscape
          //   [~UnicodeMode] DecimalEscape but only if the CapturingGroupNumber
          //                  of DecimalEscape is ≤ NcapturingParens
          //   CharacterEscape (some cases of this mixed in too)
664
          //
665 666 667 668 669 670 671
          // TODO(jgruber): It may make sense to disentangle all the different
          // cases and make the structure mirror the spec, e.g. for AtomEscape:
          //
          //  if (TryParseDecimalEscape(...)) return;
          //  if (TryParseCharacterClassEscape(...)) return;
          //  if (TryParseCharacterEscape(...)) return;
          //  if (TryParseGroupName(...)) return;
672 673 674 675 676 677 678 679 680 681
          case '1':
          case '2':
          case '3':
          case '4':
          case '5':
          case '6':
          case '7':
          case '8':
          case '9': {
            int index = 0;
682 683
            const bool is_backref =
                ParseBackReferenceIndex(&index CHECK_FAILED);
684
            if (is_backref) {
685 686 687 688 689 690 691 692 693
              if (state->IsInsideCaptureGroup(index)) {
                // The back reference is inside the capture group it refers to.
                // Nothing can possibly have been captured yet, so we use empty
                // instead. This ensures that, when checking a back reference,
                // the capture registers of the referenced capture are either
                // both set or both cleared.
                builder->AddEmpty();
              } else {
                RegExpCapture* capture = GetCapture(index);
694
                RegExpTree* atom = zone()->template New<RegExpBackReference>(
695
                    capture, builder->flags());
696 697 698 699
                builder->AddAtom(atom);
              }
              break;
            }
700 701 702
            // With /u, no identity escapes except for syntax characters
            // are allowed. Otherwise, all identity escapes are allowed.
            if (unicode()) {
703
              return ReportError(RegExpError::kInvalidEscape);
704
            }
705
            base::uc32 first_digit = Next();
706
            if (first_digit == '8' || first_digit == '9') {
707 708
              builder->AddCharacter(first_digit);
              Advance(2);
709 710
              break;
            }
711
            V8_FALLTHROUGH;
712 713 714
          }
          case '0': {
            Advance();
715 716
            if (unicode() && Next() >= '0' && Next() <= '9') {
              // With /u, decimal escape with leading 0 are not parsed as octal.
717
              return ReportError(RegExpError::kInvalidDecimalEscape);
718
            }
719
            base::uc32 octal = ParseOctalLiteral();
720 721 722
            builder->AddCharacter(octal);
            break;
          }
723
          case 'b':
724
            Advance(2);
725
            builder->AddAssertion(zone()->template New<RegExpAssertion>(
726
                RegExpAssertion::Type::BOUNDARY));
727 728
            continue;
          case 'B':
729
            Advance(2);
730
            builder->AddAssertion(zone()->template New<RegExpAssertion>(
731
                RegExpAssertion::Type::NON_BOUNDARY));
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
            continue;
          // AtomEscape ::
          //   CharacterClassEscape
          case 'd':
          case 'D':
          case 's':
          case 'S':
          case 'w':
          case 'W':
          case 'p':
          case 'P': {
            base::uc32 next = Next();
            ZoneList<CharacterRange>* ranges =
                zone()->template New<ZoneList<CharacterRange>>(2, zone());
            bool add_unicode_case_equivalents =
                unicode() && builder->ignore_case();
            bool parsed_character_class_escape = TryParseCharacterClassEscape(
                next, InClassEscapeState::kNotInClass, ranges, zone(),
                add_unicode_case_equivalents CHECK_FAILED);

            if (parsed_character_class_escape) {
              RegExpCharacterClass* cc =
                  zone()->template New<RegExpCharacterClass>(zone(), ranges);
              builder->AddCharacterClass(cc);
756
            } else {
757
              CHECK(!unicode());
758
              Advance(2);
759
              builder->AddCharacter(next);  // IdentityEscape.
760 761 762
            }
            break;
          }
763 764 765
          // AtomEscape ::
          //   k GroupName
          case 'k': {
766 767
            // Either an identity escape or a named back-reference.  The two
            // interpretations are mutually exclusive: '\k' is interpreted as
768
            // an identity escape for non-Unicode patterns without named
769 770
            // capture groups, and as the beginning of a named back-reference
            // in all other cases.
771 772
            const bool has_named_captures =
                HasNamedCaptures(InClassEscapeState::kNotInClass CHECK_FAILED);
773
            if (unicode() || has_named_captures) {
774 775 776 777
              Advance(2);
              ParseNamedBackReference(builder, state CHECK_FAILED);
              break;
            }
778
          }
779
            V8_FALLTHROUGH;
780 781 782 783 784 785 786 787 788
          // AtomEscape ::
          //   CharacterEscape
          default: {
            bool is_escaped_unicode_character = false;
            base::uc32 c = ParseCharacterEscape(
                InClassEscapeState::kNotInClass,
                &is_escaped_unicode_character CHECK_FAILED);
            if (is_escaped_unicode_character) {
              builder->AddEscapedUnicodeCharacter(c);
789
            } else {
790
              builder->AddCharacter(c);
791 792
            }
            break;
793
          }
794 795 796 797
        }
        break;
      case '{': {
        int dummy;
798
        bool parsed = ParseIntervalQuantifier(&dummy, &dummy CHECK_FAILED);
799
        if (parsed) return ReportError(RegExpError::kNothingToRepeat);
800
        V8_FALLTHROUGH;
801
      }
802 803 804
      case '}':
      case ']':
        if (unicode()) {
805
          return ReportError(RegExpError::kLoneQuantifierBrackets);
806
        }
807
        V8_FALLTHROUGH;
808
      default:
809
        builder->AddUnicodeCharacter(current());
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
        Advance();
        break;
    }  // end switch(current())

    int min;
    int max;
    switch (current()) {
      // QuantifierPrefix ::
      //   *
      //   +
      //   ?
      //   {
      case '*':
        min = 0;
        max = RegExpTree::kInfinity;
        Advance();
        break;
      case '+':
        min = 1;
        max = RegExpTree::kInfinity;
        Advance();
        break;
      case '?':
        min = 0;
        max = 1;
        Advance();
        break;
      case '{':
        if (ParseIntervalQuantifier(&min, &max)) {
          if (max < min) {
840
            return ReportError(RegExpError::kRangeOutOfOrder);
841 842
          }
          break;
843 844
        } else if (unicode()) {
          // With /u, incomplete quantifiers are not allowed.
845
          return ReportError(RegExpError::kIncompleteQuantifier);
846
        }
847
        continue;
848 849 850 851 852 853 854 855 856 857 858 859
      default:
        continue;
    }
    RegExpQuantifier::QuantifierType quantifier_type = RegExpQuantifier::GREEDY;
    if (current() == '?') {
      quantifier_type = RegExpQuantifier::NON_GREEDY;
      Advance();
    } else if (FLAG_regexp_possessive_quantifier && current() == '+') {
      // FLAG_regexp_possessive_quantifier is a debug-only flag.
      quantifier_type = RegExpQuantifier::POSSESSIVE;
      Advance();
    }
860
    if (!builder->AddQuantifierToAtom(min, max, quantifier_type)) {
861
      return ReportError(RegExpError::kInvalidQuantifier);
862
    }
863 864 865
  }
}

866 867
template <class CharT>
RegExpParserState* RegExpParserImpl<CharT>::ParseOpenParenthesis(
868 869 870
    RegExpParserState* state) {
  RegExpLookaround::Type lookaround_type = state->lookaround_type();
  bool is_named_capture = false;
871
  const ZoneVector<base::uc16>* capture_name = nullptr;
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
  SubexpressionType subexpr_type = CAPTURE;
  Advance();
  if (current() == '?') {
    switch (Next()) {
      case ':':
        Advance(2);
        subexpr_type = GROUPING;
        break;
      case '=':
        Advance(2);
        lookaround_type = RegExpLookaround::LOOKAHEAD;
        subexpr_type = POSITIVE_LOOKAROUND;
        break;
      case '!':
        Advance(2);
        lookaround_type = RegExpLookaround::LOOKAHEAD;
        subexpr_type = NEGATIVE_LOOKAROUND;
        break;
      case '<':
        Advance();
892 893 894 895 896 897 898 899 900 901
        if (Next() == '=') {
          Advance(2);
          lookaround_type = RegExpLookaround::LOOKBEHIND;
          subexpr_type = POSITIVE_LOOKAROUND;
          break;
        } else if (Next() == '!') {
          Advance(2);
          lookaround_type = RegExpLookaround::LOOKBEHIND;
          subexpr_type = NEGATIVE_LOOKAROUND;
          break;
902
        }
903 904 905 906
        is_named_capture = true;
        has_named_captures_ = true;
        Advance();
        break;
907
      default:
908
        ReportError(RegExpError::kInvalidGroup);
909 910 911 912
        return nullptr;
    }
  }
  if (subexpr_type == CAPTURE) {
913
    if (captures_started_ >= RegExpMacroAssembler::kMaxRegisterCount) {
914
      ReportError(RegExpError::kTooManyCaptures);
915 916 917 918 919 920 921 922 923
      return nullptr;
    }
    captures_started_++;

    if (is_named_capture) {
      capture_name = ParseCaptureGroupName(CHECK_FAILED);
    }
  }
  // Store current state and begin new disjunction parsing.
924 925
  return zone()->template New<RegExpParserState>(
      state, subexpr_type, lookaround_type, captures_started_, capture_name,
926
      state->builder()->flags(), zone());
927
}
928 929

#ifdef DEBUG
Jakob Gruber's avatar
Jakob Gruber committed
930 931 932
namespace {

bool IsSpecialClassEscape(base::uc32 c) {
933 934 935 936 937 938 939 940 941 942 943 944
  switch (c) {
    case 'd':
    case 'D':
    case 's':
    case 'S':
    case 'w':
    case 'W':
      return true;
    default:
      return false;
  }
}
Jakob Gruber's avatar
Jakob Gruber committed
945 946

}  // namespace
947 948 949 950 951 952 953 954
#endif

// In order to know whether an escape is a backreference or not we have to scan
// the entire regexp and find the number of capturing parentheses.  However we
// don't want to scan the regexp twice unless it is necessary.  This mini-parser
// is called when needed.  It can see the difference between capturing and
// noncapturing parentheses and can skip character classes and backslash-escaped
// characters.
955 956 957
//
// Important: The scanner has to be in a consistent state when calling
// ScanForCaptures, e.g. not in the middle of an escape sequence '\['.
958
template <class CharT>
959 960
void RegExpParserImpl<CharT>::ScanForCaptures(
    InClassEscapeState in_class_escape_state) {
961 962
  DCHECK(!is_scanned_for_captures_);
  const int saved_position = position();
963 964
  // Start with captures started previous to current position
  int capture_count = captures_started();
965 966 967 968 969 970 971 972 973 974 975 976
  // When we start inside a character class, skip everything inside the class.
  if (in_class_escape_state == InClassEscapeState::kInClass) {
    int c;
    while ((c = current()) != kEndMarker) {
      Advance();
      if (c == '\\') {
        Advance();
      } else {
        if (c == ']') break;
      }
    }
  }
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
  // Add count of captures after this position.
  int n;
  while ((n = current()) != kEndMarker) {
    Advance();
    switch (n) {
      case '\\':
        Advance();
        break;
      case '[': {
        int c;
        while ((c = current()) != kEndMarker) {
          Advance();
          if (c == '\\') {
            Advance();
          } else {
            if (c == ']') break;
          }
        }
        break;
      }
      case '(':
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
        if (current() == '?') {
          // At this point we could be in
          // * a non-capturing group '(:',
          // * a lookbehind assertion '(?<=' '(?<!'
          // * or a named capture '(?<'.
          //
          // Of these, only named captures are capturing groups.

          Advance();
          if (current() != '<') break;

1009 1010
          Advance();
          if (current() == '=' || current() == '!') break;
1011 1012 1013 1014 1015

          // Found a possible named capture. It could turn out to be a syntax
          // error (e.g. an unterminated or invalid name), but that distinction
          // does not matter for our purposes.
          has_named_captures_ = true;
1016 1017
        }
        capture_count++;
1018 1019 1020 1021 1022
        break;
    }
  }
  capture_count_ = capture_count;
  is_scanned_for_captures_ = true;
1023
  Reset(saved_position);
1024 1025
}

1026 1027
template <class CharT>
bool RegExpParserImpl<CharT>::ParseBackReferenceIndex(int* index_out) {
1028 1029 1030 1031 1032 1033 1034 1035
  DCHECK_EQ('\\', current());
  DCHECK('1' <= Next() && Next() <= '9');
  // Try to parse a decimal literal that is no greater than the total number
  // of left capturing parentheses in the input.
  int start = position();
  int value = Next() - '0';
  Advance(2);
  while (true) {
1036
    base::uc32 c = current();
1037 1038
    if (IsDecimalDigit(c)) {
      value = 10 * value + (c - '0');
1039
      if (value > RegExpMacroAssembler::kMaxRegisterCount) {
1040 1041 1042 1043 1044 1045 1046 1047 1048
        Reset(start);
        return false;
      }
      Advance();
    } else {
      break;
    }
  }
  if (value > captures_started()) {
1049 1050
    if (!is_scanned_for_captures_)
      ScanForCaptures(InClassEscapeState::kNotInClass);
1051 1052 1053 1054 1055 1056 1057 1058 1059
    if (value > capture_count_) {
      Reset(start);
      return false;
    }
  }
  *index_out = value;
  return true;
}

1060 1061 1062
namespace {

void push_code_unit(ZoneVector<base::uc16>* v, uint32_t code_unit) {
1063 1064 1065 1066 1067 1068 1069 1070
  if (code_unit <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
    v->push_back(code_unit);
  } else {
    v->push_back(unibrow::Utf16::LeadSurrogate(code_unit));
    v->push_back(unibrow::Utf16::TrailSurrogate(code_unit));
  }
}

1071 1072 1073 1074
}  // namespace

template <class CharT>
const ZoneVector<base::uc16>* RegExpParserImpl<CharT>::ParseCaptureGroupName() {
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
  // Due to special Advance requirements (see the next comment), rewind by one
  // such that names starting with a surrogate pair are parsed correctly for
  // patterns where the unicode flag is unset.
  //
  // Note that we use this odd pattern of rewinding the last advance in order
  // to adhere to the common parser behavior of expecting `current` to point at
  // the first candidate character for a function (e.g. when entering ParseFoo,
  // `current` should point at the first character of Foo).
  RewindByOneCodepoint();

1085 1086
  ZoneVector<base::uc16>* name =
      zone()->template New<ZoneVector<base::uc16>>(zone());
1087

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
  {
    // Advance behavior inside this function is tricky since
    // RegExpIdentifierName explicitly enables unicode (in spec terms, sets +U)
    // and thus allows surrogate pairs and \u{}-style escapes even in
    // non-unicode patterns. Therefore Advance within the capture group name
    // has to force-enable unicode, and outside the name revert to default
    // behavior.
    ForceUnicodeScope force_unicode(this);

    bool at_start = true;
    while (true) {
1099
      Advance();
1100
      base::uc32 c = current();
1101

1102 1103 1104 1105 1106 1107 1108 1109 1110
      // Convert unicode escapes.
      if (c == '\\' && Next() == 'u') {
        Advance(2);
        if (!ParseUnicodeEscape(&c)) {
          ReportError(RegExpError::kInvalidUnicodeEscape);
          return nullptr;
        }
        RewindByOneCodepoint();
      }
1111

1112 1113
      // The backslash char is misclassified as both ID_Start and ID_Continue.
      if (c == '\\') {
1114
        ReportError(RegExpError::kInvalidCaptureGroupName);
1115 1116
        return nullptr;
      }
1117 1118 1119 1120 1121 1122

      if (at_start) {
        if (!IsIdentifierStart(c)) {
          ReportError(RegExpError::kInvalidCaptureGroupName);
          return nullptr;
        }
1123
        push_code_unit(name, c);
1124
        at_start = false;
1125
      } else {
1126 1127 1128 1129 1130 1131 1132 1133
        if (c == '>') {
          break;
        } else if (IsIdentifierPart(c)) {
          push_code_unit(name, c);
        } else {
          ReportError(RegExpError::kInvalidCaptureGroupName);
          return nullptr;
        }
1134 1135 1136 1137
      }
    }
  }

1138 1139 1140 1141
  // This final advance goes back into the state of pointing at the next
  // relevant char, which the rest of the parser expects. See also the previous
  // comments in this function.
  Advance();
1142 1143 1144
  return name;
}

1145 1146 1147
template <class CharT>
bool RegExpParserImpl<CharT>::CreateNamedCaptureAtIndex(
    const ZoneVector<base::uc16>* name, int index) {
1148 1149 1150
  DCHECK(0 < index && index <= captures_started_);
  DCHECK_NOT_NULL(name);

1151 1152 1153 1154 1155
  RegExpCapture* capture = GetCapture(index);
  DCHECK_NULL(capture->name());

  capture->set_name(name);

1156
  if (named_captures_ == nullptr) {
1157
    named_captures_ =
1158 1159
        zone_->template New<ZoneSet<RegExpCapture*, RegExpCaptureNameLess>>(
            zone());
1160 1161
  } else {
    // Check for duplicates and bail if we find any.
1162 1163 1164

    const auto& named_capture_it = named_captures_->find(capture);
    if (named_capture_it != named_captures_->end()) {
1165
      ReportError(RegExpError::kDuplicateCaptureGroupName);
1166
      return false;
1167 1168 1169
    }
  }

1170
  named_captures_->emplace(capture);
1171 1172 1173 1174

  return true;
}

1175 1176 1177
template <class CharT>
bool RegExpParserImpl<CharT>::ParseNamedBackReference(
    RegExpBuilder* builder, RegExpParserState* state) {
1178 1179
  // The parser is assumed to be on the '<' in \k<name>.
  if (current() != '<') {
1180
    ReportError(RegExpError::kInvalidNamedReference);
1181 1182 1183
    return false;
  }

1184
  Advance();
1185
  const ZoneVector<base::uc16>* name = ParseCaptureGroupName();
1186 1187 1188 1189 1190 1191 1192
  if (name == nullptr) {
    return false;
  }

  if (state->IsInsideCaptureGroup(name)) {
    builder->AddEmpty();
  } else {
1193 1194
    RegExpBackReference* atom =
        zone()->template New<RegExpBackReference>(builder->flags());
1195 1196 1197 1198 1199 1200
    atom->set_name(name);

    builder->AddAtom(atom);

    if (named_back_references_ == nullptr) {
      named_back_references_ =
1201
          zone()->template New<ZoneList<RegExpBackReference*>>(1, zone());
1202 1203 1204 1205 1206 1207 1208
    }
    named_back_references_->Add(atom, zone());
  }

  return true;
}

1209 1210
template <class CharT>
void RegExpParserImpl<CharT>::PatchNamedBackReferences() {
1211 1212 1213
  if (named_back_references_ == nullptr) return;

  if (named_captures_ == nullptr) {
1214
    ReportError(RegExpError::kInvalidNamedCaptureReference);
1215 1216 1217 1218 1219 1220 1221 1222
    return;
  }

  // Look up and patch the actual capture for each named back reference.

  for (int i = 0; i < named_back_references_->length(); i++) {
    RegExpBackReference* ref = named_back_references_->at(i);

1223 1224 1225
    // Capture used to search the named_captures_ by name, index of the
    // capture is never used.
    static const int kInvalidIndex = 0;
1226 1227
    RegExpCapture* search_capture =
        zone()->template New<RegExpCapture>(kInvalidIndex);
1228 1229
    DCHECK_NULL(search_capture->name());
    search_capture->set_name(ref->name());
1230

1231 1232 1233 1234 1235
    int index = -1;
    const auto& capture_it = named_captures_->find(search_capture);
    if (capture_it != named_captures_->end()) {
      index = (*capture_it)->index();
    } else {
1236
      ReportError(RegExpError::kInvalidNamedCaptureReference);
1237 1238 1239 1240 1241 1242
      return;
    }

    ref->set_capture(GetCapture(index));
  }
}
1243

1244 1245
template <class CharT>
RegExpCapture* RegExpParserImpl<CharT>::GetCapture(int index) {
1246 1247
  // The index for the capture groups are one-based. Its index in the list is
  // zero-based.
1248
  const int known_captures =
1249
      is_scanned_for_captures_ ? capture_count_ : captures_started_;
1250
  DCHECK(index <= known_captures);
1251
  if (captures_ == nullptr) {
1252
    captures_ =
1253
        zone()->template New<ZoneList<RegExpCapture*>>(known_captures, zone());
1254
  }
1255
  while (captures_->length() < known_captures) {
1256 1257
    captures_->Add(zone()->template New<RegExpCapture>(captures_->length() + 1),
                   zone());
1258 1259 1260 1261
  }
  return captures_->at(index - 1);
}

1262 1263
template <class CharT>
ZoneVector<RegExpCapture*>* RegExpParserImpl<CharT>::GetNamedCaptures() const {
1264
  if (named_captures_ == nullptr || named_captures_->empty()) {
1265
    return nullptr;
1266
  }
1267

1268
  return zone()->template New<ZoneVector<RegExpCapture*>>(
1269
      named_captures_->begin(), named_captures_->end(), zone());
1270
}
1271

1272
template <class CharT>
1273 1274
bool RegExpParserImpl<CharT>::HasNamedCaptures(
    InClassEscapeState in_class_escape_state) {
1275 1276 1277 1278
  if (has_named_captures_ || is_scanned_for_captures_) {
    return has_named_captures_;
  }

1279
  ScanForCaptures(in_class_escape_state);
1280 1281 1282 1283
  DCHECK(is_scanned_for_captures_);
  return has_named_captures_;
}

1284 1285 1286 1287 1288 1289 1290
// QuantifierPrefix ::
//   { DecimalDigits }
//   { DecimalDigits , }
//   { DecimalDigits , DecimalDigits }
//
// Returns true if parsing succeeds, and set the min_out and max_out
// values. Values are truncated to RegExpTree::kInfinity if they overflow.
1291 1292 1293
template <class CharT>
bool RegExpParserImpl<CharT>::ParseIntervalQuantifier(int* min_out,
                                                      int* max_out) {
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  DCHECK_EQ(current(), '{');
  int start = position();
  Advance();
  int min = 0;
  if (!IsDecimalDigit(current())) {
    Reset(start);
    return false;
  }
  while (IsDecimalDigit(current())) {
    int next = current() - '0';
    if (min > (RegExpTree::kInfinity - next) / 10) {
      // Overflow. Skip past remaining decimal digits and return -1.
      do {
        Advance();
      } while (IsDecimalDigit(current()));
      min = RegExpTree::kInfinity;
      break;
    }
    min = 10 * min + next;
    Advance();
  }
  int max = 0;
  if (current() == '}') {
    max = min;
    Advance();
  } else if (current() == ',') {
    Advance();
    if (current() == '}') {
      max = RegExpTree::kInfinity;
      Advance();
    } else {
      while (IsDecimalDigit(current())) {
        int next = current() - '0';
        if (max > (RegExpTree::kInfinity - next) / 10) {
          do {
            Advance();
          } while (IsDecimalDigit(current()));
          max = RegExpTree::kInfinity;
          break;
        }
        max = 10 * max + next;
        Advance();
      }
      if (current() != '}') {
        Reset(start);
        return false;
      }
      Advance();
    }
  } else {
    Reset(start);
    return false;
  }
  *min_out = min;
  *max_out = max;
  return true;
}

1352 1353
template <class CharT>
base::uc32 RegExpParserImpl<CharT>::ParseOctalLiteral() {
1354 1355 1356
  DCHECK(('0' <= current() && current() <= '7') || current() == kEndMarker);
  // For compatibility with some other browsers (not all), we parse
  // up to three octal digits with a value below 256.
1357
  // ES#prod-annexB-LegacyOctalEscapeSequence
1358
  base::uc32 value = current() - '0';
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
  Advance();
  if ('0' <= current() && current() <= '7') {
    value = value * 8 + current() - '0';
    Advance();
    if (value < 32 && '0' <= current() && current() <= '7') {
      value = value * 8 + current() - '0';
      Advance();
    }
  }
  return value;
}

1371 1372
template <class CharT>
bool RegExpParserImpl<CharT>::ParseHexEscape(int length, base::uc32* value) {
1373
  int start = position();
1374
  base::uc32 val = 0;
1375
  for (int i = 0; i < length; ++i) {
1376 1377
    base::uc32 c = current();
    int d = base::HexValue(c);
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
    if (d < 0) {
      Reset(start);
      return false;
    }
    val = val * 16 + d;
    Advance();
  }
  *value = val;
  return true;
}

1389
// This parses RegExpUnicodeEscapeSequence as described in ECMA262.
1390 1391
template <class CharT>
bool RegExpParserImpl<CharT>::ParseUnicodeEscape(base::uc32* value) {
1392 1393 1394
  // Accept both \uxxxx and \u{xxxxxx} (if harmony unicode escapes are
  // allowed). In the latter case, the number of hex digits between { } is
  // arbitrary. \ and u have already been read.
1395
  if (current() == '{' && unicode()) {
1396 1397
    int start = position();
    Advance();
1398
    if (ParseUnlimitedLengthHexNumber(0x10FFFF, value)) {
1399 1400 1401 1402 1403 1404 1405 1406 1407
      if (current() == '}') {
        Advance();
        return true;
      }
    }
    Reset(start);
    return false;
  }
  // \u but no {, or \u{...} escapes not allowed.
1408 1409 1410 1411 1412 1413 1414
  bool result = ParseHexEscape(4, value);
  if (result && unicode() && unibrow::Utf16::IsLeadSurrogate(*value) &&
      current() == '\\') {
    // Attempt to read trail surrogate.
    int start = position();
    if (Next() == 'u') {
      Advance(2);
1415
      base::uc32 trail;
1416 1417
      if (ParseHexEscape(4, &trail) &&
          unibrow::Utf16::IsTrailSurrogate(trail)) {
1418 1419
        *value = unibrow::Utf16::CombineSurrogatePair(
            static_cast<base::uc16>(*value), static_cast<base::uc16>(trail));
1420 1421 1422 1423 1424 1425
        return true;
      }
    }
    Reset(start);
  }
  return result;
1426 1427
}

1428
#ifdef V8_INTL_SUPPORT
1429 1430 1431

namespace {

1432 1433
bool IsExactPropertyAlias(const char* property_name, UProperty property) {
  const char* short_name = u_getPropertyName(property, U_SHORT_PROPERTY_NAME);
1434 1435
  if (short_name != nullptr && strcmp(property_name, short_name) == 0)
    return true;
1436 1437 1438
  for (int i = 0;; i++) {
    const char* long_name = u_getPropertyName(
        property, static_cast<UPropertyNameChoice>(U_LONG_PROPERTY_NAME + i));
1439
    if (long_name == nullptr) break;
1440 1441 1442 1443 1444 1445 1446
    if (strcmp(property_name, long_name) == 0) return true;
  }
  return false;
}

bool IsExactPropertyValueAlias(const char* property_value_name,
                               UProperty property, int32_t property_value) {
1447 1448
  const char* short_name =
      u_getPropertyValueName(property, property_value, U_SHORT_PROPERTY_NAME);
1449
  if (short_name != nullptr && strcmp(property_value_name, short_name) == 0) {
1450 1451
    return true;
  }
1452 1453 1454 1455
  for (int i = 0;; i++) {
    const char* long_name = u_getPropertyValueName(
        property, property_value,
        static_cast<UPropertyNameChoice>(U_LONG_PROPERTY_NAME + i));
1456
    if (long_name == nullptr) break;
1457
    if (strcmp(property_value_name, long_name) == 0) return true;
1458 1459 1460 1461
  }
  return false;
}

1462 1463 1464
bool LookupPropertyValueName(UProperty property,
                             const char* property_value_name, bool negate,
                             ZoneList<CharacterRange>* result, Zone* zone) {
1465 1466 1467 1468 1469 1470
  UProperty property_for_lookup = property;
  if (property_for_lookup == UCHAR_SCRIPT_EXTENSIONS) {
    // For the property Script_Extensions, we have to do the property value
    // name lookup as if the property is Script.
    property_for_lookup = UCHAR_SCRIPT;
  }
1471
  int32_t property_value =
1472
      u_getPropertyValueEnum(property_for_lookup, property_value_name);
1473 1474
  if (property_value == UCHAR_INVALID_CODE) return false;

1475 1476
  // We require the property name to match exactly to one of the property value
  // aliases. However, u_getPropertyValueEnum uses loose matching.
1477
  if (!IsExactPropertyValueAlias(property_value_name, property_for_lookup,
1478
                                 property_value)) {
1479 1480 1481
    return false;
  }

1482
  UErrorCode ec = U_ZERO_ERROR;
1483 1484 1485
  icu::UnicodeSet set;
  set.applyIntPropertyValue(property, property_value, ec);
  bool success = ec == U_ZERO_ERROR && !set.isEmpty();
1486 1487

  if (success) {
1488 1489 1490 1491 1492 1493
    set.removeAllStrings();
    if (negate) set.complement();
    for (int i = 0; i < set.getRangeCount(); i++) {
      result->Add(
          CharacterRange::Range(set.getRangeStart(i), set.getRangeEnd(i)),
          zone);
1494 1495 1496 1497 1498
    }
  }
  return success;
}

1499 1500 1501 1502 1503
template <size_t N>
inline bool NameEquals(const char* name, const char (&literal)[N]) {
  return strncmp(name, literal, N + 1) == 0;
}

1504 1505 1506
bool LookupSpecialPropertyValueName(const char* name,
                                    ZoneList<CharacterRange>* result,
                                    bool negate, Zone* zone) {
1507
  if (NameEquals(name, "Any")) {
1508 1509 1510 1511 1512 1513
    if (negate) {
      // Leave the list of character ranges empty, since the negation of 'Any'
      // is the empty set.
    } else {
      result->Add(CharacterRange::Everything(), zone);
    }
1514 1515
  } else if (NameEquals(name, "ASCII")) {
    result->Add(negate ? CharacterRange::Range(0x80, String::kMaxCodePoint)
1516
                       : CharacterRange::Range(0x0, 0x7F),
1517 1518
                zone);
  } else if (NameEquals(name, "Assigned")) {
1519 1520
    return LookupPropertyValueName(UCHAR_GENERAL_CATEGORY, "Unassigned",
                                   !negate, result, zone);
1521 1522 1523 1524 1525 1526
  } else {
    return false;
  }
  return true;
}

Dan Elphick's avatar
Dan Elphick committed
1527
// Explicitly allowlist supported binary properties. The spec forbids supporting
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
// properties outside of this set to ensure interoperability.
bool IsSupportedBinaryProperty(UProperty property) {
  switch (property) {
    case UCHAR_ALPHABETIC:
    // 'Any' is not supported by ICU. See LookupSpecialPropertyValueName.
    // 'ASCII' is not supported by ICU. See LookupSpecialPropertyValueName.
    case UCHAR_ASCII_HEX_DIGIT:
    // 'Assigned' is not supported by ICU. See LookupSpecialPropertyValueName.
    case UCHAR_BIDI_CONTROL:
    case UCHAR_BIDI_MIRRORED:
    case UCHAR_CASE_IGNORABLE:
    case UCHAR_CASED:
    case UCHAR_CHANGES_WHEN_CASEFOLDED:
    case UCHAR_CHANGES_WHEN_CASEMAPPED:
    case UCHAR_CHANGES_WHEN_LOWERCASED:
    case UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED:
    case UCHAR_CHANGES_WHEN_TITLECASED:
    case UCHAR_CHANGES_WHEN_UPPERCASED:
    case UCHAR_DASH:
    case UCHAR_DEFAULT_IGNORABLE_CODE_POINT:
    case UCHAR_DEPRECATED:
    case UCHAR_DIACRITIC:
    case UCHAR_EMOJI:
1551
    case UCHAR_EMOJI_COMPONENT:
1552 1553 1554
    case UCHAR_EMOJI_MODIFIER_BASE:
    case UCHAR_EMOJI_MODIFIER:
    case UCHAR_EMOJI_PRESENTATION:
Jungshik Shin's avatar
Jungshik Shin committed
1555
    case UCHAR_EXTENDED_PICTOGRAPHIC:
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
    case UCHAR_EXTENDER:
    case UCHAR_GRAPHEME_BASE:
    case UCHAR_GRAPHEME_EXTEND:
    case UCHAR_HEX_DIGIT:
    case UCHAR_ID_CONTINUE:
    case UCHAR_ID_START:
    case UCHAR_IDEOGRAPHIC:
    case UCHAR_IDS_BINARY_OPERATOR:
    case UCHAR_IDS_TRINARY_OPERATOR:
    case UCHAR_JOIN_CONTROL:
    case UCHAR_LOGICAL_ORDER_EXCEPTION:
    case UCHAR_LOWERCASE:
    case UCHAR_MATH:
    case UCHAR_NONCHARACTER_CODE_POINT:
    case UCHAR_PATTERN_SYNTAX:
    case UCHAR_PATTERN_WHITE_SPACE:
    case UCHAR_QUOTATION_MARK:
    case UCHAR_RADICAL:
1574
    case UCHAR_REGIONAL_INDICATOR:
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
    case UCHAR_S_TERM:
    case UCHAR_SOFT_DOTTED:
    case UCHAR_TERMINAL_PUNCTUATION:
    case UCHAR_UNIFIED_IDEOGRAPH:
    case UCHAR_UPPERCASE:
    case UCHAR_VARIATION_SELECTOR:
    case UCHAR_WHITE_SPACE:
    case UCHAR_XID_CONTINUE:
    case UCHAR_XID_START:
      return true;
    default:
      break;
  }
  return false;
}

1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
bool IsUnicodePropertyValueCharacter(char c) {
  // https://tc39.github.io/proposal-regexp-unicode-property-escapes/
  //
  // Note that using this to validate each parsed char is quite conservative.
  // A possible alternative solution would be to only ensure the parsed
  // property name/value candidate string does not contain '\0' characters and
  // let ICU lookups trigger the final failure.
  if ('a' <= c && c <= 'z') return true;
  if ('A' <= c && c <= 'Z') return true;
  if ('0' <= c && c <= '9') return true;
  return (c == '_');
}

1604
}  // namespace
1605

1606 1607 1608
template <class CharT>
bool RegExpParserImpl<CharT>::ParsePropertyClassName(ZoneVector<char>* name_1,
                                                     ZoneVector<char>* name_2) {
1609 1610
  DCHECK(name_1->empty());
  DCHECK(name_2->empty());
1611 1612 1613 1614 1615 1616 1617 1618
  // Parse the property class as follows:
  // - In \p{name}, 'name' is interpreted
  //   - either as a general category property value name.
  //   - or as a binary property name.
  // - In \p{name=value}, 'name' is interpreted as an enumerated property name,
  //   and 'value' is interpreted as one of the available property value names.
  // - Aliases in PropertyAlias.txt and PropertyValueAlias.txt can be used.
  // - Loose matching is not applied.
1619
  if (current() == '{') {
1620 1621
    // Parse \p{[PropertyName=]PropertyNameValue}
    for (Advance(); current() != '}' && current() != '='; Advance()) {
1622
      if (!IsUnicodePropertyValueCharacter(current())) return false;
1623
      if (!has_next()) return false;
1624
      name_1->push_back(static_cast<char>(current()));
1625 1626 1627
    }
    if (current() == '=') {
      for (Advance(); current() != '}'; Advance()) {
1628
        if (!IsUnicodePropertyValueCharacter(current())) return false;
1629
        if (!has_next()) return false;
1630
        name_2->push_back(static_cast<char>(current()));
1631
      }
1632
      name_2->push_back(0);  // null-terminate string.
1633 1634
    }
  } else {
1635
    return false;
1636 1637
  }
  Advance();
1638
  name_1->push_back(0);  // null-terminate string.
1639

1640 1641 1642 1643
  DCHECK(name_1->size() - 1 == std::strlen(name_1->data()));
  DCHECK(name_2->empty() || name_2->size() - 1 == std::strlen(name_2->data()));
  return true;
}
1644

1645 1646 1647 1648
template <class CharT>
bool RegExpParserImpl<CharT>::AddPropertyClassRange(
    ZoneList<CharacterRange>* add_to, bool negate,
    const ZoneVector<char>& name_1, const ZoneVector<char>& name_2) {
1649
  if (name_2.empty()) {
1650
    // First attempt to interpret as general category property value name.
1651
    const char* name = name_1.data();
1652
    if (LookupPropertyValueName(UCHAR_GENERAL_CATEGORY_MASK, name, negate,
1653
                                add_to, zone())) {
1654 1655 1656
      return true;
    }
    // Interpret "Any", "ASCII", and "Assigned".
1657
    if (LookupSpecialPropertyValueName(name, add_to, negate, zone())) {
1658 1659 1660 1661
      return true;
    }
    // Then attempt to interpret as binary property name with value name 'Y'.
    UProperty property = u_getPropertyEnum(name);
1662
    if (!IsSupportedBinaryProperty(property)) return false;
1663
    if (!IsExactPropertyAlias(name, property)) return false;
1664
    return LookupPropertyValueName(property, negate ? "N" : "Y", false, add_to,
1665
                                   zone());
1666 1667 1668
  } else {
    // Both property name and value name are specified. Attempt to interpret
    // the property name as enumerated property.
1669 1670
    const char* property_name = name_1.data();
    const char* value_name = name_2.data();
1671 1672
    UProperty property = u_getPropertyEnum(property_name);
    if (!IsExactPropertyAlias(property_name, property)) return false;
1673 1674 1675 1676 1677 1678 1679
    if (property == UCHAR_GENERAL_CATEGORY) {
      // We want to allow aggregate value names such as "Letter".
      property = UCHAR_GENERAL_CATEGORY_MASK;
    } else if (property != UCHAR_SCRIPT &&
               property != UCHAR_SCRIPT_EXTENSIONS) {
      return false;
    }
1680
    return LookupPropertyValueName(property, value_name, negate, add_to,
1681
                                   zone());
1682
  }
1683 1684
}

1685
#else  // V8_INTL_SUPPORT
1686

1687 1688 1689
template <class CharT>
bool RegExpParserImpl<CharT>::ParsePropertyClassName(ZoneVector<char>* name_1,
                                                     ZoneVector<char>* name_2) {
1690
  return false;
1691
}
1692

1693 1694 1695 1696
template <class CharT>
bool RegExpParserImpl<CharT>::AddPropertyClassRange(
    ZoneList<CharacterRange>* add_to, bool negate,
    const ZoneVector<char>& name_1, const ZoneVector<char>& name_2) {
1697 1698 1699
  return false;
}

1700
#endif  // V8_INTL_SUPPORT
1701

1702 1703 1704
template <class CharT>
bool RegExpParserImpl<CharT>::ParseUnlimitedLengthHexNumber(int max_value,
                                                            base::uc32* value) {
1705 1706
  base::uc32 x = 0;
  int d = base::HexValue(current());
1707 1708 1709 1710 1711
  if (d < 0) {
    return false;
  }
  while (d >= 0) {
    x = x * 16 + d;
1712
    if (x > static_cast<base::uc32>(max_value)) {
1713 1714 1715
      return false;
    }
    Advance();
1716
    d = base::HexValue(current());
1717 1718 1719 1720 1721
  }
  *value = x;
  return true;
}

1722
// https://tc39.es/ecma262/#prod-CharacterEscape
1723
template <class CharT>
1724 1725 1726
base::uc32 RegExpParserImpl<CharT>::ParseCharacterEscape(
    InClassEscapeState in_class_escape_state,
    bool* is_escaped_unicode_character) {
1727
  DCHECK_EQ('\\', current());
1728
  DCHECK(has_next() && !IsSpecialClassEscape(Next()));
1729

1730
  Advance();
1731 1732 1733 1734 1735 1736

  const base::uc32 c = current();
  switch (c) {
    // CharacterEscape ::
    //   ControlEscape :: one of
    //     f n r t v
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
    case 'f':
      Advance();
      return '\f';
    case 'n':
      Advance();
      return '\n';
    case 'r':
      Advance();
      return '\r';
    case 't':
      Advance();
      return '\t';
    case 'v':
      Advance();
      return '\v';
1752 1753
    // CharacterEscape ::
    //   c ControlLetter
1754
    case 'c': {
1755 1756
      base::uc32 controlLetter = Next();
      base::uc32 letter = controlLetter & ~('A' ^ 'a');
1757
      if (letter >= 'A' && letter <= 'Z') {
1758 1759
        Advance(2);
        // Control letters mapped to ASCII control characters in the range
1760 1761
        // 0x00-0x1F.
        return controlLetter & 0x1F;
1762
      }
1763 1764
      if (unicode()) {
        // With /u, invalid escapes are not treated as identity escapes.
1765
        ReportError(RegExpError::kInvalidUnicodeEscape);
1766 1767
        return 0;
      }
1768 1769 1770 1771 1772 1773 1774 1775 1776
      if (in_class_escape_state == InClassEscapeState::kInClass) {
        // Inside a character class, we also accept digits and underscore as
        // control characters, unless with /u. See Annex B:
        // ES#prod-annexB-ClassControlLetter
        if ((controlLetter >= '0' && controlLetter <= '9') ||
            controlLetter == '_') {
          Advance(2);
          return controlLetter & 0x1F;
        }
1777
      }
1778 1779 1780 1781
      // We match JSC in reading the backslash as a literal
      // character instead of as starting an escape.
      return '\\';
    }
1782 1783 1784
    // CharacterEscape ::
    //   0 [lookahead ∉ DecimalDigit]
    //   [~UnicodeMode] LegacyOctalEscapeSequence
1785
    case '0':
1786 1787
      // \0 is interpreted as NUL if not followed by another digit.
      if (Next() < '0' || Next() > '9') {
1788 1789 1790
        Advance();
        return 0;
      }
1791
      V8_FALLTHROUGH;
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
      // For compatibility, we interpret a decimal escape that isn't
      // a back reference (and therefore either \0 or not valid according
      // to the specification) as a 1..3 digit octal character code.
1802
      // ES#prod-annexB-LegacyOctalEscapeSequence
1803 1804
      if (unicode()) {
        // With /u, decimal escape is not interpreted as octal character code.
1805
        ReportError(RegExpError::kInvalidClassEscape);
1806 1807
        return 0;
      }
1808
      return ParseOctalLiteral();
1809 1810
    // CharacterEscape ::
    //   HexEscapeSequence
1811 1812
    case 'x': {
      Advance();
1813
      base::uc32 value;
1814 1815 1816
      if (ParseHexEscape(2, &value)) return value;
      if (unicode()) {
        // With /u, invalid escapes are not treated as identity escapes.
1817
        ReportError(RegExpError::kInvalidEscape);
1818
        return 0;
1819
      }
1820 1821 1822
      // If \x is not followed by a two-digit hexadecimal, treat it
      // as an identity escape.
      return 'x';
1823
    }
1824 1825
    // CharacterEscape ::
    //   RegExpUnicodeEscapeSequence [?UnicodeMode]
1826 1827
    case 'u': {
      Advance();
1828
      base::uc32 value;
1829 1830 1831 1832
      if (ParseUnicodeEscape(&value)) {
        *is_escaped_unicode_character = true;
        return value;
      }
1833 1834
      if (unicode()) {
        // With /u, invalid escapes are not treated as identity escapes.
1835
        ReportError(RegExpError::kInvalidUnicodeEscape);
1836
        return 0;
1837
      }
1838 1839 1840
      // If \u is not followed by a two-digit hexadecimal, treat it
      // as an identity escape.
      return 'u';
1841
    }
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
    default:
      break;
  }

  // CharacterEscape ::
  //   IdentityEscape[?UnicodeMode, ?N]
  //
  // * With /u, no identity escapes except for syntax characters are
  //   allowed.
  // * Without /u:
  //   * '\c' is not an IdentityEscape.
  //   * '\k' is not an IdentityEscape when named captures exist.
  //   * Otherwise, all identity escapes are allowed.
  if (unicode()) {
    if (!IsSyntaxCharacterOrSlash(c)) {
1857
      ReportError(RegExpError::kInvalidEscape);
1858 1859
      return 0;
    }
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
    Advance();
    return c;
  }
  DCHECK(!unicode());
  if (c == 'c') {
    ReportError(RegExpError::kInvalidEscape);
    return 0;
  }
  Advance();
  // Note: It's important to Advance before the HasNamedCaptures call s.t. we
  // don't start scanning in the middle of an escape.
1871
  if (c == 'k' && HasNamedCaptures(in_class_escape_state)) {
1872 1873
    ReportError(RegExpError::kInvalidEscape);
    return 0;
1874
  }
1875
  return c;
1876 1877
}

1878
// https://tc39.es/ecma262/#prod-ClassEscape
1879 1880 1881 1882 1883
template <class CharT>
void RegExpParserImpl<CharT>::ParseClassEscape(
    ZoneList<CharacterRange>* ranges, Zone* zone,
    bool add_unicode_case_equivalents, base::uc32* char_out,
    bool* is_class_escape) {
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
  *is_class_escape = false;

  if (current() != '\\') {
    // Not a ClassEscape.
    *char_out = current();
    Advance();
    return;
  }

  const base::uc32 next = Next();
  switch (next) {
    case 'b':
      *char_out = '\b';
      Advance(2);
      return;
    case '-':
      if (unicode()) {
        *char_out = next;
1902
        Advance(2);
1903
        return;
1904
      }
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
      break;
    case kEndMarker:
      ReportError(RegExpError::kEscapeAtEndOfPattern);
      return;
    default:
      break;
  }

  static constexpr InClassEscapeState kInClassEscape =
      InClassEscapeState::kInClass;
  *is_class_escape = TryParseCharacterClassEscape(
      next, kInClassEscape, ranges, zone, add_unicode_case_equivalents);
  if (*is_class_escape) return;

  bool dummy = false;  // Unused.
  *char_out = ParseCharacterEscape(kInClassEscape, &dummy);
}

// https://tc39.es/ecma262/#prod-CharacterClassEscape
template <class CharT>
bool RegExpParserImpl<CharT>::TryParseCharacterClassEscape(
    base::uc32 next, InClassEscapeState in_class_escape_state,
    ZoneList<CharacterRange>* ranges, Zone* zone,
    bool add_unicode_case_equivalents) {
  DCHECK_EQ(current(), '\\');
  DCHECK_EQ(Next(), next);

  switch (next) {
    case 'd':
    case 'D':
    case 's':
    case 'S':
    case 'w':
    case 'W':
1939 1940 1941
      CharacterRange::AddClassEscape(static_cast<StandardCharacterSet>(next),
                                     ranges, add_unicode_case_equivalents,
                                     zone);
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
      Advance(2);
      return true;
    case 'p':
    case 'P': {
      if (!unicode()) return false;
      bool negate = next == 'P';
      Advance(2);
      ZoneVector<char> name_1(zone);
      ZoneVector<char> name_2(zone);
      if (!ParsePropertyClassName(&name_1, &name_2) ||
          !AddPropertyClassRange(ranges, negate, name_1, name_2)) {
        ReportError(in_class_escape_state == InClassEscapeState::kInClass
                        ? RegExpError::kInvalidClassPropertyName
                        : RegExpError::kInvalidPropertyName);
      }
      return true;
1958
    }
1959 1960
    default:
      return false;
1961
  }
1962
}
1963

1964 1965 1966
template <class CharT>
RegExpTree* RegExpParserImpl<CharT>::ParseCharacterClass(
    const RegExpBuilder* builder) {
1967 1968 1969 1970 1971 1972 1973 1974
  DCHECK_EQ(current(), '[');
  Advance();
  bool is_negated = false;
  if (current() == '^') {
    is_negated = true;
    Advance();
  }
  ZoneList<CharacterRange>* ranges =
1975
      zone()->template New<ZoneList<CharacterRange>>(2, zone());
1976
  bool add_unicode_case_equivalents = unicode() && builder->ignore_case();
1977
  while (has_more() && current() != ']') {
1978
    base::uc32 char_1, char_2;
1979 1980 1981
    bool is_class_1, is_class_2;
    ParseClassEscape(ranges, zone(), add_unicode_case_equivalents, &char_1,
                     &is_class_1 CHECK_FAILED);
1982 1983 1984 1985 1986 1987 1988
    if (current() == '-') {
      Advance();
      if (current() == kEndMarker) {
        // If we reach the end we break out of the loop and let the
        // following code report an error.
        break;
      } else if (current() == ']') {
1989
        if (!is_class_1) ranges->Add(CharacterRange::Singleton(char_1), zone());
1990 1991 1992
        ranges->Add(CharacterRange::Singleton('-'), zone());
        break;
      }
1993 1994 1995
      ParseClassEscape(ranges, zone(), add_unicode_case_equivalents, &char_2,
                       &is_class_2 CHECK_FAILED);
      if (is_class_1 || is_class_2) {
1996
        // Either end is an escaped character class. Treat the '-' verbatim.
1997 1998
        if (unicode()) {
          // ES2015 21.2.2.15.1 step 1.
1999
          return ReportError(RegExpError::kInvalidCharacterClass);
2000
        }
2001
        if (!is_class_1) ranges->Add(CharacterRange::Singleton(char_1), zone());
2002
        ranges->Add(CharacterRange::Singleton('-'), zone());
2003
        if (!is_class_2) ranges->Add(CharacterRange::Singleton(char_2), zone());
2004 2005
        continue;
      }
2006
      // ES2015 21.2.2.15.1 step 6.
2007
      if (char_1 > char_2) {
2008
        return ReportError(RegExpError::kOutOfOrderCharacterClass);
2009
      }
2010
      ranges->Add(CharacterRange::Range(char_1, char_2), zone());
2011
    } else {
2012
      if (!is_class_1) ranges->Add(CharacterRange::Singleton(char_1), zone());
2013 2014 2015
    }
  }
  if (!has_more()) {
2016
    return ReportError(RegExpError::kUnterminatedCharacterClass);
2017 2018
  }
  Advance();
2019 2020
  RegExpCharacterClass::CharacterClassFlags character_class_flags;
  if (is_negated) character_class_flags = RegExpCharacterClass::NEGATED;
2021 2022
  return zone()->template New<RegExpCharacterClass>(zone(), ranges,
                                                    character_class_flags);
2023 2024 2025 2026
}

#undef CHECK_FAILED

2027 2028
template <class CharT>
bool RegExpParserImpl<CharT>::Parse(RegExpCompileData* result) {
2029
  DCHECK_NOT_NULL(result);
2030
  RegExpTree* tree = ParsePattern();
2031

2032
  if (failed()) {
2033 2034
    DCHECK_NULL(tree);
    DCHECK_NE(error_, RegExpError::kNone);
2035 2036
    result->error = error_;
    result->error_pos = error_pos_;
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
    return false;
  }

  DCHECK_NOT_NULL(tree);
  DCHECK_EQ(error_, RegExpError::kNone);
  if (FLAG_trace_regexp_parser) {
    StdoutStream os;
    tree->Print(os, zone());
    os << "\n";
  }

  result->tree = tree;
  const int capture_count = captures_started();
  result->simple = tree->IsAtom() && simple() && capture_count == 0;
  result->contains_anchor = contains_anchor();
  result->capture_count = capture_count;
  result->named_captures = GetNamedCaptures();
  return true;
2055 2056
}

2057
void RegExpBuilder::AddLeadSurrogate(base::uc16 lead_surrogate) {
2058 2059 2060 2061 2062 2063
  DCHECK(unibrow::Utf16::IsLeadSurrogate(lead_surrogate));
  FlushPendingSurrogate();
  // Hold onto the lead surrogate, waiting for a trail surrogate to follow.
  pending_surrogate_ = lead_surrogate;
}

2064
void RegExpBuilder::AddTrailSurrogate(base::uc16 trail_surrogate) {
2065 2066
  DCHECK(unibrow::Utf16::IsTrailSurrogate(trail_surrogate));
  if (pending_surrogate_ != kNoPendingSurrogate) {
2067
    base::uc16 lead_surrogate = pending_surrogate_;
2068
    pending_surrogate_ = kNoPendingSurrogate;
2069
    DCHECK(unibrow::Utf16::IsLeadSurrogate(lead_surrogate));
2070
    base::uc32 combined =
2071 2072
        unibrow::Utf16::CombineSurrogatePair(lead_surrogate, trail_surrogate);
    if (NeedsDesugaringForIgnoreCase(combined)) {
2073
      AddCharacterClassForDesugaring(combined);
2074
    } else {
2075
      ZoneList<base::uc16> surrogate_pair(2, zone());
2076 2077 2078
      surrogate_pair.Add(lead_surrogate, zone());
      surrogate_pair.Add(trail_surrogate, zone());
      RegExpAtom* atom =
2079
          zone()->New<RegExpAtom>(surrogate_pair.ToConstVector());
2080 2081
      AddAtom(atom);
    }
2082 2083 2084 2085 2086 2087 2088 2089 2090
  } else {
    pending_surrogate_ = trail_surrogate;
    FlushPendingSurrogate();
  }
}

void RegExpBuilder::FlushPendingSurrogate() {
  if (pending_surrogate_ != kNoPendingSurrogate) {
    DCHECK(unicode());
2091
    base::uc32 c = pending_surrogate_;
2092
    pending_surrogate_ = kNoPendingSurrogate;
2093
    AddCharacterClassForDesugaring(c);
2094 2095 2096
  }
}

2097
void RegExpBuilder::FlushCharacters() {
2098
  FlushPendingSurrogate();
2099
  pending_empty_ = false;
2100
  if (characters_ != nullptr) {
2101
    RegExpTree* atom = zone()->New<RegExpAtom>(characters_->ToConstVector());
2102
    characters_ = nullptr;
2103
    text_.emplace_back(atom);
2104 2105 2106 2107 2108 2109
    LAST(ADD_ATOM);
  }
}

void RegExpBuilder::FlushText() {
  FlushCharacters();
2110
  size_t num_text = text_.size();
2111 2112 2113
  if (num_text == 0) {
    return;
  } else if (num_text == 1) {
2114
    terms_.emplace_back(text_.back());
2115
  } else {
2116
    RegExpText* text = zone()->New<RegExpText>(zone());
2117
    for (size_t i = 0; i < num_text; i++) {
2118 2119
      text_[i]->AppendToText(text, zone());
    }
2120
    terms_.emplace_back(text);
2121
  }
2122
  text_.clear();
2123 2124
}

2125
void RegExpBuilder::AddCharacter(base::uc16 c) {
2126
  FlushPendingSurrogate();
2127
  pending_empty_ = false;
2128
  if (NeedsDesugaringForIgnoreCase(c)) {
2129
    AddCharacterClassForDesugaring(c);
2130
  } else {
2131
    if (characters_ == nullptr) {
2132
      characters_ = zone()->New<ZoneList<base::uc16>>(4, zone());
2133 2134 2135
    }
    characters_->Add(c, zone());
    LAST(ADD_CHAR);
2136 2137 2138
  }
}

2139 2140
void RegExpBuilder::AddUnicodeCharacter(base::uc32 c) {
  if (c > static_cast<base::uc32>(unibrow::Utf16::kMaxNonSurrogateCharCode)) {
2141 2142 2143 2144 2145 2146 2147
    DCHECK(unicode());
    AddLeadSurrogate(unibrow::Utf16::LeadSurrogate(c));
    AddTrailSurrogate(unibrow::Utf16::TrailSurrogate(c));
  } else if (unicode() && unibrow::Utf16::IsLeadSurrogate(c)) {
    AddLeadSurrogate(c);
  } else if (unicode() && unibrow::Utf16::IsTrailSurrogate(c)) {
    AddTrailSurrogate(c);
2148
  } else {
2149
    AddCharacter(static_cast<base::uc16>(c));
2150 2151 2152
  }
}

2153
void RegExpBuilder::AddEscapedUnicodeCharacter(base::uc32 character) {
2154 2155 2156 2157 2158 2159
  // A lead or trail surrogate parsed via escape sequence will not
  // pair up with any preceding lead or following trail surrogate.
  FlushPendingSurrogate();
  AddUnicodeCharacter(character);
  FlushPendingSurrogate();
}
2160

2161 2162
void RegExpBuilder::AddEmpty() { pending_empty_ = true; }

2163
void RegExpBuilder::AddCharacterClass(RegExpCharacterClass* cc) {
2164
  if (NeedsDesugaringForUnicode(cc)) {
2165
    // With /u, character class needs to be desugared, so it
2166 2167 2168 2169 2170 2171 2172
    // must be a standalone term instead of being part of a RegExpText.
    AddTerm(cc);
  } else {
    AddAtom(cc);
  }
}

2173
void RegExpBuilder::AddCharacterClassForDesugaring(base::uc32 c) {
2174
  AddTerm(zone()->New<RegExpCharacterClass>(
2175
      zone(), CharacterRange::List(zone(), CharacterRange::Singleton(c))));
2176 2177
}

2178 2179 2180 2181 2182 2183 2184
void RegExpBuilder::AddAtom(RegExpTree* term) {
  if (term->IsEmpty()) {
    AddEmpty();
    return;
  }
  if (term->IsTextElement()) {
    FlushCharacters();
2185
    text_.emplace_back(term);
2186 2187
  } else {
    FlushText();
2188
    terms_.emplace_back(term);
2189 2190 2191 2192
  }
  LAST(ADD_ATOM);
}

2193 2194
void RegExpBuilder::AddTerm(RegExpTree* term) {
  FlushText();
2195
  terms_.emplace_back(term);
2196 2197 2198
  LAST(ADD_ATOM);
}

2199 2200
void RegExpBuilder::AddAssertion(RegExpTree* assert) {
  FlushText();
2201
  terms_.emplace_back(assert);
2202 2203 2204 2205 2206 2207 2208
  LAST(ADD_ASSERT);
}

void RegExpBuilder::NewAlternative() { FlushTerms(); }

void RegExpBuilder::FlushTerms() {
  FlushText();
2209
  size_t num_terms = terms_.size();
2210 2211
  RegExpTree* alternative;
  if (num_terms == 0) {
2212
    alternative = zone()->New<RegExpEmpty>();
2213
  } else if (num_terms == 1) {
2214
    alternative = terms_.back();
2215
  } else {
2216 2217 2218
    alternative =
        zone()->New<RegExpAlternative>(zone()->New<ZoneList<RegExpTree*>>(
            base::VectorOf(terms_.begin(), terms_.size()), zone()));
2219
  }
2220 2221
  alternatives_.emplace_back(alternative);
  terms_.clear();
2222 2223 2224
  LAST(ADD_NONE);
}

2225 2226
bool RegExpBuilder::NeedsDesugaringForUnicode(RegExpCharacterClass* cc) {
  if (!unicode()) return false;
2227 2228 2229 2230
  // TODO(yangguo): we could be smarter than this. Case-insensitivity does not
  // necessarily mean that we need to desugar. It's probably nicer to have a
  // separate pass to figure out unicode desugarings.
  if (ignore_case()) return true;
2231 2232 2233
  ZoneList<CharacterRange>* ranges = cc->ranges(zone());
  CharacterRange::Canonicalize(ranges);
  for (int i = ranges->length() - 1; i >= 0; i--) {
2234 2235
    base::uc32 from = ranges->at(i).from();
    base::uc32 to = ranges->at(i).to();
2236 2237 2238 2239 2240 2241 2242 2243
    // Check for non-BMP characters.
    if (to >= kNonBmpStart) return true;
    // Check for lone surrogates.
    if (from <= kTrailSurrogateEnd && to >= kLeadSurrogateStart) return true;
  }
  return false;
}

2244
bool RegExpBuilder::NeedsDesugaringForIgnoreCase(base::uc32 c) {
2245
#ifdef V8_INTL_SUPPORT
2246
  if (unicode() && ignore_case()) {
2247 2248 2249 2250
    icu::UnicodeSet set(c, c);
    set.closeOver(USET_CASE_INSENSITIVE);
    set.removeAllStrings();
    return set.size() > 1;
2251 2252 2253
  }
  // In the case where ICU is not included, we act as if the unicode flag is
  // not set, and do not desugar.
2254
#endif  // V8_INTL_SUPPORT
2255 2256 2257
  return false;
}

2258 2259
RegExpTree* RegExpBuilder::ToRegExp() {
  FlushTerms();
2260
  size_t num_alternatives = alternatives_.size();
2261
  if (num_alternatives == 0) return zone()->New<RegExpEmpty>();
2262 2263 2264
  if (num_alternatives == 1) return alternatives_.back();
  return zone()->New<RegExpDisjunction>(zone()->New<ZoneList<RegExpTree*>>(
      base::VectorOf(alternatives_.begin(), alternatives_.size()), zone()));
2265 2266
}

2267
bool RegExpBuilder::AddQuantifierToAtom(
2268
    int min, int max, RegExpQuantifier::QuantifierType quantifier_type) {
2269
  FlushPendingSurrogate();
2270 2271
  if (pending_empty_) {
    pending_empty_ = false;
2272
    return true;
2273 2274
  }
  RegExpTree* atom;
2275
  if (characters_ != nullptr) {
2276 2277
    DCHECK(last_added_ == ADD_CHAR);
    // Last atom was character.
2278
    base::Vector<const base::uc16> char_vector = characters_->ToConstVector();
2279 2280
    int num_chars = char_vector.length();
    if (num_chars > 1) {
2281 2282
      base::Vector<const base::uc16> prefix =
          char_vector.SubVector(0, num_chars - 1);
2283
      text_.emplace_back(zone()->New<RegExpAtom>(prefix));
2284 2285
      char_vector = char_vector.SubVector(num_chars - 1, num_chars);
    }
2286
    characters_ = nullptr;
2287
    atom = zone()->New<RegExpAtom>(char_vector);
2288
    FlushText();
2289
  } else if (text_.size() > 0) {
2290
    DCHECK(last_added_ == ADD_ATOM);
2291 2292
    atom = text_.back();
    text_.pop_back();
2293
    FlushText();
2294
  } else if (terms_.size() > 0) {
2295
    DCHECK(last_added_ == ADD_ATOM);
2296 2297
    atom = terms_.back();
    terms_.pop_back();
2298 2299 2300 2301 2302 2303 2304 2305
    if (atom->IsLookaround()) {
      // With /u, lookarounds are not quantifiable.
      if (unicode()) return false;
      // Lookbehinds are not quantifiable.
      if (atom->AsLookaround()->type() == RegExpLookaround::LOOKBEHIND) {
        return false;
      }
    }
2306 2307 2308 2309
    if (atom->max_match() == 0) {
      // Guaranteed to only match an empty string.
      LAST(ADD_TERM);
      if (min == 0) {
2310
        return true;
2311
      }
2312
      terms_.emplace_back(atom);
2313
      return true;
2314 2315 2316 2317 2318
    }
  } else {
    // Only call immediately after adding an atom or character!
    UNREACHABLE();
  }
2319 2320
  terms_.emplace_back(
      zone()->New<RegExpQuantifier>(min, max, quantifier_type, atom));
2321
  LAST(ADD_TERM);
2322
  return true;
2323 2324
}

2325 2326 2327 2328 2329 2330 2331 2332
template class RegExpParserImpl<uint8_t>;
template class RegExpParserImpl<base::uc16>;

}  // namespace

// static
bool RegExpParser::ParseRegExpFromHeapString(Isolate* isolate, Zone* zone,
                                             Handle<String> input,
2333
                                             RegExpFlags flags,
2334 2335
                                             RegExpCompileData* result) {
  DisallowGarbageCollection no_gc;
2336
  uintptr_t stack_limit = isolate->stack_guard()->real_climit();
2337 2338 2339
  String::FlatContent content = input->GetFlatContent(no_gc);
  if (content.IsOneByte()) {
    base::Vector<const uint8_t> v = content.ToOneByteVector();
2340 2341
    return RegExpParserImpl<uint8_t>{v.begin(),   v.length(), flags,
                                     stack_limit, zone,       no_gc}
2342 2343 2344
        .Parse(result);
  } else {
    base::Vector<const base::uc16> v = content.ToUC16Vector();
2345 2346
    return RegExpParserImpl<base::uc16>{v.begin(),   v.length(), flags,
                                        stack_limit, zone,       no_gc}
2347 2348 2349 2350
        .Parse(result);
  }
}

2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
// static
template <class CharT>
bool RegExpParser::VerifyRegExpSyntax(Zone* zone, uintptr_t stack_limit,
                                      const CharT* input, int input_length,
                                      RegExpFlags flags,
                                      RegExpCompileData* result,
                                      const DisallowGarbageCollection& no_gc) {
  return RegExpParserImpl<CharT>{input,       input_length, flags,
                                 stack_limit, zone,         no_gc}
      .Parse(result);
}

template bool RegExpParser::VerifyRegExpSyntax<uint8_t>(
    Zone*, uintptr_t, const uint8_t*, int, RegExpFlags, RegExpCompileData*,
    const DisallowGarbageCollection&);
template bool RegExpParser::VerifyRegExpSyntax<base::uc16>(
    Zone*, uintptr_t, const base::uc16*, int, RegExpFlags, RegExpCompileData*,
    const DisallowGarbageCollection&);

2370 2371
// static
bool RegExpParser::VerifyRegExpSyntax(Isolate* isolate, Zone* zone,
2372
                                      Handle<String> input, RegExpFlags flags,
2373 2374 2375 2376 2377
                                      RegExpCompileData* result,
                                      const DisallowGarbageCollection&) {
  return ParseRegExpFromHeapString(isolate, zone, input, flags, result);
}

2378 2379
#undef LAST

2380 2381
}  // namespace internal
}  // namespace v8