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