Home | History | Annotate | Download | only in src
      1 // Copyright 2006-2008 the V8 project authors. All rights reserved.
      2 // Redistribution and use in source and binary forms, with or without
      3 // modification, are permitted provided that the following conditions are
      4 // met:
      5 //
      6 //     * Redistributions of source code must retain the above copyright
      7 //       notice, this list of conditions and the following disclaimer.
      8 //     * Redistributions in binary form must reproduce the above
      9 //       copyright notice, this list of conditions and the following
     10 //       disclaimer in the documentation and/or other materials provided
     11 //       with the distribution.
     12 //     * Neither the name of Google Inc. nor the names of its
     13 //       contributors may be used to endorse or promote products derived
     14 //       from this software without specific prior written permission.
     15 //
     16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27 
     28 #ifndef V8_JSREGEXP_H_
     29 #define V8_JSREGEXP_H_
     30 
     31 #include "macro-assembler.h"
     32 #include "zone-inl.h"
     33 
     34 namespace v8 {
     35 namespace internal {
     36 
     37 
     38 class RegExpMacroAssembler;
     39 
     40 
     41 class RegExpImpl {
     42  public:
     43   // Whether V8 is compiled with native regexp support or not.
     44   static bool UsesNativeRegExp() {
     45 #ifdef V8_INTERPRETED_REGEXP
     46     return false;
     47 #else
     48     return true;
     49 #endif
     50   }
     51 
     52   // Creates a regular expression literal in the old space.
     53   // This function calls the garbage collector if necessary.
     54   static Handle<Object> CreateRegExpLiteral(Handle<JSFunction> constructor,
     55                                             Handle<String> pattern,
     56                                             Handle<String> flags,
     57                                             bool* has_pending_exception);
     58 
     59   // Returns a string representation of a regular expression.
     60   // Implements RegExp.prototype.toString, see ECMA-262 section 15.10.6.4.
     61   // This function calls the garbage collector if necessary.
     62   static Handle<String> ToString(Handle<Object> value);
     63 
     64   // Parses the RegExp pattern and prepares the JSRegExp object with
     65   // generic data and choice of implementation - as well as what
     66   // the implementation wants to store in the data field.
     67   // Returns false if compilation fails.
     68   static Handle<Object> Compile(Handle<JSRegExp> re,
     69                                 Handle<String> pattern,
     70                                 Handle<String> flags);
     71 
     72   // See ECMA-262 section 15.10.6.2.
     73   // This function calls the garbage collector if necessary.
     74   static Handle<Object> Exec(Handle<JSRegExp> regexp,
     75                              Handle<String> subject,
     76                              int index,
     77                              Handle<JSArray> lastMatchInfo);
     78 
     79   // Prepares a JSRegExp object with Irregexp-specific data.
     80   static void IrregexpInitialize(Handle<JSRegExp> re,
     81                                  Handle<String> pattern,
     82                                  JSRegExp::Flags flags,
     83                                  int capture_register_count);
     84 
     85 
     86   static void AtomCompile(Handle<JSRegExp> re,
     87                           Handle<String> pattern,
     88                           JSRegExp::Flags flags,
     89                           Handle<String> match_pattern);
     90 
     91   static Handle<Object> AtomExec(Handle<JSRegExp> regexp,
     92                                  Handle<String> subject,
     93                                  int index,
     94                                  Handle<JSArray> lastMatchInfo);
     95 
     96   enum IrregexpResult { RE_FAILURE = 0, RE_SUCCESS = 1, RE_EXCEPTION = -1 };
     97 
     98   // Prepare a RegExp for being executed one or more times (using
     99   // IrregexpExecOnce) on the subject.
    100   // This ensures that the regexp is compiled for the subject, and that
    101   // the subject is flat.
    102   // Returns the number of integer spaces required by IrregexpExecOnce
    103   // as its "registers" argument. If the regexp cannot be compiled,
    104   // an exception is set as pending, and this function returns negative.
    105   static int IrregexpPrepare(Handle<JSRegExp> regexp,
    106                              Handle<String> subject);
    107 
    108   // Execute a regular expression once on the subject, starting from
    109   // character "index".
    110   // If successful, returns RE_SUCCESS and set the capture positions
    111   // in the first registers.
    112   // If matching fails, returns RE_FAILURE.
    113   // If execution fails, sets a pending exception and returns RE_EXCEPTION.
    114   static IrregexpResult IrregexpExecOnce(Handle<JSRegExp> regexp,
    115                                          Handle<String> subject,
    116                                          int index,
    117                                          Vector<int> registers);
    118 
    119   // Execute an Irregexp bytecode pattern.
    120   // On a successful match, the result is a JSArray containing
    121   // captured positions. On a failure, the result is the null value.
    122   // Returns an empty handle in case of an exception.
    123   static Handle<Object> IrregexpExec(Handle<JSRegExp> regexp,
    124                                      Handle<String> subject,
    125                                      int index,
    126                                      Handle<JSArray> lastMatchInfo);
    127 
    128   // Array index in the lastMatchInfo array.
    129   static const int kLastCaptureCount = 0;
    130   static const int kLastSubject = 1;
    131   static const int kLastInput = 2;
    132   static const int kFirstCapture = 3;
    133   static const int kLastMatchOverhead = 3;
    134 
    135   // Direct offset into the lastMatchInfo array.
    136   static const int kLastCaptureCountOffset =
    137       FixedArray::kHeaderSize + kLastCaptureCount * kPointerSize;
    138   static const int kLastSubjectOffset =
    139       FixedArray::kHeaderSize + kLastSubject * kPointerSize;
    140   static const int kLastInputOffset =
    141       FixedArray::kHeaderSize + kLastInput * kPointerSize;
    142   static const int kFirstCaptureOffset =
    143       FixedArray::kHeaderSize + kFirstCapture * kPointerSize;
    144 
    145   // Used to access the lastMatchInfo array.
    146   static int GetCapture(FixedArray* array, int index) {
    147     return Smi::cast(array->get(index + kFirstCapture))->value();
    148   }
    149 
    150   static void SetLastCaptureCount(FixedArray* array, int to) {
    151     array->set(kLastCaptureCount, Smi::FromInt(to));
    152   }
    153 
    154   static void SetLastSubject(FixedArray* array, String* to) {
    155     array->set(kLastSubject, to);
    156   }
    157 
    158   static void SetLastInput(FixedArray* array, String* to) {
    159     array->set(kLastInput, to);
    160   }
    161 
    162   static void SetCapture(FixedArray* array, int index, int to) {
    163     array->set(index + kFirstCapture, Smi::FromInt(to));
    164   }
    165 
    166   static int GetLastCaptureCount(FixedArray* array) {
    167     return Smi::cast(array->get(kLastCaptureCount))->value();
    168   }
    169 
    170   // For acting on the JSRegExp data FixedArray.
    171   static int IrregexpMaxRegisterCount(FixedArray* re);
    172   static void SetIrregexpMaxRegisterCount(FixedArray* re, int value);
    173   static int IrregexpNumberOfCaptures(FixedArray* re);
    174   static int IrregexpNumberOfRegisters(FixedArray* re);
    175   static ByteArray* IrregexpByteCode(FixedArray* re, bool is_ascii);
    176   static Code* IrregexpNativeCode(FixedArray* re, bool is_ascii);
    177 
    178   // Limit the space regexps take up on the heap.  In order to limit this we
    179   // would like to keep track of the amount of regexp code on the heap.  This
    180   // is not tracked, however.  As a conservative approximation we track the
    181   // total regexp code compiled including code that has subsequently been freed
    182   // and the total executable memory at any point.
    183   static const int kRegExpExecutableMemoryLimit = 16 * MB;
    184   static const int kRegWxpCompiledLimit = 1 * MB;
    185 
    186  private:
    187   static String* last_ascii_string_;
    188   static String* two_byte_cached_string_;
    189 
    190   static bool CompileIrregexp(Handle<JSRegExp> re, bool is_ascii);
    191   static inline bool EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii);
    192 
    193 
    194   // Set the subject cache.  The previous string buffer is not deleted, so the
    195   // caller should ensure that it doesn't leak.
    196   static void SetSubjectCache(String* subject,
    197                               char* utf8_subject,
    198                               int uft8_length,
    199                               int character_position,
    200                               int utf8_position);
    201 
    202   // A one element cache of the last utf8_subject string and its length.  The
    203   // subject JS String object is cached in the heap.  We also cache a
    204   // translation between position and utf8 position.
    205   static char* utf8_subject_cache_;
    206   static int utf8_length_cache_;
    207   static int utf8_position_;
    208   static int character_position_;
    209 };
    210 
    211 
    212 // Represents the location of one element relative to the intersection of
    213 // two sets. Corresponds to the four areas of a Venn diagram.
    214 enum ElementInSetsRelation {
    215   kInsideNone = 0,
    216   kInsideFirst = 1,
    217   kInsideSecond = 2,
    218   kInsideBoth = 3
    219 };
    220 
    221 
    222 // Represents the relation of two sets.
    223 // Sets can be either disjoint, partially or fully overlapping, or equal.
    224 class SetRelation BASE_EMBEDDED {
    225  public:
    226   // Relation is represented by a bit saying whether there are elements in
    227   // one set that is not in the other, and a bit saying that there are elements
    228   // that are in both sets.
    229 
    230   // Location of an element. Corresponds to the internal areas of
    231   // a Venn diagram.
    232   enum {
    233     kInFirst = 1 << kInsideFirst,
    234     kInSecond = 1 << kInsideSecond,
    235     kInBoth = 1 << kInsideBoth
    236   };
    237   SetRelation() : bits_(0) {}
    238   ~SetRelation() {}
    239   // Add the existence of objects in a particular
    240   void SetElementsInFirstSet() { bits_ |= kInFirst; }
    241   void SetElementsInSecondSet() { bits_ |= kInSecond; }
    242   void SetElementsInBothSets() { bits_ |= kInBoth; }
    243   // Check the currently known relation of the sets (common functions only,
    244   // for other combinations, use value() to get the bits and check them
    245   // manually).
    246   // Sets are completely disjoint.
    247   bool Disjoint() { return (bits_ & kInBoth) == 0; }
    248   // Sets are equal.
    249   bool Equals() { return (bits_ & (kInFirst | kInSecond)) == 0; }
    250   // First set contains second.
    251   bool Contains() { return (bits_ & kInSecond) == 0; }
    252   // Second set contains first.
    253   bool ContainedIn() { return (bits_ & kInFirst) == 0; }
    254   bool NonTrivialIntersection() {
    255     return (bits_ == (kInFirst | kInSecond | kInBoth));
    256   }
    257   int value() { return bits_; }
    258  private:
    259   int bits_;
    260 };
    261 
    262 
    263 class CharacterRange {
    264  public:
    265   CharacterRange() : from_(0), to_(0) { }
    266   // For compatibility with the CHECK_OK macro
    267   CharacterRange(void* null) { ASSERT_EQ(NULL, null); }  //NOLINT
    268   CharacterRange(uc16 from, uc16 to) : from_(from), to_(to) { }
    269   static void AddClassEscape(uc16 type, ZoneList<CharacterRange>* ranges);
    270   static Vector<const uc16> GetWordBounds();
    271   static inline CharacterRange Singleton(uc16 value) {
    272     return CharacterRange(value, value);
    273   }
    274   static inline CharacterRange Range(uc16 from, uc16 to) {
    275     ASSERT(from <= to);
    276     return CharacterRange(from, to);
    277   }
    278   static inline CharacterRange Everything() {
    279     return CharacterRange(0, 0xFFFF);
    280   }
    281   bool Contains(uc16 i) { return from_ <= i && i <= to_; }
    282   uc16 from() const { return from_; }
    283   void set_from(uc16 value) { from_ = value; }
    284   uc16 to() const { return to_; }
    285   void set_to(uc16 value) { to_ = value; }
    286   bool is_valid() { return from_ <= to_; }
    287   bool IsEverything(uc16 max) { return from_ == 0 && to_ >= max; }
    288   bool IsSingleton() { return (from_ == to_); }
    289   void AddCaseEquivalents(ZoneList<CharacterRange>* ranges, bool is_ascii);
    290   static void Split(ZoneList<CharacterRange>* base,
    291                     Vector<const uc16> overlay,
    292                     ZoneList<CharacterRange>** included,
    293                     ZoneList<CharacterRange>** excluded);
    294   // Whether a range list is in canonical form: Ranges ordered by from value,
    295   // and ranges non-overlapping and non-adjacent.
    296   static bool IsCanonical(ZoneList<CharacterRange>* ranges);
    297   // Convert range list to canonical form. The characters covered by the ranges
    298   // will still be the same, but no character is in more than one range, and
    299   // adjacent ranges are merged. The resulting list may be shorter than the
    300   // original, but cannot be longer.
    301   static void Canonicalize(ZoneList<CharacterRange>* ranges);
    302   // Check how the set of characters defined by a CharacterRange list relates
    303   // to the set of word characters. List must be in canonical form.
    304   static SetRelation WordCharacterRelation(ZoneList<CharacterRange>* ranges);
    305   // Takes two character range lists (representing character sets) in canonical
    306   // form and merges them.
    307   // The characters that are only covered by the first set are added to
    308   // first_set_only_out. the characters that are only in the second set are
    309   // added to second_set_only_out, and the characters that are in both are
    310   // added to both_sets_out.
    311   // The pointers to first_set_only_out, second_set_only_out and both_sets_out
    312   // should be to empty lists, but they need not be distinct, and may be NULL.
    313   // If NULL, the characters are dropped, and if two arguments are the same
    314   // pointer, the result is the union of the two sets that would be created
    315   // if the pointers had been distinct.
    316   // This way, the Merge function can compute all the usual set operations:
    317   // union (all three out-sets are equal), intersection (only both_sets_out is
    318   // non-NULL), and set difference (only first_set is non-NULL).
    319   static void Merge(ZoneList<CharacterRange>* first_set,
    320                     ZoneList<CharacterRange>* second_set,
    321                     ZoneList<CharacterRange>* first_set_only_out,
    322                     ZoneList<CharacterRange>* second_set_only_out,
    323                     ZoneList<CharacterRange>* both_sets_out);
    324   // Negate the contents of a character range in canonical form.
    325   static void Negate(ZoneList<CharacterRange>* src,
    326                      ZoneList<CharacterRange>* dst);
    327   static const int kStartMarker = (1 << 24);
    328   static const int kPayloadMask = (1 << 24) - 1;
    329 
    330  private:
    331   uc16 from_;
    332   uc16 to_;
    333 };
    334 
    335 
    336 // A set of unsigned integers that behaves especially well on small
    337 // integers (< 32).  May do zone-allocation.
    338 class OutSet: public ZoneObject {
    339  public:
    340   OutSet() : first_(0), remaining_(NULL), successors_(NULL) { }
    341   OutSet* Extend(unsigned value);
    342   bool Get(unsigned value);
    343   static const unsigned kFirstLimit = 32;
    344 
    345  private:
    346   // Destructively set a value in this set.  In most cases you want
    347   // to use Extend instead to ensure that only one instance exists
    348   // that contains the same values.
    349   void Set(unsigned value);
    350 
    351   // The successors are a list of sets that contain the same values
    352   // as this set and the one more value that is not present in this
    353   // set.
    354   ZoneList<OutSet*>* successors() { return successors_; }
    355 
    356   OutSet(uint32_t first, ZoneList<unsigned>* remaining)
    357       : first_(first), remaining_(remaining), successors_(NULL) { }
    358   uint32_t first_;
    359   ZoneList<unsigned>* remaining_;
    360   ZoneList<OutSet*>* successors_;
    361   friend class Trace;
    362 };
    363 
    364 
    365 // A mapping from integers, specified as ranges, to a set of integers.
    366 // Used for mapping character ranges to choices.
    367 class DispatchTable : public ZoneObject {
    368  public:
    369   class Entry {
    370    public:
    371     Entry() : from_(0), to_(0), out_set_(NULL) { }
    372     Entry(uc16 from, uc16 to, OutSet* out_set)
    373         : from_(from), to_(to), out_set_(out_set) { }
    374     uc16 from() { return from_; }
    375     uc16 to() { return to_; }
    376     void set_to(uc16 value) { to_ = value; }
    377     void AddValue(int value) { out_set_ = out_set_->Extend(value); }
    378     OutSet* out_set() { return out_set_; }
    379    private:
    380     uc16 from_;
    381     uc16 to_;
    382     OutSet* out_set_;
    383   };
    384 
    385   class Config {
    386    public:
    387     typedef uc16 Key;
    388     typedef Entry Value;
    389     static const uc16 kNoKey;
    390     static const Entry kNoValue;
    391     static inline int Compare(uc16 a, uc16 b) {
    392       if (a == b)
    393         return 0;
    394       else if (a < b)
    395         return -1;
    396       else
    397         return 1;
    398     }
    399   };
    400 
    401   void AddRange(CharacterRange range, int value);
    402   OutSet* Get(uc16 value);
    403   void Dump();
    404 
    405   template <typename Callback>
    406   void ForEach(Callback* callback) { return tree()->ForEach(callback); }
    407  private:
    408   // There can't be a static empty set since it allocates its
    409   // successors in a zone and caches them.
    410   OutSet* empty() { return &empty_; }
    411   OutSet empty_;
    412   ZoneSplayTree<Config>* tree() { return &tree_; }
    413   ZoneSplayTree<Config> tree_;
    414 };
    415 
    416 
    417 #define FOR_EACH_NODE_TYPE(VISIT)                                    \
    418   VISIT(End)                                                         \
    419   VISIT(Action)                                                      \
    420   VISIT(Choice)                                                      \
    421   VISIT(BackReference)                                               \
    422   VISIT(Assertion)                                                   \
    423   VISIT(Text)
    424 
    425 
    426 #define FOR_EACH_REG_EXP_TREE_TYPE(VISIT)                            \
    427   VISIT(Disjunction)                                                 \
    428   VISIT(Alternative)                                                 \
    429   VISIT(Assertion)                                                   \
    430   VISIT(CharacterClass)                                              \
    431   VISIT(Atom)                                                        \
    432   VISIT(Quantifier)                                                  \
    433   VISIT(Capture)                                                     \
    434   VISIT(Lookahead)                                                   \
    435   VISIT(BackReference)                                               \
    436   VISIT(Empty)                                                       \
    437   VISIT(Text)
    438 
    439 
    440 #define FORWARD_DECLARE(Name) class RegExp##Name;
    441 FOR_EACH_REG_EXP_TREE_TYPE(FORWARD_DECLARE)
    442 #undef FORWARD_DECLARE
    443 
    444 
    445 class TextElement {
    446  public:
    447   enum Type {UNINITIALIZED, ATOM, CHAR_CLASS};
    448   TextElement() : type(UNINITIALIZED) { }
    449   explicit TextElement(Type t) : type(t), cp_offset(-1) { }
    450   static TextElement Atom(RegExpAtom* atom);
    451   static TextElement CharClass(RegExpCharacterClass* char_class);
    452   int length();
    453   Type type;
    454   union {
    455     RegExpAtom* u_atom;
    456     RegExpCharacterClass* u_char_class;
    457   } data;
    458   int cp_offset;
    459 };
    460 
    461 
    462 class Trace;
    463 
    464 
    465 struct NodeInfo {
    466   NodeInfo()
    467       : being_analyzed(false),
    468         been_analyzed(false),
    469         follows_word_interest(false),
    470         follows_newline_interest(false),
    471         follows_start_interest(false),
    472         at_end(false),
    473         visited(false) { }
    474 
    475   // Returns true if the interests and assumptions of this node
    476   // matches the given one.
    477   bool Matches(NodeInfo* that) {
    478     return (at_end == that->at_end) &&
    479            (follows_word_interest == that->follows_word_interest) &&
    480            (follows_newline_interest == that->follows_newline_interest) &&
    481            (follows_start_interest == that->follows_start_interest);
    482   }
    483 
    484   // Updates the interests of this node given the interests of the
    485   // node preceding it.
    486   void AddFromPreceding(NodeInfo* that) {
    487     at_end |= that->at_end;
    488     follows_word_interest |= that->follows_word_interest;
    489     follows_newline_interest |= that->follows_newline_interest;
    490     follows_start_interest |= that->follows_start_interest;
    491   }
    492 
    493   bool HasLookbehind() {
    494     return follows_word_interest ||
    495            follows_newline_interest ||
    496            follows_start_interest;
    497   }
    498 
    499   // Sets the interests of this node to include the interests of the
    500   // following node.
    501   void AddFromFollowing(NodeInfo* that) {
    502     follows_word_interest |= that->follows_word_interest;
    503     follows_newline_interest |= that->follows_newline_interest;
    504     follows_start_interest |= that->follows_start_interest;
    505   }
    506 
    507   void ResetCompilationState() {
    508     being_analyzed = false;
    509     been_analyzed = false;
    510   }
    511 
    512   bool being_analyzed: 1;
    513   bool been_analyzed: 1;
    514 
    515   // These bits are set of this node has to know what the preceding
    516   // character was.
    517   bool follows_word_interest: 1;
    518   bool follows_newline_interest: 1;
    519   bool follows_start_interest: 1;
    520 
    521   bool at_end: 1;
    522   bool visited: 1;
    523 };
    524 
    525 
    526 class SiblingList {
    527  public:
    528   SiblingList() : list_(NULL) { }
    529   int length() {
    530     return list_ == NULL ? 0 : list_->length();
    531   }
    532   void Ensure(RegExpNode* parent) {
    533     if (list_ == NULL) {
    534       list_ = new ZoneList<RegExpNode*>(2);
    535       list_->Add(parent);
    536     }
    537   }
    538   void Add(RegExpNode* node) { list_->Add(node); }
    539   RegExpNode* Get(int index) { return list_->at(index); }
    540  private:
    541   ZoneList<RegExpNode*>* list_;
    542 };
    543 
    544 
    545 // Details of a quick mask-compare check that can look ahead in the
    546 // input stream.
    547 class QuickCheckDetails {
    548  public:
    549   QuickCheckDetails()
    550       : characters_(0),
    551         mask_(0),
    552         value_(0),
    553         cannot_match_(false) { }
    554   explicit QuickCheckDetails(int characters)
    555       : characters_(characters),
    556         mask_(0),
    557         value_(0),
    558         cannot_match_(false) { }
    559   bool Rationalize(bool ascii);
    560   // Merge in the information from another branch of an alternation.
    561   void Merge(QuickCheckDetails* other, int from_index);
    562   // Advance the current position by some amount.
    563   void Advance(int by, bool ascii);
    564   void Clear();
    565   bool cannot_match() { return cannot_match_; }
    566   void set_cannot_match() { cannot_match_ = true; }
    567   struct Position {
    568     Position() : mask(0), value(0), determines_perfectly(false) { }
    569     uc16 mask;
    570     uc16 value;
    571     bool determines_perfectly;
    572   };
    573   int characters() { return characters_; }
    574   void set_characters(int characters) { characters_ = characters; }
    575   Position* positions(int index) {
    576     ASSERT(index >= 0);
    577     ASSERT(index < characters_);
    578     return positions_ + index;
    579   }
    580   uint32_t mask() { return mask_; }
    581   uint32_t value() { return value_; }
    582 
    583  private:
    584   // How many characters do we have quick check information from.  This is
    585   // the same for all branches of a choice node.
    586   int characters_;
    587   Position positions_[4];
    588   // These values are the condensate of the above array after Rationalize().
    589   uint32_t mask_;
    590   uint32_t value_;
    591   // If set to true, there is no way this quick check can match at all.
    592   // E.g., if it requires to be at the start of the input, and isn't.
    593   bool cannot_match_;
    594 };
    595 
    596 
    597 class RegExpNode: public ZoneObject {
    598  public:
    599   RegExpNode() : first_character_set_(NULL), trace_count_(0) { }
    600   virtual ~RegExpNode();
    601   virtual void Accept(NodeVisitor* visitor) = 0;
    602   // Generates a goto to this node or actually generates the code at this point.
    603   virtual void Emit(RegExpCompiler* compiler, Trace* trace) = 0;
    604   // How many characters must this node consume at a minimum in order to
    605   // succeed.  If we have found at least 'still_to_find' characters that
    606   // must be consumed there is no need to ask any following nodes whether
    607   // they are sure to eat any more characters.  The not_at_start argument is
    608   // used to indicate that we know we are not at the start of the input.  In
    609   // this case anchored branches will always fail and can be ignored when
    610   // determining how many characters are consumed on success.
    611   virtual int EatsAtLeast(int still_to_find,
    612                           int recursion_depth,
    613                           bool not_at_start) = 0;
    614   // Emits some quick code that checks whether the preloaded characters match.
    615   // Falls through on certain failure, jumps to the label on possible success.
    616   // If the node cannot make a quick check it does nothing and returns false.
    617   bool EmitQuickCheck(RegExpCompiler* compiler,
    618                       Trace* trace,
    619                       bool preload_has_checked_bounds,
    620                       Label* on_possible_success,
    621                       QuickCheckDetails* details_return,
    622                       bool fall_through_on_failure);
    623   // For a given number of characters this returns a mask and a value.  The
    624   // next n characters are anded with the mask and compared with the value.
    625   // A comparison failure indicates the node cannot match the next n characters.
    626   // A comparison success indicates the node may match.
    627   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
    628                                     RegExpCompiler* compiler,
    629                                     int characters_filled_in,
    630                                     bool not_at_start) = 0;
    631   static const int kNodeIsTooComplexForGreedyLoops = -1;
    632   virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
    633   Label* label() { return &label_; }
    634   // If non-generic code is generated for a node (ie the node is not at the
    635   // start of the trace) then it cannot be reused.  This variable sets a limit
    636   // on how often we allow that to happen before we insist on starting a new
    637   // trace and generating generic code for a node that can be reused by flushing
    638   // the deferred actions in the current trace and generating a goto.
    639   static const int kMaxCopiesCodeGenerated = 10;
    640 
    641   NodeInfo* info() { return &info_; }
    642 
    643   void AddSibling(RegExpNode* node) { siblings_.Add(node); }
    644 
    645   // Static version of EnsureSibling that expresses the fact that the
    646   // result has the same type as the input.
    647   template <class C>
    648   static C* EnsureSibling(C* node, NodeInfo* info, bool* cloned) {
    649     return static_cast<C*>(node->EnsureSibling(info, cloned));
    650   }
    651 
    652   SiblingList* siblings() { return &siblings_; }
    653   void set_siblings(SiblingList* other) { siblings_ = *other; }
    654 
    655   // Return the set of possible next characters recognized by the regexp
    656   // (or a safe subset, potentially the set of all characters).
    657   ZoneList<CharacterRange>* FirstCharacterSet();
    658 
    659   // Compute (if possible within the budget of traversed nodes) the
    660   // possible first characters of the input matched by this node and
    661   // its continuation. Returns the remaining budget after the computation.
    662   // If the budget is spent, the result is negative, and the cached
    663   // first_character_set_ value isn't set.
    664   virtual int ComputeFirstCharacterSet(int budget);
    665 
    666   // Get and set the cached first character set value.
    667   ZoneList<CharacterRange>* first_character_set() {
    668     return first_character_set_;
    669   }
    670   void set_first_character_set(ZoneList<CharacterRange>* character_set) {
    671     first_character_set_ = character_set;
    672   }
    673 
    674  protected:
    675   enum LimitResult { DONE, CONTINUE };
    676   static const int kComputeFirstCharacterSetFail = -1;
    677 
    678   LimitResult LimitVersions(RegExpCompiler* compiler, Trace* trace);
    679 
    680   // Returns a sibling of this node whose interests and assumptions
    681   // match the ones in the given node info.  If no sibling exists NULL
    682   // is returned.
    683   RegExpNode* TryGetSibling(NodeInfo* info);
    684 
    685   // Returns a sibling of this node whose interests match the ones in
    686   // the given node info.  The info must not contain any assertions.
    687   // If no node exists a new one will be created by cloning the current
    688   // node.  The result will always be an instance of the same concrete
    689   // class as this node.
    690   RegExpNode* EnsureSibling(NodeInfo* info, bool* cloned);
    691 
    692   // Returns a clone of this node initialized using the copy constructor
    693   // of its concrete class.  Note that the node may have to be pre-
    694   // processed before it is on a usable state.
    695   virtual RegExpNode* Clone() = 0;
    696 
    697  private:
    698   static const int kFirstCharBudget = 10;
    699   Label label_;
    700   NodeInfo info_;
    701   SiblingList siblings_;
    702   ZoneList<CharacterRange>* first_character_set_;
    703   // This variable keeps track of how many times code has been generated for
    704   // this node (in different traces).  We don't keep track of where the
    705   // generated code is located unless the code is generated at the start of
    706   // a trace, in which case it is generic and can be reused by flushing the
    707   // deferred operations in the current trace and generating a goto.
    708   int trace_count_;
    709 };
    710 
    711 
    712 // A simple closed interval.
    713 class Interval {
    714  public:
    715   Interval() : from_(kNone), to_(kNone) { }
    716   Interval(int from, int to) : from_(from), to_(to) { }
    717   Interval Union(Interval that) {
    718     if (that.from_ == kNone)
    719       return *this;
    720     else if (from_ == kNone)
    721       return that;
    722     else
    723       return Interval(Min(from_, that.from_), Max(to_, that.to_));
    724   }
    725   bool Contains(int value) {
    726     return (from_ <= value) && (value <= to_);
    727   }
    728   bool is_empty() { return from_ == kNone; }
    729   int from() { return from_; }
    730   int to() { return to_; }
    731   static Interval Empty() { return Interval(); }
    732   static const int kNone = -1;
    733  private:
    734   int from_;
    735   int to_;
    736 };
    737 
    738 
    739 class SeqRegExpNode: public RegExpNode {
    740  public:
    741   explicit SeqRegExpNode(RegExpNode* on_success)
    742       : on_success_(on_success) { }
    743   RegExpNode* on_success() { return on_success_; }
    744   void set_on_success(RegExpNode* node) { on_success_ = node; }
    745  private:
    746   RegExpNode* on_success_;
    747 };
    748 
    749 
    750 class ActionNode: public SeqRegExpNode {
    751  public:
    752   enum Type {
    753     SET_REGISTER,
    754     INCREMENT_REGISTER,
    755     STORE_POSITION,
    756     BEGIN_SUBMATCH,
    757     POSITIVE_SUBMATCH_SUCCESS,
    758     EMPTY_MATCH_CHECK,
    759     CLEAR_CAPTURES
    760   };
    761   static ActionNode* SetRegister(int reg, int val, RegExpNode* on_success);
    762   static ActionNode* IncrementRegister(int reg, RegExpNode* on_success);
    763   static ActionNode* StorePosition(int reg,
    764                                    bool is_capture,
    765                                    RegExpNode* on_success);
    766   static ActionNode* ClearCaptures(Interval range, RegExpNode* on_success);
    767   static ActionNode* BeginSubmatch(int stack_pointer_reg,
    768                                    int position_reg,
    769                                    RegExpNode* on_success);
    770   static ActionNode* PositiveSubmatchSuccess(int stack_pointer_reg,
    771                                              int restore_reg,
    772                                              int clear_capture_count,
    773                                              int clear_capture_from,
    774                                              RegExpNode* on_success);
    775   static ActionNode* EmptyMatchCheck(int start_register,
    776                                      int repetition_register,
    777                                      int repetition_limit,
    778                                      RegExpNode* on_success);
    779   virtual void Accept(NodeVisitor* visitor);
    780   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
    781   virtual int EatsAtLeast(int still_to_find,
    782                           int recursion_depth,
    783                           bool not_at_start);
    784   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
    785                                     RegExpCompiler* compiler,
    786                                     int filled_in,
    787                                     bool not_at_start) {
    788     return on_success()->GetQuickCheckDetails(
    789         details, compiler, filled_in, not_at_start);
    790   }
    791   Type type() { return type_; }
    792   // TODO(erikcorry): We should allow some action nodes in greedy loops.
    793   virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
    794   virtual ActionNode* Clone() { return new ActionNode(*this); }
    795   virtual int ComputeFirstCharacterSet(int budget);
    796  private:
    797   union {
    798     struct {
    799       int reg;
    800       int value;
    801     } u_store_register;
    802     struct {
    803       int reg;
    804     } u_increment_register;
    805     struct {
    806       int reg;
    807       bool is_capture;
    808     } u_position_register;
    809     struct {
    810       int stack_pointer_register;
    811       int current_position_register;
    812       int clear_register_count;
    813       int clear_register_from;
    814     } u_submatch;
    815     struct {
    816       int start_register;
    817       int repetition_register;
    818       int repetition_limit;
    819     } u_empty_match_check;
    820     struct {
    821       int range_from;
    822       int range_to;
    823     } u_clear_captures;
    824   } data_;
    825   ActionNode(Type type, RegExpNode* on_success)
    826       : SeqRegExpNode(on_success),
    827         type_(type) { }
    828   Type type_;
    829   friend class DotPrinter;
    830 };
    831 
    832 
    833 class TextNode: public SeqRegExpNode {
    834  public:
    835   TextNode(ZoneList<TextElement>* elms,
    836            RegExpNode* on_success)
    837       : SeqRegExpNode(on_success),
    838         elms_(elms) { }
    839   TextNode(RegExpCharacterClass* that,
    840            RegExpNode* on_success)
    841       : SeqRegExpNode(on_success),
    842         elms_(new ZoneList<TextElement>(1)) {
    843     elms_->Add(TextElement::CharClass(that));
    844   }
    845   virtual void Accept(NodeVisitor* visitor);
    846   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
    847   virtual int EatsAtLeast(int still_to_find,
    848                           int recursion_depth,
    849                           bool not_at_start);
    850   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
    851                                     RegExpCompiler* compiler,
    852                                     int characters_filled_in,
    853                                     bool not_at_start);
    854   ZoneList<TextElement>* elements() { return elms_; }
    855   void MakeCaseIndependent(bool is_ascii);
    856   virtual int GreedyLoopTextLength();
    857   virtual TextNode* Clone() {
    858     TextNode* result = new TextNode(*this);
    859     result->CalculateOffsets();
    860     return result;
    861   }
    862   void CalculateOffsets();
    863   virtual int ComputeFirstCharacterSet(int budget);
    864  private:
    865   enum TextEmitPassType {
    866     NON_ASCII_MATCH,             // Check for characters that can't match.
    867     SIMPLE_CHARACTER_MATCH,      // Case-dependent single character check.
    868     NON_LETTER_CHARACTER_MATCH,  // Check characters that have no case equivs.
    869     CASE_CHARACTER_MATCH,        // Case-independent single character check.
    870     CHARACTER_CLASS_MATCH        // Character class.
    871   };
    872   static bool SkipPass(int pass, bool ignore_case);
    873   static const int kFirstRealPass = SIMPLE_CHARACTER_MATCH;
    874   static const int kLastPass = CHARACTER_CLASS_MATCH;
    875   void TextEmitPass(RegExpCompiler* compiler,
    876                     TextEmitPassType pass,
    877                     bool preloaded,
    878                     Trace* trace,
    879                     bool first_element_checked,
    880                     int* checked_up_to);
    881   int Length();
    882   ZoneList<TextElement>* elms_;
    883 };
    884 
    885 
    886 class AssertionNode: public SeqRegExpNode {
    887  public:
    888   enum AssertionNodeType {
    889     AT_END,
    890     AT_START,
    891     AT_BOUNDARY,
    892     AT_NON_BOUNDARY,
    893     AFTER_NEWLINE,
    894     // Types not directly expressible in regexp syntax.
    895     // Used for modifying a boundary node if its following character is
    896     // known to be word and/or non-word.
    897     AFTER_NONWORD_CHARACTER,
    898     AFTER_WORD_CHARACTER
    899   };
    900   static AssertionNode* AtEnd(RegExpNode* on_success) {
    901     return new AssertionNode(AT_END, on_success);
    902   }
    903   static AssertionNode* AtStart(RegExpNode* on_success) {
    904     return new AssertionNode(AT_START, on_success);
    905   }
    906   static AssertionNode* AtBoundary(RegExpNode* on_success) {
    907     return new AssertionNode(AT_BOUNDARY, on_success);
    908   }
    909   static AssertionNode* AtNonBoundary(RegExpNode* on_success) {
    910     return new AssertionNode(AT_NON_BOUNDARY, on_success);
    911   }
    912   static AssertionNode* AfterNewline(RegExpNode* on_success) {
    913     return new AssertionNode(AFTER_NEWLINE, on_success);
    914   }
    915   virtual void Accept(NodeVisitor* visitor);
    916   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
    917   virtual int EatsAtLeast(int still_to_find,
    918                           int recursion_depth,
    919                           bool not_at_start);
    920   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
    921                                     RegExpCompiler* compiler,
    922                                     int filled_in,
    923                                     bool not_at_start);
    924   virtual int ComputeFirstCharacterSet(int budget);
    925   virtual AssertionNode* Clone() { return new AssertionNode(*this); }
    926   AssertionNodeType type() { return type_; }
    927   void set_type(AssertionNodeType type) { type_ = type; }
    928  private:
    929   AssertionNode(AssertionNodeType t, RegExpNode* on_success)
    930       : SeqRegExpNode(on_success), type_(t) { }
    931   AssertionNodeType type_;
    932 };
    933 
    934 
    935 class BackReferenceNode: public SeqRegExpNode {
    936  public:
    937   BackReferenceNode(int start_reg,
    938                     int end_reg,
    939                     RegExpNode* on_success)
    940       : SeqRegExpNode(on_success),
    941         start_reg_(start_reg),
    942         end_reg_(end_reg) { }
    943   virtual void Accept(NodeVisitor* visitor);
    944   int start_register() { return start_reg_; }
    945   int end_register() { return end_reg_; }
    946   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
    947   virtual int EatsAtLeast(int still_to_find,
    948                           int recursion_depth,
    949                           bool not_at_start);
    950   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
    951                                     RegExpCompiler* compiler,
    952                                     int characters_filled_in,
    953                                     bool not_at_start) {
    954     return;
    955   }
    956   virtual BackReferenceNode* Clone() { return new BackReferenceNode(*this); }
    957   virtual int ComputeFirstCharacterSet(int budget);
    958  private:
    959   int start_reg_;
    960   int end_reg_;
    961 };
    962 
    963 
    964 class EndNode: public RegExpNode {
    965  public:
    966   enum Action { ACCEPT, BACKTRACK, NEGATIVE_SUBMATCH_SUCCESS };
    967   explicit EndNode(Action action) : action_(action) { }
    968   virtual void Accept(NodeVisitor* visitor);
    969   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
    970   virtual int EatsAtLeast(int still_to_find,
    971                           int recursion_depth,
    972                           bool not_at_start) { return 0; }
    973   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
    974                                     RegExpCompiler* compiler,
    975                                     int characters_filled_in,
    976                                     bool not_at_start) {
    977     // Returning 0 from EatsAtLeast should ensure we never get here.
    978     UNREACHABLE();
    979   }
    980   virtual EndNode* Clone() { return new EndNode(*this); }
    981  private:
    982   Action action_;
    983 };
    984 
    985 
    986 class NegativeSubmatchSuccess: public EndNode {
    987  public:
    988   NegativeSubmatchSuccess(int stack_pointer_reg,
    989                           int position_reg,
    990                           int clear_capture_count,
    991                           int clear_capture_start)
    992       : EndNode(NEGATIVE_SUBMATCH_SUCCESS),
    993         stack_pointer_register_(stack_pointer_reg),
    994         current_position_register_(position_reg),
    995         clear_capture_count_(clear_capture_count),
    996         clear_capture_start_(clear_capture_start) { }
    997   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
    998 
    999  private:
   1000   int stack_pointer_register_;
   1001   int current_position_register_;
   1002   int clear_capture_count_;
   1003   int clear_capture_start_;
   1004 };
   1005 
   1006 
   1007 class Guard: public ZoneObject {
   1008  public:
   1009   enum Relation { LT, GEQ };
   1010   Guard(int reg, Relation op, int value)
   1011       : reg_(reg),
   1012         op_(op),
   1013         value_(value) { }
   1014   int reg() { return reg_; }
   1015   Relation op() { return op_; }
   1016   int value() { return value_; }
   1017 
   1018  private:
   1019   int reg_;
   1020   Relation op_;
   1021   int value_;
   1022 };
   1023 
   1024 
   1025 class GuardedAlternative {
   1026  public:
   1027   explicit GuardedAlternative(RegExpNode* node) : node_(node), guards_(NULL) { }
   1028   void AddGuard(Guard* guard);
   1029   RegExpNode* node() { return node_; }
   1030   void set_node(RegExpNode* node) { node_ = node; }
   1031   ZoneList<Guard*>* guards() { return guards_; }
   1032 
   1033  private:
   1034   RegExpNode* node_;
   1035   ZoneList<Guard*>* guards_;
   1036 };
   1037 
   1038 
   1039 class AlternativeGeneration;
   1040 
   1041 
   1042 class ChoiceNode: public RegExpNode {
   1043  public:
   1044   explicit ChoiceNode(int expected_size)
   1045       : alternatives_(new ZoneList<GuardedAlternative>(expected_size)),
   1046         table_(NULL),
   1047         not_at_start_(false),
   1048         being_calculated_(false) { }
   1049   virtual void Accept(NodeVisitor* visitor);
   1050   void AddAlternative(GuardedAlternative node) { alternatives()->Add(node); }
   1051   ZoneList<GuardedAlternative>* alternatives() { return alternatives_; }
   1052   DispatchTable* GetTable(bool ignore_case);
   1053   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
   1054   virtual int EatsAtLeast(int still_to_find,
   1055                           int recursion_depth,
   1056                           bool not_at_start);
   1057   int EatsAtLeastHelper(int still_to_find,
   1058                         int recursion_depth,
   1059                         RegExpNode* ignore_this_node,
   1060                         bool not_at_start);
   1061   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
   1062                                     RegExpCompiler* compiler,
   1063                                     int characters_filled_in,
   1064                                     bool not_at_start);
   1065   virtual ChoiceNode* Clone() { return new ChoiceNode(*this); }
   1066 
   1067   bool being_calculated() { return being_calculated_; }
   1068   bool not_at_start() { return not_at_start_; }
   1069   void set_not_at_start() { not_at_start_ = true; }
   1070   void set_being_calculated(bool b) { being_calculated_ = b; }
   1071   virtual bool try_to_emit_quick_check_for_alternative(int i) { return true; }
   1072 
   1073  protected:
   1074   int GreedyLoopTextLength(GuardedAlternative* alternative);
   1075   ZoneList<GuardedAlternative>* alternatives_;
   1076 
   1077  private:
   1078   friend class DispatchTableConstructor;
   1079   friend class Analysis;
   1080   void GenerateGuard(RegExpMacroAssembler* macro_assembler,
   1081                      Guard* guard,
   1082                      Trace* trace);
   1083   int CalculatePreloadCharacters(RegExpCompiler* compiler, bool not_at_start);
   1084   void EmitOutOfLineContinuation(RegExpCompiler* compiler,
   1085                                  Trace* trace,
   1086                                  GuardedAlternative alternative,
   1087                                  AlternativeGeneration* alt_gen,
   1088                                  int preload_characters,
   1089                                  bool next_expects_preload);
   1090   DispatchTable* table_;
   1091   // If true, this node is never checked at the start of the input.
   1092   // Allows a new trace to start with at_start() set to false.
   1093   bool not_at_start_;
   1094   bool being_calculated_;
   1095 };
   1096 
   1097 
   1098 class NegativeLookaheadChoiceNode: public ChoiceNode {
   1099  public:
   1100   explicit NegativeLookaheadChoiceNode(GuardedAlternative this_must_fail,
   1101                                        GuardedAlternative then_do_this)
   1102       : ChoiceNode(2) {
   1103     AddAlternative(this_must_fail);
   1104     AddAlternative(then_do_this);
   1105   }
   1106   virtual int EatsAtLeast(int still_to_find,
   1107                           int recursion_depth,
   1108                           bool not_at_start);
   1109   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
   1110                                     RegExpCompiler* compiler,
   1111                                     int characters_filled_in,
   1112                                     bool not_at_start);
   1113   // For a negative lookahead we don't emit the quick check for the
   1114   // alternative that is expected to fail.  This is because quick check code
   1115   // starts by loading enough characters for the alternative that takes fewest
   1116   // characters, but on a negative lookahead the negative branch did not take
   1117   // part in that calculation (EatsAtLeast) so the assumptions don't hold.
   1118   virtual bool try_to_emit_quick_check_for_alternative(int i) { return i != 0; }
   1119   virtual int ComputeFirstCharacterSet(int budget);
   1120 };
   1121 
   1122 
   1123 class LoopChoiceNode: public ChoiceNode {
   1124  public:
   1125   explicit LoopChoiceNode(bool body_can_be_zero_length)
   1126       : ChoiceNode(2),
   1127         loop_node_(NULL),
   1128         continue_node_(NULL),
   1129         body_can_be_zero_length_(body_can_be_zero_length) { }
   1130   void AddLoopAlternative(GuardedAlternative alt);
   1131   void AddContinueAlternative(GuardedAlternative alt);
   1132   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
   1133   virtual int EatsAtLeast(int still_to_find,
   1134                           int recursion_depth,
   1135                           bool not_at_start);
   1136   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
   1137                                     RegExpCompiler* compiler,
   1138                                     int characters_filled_in,
   1139                                     bool not_at_start);
   1140   virtual int ComputeFirstCharacterSet(int budget);
   1141   virtual LoopChoiceNode* Clone() { return new LoopChoiceNode(*this); }
   1142   RegExpNode* loop_node() { return loop_node_; }
   1143   RegExpNode* continue_node() { return continue_node_; }
   1144   bool body_can_be_zero_length() { return body_can_be_zero_length_; }
   1145   virtual void Accept(NodeVisitor* visitor);
   1146 
   1147  private:
   1148   // AddAlternative is made private for loop nodes because alternatives
   1149   // should not be added freely, we need to keep track of which node
   1150   // goes back to the node itself.
   1151   void AddAlternative(GuardedAlternative node) {
   1152     ChoiceNode::AddAlternative(node);
   1153   }
   1154 
   1155   RegExpNode* loop_node_;
   1156   RegExpNode* continue_node_;
   1157   bool body_can_be_zero_length_;
   1158 };
   1159 
   1160 
   1161 // There are many ways to generate code for a node.  This class encapsulates
   1162 // the current way we should be generating.  In other words it encapsulates
   1163 // the current state of the code generator.  The effect of this is that we
   1164 // generate code for paths that the matcher can take through the regular
   1165 // expression.  A given node in the regexp can be code-generated several times
   1166 // as it can be part of several traces.  For example for the regexp:
   1167 // /foo(bar|ip)baz/ the code to match baz will be generated twice, once as part
   1168 // of the foo-bar-baz trace and once as part of the foo-ip-baz trace.  The code
   1169 // to match foo is generated only once (the traces have a common prefix).  The
   1170 // code to store the capture is deferred and generated (twice) after the places
   1171 // where baz has been matched.
   1172 class Trace {
   1173  public:
   1174   // A value for a property that is either known to be true, know to be false,
   1175   // or not known.
   1176   enum TriBool {
   1177     UNKNOWN = -1, FALSE = 0, TRUE = 1
   1178   };
   1179 
   1180   class DeferredAction {
   1181    public:
   1182     DeferredAction(ActionNode::Type type, int reg)
   1183         : type_(type), reg_(reg), next_(NULL) { }
   1184     DeferredAction* next() { return next_; }
   1185     bool Mentions(int reg);
   1186     int reg() { return reg_; }
   1187     ActionNode::Type type() { return type_; }
   1188    private:
   1189     ActionNode::Type type_;
   1190     int reg_;
   1191     DeferredAction* next_;
   1192     friend class Trace;
   1193   };
   1194 
   1195   class DeferredCapture : public DeferredAction {
   1196    public:
   1197     DeferredCapture(int reg, bool is_capture, Trace* trace)
   1198         : DeferredAction(ActionNode::STORE_POSITION, reg),
   1199           cp_offset_(trace->cp_offset()),
   1200           is_capture_(is_capture) { }
   1201     int cp_offset() { return cp_offset_; }
   1202     bool is_capture() { return is_capture_; }
   1203    private:
   1204     int cp_offset_;
   1205     bool is_capture_;
   1206     void set_cp_offset(int cp_offset) { cp_offset_ = cp_offset; }
   1207   };
   1208 
   1209   class DeferredSetRegister : public DeferredAction {
   1210    public:
   1211     DeferredSetRegister(int reg, int value)
   1212         : DeferredAction(ActionNode::SET_REGISTER, reg),
   1213           value_(value) { }
   1214     int value() { return value_; }
   1215    private:
   1216     int value_;
   1217   };
   1218 
   1219   class DeferredClearCaptures : public DeferredAction {
   1220    public:
   1221     explicit DeferredClearCaptures(Interval range)
   1222         : DeferredAction(ActionNode::CLEAR_CAPTURES, -1),
   1223           range_(range) { }
   1224     Interval range() { return range_; }
   1225    private:
   1226     Interval range_;
   1227   };
   1228 
   1229   class DeferredIncrementRegister : public DeferredAction {
   1230    public:
   1231     explicit DeferredIncrementRegister(int reg)
   1232         : DeferredAction(ActionNode::INCREMENT_REGISTER, reg) { }
   1233   };
   1234 
   1235   Trace()
   1236       : cp_offset_(0),
   1237         actions_(NULL),
   1238         backtrack_(NULL),
   1239         stop_node_(NULL),
   1240         loop_label_(NULL),
   1241         characters_preloaded_(0),
   1242         bound_checked_up_to_(0),
   1243         flush_budget_(100),
   1244         at_start_(UNKNOWN) { }
   1245 
   1246   // End the trace.  This involves flushing the deferred actions in the trace
   1247   // and pushing a backtrack location onto the backtrack stack.  Once this is
   1248   // done we can start a new trace or go to one that has already been
   1249   // generated.
   1250   void Flush(RegExpCompiler* compiler, RegExpNode* successor);
   1251   int cp_offset() { return cp_offset_; }
   1252   DeferredAction* actions() { return actions_; }
   1253   // A trivial trace is one that has no deferred actions or other state that
   1254   // affects the assumptions used when generating code.  There is no recorded
   1255   // backtrack location in a trivial trace, so with a trivial trace we will
   1256   // generate code that, on a failure to match, gets the backtrack location
   1257   // from the backtrack stack rather than using a direct jump instruction.  We
   1258   // always start code generation with a trivial trace and non-trivial traces
   1259   // are created as we emit code for nodes or add to the list of deferred
   1260   // actions in the trace.  The location of the code generated for a node using
   1261   // a trivial trace is recorded in a label in the node so that gotos can be
   1262   // generated to that code.
   1263   bool is_trivial() {
   1264     return backtrack_ == NULL &&
   1265            actions_ == NULL &&
   1266            cp_offset_ == 0 &&
   1267            characters_preloaded_ == 0 &&
   1268            bound_checked_up_to_ == 0 &&
   1269            quick_check_performed_.characters() == 0 &&
   1270            at_start_ == UNKNOWN;
   1271   }
   1272   TriBool at_start() { return at_start_; }
   1273   void set_at_start(bool at_start) { at_start_ = at_start ? TRUE : FALSE; }
   1274   Label* backtrack() { return backtrack_; }
   1275   Label* loop_label() { return loop_label_; }
   1276   RegExpNode* stop_node() { return stop_node_; }
   1277   int characters_preloaded() { return characters_preloaded_; }
   1278   int bound_checked_up_to() { return bound_checked_up_to_; }
   1279   int flush_budget() { return flush_budget_; }
   1280   QuickCheckDetails* quick_check_performed() { return &quick_check_performed_; }
   1281   bool mentions_reg(int reg);
   1282   // Returns true if a deferred position store exists to the specified
   1283   // register and stores the offset in the out-parameter.  Otherwise
   1284   // returns false.
   1285   bool GetStoredPosition(int reg, int* cp_offset);
   1286   // These set methods and AdvanceCurrentPositionInTrace should be used only on
   1287   // new traces - the intention is that traces are immutable after creation.
   1288   void add_action(DeferredAction* new_action) {
   1289     ASSERT(new_action->next_ == NULL);
   1290     new_action->next_ = actions_;
   1291     actions_ = new_action;
   1292   }
   1293   void set_backtrack(Label* backtrack) { backtrack_ = backtrack; }
   1294   void set_stop_node(RegExpNode* node) { stop_node_ = node; }
   1295   void set_loop_label(Label* label) { loop_label_ = label; }
   1296   void set_characters_preloaded(int count) { characters_preloaded_ = count; }
   1297   void set_bound_checked_up_to(int to) { bound_checked_up_to_ = to; }
   1298   void set_flush_budget(int to) { flush_budget_ = to; }
   1299   void set_quick_check_performed(QuickCheckDetails* d) {
   1300     quick_check_performed_ = *d;
   1301   }
   1302   void InvalidateCurrentCharacter();
   1303   void AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler);
   1304  private:
   1305   int FindAffectedRegisters(OutSet* affected_registers);
   1306   void PerformDeferredActions(RegExpMacroAssembler* macro,
   1307                                int max_register,
   1308                                OutSet& affected_registers,
   1309                                OutSet* registers_to_pop,
   1310                                OutSet* registers_to_clear);
   1311   void RestoreAffectedRegisters(RegExpMacroAssembler* macro,
   1312                                 int max_register,
   1313                                 OutSet& registers_to_pop,
   1314                                 OutSet& registers_to_clear);
   1315   int cp_offset_;
   1316   DeferredAction* actions_;
   1317   Label* backtrack_;
   1318   RegExpNode* stop_node_;
   1319   Label* loop_label_;
   1320   int characters_preloaded_;
   1321   int bound_checked_up_to_;
   1322   QuickCheckDetails quick_check_performed_;
   1323   int flush_budget_;
   1324   TriBool at_start_;
   1325 };
   1326 
   1327 
   1328 class NodeVisitor {
   1329  public:
   1330   virtual ~NodeVisitor() { }
   1331 #define DECLARE_VISIT(Type)                                          \
   1332   virtual void Visit##Type(Type##Node* that) = 0;
   1333 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
   1334 #undef DECLARE_VISIT
   1335   virtual void VisitLoopChoice(LoopChoiceNode* that) { VisitChoice(that); }
   1336 };
   1337 
   1338 
   1339 // Node visitor used to add the start set of the alternatives to the
   1340 // dispatch table of a choice node.
   1341 class DispatchTableConstructor: public NodeVisitor {
   1342  public:
   1343   DispatchTableConstructor(DispatchTable* table, bool ignore_case)
   1344       : table_(table),
   1345         choice_index_(-1),
   1346         ignore_case_(ignore_case) { }
   1347 
   1348   void BuildTable(ChoiceNode* node);
   1349 
   1350   void AddRange(CharacterRange range) {
   1351     table()->AddRange(range, choice_index_);
   1352   }
   1353 
   1354   void AddInverse(ZoneList<CharacterRange>* ranges);
   1355 
   1356 #define DECLARE_VISIT(Type)                                          \
   1357   virtual void Visit##Type(Type##Node* that);
   1358 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
   1359 #undef DECLARE_VISIT
   1360 
   1361   DispatchTable* table() { return table_; }
   1362   void set_choice_index(int value) { choice_index_ = value; }
   1363 
   1364  protected:
   1365   DispatchTable* table_;
   1366   int choice_index_;
   1367   bool ignore_case_;
   1368 };
   1369 
   1370 
   1371 // Assertion propagation moves information about assertions such as
   1372 // \b to the affected nodes.  For instance, in /.\b./ information must
   1373 // be propagated to the first '.' that whatever follows needs to know
   1374 // if it matched a word or a non-word, and to the second '.' that it
   1375 // has to check if it succeeds a word or non-word.  In this case the
   1376 // result will be something like:
   1377 //
   1378 //   +-------+        +------------+
   1379 //   |   .   |        |      .     |
   1380 //   +-------+  --->  +------------+
   1381 //   | word? |        | check word |
   1382 //   +-------+        +------------+
   1383 class Analysis: public NodeVisitor {
   1384  public:
   1385   Analysis(bool ignore_case, bool is_ascii)
   1386       : ignore_case_(ignore_case),
   1387         is_ascii_(is_ascii),
   1388         error_message_(NULL) { }
   1389   void EnsureAnalyzed(RegExpNode* node);
   1390 
   1391 #define DECLARE_VISIT(Type)                                          \
   1392   virtual void Visit##Type(Type##Node* that);
   1393 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
   1394 #undef DECLARE_VISIT
   1395   virtual void VisitLoopChoice(LoopChoiceNode* that);
   1396 
   1397   bool has_failed() { return error_message_ != NULL; }
   1398   const char* error_message() {
   1399     ASSERT(error_message_ != NULL);
   1400     return error_message_;
   1401   }
   1402   void fail(const char* error_message) {
   1403     error_message_ = error_message;
   1404   }
   1405  private:
   1406   bool ignore_case_;
   1407   bool is_ascii_;
   1408   const char* error_message_;
   1409 
   1410   DISALLOW_IMPLICIT_CONSTRUCTORS(Analysis);
   1411 };
   1412 
   1413 
   1414 struct RegExpCompileData {
   1415   RegExpCompileData()
   1416     : tree(NULL),
   1417       node(NULL),
   1418       simple(true),
   1419       contains_anchor(false),
   1420       capture_count(0) { }
   1421   RegExpTree* tree;
   1422   RegExpNode* node;
   1423   bool simple;
   1424   bool contains_anchor;
   1425   Handle<String> error;
   1426   int capture_count;
   1427 };
   1428 
   1429 
   1430 class RegExpEngine: public AllStatic {
   1431  public:
   1432   struct CompilationResult {
   1433     explicit CompilationResult(const char* error_message)
   1434         : error_message(error_message),
   1435           code(HEAP->the_hole_value()),
   1436           num_registers(0) {}
   1437     CompilationResult(Object* code, int registers)
   1438       : error_message(NULL),
   1439         code(code),
   1440         num_registers(registers) {}
   1441     const char* error_message;
   1442     Object* code;
   1443     int num_registers;
   1444   };
   1445 
   1446   static CompilationResult Compile(RegExpCompileData* input,
   1447                                    bool ignore_case,
   1448                                    bool multiline,
   1449                                    Handle<String> pattern,
   1450                                    bool is_ascii);
   1451 
   1452   static void DotPrint(const char* label, RegExpNode* node, bool ignore_case);
   1453 };
   1454 
   1455 
   1456 class OffsetsVector {
   1457  public:
   1458   explicit inline OffsetsVector(int num_registers)
   1459       : offsets_vector_length_(num_registers) {
   1460     if (offsets_vector_length_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
   1461       vector_ = NewArray<int>(offsets_vector_length_);
   1462     } else {
   1463       vector_ = Isolate::Current()->jsregexp_static_offsets_vector();
   1464     }
   1465   }
   1466   inline ~OffsetsVector() {
   1467     if (offsets_vector_length_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
   1468       DeleteArray(vector_);
   1469       vector_ = NULL;
   1470     }
   1471   }
   1472   inline int* vector() { return vector_; }
   1473   inline int length() { return offsets_vector_length_; }
   1474 
   1475   static const int kStaticOffsetsVectorSize = 50;
   1476 
   1477  private:
   1478   static Address static_offsets_vector_address(Isolate* isolate) {
   1479     return reinterpret_cast<Address>(isolate->jsregexp_static_offsets_vector());
   1480   }
   1481 
   1482   int* vector_;
   1483   int offsets_vector_length_;
   1484 
   1485   friend class ExternalReference;
   1486 };
   1487 
   1488 
   1489 } }  // namespace v8::internal
   1490 
   1491 #endif  // V8_JSREGEXP_H_
   1492