blob: c0d50a3088da11b439f83797fbf3b76f199cf100 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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
31namespace v8 { namespace internal {
32
ager@chromium.orga74f0da2008-12-03 16:05:52 +000033
34class RegExpMacroAssembler;
35
36
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037class RegExpImpl {
38 public:
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000039 static inline bool UseNativeRegexp() {
ager@chromium.org5ec48922009-05-05 07:25:34 +000040#ifdef V8_ARCH_ARM
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000041 return false;
ager@chromium.org5ec48922009-05-05 07:25:34 +000042#endif
43#ifdef V8_ARCH_X64
44 return false;
45#endif
46#ifdef V8_ARCH_IA32
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000047 return FLAG_regexp_native;
48#endif
49 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000050 // Creates a regular expression literal in the old space.
51 // This function calls the garbage collector if necessary.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000052 static Handle<Object> CreateRegExpLiteral(Handle<JSFunction> constructor,
53 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000054 Handle<String> flags,
55 bool* has_pending_exception);
56
57 // Returns a string representation of a regular expression.
58 // Implements RegExp.prototype.toString, see ECMA-262 section 15.10.6.4.
59 // This function calls the garbage collector if necessary.
60 static Handle<String> ToString(Handle<Object> value);
61
ager@chromium.org8bb60582008-12-11 12:02:20 +000062 // Parses the RegExp pattern and prepares the JSRegExp object with
63 // generic data and choice of implementation - as well as what
64 // the implementation wants to store in the data field.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000065 // Returns false if compilation fails.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000066 static Handle<Object> Compile(Handle<JSRegExp> re,
67 Handle<String> pattern,
68 Handle<String> flags);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000069
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000070 // See ECMA-262 section 15.10.6.2.
71 // This function calls the garbage collector if necessary.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000072 static Handle<Object> Exec(Handle<JSRegExp> regexp,
73 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000074 int index,
75 Handle<JSArray> lastMatchInfo);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000076
77 // Call RegExp.prototyp.exec(string) in a loop.
78 // Used by String.prototype.match and String.prototype.replace.
79 // This function calls the garbage collector if necessary.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000080 static Handle<Object> ExecGlobal(Handle<JSRegExp> regexp,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000081 Handle<String> subject,
82 Handle<JSArray> lastMatchInfo);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000083
ager@chromium.org8bb60582008-12-11 12:02:20 +000084 // Prepares a JSRegExp object with Irregexp-specific data.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000085 static void IrregexpPrepare(Handle<JSRegExp> re,
86 Handle<String> pattern,
87 JSRegExp::Flags flags,
88 int capture_register_count);
ager@chromium.orga74f0da2008-12-03 16:05:52 +000089
90
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000091 static void AtomCompile(Handle<JSRegExp> re,
92 Handle<String> pattern,
93 JSRegExp::Flags flags,
94 Handle<String> match_pattern);
95
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000096 static Handle<Object> AtomExec(Handle<JSRegExp> regexp,
97 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000098 int index,
99 Handle<JSArray> lastMatchInfo);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000100
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000101 // Execute an Irregexp bytecode pattern.
ager@chromium.org41826e72009-03-30 13:30:57 +0000102 // On a successful match, the result is a JSArray containing
103 // captured positions. On a failure, the result is the null value.
104 // Returns an empty handle in case of an exception.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000105 static Handle<Object> IrregexpExec(Handle<JSRegExp> regexp,
106 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000107 int index,
108 Handle<JSArray> lastMatchInfo);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000109
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000110 // Offsets in the lastMatchInfo array.
111 static const int kLastCaptureCount = 0;
112 static const int kLastSubject = 1;
113 static const int kLastInput = 2;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000114 static const int kFirstCapture = 3;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000115 static const int kLastMatchOverhead = 3;
116
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000117 // Used to access the lastMatchInfo array.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000118 static int GetCapture(FixedArray* array, int index) {
119 return Smi::cast(array->get(index + kFirstCapture))->value();
120 }
121
122 static void SetLastCaptureCount(FixedArray* array, int to) {
123 array->set(kLastCaptureCount, Smi::FromInt(to));
124 }
125
126 static void SetLastSubject(FixedArray* array, String* to) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000127 array->set(kLastSubject, to);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000128 }
129
130 static void SetLastInput(FixedArray* array, String* to) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000131 array->set(kLastInput, to);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000132 }
133
134 static void SetCapture(FixedArray* array, int index, int to) {
135 array->set(index + kFirstCapture, Smi::FromInt(to));
136 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000137
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000138 static int GetLastCaptureCount(FixedArray* array) {
139 return Smi::cast(array->get(kLastCaptureCount))->value();
140 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000141
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000142 // For acting on the JSRegExp data FixedArray.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000143 static int IrregexpMaxRegisterCount(FixedArray* re);
144 static void SetIrregexpMaxRegisterCount(FixedArray* re, int value);
145 static int IrregexpNumberOfCaptures(FixedArray* re);
146 static int IrregexpNumberOfRegisters(FixedArray* re);
147 static ByteArray* IrregexpByteCode(FixedArray* re, bool is_ascii);
148 static Code* IrregexpNativeCode(FixedArray* re, bool is_ascii);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000149
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000150 private:
151 static String* last_ascii_string_;
152 static String* two_byte_cached_string_;
153
154 static bool EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii);
155
156
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000157 // Set the subject cache. The previous string buffer is not deleted, so the
158 // caller should ensure that it doesn't leak.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000159 static void SetSubjectCache(String* subject,
160 char* utf8_subject,
161 int uft8_length,
162 int character_position,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000163 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
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000175class CharacterRange {
176 public:
177 CharacterRange() : from_(0), to_(0) { }
178 // For compatibility with the CHECK_OK macro
179 CharacterRange(void* null) { ASSERT_EQ(NULL, null); } //NOLINT
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();
183 static inline CharacterRange Singleton(uc16 value) {
184 return CharacterRange(value, value);
185 }
186 static inline CharacterRange Range(uc16 from, uc16 to) {
187 ASSERT(from <= to);
188 return CharacterRange(from, to);
189 }
190 static inline CharacterRange Everything() {
191 return CharacterRange(0, 0xFFFF);
192 }
193 bool Contains(uc16 i) { return from_ <= i && i <= to_; }
194 uc16 from() const { return from_; }
195 void set_from(uc16 value) { from_ = value; }
196 uc16 to() const { return to_; }
197 void set_to(uc16 value) { to_ = value; }
198 bool is_valid() { return from_ <= to_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000199 bool IsEverything(uc16 max) { return from_ == 0 && to_ >= max; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000200 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
217template <typename Node, class Callback>
218static void DoForEach(Node* node, Callback* callback);
219
220
221// A zone splay tree. The config type parameter encapsulates the
222// different configurations of a concrete splay tree:
223//
224// typedef Key: the key type
225// typedef Value: the value type
226// static const kNoKey: the dummy key used when no key is set
227// static const kNoValue: the dummy value used to initialize nodes
228// int (Compare)(Key& a, Key& b) -> {-1, 0, 1}: comparison function
229//
230template <typename Config>
231class ZoneSplayTree : public ZoneObject {
232 public:
233 typedef typename Config::Key Key;
234 typedef typename Config::Value Value;
235
236 class Locator;
237
238 ZoneSplayTree() : root_(NULL) { }
239
240 // Inserts the given key in this tree with the given value. Returns
241 // true if a node was inserted, otherwise false. If found the locator
242 // is enabled and provides access to the mapping for the key.
243 bool Insert(const Key& key, Locator* locator);
244
245 // Looks up the key in this tree and returns true if it was found,
246 // otherwise false. If the node is found the locator is enabled and
247 // provides access to the mapping for the key.
248 bool Find(const Key& key, Locator* locator);
249
250 // Finds the mapping with the greatest key less than or equal to the
251 // given key.
252 bool FindGreatestLessThan(const Key& key, Locator* locator);
253
254 // Find the mapping with the greatest key in this tree.
255 bool FindGreatest(Locator* locator);
256
257 // Finds the mapping with the least key greater than or equal to the
258 // given key.
259 bool FindLeastGreaterThan(const Key& key, Locator* locator);
260
261 // Find the mapping with the least key in this tree.
262 bool FindLeast(Locator* locator);
263
264 // Remove the node with the given key from the tree.
265 bool Remove(const Key& key);
266
267 bool is_empty() { return root_ == NULL; }
268
269 // Perform the splay operation for the given key. Moves the node with
270 // the given key to the top of the tree. If no node has the given
271 // key, the last node on the search path is moved to the top of the
272 // tree.
273 void Splay(const Key& key);
274
275 class Node : public ZoneObject {
276 public:
277 Node(const Key& key, const Value& value)
278 : key_(key),
279 value_(value),
280 left_(NULL),
281 right_(NULL) { }
282 Key key() { return key_; }
283 Value value() { return value_; }
284 Node* left() { return left_; }
285 Node* right() { return right_; }
286 private:
287 friend class ZoneSplayTree;
288 friend class Locator;
289 Key key_;
290 Value value_;
291 Node* left_;
292 Node* right_;
293 };
294
295 // A locator provides access to a node in the tree without actually
296 // exposing the node.
297 class Locator {
298 public:
299 explicit Locator(Node* node) : node_(node) { }
300 Locator() : node_(NULL) { }
301 const Key& key() { return node_->key_; }
302 Value& value() { return node_->value_; }
303 void set_value(const Value& value) { node_->value_ = value; }
304 inline void bind(Node* node) { node_ = node; }
305 private:
306 Node* node_;
307 };
308
309 template <class Callback>
310 void ForEach(Callback* c) {
311 DoForEach<typename ZoneSplayTree<Config>::Node, Callback>(root_, c);
312 }
313
314 private:
315 Node* root_;
316};
317
318
319// A set of unsigned integers that behaves especially well on small
320// integers (< 32). May do zone-allocation.
321class OutSet: public ZoneObject {
322 public:
323 OutSet() : first_(0), remaining_(NULL), successors_(NULL) { }
324 OutSet* Extend(unsigned value);
325 bool Get(unsigned value);
326 static const unsigned kFirstLimit = 32;
327
328 private:
329 // Destructively set a value in this set. In most cases you want
330 // to use Extend instead to ensure that only one instance exists
331 // that contains the same values.
332 void Set(unsigned value);
333
334 // The successors are a list of sets that contain the same values
335 // as this set and the one more value that is not present in this
336 // set.
337 ZoneList<OutSet*>* successors() { return successors_; }
338
339 OutSet(uint32_t first, ZoneList<unsigned>* remaining)
340 : first_(first), remaining_(remaining), successors_(NULL) { }
341 uint32_t first_;
342 ZoneList<unsigned>* remaining_;
343 ZoneList<OutSet*>* successors_;
ager@chromium.org32912102009-01-16 10:38:43 +0000344 friend class Trace;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000345};
346
347
348// A mapping from integers, specified as ranges, to a set of integers.
349// Used for mapping character ranges to choices.
350class DispatchTable : public ZoneObject {
351 public:
352 class Entry {
353 public:
354 Entry() : from_(0), to_(0), out_set_(NULL) { }
355 Entry(uc16 from, uc16 to, OutSet* out_set)
356 : from_(from), to_(to), out_set_(out_set) { }
357 uc16 from() { return from_; }
358 uc16 to() { return to_; }
359 void set_to(uc16 value) { to_ = value; }
360 void AddValue(int value) { out_set_ = out_set_->Extend(value); }
361 OutSet* out_set() { return out_set_; }
362 private:
363 uc16 from_;
364 uc16 to_;
365 OutSet* out_set_;
366 };
367
368 class Config {
369 public:
370 typedef uc16 Key;
371 typedef Entry Value;
372 static const uc16 kNoKey;
373 static const Entry kNoValue;
374 static inline int Compare(uc16 a, uc16 b) {
375 if (a == b)
376 return 0;
377 else if (a < b)
378 return -1;
379 else
380 return 1;
381 }
382 };
383
384 void AddRange(CharacterRange range, int value);
385 OutSet* Get(uc16 value);
386 void Dump();
387
388 template <typename Callback>
389 void ForEach(Callback* callback) { return tree()->ForEach(callback); }
390 private:
391 // There can't be a static empty set since it allocates its
392 // successors in a zone and caches them.
393 OutSet* empty() { return &empty_; }
394 OutSet empty_;
395 ZoneSplayTree<Config>* tree() { return &tree_; }
396 ZoneSplayTree<Config> tree_;
397};
398
399
400#define FOR_EACH_NODE_TYPE(VISIT) \
401 VISIT(End) \
402 VISIT(Action) \
403 VISIT(Choice) \
404 VISIT(BackReference) \
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000405 VISIT(Assertion) \
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000406 VISIT(Text)
407
408
409#define FOR_EACH_REG_EXP_TREE_TYPE(VISIT) \
410 VISIT(Disjunction) \
411 VISIT(Alternative) \
412 VISIT(Assertion) \
413 VISIT(CharacterClass) \
414 VISIT(Atom) \
415 VISIT(Quantifier) \
416 VISIT(Capture) \
417 VISIT(Lookahead) \
418 VISIT(BackReference) \
419 VISIT(Empty) \
420 VISIT(Text)
421
422
423#define FORWARD_DECLARE(Name) class RegExp##Name;
424FOR_EACH_REG_EXP_TREE_TYPE(FORWARD_DECLARE)
425#undef FORWARD_DECLARE
426
427
428class TextElement {
429 public:
430 enum Type {UNINITIALIZED, ATOM, CHAR_CLASS};
431 TextElement() : type(UNINITIALIZED) { }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000432 explicit TextElement(Type t) : type(t), cp_offset(-1) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000433 static TextElement Atom(RegExpAtom* atom);
434 static TextElement CharClass(RegExpCharacterClass* char_class);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000435 int length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000436 Type type;
437 union {
438 RegExpAtom* u_atom;
439 RegExpCharacterClass* u_char_class;
440 } data;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000441 int cp_offset;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000442};
443
444
ager@chromium.org32912102009-01-16 10:38:43 +0000445class Trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000446
447
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000448struct NodeInfo {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000449 NodeInfo()
450 : being_analyzed(false),
451 been_analyzed(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000452 follows_word_interest(false),
453 follows_newline_interest(false),
454 follows_start_interest(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000455 at_end(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000456 visited(false) { }
457
458 // Returns true if the interests and assumptions of this node
459 // matches the given one.
460 bool Matches(NodeInfo* that) {
461 return (at_end == that->at_end) &&
462 (follows_word_interest == that->follows_word_interest) &&
463 (follows_newline_interest == that->follows_newline_interest) &&
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000464 (follows_start_interest == that->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000465 }
466
467 // Updates the interests of this node given the interests of the
468 // node preceding it.
469 void AddFromPreceding(NodeInfo* that) {
470 at_end |= that->at_end;
471 follows_word_interest |= that->follows_word_interest;
472 follows_newline_interest |= that->follows_newline_interest;
473 follows_start_interest |= that->follows_start_interest;
474 }
475
ager@chromium.org8bb60582008-12-11 12:02:20 +0000476 bool HasLookbehind() {
477 return follows_word_interest ||
478 follows_newline_interest ||
479 follows_start_interest;
480 }
481
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000482 // Sets the interests of this node to include the interests of the
483 // following node.
484 void AddFromFollowing(NodeInfo* that) {
485 follows_word_interest |= that->follows_word_interest;
486 follows_newline_interest |= that->follows_newline_interest;
487 follows_start_interest |= that->follows_start_interest;
488 }
489
490 void ResetCompilationState() {
491 being_analyzed = false;
492 been_analyzed = false;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000493 }
494
495 bool being_analyzed: 1;
496 bool been_analyzed: 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000497
498 // These bits are set of this node has to know what the preceding
499 // character was.
500 bool follows_word_interest: 1;
501 bool follows_newline_interest: 1;
502 bool follows_start_interest: 1;
503
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000504 bool at_end: 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000505 bool visited: 1;
506};
507
508
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000509class SiblingList {
510 public:
511 SiblingList() : list_(NULL) { }
512 int length() {
513 return list_ == NULL ? 0 : list_->length();
514 }
515 void Ensure(RegExpNode* parent) {
516 if (list_ == NULL) {
517 list_ = new ZoneList<RegExpNode*>(2);
518 list_->Add(parent);
519 }
520 }
521 void Add(RegExpNode* node) { list_->Add(node); }
522 RegExpNode* Get(int index) { return list_->at(index); }
523 private:
524 ZoneList<RegExpNode*>* list_;
525};
526
527
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000528// Details of a quick mask-compare check that can look ahead in the
529// input stream.
530class QuickCheckDetails {
531 public:
532 QuickCheckDetails()
533 : characters_(0),
534 mask_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000535 value_(0),
536 cannot_match_(false) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000537 explicit QuickCheckDetails(int characters)
538 : characters_(characters),
539 mask_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000540 value_(0),
541 cannot_match_(false) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000542 bool Rationalize(bool ascii);
543 // Merge in the information from another branch of an alternation.
544 void Merge(QuickCheckDetails* other, int from_index);
545 // Advance the current position by some amount.
546 void Advance(int by, bool ascii);
547 void Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000548 bool cannot_match() { return cannot_match_; }
549 void set_cannot_match() { cannot_match_ = true; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000550 struct Position {
551 Position() : mask(0), value(0), determines_perfectly(false) { }
552 uc16 mask;
553 uc16 value;
554 bool determines_perfectly;
555 };
556 int characters() { return characters_; }
557 void set_characters(int characters) { characters_ = characters; }
558 Position* positions(int index) {
559 ASSERT(index >= 0);
560 ASSERT(index < characters_);
561 return positions_ + index;
562 }
563 uint32_t mask() { return mask_; }
564 uint32_t value() { return value_; }
565
566 private:
567 // How many characters do we have quick check information from. This is
568 // the same for all branches of a choice node.
569 int characters_;
570 Position positions_[4];
571 // These values are the condensate of the above array after Rationalize().
572 uint32_t mask_;
573 uint32_t value_;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000574 // If set to true, there is no way this quick check can match at all.
575 // E.g., if it requires to be at the start of the input, and isn't.
576 bool cannot_match_;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000577};
578
579
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000580class RegExpNode: public ZoneObject {
581 public:
ager@chromium.org32912102009-01-16 10:38:43 +0000582 RegExpNode() : trace_count_(0) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000583 virtual ~RegExpNode();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000584 virtual void Accept(NodeVisitor* visitor) = 0;
585 // Generates a goto to this node or actually generates the code at this point.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000586 virtual void Emit(RegExpCompiler* compiler, Trace* trace) = 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000587 // How many characters must this node consume at a minimum in order to
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000588 // succeed. If we have found at least 'still_to_find' characters that
589 // must be consumed there is no need to ask any following nodes whether
590 // they are sure to eat any more characters.
591 virtual int EatsAtLeast(int still_to_find, int recursion_depth) = 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000592 // Emits some quick code that checks whether the preloaded characters match.
593 // Falls through on certain failure, jumps to the label on possible success.
594 // If the node cannot make a quick check it does nothing and returns false.
595 bool EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +0000596 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000597 bool preload_has_checked_bounds,
598 Label* on_possible_success,
599 QuickCheckDetails* details_return,
600 bool fall_through_on_failure);
601 // For a given number of characters this returns a mask and a value. The
602 // next n characters are anded with the mask and compared with the value.
603 // A comparison failure indicates the node cannot match the next n characters.
604 // A comparison success indicates the node may match.
605 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
606 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000607 int characters_filled_in,
608 bool not_at_start) = 0;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000609 static const int kNodeIsTooComplexForGreedyLoops = -1;
610 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
611 Label* label() { return &label_; }
ager@chromium.org32912102009-01-16 10:38:43 +0000612 // If non-generic code is generated for a node (ie the node is not at the
613 // start of the trace) then it cannot be reused. This variable sets a limit
614 // on how often we allow that to happen before we insist on starting a new
615 // trace and generating generic code for a node that can be reused by flushing
616 // the deferred actions in the current trace and generating a goto.
617 static const int kMaxCopiesCodeGenerated = 10;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000618
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000619 NodeInfo* info() { return &info_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000620
621 void AddSibling(RegExpNode* node) { siblings_.Add(node); }
622
623 // Static version of EnsureSibling that expresses the fact that the
624 // result has the same type as the input.
625 template <class C>
626 static C* EnsureSibling(C* node, NodeInfo* info, bool* cloned) {
627 return static_cast<C*>(node->EnsureSibling(info, cloned));
628 }
629
630 SiblingList* siblings() { return &siblings_; }
631 void set_siblings(SiblingList* other) { siblings_ = *other; }
632
633 protected:
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000634 enum LimitResult { DONE, CONTINUE };
ager@chromium.org32912102009-01-16 10:38:43 +0000635 LimitResult LimitVersions(RegExpCompiler* compiler, Trace* trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000636
637 // Returns a sibling of this node whose interests and assumptions
638 // match the ones in the given node info. If no sibling exists NULL
639 // is returned.
640 RegExpNode* TryGetSibling(NodeInfo* info);
641
642 // Returns a sibling of this node whose interests match the ones in
643 // the given node info. The info must not contain any assertions.
644 // If no node exists a new one will be created by cloning the current
645 // node. The result will always be an instance of the same concrete
646 // class as this node.
647 RegExpNode* EnsureSibling(NodeInfo* info, bool* cloned);
648
649 // Returns a clone of this node initialized using the copy constructor
650 // of its concrete class. Note that the node may have to be pre-
ager@chromium.org32912102009-01-16 10:38:43 +0000651 // processed before it is on a usable state.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000652 virtual RegExpNode* Clone() = 0;
653
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000654 private:
655 Label label_;
656 NodeInfo info_;
657 SiblingList siblings_;
ager@chromium.org32912102009-01-16 10:38:43 +0000658 // This variable keeps track of how many times code has been generated for
659 // this node (in different traces). We don't keep track of where the
660 // generated code is located unless the code is generated at the start of
661 // a trace, in which case it is generic and can be reused by flushing the
662 // deferred operations in the current trace and generating a goto.
663 int trace_count_;
664};
665
666
667// A simple closed interval.
668class Interval {
669 public:
670 Interval() : from_(kNone), to_(kNone) { }
671 Interval(int from, int to) : from_(from), to_(to) { }
672 Interval Union(Interval that) {
673 if (that.from_ == kNone)
674 return *this;
675 else if (from_ == kNone)
676 return that;
677 else
678 return Interval(Min(from_, that.from_), Max(to_, that.to_));
679 }
680 bool Contains(int value) {
681 return (from_ <= value) && (value <= to_);
682 }
683 bool is_empty() { return from_ == kNone; }
684 int from() { return from_; }
685 int to() { return to_; }
686 static Interval Empty() { return Interval(); }
687 static const int kNone = -1;
688 private:
689 int from_;
690 int to_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000691};
692
693
694class SeqRegExpNode: public RegExpNode {
695 public:
696 explicit SeqRegExpNode(RegExpNode* on_success)
697 : on_success_(on_success) { }
698 RegExpNode* on_success() { return on_success_; }
699 void set_on_success(RegExpNode* node) { on_success_ = node; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000700 private:
701 RegExpNode* on_success_;
702};
703
704
705class ActionNode: public SeqRegExpNode {
706 public:
707 enum Type {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000708 SET_REGISTER,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000709 INCREMENT_REGISTER,
710 STORE_POSITION,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000711 BEGIN_SUBMATCH,
ager@chromium.org32912102009-01-16 10:38:43 +0000712 POSITIVE_SUBMATCH_SUCCESS,
713 EMPTY_MATCH_CHECK,
714 CLEAR_CAPTURES
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000715 };
ager@chromium.org8bb60582008-12-11 12:02:20 +0000716 static ActionNode* SetRegister(int reg, int val, RegExpNode* on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000717 static ActionNode* IncrementRegister(int reg, RegExpNode* on_success);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000718 static ActionNode* StorePosition(int reg,
719 bool is_capture,
720 RegExpNode* on_success);
ager@chromium.org32912102009-01-16 10:38:43 +0000721 static ActionNode* ClearCaptures(Interval range, RegExpNode* on_success);
722 static ActionNode* BeginSubmatch(int stack_pointer_reg,
723 int position_reg,
724 RegExpNode* on_success);
725 static ActionNode* PositiveSubmatchSuccess(int stack_pointer_reg,
726 int restore_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000727 int clear_capture_count,
728 int clear_capture_from,
ager@chromium.org32912102009-01-16 10:38:43 +0000729 RegExpNode* on_success);
730 static ActionNode* EmptyMatchCheck(int start_register,
731 int repetition_register,
732 int repetition_limit,
733 RegExpNode* on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000734 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000735 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
736 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000737 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
738 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000739 int filled_in,
740 bool not_at_start) {
741 return on_success()->GetQuickCheckDetails(
742 details, compiler, filled_in, not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000743 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000744 Type type() { return type_; }
745 // TODO(erikcorry): We should allow some action nodes in greedy loops.
746 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000747 virtual ActionNode* Clone() { return new ActionNode(*this); }
748
749 private:
750 union {
751 struct {
752 int reg;
753 int value;
754 } u_store_register;
755 struct {
756 int reg;
757 } u_increment_register;
758 struct {
759 int reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000760 bool is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000761 } u_position_register;
762 struct {
763 int stack_pointer_register;
764 int current_position_register;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000765 int clear_register_count;
766 int clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000767 } u_submatch;
ager@chromium.org32912102009-01-16 10:38:43 +0000768 struct {
769 int start_register;
770 int repetition_register;
771 int repetition_limit;
772 } u_empty_match_check;
773 struct {
774 int range_from;
775 int range_to;
776 } u_clear_captures;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000777 } data_;
778 ActionNode(Type type, RegExpNode* on_success)
779 : SeqRegExpNode(on_success),
780 type_(type) { }
781 Type type_;
782 friend class DotPrinter;
783};
784
785
786class TextNode: public SeqRegExpNode {
787 public:
788 TextNode(ZoneList<TextElement>* elms,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000789 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000790 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000791 elms_(elms) { }
792 TextNode(RegExpCharacterClass* that,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000793 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000794 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000795 elms_(new ZoneList<TextElement>(1)) {
796 elms_->Add(TextElement::CharClass(that));
797 }
798 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000799 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
800 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000801 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
802 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000803 int characters_filled_in,
804 bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000805 ZoneList<TextElement>* elements() { return elms_; }
806 void MakeCaseIndependent();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000807 virtual int GreedyLoopTextLength();
808 virtual TextNode* Clone() {
809 TextNode* result = new TextNode(*this);
810 result->CalculateOffsets();
811 return result;
812 }
813 void CalculateOffsets();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000814
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000815 private:
816 enum TextEmitPassType {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000817 NON_ASCII_MATCH, // Check for characters that can't match.
818 SIMPLE_CHARACTER_MATCH, // Case-dependent single character check.
819 NON_LETTER_CHARACTER_MATCH, // Check characters that have no case equivs.
820 CASE_CHARACTER_MATCH, // Case-independent single character check.
821 CHARACTER_CLASS_MATCH // Character class.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000822 };
ager@chromium.org381abbb2009-02-25 13:23:22 +0000823 static bool SkipPass(int pass, bool ignore_case);
824 static const int kFirstRealPass = SIMPLE_CHARACTER_MATCH;
825 static const int kLastPass = CHARACTER_CLASS_MATCH;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000826 void TextEmitPass(RegExpCompiler* compiler,
827 TextEmitPassType pass,
828 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +0000829 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000830 bool first_element_checked,
831 int* checked_up_to);
832 int Length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000833 ZoneList<TextElement>* elms_;
834};
835
836
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000837class AssertionNode: public SeqRegExpNode {
838 public:
839 enum AssertionNodeType {
840 AT_END,
841 AT_START,
842 AT_BOUNDARY,
843 AT_NON_BOUNDARY,
844 AFTER_NEWLINE
845 };
846 static AssertionNode* AtEnd(RegExpNode* on_success) {
847 return new AssertionNode(AT_END, on_success);
848 }
849 static AssertionNode* AtStart(RegExpNode* on_success) {
850 return new AssertionNode(AT_START, on_success);
851 }
852 static AssertionNode* AtBoundary(RegExpNode* on_success) {
853 return new AssertionNode(AT_BOUNDARY, on_success);
854 }
855 static AssertionNode* AtNonBoundary(RegExpNode* on_success) {
856 return new AssertionNode(AT_NON_BOUNDARY, on_success);
857 }
858 static AssertionNode* AfterNewline(RegExpNode* on_success) {
859 return new AssertionNode(AFTER_NEWLINE, on_success);
860 }
861 virtual void Accept(NodeVisitor* visitor);
862 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
863 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
864 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
865 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000866 int filled_in,
867 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000868 virtual AssertionNode* Clone() { return new AssertionNode(*this); }
869 AssertionNodeType type() { return type_; }
870 private:
871 AssertionNode(AssertionNodeType t, RegExpNode* on_success)
872 : SeqRegExpNode(on_success), type_(t) { }
873 AssertionNodeType type_;
874};
875
876
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000877class BackReferenceNode: public SeqRegExpNode {
878 public:
879 BackReferenceNode(int start_reg,
880 int end_reg,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000881 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000882 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000883 start_reg_(start_reg),
884 end_reg_(end_reg) { }
885 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000886 int start_register() { return start_reg_; }
887 int end_register() { return end_reg_; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000888 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
889 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000890 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
891 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000892 int characters_filled_in,
893 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000894 return;
895 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000896 virtual BackReferenceNode* Clone() { return new BackReferenceNode(*this); }
897
898 private:
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000899 int start_reg_;
900 int end_reg_;
901};
902
903
904class EndNode: public RegExpNode {
905 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000906 enum Action { ACCEPT, BACKTRACK, NEGATIVE_SUBMATCH_SUCCESS };
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000907 explicit EndNode(Action action) : action_(action) { }
908 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000909 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
910 virtual int EatsAtLeast(int still_to_find, int recursion_depth) { return 0; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000911 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
912 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000913 int characters_filled_in,
914 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000915 // Returning 0 from EatsAtLeast should ensure we never get here.
916 UNREACHABLE();
917 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000918 virtual EndNode* Clone() { return new EndNode(*this); }
919
920 private:
921 Action action_;
922};
923
924
ager@chromium.org8bb60582008-12-11 12:02:20 +0000925class NegativeSubmatchSuccess: public EndNode {
926 public:
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000927 NegativeSubmatchSuccess(int stack_pointer_reg,
928 int position_reg,
929 int clear_capture_count,
930 int clear_capture_start)
ager@chromium.org8bb60582008-12-11 12:02:20 +0000931 : EndNode(NEGATIVE_SUBMATCH_SUCCESS),
932 stack_pointer_register_(stack_pointer_reg),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000933 current_position_register_(position_reg),
934 clear_capture_count_(clear_capture_count),
935 clear_capture_start_(clear_capture_start) { }
936 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000937
938 private:
939 int stack_pointer_register_;
940 int current_position_register_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000941 int clear_capture_count_;
942 int clear_capture_start_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000943};
944
945
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000946class Guard: public ZoneObject {
947 public:
948 enum Relation { LT, GEQ };
949 Guard(int reg, Relation op, int value)
950 : reg_(reg),
951 op_(op),
952 value_(value) { }
953 int reg() { return reg_; }
954 Relation op() { return op_; }
955 int value() { return value_; }
956
957 private:
958 int reg_;
959 Relation op_;
960 int value_;
961};
962
963
964class GuardedAlternative {
965 public:
966 explicit GuardedAlternative(RegExpNode* node) : node_(node), guards_(NULL) { }
967 void AddGuard(Guard* guard);
968 RegExpNode* node() { return node_; }
969 void set_node(RegExpNode* node) { node_ = node; }
970 ZoneList<Guard*>* guards() { return guards_; }
971
972 private:
973 RegExpNode* node_;
974 ZoneList<Guard*>* guards_;
975};
976
977
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000978class AlternativeGeneration;
979
980
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000981class ChoiceNode: public RegExpNode {
982 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000983 explicit ChoiceNode(int expected_size)
984 : alternatives_(new ZoneList<GuardedAlternative>(expected_size)),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000985 table_(NULL),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000986 not_at_start_(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000987 being_calculated_(false) { }
988 virtual void Accept(NodeVisitor* visitor);
989 void AddAlternative(GuardedAlternative node) { alternatives()->Add(node); }
990 ZoneList<GuardedAlternative>* alternatives() { return alternatives_; }
991 DispatchTable* GetTable(bool ignore_case);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000992 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
993 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
994 int EatsAtLeastHelper(int still_to_find,
995 int recursion_depth,
996 RegExpNode* ignore_this_node);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000997 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
998 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000999 int characters_filled_in,
1000 bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001001 virtual ChoiceNode* Clone() { return new ChoiceNode(*this); }
1002
1003 bool being_calculated() { return being_calculated_; }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001004 bool not_at_start() { return not_at_start_; }
1005 void set_not_at_start() { not_at_start_ = true; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001006 void set_being_calculated(bool b) { being_calculated_ = b; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001007 virtual bool try_to_emit_quick_check_for_alternative(int i) { return true; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001008
ager@chromium.org8bb60582008-12-11 12:02:20 +00001009 protected:
ager@chromium.org5ec48922009-05-05 07:25:34 +00001010 int GreedyLoopTextLength(GuardedAlternative* alternative);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001011 ZoneList<GuardedAlternative>* alternatives_;
1012
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001013 private:
1014 friend class DispatchTableConstructor;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001015 friend class Analysis;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001016 void GenerateGuard(RegExpMacroAssembler* macro_assembler,
ager@chromium.org5ec48922009-05-05 07:25:34 +00001017 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001018 Trace* trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001019 int CalculatePreloadCharacters(RegExpCompiler* compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001020 void EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001021 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001022 GuardedAlternative alternative,
1023 AlternativeGeneration* alt_gen,
1024 int preload_characters,
1025 bool next_expects_preload);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001026 DispatchTable* table_;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001027 // If true, this node is never checked at the start of the input.
1028 // Allows a new trace to start with at_start() set to false.
1029 bool not_at_start_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001030 bool being_calculated_;
1031};
1032
1033
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001034class NegativeLookaheadChoiceNode: public ChoiceNode {
1035 public:
1036 explicit NegativeLookaheadChoiceNode(GuardedAlternative this_must_fail,
1037 GuardedAlternative then_do_this)
1038 : ChoiceNode(2) {
1039 AddAlternative(this_must_fail);
1040 AddAlternative(then_do_this);
1041 }
1042 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
1043 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1044 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001045 int characters_filled_in,
1046 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001047 // For a negative lookahead we don't emit the quick check for the
1048 // alternative that is expected to fail. This is because quick check code
1049 // starts by loading enough characters for the alternative that takes fewest
1050 // characters, but on a negative lookahead the negative branch did not take
1051 // part in that calculation (EatsAtLeast) so the assumptions don't hold.
1052 virtual bool try_to_emit_quick_check_for_alternative(int i) { return i != 0; }
1053};
1054
1055
ager@chromium.org8bb60582008-12-11 12:02:20 +00001056class LoopChoiceNode: public ChoiceNode {
1057 public:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001058 explicit LoopChoiceNode(bool body_can_be_zero_length)
1059 : ChoiceNode(2),
1060 loop_node_(NULL),
1061 continue_node_(NULL),
1062 body_can_be_zero_length_(body_can_be_zero_length) { }
1063 void AddLoopAlternative(GuardedAlternative alt);
1064 void AddContinueAlternative(GuardedAlternative alt);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001065 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
1066 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001067 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1068 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001069 int characters_filled_in,
1070 bool not_at_start);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001071 virtual LoopChoiceNode* Clone() { return new LoopChoiceNode(*this); }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001072 RegExpNode* loop_node() { return loop_node_; }
1073 RegExpNode* continue_node() { return continue_node_; }
1074 bool body_can_be_zero_length() { return body_can_be_zero_length_; }
1075 virtual void Accept(NodeVisitor* visitor);
1076
1077 private:
1078 // AddAlternative is made private for loop nodes because alternatives
1079 // should not be added freely, we need to keep track of which node
1080 // goes back to the node itself.
1081 void AddAlternative(GuardedAlternative node) {
1082 ChoiceNode::AddAlternative(node);
1083 }
1084
1085 RegExpNode* loop_node_;
1086 RegExpNode* continue_node_;
1087 bool body_can_be_zero_length_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001088};
1089
1090
1091// There are many ways to generate code for a node. This class encapsulates
1092// the current way we should be generating. In other words it encapsulates
ager@chromium.org32912102009-01-16 10:38:43 +00001093// the current state of the code generator. The effect of this is that we
1094// generate code for paths that the matcher can take through the regular
1095// expression. A given node in the regexp can be code-generated several times
1096// as it can be part of several traces. For example for the regexp:
1097// /foo(bar|ip)baz/ the code to match baz will be generated twice, once as part
1098// of the foo-bar-baz trace and once as part of the foo-ip-baz trace. The code
1099// to match foo is generated only once (the traces have a common prefix). The
1100// code to store the capture is deferred and generated (twice) after the places
1101// where baz has been matched.
1102class Trace {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001103 public:
iposva@chromium.org245aa852009-02-10 00:49:54 +00001104 // A value for a property that is either known to be true, know to be false,
1105 // or not known.
1106 enum TriBool {
1107 UNKNOWN = -1, FALSE = 0, TRUE = 1
1108 };
1109
ager@chromium.org8bb60582008-12-11 12:02:20 +00001110 class DeferredAction {
1111 public:
1112 DeferredAction(ActionNode::Type type, int reg)
1113 : type_(type), reg_(reg), next_(NULL) { }
1114 DeferredAction* next() { return next_; }
ager@chromium.org32912102009-01-16 10:38:43 +00001115 bool Mentions(int reg);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001116 int reg() { return reg_; }
1117 ActionNode::Type type() { return type_; }
1118 private:
1119 ActionNode::Type type_;
1120 int reg_;
1121 DeferredAction* next_;
ager@chromium.org32912102009-01-16 10:38:43 +00001122 friend class Trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001123 };
1124
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001125 class DeferredCapture : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001126 public:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001127 DeferredCapture(int reg, bool is_capture, Trace* trace)
ager@chromium.org8bb60582008-12-11 12:02:20 +00001128 : DeferredAction(ActionNode::STORE_POSITION, reg),
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001129 cp_offset_(trace->cp_offset()),
1130 is_capture_(is_capture) { }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001131 int cp_offset() { return cp_offset_; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001132 bool is_capture() { return is_capture_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001133 private:
1134 int cp_offset_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001135 bool is_capture_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001136 void set_cp_offset(int cp_offset) { cp_offset_ = cp_offset; }
1137 };
1138
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001139 class DeferredSetRegister : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001140 public:
1141 DeferredSetRegister(int reg, int value)
1142 : DeferredAction(ActionNode::SET_REGISTER, reg),
1143 value_(value) { }
1144 int value() { return value_; }
1145 private:
1146 int value_;
1147 };
1148
ager@chromium.org32912102009-01-16 10:38:43 +00001149 class DeferredClearCaptures : public DeferredAction {
1150 public:
1151 explicit DeferredClearCaptures(Interval range)
1152 : DeferredAction(ActionNode::CLEAR_CAPTURES, -1),
1153 range_(range) { }
1154 Interval range() { return range_; }
1155 private:
1156 Interval range_;
1157 };
1158
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001159 class DeferredIncrementRegister : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001160 public:
1161 explicit DeferredIncrementRegister(int reg)
1162 : DeferredAction(ActionNode::INCREMENT_REGISTER, reg) { }
1163 };
1164
ager@chromium.org32912102009-01-16 10:38:43 +00001165 Trace()
ager@chromium.org8bb60582008-12-11 12:02:20 +00001166 : cp_offset_(0),
1167 actions_(NULL),
1168 backtrack_(NULL),
1169 stop_node_(NULL),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001170 loop_label_(NULL),
1171 characters_preloaded_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001172 bound_checked_up_to_(0),
ager@chromium.org381abbb2009-02-25 13:23:22 +00001173 flush_budget_(100),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001174 at_start_(UNKNOWN) { }
1175
ager@chromium.org32912102009-01-16 10:38:43 +00001176 // End the trace. This involves flushing the deferred actions in the trace
1177 // and pushing a backtrack location onto the backtrack stack. Once this is
1178 // done we can start a new trace or go to one that has already been
1179 // generated.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001180 void Flush(RegExpCompiler* compiler, RegExpNode* successor);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001181 int cp_offset() { return cp_offset_; }
1182 DeferredAction* actions() { return actions_; }
ager@chromium.org32912102009-01-16 10:38:43 +00001183 // A trivial trace is one that has no deferred actions or other state that
1184 // affects the assumptions used when generating code. There is no recorded
1185 // backtrack location in a trivial trace, so with a trivial trace we will
1186 // generate code that, on a failure to match, gets the backtrack location
1187 // from the backtrack stack rather than using a direct jump instruction. We
1188 // always start code generation with a trivial trace and non-trivial traces
1189 // are created as we emit code for nodes or add to the list of deferred
1190 // actions in the trace. The location of the code generated for a node using
1191 // a trivial trace is recorded in a label in the node so that gotos can be
1192 // generated to that code.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001193 bool is_trivial() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001194 return backtrack_ == NULL &&
1195 actions_ == NULL &&
1196 cp_offset_ == 0 &&
1197 characters_preloaded_ == 0 &&
1198 bound_checked_up_to_ == 0 &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001199 quick_check_performed_.characters() == 0 &&
1200 at_start_ == UNKNOWN;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001201 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001202 TriBool at_start() { return at_start_; }
1203 void set_at_start(bool at_start) { at_start_ = at_start ? TRUE : FALSE; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001204 Label* backtrack() { return backtrack_; }
1205 Label* loop_label() { return loop_label_; }
1206 RegExpNode* stop_node() { return stop_node_; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001207 int characters_preloaded() { return characters_preloaded_; }
1208 int bound_checked_up_to() { return bound_checked_up_to_; }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001209 int flush_budget() { return flush_budget_; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001210 QuickCheckDetails* quick_check_performed() { return &quick_check_performed_; }
1211 bool mentions_reg(int reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001212 // Returns true if a deferred position store exists to the specified
1213 // register and stores the offset in the out-parameter. Otherwise
1214 // returns false.
1215 bool GetStoredPosition(int reg, int* cp_offset);
1216 // These set methods and AdvanceCurrentPositionInTrace should be used only on
1217 // new traces - the intention is that traces are immutable after creation.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001218 void add_action(DeferredAction* new_action) {
1219 ASSERT(new_action->next_ == NULL);
1220 new_action->next_ = actions_;
1221 actions_ = new_action;
1222 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001223 void set_backtrack(Label* backtrack) { backtrack_ = backtrack; }
1224 void set_stop_node(RegExpNode* node) { stop_node_ = node; }
1225 void set_loop_label(Label* label) { loop_label_ = label; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001226 void set_characters_preloaded(int cpre) { characters_preloaded_ = cpre; }
1227 void set_bound_checked_up_to(int to) { bound_checked_up_to_ = to; }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001228 void set_flush_budget(int to) { flush_budget_ = to; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001229 void set_quick_check_performed(QuickCheckDetails* d) {
1230 quick_check_performed_ = *d;
1231 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001232 void InvalidateCurrentCharacter();
1233 void AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001234 private:
1235 int FindAffectedRegisters(OutSet* affected_registers);
1236 void PerformDeferredActions(RegExpMacroAssembler* macro,
1237 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001238 OutSet& affected_registers,
1239 OutSet* registers_to_pop,
1240 OutSet* registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001241 void RestoreAffectedRegisters(RegExpMacroAssembler* macro,
1242 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001243 OutSet& registers_to_pop,
1244 OutSet& registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001245 int cp_offset_;
1246 DeferredAction* actions_;
1247 Label* backtrack_;
1248 RegExpNode* stop_node_;
1249 Label* loop_label_;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001250 int characters_preloaded_;
1251 int bound_checked_up_to_;
1252 QuickCheckDetails quick_check_performed_;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001253 int flush_budget_;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001254 TriBool at_start_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001255};
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001256
1257
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001258class NodeVisitor {
1259 public:
1260 virtual ~NodeVisitor() { }
1261#define DECLARE_VISIT(Type) \
1262 virtual void Visit##Type(Type##Node* that) = 0;
1263FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1264#undef DECLARE_VISIT
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001265 virtual void VisitLoopChoice(LoopChoiceNode* that) { VisitChoice(that); }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001266};
1267
1268
1269// Node visitor used to add the start set of the alternatives to the
1270// dispatch table of a choice node.
1271class DispatchTableConstructor: public NodeVisitor {
1272 public:
1273 DispatchTableConstructor(DispatchTable* table, bool ignore_case)
1274 : table_(table),
1275 choice_index_(-1),
1276 ignore_case_(ignore_case) { }
1277
1278 void BuildTable(ChoiceNode* node);
1279
1280 void AddRange(CharacterRange range) {
1281 table()->AddRange(range, choice_index_);
1282 }
1283
1284 void AddInverse(ZoneList<CharacterRange>* ranges);
1285
1286#define DECLARE_VISIT(Type) \
1287 virtual void Visit##Type(Type##Node* that);
1288FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1289#undef DECLARE_VISIT
1290
1291 DispatchTable* table() { return table_; }
1292 void set_choice_index(int value) { choice_index_ = value; }
1293
1294 protected:
ager@chromium.org5ec48922009-05-05 07:25:34 +00001295 DispatchTable* table_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001296 int choice_index_;
1297 bool ignore_case_;
1298};
1299
1300
ager@chromium.org8bb60582008-12-11 12:02:20 +00001301// Assertion propagation moves information about assertions such as
1302// \b to the affected nodes. For instance, in /.\b./ information must
1303// be propagated to the first '.' that whatever follows needs to know
1304// if it matched a word or a non-word, and to the second '.' that it
1305// has to check if it succeeds a word or non-word. In this case the
1306// result will be something like:
1307//
1308// +-------+ +------------+
1309// | . | | . |
1310// +-------+ ---> +------------+
1311// | word? | | check word |
1312// +-------+ +------------+
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001313class Analysis: public NodeVisitor {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001314 public:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001315 explicit Analysis(bool ignore_case)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001316 : ignore_case_(ignore_case) { }
1317 void EnsureAnalyzed(RegExpNode* node);
1318
1319#define DECLARE_VISIT(Type) \
1320 virtual void Visit##Type(Type##Node* that);
1321FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1322#undef DECLARE_VISIT
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001323 virtual void VisitLoopChoice(LoopChoiceNode* that);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001324
1325 private:
1326 bool ignore_case_;
1327
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001328 DISALLOW_IMPLICIT_CONSTRUCTORS(Analysis);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001329};
1330
1331
ager@chromium.org8bb60582008-12-11 12:02:20 +00001332struct RegExpCompileData {
1333 RegExpCompileData()
1334 : tree(NULL),
1335 node(NULL),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001336 simple(true),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001337 contains_anchor(false),
ager@chromium.org8bb60582008-12-11 12:02:20 +00001338 capture_count(0) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001339 RegExpTree* tree;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001340 RegExpNode* node;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001341 bool simple;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001342 bool contains_anchor;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001343 Handle<String> error;
1344 int capture_count;
1345};
1346
1347
1348class RegExpEngine: public AllStatic {
1349 public:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001350 struct CompilationResult {
1351 explicit CompilationResult(const char* error_message)
1352 : error_message(error_message),
1353 code(Heap::the_hole_value()),
1354 num_registers(0) {}
1355 CompilationResult(Object* code, int registers)
1356 : error_message(NULL),
1357 code(code),
1358 num_registers(registers) {}
1359 const char* error_message;
1360 Object* code;
1361 int num_registers;
1362 };
1363
1364 static CompilationResult Compile(RegExpCompileData* input,
1365 bool ignore_case,
1366 bool multiline,
1367 Handle<String> pattern,
1368 bool is_ascii);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001369
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001370 static void DotPrint(const char* label, RegExpNode* node, bool ignore_case);
1371};
1372
1373
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001374} } // namespace v8::internal
1375
1376#endif // V8_JSREGEXP_H_