blob: 18bd19b44c456ad72ce8f7c54c2a309a965eddc5 [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
kasperl@chromium.org71affb52009-05-26 05:44:31 +000031namespace v8 {
32namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000033
ager@chromium.orga74f0da2008-12-03 16:05:52 +000034
35class RegExpMacroAssembler;
36
37
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000038class RegExpImpl {
39 public:
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000040 static inline bool UseNativeRegexp() {
ager@chromium.org9085a012009-05-11 19:22:57 +000041#ifdef V8_TARGET_ARCH_IA32
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000042 return FLAG_regexp_native;
ager@chromium.org9085a012009-05-11 19:22:57 +000043#else
44 return false;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000045#endif
46 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000047 // Creates a regular expression literal in the old space.
48 // This function calls the garbage collector if necessary.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000049 static Handle<Object> CreateRegExpLiteral(Handle<JSFunction> constructor,
50 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051 Handle<String> flags,
52 bool* has_pending_exception);
53
54 // Returns a string representation of a regular expression.
55 // Implements RegExp.prototype.toString, see ECMA-262 section 15.10.6.4.
56 // This function calls the garbage collector if necessary.
57 static Handle<String> ToString(Handle<Object> value);
58
ager@chromium.org8bb60582008-12-11 12:02:20 +000059 // Parses the RegExp pattern and prepares the JSRegExp object with
60 // generic data and choice of implementation - as well as what
61 // the implementation wants to store in the data field.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000062 // Returns false if compilation fails.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000063 static Handle<Object> Compile(Handle<JSRegExp> re,
64 Handle<String> pattern,
65 Handle<String> flags);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000066
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067 // See ECMA-262 section 15.10.6.2.
68 // This function calls the garbage collector if necessary.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000069 static Handle<Object> Exec(Handle<JSRegExp> regexp,
70 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000071 int index,
72 Handle<JSArray> lastMatchInfo);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073
74 // Call RegExp.prototyp.exec(string) in a loop.
75 // Used by String.prototype.match and String.prototype.replace.
76 // This function calls the garbage collector if necessary.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000077 static Handle<Object> ExecGlobal(Handle<JSRegExp> regexp,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000078 Handle<String> subject,
79 Handle<JSArray> lastMatchInfo);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000080
ager@chromium.org8bb60582008-12-11 12:02:20 +000081 // Prepares a JSRegExp object with Irregexp-specific data.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000082 static void IrregexpPrepare(Handle<JSRegExp> re,
83 Handle<String> pattern,
84 JSRegExp::Flags flags,
85 int capture_register_count);
ager@chromium.orga74f0da2008-12-03 16:05:52 +000086
87
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000088 static void AtomCompile(Handle<JSRegExp> re,
89 Handle<String> pattern,
90 JSRegExp::Flags flags,
91 Handle<String> match_pattern);
92
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000093 static Handle<Object> AtomExec(Handle<JSRegExp> regexp,
94 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000095 int index,
96 Handle<JSArray> lastMatchInfo);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000097
ager@chromium.orga74f0da2008-12-03 16:05:52 +000098 // Execute an Irregexp bytecode pattern.
ager@chromium.org41826e72009-03-30 13:30:57 +000099 // On a successful match, the result is a JSArray containing
100 // captured positions. On a failure, the result is the null value.
101 // Returns an empty handle in case of an exception.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000102 static Handle<Object> IrregexpExec(Handle<JSRegExp> regexp,
103 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000104 int index,
105 Handle<JSArray> lastMatchInfo);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000106
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000107 // Offsets in the lastMatchInfo array.
108 static const int kLastCaptureCount = 0;
109 static const int kLastSubject = 1;
110 static const int kLastInput = 2;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000111 static const int kFirstCapture = 3;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000112 static const int kLastMatchOverhead = 3;
113
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000114 // Used to access the lastMatchInfo array.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000115 static int GetCapture(FixedArray* array, int index) {
116 return Smi::cast(array->get(index + kFirstCapture))->value();
117 }
118
119 static void SetLastCaptureCount(FixedArray* array, int to) {
120 array->set(kLastCaptureCount, Smi::FromInt(to));
121 }
122
123 static void SetLastSubject(FixedArray* array, String* to) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000124 array->set(kLastSubject, to);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000125 }
126
127 static void SetLastInput(FixedArray* array, String* to) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000128 array->set(kLastInput, to);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000129 }
130
131 static void SetCapture(FixedArray* array, int index, int to) {
132 array->set(index + kFirstCapture, Smi::FromInt(to));
133 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000134
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000135 static int GetLastCaptureCount(FixedArray* array) {
136 return Smi::cast(array->get(kLastCaptureCount))->value();
137 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000138
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000139 // For acting on the JSRegExp data FixedArray.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000140 static int IrregexpMaxRegisterCount(FixedArray* re);
141 static void SetIrregexpMaxRegisterCount(FixedArray* re, int value);
142 static int IrregexpNumberOfCaptures(FixedArray* re);
143 static int IrregexpNumberOfRegisters(FixedArray* re);
144 static ByteArray* IrregexpByteCode(FixedArray* re, bool is_ascii);
145 static Code* IrregexpNativeCode(FixedArray* re, bool is_ascii);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000146
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000147 private:
148 static String* last_ascii_string_;
149 static String* two_byte_cached_string_;
150
151 static bool EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii);
152
153
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000154 // Set the subject cache. The previous string buffer is not deleted, so the
155 // caller should ensure that it doesn't leak.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000156 static void SetSubjectCache(String* subject,
157 char* utf8_subject,
158 int uft8_length,
159 int character_position,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000160 int utf8_position);
161
162 // A one element cache of the last utf8_subject string and its length. The
163 // subject JS String object is cached in the heap. We also cache a
164 // translation between position and utf8 position.
165 static char* utf8_subject_cache_;
166 static int utf8_length_cache_;
167 static int utf8_position_;
168 static int character_position_;
169};
170
171
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000172class CharacterRange {
173 public:
174 CharacterRange() : from_(0), to_(0) { }
175 // For compatibility with the CHECK_OK macro
176 CharacterRange(void* null) { ASSERT_EQ(NULL, null); } //NOLINT
177 CharacterRange(uc16 from, uc16 to) : from_(from), to_(to) { }
178 static void AddClassEscape(uc16 type, ZoneList<CharacterRange>* ranges);
179 static Vector<const uc16> GetWordBounds();
180 static inline CharacterRange Singleton(uc16 value) {
181 return CharacterRange(value, value);
182 }
183 static inline CharacterRange Range(uc16 from, uc16 to) {
184 ASSERT(from <= to);
185 return CharacterRange(from, to);
186 }
187 static inline CharacterRange Everything() {
188 return CharacterRange(0, 0xFFFF);
189 }
190 bool Contains(uc16 i) { return from_ <= i && i <= to_; }
191 uc16 from() const { return from_; }
192 void set_from(uc16 value) { from_ = value; }
193 uc16 to() const { return to_; }
194 void set_to(uc16 value) { to_ = value; }
195 bool is_valid() { return from_ <= to_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000196 bool IsEverything(uc16 max) { return from_ == 0 && to_ >= max; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000197 bool IsSingleton() { return (from_ == to_); }
198 void AddCaseEquivalents(ZoneList<CharacterRange>* ranges);
199 static void Split(ZoneList<CharacterRange>* base,
200 Vector<const uc16> overlay,
201 ZoneList<CharacterRange>** included,
202 ZoneList<CharacterRange>** excluded);
203
204 static const int kRangeCanonicalizeMax = 0x346;
205 static const int kStartMarker = (1 << 24);
206 static const int kPayloadMask = (1 << 24) - 1;
207
208 private:
209 uc16 from_;
210 uc16 to_;
211};
212
213
214template <typename Node, class Callback>
215static void DoForEach(Node* node, Callback* callback);
216
217
218// A zone splay tree. The config type parameter encapsulates the
219// different configurations of a concrete splay tree:
220//
221// typedef Key: the key type
222// typedef Value: the value type
223// static const kNoKey: the dummy key used when no key is set
224// static const kNoValue: the dummy value used to initialize nodes
225// int (Compare)(Key& a, Key& b) -> {-1, 0, 1}: comparison function
226//
227template <typename Config>
228class ZoneSplayTree : public ZoneObject {
229 public:
230 typedef typename Config::Key Key;
231 typedef typename Config::Value Value;
232
233 class Locator;
234
235 ZoneSplayTree() : root_(NULL) { }
236
237 // Inserts the given key in this tree with the given value. Returns
238 // true if a node was inserted, otherwise false. If found the locator
239 // is enabled and provides access to the mapping for the key.
240 bool Insert(const Key& key, Locator* locator);
241
242 // Looks up the key in this tree and returns true if it was found,
243 // otherwise false. If the node is found the locator is enabled and
244 // provides access to the mapping for the key.
245 bool Find(const Key& key, Locator* locator);
246
247 // Finds the mapping with the greatest key less than or equal to the
248 // given key.
249 bool FindGreatestLessThan(const Key& key, Locator* locator);
250
251 // Find the mapping with the greatest key in this tree.
252 bool FindGreatest(Locator* locator);
253
254 // Finds the mapping with the least key greater than or equal to the
255 // given key.
256 bool FindLeastGreaterThan(const Key& key, Locator* locator);
257
258 // Find the mapping with the least key in this tree.
259 bool FindLeast(Locator* locator);
260
261 // Remove the node with the given key from the tree.
262 bool Remove(const Key& key);
263
264 bool is_empty() { return root_ == NULL; }
265
266 // Perform the splay operation for the given key. Moves the node with
267 // the given key to the top of the tree. If no node has the given
268 // key, the last node on the search path is moved to the top of the
269 // tree.
270 void Splay(const Key& key);
271
272 class Node : public ZoneObject {
273 public:
274 Node(const Key& key, const Value& value)
275 : key_(key),
276 value_(value),
277 left_(NULL),
278 right_(NULL) { }
279 Key key() { return key_; }
280 Value value() { return value_; }
281 Node* left() { return left_; }
282 Node* right() { return right_; }
283 private:
284 friend class ZoneSplayTree;
285 friend class Locator;
286 Key key_;
287 Value value_;
288 Node* left_;
289 Node* right_;
290 };
291
292 // A locator provides access to a node in the tree without actually
293 // exposing the node.
294 class Locator {
295 public:
296 explicit Locator(Node* node) : node_(node) { }
297 Locator() : node_(NULL) { }
298 const Key& key() { return node_->key_; }
299 Value& value() { return node_->value_; }
300 void set_value(const Value& value) { node_->value_ = value; }
301 inline void bind(Node* node) { node_ = node; }
302 private:
303 Node* node_;
304 };
305
306 template <class Callback>
307 void ForEach(Callback* c) {
308 DoForEach<typename ZoneSplayTree<Config>::Node, Callback>(root_, c);
309 }
310
311 private:
312 Node* root_;
313};
314
315
316// A set of unsigned integers that behaves especially well on small
317// integers (< 32). May do zone-allocation.
318class OutSet: public ZoneObject {
319 public:
320 OutSet() : first_(0), remaining_(NULL), successors_(NULL) { }
321 OutSet* Extend(unsigned value);
322 bool Get(unsigned value);
323 static const unsigned kFirstLimit = 32;
324
325 private:
326 // Destructively set a value in this set. In most cases you want
327 // to use Extend instead to ensure that only one instance exists
328 // that contains the same values.
329 void Set(unsigned value);
330
331 // The successors are a list of sets that contain the same values
332 // as this set and the one more value that is not present in this
333 // set.
334 ZoneList<OutSet*>* successors() { return successors_; }
335
336 OutSet(uint32_t first, ZoneList<unsigned>* remaining)
337 : first_(first), remaining_(remaining), successors_(NULL) { }
338 uint32_t first_;
339 ZoneList<unsigned>* remaining_;
340 ZoneList<OutSet*>* successors_;
ager@chromium.org32912102009-01-16 10:38:43 +0000341 friend class Trace;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000342};
343
344
345// A mapping from integers, specified as ranges, to a set of integers.
346// Used for mapping character ranges to choices.
347class DispatchTable : public ZoneObject {
348 public:
349 class Entry {
350 public:
351 Entry() : from_(0), to_(0), out_set_(NULL) { }
352 Entry(uc16 from, uc16 to, OutSet* out_set)
353 : from_(from), to_(to), out_set_(out_set) { }
354 uc16 from() { return from_; }
355 uc16 to() { return to_; }
356 void set_to(uc16 value) { to_ = value; }
357 void AddValue(int value) { out_set_ = out_set_->Extend(value); }
358 OutSet* out_set() { return out_set_; }
359 private:
360 uc16 from_;
361 uc16 to_;
362 OutSet* out_set_;
363 };
364
365 class Config {
366 public:
367 typedef uc16 Key;
368 typedef Entry Value;
369 static const uc16 kNoKey;
370 static const Entry kNoValue;
371 static inline int Compare(uc16 a, uc16 b) {
372 if (a == b)
373 return 0;
374 else if (a < b)
375 return -1;
376 else
377 return 1;
378 }
379 };
380
381 void AddRange(CharacterRange range, int value);
382 OutSet* Get(uc16 value);
383 void Dump();
384
385 template <typename Callback>
386 void ForEach(Callback* callback) { return tree()->ForEach(callback); }
387 private:
388 // There can't be a static empty set since it allocates its
389 // successors in a zone and caches them.
390 OutSet* empty() { return &empty_; }
391 OutSet empty_;
392 ZoneSplayTree<Config>* tree() { return &tree_; }
393 ZoneSplayTree<Config> tree_;
394};
395
396
397#define FOR_EACH_NODE_TYPE(VISIT) \
398 VISIT(End) \
399 VISIT(Action) \
400 VISIT(Choice) \
401 VISIT(BackReference) \
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000402 VISIT(Assertion) \
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000403 VISIT(Text)
404
405
406#define FOR_EACH_REG_EXP_TREE_TYPE(VISIT) \
407 VISIT(Disjunction) \
408 VISIT(Alternative) \
409 VISIT(Assertion) \
410 VISIT(CharacterClass) \
411 VISIT(Atom) \
412 VISIT(Quantifier) \
413 VISIT(Capture) \
414 VISIT(Lookahead) \
415 VISIT(BackReference) \
416 VISIT(Empty) \
417 VISIT(Text)
418
419
420#define FORWARD_DECLARE(Name) class RegExp##Name;
421FOR_EACH_REG_EXP_TREE_TYPE(FORWARD_DECLARE)
422#undef FORWARD_DECLARE
423
424
425class TextElement {
426 public:
427 enum Type {UNINITIALIZED, ATOM, CHAR_CLASS};
428 TextElement() : type(UNINITIALIZED) { }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000429 explicit TextElement(Type t) : type(t), cp_offset(-1) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000430 static TextElement Atom(RegExpAtom* atom);
431 static TextElement CharClass(RegExpCharacterClass* char_class);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000432 int length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000433 Type type;
434 union {
435 RegExpAtom* u_atom;
436 RegExpCharacterClass* u_char_class;
437 } data;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000438 int cp_offset;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000439};
440
441
ager@chromium.org32912102009-01-16 10:38:43 +0000442class Trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000443
444
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000445struct NodeInfo {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000446 NodeInfo()
447 : being_analyzed(false),
448 been_analyzed(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000449 follows_word_interest(false),
450 follows_newline_interest(false),
451 follows_start_interest(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000452 at_end(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000453 visited(false) { }
454
455 // Returns true if the interests and assumptions of this node
456 // matches the given one.
457 bool Matches(NodeInfo* that) {
458 return (at_end == that->at_end) &&
459 (follows_word_interest == that->follows_word_interest) &&
460 (follows_newline_interest == that->follows_newline_interest) &&
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000461 (follows_start_interest == that->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000462 }
463
464 // Updates the interests of this node given the interests of the
465 // node preceding it.
466 void AddFromPreceding(NodeInfo* that) {
467 at_end |= that->at_end;
468 follows_word_interest |= that->follows_word_interest;
469 follows_newline_interest |= that->follows_newline_interest;
470 follows_start_interest |= that->follows_start_interest;
471 }
472
ager@chromium.org8bb60582008-12-11 12:02:20 +0000473 bool HasLookbehind() {
474 return follows_word_interest ||
475 follows_newline_interest ||
476 follows_start_interest;
477 }
478
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000479 // Sets the interests of this node to include the interests of the
480 // following node.
481 void AddFromFollowing(NodeInfo* that) {
482 follows_word_interest |= that->follows_word_interest;
483 follows_newline_interest |= that->follows_newline_interest;
484 follows_start_interest |= that->follows_start_interest;
485 }
486
487 void ResetCompilationState() {
488 being_analyzed = false;
489 been_analyzed = false;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000490 }
491
492 bool being_analyzed: 1;
493 bool been_analyzed: 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000494
495 // These bits are set of this node has to know what the preceding
496 // character was.
497 bool follows_word_interest: 1;
498 bool follows_newline_interest: 1;
499 bool follows_start_interest: 1;
500
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000501 bool at_end: 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000502 bool visited: 1;
503};
504
505
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000506class SiblingList {
507 public:
508 SiblingList() : list_(NULL) { }
509 int length() {
510 return list_ == NULL ? 0 : list_->length();
511 }
512 void Ensure(RegExpNode* parent) {
513 if (list_ == NULL) {
514 list_ = new ZoneList<RegExpNode*>(2);
515 list_->Add(parent);
516 }
517 }
518 void Add(RegExpNode* node) { list_->Add(node); }
519 RegExpNode* Get(int index) { return list_->at(index); }
520 private:
521 ZoneList<RegExpNode*>* list_;
522};
523
524
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000525// Details of a quick mask-compare check that can look ahead in the
526// input stream.
527class QuickCheckDetails {
528 public:
529 QuickCheckDetails()
530 : characters_(0),
531 mask_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000532 value_(0),
533 cannot_match_(false) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000534 explicit QuickCheckDetails(int characters)
535 : characters_(characters),
536 mask_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000537 value_(0),
538 cannot_match_(false) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000539 bool Rationalize(bool ascii);
540 // Merge in the information from another branch of an alternation.
541 void Merge(QuickCheckDetails* other, int from_index);
542 // Advance the current position by some amount.
543 void Advance(int by, bool ascii);
544 void Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000545 bool cannot_match() { return cannot_match_; }
546 void set_cannot_match() { cannot_match_ = true; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000547 struct Position {
548 Position() : mask(0), value(0), determines_perfectly(false) { }
549 uc16 mask;
550 uc16 value;
551 bool determines_perfectly;
552 };
553 int characters() { return characters_; }
554 void set_characters(int characters) { characters_ = characters; }
555 Position* positions(int index) {
556 ASSERT(index >= 0);
557 ASSERT(index < characters_);
558 return positions_ + index;
559 }
560 uint32_t mask() { return mask_; }
561 uint32_t value() { return value_; }
562
563 private:
564 // How many characters do we have quick check information from. This is
565 // the same for all branches of a choice node.
566 int characters_;
567 Position positions_[4];
568 // These values are the condensate of the above array after Rationalize().
569 uint32_t mask_;
570 uint32_t value_;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000571 // If set to true, there is no way this quick check can match at all.
572 // E.g., if it requires to be at the start of the input, and isn't.
573 bool cannot_match_;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000574};
575
576
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000577class RegExpNode: public ZoneObject {
578 public:
ager@chromium.org32912102009-01-16 10:38:43 +0000579 RegExpNode() : trace_count_(0) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000580 virtual ~RegExpNode();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000581 virtual void Accept(NodeVisitor* visitor) = 0;
582 // Generates a goto to this node or actually generates the code at this point.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000583 virtual void Emit(RegExpCompiler* compiler, Trace* trace) = 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000584 // How many characters must this node consume at a minimum in order to
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000585 // succeed. If we have found at least 'still_to_find' characters that
586 // must be consumed there is no need to ask any following nodes whether
587 // they are sure to eat any more characters.
588 virtual int EatsAtLeast(int still_to_find, int recursion_depth) = 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000589 // Emits some quick code that checks whether the preloaded characters match.
590 // Falls through on certain failure, jumps to the label on possible success.
591 // If the node cannot make a quick check it does nothing and returns false.
592 bool EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +0000593 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000594 bool preload_has_checked_bounds,
595 Label* on_possible_success,
596 QuickCheckDetails* details_return,
597 bool fall_through_on_failure);
598 // For a given number of characters this returns a mask and a value. The
599 // next n characters are anded with the mask and compared with the value.
600 // A comparison failure indicates the node cannot match the next n characters.
601 // A comparison success indicates the node may match.
602 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
603 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000604 int characters_filled_in,
605 bool not_at_start) = 0;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000606 static const int kNodeIsTooComplexForGreedyLoops = -1;
607 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
608 Label* label() { return &label_; }
ager@chromium.org32912102009-01-16 10:38:43 +0000609 // If non-generic code is generated for a node (ie the node is not at the
610 // start of the trace) then it cannot be reused. This variable sets a limit
611 // on how often we allow that to happen before we insist on starting a new
612 // trace and generating generic code for a node that can be reused by flushing
613 // the deferred actions in the current trace and generating a goto.
614 static const int kMaxCopiesCodeGenerated = 10;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000615
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000616 NodeInfo* info() { return &info_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000617
618 void AddSibling(RegExpNode* node) { siblings_.Add(node); }
619
620 // Static version of EnsureSibling that expresses the fact that the
621 // result has the same type as the input.
622 template <class C>
623 static C* EnsureSibling(C* node, NodeInfo* info, bool* cloned) {
624 return static_cast<C*>(node->EnsureSibling(info, cloned));
625 }
626
627 SiblingList* siblings() { return &siblings_; }
628 void set_siblings(SiblingList* other) { siblings_ = *other; }
629
630 protected:
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000631 enum LimitResult { DONE, CONTINUE };
ager@chromium.org32912102009-01-16 10:38:43 +0000632 LimitResult LimitVersions(RegExpCompiler* compiler, Trace* trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000633
634 // Returns a sibling of this node whose interests and assumptions
635 // match the ones in the given node info. If no sibling exists NULL
636 // is returned.
637 RegExpNode* TryGetSibling(NodeInfo* info);
638
639 // Returns a sibling of this node whose interests match the ones in
640 // the given node info. The info must not contain any assertions.
641 // If no node exists a new one will be created by cloning the current
642 // node. The result will always be an instance of the same concrete
643 // class as this node.
644 RegExpNode* EnsureSibling(NodeInfo* info, bool* cloned);
645
646 // Returns a clone of this node initialized using the copy constructor
647 // of its concrete class. Note that the node may have to be pre-
ager@chromium.org32912102009-01-16 10:38:43 +0000648 // processed before it is on a usable state.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000649 virtual RegExpNode* Clone() = 0;
650
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000651 private:
652 Label label_;
653 NodeInfo info_;
654 SiblingList siblings_;
ager@chromium.org32912102009-01-16 10:38:43 +0000655 // This variable keeps track of how many times code has been generated for
656 // this node (in different traces). We don't keep track of where the
657 // generated code is located unless the code is generated at the start of
658 // a trace, in which case it is generic and can be reused by flushing the
659 // deferred operations in the current trace and generating a goto.
660 int trace_count_;
661};
662
663
664// A simple closed interval.
665class Interval {
666 public:
667 Interval() : from_(kNone), to_(kNone) { }
668 Interval(int from, int to) : from_(from), to_(to) { }
669 Interval Union(Interval that) {
670 if (that.from_ == kNone)
671 return *this;
672 else if (from_ == kNone)
673 return that;
674 else
675 return Interval(Min(from_, that.from_), Max(to_, that.to_));
676 }
677 bool Contains(int value) {
678 return (from_ <= value) && (value <= to_);
679 }
680 bool is_empty() { return from_ == kNone; }
681 int from() { return from_; }
682 int to() { return to_; }
683 static Interval Empty() { return Interval(); }
684 static const int kNone = -1;
685 private:
686 int from_;
687 int to_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000688};
689
690
691class SeqRegExpNode: public RegExpNode {
692 public:
693 explicit SeqRegExpNode(RegExpNode* on_success)
694 : on_success_(on_success) { }
695 RegExpNode* on_success() { return on_success_; }
696 void set_on_success(RegExpNode* node) { on_success_ = node; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000697 private:
698 RegExpNode* on_success_;
699};
700
701
702class ActionNode: public SeqRegExpNode {
703 public:
704 enum Type {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000705 SET_REGISTER,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000706 INCREMENT_REGISTER,
707 STORE_POSITION,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000708 BEGIN_SUBMATCH,
ager@chromium.org32912102009-01-16 10:38:43 +0000709 POSITIVE_SUBMATCH_SUCCESS,
710 EMPTY_MATCH_CHECK,
711 CLEAR_CAPTURES
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000712 };
ager@chromium.org8bb60582008-12-11 12:02:20 +0000713 static ActionNode* SetRegister(int reg, int val, RegExpNode* on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000714 static ActionNode* IncrementRegister(int reg, RegExpNode* on_success);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000715 static ActionNode* StorePosition(int reg,
716 bool is_capture,
717 RegExpNode* on_success);
ager@chromium.org32912102009-01-16 10:38:43 +0000718 static ActionNode* ClearCaptures(Interval range, RegExpNode* on_success);
719 static ActionNode* BeginSubmatch(int stack_pointer_reg,
720 int position_reg,
721 RegExpNode* on_success);
722 static ActionNode* PositiveSubmatchSuccess(int stack_pointer_reg,
723 int restore_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000724 int clear_capture_count,
725 int clear_capture_from,
ager@chromium.org32912102009-01-16 10:38:43 +0000726 RegExpNode* on_success);
727 static ActionNode* EmptyMatchCheck(int start_register,
728 int repetition_register,
729 int repetition_limit,
730 RegExpNode* on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000731 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000732 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
733 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000734 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
735 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000736 int filled_in,
737 bool not_at_start) {
738 return on_success()->GetQuickCheckDetails(
739 details, compiler, filled_in, not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000740 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000741 Type type() { return type_; }
742 // TODO(erikcorry): We should allow some action nodes in greedy loops.
743 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000744 virtual ActionNode* Clone() { return new ActionNode(*this); }
745
746 private:
747 union {
748 struct {
749 int reg;
750 int value;
751 } u_store_register;
752 struct {
753 int reg;
754 } u_increment_register;
755 struct {
756 int reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000757 bool is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000758 } u_position_register;
759 struct {
760 int stack_pointer_register;
761 int current_position_register;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000762 int clear_register_count;
763 int clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000764 } u_submatch;
ager@chromium.org32912102009-01-16 10:38:43 +0000765 struct {
766 int start_register;
767 int repetition_register;
768 int repetition_limit;
769 } u_empty_match_check;
770 struct {
771 int range_from;
772 int range_to;
773 } u_clear_captures;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000774 } data_;
775 ActionNode(Type type, RegExpNode* on_success)
776 : SeqRegExpNode(on_success),
777 type_(type) { }
778 Type type_;
779 friend class DotPrinter;
780};
781
782
783class TextNode: public SeqRegExpNode {
784 public:
785 TextNode(ZoneList<TextElement>* elms,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000786 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000787 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000788 elms_(elms) { }
789 TextNode(RegExpCharacterClass* that,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000790 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000791 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000792 elms_(new ZoneList<TextElement>(1)) {
793 elms_->Add(TextElement::CharClass(that));
794 }
795 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000796 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
797 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000798 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
799 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000800 int characters_filled_in,
801 bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000802 ZoneList<TextElement>* elements() { return elms_; }
803 void MakeCaseIndependent();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000804 virtual int GreedyLoopTextLength();
805 virtual TextNode* Clone() {
806 TextNode* result = new TextNode(*this);
807 result->CalculateOffsets();
808 return result;
809 }
810 void CalculateOffsets();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000811
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000812 private:
813 enum TextEmitPassType {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000814 NON_ASCII_MATCH, // Check for characters that can't match.
815 SIMPLE_CHARACTER_MATCH, // Case-dependent single character check.
816 NON_LETTER_CHARACTER_MATCH, // Check characters that have no case equivs.
817 CASE_CHARACTER_MATCH, // Case-independent single character check.
818 CHARACTER_CLASS_MATCH // Character class.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000819 };
ager@chromium.org381abbb2009-02-25 13:23:22 +0000820 static bool SkipPass(int pass, bool ignore_case);
821 static const int kFirstRealPass = SIMPLE_CHARACTER_MATCH;
822 static const int kLastPass = CHARACTER_CLASS_MATCH;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000823 void TextEmitPass(RegExpCompiler* compiler,
824 TextEmitPassType pass,
825 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +0000826 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000827 bool first_element_checked,
828 int* checked_up_to);
829 int Length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000830 ZoneList<TextElement>* elms_;
831};
832
833
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000834class AssertionNode: public SeqRegExpNode {
835 public:
836 enum AssertionNodeType {
837 AT_END,
838 AT_START,
839 AT_BOUNDARY,
840 AT_NON_BOUNDARY,
841 AFTER_NEWLINE
842 };
843 static AssertionNode* AtEnd(RegExpNode* on_success) {
844 return new AssertionNode(AT_END, on_success);
845 }
846 static AssertionNode* AtStart(RegExpNode* on_success) {
847 return new AssertionNode(AT_START, on_success);
848 }
849 static AssertionNode* AtBoundary(RegExpNode* on_success) {
850 return new AssertionNode(AT_BOUNDARY, on_success);
851 }
852 static AssertionNode* AtNonBoundary(RegExpNode* on_success) {
853 return new AssertionNode(AT_NON_BOUNDARY, on_success);
854 }
855 static AssertionNode* AfterNewline(RegExpNode* on_success) {
856 return new AssertionNode(AFTER_NEWLINE, on_success);
857 }
858 virtual void Accept(NodeVisitor* visitor);
859 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
860 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
861 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
862 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000863 int filled_in,
864 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000865 virtual AssertionNode* Clone() { return new AssertionNode(*this); }
866 AssertionNodeType type() { return type_; }
867 private:
868 AssertionNode(AssertionNodeType t, RegExpNode* on_success)
869 : SeqRegExpNode(on_success), type_(t) { }
870 AssertionNodeType type_;
871};
872
873
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000874class BackReferenceNode: public SeqRegExpNode {
875 public:
876 BackReferenceNode(int start_reg,
877 int end_reg,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000878 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000879 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000880 start_reg_(start_reg),
881 end_reg_(end_reg) { }
882 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000883 int start_register() { return start_reg_; }
884 int end_register() { return end_reg_; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000885 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
886 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000887 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
888 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000889 int characters_filled_in,
890 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000891 return;
892 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000893 virtual BackReferenceNode* Clone() { return new BackReferenceNode(*this); }
894
895 private:
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000896 int start_reg_;
897 int end_reg_;
898};
899
900
901class EndNode: public RegExpNode {
902 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000903 enum Action { ACCEPT, BACKTRACK, NEGATIVE_SUBMATCH_SUCCESS };
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000904 explicit EndNode(Action action) : action_(action) { }
905 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000906 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
907 virtual int EatsAtLeast(int still_to_find, int recursion_depth) { return 0; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000908 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
909 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000910 int characters_filled_in,
911 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000912 // Returning 0 from EatsAtLeast should ensure we never get here.
913 UNREACHABLE();
914 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000915 virtual EndNode* Clone() { return new EndNode(*this); }
916
917 private:
918 Action action_;
919};
920
921
ager@chromium.org8bb60582008-12-11 12:02:20 +0000922class NegativeSubmatchSuccess: public EndNode {
923 public:
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000924 NegativeSubmatchSuccess(int stack_pointer_reg,
925 int position_reg,
926 int clear_capture_count,
927 int clear_capture_start)
ager@chromium.org8bb60582008-12-11 12:02:20 +0000928 : EndNode(NEGATIVE_SUBMATCH_SUCCESS),
929 stack_pointer_register_(stack_pointer_reg),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000930 current_position_register_(position_reg),
931 clear_capture_count_(clear_capture_count),
932 clear_capture_start_(clear_capture_start) { }
933 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000934
935 private:
936 int stack_pointer_register_;
937 int current_position_register_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000938 int clear_capture_count_;
939 int clear_capture_start_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000940};
941
942
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000943class Guard: public ZoneObject {
944 public:
945 enum Relation { LT, GEQ };
946 Guard(int reg, Relation op, int value)
947 : reg_(reg),
948 op_(op),
949 value_(value) { }
950 int reg() { return reg_; }
951 Relation op() { return op_; }
952 int value() { return value_; }
953
954 private:
955 int reg_;
956 Relation op_;
957 int value_;
958};
959
960
961class GuardedAlternative {
962 public:
963 explicit GuardedAlternative(RegExpNode* node) : node_(node), guards_(NULL) { }
964 void AddGuard(Guard* guard);
965 RegExpNode* node() { return node_; }
966 void set_node(RegExpNode* node) { node_ = node; }
967 ZoneList<Guard*>* guards() { return guards_; }
968
969 private:
970 RegExpNode* node_;
971 ZoneList<Guard*>* guards_;
972};
973
974
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000975class AlternativeGeneration;
976
977
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000978class ChoiceNode: public RegExpNode {
979 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000980 explicit ChoiceNode(int expected_size)
981 : alternatives_(new ZoneList<GuardedAlternative>(expected_size)),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000982 table_(NULL),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000983 not_at_start_(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000984 being_calculated_(false) { }
985 virtual void Accept(NodeVisitor* visitor);
986 void AddAlternative(GuardedAlternative node) { alternatives()->Add(node); }
987 ZoneList<GuardedAlternative>* alternatives() { return alternatives_; }
988 DispatchTable* GetTable(bool ignore_case);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000989 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
990 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
991 int EatsAtLeastHelper(int still_to_find,
992 int recursion_depth,
993 RegExpNode* ignore_this_node);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000994 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
995 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000996 int characters_filled_in,
997 bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000998 virtual ChoiceNode* Clone() { return new ChoiceNode(*this); }
999
1000 bool being_calculated() { return being_calculated_; }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001001 bool not_at_start() { return not_at_start_; }
1002 void set_not_at_start() { not_at_start_ = true; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001003 void set_being_calculated(bool b) { being_calculated_ = b; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001004 virtual bool try_to_emit_quick_check_for_alternative(int i) { return true; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001005
ager@chromium.org8bb60582008-12-11 12:02:20 +00001006 protected:
ager@chromium.org5ec48922009-05-05 07:25:34 +00001007 int GreedyLoopTextLength(GuardedAlternative* alternative);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001008 ZoneList<GuardedAlternative>* alternatives_;
1009
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001010 private:
1011 friend class DispatchTableConstructor;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001012 friend class Analysis;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001013 void GenerateGuard(RegExpMacroAssembler* macro_assembler,
ager@chromium.org5ec48922009-05-05 07:25:34 +00001014 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001015 Trace* trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001016 int CalculatePreloadCharacters(RegExpCompiler* compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001017 void EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001018 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001019 GuardedAlternative alternative,
1020 AlternativeGeneration* alt_gen,
1021 int preload_characters,
1022 bool next_expects_preload);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001023 DispatchTable* table_;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001024 // If true, this node is never checked at the start of the input.
1025 // Allows a new trace to start with at_start() set to false.
1026 bool not_at_start_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001027 bool being_calculated_;
1028};
1029
1030
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001031class NegativeLookaheadChoiceNode: public ChoiceNode {
1032 public:
1033 explicit NegativeLookaheadChoiceNode(GuardedAlternative this_must_fail,
1034 GuardedAlternative then_do_this)
1035 : ChoiceNode(2) {
1036 AddAlternative(this_must_fail);
1037 AddAlternative(then_do_this);
1038 }
1039 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
1040 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1041 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001042 int characters_filled_in,
1043 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001044 // For a negative lookahead we don't emit the quick check for the
1045 // alternative that is expected to fail. This is because quick check code
1046 // starts by loading enough characters for the alternative that takes fewest
1047 // characters, but on a negative lookahead the negative branch did not take
1048 // part in that calculation (EatsAtLeast) so the assumptions don't hold.
1049 virtual bool try_to_emit_quick_check_for_alternative(int i) { return i != 0; }
1050};
1051
1052
ager@chromium.org8bb60582008-12-11 12:02:20 +00001053class LoopChoiceNode: public ChoiceNode {
1054 public:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001055 explicit LoopChoiceNode(bool body_can_be_zero_length)
1056 : ChoiceNode(2),
1057 loop_node_(NULL),
1058 continue_node_(NULL),
1059 body_can_be_zero_length_(body_can_be_zero_length) { }
1060 void AddLoopAlternative(GuardedAlternative alt);
1061 void AddContinueAlternative(GuardedAlternative alt);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001062 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
1063 virtual int EatsAtLeast(int still_to_find, int recursion_depth);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001064 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1065 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001066 int characters_filled_in,
1067 bool not_at_start);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001068 virtual LoopChoiceNode* Clone() { return new LoopChoiceNode(*this); }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001069 RegExpNode* loop_node() { return loop_node_; }
1070 RegExpNode* continue_node() { return continue_node_; }
1071 bool body_can_be_zero_length() { return body_can_be_zero_length_; }
1072 virtual void Accept(NodeVisitor* visitor);
1073
1074 private:
1075 // AddAlternative is made private for loop nodes because alternatives
1076 // should not be added freely, we need to keep track of which node
1077 // goes back to the node itself.
1078 void AddAlternative(GuardedAlternative node) {
1079 ChoiceNode::AddAlternative(node);
1080 }
1081
1082 RegExpNode* loop_node_;
1083 RegExpNode* continue_node_;
1084 bool body_can_be_zero_length_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001085};
1086
1087
1088// There are many ways to generate code for a node. This class encapsulates
1089// the current way we should be generating. In other words it encapsulates
ager@chromium.org32912102009-01-16 10:38:43 +00001090// the current state of the code generator. The effect of this is that we
1091// generate code for paths that the matcher can take through the regular
1092// expression. A given node in the regexp can be code-generated several times
1093// as it can be part of several traces. For example for the regexp:
1094// /foo(bar|ip)baz/ the code to match baz will be generated twice, once as part
1095// of the foo-bar-baz trace and once as part of the foo-ip-baz trace. The code
1096// to match foo is generated only once (the traces have a common prefix). The
1097// code to store the capture is deferred and generated (twice) after the places
1098// where baz has been matched.
1099class Trace {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001100 public:
iposva@chromium.org245aa852009-02-10 00:49:54 +00001101 // A value for a property that is either known to be true, know to be false,
1102 // or not known.
1103 enum TriBool {
1104 UNKNOWN = -1, FALSE = 0, TRUE = 1
1105 };
1106
ager@chromium.org8bb60582008-12-11 12:02:20 +00001107 class DeferredAction {
1108 public:
1109 DeferredAction(ActionNode::Type type, int reg)
1110 : type_(type), reg_(reg), next_(NULL) { }
1111 DeferredAction* next() { return next_; }
ager@chromium.org32912102009-01-16 10:38:43 +00001112 bool Mentions(int reg);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001113 int reg() { return reg_; }
1114 ActionNode::Type type() { return type_; }
1115 private:
1116 ActionNode::Type type_;
1117 int reg_;
1118 DeferredAction* next_;
ager@chromium.org32912102009-01-16 10:38:43 +00001119 friend class Trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001120 };
1121
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001122 class DeferredCapture : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001123 public:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001124 DeferredCapture(int reg, bool is_capture, Trace* trace)
ager@chromium.org8bb60582008-12-11 12:02:20 +00001125 : DeferredAction(ActionNode::STORE_POSITION, reg),
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001126 cp_offset_(trace->cp_offset()),
1127 is_capture_(is_capture) { }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001128 int cp_offset() { return cp_offset_; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001129 bool is_capture() { return is_capture_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001130 private:
1131 int cp_offset_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001132 bool is_capture_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001133 void set_cp_offset(int cp_offset) { cp_offset_ = cp_offset; }
1134 };
1135
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001136 class DeferredSetRegister : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001137 public:
1138 DeferredSetRegister(int reg, int value)
1139 : DeferredAction(ActionNode::SET_REGISTER, reg),
1140 value_(value) { }
1141 int value() { return value_; }
1142 private:
1143 int value_;
1144 };
1145
ager@chromium.org32912102009-01-16 10:38:43 +00001146 class DeferredClearCaptures : public DeferredAction {
1147 public:
1148 explicit DeferredClearCaptures(Interval range)
1149 : DeferredAction(ActionNode::CLEAR_CAPTURES, -1),
1150 range_(range) { }
1151 Interval range() { return range_; }
1152 private:
1153 Interval range_;
1154 };
1155
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001156 class DeferredIncrementRegister : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001157 public:
1158 explicit DeferredIncrementRegister(int reg)
1159 : DeferredAction(ActionNode::INCREMENT_REGISTER, reg) { }
1160 };
1161
ager@chromium.org32912102009-01-16 10:38:43 +00001162 Trace()
ager@chromium.org8bb60582008-12-11 12:02:20 +00001163 : cp_offset_(0),
1164 actions_(NULL),
1165 backtrack_(NULL),
1166 stop_node_(NULL),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001167 loop_label_(NULL),
1168 characters_preloaded_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001169 bound_checked_up_to_(0),
ager@chromium.org381abbb2009-02-25 13:23:22 +00001170 flush_budget_(100),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001171 at_start_(UNKNOWN) { }
1172
ager@chromium.org32912102009-01-16 10:38:43 +00001173 // End the trace. This involves flushing the deferred actions in the trace
1174 // and pushing a backtrack location onto the backtrack stack. Once this is
1175 // done we can start a new trace or go to one that has already been
1176 // generated.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001177 void Flush(RegExpCompiler* compiler, RegExpNode* successor);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001178 int cp_offset() { return cp_offset_; }
1179 DeferredAction* actions() { return actions_; }
ager@chromium.org32912102009-01-16 10:38:43 +00001180 // A trivial trace is one that has no deferred actions or other state that
1181 // affects the assumptions used when generating code. There is no recorded
1182 // backtrack location in a trivial trace, so with a trivial trace we will
1183 // generate code that, on a failure to match, gets the backtrack location
1184 // from the backtrack stack rather than using a direct jump instruction. We
1185 // always start code generation with a trivial trace and non-trivial traces
1186 // are created as we emit code for nodes or add to the list of deferred
1187 // actions in the trace. The location of the code generated for a node using
1188 // a trivial trace is recorded in a label in the node so that gotos can be
1189 // generated to that code.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001190 bool is_trivial() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001191 return backtrack_ == NULL &&
1192 actions_ == NULL &&
1193 cp_offset_ == 0 &&
1194 characters_preloaded_ == 0 &&
1195 bound_checked_up_to_ == 0 &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001196 quick_check_performed_.characters() == 0 &&
1197 at_start_ == UNKNOWN;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001198 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001199 TriBool at_start() { return at_start_; }
1200 void set_at_start(bool at_start) { at_start_ = at_start ? TRUE : FALSE; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001201 Label* backtrack() { return backtrack_; }
1202 Label* loop_label() { return loop_label_; }
1203 RegExpNode* stop_node() { return stop_node_; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001204 int characters_preloaded() { return characters_preloaded_; }
1205 int bound_checked_up_to() { return bound_checked_up_to_; }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001206 int flush_budget() { return flush_budget_; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001207 QuickCheckDetails* quick_check_performed() { return &quick_check_performed_; }
1208 bool mentions_reg(int reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001209 // Returns true if a deferred position store exists to the specified
1210 // register and stores the offset in the out-parameter. Otherwise
1211 // returns false.
1212 bool GetStoredPosition(int reg, int* cp_offset);
1213 // These set methods and AdvanceCurrentPositionInTrace should be used only on
1214 // new traces - the intention is that traces are immutable after creation.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001215 void add_action(DeferredAction* new_action) {
1216 ASSERT(new_action->next_ == NULL);
1217 new_action->next_ = actions_;
1218 actions_ = new_action;
1219 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001220 void set_backtrack(Label* backtrack) { backtrack_ = backtrack; }
1221 void set_stop_node(RegExpNode* node) { stop_node_ = node; }
1222 void set_loop_label(Label* label) { loop_label_ = label; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001223 void set_characters_preloaded(int cpre) { characters_preloaded_ = cpre; }
1224 void set_bound_checked_up_to(int to) { bound_checked_up_to_ = to; }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001225 void set_flush_budget(int to) { flush_budget_ = to; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001226 void set_quick_check_performed(QuickCheckDetails* d) {
1227 quick_check_performed_ = *d;
1228 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001229 void InvalidateCurrentCharacter();
1230 void AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001231 private:
1232 int FindAffectedRegisters(OutSet* affected_registers);
1233 void PerformDeferredActions(RegExpMacroAssembler* macro,
1234 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001235 OutSet& affected_registers,
1236 OutSet* registers_to_pop,
1237 OutSet* registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001238 void RestoreAffectedRegisters(RegExpMacroAssembler* macro,
1239 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001240 OutSet& registers_to_pop,
1241 OutSet& registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001242 int cp_offset_;
1243 DeferredAction* actions_;
1244 Label* backtrack_;
1245 RegExpNode* stop_node_;
1246 Label* loop_label_;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001247 int characters_preloaded_;
1248 int bound_checked_up_to_;
1249 QuickCheckDetails quick_check_performed_;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001250 int flush_budget_;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001251 TriBool at_start_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001252};
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001253
1254
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001255class NodeVisitor {
1256 public:
1257 virtual ~NodeVisitor() { }
1258#define DECLARE_VISIT(Type) \
1259 virtual void Visit##Type(Type##Node* that) = 0;
1260FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1261#undef DECLARE_VISIT
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001262 virtual void VisitLoopChoice(LoopChoiceNode* that) { VisitChoice(that); }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001263};
1264
1265
1266// Node visitor used to add the start set of the alternatives to the
1267// dispatch table of a choice node.
1268class DispatchTableConstructor: public NodeVisitor {
1269 public:
1270 DispatchTableConstructor(DispatchTable* table, bool ignore_case)
1271 : table_(table),
1272 choice_index_(-1),
1273 ignore_case_(ignore_case) { }
1274
1275 void BuildTable(ChoiceNode* node);
1276
1277 void AddRange(CharacterRange range) {
1278 table()->AddRange(range, choice_index_);
1279 }
1280
1281 void AddInverse(ZoneList<CharacterRange>* ranges);
1282
1283#define DECLARE_VISIT(Type) \
1284 virtual void Visit##Type(Type##Node* that);
1285FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1286#undef DECLARE_VISIT
1287
1288 DispatchTable* table() { return table_; }
1289 void set_choice_index(int value) { choice_index_ = value; }
1290
1291 protected:
ager@chromium.org5ec48922009-05-05 07:25:34 +00001292 DispatchTable* table_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001293 int choice_index_;
1294 bool ignore_case_;
1295};
1296
1297
ager@chromium.org8bb60582008-12-11 12:02:20 +00001298// Assertion propagation moves information about assertions such as
1299// \b to the affected nodes. For instance, in /.\b./ information must
1300// be propagated to the first '.' that whatever follows needs to know
1301// if it matched a word or a non-word, and to the second '.' that it
1302// has to check if it succeeds a word or non-word. In this case the
1303// result will be something like:
1304//
1305// +-------+ +------------+
1306// | . | | . |
1307// +-------+ ---> +------------+
1308// | word? | | check word |
1309// +-------+ +------------+
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001310class Analysis: public NodeVisitor {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001311 public:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001312 explicit Analysis(bool ignore_case)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001313 : ignore_case_(ignore_case) { }
1314 void EnsureAnalyzed(RegExpNode* node);
1315
1316#define DECLARE_VISIT(Type) \
1317 virtual void Visit##Type(Type##Node* that);
1318FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1319#undef DECLARE_VISIT
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001320 virtual void VisitLoopChoice(LoopChoiceNode* that);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001321
1322 private:
1323 bool ignore_case_;
1324
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001325 DISALLOW_IMPLICIT_CONSTRUCTORS(Analysis);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001326};
1327
1328
ager@chromium.org8bb60582008-12-11 12:02:20 +00001329struct RegExpCompileData {
1330 RegExpCompileData()
1331 : tree(NULL),
1332 node(NULL),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001333 simple(true),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001334 contains_anchor(false),
ager@chromium.org8bb60582008-12-11 12:02:20 +00001335 capture_count(0) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001336 RegExpTree* tree;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001337 RegExpNode* node;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001338 bool simple;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001339 bool contains_anchor;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001340 Handle<String> error;
1341 int capture_count;
1342};
1343
1344
1345class RegExpEngine: public AllStatic {
1346 public:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001347 struct CompilationResult {
1348 explicit CompilationResult(const char* error_message)
1349 : error_message(error_message),
1350 code(Heap::the_hole_value()),
1351 num_registers(0) {}
1352 CompilationResult(Object* code, int registers)
1353 : error_message(NULL),
1354 code(code),
1355 num_registers(registers) {}
1356 const char* error_message;
1357 Object* code;
1358 int num_registers;
1359 };
1360
1361 static CompilationResult Compile(RegExpCompileData* input,
1362 bool ignore_case,
1363 bool multiline,
1364 Handle<String> pattern,
1365 bool is_ascii);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001366
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001367 static void DotPrint(const char* label, RegExpNode* node, bool ignore_case);
1368};
1369
1370
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001371} } // namespace v8::internal
1372
1373#endif // V8_JSREGEXP_H_