blob: 4847739316dfa316c560d5896a226c2ab59fbf3a [file] [log] [blame]
yangguo@chromium.org659ceec2012-01-26 07:37:54 +00001// Copyright 2012 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
lrn@chromium.org1c092762011-05-09 09:42:16 +000031#include "allocation.h"
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +000032#include "assembler.h"
ager@chromium.orgce5e87b2010-03-10 10:24:18 +000033#include "zone-inl.h"
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +000034
kasperl@chromium.org71affb52009-05-26 05:44:31 +000035namespace v8 {
36namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037
yangguo@chromium.org659ceec2012-01-26 07:37:54 +000038class NodeVisitor;
39class RegExpCompiler;
ager@chromium.orga74f0da2008-12-03 16:05:52 +000040class RegExpMacroAssembler;
yangguo@chromium.org659ceec2012-01-26 07:37:54 +000041class RegExpNode;
42class RegExpTree;
erik.corry@gmail.comed49e962012-04-17 11:57:53 +000043class BoyerMooreLookahead;
ager@chromium.orga74f0da2008-12-03 16:05:52 +000044
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045class RegExpImpl {
46 public:
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000047 // Whether V8 is compiled with native regexp support or not.
48 static bool UsesNativeRegExp() {
ricow@chromium.orgc9c80822010-04-21 08:22:37 +000049#ifdef V8_INTERPRETED_REGEXP
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000050 return false;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +000051#else
52 return true;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000053#endif
54 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000055
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000056 // Creates a regular expression literal in the old space.
57 // This function calls the garbage collector if necessary.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000058 static Handle<Object> CreateRegExpLiteral(Handle<JSFunction> constructor,
59 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000060 Handle<String> flags,
61 bool* has_pending_exception);
62
63 // Returns a string representation of a regular expression.
64 // Implements RegExp.prototype.toString, see ECMA-262 section 15.10.6.4.
65 // This function calls the garbage collector if necessary.
66 static Handle<String> ToString(Handle<Object> value);
67
ager@chromium.org8bb60582008-12-11 12:02:20 +000068 // Parses the RegExp pattern and prepares the JSRegExp object with
69 // generic data and choice of implementation - as well as what
70 // the implementation wants to store in the data field.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000071 // Returns false if compilation fails.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000072 static Handle<Object> Compile(Handle<JSRegExp> re,
73 Handle<String> pattern,
74 Handle<String> flags);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000075
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000076 // See ECMA-262 section 15.10.6.2.
77 // This function calls the garbage collector if necessary.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000078 static Handle<Object> Exec(Handle<JSRegExp> regexp,
79 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000080 int index,
81 Handle<JSArray> lastMatchInfo);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000082
ager@chromium.org8bb60582008-12-11 12:02:20 +000083 // Prepares a JSRegExp object with Irregexp-specific data.
whesse@chromium.orgcec079d2010-03-22 14:44:04 +000084 static void IrregexpInitialize(Handle<JSRegExp> re,
85 Handle<String> pattern,
86 JSRegExp::Flags flags,
87 int capture_register_count);
ager@chromium.orga74f0da2008-12-03 16:05:52 +000088
89
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000090 static void AtomCompile(Handle<JSRegExp> re,
91 Handle<String> pattern,
92 JSRegExp::Flags flags,
93 Handle<String> match_pattern);
94
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000095 static Handle<Object> AtomExec(Handle<JSRegExp> regexp,
96 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000097 int index,
98 Handle<JSArray> lastMatchInfo);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000099
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000100 enum IrregexpResult { RE_FAILURE = 0, RE_SUCCESS = 1, RE_EXCEPTION = -1 };
101
102 // Prepare a RegExp for being executed one or more times (using
103 // IrregexpExecOnce) on the subject.
104 // This ensures that the regexp is compiled for the subject, and that
105 // the subject is flat.
106 // Returns the number of integer spaces required by IrregexpExecOnce
107 // as its "registers" argument. If the regexp cannot be compiled,
108 // an exception is set as pending, and this function returns negative.
109 static int IrregexpPrepare(Handle<JSRegExp> regexp,
110 Handle<String> subject);
111
112 // Execute a regular expression once on the subject, starting from
113 // character "index".
114 // If successful, returns RE_SUCCESS and set the capture positions
115 // in the first registers.
116 // If matching fails, returns RE_FAILURE.
117 // If execution fails, sets a pending exception and returns RE_EXCEPTION.
118 static IrregexpResult IrregexpExecOnce(Handle<JSRegExp> regexp,
119 Handle<String> subject,
120 int index,
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000121 Vector<int> registers);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000122
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000123 // Execute an Irregexp bytecode pattern.
ager@chromium.org41826e72009-03-30 13:30:57 +0000124 // On a successful match, the result is a JSArray containing
125 // captured positions. On a failure, the result is the null value.
126 // Returns an empty handle in case of an exception.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000127 static Handle<Object> IrregexpExec(Handle<JSRegExp> regexp,
128 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000129 int index,
130 Handle<JSArray> lastMatchInfo);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000131
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000132 // Array index in the lastMatchInfo array.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000133 static const int kLastCaptureCount = 0;
134 static const int kLastSubject = 1;
135 static const int kLastInput = 2;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000136 static const int kFirstCapture = 3;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000137 static const int kLastMatchOverhead = 3;
138
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000139 // Direct offset into the lastMatchInfo array.
140 static const int kLastCaptureCountOffset =
141 FixedArray::kHeaderSize + kLastCaptureCount * kPointerSize;
142 static const int kLastSubjectOffset =
143 FixedArray::kHeaderSize + kLastSubject * kPointerSize;
144 static const int kLastInputOffset =
145 FixedArray::kHeaderSize + kLastInput * kPointerSize;
146 static const int kFirstCaptureOffset =
147 FixedArray::kHeaderSize + kFirstCapture * kPointerSize;
148
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000149 // Used to access the lastMatchInfo array.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000150 static int GetCapture(FixedArray* array, int index) {
151 return Smi::cast(array->get(index + kFirstCapture))->value();
152 }
153
154 static void SetLastCaptureCount(FixedArray* array, int to) {
155 array->set(kLastCaptureCount, Smi::FromInt(to));
156 }
157
158 static void SetLastSubject(FixedArray* array, String* to) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000159 array->set(kLastSubject, to);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000160 }
161
162 static void SetLastInput(FixedArray* array, String* to) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000163 array->set(kLastInput, to);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000164 }
165
166 static void SetCapture(FixedArray* array, int index, int to) {
167 array->set(index + kFirstCapture, Smi::FromInt(to));
168 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000169
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000170 static int GetLastCaptureCount(FixedArray* array) {
171 return Smi::cast(array->get(kLastCaptureCount))->value();
172 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000173
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000174 // For acting on the JSRegExp data FixedArray.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000175 static int IrregexpMaxRegisterCount(FixedArray* re);
176 static void SetIrregexpMaxRegisterCount(FixedArray* re, int value);
177 static int IrregexpNumberOfCaptures(FixedArray* re);
178 static int IrregexpNumberOfRegisters(FixedArray* re);
179 static ByteArray* IrregexpByteCode(FixedArray* re, bool is_ascii);
180 static Code* IrregexpNativeCode(FixedArray* re, bool is_ascii);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000181
karlklose@chromium.org83a47282011-05-11 11:54:09 +0000182 // Limit the space regexps take up on the heap. In order to limit this we
183 // would like to keep track of the amount of regexp code on the heap. This
184 // is not tracked, however. As a conservative approximation we track the
185 // total regexp code compiled including code that has subsequently been freed
186 // and the total executable memory at any point.
187 static const int kRegExpExecutableMemoryLimit = 16 * MB;
188 static const int kRegWxpCompiledLimit = 1 * MB;
189
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000190 private:
191 static String* last_ascii_string_;
192 static String* two_byte_cached_string_;
193
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000194 static bool CompileIrregexp(
195 Handle<JSRegExp> re, Handle<String> sample_subject, bool is_ascii);
196 static inline bool EnsureCompiledIrregexp(
197 Handle<JSRegExp> re, Handle<String> sample_subject, bool is_ascii);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000198
199
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000200 // Set the subject cache. The previous string buffer is not deleted, so the
201 // caller should ensure that it doesn't leak.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000202 static void SetSubjectCache(String* subject,
203 char* utf8_subject,
204 int uft8_length,
205 int character_position,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000206 int utf8_position);
207
208 // A one element cache of the last utf8_subject string and its length. The
209 // subject JS String object is cached in the heap. We also cache a
210 // translation between position and utf8 position.
211 static char* utf8_subject_cache_;
212 static int utf8_length_cache_;
213 static int utf8_position_;
214 static int character_position_;
215};
216
217
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000218// Represents the location of one element relative to the intersection of
219// two sets. Corresponds to the four areas of a Venn diagram.
220enum ElementInSetsRelation {
221 kInsideNone = 0,
222 kInsideFirst = 1,
223 kInsideSecond = 2,
224 kInsideBoth = 3
225};
226
227
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000228class CharacterRange {
229 public:
230 CharacterRange() : from_(0), to_(0) { }
231 // For compatibility with the CHECK_OK macro
232 CharacterRange(void* null) { ASSERT_EQ(NULL, null); } //NOLINT
233 CharacterRange(uc16 from, uc16 to) : from_(from), to_(to) { }
234 static void AddClassEscape(uc16 type, ZoneList<CharacterRange>* ranges);
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000235 static Vector<const int> GetWordBounds();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000236 static inline CharacterRange Singleton(uc16 value) {
237 return CharacterRange(value, value);
238 }
239 static inline CharacterRange Range(uc16 from, uc16 to) {
240 ASSERT(from <= to);
241 return CharacterRange(from, to);
242 }
243 static inline CharacterRange Everything() {
244 return CharacterRange(0, 0xFFFF);
245 }
246 bool Contains(uc16 i) { return from_ <= i && i <= to_; }
247 uc16 from() const { return from_; }
248 void set_from(uc16 value) { from_ = value; }
249 uc16 to() const { return to_; }
250 void set_to(uc16 value) { to_ = value; }
251 bool is_valid() { return from_ <= to_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000252 bool IsEverything(uc16 max) { return from_ == 0 && to_ >= max; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000253 bool IsSingleton() { return (from_ == to_); }
ager@chromium.org38e4c712009-11-11 09:11:58 +0000254 void AddCaseEquivalents(ZoneList<CharacterRange>* ranges, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000255 static void Split(ZoneList<CharacterRange>* base,
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000256 Vector<const int> overlay,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000257 ZoneList<CharacterRange>** included,
258 ZoneList<CharacterRange>** excluded);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000259 // Whether a range list is in canonical form: Ranges ordered by from value,
260 // and ranges non-overlapping and non-adjacent.
261 static bool IsCanonical(ZoneList<CharacterRange>* ranges);
262 // Convert range list to canonical form. The characters covered by the ranges
263 // will still be the same, but no character is in more than one range, and
264 // adjacent ranges are merged. The resulting list may be shorter than the
265 // original, but cannot be longer.
266 static void Canonicalize(ZoneList<CharacterRange>* ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000267 // Negate the contents of a character range in canonical form.
268 static void Negate(ZoneList<CharacterRange>* src,
269 ZoneList<CharacterRange>* dst);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000270 static const int kStartMarker = (1 << 24);
271 static const int kPayloadMask = (1 << 24) - 1;
272
273 private:
274 uc16 from_;
275 uc16 to_;
276};
277
278
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000279// A set of unsigned integers that behaves especially well on small
280// integers (< 32). May do zone-allocation.
281class OutSet: public ZoneObject {
282 public:
283 OutSet() : first_(0), remaining_(NULL), successors_(NULL) { }
284 OutSet* Extend(unsigned value);
285 bool Get(unsigned value);
286 static const unsigned kFirstLimit = 32;
287
288 private:
289 // Destructively set a value in this set. In most cases you want
290 // to use Extend instead to ensure that only one instance exists
291 // that contains the same values.
292 void Set(unsigned value);
293
294 // The successors are a list of sets that contain the same values
295 // as this set and the one more value that is not present in this
296 // set.
297 ZoneList<OutSet*>* successors() { return successors_; }
298
299 OutSet(uint32_t first, ZoneList<unsigned>* remaining)
300 : first_(first), remaining_(remaining), successors_(NULL) { }
301 uint32_t first_;
302 ZoneList<unsigned>* remaining_;
303 ZoneList<OutSet*>* successors_;
ager@chromium.org32912102009-01-16 10:38:43 +0000304 friend class Trace;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000305};
306
307
308// A mapping from integers, specified as ranges, to a set of integers.
309// Used for mapping character ranges to choices.
310class DispatchTable : public ZoneObject {
311 public:
312 class Entry {
313 public:
314 Entry() : from_(0), to_(0), out_set_(NULL) { }
315 Entry(uc16 from, uc16 to, OutSet* out_set)
316 : from_(from), to_(to), out_set_(out_set) { }
317 uc16 from() { return from_; }
318 uc16 to() { return to_; }
319 void set_to(uc16 value) { to_ = value; }
320 void AddValue(int value) { out_set_ = out_set_->Extend(value); }
321 OutSet* out_set() { return out_set_; }
322 private:
323 uc16 from_;
324 uc16 to_;
325 OutSet* out_set_;
326 };
327
328 class Config {
329 public:
330 typedef uc16 Key;
331 typedef Entry Value;
332 static const uc16 kNoKey;
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +0000333 static const Entry NoValue() { return Value(); }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000334 static inline int Compare(uc16 a, uc16 b) {
335 if (a == b)
336 return 0;
337 else if (a < b)
338 return -1;
339 else
340 return 1;
341 }
342 };
343
344 void AddRange(CharacterRange range, int value);
345 OutSet* Get(uc16 value);
346 void Dump();
347
348 template <typename Callback>
349 void ForEach(Callback* callback) { return tree()->ForEach(callback); }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000350
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000351 private:
352 // There can't be a static empty set since it allocates its
353 // successors in a zone and caches them.
354 OutSet* empty() { return &empty_; }
355 OutSet empty_;
356 ZoneSplayTree<Config>* tree() { return &tree_; }
357 ZoneSplayTree<Config> tree_;
358};
359
360
361#define FOR_EACH_NODE_TYPE(VISIT) \
362 VISIT(End) \
363 VISIT(Action) \
364 VISIT(Choice) \
365 VISIT(BackReference) \
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000366 VISIT(Assertion) \
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000367 VISIT(Text)
368
369
370#define FOR_EACH_REG_EXP_TREE_TYPE(VISIT) \
371 VISIT(Disjunction) \
372 VISIT(Alternative) \
373 VISIT(Assertion) \
374 VISIT(CharacterClass) \
375 VISIT(Atom) \
376 VISIT(Quantifier) \
377 VISIT(Capture) \
378 VISIT(Lookahead) \
379 VISIT(BackReference) \
380 VISIT(Empty) \
381 VISIT(Text)
382
383
384#define FORWARD_DECLARE(Name) class RegExp##Name;
385FOR_EACH_REG_EXP_TREE_TYPE(FORWARD_DECLARE)
386#undef FORWARD_DECLARE
387
388
389class TextElement {
390 public:
391 enum Type {UNINITIALIZED, ATOM, CHAR_CLASS};
392 TextElement() : type(UNINITIALIZED) { }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000393 explicit TextElement(Type t) : type(t), cp_offset(-1) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000394 static TextElement Atom(RegExpAtom* atom);
395 static TextElement CharClass(RegExpCharacterClass* char_class);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000396 int length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000397 Type type;
398 union {
399 RegExpAtom* u_atom;
400 RegExpCharacterClass* u_char_class;
401 } data;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000402 int cp_offset;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000403};
404
405
ager@chromium.org32912102009-01-16 10:38:43 +0000406class Trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000407
408
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000409struct NodeInfo {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000410 NodeInfo()
411 : being_analyzed(false),
412 been_analyzed(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000413 follows_word_interest(false),
414 follows_newline_interest(false),
415 follows_start_interest(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000416 at_end(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000417 visited(false) { }
418
419 // Returns true if the interests and assumptions of this node
420 // matches the given one.
421 bool Matches(NodeInfo* that) {
422 return (at_end == that->at_end) &&
423 (follows_word_interest == that->follows_word_interest) &&
424 (follows_newline_interest == that->follows_newline_interest) &&
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000425 (follows_start_interest == that->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000426 }
427
428 // Updates the interests of this node given the interests of the
429 // node preceding it.
430 void AddFromPreceding(NodeInfo* that) {
431 at_end |= that->at_end;
432 follows_word_interest |= that->follows_word_interest;
433 follows_newline_interest |= that->follows_newline_interest;
434 follows_start_interest |= that->follows_start_interest;
435 }
436
ager@chromium.org8bb60582008-12-11 12:02:20 +0000437 bool HasLookbehind() {
438 return follows_word_interest ||
439 follows_newline_interest ||
440 follows_start_interest;
441 }
442
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000443 // Sets the interests of this node to include the interests of the
444 // following node.
445 void AddFromFollowing(NodeInfo* that) {
446 follows_word_interest |= that->follows_word_interest;
447 follows_newline_interest |= that->follows_newline_interest;
448 follows_start_interest |= that->follows_start_interest;
449 }
450
451 void ResetCompilationState() {
452 being_analyzed = false;
453 been_analyzed = false;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000454 }
455
456 bool being_analyzed: 1;
457 bool been_analyzed: 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000458
459 // These bits are set of this node has to know what the preceding
460 // character was.
461 bool follows_word_interest: 1;
462 bool follows_newline_interest: 1;
463 bool follows_start_interest: 1;
464
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000465 bool at_end: 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000466 bool visited: 1;
467};
468
469
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000470class SiblingList {
471 public:
472 SiblingList() : list_(NULL) { }
473 int length() {
474 return list_ == NULL ? 0 : list_->length();
475 }
476 void Ensure(RegExpNode* parent) {
477 if (list_ == NULL) {
478 list_ = new ZoneList<RegExpNode*>(2);
479 list_->Add(parent);
480 }
481 }
482 void Add(RegExpNode* node) { list_->Add(node); }
483 RegExpNode* Get(int index) { return list_->at(index); }
484 private:
485 ZoneList<RegExpNode*>* list_;
486};
487
488
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000489// Details of a quick mask-compare check that can look ahead in the
490// input stream.
491class QuickCheckDetails {
492 public:
493 QuickCheckDetails()
494 : characters_(0),
495 mask_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000496 value_(0),
497 cannot_match_(false) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000498 explicit QuickCheckDetails(int characters)
499 : characters_(characters),
500 mask_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000501 value_(0),
502 cannot_match_(false) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000503 bool Rationalize(bool ascii);
504 // Merge in the information from another branch of an alternation.
505 void Merge(QuickCheckDetails* other, int from_index);
506 // Advance the current position by some amount.
507 void Advance(int by, bool ascii);
508 void Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000509 bool cannot_match() { return cannot_match_; }
510 void set_cannot_match() { cannot_match_ = true; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000511 struct Position {
512 Position() : mask(0), value(0), determines_perfectly(false) { }
513 uc16 mask;
514 uc16 value;
515 bool determines_perfectly;
516 };
517 int characters() { return characters_; }
518 void set_characters(int characters) { characters_ = characters; }
519 Position* positions(int index) {
520 ASSERT(index >= 0);
521 ASSERT(index < characters_);
522 return positions_ + index;
523 }
524 uint32_t mask() { return mask_; }
525 uint32_t value() { return value_; }
526
527 private:
528 // How many characters do we have quick check information from. This is
529 // the same for all branches of a choice node.
530 int characters_;
531 Position positions_[4];
532 // These values are the condensate of the above array after Rationalize().
533 uint32_t mask_;
534 uint32_t value_;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000535 // If set to true, there is no way this quick check can match at all.
536 // E.g., if it requires to be at the start of the input, and isn't.
537 bool cannot_match_;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000538};
539
540
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000541class RegExpNode: public ZoneObject {
542 public:
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000543 RegExpNode() : first_character_set_(NULL), trace_count_(0) {
544 bm_info_[0] = bm_info_[1] = NULL;
545 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000546 virtual ~RegExpNode();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000547 virtual void Accept(NodeVisitor* visitor) = 0;
548 // Generates a goto to this node or actually generates the code at this point.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000549 virtual void Emit(RegExpCompiler* compiler, Trace* trace) = 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000550 // How many characters must this node consume at a minimum in order to
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000551 // succeed. If we have found at least 'still_to_find' characters that
552 // must be consumed there is no need to ask any following nodes whether
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000553 // they are sure to eat any more characters. The not_at_start argument is
554 // used to indicate that we know we are not at the start of the input. In
555 // this case anchored branches will always fail and can be ignored when
556 // determining how many characters are consumed on success.
557 virtual int EatsAtLeast(int still_to_find,
558 int recursion_depth,
559 bool not_at_start) = 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000560 // Emits some quick code that checks whether the preloaded characters match.
561 // Falls through on certain failure, jumps to the label on possible success.
562 // If the node cannot make a quick check it does nothing and returns false.
563 bool EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +0000564 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000565 bool preload_has_checked_bounds,
566 Label* on_possible_success,
567 QuickCheckDetails* details_return,
568 bool fall_through_on_failure);
569 // For a given number of characters this returns a mask and a value. The
570 // next n characters are anded with the mask and compared with the value.
571 // A comparison failure indicates the node cannot match the next n characters.
572 // A comparison success indicates the node may match.
573 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
574 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000575 int characters_filled_in,
576 bool not_at_start) = 0;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000577 static const int kNodeIsTooComplexForGreedyLoops = -1;
578 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000579 // Only returns the successor for a text node of length 1 that matches any
580 // character and that has no guards on it.
581 virtual RegExpNode* GetSuccessorOfOmnivorousTextNode(
582 RegExpCompiler* compiler) {
583 return NULL;
584 }
585
586 // Collects information on the possible code units (mod 128) that can match if
587 // we look forward. This is used for a Boyer-Moore-like string searching
588 // implementation. TODO(erikcorry): This should share more code with
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000589 // EatsAtLeast, GetQuickCheckDetails.
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000590 virtual void FillInBMInfo(
591 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
592 UNREACHABLE();
593 }
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000594 // We want to avoid recalculating the lookahead info, so we store it on the
595 // node. Only info that is for this node is stored. We can tell that the
596 // info is for this node when offset == 0, so the information is calculated
597 // relative to this node.
598 void SaveBMInfo(BoyerMooreLookahead* bm, bool not_at_start, int offset) {
599 if (offset == 0) set_bm_info(not_at_start, bm);
600 }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000601
ager@chromium.org8bb60582008-12-11 12:02:20 +0000602 Label* label() { return &label_; }
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000603 // If non-generic code is generated for a node (i.e. the node is not at the
ager@chromium.org32912102009-01-16 10:38:43 +0000604 // start of the trace) then it cannot be reused. This variable sets a limit
605 // on how often we allow that to happen before we insist on starting a new
606 // trace and generating generic code for a node that can be reused by flushing
607 // the deferred actions in the current trace and generating a goto.
608 static const int kMaxCopiesCodeGenerated = 10;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000609
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000610 NodeInfo* info() { return &info_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000611
612 void AddSibling(RegExpNode* node) { siblings_.Add(node); }
613
614 // Static version of EnsureSibling that expresses the fact that the
615 // result has the same type as the input.
616 template <class C>
617 static C* EnsureSibling(C* node, NodeInfo* info, bool* cloned) {
618 return static_cast<C*>(node->EnsureSibling(info, cloned));
619 }
620
621 SiblingList* siblings() { return &siblings_; }
622 void set_siblings(SiblingList* other) { siblings_ = *other; }
623
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000624 // Get and set the cached first character set value.
625 ZoneList<CharacterRange>* first_character_set() {
626 return first_character_set_;
627 }
628 void set_first_character_set(ZoneList<CharacterRange>* character_set) {
629 first_character_set_ = character_set;
630 }
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000631 BoyerMooreLookahead* bm_info(bool not_at_start) {
632 return bm_info_[not_at_start ? 1 : 0];
633 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000634
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000635 protected:
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000636 enum LimitResult { DONE, CONTINUE };
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000637 static const int kComputeFirstCharacterSetFail = -1;
638
ager@chromium.org32912102009-01-16 10:38:43 +0000639 LimitResult LimitVersions(RegExpCompiler* compiler, Trace* trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000640
641 // Returns a sibling of this node whose interests and assumptions
642 // match the ones in the given node info. If no sibling exists NULL
643 // is returned.
644 RegExpNode* TryGetSibling(NodeInfo* info);
645
646 // Returns a sibling of this node whose interests match the ones in
647 // the given node info. The info must not contain any assertions.
648 // If no node exists a new one will be created by cloning the current
649 // node. The result will always be an instance of the same concrete
650 // class as this node.
651 RegExpNode* EnsureSibling(NodeInfo* info, bool* cloned);
652
653 // Returns a clone of this node initialized using the copy constructor
654 // of its concrete class. Note that the node may have to be pre-
ager@chromium.org32912102009-01-16 10:38:43 +0000655 // processed before it is on a usable state.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000656 virtual RegExpNode* Clone() = 0;
657
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000658 void set_bm_info(bool not_at_start, BoyerMooreLookahead* bm) {
659 bm_info_[not_at_start ? 1 : 0] = bm;
660 }
661
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000662 private:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000663 static const int kFirstCharBudget = 10;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000664 Label label_;
665 NodeInfo info_;
666 SiblingList siblings_;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000667 ZoneList<CharacterRange>* first_character_set_;
ager@chromium.org32912102009-01-16 10:38:43 +0000668 // This variable keeps track of how many times code has been generated for
669 // this node (in different traces). We don't keep track of where the
670 // generated code is located unless the code is generated at the start of
671 // a trace, in which case it is generic and can be reused by flushing the
672 // deferred operations in the current trace and generating a goto.
673 int trace_count_;
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000674 BoyerMooreLookahead* bm_info_[2];
ager@chromium.org32912102009-01-16 10:38:43 +0000675};
676
677
678// A simple closed interval.
679class Interval {
680 public:
681 Interval() : from_(kNone), to_(kNone) { }
682 Interval(int from, int to) : from_(from), to_(to) { }
683 Interval Union(Interval that) {
684 if (that.from_ == kNone)
685 return *this;
686 else if (from_ == kNone)
687 return that;
688 else
689 return Interval(Min(from_, that.from_), Max(to_, that.to_));
690 }
691 bool Contains(int value) {
692 return (from_ <= value) && (value <= to_);
693 }
694 bool is_empty() { return from_ == kNone; }
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000695 int from() const { return from_; }
696 int to() const { return to_; }
ager@chromium.org32912102009-01-16 10:38:43 +0000697 static Interval Empty() { return Interval(); }
698 static const int kNone = -1;
699 private:
700 int from_;
701 int to_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000702};
703
704
705class SeqRegExpNode: public RegExpNode {
706 public:
707 explicit SeqRegExpNode(RegExpNode* on_success)
708 : on_success_(on_success) { }
709 RegExpNode* on_success() { return on_success_; }
710 void set_on_success(RegExpNode* node) { on_success_ = node; }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000711 virtual void FillInBMInfo(
712 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
713 on_success_->FillInBMInfo(offset, bm, not_at_start);
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000714 if (offset == 0) set_bm_info(not_at_start, bm);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000715 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000716 private:
717 RegExpNode* on_success_;
718};
719
720
721class ActionNode: public SeqRegExpNode {
722 public:
723 enum Type {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000724 SET_REGISTER,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000725 INCREMENT_REGISTER,
726 STORE_POSITION,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000727 BEGIN_SUBMATCH,
ager@chromium.org32912102009-01-16 10:38:43 +0000728 POSITIVE_SUBMATCH_SUCCESS,
729 EMPTY_MATCH_CHECK,
730 CLEAR_CAPTURES
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000731 };
ager@chromium.org8bb60582008-12-11 12:02:20 +0000732 static ActionNode* SetRegister(int reg, int val, RegExpNode* on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000733 static ActionNode* IncrementRegister(int reg, RegExpNode* on_success);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000734 static ActionNode* StorePosition(int reg,
735 bool is_capture,
736 RegExpNode* on_success);
ager@chromium.org32912102009-01-16 10:38:43 +0000737 static ActionNode* ClearCaptures(Interval range, RegExpNode* on_success);
738 static ActionNode* BeginSubmatch(int stack_pointer_reg,
739 int position_reg,
740 RegExpNode* on_success);
741 static ActionNode* PositiveSubmatchSuccess(int stack_pointer_reg,
742 int restore_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000743 int clear_capture_count,
744 int clear_capture_from,
ager@chromium.org32912102009-01-16 10:38:43 +0000745 RegExpNode* on_success);
746 static ActionNode* EmptyMatchCheck(int start_register,
747 int repetition_register,
748 int repetition_limit,
749 RegExpNode* on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000750 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000751 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000752 virtual int EatsAtLeast(int still_to_find,
753 int recursion_depth,
754 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000755 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
756 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000757 int filled_in,
758 bool not_at_start) {
759 return on_success()->GetQuickCheckDetails(
760 details, compiler, filled_in, not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000761 }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000762 virtual void FillInBMInfo(
763 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000764 Type type() { return type_; }
765 // TODO(erikcorry): We should allow some action nodes in greedy loops.
766 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000767 virtual ActionNode* Clone() { return new ActionNode(*this); }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000768
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000769 private:
770 union {
771 struct {
772 int reg;
773 int value;
774 } u_store_register;
775 struct {
776 int reg;
777 } u_increment_register;
778 struct {
779 int reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000780 bool is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000781 } u_position_register;
782 struct {
783 int stack_pointer_register;
784 int current_position_register;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000785 int clear_register_count;
786 int clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000787 } u_submatch;
ager@chromium.org32912102009-01-16 10:38:43 +0000788 struct {
789 int start_register;
790 int repetition_register;
791 int repetition_limit;
792 } u_empty_match_check;
793 struct {
794 int range_from;
795 int range_to;
796 } u_clear_captures;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000797 } data_;
798 ActionNode(Type type, RegExpNode* on_success)
799 : SeqRegExpNode(on_success),
800 type_(type) { }
801 Type type_;
802 friend class DotPrinter;
803};
804
805
806class TextNode: public SeqRegExpNode {
807 public:
808 TextNode(ZoneList<TextElement>* elms,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000809 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000810 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000811 elms_(elms) { }
812 TextNode(RegExpCharacterClass* that,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000813 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000814 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000815 elms_(new ZoneList<TextElement>(1)) {
816 elms_->Add(TextElement::CharClass(that));
817 }
818 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000819 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000820 virtual int EatsAtLeast(int still_to_find,
821 int recursion_depth,
822 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000823 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
824 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000825 int characters_filled_in,
826 bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000827 ZoneList<TextElement>* elements() { return elms_; }
ager@chromium.org38e4c712009-11-11 09:11:58 +0000828 void MakeCaseIndependent(bool is_ascii);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000829 virtual int GreedyLoopTextLength();
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000830 virtual RegExpNode* GetSuccessorOfOmnivorousTextNode(
831 RegExpCompiler* compiler);
832 virtual void FillInBMInfo(
833 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000834 virtual TextNode* Clone() {
835 TextNode* result = new TextNode(*this);
836 result->CalculateOffsets();
837 return result;
838 }
839 void CalculateOffsets();
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000840
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000841 private:
842 enum TextEmitPassType {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000843 NON_ASCII_MATCH, // Check for characters that can't match.
844 SIMPLE_CHARACTER_MATCH, // Case-dependent single character check.
845 NON_LETTER_CHARACTER_MATCH, // Check characters that have no case equivs.
846 CASE_CHARACTER_MATCH, // Case-independent single character check.
847 CHARACTER_CLASS_MATCH // Character class.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000848 };
ager@chromium.org381abbb2009-02-25 13:23:22 +0000849 static bool SkipPass(int pass, bool ignore_case);
850 static const int kFirstRealPass = SIMPLE_CHARACTER_MATCH;
851 static const int kLastPass = CHARACTER_CLASS_MATCH;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000852 void TextEmitPass(RegExpCompiler* compiler,
853 TextEmitPassType pass,
854 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +0000855 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000856 bool first_element_checked,
857 int* checked_up_to);
858 int Length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000859 ZoneList<TextElement>* elms_;
860};
861
862
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000863class AssertionNode: public SeqRegExpNode {
864 public:
865 enum AssertionNodeType {
866 AT_END,
867 AT_START,
868 AT_BOUNDARY,
869 AT_NON_BOUNDARY,
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000870 AFTER_NEWLINE
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000871 };
872 static AssertionNode* AtEnd(RegExpNode* on_success) {
873 return new AssertionNode(AT_END, on_success);
874 }
875 static AssertionNode* AtStart(RegExpNode* on_success) {
876 return new AssertionNode(AT_START, on_success);
877 }
878 static AssertionNode* AtBoundary(RegExpNode* on_success) {
879 return new AssertionNode(AT_BOUNDARY, on_success);
880 }
881 static AssertionNode* AtNonBoundary(RegExpNode* on_success) {
882 return new AssertionNode(AT_NON_BOUNDARY, on_success);
883 }
884 static AssertionNode* AfterNewline(RegExpNode* on_success) {
885 return new AssertionNode(AFTER_NEWLINE, on_success);
886 }
887 virtual void Accept(NodeVisitor* visitor);
888 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000889 virtual int EatsAtLeast(int still_to_find,
890 int recursion_depth,
891 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000892 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
893 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000894 int filled_in,
895 bool not_at_start);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000896 virtual void FillInBMInfo(
897 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000898 virtual AssertionNode* Clone() { return new AssertionNode(*this); }
899 AssertionNodeType type() { return type_; }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000900 void set_type(AssertionNodeType type) { type_ = type; }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000901
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000902 private:
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000903 void EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace);
904 enum IfPrevious { kIsNonWord, kIsWord };
905 void BacktrackIfPrevious(RegExpCompiler* compiler,
906 Trace* trace,
907 IfPrevious backtrack_if_previous);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000908 AssertionNode(AssertionNodeType t, RegExpNode* on_success)
909 : SeqRegExpNode(on_success), type_(t) { }
910 AssertionNodeType type_;
911};
912
913
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000914class BackReferenceNode: public SeqRegExpNode {
915 public:
916 BackReferenceNode(int start_reg,
917 int end_reg,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000918 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000919 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000920 start_reg_(start_reg),
921 end_reg_(end_reg) { }
922 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000923 int start_register() { return start_reg_; }
924 int end_register() { return end_reg_; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000925 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000926 virtual int EatsAtLeast(int still_to_find,
927 int recursion_depth,
928 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000929 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
930 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000931 int characters_filled_in,
932 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000933 return;
934 }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000935 virtual void FillInBMInfo(
erik.corry@gmail.comed49e962012-04-17 11:57:53 +0000936 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000937 virtual BackReferenceNode* Clone() { return new BackReferenceNode(*this); }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000938
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000939 private:
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000940 int start_reg_;
941 int end_reg_;
942};
943
944
945class EndNode: public RegExpNode {
946 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000947 enum Action { ACCEPT, BACKTRACK, NEGATIVE_SUBMATCH_SUCCESS };
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000948 explicit EndNode(Action action) : action_(action) { }
949 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000950 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000951 virtual int EatsAtLeast(int still_to_find,
952 int recursion_depth,
953 bool not_at_start) { return 0; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000954 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
955 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000956 int characters_filled_in,
957 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000958 // Returning 0 from EatsAtLeast should ensure we never get here.
959 UNREACHABLE();
960 }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000961 virtual void FillInBMInfo(
962 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
963 // Returning 0 from EatsAtLeast should ensure we never get here.
964 UNREACHABLE();
965 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000966 virtual EndNode* Clone() { return new EndNode(*this); }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000967 private:
968 Action action_;
969};
970
971
ager@chromium.org8bb60582008-12-11 12:02:20 +0000972class NegativeSubmatchSuccess: public EndNode {
973 public:
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000974 NegativeSubmatchSuccess(int stack_pointer_reg,
975 int position_reg,
976 int clear_capture_count,
977 int clear_capture_start)
ager@chromium.org8bb60582008-12-11 12:02:20 +0000978 : EndNode(NEGATIVE_SUBMATCH_SUCCESS),
979 stack_pointer_register_(stack_pointer_reg),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000980 current_position_register_(position_reg),
981 clear_capture_count_(clear_capture_count),
982 clear_capture_start_(clear_capture_start) { }
983 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000984
985 private:
986 int stack_pointer_register_;
987 int current_position_register_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000988 int clear_capture_count_;
989 int clear_capture_start_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000990};
991
992
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000993class Guard: public ZoneObject {
994 public:
995 enum Relation { LT, GEQ };
996 Guard(int reg, Relation op, int value)
997 : reg_(reg),
998 op_(op),
999 value_(value) { }
1000 int reg() { return reg_; }
1001 Relation op() { return op_; }
1002 int value() { return value_; }
1003
1004 private:
1005 int reg_;
1006 Relation op_;
1007 int value_;
1008};
1009
1010
1011class GuardedAlternative {
1012 public:
1013 explicit GuardedAlternative(RegExpNode* node) : node_(node), guards_(NULL) { }
1014 void AddGuard(Guard* guard);
1015 RegExpNode* node() { return node_; }
1016 void set_node(RegExpNode* node) { node_ = node; }
1017 ZoneList<Guard*>* guards() { return guards_; }
1018
1019 private:
1020 RegExpNode* node_;
1021 ZoneList<Guard*>* guards_;
1022};
1023
1024
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001025class AlternativeGeneration;
1026
1027
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001028class ChoiceNode: public RegExpNode {
1029 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +00001030 explicit ChoiceNode(int expected_size)
1031 : alternatives_(new ZoneList<GuardedAlternative>(expected_size)),
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001032 table_(NULL),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001033 not_at_start_(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001034 being_calculated_(false) { }
1035 virtual void Accept(NodeVisitor* visitor);
1036 void AddAlternative(GuardedAlternative node) { alternatives()->Add(node); }
1037 ZoneList<GuardedAlternative>* alternatives() { return alternatives_; }
1038 DispatchTable* GetTable(bool ignore_case);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001039 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001040 virtual int EatsAtLeast(int still_to_find,
1041 int recursion_depth,
1042 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001043 int EatsAtLeastHelper(int still_to_find,
1044 int recursion_depth,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001045 RegExpNode* ignore_this_node,
1046 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001047 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1048 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001049 int characters_filled_in,
1050 bool not_at_start);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001051 virtual void FillInBMInfo(
1052 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001053 virtual ChoiceNode* Clone() { return new ChoiceNode(*this); }
1054
1055 bool being_calculated() { return being_calculated_; }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001056 bool not_at_start() { return not_at_start_; }
1057 void set_not_at_start() { not_at_start_ = true; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001058 void set_being_calculated(bool b) { being_calculated_ = b; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001059 virtual bool try_to_emit_quick_check_for_alternative(int i) { return true; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001060
ager@chromium.org8bb60582008-12-11 12:02:20 +00001061 protected:
jkummerow@chromium.org486075a2011-09-07 12:44:28 +00001062 int GreedyLoopTextLengthForAlternative(GuardedAlternative* alternative);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001063 ZoneList<GuardedAlternative>* alternatives_;
1064
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001065 private:
1066 friend class DispatchTableConstructor;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001067 friend class Analysis;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001068 void GenerateGuard(RegExpMacroAssembler* macro_assembler,
ager@chromium.org5ec48922009-05-05 07:25:34 +00001069 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001070 Trace* trace);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001071 int CalculatePreloadCharacters(RegExpCompiler* compiler, int eats_at_least);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001072 void EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001073 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001074 GuardedAlternative alternative,
1075 AlternativeGeneration* alt_gen,
1076 int preload_characters,
1077 bool next_expects_preload);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001078 DispatchTable* table_;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001079 // If true, this node is never checked at the start of the input.
1080 // Allows a new trace to start with at_start() set to false.
1081 bool not_at_start_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001082 bool being_calculated_;
1083};
1084
1085
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001086class NegativeLookaheadChoiceNode: public ChoiceNode {
1087 public:
1088 explicit NegativeLookaheadChoiceNode(GuardedAlternative this_must_fail,
1089 GuardedAlternative then_do_this)
1090 : ChoiceNode(2) {
1091 AddAlternative(this_must_fail);
1092 AddAlternative(then_do_this);
1093 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001094 virtual int EatsAtLeast(int still_to_find,
1095 int recursion_depth,
1096 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001097 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1098 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001099 int characters_filled_in,
1100 bool not_at_start);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001101 virtual void FillInBMInfo(
1102 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
1103 alternatives_->at(1).node()->FillInBMInfo(offset, bm, not_at_start);
erik.corry@gmail.comed49e962012-04-17 11:57:53 +00001104 if (offset == 0) set_bm_info(not_at_start, bm);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001105 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001106 // For a negative lookahead we don't emit the quick check for the
1107 // alternative that is expected to fail. This is because quick check code
1108 // starts by loading enough characters for the alternative that takes fewest
1109 // characters, but on a negative lookahead the negative branch did not take
1110 // part in that calculation (EatsAtLeast) so the assumptions don't hold.
1111 virtual bool try_to_emit_quick_check_for_alternative(int i) { return i != 0; }
1112};
1113
1114
ager@chromium.org8bb60582008-12-11 12:02:20 +00001115class LoopChoiceNode: public ChoiceNode {
1116 public:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001117 explicit LoopChoiceNode(bool body_can_be_zero_length)
1118 : ChoiceNode(2),
1119 loop_node_(NULL),
1120 continue_node_(NULL),
1121 body_can_be_zero_length_(body_can_be_zero_length) { }
1122 void AddLoopAlternative(GuardedAlternative alt);
1123 void AddContinueAlternative(GuardedAlternative alt);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001124 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001125 virtual int EatsAtLeast(int still_to_find,
1126 int recursion_depth,
1127 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001128 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1129 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001130 int characters_filled_in,
1131 bool not_at_start);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001132 virtual void FillInBMInfo(
1133 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001134 virtual LoopChoiceNode* Clone() { return new LoopChoiceNode(*this); }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001135 RegExpNode* loop_node() { return loop_node_; }
1136 RegExpNode* continue_node() { return continue_node_; }
1137 bool body_can_be_zero_length() { return body_can_be_zero_length_; }
1138 virtual void Accept(NodeVisitor* visitor);
1139
1140 private:
1141 // AddAlternative is made private for loop nodes because alternatives
1142 // should not be added freely, we need to keep track of which node
1143 // goes back to the node itself.
1144 void AddAlternative(GuardedAlternative node) {
1145 ChoiceNode::AddAlternative(node);
1146 }
1147
1148 RegExpNode* loop_node_;
1149 RegExpNode* continue_node_;
1150 bool body_can_be_zero_length_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001151};
1152
1153
erik.corry@gmail.comed49e962012-04-17 11:57:53 +00001154// Improve the speed that we scan for an initial point where a non-anchored
1155// regexp can match by using a Boyer-Moore-like table. This is done by
1156// identifying non-greedy non-capturing loops in the nodes that eat any
1157// character one at a time. For example in the middle of the regexp
1158// /foo[\s\S]*?bar/ we find such a loop. There is also such a loop implicitly
1159// inserted at the start of any non-anchored regexp.
1160//
1161// When we have found such a loop we look ahead in the nodes to find the set of
1162// characters that can come at given distances. For example for the regexp
1163// /.?foo/ we know that there are at least 3 characters ahead of us, and the
1164// sets of characters that can occur are [any, [f, o], [o]]. We find a range in
1165// the lookahead info where the set of characters is reasonably constrained. In
1166// our example this is from index 1 to 2 (0 is not constrained). We can now
1167// look 3 characters ahead and if we don't find one of [f, o] (the union of
1168// [f, o] and [o]) then we can skip forwards by the range size (in this case 2).
1169//
1170// For Unicode input strings we do the same, but modulo 128.
1171//
1172// We also look at the first string fed to the regexp and use that to get a hint
1173// of the character frequencies in the inputs. This affects the assessment of
1174// whether the set of characters is 'reasonably constrained'.
1175//
1176// We also have another lookahead mechanism (called quick check in the code),
1177// which uses a wide load of multiple characters followed by a mask and compare
1178// to determine whether a match is possible at this point.
1179enum ContainedInLattice {
1180 kNotYet = 0,
1181 kLatticeIn = 1,
1182 kLatticeOut = 2,
1183 kLatticeUnknown = 3 // Can also mean both in and out.
1184};
1185
1186
1187inline ContainedInLattice Combine(ContainedInLattice a, ContainedInLattice b) {
1188 return static_cast<ContainedInLattice>(a | b);
1189}
1190
1191
1192ContainedInLattice AddRange(ContainedInLattice a,
1193 const int* ranges,
1194 int ranges_size,
1195 Interval new_range);
1196
1197
1198class BoyerMoorePositionInfo : public ZoneObject {
1199 public:
1200 BoyerMoorePositionInfo()
1201 : map_(new ZoneList<bool>(kMapSize)),
1202 map_count_(0),
1203 w_(kNotYet),
1204 s_(kNotYet),
1205 d_(kNotYet),
1206 surrogate_(kNotYet) {
1207 for (int i = 0; i < kMapSize; i++) {
1208 map_->Add(false);
1209 }
1210 }
1211
1212 bool& at(int i) { return map_->at(i); }
1213
1214 static const int kMapSize = 128;
1215 static const int kMask = kMapSize - 1;
1216
1217 int map_count() const { return map_count_; }
1218
1219 void Set(int character);
1220 void SetInterval(const Interval& interval);
1221 void SetAll();
1222 bool is_non_word() { return w_ == kLatticeOut; }
1223 bool is_word() { return w_ == kLatticeIn; }
1224
1225 private:
1226 ZoneList<bool>* map_;
1227 int map_count_; // Number of set bits in the map.
1228 ContainedInLattice w_; // The \w character class.
1229 ContainedInLattice s_; // The \s character class.
1230 ContainedInLattice d_; // The \d character class.
1231 ContainedInLattice surrogate_; // Surrogate UTF-16 code units.
1232};
1233
1234
1235class BoyerMooreLookahead : public ZoneObject {
1236 public:
1237 BoyerMooreLookahead(int length, RegExpCompiler* compiler);
1238
1239 int length() { return length_; }
1240 int max_char() { return max_char_; }
1241 RegExpCompiler* compiler() { return compiler_; }
1242
1243 int Count(int map_number) {
1244 return bitmaps_->at(map_number)->map_count();
1245 }
1246
1247 BoyerMoorePositionInfo* at(int i) { return bitmaps_->at(i); }
1248
1249 void Set(int map_number, int character) {
1250 if (character > max_char_) return;
1251 BoyerMoorePositionInfo* info = bitmaps_->at(map_number);
1252 info->Set(character);
1253 }
1254
1255 void SetInterval(int map_number, const Interval& interval) {
1256 if (interval.from() > max_char_) return;
1257 BoyerMoorePositionInfo* info = bitmaps_->at(map_number);
1258 if (interval.to() > max_char_) {
1259 info->SetInterval(Interval(interval.from(), max_char_));
1260 } else {
1261 info->SetInterval(interval);
1262 }
1263 }
1264
1265 void SetAll(int map_number) {
1266 bitmaps_->at(map_number)->SetAll();
1267 }
1268
1269 void SetRest(int from_map) {
1270 for (int i = from_map; i < length_; i++) SetAll(i);
1271 }
1272 bool EmitSkipInstructions(RegExpMacroAssembler* masm);
1273
1274 private:
1275 // This is the value obtained by EatsAtLeast. If we do not have at least this
1276 // many characters left in the sample string then the match is bound to fail.
1277 // Therefore it is OK to read a character this far ahead of the current match
1278 // point.
1279 int length_;
1280 RegExpCompiler* compiler_;
1281 // 0x7f for ASCII, 0xffff for UTF-16.
1282 int max_char_;
1283 ZoneList<BoyerMoorePositionInfo*>* bitmaps_;
1284
1285 int GetSkipTable(int min_lookahead,
1286 int max_lookahead,
1287 Handle<ByteArray> boolean_skip_table);
1288 bool FindWorthwhileInterval(int* from, int* to);
1289 int FindBestInterval(
1290 int max_number_of_chars, int old_biggest_points, int* from, int* to);
1291};
1292
1293
ager@chromium.org8bb60582008-12-11 12:02:20 +00001294// There are many ways to generate code for a node. This class encapsulates
1295// the current way we should be generating. In other words it encapsulates
ager@chromium.org32912102009-01-16 10:38:43 +00001296// the current state of the code generator. The effect of this is that we
1297// generate code for paths that the matcher can take through the regular
1298// expression. A given node in the regexp can be code-generated several times
1299// as it can be part of several traces. For example for the regexp:
1300// /foo(bar|ip)baz/ the code to match baz will be generated twice, once as part
1301// of the foo-bar-baz trace and once as part of the foo-ip-baz trace. The code
1302// to match foo is generated only once (the traces have a common prefix). The
1303// code to store the capture is deferred and generated (twice) after the places
1304// where baz has been matched.
1305class Trace {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001306 public:
iposva@chromium.org245aa852009-02-10 00:49:54 +00001307 // A value for a property that is either known to be true, know to be false,
1308 // or not known.
1309 enum TriBool {
1310 UNKNOWN = -1, FALSE = 0, TRUE = 1
1311 };
1312
ager@chromium.org8bb60582008-12-11 12:02:20 +00001313 class DeferredAction {
1314 public:
1315 DeferredAction(ActionNode::Type type, int reg)
1316 : type_(type), reg_(reg), next_(NULL) { }
1317 DeferredAction* next() { return next_; }
ager@chromium.org32912102009-01-16 10:38:43 +00001318 bool Mentions(int reg);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001319 int reg() { return reg_; }
1320 ActionNode::Type type() { return type_; }
1321 private:
1322 ActionNode::Type type_;
1323 int reg_;
1324 DeferredAction* next_;
ager@chromium.org32912102009-01-16 10:38:43 +00001325 friend class Trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001326 };
1327
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001328 class DeferredCapture : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001329 public:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001330 DeferredCapture(int reg, bool is_capture, Trace* trace)
ager@chromium.org8bb60582008-12-11 12:02:20 +00001331 : DeferredAction(ActionNode::STORE_POSITION, reg),
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001332 cp_offset_(trace->cp_offset()),
1333 is_capture_(is_capture) { }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001334 int cp_offset() { return cp_offset_; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001335 bool is_capture() { return is_capture_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001336 private:
1337 int cp_offset_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001338 bool is_capture_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001339 void set_cp_offset(int cp_offset) { cp_offset_ = cp_offset; }
1340 };
1341
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001342 class DeferredSetRegister : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001343 public:
1344 DeferredSetRegister(int reg, int value)
1345 : DeferredAction(ActionNode::SET_REGISTER, reg),
1346 value_(value) { }
1347 int value() { return value_; }
1348 private:
1349 int value_;
1350 };
1351
ager@chromium.org32912102009-01-16 10:38:43 +00001352 class DeferredClearCaptures : public DeferredAction {
1353 public:
1354 explicit DeferredClearCaptures(Interval range)
1355 : DeferredAction(ActionNode::CLEAR_CAPTURES, -1),
1356 range_(range) { }
1357 Interval range() { return range_; }
1358 private:
1359 Interval range_;
1360 };
1361
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001362 class DeferredIncrementRegister : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001363 public:
1364 explicit DeferredIncrementRegister(int reg)
1365 : DeferredAction(ActionNode::INCREMENT_REGISTER, reg) { }
1366 };
1367
ager@chromium.org32912102009-01-16 10:38:43 +00001368 Trace()
ager@chromium.org8bb60582008-12-11 12:02:20 +00001369 : cp_offset_(0),
1370 actions_(NULL),
1371 backtrack_(NULL),
1372 stop_node_(NULL),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001373 loop_label_(NULL),
1374 characters_preloaded_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001375 bound_checked_up_to_(0),
ager@chromium.org381abbb2009-02-25 13:23:22 +00001376 flush_budget_(100),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001377 at_start_(UNKNOWN) { }
1378
ager@chromium.org32912102009-01-16 10:38:43 +00001379 // End the trace. This involves flushing the deferred actions in the trace
1380 // and pushing a backtrack location onto the backtrack stack. Once this is
1381 // done we can start a new trace or go to one that has already been
1382 // generated.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001383 void Flush(RegExpCompiler* compiler, RegExpNode* successor);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001384 int cp_offset() { return cp_offset_; }
1385 DeferredAction* actions() { return actions_; }
ager@chromium.org32912102009-01-16 10:38:43 +00001386 // A trivial trace is one that has no deferred actions or other state that
1387 // affects the assumptions used when generating code. There is no recorded
1388 // backtrack location in a trivial trace, so with a trivial trace we will
1389 // generate code that, on a failure to match, gets the backtrack location
1390 // from the backtrack stack rather than using a direct jump instruction. We
1391 // always start code generation with a trivial trace and non-trivial traces
1392 // are created as we emit code for nodes or add to the list of deferred
1393 // actions in the trace. The location of the code generated for a node using
1394 // a trivial trace is recorded in a label in the node so that gotos can be
1395 // generated to that code.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001396 bool is_trivial() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001397 return backtrack_ == NULL &&
1398 actions_ == NULL &&
1399 cp_offset_ == 0 &&
1400 characters_preloaded_ == 0 &&
1401 bound_checked_up_to_ == 0 &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001402 quick_check_performed_.characters() == 0 &&
1403 at_start_ == UNKNOWN;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001404 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001405 TriBool at_start() { return at_start_; }
1406 void set_at_start(bool at_start) { at_start_ = at_start ? TRUE : FALSE; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001407 Label* backtrack() { return backtrack_; }
1408 Label* loop_label() { return loop_label_; }
1409 RegExpNode* stop_node() { return stop_node_; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001410 int characters_preloaded() { return characters_preloaded_; }
1411 int bound_checked_up_to() { return bound_checked_up_to_; }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001412 int flush_budget() { return flush_budget_; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001413 QuickCheckDetails* quick_check_performed() { return &quick_check_performed_; }
1414 bool mentions_reg(int reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001415 // Returns true if a deferred position store exists to the specified
1416 // register and stores the offset in the out-parameter. Otherwise
1417 // returns false.
1418 bool GetStoredPosition(int reg, int* cp_offset);
1419 // These set methods and AdvanceCurrentPositionInTrace should be used only on
1420 // new traces - the intention is that traces are immutable after creation.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001421 void add_action(DeferredAction* new_action) {
1422 ASSERT(new_action->next_ == NULL);
1423 new_action->next_ = actions_;
1424 actions_ = new_action;
1425 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001426 void set_backtrack(Label* backtrack) { backtrack_ = backtrack; }
1427 void set_stop_node(RegExpNode* node) { stop_node_ = node; }
1428 void set_loop_label(Label* label) { loop_label_ = label; }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001429 void set_characters_preloaded(int count) { characters_preloaded_ = count; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001430 void set_bound_checked_up_to(int to) { bound_checked_up_to_ = to; }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001431 void set_flush_budget(int to) { flush_budget_ = to; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001432 void set_quick_check_performed(QuickCheckDetails* d) {
1433 quick_check_performed_ = *d;
1434 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001435 void InvalidateCurrentCharacter();
1436 void AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler);
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001437
ager@chromium.org8bb60582008-12-11 12:02:20 +00001438 private:
1439 int FindAffectedRegisters(OutSet* affected_registers);
1440 void PerformDeferredActions(RegExpMacroAssembler* macro,
1441 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001442 OutSet& affected_registers,
1443 OutSet* registers_to_pop,
1444 OutSet* registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001445 void RestoreAffectedRegisters(RegExpMacroAssembler* macro,
1446 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001447 OutSet& registers_to_pop,
1448 OutSet& registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001449 int cp_offset_;
1450 DeferredAction* actions_;
1451 Label* backtrack_;
1452 RegExpNode* stop_node_;
1453 Label* loop_label_;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001454 int characters_preloaded_;
1455 int bound_checked_up_to_;
1456 QuickCheckDetails quick_check_performed_;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001457 int flush_budget_;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001458 TriBool at_start_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001459};
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001460
1461
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001462class NodeVisitor {
1463 public:
1464 virtual ~NodeVisitor() { }
1465#define DECLARE_VISIT(Type) \
1466 virtual void Visit##Type(Type##Node* that) = 0;
1467FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1468#undef DECLARE_VISIT
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001469 virtual void VisitLoopChoice(LoopChoiceNode* that) { VisitChoice(that); }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001470};
1471
1472
1473// Node visitor used to add the start set of the alternatives to the
1474// dispatch table of a choice node.
1475class DispatchTableConstructor: public NodeVisitor {
1476 public:
1477 DispatchTableConstructor(DispatchTable* table, bool ignore_case)
1478 : table_(table),
1479 choice_index_(-1),
1480 ignore_case_(ignore_case) { }
1481
1482 void BuildTable(ChoiceNode* node);
1483
1484 void AddRange(CharacterRange range) {
1485 table()->AddRange(range, choice_index_);
1486 }
1487
1488 void AddInverse(ZoneList<CharacterRange>* ranges);
1489
1490#define DECLARE_VISIT(Type) \
1491 virtual void Visit##Type(Type##Node* that);
1492FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1493#undef DECLARE_VISIT
1494
1495 DispatchTable* table() { return table_; }
1496 void set_choice_index(int value) { choice_index_ = value; }
1497
1498 protected:
ager@chromium.org5ec48922009-05-05 07:25:34 +00001499 DispatchTable* table_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001500 int choice_index_;
1501 bool ignore_case_;
1502};
1503
1504
ager@chromium.org8bb60582008-12-11 12:02:20 +00001505// Assertion propagation moves information about assertions such as
1506// \b to the affected nodes. For instance, in /.\b./ information must
1507// be propagated to the first '.' that whatever follows needs to know
1508// if it matched a word or a non-word, and to the second '.' that it
1509// has to check if it succeeds a word or non-word. In this case the
1510// result will be something like:
1511//
1512// +-------+ +------------+
1513// | . | | . |
1514// +-------+ ---> +------------+
1515// | word? | | check word |
1516// +-------+ +------------+
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001517class Analysis: public NodeVisitor {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001518 public:
ager@chromium.org38e4c712009-11-11 09:11:58 +00001519 Analysis(bool ignore_case, bool is_ascii)
1520 : ignore_case_(ignore_case),
1521 is_ascii_(is_ascii),
1522 error_message_(NULL) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001523 void EnsureAnalyzed(RegExpNode* node);
1524
1525#define DECLARE_VISIT(Type) \
1526 virtual void Visit##Type(Type##Node* that);
1527FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1528#undef DECLARE_VISIT
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001529 virtual void VisitLoopChoice(LoopChoiceNode* that);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001530
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001531 bool has_failed() { return error_message_ != NULL; }
1532 const char* error_message() {
1533 ASSERT(error_message_ != NULL);
1534 return error_message_;
1535 }
1536 void fail(const char* error_message) {
1537 error_message_ = error_message;
1538 }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001539
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001540 private:
1541 bool ignore_case_;
ager@chromium.org38e4c712009-11-11 09:11:58 +00001542 bool is_ascii_;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001543 const char* error_message_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001544
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001545 DISALLOW_IMPLICIT_CONSTRUCTORS(Analysis);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001546};
1547
1548
ager@chromium.org8bb60582008-12-11 12:02:20 +00001549struct RegExpCompileData {
1550 RegExpCompileData()
1551 : tree(NULL),
1552 node(NULL),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001553 simple(true),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001554 contains_anchor(false),
ager@chromium.org8bb60582008-12-11 12:02:20 +00001555 capture_count(0) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001556 RegExpTree* tree;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001557 RegExpNode* node;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001558 bool simple;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001559 bool contains_anchor;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001560 Handle<String> error;
1561 int capture_count;
1562};
1563
1564
1565class RegExpEngine: public AllStatic {
1566 public:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001567 struct CompilationResult {
1568 explicit CompilationResult(const char* error_message)
1569 : error_message(error_message),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001570 code(HEAP->the_hole_value()),
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001571 num_registers(0) {}
1572 CompilationResult(Object* code, int registers)
1573 : error_message(NULL),
1574 code(code),
1575 num_registers(registers) {}
1576 const char* error_message;
1577 Object* code;
1578 int num_registers;
1579 };
1580
1581 static CompilationResult Compile(RegExpCompileData* input,
1582 bool ignore_case,
1583 bool multiline,
1584 Handle<String> pattern,
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001585 Handle<String> sample_subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001586 bool is_ascii);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001587
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001588 static void DotPrint(const char* label, RegExpNode* node, bool ignore_case);
1589};
1590
1591
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001592class OffsetsVector {
1593 public:
ulan@chromium.org812308e2012-02-29 15:58:45 +00001594 inline OffsetsVector(int num_registers, Isolate* isolate)
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001595 : offsets_vector_length_(num_registers) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001596 if (offsets_vector_length_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001597 vector_ = NewArray<int>(offsets_vector_length_);
1598 } else {
ulan@chromium.org812308e2012-02-29 15:58:45 +00001599 vector_ = isolate->jsregexp_static_offsets_vector();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001600 }
1601 }
1602 inline ~OffsetsVector() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001603 if (offsets_vector_length_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001604 DeleteArray(vector_);
1605 vector_ = NULL;
1606 }
1607 }
1608 inline int* vector() { return vector_; }
1609 inline int length() { return offsets_vector_length_; }
1610
1611 static const int kStaticOffsetsVectorSize = 50;
1612
1613 private:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001614 static Address static_offsets_vector_address(Isolate* isolate) {
1615 return reinterpret_cast<Address>(isolate->jsregexp_static_offsets_vector());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001616 }
1617
1618 int* vector_;
1619 int offsets_vector_length_;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001620
1621 friend class ExternalReference;
1622};
1623
1624
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001625} } // namespace v8::internal
1626
1627#endif // V8_JSREGEXP_H_