• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 namespace v8 {
32 namespace internal {
33 
34 
35 class RegExpMacroAssembler;
36 
37 
38 class RegExpImpl {
39  public:
40   // Whether V8 is compiled with native regexp support or not.
UsesNativeRegExp()41   static bool UsesNativeRegExp() {
42 #ifdef V8_NATIVE_REGEXP
43     return true;
44 #else
45     return false;
46 #endif
47   }
48 
49   // Creates a regular expression literal in the old space.
50   // This function calls the garbage collector if necessary.
51   static Handle<Object> CreateRegExpLiteral(Handle<JSFunction> constructor,
52                                             Handle<String> pattern,
53                                             Handle<String> flags,
54                                             bool* has_pending_exception);
55 
56   // Returns a string representation of a regular expression.
57   // Implements RegExp.prototype.toString, see ECMA-262 section 15.10.6.4.
58   // This function calls the garbage collector if necessary.
59   static Handle<String> ToString(Handle<Object> value);
60 
61   // Parses the RegExp pattern and prepares the JSRegExp object with
62   // generic data and choice of implementation - as well as what
63   // the implementation wants to store in the data field.
64   // Returns false if compilation fails.
65   static Handle<Object> Compile(Handle<JSRegExp> re,
66                                 Handle<String> pattern,
67                                 Handle<String> flags);
68 
69   // See ECMA-262 section 15.10.6.2.
70   // This function calls the garbage collector if necessary.
71   static Handle<Object> Exec(Handle<JSRegExp> regexp,
72                              Handle<String> subject,
73                              int index,
74                              Handle<JSArray> lastMatchInfo);
75 
76   // Call RegExp.prototyp.exec(string) in a loop.
77   // Used by String.prototype.match and String.prototype.replace.
78   // This function calls the garbage collector if necessary.
79   static Handle<Object> ExecGlobal(Handle<JSRegExp> regexp,
80                                    Handle<String> subject,
81                                    Handle<JSArray> lastMatchInfo);
82 
83   // Prepares a JSRegExp object with Irregexp-specific data.
84   static void IrregexpPrepare(Handle<JSRegExp> re,
85                               Handle<String> pattern,
86                               JSRegExp::Flags flags,
87                               int capture_register_count);
88 
89 
90   static void AtomCompile(Handle<JSRegExp> re,
91                           Handle<String> pattern,
92                           JSRegExp::Flags flags,
93                           Handle<String> match_pattern);
94 
95   static Handle<Object> AtomExec(Handle<JSRegExp> regexp,
96                                  Handle<String> subject,
97                                  int index,
98                                  Handle<JSArray> lastMatchInfo);
99 
100   // Execute an Irregexp bytecode pattern.
101   // On a successful match, the result is a JSArray containing
102   // captured positions. On a failure, the result is the null value.
103   // Returns an empty handle in case of an exception.
104   static Handle<Object> IrregexpExec(Handle<JSRegExp> regexp,
105                                      Handle<String> subject,
106                                      int index,
107                                      Handle<JSArray> lastMatchInfo);
108 
109   // Offsets in the lastMatchInfo array.
110   static const int kLastCaptureCount = 0;
111   static const int kLastSubject = 1;
112   static const int kLastInput = 2;
113   static const int kFirstCapture = 3;
114   static const int kLastMatchOverhead = 3;
115 
116   // Used to access the lastMatchInfo array.
GetCapture(FixedArray * array,int index)117   static int GetCapture(FixedArray* array, int index) {
118     return Smi::cast(array->get(index + kFirstCapture))->value();
119   }
120 
SetLastCaptureCount(FixedArray * array,int to)121   static void SetLastCaptureCount(FixedArray* array, int to) {
122     array->set(kLastCaptureCount, Smi::FromInt(to));
123   }
124 
SetLastSubject(FixedArray * array,String * to)125   static void SetLastSubject(FixedArray* array, String* to) {
126     array->set(kLastSubject, to);
127   }
128 
SetLastInput(FixedArray * array,String * to)129   static void SetLastInput(FixedArray* array, String* to) {
130     array->set(kLastInput, to);
131   }
132 
SetCapture(FixedArray * array,int index,int to)133   static void SetCapture(FixedArray* array, int index, int to) {
134     array->set(index + kFirstCapture, Smi::FromInt(to));
135   }
136 
GetLastCaptureCount(FixedArray * array)137   static int GetLastCaptureCount(FixedArray* array) {
138     return Smi::cast(array->get(kLastCaptureCount))->value();
139   }
140 
141   // For acting on the JSRegExp data FixedArray.
142   static int IrregexpMaxRegisterCount(FixedArray* re);
143   static void SetIrregexpMaxRegisterCount(FixedArray* re, int value);
144   static int IrregexpNumberOfCaptures(FixedArray* re);
145   static int IrregexpNumberOfRegisters(FixedArray* re);
146   static ByteArray* IrregexpByteCode(FixedArray* re, bool is_ascii);
147   static Code* IrregexpNativeCode(FixedArray* re, bool is_ascii);
148 
149  private:
150   static String* last_ascii_string_;
151   static String* two_byte_cached_string_;
152 
153   static bool CompileIrregexp(Handle<JSRegExp> re, bool is_ascii);
154   static inline bool EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii);
155 
156 
157   // Set the subject cache.  The previous string buffer is not deleted, so the
158   // caller should ensure that it doesn't leak.
159   static void SetSubjectCache(String* subject,
160                               char* utf8_subject,
161                               int uft8_length,
162                               int character_position,
163                               int utf8_position);
164 
165   // A one element cache of the last utf8_subject string and its length.  The
166   // subject JS String object is cached in the heap.  We also cache a
167   // translation between position and utf8 position.
168   static char* utf8_subject_cache_;
169   static int utf8_length_cache_;
170   static int utf8_position_;
171   static int character_position_;
172 };
173 
174 
175 class CharacterRange {
176  public:
CharacterRange()177   CharacterRange() : from_(0), to_(0) { }
178   // For compatibility with the CHECK_OK macro
CharacterRange(void * null)179   CharacterRange(void* null) { ASSERT_EQ(NULL, null); }  //NOLINT
CharacterRange(uc16 from,uc16 to)180   CharacterRange(uc16 from, uc16 to) : from_(from), to_(to) { }
181   static void AddClassEscape(uc16 type, ZoneList<CharacterRange>* ranges);
182   static Vector<const uc16> GetWordBounds();
Singleton(uc16 value)183   static inline CharacterRange Singleton(uc16 value) {
184     return CharacterRange(value, value);
185   }
Range(uc16 from,uc16 to)186   static inline CharacterRange Range(uc16 from, uc16 to) {
187     ASSERT(from <= to);
188     return CharacterRange(from, to);
189   }
Everything()190   static inline CharacterRange Everything() {
191     return CharacterRange(0, 0xFFFF);
192   }
Contains(uc16 i)193   bool Contains(uc16 i) { return from_ <= i && i <= to_; }
from()194   uc16 from() const { return from_; }
set_from(uc16 value)195   void set_from(uc16 value) { from_ = value; }
to()196   uc16 to() const { return to_; }
set_to(uc16 value)197   void set_to(uc16 value) { to_ = value; }
is_valid()198   bool is_valid() { return from_ <= to_; }
IsEverything(uc16 max)199   bool IsEverything(uc16 max) { return from_ == 0 && to_ >= max; }
IsSingleton()200   bool IsSingleton() { return (from_ == to_); }
201   void AddCaseEquivalents(ZoneList<CharacterRange>* ranges);
202   static void Split(ZoneList<CharacterRange>* base,
203                     Vector<const uc16> overlay,
204                     ZoneList<CharacterRange>** included,
205                     ZoneList<CharacterRange>** excluded);
206 
207   static const int kRangeCanonicalizeMax = 0x346;
208   static const int kStartMarker = (1 << 24);
209   static const int kPayloadMask = (1 << 24) - 1;
210 
211  private:
212   uc16 from_;
213   uc16 to_;
214 };
215 
216 
217 // A set of unsigned integers that behaves especially well on small
218 // integers (< 32).  May do zone-allocation.
219 class OutSet: public ZoneObject {
220  public:
OutSet()221   OutSet() : first_(0), remaining_(NULL), successors_(NULL) { }
222   OutSet* Extend(unsigned value);
223   bool Get(unsigned value);
224   static const unsigned kFirstLimit = 32;
225 
226  private:
227   // Destructively set a value in this set.  In most cases you want
228   // to use Extend instead to ensure that only one instance exists
229   // that contains the same values.
230   void Set(unsigned value);
231 
232   // The successors are a list of sets that contain the same values
233   // as this set and the one more value that is not present in this
234   // set.
successors()235   ZoneList<OutSet*>* successors() { return successors_; }
236 
OutSet(uint32_t first,ZoneList<unsigned> * remaining)237   OutSet(uint32_t first, ZoneList<unsigned>* remaining)
238       : first_(first), remaining_(remaining), successors_(NULL) { }
239   uint32_t first_;
240   ZoneList<unsigned>* remaining_;
241   ZoneList<OutSet*>* successors_;
242   friend class Trace;
243 };
244 
245 
246 // A mapping from integers, specified as ranges, to a set of integers.
247 // Used for mapping character ranges to choices.
248 class DispatchTable : public ZoneObject {
249  public:
250   class Entry {
251    public:
Entry()252     Entry() : from_(0), to_(0), out_set_(NULL) { }
Entry(uc16 from,uc16 to,OutSet * out_set)253     Entry(uc16 from, uc16 to, OutSet* out_set)
254         : from_(from), to_(to), out_set_(out_set) { }
from()255     uc16 from() { return from_; }
to()256     uc16 to() { return to_; }
set_to(uc16 value)257     void set_to(uc16 value) { to_ = value; }
AddValue(int value)258     void AddValue(int value) { out_set_ = out_set_->Extend(value); }
out_set()259     OutSet* out_set() { return out_set_; }
260    private:
261     uc16 from_;
262     uc16 to_;
263     OutSet* out_set_;
264   };
265 
266   class Config {
267    public:
268     typedef uc16 Key;
269     typedef Entry Value;
270     static const uc16 kNoKey;
271     static const Entry kNoValue;
Compare(uc16 a,uc16 b)272     static inline int Compare(uc16 a, uc16 b) {
273       if (a == b)
274         return 0;
275       else if (a < b)
276         return -1;
277       else
278         return 1;
279     }
280   };
281 
282   void AddRange(CharacterRange range, int value);
283   OutSet* Get(uc16 value);
284   void Dump();
285 
286   template <typename Callback>
ForEach(Callback * callback)287   void ForEach(Callback* callback) { return tree()->ForEach(callback); }
288  private:
289   // There can't be a static empty set since it allocates its
290   // successors in a zone and caches them.
empty()291   OutSet* empty() { return &empty_; }
292   OutSet empty_;
tree()293   ZoneSplayTree<Config>* tree() { return &tree_; }
294   ZoneSplayTree<Config> tree_;
295 };
296 
297 
298 #define FOR_EACH_NODE_TYPE(VISIT)                                    \
299   VISIT(End)                                                         \
300   VISIT(Action)                                                      \
301   VISIT(Choice)                                                      \
302   VISIT(BackReference)                                               \
303   VISIT(Assertion)                                                   \
304   VISIT(Text)
305 
306 
307 #define FOR_EACH_REG_EXP_TREE_TYPE(VISIT)                            \
308   VISIT(Disjunction)                                                 \
309   VISIT(Alternative)                                                 \
310   VISIT(Assertion)                                                   \
311   VISIT(CharacterClass)                                              \
312   VISIT(Atom)                                                        \
313   VISIT(Quantifier)                                                  \
314   VISIT(Capture)                                                     \
315   VISIT(Lookahead)                                                   \
316   VISIT(BackReference)                                               \
317   VISIT(Empty)                                                       \
318   VISIT(Text)
319 
320 
321 #define FORWARD_DECLARE(Name) class RegExp##Name;
FOR_EACH_REG_EXP_TREE_TYPE(FORWARD_DECLARE)322 FOR_EACH_REG_EXP_TREE_TYPE(FORWARD_DECLARE)
323 #undef FORWARD_DECLARE
324 
325 
326 class TextElement {
327  public:
328   enum Type {UNINITIALIZED, ATOM, CHAR_CLASS};
329   TextElement() : type(UNINITIALIZED) { }
330   explicit TextElement(Type t) : type(t), cp_offset(-1) { }
331   static TextElement Atom(RegExpAtom* atom);
332   static TextElement CharClass(RegExpCharacterClass* char_class);
333   int length();
334   Type type;
335   union {
336     RegExpAtom* u_atom;
337     RegExpCharacterClass* u_char_class;
338   } data;
339   int cp_offset;
340 };
341 
342 
343 class Trace;
344 
345 
346 struct NodeInfo {
NodeInfoNodeInfo347   NodeInfo()
348       : being_analyzed(false),
349         been_analyzed(false),
350         follows_word_interest(false),
351         follows_newline_interest(false),
352         follows_start_interest(false),
353         at_end(false),
354         visited(false) { }
355 
356   // Returns true if the interests and assumptions of this node
357   // matches the given one.
MatchesNodeInfo358   bool Matches(NodeInfo* that) {
359     return (at_end == that->at_end) &&
360            (follows_word_interest == that->follows_word_interest) &&
361            (follows_newline_interest == that->follows_newline_interest) &&
362            (follows_start_interest == that->follows_start_interest);
363   }
364 
365   // Updates the interests of this node given the interests of the
366   // node preceding it.
AddFromPrecedingNodeInfo367   void AddFromPreceding(NodeInfo* that) {
368     at_end |= that->at_end;
369     follows_word_interest |= that->follows_word_interest;
370     follows_newline_interest |= that->follows_newline_interest;
371     follows_start_interest |= that->follows_start_interest;
372   }
373 
HasLookbehindNodeInfo374   bool HasLookbehind() {
375     return follows_word_interest ||
376            follows_newline_interest ||
377            follows_start_interest;
378   }
379 
380   // Sets the interests of this node to include the interests of the
381   // following node.
AddFromFollowingNodeInfo382   void AddFromFollowing(NodeInfo* that) {
383     follows_word_interest |= that->follows_word_interest;
384     follows_newline_interest |= that->follows_newline_interest;
385     follows_start_interest |= that->follows_start_interest;
386   }
387 
ResetCompilationStateNodeInfo388   void ResetCompilationState() {
389     being_analyzed = false;
390     been_analyzed = false;
391   }
392 
393   bool being_analyzed: 1;
394   bool been_analyzed: 1;
395 
396   // These bits are set of this node has to know what the preceding
397   // character was.
398   bool follows_word_interest: 1;
399   bool follows_newline_interest: 1;
400   bool follows_start_interest: 1;
401 
402   bool at_end: 1;
403   bool visited: 1;
404 };
405 
406 
407 class SiblingList {
408  public:
SiblingList()409   SiblingList() : list_(NULL) { }
length()410   int length() {
411     return list_ == NULL ? 0 : list_->length();
412   }
Ensure(RegExpNode * parent)413   void Ensure(RegExpNode* parent) {
414     if (list_ == NULL) {
415       list_ = new ZoneList<RegExpNode*>(2);
416       list_->Add(parent);
417     }
418   }
Add(RegExpNode * node)419   void Add(RegExpNode* node) { list_->Add(node); }
Get(int index)420   RegExpNode* Get(int index) { return list_->at(index); }
421  private:
422   ZoneList<RegExpNode*>* list_;
423 };
424 
425 
426 // Details of a quick mask-compare check that can look ahead in the
427 // input stream.
428 class QuickCheckDetails {
429  public:
QuickCheckDetails()430   QuickCheckDetails()
431       : characters_(0),
432         mask_(0),
433         value_(0),
434         cannot_match_(false) { }
QuickCheckDetails(int characters)435   explicit QuickCheckDetails(int characters)
436       : characters_(characters),
437         mask_(0),
438         value_(0),
439         cannot_match_(false) { }
440   bool Rationalize(bool ascii);
441   // Merge in the information from another branch of an alternation.
442   void Merge(QuickCheckDetails* other, int from_index);
443   // Advance the current position by some amount.
444   void Advance(int by, bool ascii);
445   void Clear();
cannot_match()446   bool cannot_match() { return cannot_match_; }
set_cannot_match()447   void set_cannot_match() { cannot_match_ = true; }
448   struct Position {
PositionPosition449     Position() : mask(0), value(0), determines_perfectly(false) { }
450     uc16 mask;
451     uc16 value;
452     bool determines_perfectly;
453   };
characters()454   int characters() { return characters_; }
set_characters(int characters)455   void set_characters(int characters) { characters_ = characters; }
positions(int index)456   Position* positions(int index) {
457     ASSERT(index >= 0);
458     ASSERT(index < characters_);
459     return positions_ + index;
460   }
mask()461   uint32_t mask() { return mask_; }
value()462   uint32_t value() { return value_; }
463 
464  private:
465   // How many characters do we have quick check information from.  This is
466   // the same for all branches of a choice node.
467   int characters_;
468   Position positions_[4];
469   // These values are the condensate of the above array after Rationalize().
470   uint32_t mask_;
471   uint32_t value_;
472   // If set to true, there is no way this quick check can match at all.
473   // E.g., if it requires to be at the start of the input, and isn't.
474   bool cannot_match_;
475 };
476 
477 
478 class RegExpNode: public ZoneObject {
479  public:
RegExpNode()480   RegExpNode() : trace_count_(0) { }
481   virtual ~RegExpNode();
482   virtual void Accept(NodeVisitor* visitor) = 0;
483   // Generates a goto to this node or actually generates the code at this point.
484   virtual void Emit(RegExpCompiler* compiler, Trace* trace) = 0;
485   // How many characters must this node consume at a minimum in order to
486   // succeed.  If we have found at least 'still_to_find' characters that
487   // must be consumed there is no need to ask any following nodes whether
488   // they are sure to eat any more characters.
489   virtual int EatsAtLeast(int still_to_find, int recursion_depth) = 0;
490   // Emits some quick code that checks whether the preloaded characters match.
491   // Falls through on certain failure, jumps to the label on possible success.
492   // If the node cannot make a quick check it does nothing and returns false.
493   bool EmitQuickCheck(RegExpCompiler* compiler,
494                       Trace* trace,
495                       bool preload_has_checked_bounds,
496                       Label* on_possible_success,
497                       QuickCheckDetails* details_return,
498                       bool fall_through_on_failure);
499   // For a given number of characters this returns a mask and a value.  The
500   // next n characters are anded with the mask and compared with the value.
501   // A comparison failure indicates the node cannot match the next n characters.
502   // A comparison success indicates the node may match.
503   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
504                                     RegExpCompiler* compiler,
505                                     int characters_filled_in,
506                                     bool not_at_start) = 0;
507   static const int kNodeIsTooComplexForGreedyLoops = -1;
GreedyLoopTextLength()508   virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
label()509   Label* label() { return &label_; }
510   // If non-generic code is generated for a node (ie the node is not at the
511   // start of the trace) then it cannot be reused.  This variable sets a limit
512   // on how often we allow that to happen before we insist on starting a new
513   // trace and generating generic code for a node that can be reused by flushing
514   // the deferred actions in the current trace and generating a goto.
515   static const int kMaxCopiesCodeGenerated = 10;
516 
info()517   NodeInfo* info() { return &info_; }
518 
AddSibling(RegExpNode * node)519   void AddSibling(RegExpNode* node) { siblings_.Add(node); }
520 
521   // Static version of EnsureSibling that expresses the fact that the
522   // result has the same type as the input.
523   template <class C>
EnsureSibling(C * node,NodeInfo * info,bool * cloned)524   static C* EnsureSibling(C* node, NodeInfo* info, bool* cloned) {
525     return static_cast<C*>(node->EnsureSibling(info, cloned));
526   }
527 
siblings()528   SiblingList* siblings() { return &siblings_; }
set_siblings(SiblingList * other)529   void set_siblings(SiblingList* other) { siblings_ = *other; }
530 
531  protected:
532   enum LimitResult { DONE, CONTINUE };
533   LimitResult LimitVersions(RegExpCompiler* compiler, Trace* trace);
534 
535   // Returns a sibling of this node whose interests and assumptions
536   // match the ones in the given node info.  If no sibling exists NULL
537   // is returned.
538   RegExpNode* TryGetSibling(NodeInfo* info);
539 
540   // Returns a sibling of this node whose interests match the ones in
541   // the given node info.  The info must not contain any assertions.
542   // If no node exists a new one will be created by cloning the current
543   // node.  The result will always be an instance of the same concrete
544   // class as this node.
545   RegExpNode* EnsureSibling(NodeInfo* info, bool* cloned);
546 
547   // Returns a clone of this node initialized using the copy constructor
548   // of its concrete class.  Note that the node may have to be pre-
549   // processed before it is on a usable state.
550   virtual RegExpNode* Clone() = 0;
551 
552  private:
553   Label label_;
554   NodeInfo info_;
555   SiblingList siblings_;
556   // This variable keeps track of how many times code has been generated for
557   // this node (in different traces).  We don't keep track of where the
558   // generated code is located unless the code is generated at the start of
559   // a trace, in which case it is generic and can be reused by flushing the
560   // deferred operations in the current trace and generating a goto.
561   int trace_count_;
562 };
563 
564 
565 // A simple closed interval.
566 class Interval {
567  public:
Interval()568   Interval() : from_(kNone), to_(kNone) { }
Interval(int from,int to)569   Interval(int from, int to) : from_(from), to_(to) { }
Union(Interval that)570   Interval Union(Interval that) {
571     if (that.from_ == kNone)
572       return *this;
573     else if (from_ == kNone)
574       return that;
575     else
576       return Interval(Min(from_, that.from_), Max(to_, that.to_));
577   }
Contains(int value)578   bool Contains(int value) {
579     return (from_ <= value) && (value <= to_);
580   }
is_empty()581   bool is_empty() { return from_ == kNone; }
from()582   int from() { return from_; }
to()583   int to() { return to_; }
Empty()584   static Interval Empty() { return Interval(); }
585   static const int kNone = -1;
586  private:
587   int from_;
588   int to_;
589 };
590 
591 
592 class SeqRegExpNode: public RegExpNode {
593  public:
SeqRegExpNode(RegExpNode * on_success)594   explicit SeqRegExpNode(RegExpNode* on_success)
595       : on_success_(on_success) { }
on_success()596   RegExpNode* on_success() { return on_success_; }
set_on_success(RegExpNode * node)597   void set_on_success(RegExpNode* node) { on_success_ = node; }
598  private:
599   RegExpNode* on_success_;
600 };
601 
602 
603 class ActionNode: public SeqRegExpNode {
604  public:
605   enum Type {
606     SET_REGISTER,
607     INCREMENT_REGISTER,
608     STORE_POSITION,
609     BEGIN_SUBMATCH,
610     POSITIVE_SUBMATCH_SUCCESS,
611     EMPTY_MATCH_CHECK,
612     CLEAR_CAPTURES
613   };
614   static ActionNode* SetRegister(int reg, int val, RegExpNode* on_success);
615   static ActionNode* IncrementRegister(int reg, RegExpNode* on_success);
616   static ActionNode* StorePosition(int reg,
617                                    bool is_capture,
618                                    RegExpNode* on_success);
619   static ActionNode* ClearCaptures(Interval range, RegExpNode* on_success);
620   static ActionNode* BeginSubmatch(int stack_pointer_reg,
621                                    int position_reg,
622                                    RegExpNode* on_success);
623   static ActionNode* PositiveSubmatchSuccess(int stack_pointer_reg,
624                                              int restore_reg,
625                                              int clear_capture_count,
626                                              int clear_capture_from,
627                                              RegExpNode* on_success);
628   static ActionNode* EmptyMatchCheck(int start_register,
629                                      int repetition_register,
630                                      int repetition_limit,
631                                      RegExpNode* on_success);
632   virtual void Accept(NodeVisitor* visitor);
633   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
634   virtual int EatsAtLeast(int still_to_find, int recursion_depth);
GetQuickCheckDetails(QuickCheckDetails * details,RegExpCompiler * compiler,int filled_in,bool not_at_start)635   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
636                                     RegExpCompiler* compiler,
637                                     int filled_in,
638                                     bool not_at_start) {
639     return on_success()->GetQuickCheckDetails(
640         details, compiler, filled_in, not_at_start);
641   }
type()642   Type type() { return type_; }
643   // TODO(erikcorry): We should allow some action nodes in greedy loops.
GreedyLoopTextLength()644   virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
Clone()645   virtual ActionNode* Clone() { return new ActionNode(*this); }
646 
647  private:
648   union {
649     struct {
650       int reg;
651       int value;
652     } u_store_register;
653     struct {
654       int reg;
655     } u_increment_register;
656     struct {
657       int reg;
658       bool is_capture;
659     } u_position_register;
660     struct {
661       int stack_pointer_register;
662       int current_position_register;
663       int clear_register_count;
664       int clear_register_from;
665     } u_submatch;
666     struct {
667       int start_register;
668       int repetition_register;
669       int repetition_limit;
670     } u_empty_match_check;
671     struct {
672       int range_from;
673       int range_to;
674     } u_clear_captures;
675   } data_;
ActionNode(Type type,RegExpNode * on_success)676   ActionNode(Type type, RegExpNode* on_success)
677       : SeqRegExpNode(on_success),
678         type_(type) { }
679   Type type_;
680   friend class DotPrinter;
681 };
682 
683 
684 class TextNode: public SeqRegExpNode {
685  public:
TextNode(ZoneList<TextElement> * elms,RegExpNode * on_success)686   TextNode(ZoneList<TextElement>* elms,
687            RegExpNode* on_success)
688       : SeqRegExpNode(on_success),
689         elms_(elms) { }
TextNode(RegExpCharacterClass * that,RegExpNode * on_success)690   TextNode(RegExpCharacterClass* that,
691            RegExpNode* on_success)
692       : SeqRegExpNode(on_success),
693         elms_(new ZoneList<TextElement>(1)) {
694     elms_->Add(TextElement::CharClass(that));
695   }
696   virtual void Accept(NodeVisitor* visitor);
697   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
698   virtual int EatsAtLeast(int still_to_find, int recursion_depth);
699   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
700                                     RegExpCompiler* compiler,
701                                     int characters_filled_in,
702                                     bool not_at_start);
elements()703   ZoneList<TextElement>* elements() { return elms_; }
704   void MakeCaseIndependent();
705   virtual int GreedyLoopTextLength();
Clone()706   virtual TextNode* Clone() {
707     TextNode* result = new TextNode(*this);
708     result->CalculateOffsets();
709     return result;
710   }
711   void CalculateOffsets();
712 
713  private:
714   enum TextEmitPassType {
715     NON_ASCII_MATCH,             // Check for characters that can't match.
716     SIMPLE_CHARACTER_MATCH,      // Case-dependent single character check.
717     NON_LETTER_CHARACTER_MATCH,  // Check characters that have no case equivs.
718     CASE_CHARACTER_MATCH,        // Case-independent single character check.
719     CHARACTER_CLASS_MATCH        // Character class.
720   };
721   static bool SkipPass(int pass, bool ignore_case);
722   static const int kFirstRealPass = SIMPLE_CHARACTER_MATCH;
723   static const int kLastPass = CHARACTER_CLASS_MATCH;
724   void TextEmitPass(RegExpCompiler* compiler,
725                     TextEmitPassType pass,
726                     bool preloaded,
727                     Trace* trace,
728                     bool first_element_checked,
729                     int* checked_up_to);
730   int Length();
731   ZoneList<TextElement>* elms_;
732 };
733 
734 
735 class AssertionNode: public SeqRegExpNode {
736  public:
737   enum AssertionNodeType {
738     AT_END,
739     AT_START,
740     AT_BOUNDARY,
741     AT_NON_BOUNDARY,
742     AFTER_NEWLINE
743   };
AtEnd(RegExpNode * on_success)744   static AssertionNode* AtEnd(RegExpNode* on_success) {
745     return new AssertionNode(AT_END, on_success);
746   }
AtStart(RegExpNode * on_success)747   static AssertionNode* AtStart(RegExpNode* on_success) {
748     return new AssertionNode(AT_START, on_success);
749   }
AtBoundary(RegExpNode * on_success)750   static AssertionNode* AtBoundary(RegExpNode* on_success) {
751     return new AssertionNode(AT_BOUNDARY, on_success);
752   }
AtNonBoundary(RegExpNode * on_success)753   static AssertionNode* AtNonBoundary(RegExpNode* on_success) {
754     return new AssertionNode(AT_NON_BOUNDARY, on_success);
755   }
AfterNewline(RegExpNode * on_success)756   static AssertionNode* AfterNewline(RegExpNode* on_success) {
757     return new AssertionNode(AFTER_NEWLINE, on_success);
758   }
759   virtual void Accept(NodeVisitor* visitor);
760   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
761   virtual int EatsAtLeast(int still_to_find, int recursion_depth);
762   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
763                                     RegExpCompiler* compiler,
764                                     int filled_in,
765                                     bool not_at_start);
Clone()766   virtual AssertionNode* Clone() { return new AssertionNode(*this); }
type()767   AssertionNodeType type() { return type_; }
768  private:
AssertionNode(AssertionNodeType t,RegExpNode * on_success)769   AssertionNode(AssertionNodeType t, RegExpNode* on_success)
770       : SeqRegExpNode(on_success), type_(t) { }
771   AssertionNodeType type_;
772 };
773 
774 
775 class BackReferenceNode: public SeqRegExpNode {
776  public:
BackReferenceNode(int start_reg,int end_reg,RegExpNode * on_success)777   BackReferenceNode(int start_reg,
778                     int end_reg,
779                     RegExpNode* on_success)
780       : SeqRegExpNode(on_success),
781         start_reg_(start_reg),
782         end_reg_(end_reg) { }
783   virtual void Accept(NodeVisitor* visitor);
start_register()784   int start_register() { return start_reg_; }
end_register()785   int end_register() { return end_reg_; }
786   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
787   virtual int EatsAtLeast(int still_to_find, int recursion_depth);
GetQuickCheckDetails(QuickCheckDetails * details,RegExpCompiler * compiler,int characters_filled_in,bool not_at_start)788   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
789                                     RegExpCompiler* compiler,
790                                     int characters_filled_in,
791                                     bool not_at_start) {
792     return;
793   }
Clone()794   virtual BackReferenceNode* Clone() { return new BackReferenceNode(*this); }
795 
796  private:
797   int start_reg_;
798   int end_reg_;
799 };
800 
801 
802 class EndNode: public RegExpNode {
803  public:
804   enum Action { ACCEPT, BACKTRACK, NEGATIVE_SUBMATCH_SUCCESS };
EndNode(Action action)805   explicit EndNode(Action action) : action_(action) { }
806   virtual void Accept(NodeVisitor* visitor);
807   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
EatsAtLeast(int still_to_find,int recursion_depth)808   virtual int EatsAtLeast(int still_to_find, int recursion_depth) { return 0; }
GetQuickCheckDetails(QuickCheckDetails * details,RegExpCompiler * compiler,int characters_filled_in,bool not_at_start)809   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
810                                     RegExpCompiler* compiler,
811                                     int characters_filled_in,
812                                     bool not_at_start) {
813     // Returning 0 from EatsAtLeast should ensure we never get here.
814     UNREACHABLE();
815   }
Clone()816   virtual EndNode* Clone() { return new EndNode(*this); }
817 
818  private:
819   Action action_;
820 };
821 
822 
823 class NegativeSubmatchSuccess: public EndNode {
824  public:
NegativeSubmatchSuccess(int stack_pointer_reg,int position_reg,int clear_capture_count,int clear_capture_start)825   NegativeSubmatchSuccess(int stack_pointer_reg,
826                           int position_reg,
827                           int clear_capture_count,
828                           int clear_capture_start)
829       : EndNode(NEGATIVE_SUBMATCH_SUCCESS),
830         stack_pointer_register_(stack_pointer_reg),
831         current_position_register_(position_reg),
832         clear_capture_count_(clear_capture_count),
833         clear_capture_start_(clear_capture_start) { }
834   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
835 
836  private:
837   int stack_pointer_register_;
838   int current_position_register_;
839   int clear_capture_count_;
840   int clear_capture_start_;
841 };
842 
843 
844 class Guard: public ZoneObject {
845  public:
846   enum Relation { LT, GEQ };
Guard(int reg,Relation op,int value)847   Guard(int reg, Relation op, int value)
848       : reg_(reg),
849         op_(op),
850         value_(value) { }
reg()851   int reg() { return reg_; }
op()852   Relation op() { return op_; }
value()853   int value() { return value_; }
854 
855  private:
856   int reg_;
857   Relation op_;
858   int value_;
859 };
860 
861 
862 class GuardedAlternative {
863  public:
GuardedAlternative(RegExpNode * node)864   explicit GuardedAlternative(RegExpNode* node) : node_(node), guards_(NULL) { }
865   void AddGuard(Guard* guard);
node()866   RegExpNode* node() { return node_; }
set_node(RegExpNode * node)867   void set_node(RegExpNode* node) { node_ = node; }
guards()868   ZoneList<Guard*>* guards() { return guards_; }
869 
870  private:
871   RegExpNode* node_;
872   ZoneList<Guard*>* guards_;
873 };
874 
875 
876 class AlternativeGeneration;
877 
878 
879 class ChoiceNode: public RegExpNode {
880  public:
ChoiceNode(int expected_size)881   explicit ChoiceNode(int expected_size)
882       : alternatives_(new ZoneList<GuardedAlternative>(expected_size)),
883         table_(NULL),
884         not_at_start_(false),
885         being_calculated_(false) { }
886   virtual void Accept(NodeVisitor* visitor);
AddAlternative(GuardedAlternative node)887   void AddAlternative(GuardedAlternative node) { alternatives()->Add(node); }
alternatives()888   ZoneList<GuardedAlternative>* alternatives() { return alternatives_; }
889   DispatchTable* GetTable(bool ignore_case);
890   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
891   virtual int EatsAtLeast(int still_to_find, int recursion_depth);
892   int EatsAtLeastHelper(int still_to_find,
893                         int recursion_depth,
894                         RegExpNode* ignore_this_node);
895   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
896                                     RegExpCompiler* compiler,
897                                     int characters_filled_in,
898                                     bool not_at_start);
Clone()899   virtual ChoiceNode* Clone() { return new ChoiceNode(*this); }
900 
being_calculated()901   bool being_calculated() { return being_calculated_; }
not_at_start()902   bool not_at_start() { return not_at_start_; }
set_not_at_start()903   void set_not_at_start() { not_at_start_ = true; }
set_being_calculated(bool b)904   void set_being_calculated(bool b) { being_calculated_ = b; }
try_to_emit_quick_check_for_alternative(int i)905   virtual bool try_to_emit_quick_check_for_alternative(int i) { return true; }
906 
907  protected:
908   int GreedyLoopTextLength(GuardedAlternative* alternative);
909   ZoneList<GuardedAlternative>* alternatives_;
910 
911  private:
912   friend class DispatchTableConstructor;
913   friend class Analysis;
914   void GenerateGuard(RegExpMacroAssembler* macro_assembler,
915                      Guard* guard,
916                      Trace* trace);
917   int CalculatePreloadCharacters(RegExpCompiler* compiler);
918   void EmitOutOfLineContinuation(RegExpCompiler* compiler,
919                                  Trace* trace,
920                                  GuardedAlternative alternative,
921                                  AlternativeGeneration* alt_gen,
922                                  int preload_characters,
923                                  bool next_expects_preload);
924   DispatchTable* table_;
925   // If true, this node is never checked at the start of the input.
926   // Allows a new trace to start with at_start() set to false.
927   bool not_at_start_;
928   bool being_calculated_;
929 };
930 
931 
932 class NegativeLookaheadChoiceNode: public ChoiceNode {
933  public:
NegativeLookaheadChoiceNode(GuardedAlternative this_must_fail,GuardedAlternative then_do_this)934   explicit NegativeLookaheadChoiceNode(GuardedAlternative this_must_fail,
935                                        GuardedAlternative then_do_this)
936       : ChoiceNode(2) {
937     AddAlternative(this_must_fail);
938     AddAlternative(then_do_this);
939   }
940   virtual int EatsAtLeast(int still_to_find, int recursion_depth);
941   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
942                                     RegExpCompiler* compiler,
943                                     int characters_filled_in,
944                                     bool not_at_start);
945   // For a negative lookahead we don't emit the quick check for the
946   // alternative that is expected to fail.  This is because quick check code
947   // starts by loading enough characters for the alternative that takes fewest
948   // characters, but on a negative lookahead the negative branch did not take
949   // part in that calculation (EatsAtLeast) so the assumptions don't hold.
try_to_emit_quick_check_for_alternative(int i)950   virtual bool try_to_emit_quick_check_for_alternative(int i) { return i != 0; }
951 };
952 
953 
954 class LoopChoiceNode: public ChoiceNode {
955  public:
LoopChoiceNode(bool body_can_be_zero_length)956   explicit LoopChoiceNode(bool body_can_be_zero_length)
957       : ChoiceNode(2),
958         loop_node_(NULL),
959         continue_node_(NULL),
960         body_can_be_zero_length_(body_can_be_zero_length) { }
961   void AddLoopAlternative(GuardedAlternative alt);
962   void AddContinueAlternative(GuardedAlternative alt);
963   virtual void Emit(RegExpCompiler* compiler, Trace* trace);
964   virtual int EatsAtLeast(int still_to_find, int recursion_depth);
965   virtual void GetQuickCheckDetails(QuickCheckDetails* details,
966                                     RegExpCompiler* compiler,
967                                     int characters_filled_in,
968                                     bool not_at_start);
Clone()969   virtual LoopChoiceNode* Clone() { return new LoopChoiceNode(*this); }
loop_node()970   RegExpNode* loop_node() { return loop_node_; }
continue_node()971   RegExpNode* continue_node() { return continue_node_; }
body_can_be_zero_length()972   bool body_can_be_zero_length() { return body_can_be_zero_length_; }
973   virtual void Accept(NodeVisitor* visitor);
974 
975  private:
976   // AddAlternative is made private for loop nodes because alternatives
977   // should not be added freely, we need to keep track of which node
978   // goes back to the node itself.
AddAlternative(GuardedAlternative node)979   void AddAlternative(GuardedAlternative node) {
980     ChoiceNode::AddAlternative(node);
981   }
982 
983   RegExpNode* loop_node_;
984   RegExpNode* continue_node_;
985   bool body_can_be_zero_length_;
986 };
987 
988 
989 // There are many ways to generate code for a node.  This class encapsulates
990 // the current way we should be generating.  In other words it encapsulates
991 // the current state of the code generator.  The effect of this is that we
992 // generate code for paths that the matcher can take through the regular
993 // expression.  A given node in the regexp can be code-generated several times
994 // as it can be part of several traces.  For example for the regexp:
995 // /foo(bar|ip)baz/ the code to match baz will be generated twice, once as part
996 // of the foo-bar-baz trace and once as part of the foo-ip-baz trace.  The code
997 // to match foo is generated only once (the traces have a common prefix).  The
998 // code to store the capture is deferred and generated (twice) after the places
999 // where baz has been matched.
1000 class Trace {
1001  public:
1002   // A value for a property that is either known to be true, know to be false,
1003   // or not known.
1004   enum TriBool {
1005     UNKNOWN = -1, FALSE = 0, TRUE = 1
1006   };
1007 
1008   class DeferredAction {
1009    public:
DeferredAction(ActionNode::Type type,int reg)1010     DeferredAction(ActionNode::Type type, int reg)
1011         : type_(type), reg_(reg), next_(NULL) { }
next()1012     DeferredAction* next() { return next_; }
1013     bool Mentions(int reg);
reg()1014     int reg() { return reg_; }
type()1015     ActionNode::Type type() { return type_; }
1016    private:
1017     ActionNode::Type type_;
1018     int reg_;
1019     DeferredAction* next_;
1020     friend class Trace;
1021   };
1022 
1023   class DeferredCapture : public DeferredAction {
1024    public:
DeferredCapture(int reg,bool is_capture,Trace * trace)1025     DeferredCapture(int reg, bool is_capture, Trace* trace)
1026         : DeferredAction(ActionNode::STORE_POSITION, reg),
1027           cp_offset_(trace->cp_offset()),
1028           is_capture_(is_capture) { }
cp_offset()1029     int cp_offset() { return cp_offset_; }
is_capture()1030     bool is_capture() { return is_capture_; }
1031    private:
1032     int cp_offset_;
1033     bool is_capture_;
set_cp_offset(int cp_offset)1034     void set_cp_offset(int cp_offset) { cp_offset_ = cp_offset; }
1035   };
1036 
1037   class DeferredSetRegister : public DeferredAction {
1038    public:
DeferredSetRegister(int reg,int value)1039     DeferredSetRegister(int reg, int value)
1040         : DeferredAction(ActionNode::SET_REGISTER, reg),
1041           value_(value) { }
value()1042     int value() { return value_; }
1043    private:
1044     int value_;
1045   };
1046 
1047   class DeferredClearCaptures : public DeferredAction {
1048    public:
DeferredClearCaptures(Interval range)1049     explicit DeferredClearCaptures(Interval range)
1050         : DeferredAction(ActionNode::CLEAR_CAPTURES, -1),
1051           range_(range) { }
range()1052     Interval range() { return range_; }
1053    private:
1054     Interval range_;
1055   };
1056 
1057   class DeferredIncrementRegister : public DeferredAction {
1058    public:
DeferredIncrementRegister(int reg)1059     explicit DeferredIncrementRegister(int reg)
1060         : DeferredAction(ActionNode::INCREMENT_REGISTER, reg) { }
1061   };
1062 
Trace()1063   Trace()
1064       : cp_offset_(0),
1065         actions_(NULL),
1066         backtrack_(NULL),
1067         stop_node_(NULL),
1068         loop_label_(NULL),
1069         characters_preloaded_(0),
1070         bound_checked_up_to_(0),
1071         flush_budget_(100),
1072         at_start_(UNKNOWN) { }
1073 
1074   // End the trace.  This involves flushing the deferred actions in the trace
1075   // and pushing a backtrack location onto the backtrack stack.  Once this is
1076   // done we can start a new trace or go to one that has already been
1077   // generated.
1078   void Flush(RegExpCompiler* compiler, RegExpNode* successor);
cp_offset()1079   int cp_offset() { return cp_offset_; }
actions()1080   DeferredAction* actions() { return actions_; }
1081   // A trivial trace is one that has no deferred actions or other state that
1082   // affects the assumptions used when generating code.  There is no recorded
1083   // backtrack location in a trivial trace, so with a trivial trace we will
1084   // generate code that, on a failure to match, gets the backtrack location
1085   // from the backtrack stack rather than using a direct jump instruction.  We
1086   // always start code generation with a trivial trace and non-trivial traces
1087   // are created as we emit code for nodes or add to the list of deferred
1088   // actions in the trace.  The location of the code generated for a node using
1089   // a trivial trace is recorded in a label in the node so that gotos can be
1090   // generated to that code.
is_trivial()1091   bool is_trivial() {
1092     return backtrack_ == NULL &&
1093            actions_ == NULL &&
1094            cp_offset_ == 0 &&
1095            characters_preloaded_ == 0 &&
1096            bound_checked_up_to_ == 0 &&
1097            quick_check_performed_.characters() == 0 &&
1098            at_start_ == UNKNOWN;
1099   }
at_start()1100   TriBool at_start() { return at_start_; }
set_at_start(bool at_start)1101   void set_at_start(bool at_start) { at_start_ = at_start ? TRUE : FALSE; }
backtrack()1102   Label* backtrack() { return backtrack_; }
loop_label()1103   Label* loop_label() { return loop_label_; }
stop_node()1104   RegExpNode* stop_node() { return stop_node_; }
characters_preloaded()1105   int characters_preloaded() { return characters_preloaded_; }
bound_checked_up_to()1106   int bound_checked_up_to() { return bound_checked_up_to_; }
flush_budget()1107   int flush_budget() { return flush_budget_; }
quick_check_performed()1108   QuickCheckDetails* quick_check_performed() { return &quick_check_performed_; }
1109   bool mentions_reg(int reg);
1110   // Returns true if a deferred position store exists to the specified
1111   // register and stores the offset in the out-parameter.  Otherwise
1112   // returns false.
1113   bool GetStoredPosition(int reg, int* cp_offset);
1114   // These set methods and AdvanceCurrentPositionInTrace should be used only on
1115   // new traces - the intention is that traces are immutable after creation.
add_action(DeferredAction * new_action)1116   void add_action(DeferredAction* new_action) {
1117     ASSERT(new_action->next_ == NULL);
1118     new_action->next_ = actions_;
1119     actions_ = new_action;
1120   }
set_backtrack(Label * backtrack)1121   void set_backtrack(Label* backtrack) { backtrack_ = backtrack; }
set_stop_node(RegExpNode * node)1122   void set_stop_node(RegExpNode* node) { stop_node_ = node; }
set_loop_label(Label * label)1123   void set_loop_label(Label* label) { loop_label_ = label; }
set_characters_preloaded(int cpre)1124   void set_characters_preloaded(int cpre) { characters_preloaded_ = cpre; }
set_bound_checked_up_to(int to)1125   void set_bound_checked_up_to(int to) { bound_checked_up_to_ = to; }
set_flush_budget(int to)1126   void set_flush_budget(int to) { flush_budget_ = to; }
set_quick_check_performed(QuickCheckDetails * d)1127   void set_quick_check_performed(QuickCheckDetails* d) {
1128     quick_check_performed_ = *d;
1129   }
1130   void InvalidateCurrentCharacter();
1131   void AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler);
1132  private:
1133   int FindAffectedRegisters(OutSet* affected_registers);
1134   void PerformDeferredActions(RegExpMacroAssembler* macro,
1135                                int max_register,
1136                                OutSet& affected_registers,
1137                                OutSet* registers_to_pop,
1138                                OutSet* registers_to_clear);
1139   void RestoreAffectedRegisters(RegExpMacroAssembler* macro,
1140                                 int max_register,
1141                                 OutSet& registers_to_pop,
1142                                 OutSet& registers_to_clear);
1143   int cp_offset_;
1144   DeferredAction* actions_;
1145   Label* backtrack_;
1146   RegExpNode* stop_node_;
1147   Label* loop_label_;
1148   int characters_preloaded_;
1149   int bound_checked_up_to_;
1150   QuickCheckDetails quick_check_performed_;
1151   int flush_budget_;
1152   TriBool at_start_;
1153 };
1154 
1155 
1156 class NodeVisitor {
1157  public:
~NodeVisitor()1158   virtual ~NodeVisitor() { }
1159 #define DECLARE_VISIT(Type)                                          \
1160   virtual void Visit##Type(Type##Node* that) = 0;
FOR_EACH_NODE_TYPE(DECLARE_VISIT)1161 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1162 #undef DECLARE_VISIT
1163   virtual void VisitLoopChoice(LoopChoiceNode* that) { VisitChoice(that); }
1164 };
1165 
1166 
1167 // Node visitor used to add the start set of the alternatives to the
1168 // dispatch table of a choice node.
1169 class DispatchTableConstructor: public NodeVisitor {
1170  public:
DispatchTableConstructor(DispatchTable * table,bool ignore_case)1171   DispatchTableConstructor(DispatchTable* table, bool ignore_case)
1172       : table_(table),
1173         choice_index_(-1),
1174         ignore_case_(ignore_case) { }
1175 
1176   void BuildTable(ChoiceNode* node);
1177 
AddRange(CharacterRange range)1178   void AddRange(CharacterRange range) {
1179     table()->AddRange(range, choice_index_);
1180   }
1181 
1182   void AddInverse(ZoneList<CharacterRange>* ranges);
1183 
1184 #define DECLARE_VISIT(Type)                                          \
1185   virtual void Visit##Type(Type##Node* that);
FOR_EACH_NODE_TYPE(DECLARE_VISIT)1186 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1187 #undef DECLARE_VISIT
1188 
1189   DispatchTable* table() { return table_; }
set_choice_index(int value)1190   void set_choice_index(int value) { choice_index_ = value; }
1191 
1192  protected:
1193   DispatchTable* table_;
1194   int choice_index_;
1195   bool ignore_case_;
1196 };
1197 
1198 
1199 // Assertion propagation moves information about assertions such as
1200 // \b to the affected nodes.  For instance, in /.\b./ information must
1201 // be propagated to the first '.' that whatever follows needs to know
1202 // if it matched a word or a non-word, and to the second '.' that it
1203 // has to check if it succeeds a word or non-word.  In this case the
1204 // result will be something like:
1205 //
1206 //   +-------+        +------------+
1207 //   |   .   |        |      .     |
1208 //   +-------+  --->  +------------+
1209 //   | word? |        | check word |
1210 //   +-------+        +------------+
1211 class Analysis: public NodeVisitor {
1212  public:
Analysis(bool ignore_case)1213   explicit Analysis(bool ignore_case)
1214       : ignore_case_(ignore_case), error_message_(NULL) { }
1215   void EnsureAnalyzed(RegExpNode* node);
1216 
1217 #define DECLARE_VISIT(Type)                                          \
1218   virtual void Visit##Type(Type##Node* that);
1219 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1220 #undef DECLARE_VISIT
1221   virtual void VisitLoopChoice(LoopChoiceNode* that);
1222 
has_failed()1223   bool has_failed() { return error_message_ != NULL; }
error_message()1224   const char* error_message() {
1225     ASSERT(error_message_ != NULL);
1226     return error_message_;
1227   }
fail(const char * error_message)1228   void fail(const char* error_message) {
1229     error_message_ = error_message;
1230   }
1231  private:
1232   bool ignore_case_;
1233   const char* error_message_;
1234 
1235   DISALLOW_IMPLICIT_CONSTRUCTORS(Analysis);
1236 };
1237 
1238 
1239 struct RegExpCompileData {
RegExpCompileDataRegExpCompileData1240   RegExpCompileData()
1241     : tree(NULL),
1242       node(NULL),
1243       simple(true),
1244       contains_anchor(false),
1245       capture_count(0) { }
1246   RegExpTree* tree;
1247   RegExpNode* node;
1248   bool simple;
1249   bool contains_anchor;
1250   Handle<String> error;
1251   int capture_count;
1252 };
1253 
1254 
1255 class RegExpEngine: public AllStatic {
1256  public:
1257   struct CompilationResult {
CompilationResultCompilationResult1258     explicit CompilationResult(const char* error_message)
1259         : error_message(error_message),
1260           code(Heap::the_hole_value()),
1261           num_registers(0) {}
CompilationResultCompilationResult1262     CompilationResult(Object* code, int registers)
1263       : error_message(NULL),
1264         code(code),
1265         num_registers(registers) {}
1266     const char* error_message;
1267     Object* code;
1268     int num_registers;
1269   };
1270 
1271   static CompilationResult Compile(RegExpCompileData* input,
1272                                    bool ignore_case,
1273                                    bool multiline,
1274                                    Handle<String> pattern,
1275                                    bool is_ascii);
1276 
1277   static void DotPrint(const char* label, RegExpNode* node, bool ignore_case);
1278 };
1279 
1280 
1281 } }  // namespace v8::internal
1282 
1283 #endif  // V8_JSREGEXP_H_
1284