blob: 288e995dd19036cffd7cfa44a13a7da527ae2b55 [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;
ager@chromium.orga74f0da2008-12-03 16:05:52 +000043
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000044class RegExpImpl {
45 public:
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000046 // Whether V8 is compiled with native regexp support or not.
47 static bool UsesNativeRegExp() {
ricow@chromium.orgc9c80822010-04-21 08:22:37 +000048#ifdef V8_INTERPRETED_REGEXP
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000049 return false;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +000050#else
51 return true;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000052#endif
53 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000054
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000055 // Creates a regular expression literal in the old space.
56 // This function calls the garbage collector if necessary.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000057 static Handle<Object> CreateRegExpLiteral(Handle<JSFunction> constructor,
58 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000059 Handle<String> flags,
60 bool* has_pending_exception);
61
62 // Returns a string representation of a regular expression.
63 // Implements RegExp.prototype.toString, see ECMA-262 section 15.10.6.4.
64 // This function calls the garbage collector if necessary.
65 static Handle<String> ToString(Handle<Object> value);
66
ager@chromium.org8bb60582008-12-11 12:02:20 +000067 // Parses the RegExp pattern and prepares the JSRegExp object with
68 // generic data and choice of implementation - as well as what
69 // the implementation wants to store in the data field.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000070 // Returns false if compilation fails.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000071 static Handle<Object> Compile(Handle<JSRegExp> re,
72 Handle<String> pattern,
73 Handle<String> flags);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000074
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000075 // See ECMA-262 section 15.10.6.2.
76 // This function calls the garbage collector if necessary.
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000077 static Handle<Object> Exec(Handle<JSRegExp> regexp,
78 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000079 int index,
80 Handle<JSArray> lastMatchInfo);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081
ager@chromium.org8bb60582008-12-11 12:02:20 +000082 // Prepares a JSRegExp object with Irregexp-specific data.
whesse@chromium.orgcec079d2010-03-22 14:44:04 +000083 static void IrregexpInitialize(Handle<JSRegExp> re,
84 Handle<String> pattern,
85 JSRegExp::Flags flags,
86 int capture_register_count);
ager@chromium.orga74f0da2008-12-03 16:05:52 +000087
88
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000089 static void AtomCompile(Handle<JSRegExp> re,
90 Handle<String> pattern,
91 JSRegExp::Flags flags,
92 Handle<String> match_pattern);
93
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000094 static Handle<Object> AtomExec(Handle<JSRegExp> regexp,
95 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000096 int index,
97 Handle<JSArray> lastMatchInfo);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000098
whesse@chromium.orgcec079d2010-03-22 14:44:04 +000099 enum IrregexpResult { RE_FAILURE = 0, RE_SUCCESS = 1, RE_EXCEPTION = -1 };
100
101 // Prepare a RegExp for being executed one or more times (using
102 // IrregexpExecOnce) on the subject.
103 // This ensures that the regexp is compiled for the subject, and that
104 // the subject is flat.
105 // Returns the number of integer spaces required by IrregexpExecOnce
106 // as its "registers" argument. If the regexp cannot be compiled,
107 // an exception is set as pending, and this function returns negative.
108 static int IrregexpPrepare(Handle<JSRegExp> regexp,
109 Handle<String> subject);
110
111 // Execute a regular expression once on the subject, starting from
112 // character "index".
113 // If successful, returns RE_SUCCESS and set the capture positions
114 // in the first registers.
115 // If matching fails, returns RE_FAILURE.
116 // If execution fails, sets a pending exception and returns RE_EXCEPTION.
117 static IrregexpResult IrregexpExecOnce(Handle<JSRegExp> regexp,
118 Handle<String> subject,
119 int index,
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000120 Vector<int> registers);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000121
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000122 // Execute an Irregexp bytecode pattern.
ager@chromium.org41826e72009-03-30 13:30:57 +0000123 // On a successful match, the result is a JSArray containing
124 // captured positions. On a failure, the result is the null value.
125 // Returns an empty handle in case of an exception.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000126 static Handle<Object> IrregexpExec(Handle<JSRegExp> regexp,
127 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000128 int index,
129 Handle<JSArray> lastMatchInfo);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000130
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000131 // Array index in the lastMatchInfo array.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000132 static const int kLastCaptureCount = 0;
133 static const int kLastSubject = 1;
134 static const int kLastInput = 2;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000135 static const int kFirstCapture = 3;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000136 static const int kLastMatchOverhead = 3;
137
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000138 // Direct offset into the lastMatchInfo array.
139 static const int kLastCaptureCountOffset =
140 FixedArray::kHeaderSize + kLastCaptureCount * kPointerSize;
141 static const int kLastSubjectOffset =
142 FixedArray::kHeaderSize + kLastSubject * kPointerSize;
143 static const int kLastInputOffset =
144 FixedArray::kHeaderSize + kLastInput * kPointerSize;
145 static const int kFirstCaptureOffset =
146 FixedArray::kHeaderSize + kFirstCapture * kPointerSize;
147
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000148 // Used to access the lastMatchInfo array.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000149 static int GetCapture(FixedArray* array, int index) {
150 return Smi::cast(array->get(index + kFirstCapture))->value();
151 }
152
153 static void SetLastCaptureCount(FixedArray* array, int to) {
154 array->set(kLastCaptureCount, Smi::FromInt(to));
155 }
156
157 static void SetLastSubject(FixedArray* array, String* to) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000158 array->set(kLastSubject, to);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000159 }
160
161 static void SetLastInput(FixedArray* array, String* to) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000162 array->set(kLastInput, to);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000163 }
164
165 static void SetCapture(FixedArray* array, int index, int to) {
166 array->set(index + kFirstCapture, Smi::FromInt(to));
167 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000168
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000169 static int GetLastCaptureCount(FixedArray* array) {
170 return Smi::cast(array->get(kLastCaptureCount))->value();
171 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000172
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000173 // For acting on the JSRegExp data FixedArray.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000174 static int IrregexpMaxRegisterCount(FixedArray* re);
175 static void SetIrregexpMaxRegisterCount(FixedArray* re, int value);
176 static int IrregexpNumberOfCaptures(FixedArray* re);
177 static int IrregexpNumberOfRegisters(FixedArray* re);
178 static ByteArray* IrregexpByteCode(FixedArray* re, bool is_ascii);
179 static Code* IrregexpNativeCode(FixedArray* re, bool is_ascii);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000180
karlklose@chromium.org83a47282011-05-11 11:54:09 +0000181 // Limit the space regexps take up on the heap. In order to limit this we
182 // would like to keep track of the amount of regexp code on the heap. This
183 // is not tracked, however. As a conservative approximation we track the
184 // total regexp code compiled including code that has subsequently been freed
185 // and the total executable memory at any point.
186 static const int kRegExpExecutableMemoryLimit = 16 * MB;
187 static const int kRegWxpCompiledLimit = 1 * MB;
188
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000189 private:
190 static String* last_ascii_string_;
191 static String* two_byte_cached_string_;
192
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000193 static bool CompileIrregexp(
194 Handle<JSRegExp> re, Handle<String> sample_subject, bool is_ascii);
195 static inline bool EnsureCompiledIrregexp(
196 Handle<JSRegExp> re, Handle<String> sample_subject, bool is_ascii);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000197
198
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000199 // Set the subject cache. The previous string buffer is not deleted, so the
200 // caller should ensure that it doesn't leak.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000201 static void SetSubjectCache(String* subject,
202 char* utf8_subject,
203 int uft8_length,
204 int character_position,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000205 int utf8_position);
206
207 // A one element cache of the last utf8_subject string and its length. The
208 // subject JS String object is cached in the heap. We also cache a
209 // translation between position and utf8 position.
210 static char* utf8_subject_cache_;
211 static int utf8_length_cache_;
212 static int utf8_position_;
213 static int character_position_;
214};
215
216
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000217// Represents the location of one element relative to the intersection of
218// two sets. Corresponds to the four areas of a Venn diagram.
219enum ElementInSetsRelation {
220 kInsideNone = 0,
221 kInsideFirst = 1,
222 kInsideSecond = 2,
223 kInsideBoth = 3
224};
225
226
227// Represents the relation of two sets.
228// Sets can be either disjoint, partially or fully overlapping, or equal.
229class SetRelation BASE_EMBEDDED {
230 public:
231 // Relation is represented by a bit saying whether there are elements in
232 // one set that is not in the other, and a bit saying that there are elements
233 // that are in both sets.
234
235 // Location of an element. Corresponds to the internal areas of
236 // a Venn diagram.
237 enum {
238 kInFirst = 1 << kInsideFirst,
239 kInSecond = 1 << kInsideSecond,
240 kInBoth = 1 << kInsideBoth
241 };
242 SetRelation() : bits_(0) {}
243 ~SetRelation() {}
244 // Add the existence of objects in a particular
245 void SetElementsInFirstSet() { bits_ |= kInFirst; }
246 void SetElementsInSecondSet() { bits_ |= kInSecond; }
247 void SetElementsInBothSets() { bits_ |= kInBoth; }
248 // Check the currently known relation of the sets (common functions only,
249 // for other combinations, use value() to get the bits and check them
250 // manually).
251 // Sets are completely disjoint.
252 bool Disjoint() { return (bits_ & kInBoth) == 0; }
253 // Sets are equal.
254 bool Equals() { return (bits_ & (kInFirst | kInSecond)) == 0; }
255 // First set contains second.
256 bool Contains() { return (bits_ & kInSecond) == 0; }
257 // Second set contains first.
258 bool ContainedIn() { return (bits_ & kInFirst) == 0; }
259 bool NonTrivialIntersection() {
260 return (bits_ == (kInFirst | kInSecond | kInBoth));
261 }
262 int value() { return bits_; }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000263
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000264 private:
265 int bits_;
266};
267
268
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000269class CharacterRange {
270 public:
271 CharacterRange() : from_(0), to_(0) { }
272 // For compatibility with the CHECK_OK macro
273 CharacterRange(void* null) { ASSERT_EQ(NULL, null); } //NOLINT
274 CharacterRange(uc16 from, uc16 to) : from_(from), to_(to) { }
275 static void AddClassEscape(uc16 type, ZoneList<CharacterRange>* ranges);
276 static Vector<const uc16> GetWordBounds();
277 static inline CharacterRange Singleton(uc16 value) {
278 return CharacterRange(value, value);
279 }
280 static inline CharacterRange Range(uc16 from, uc16 to) {
281 ASSERT(from <= to);
282 return CharacterRange(from, to);
283 }
284 static inline CharacterRange Everything() {
285 return CharacterRange(0, 0xFFFF);
286 }
287 bool Contains(uc16 i) { return from_ <= i && i <= to_; }
288 uc16 from() const { return from_; }
289 void set_from(uc16 value) { from_ = value; }
290 uc16 to() const { return to_; }
291 void set_to(uc16 value) { to_ = value; }
292 bool is_valid() { return from_ <= to_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000293 bool IsEverything(uc16 max) { return from_ == 0 && to_ >= max; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000294 bool IsSingleton() { return (from_ == to_); }
ager@chromium.org38e4c712009-11-11 09:11:58 +0000295 void AddCaseEquivalents(ZoneList<CharacterRange>* ranges, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000296 static void Split(ZoneList<CharacterRange>* base,
297 Vector<const uc16> overlay,
298 ZoneList<CharacterRange>** included,
299 ZoneList<CharacterRange>** excluded);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000300 // Whether a range list is in canonical form: Ranges ordered by from value,
301 // and ranges non-overlapping and non-adjacent.
302 static bool IsCanonical(ZoneList<CharacterRange>* ranges);
303 // Convert range list to canonical form. The characters covered by the ranges
304 // will still be the same, but no character is in more than one range, and
305 // adjacent ranges are merged. The resulting list may be shorter than the
306 // original, but cannot be longer.
307 static void Canonicalize(ZoneList<CharacterRange>* ranges);
308 // Check how the set of characters defined by a CharacterRange list relates
309 // to the set of word characters. List must be in canonical form.
310 static SetRelation WordCharacterRelation(ZoneList<CharacterRange>* ranges);
311 // Takes two character range lists (representing character sets) in canonical
312 // form and merges them.
313 // The characters that are only covered by the first set are added to
314 // first_set_only_out. the characters that are only in the second set are
315 // added to second_set_only_out, and the characters that are in both are
316 // added to both_sets_out.
317 // The pointers to first_set_only_out, second_set_only_out and both_sets_out
318 // should be to empty lists, but they need not be distinct, and may be NULL.
319 // If NULL, the characters are dropped, and if two arguments are the same
320 // pointer, the result is the union of the two sets that would be created
321 // if the pointers had been distinct.
322 // This way, the Merge function can compute all the usual set operations:
323 // union (all three out-sets are equal), intersection (only both_sets_out is
324 // non-NULL), and set difference (only first_set is non-NULL).
325 static void Merge(ZoneList<CharacterRange>* first_set,
326 ZoneList<CharacterRange>* second_set,
327 ZoneList<CharacterRange>* first_set_only_out,
328 ZoneList<CharacterRange>* second_set_only_out,
329 ZoneList<CharacterRange>* both_sets_out);
330 // Negate the contents of a character range in canonical form.
331 static void Negate(ZoneList<CharacterRange>* src,
332 ZoneList<CharacterRange>* dst);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000333 static const int kStartMarker = (1 << 24);
334 static const int kPayloadMask = (1 << 24) - 1;
335
336 private:
337 uc16 from_;
338 uc16 to_;
339};
340
341
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000342// A set of unsigned integers that behaves especially well on small
343// integers (< 32). May do zone-allocation.
344class OutSet: public ZoneObject {
345 public:
346 OutSet() : first_(0), remaining_(NULL), successors_(NULL) { }
347 OutSet* Extend(unsigned value);
348 bool Get(unsigned value);
349 static const unsigned kFirstLimit = 32;
350
351 private:
352 // Destructively set a value in this set. In most cases you want
353 // to use Extend instead to ensure that only one instance exists
354 // that contains the same values.
355 void Set(unsigned value);
356
357 // The successors are a list of sets that contain the same values
358 // as this set and the one more value that is not present in this
359 // set.
360 ZoneList<OutSet*>* successors() { return successors_; }
361
362 OutSet(uint32_t first, ZoneList<unsigned>* remaining)
363 : first_(first), remaining_(remaining), successors_(NULL) { }
364 uint32_t first_;
365 ZoneList<unsigned>* remaining_;
366 ZoneList<OutSet*>* successors_;
ager@chromium.org32912102009-01-16 10:38:43 +0000367 friend class Trace;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000368};
369
370
371// A mapping from integers, specified as ranges, to a set of integers.
372// Used for mapping character ranges to choices.
373class DispatchTable : public ZoneObject {
374 public:
375 class Entry {
376 public:
377 Entry() : from_(0), to_(0), out_set_(NULL) { }
378 Entry(uc16 from, uc16 to, OutSet* out_set)
379 : from_(from), to_(to), out_set_(out_set) { }
380 uc16 from() { return from_; }
381 uc16 to() { return to_; }
382 void set_to(uc16 value) { to_ = value; }
383 void AddValue(int value) { out_set_ = out_set_->Extend(value); }
384 OutSet* out_set() { return out_set_; }
385 private:
386 uc16 from_;
387 uc16 to_;
388 OutSet* out_set_;
389 };
390
391 class Config {
392 public:
393 typedef uc16 Key;
394 typedef Entry Value;
395 static const uc16 kNoKey;
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +0000396 static const Entry NoValue() { return Value(); }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000397 static inline int Compare(uc16 a, uc16 b) {
398 if (a == b)
399 return 0;
400 else if (a < b)
401 return -1;
402 else
403 return 1;
404 }
405 };
406
407 void AddRange(CharacterRange range, int value);
408 OutSet* Get(uc16 value);
409 void Dump();
410
411 template <typename Callback>
412 void ForEach(Callback* callback) { return tree()->ForEach(callback); }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000413
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000414 private:
415 // There can't be a static empty set since it allocates its
416 // successors in a zone and caches them.
417 OutSet* empty() { return &empty_; }
418 OutSet empty_;
419 ZoneSplayTree<Config>* tree() { return &tree_; }
420 ZoneSplayTree<Config> tree_;
421};
422
423
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000424// Improve the speed that we scan for an initial point where a non-anchored
425// regexp can match by using a Boyer-Moore-like table. This is done by
426// identifying non-greedy non-capturing loops in the nodes that eat any
427// character one at a time. For example in the middle of the regexp
428// /foo[\s\S]*?bar/ we find such a loop. There is also such a loop implicitly
429// inserted at the start of any non-anchored regexp.
430//
431// When we have found such a loop we look ahead in the nodes to find the set of
432// characters that can come at given distances. For example for the regexp
433// /.?foo/ we know that there are at least 3 characters ahead of us, and the
434// sets of characters that can occur are [any, [f, o], [o]]. We find a range in
435// the lookahead info where the set of characters is reasonably constrained. In
436// our example this is from index 1 to 2 (0 is not constrained). We can now
437// look 3 characters ahead and if we don't find one of [f, o] (the union of
438// [f, o] and [o]) then we can skip forwards by the range size (in this case 2).
439//
440// For Unicode input strings we do the same, but modulo 128.
441//
442// We also look at the first string fed to the regexp and use that to get a hint
443// of the character frequencies in the inputs. This affects the assessment of
444// whether the set of characters is 'reasonably constrained'.
445//
446// We also have another lookahead mechanism (called quick check in the code),
447// which uses a wide load of multiple characters followed by a mask and compare
448// to determine whether a match is possible at this point.
449class BoyerMooreLookahead {
450 public:
451 BoyerMooreLookahead(int length, int map_length, RegExpCompiler* compiler);
452
453 int length() { return length_; }
454 int max_char() { return max_char_; }
455 RegExpCompiler* compiler() { return compiler_; }
456
457 static const int kTooManyCharacters = 32;
458
459 int Count(int map_number) {
460 ZoneList<bool>* map = bitmaps_->at(map_number);
461 if (map == NULL) return map_length_;
462 int count = 0;
463 for (int i = 0; i < map_length_; i++) {
464 if (map->at(i)) count++;
465 }
466 return count;
467 }
468
469 void Set(int map_number, int character) {
470 if (character > max_char_) return;
471 ZoneList<bool>* map = bitmaps_->at(map_number);
472 if (map == NULL) return;
473 map->at(character & (map_length_ - 1)) = true;
474 }
475
476 void SetAll(int map_number) {
477 bitmaps_->at(map_number) = NULL;
478 }
479
480 void SetRest(int from_map) {
481 for (int i = from_map; i < length_; i++) SetAll(i);
482 }
483 bool EmitSkipInstructions(RegExpMacroAssembler* masm);
484
485 private:
486 // This is the value obtained by EatsAtLeast. If we do not have at least this
487 // many characters left in the sample string then the match is bound to fail.
488 // Therefore it is OK to read a character this far ahead of the current match
489 // point.
490 int length_;
491 // We conservatively consider all character values modulo this length. For
492 // ASCII there is no loss of precision, since this has a value of 128.
493 int map_length_;
494 RegExpCompiler* compiler_;
495 // 0x7f for ASCII, 0xffff for UTF-16.
496 int max_char_;
497 ZoneList<ZoneList<bool>*>* bitmaps_;
498
499 int GetSkipTable(int min_lookahead,
500 int max_lookahead,
501 Handle<ByteArray> boolean_skip_table);
502 bool FindWorthwhileInterval(int* from, int* to);
503 int FindBestInterval(
504 int max_number_of_chars, int old_biggest_points, int* from, int* to);
505};
506
507
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000508#define FOR_EACH_NODE_TYPE(VISIT) \
509 VISIT(End) \
510 VISIT(Action) \
511 VISIT(Choice) \
512 VISIT(BackReference) \
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000513 VISIT(Assertion) \
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000514 VISIT(Text)
515
516
517#define FOR_EACH_REG_EXP_TREE_TYPE(VISIT) \
518 VISIT(Disjunction) \
519 VISIT(Alternative) \
520 VISIT(Assertion) \
521 VISIT(CharacterClass) \
522 VISIT(Atom) \
523 VISIT(Quantifier) \
524 VISIT(Capture) \
525 VISIT(Lookahead) \
526 VISIT(BackReference) \
527 VISIT(Empty) \
528 VISIT(Text)
529
530
531#define FORWARD_DECLARE(Name) class RegExp##Name;
532FOR_EACH_REG_EXP_TREE_TYPE(FORWARD_DECLARE)
533#undef FORWARD_DECLARE
534
535
536class TextElement {
537 public:
538 enum Type {UNINITIALIZED, ATOM, CHAR_CLASS};
539 TextElement() : type(UNINITIALIZED) { }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000540 explicit TextElement(Type t) : type(t), cp_offset(-1) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000541 static TextElement Atom(RegExpAtom* atom);
542 static TextElement CharClass(RegExpCharacterClass* char_class);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000543 int length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000544 Type type;
545 union {
546 RegExpAtom* u_atom;
547 RegExpCharacterClass* u_char_class;
548 } data;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000549 int cp_offset;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000550};
551
552
ager@chromium.org32912102009-01-16 10:38:43 +0000553class Trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000554
555
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000556struct NodeInfo {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000557 NodeInfo()
558 : being_analyzed(false),
559 been_analyzed(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000560 follows_word_interest(false),
561 follows_newline_interest(false),
562 follows_start_interest(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000563 at_end(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000564 visited(false) { }
565
566 // Returns true if the interests and assumptions of this node
567 // matches the given one.
568 bool Matches(NodeInfo* that) {
569 return (at_end == that->at_end) &&
570 (follows_word_interest == that->follows_word_interest) &&
571 (follows_newline_interest == that->follows_newline_interest) &&
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000572 (follows_start_interest == that->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000573 }
574
575 // Updates the interests of this node given the interests of the
576 // node preceding it.
577 void AddFromPreceding(NodeInfo* that) {
578 at_end |= that->at_end;
579 follows_word_interest |= that->follows_word_interest;
580 follows_newline_interest |= that->follows_newline_interest;
581 follows_start_interest |= that->follows_start_interest;
582 }
583
ager@chromium.org8bb60582008-12-11 12:02:20 +0000584 bool HasLookbehind() {
585 return follows_word_interest ||
586 follows_newline_interest ||
587 follows_start_interest;
588 }
589
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000590 // Sets the interests of this node to include the interests of the
591 // following node.
592 void AddFromFollowing(NodeInfo* that) {
593 follows_word_interest |= that->follows_word_interest;
594 follows_newline_interest |= that->follows_newline_interest;
595 follows_start_interest |= that->follows_start_interest;
596 }
597
598 void ResetCompilationState() {
599 being_analyzed = false;
600 been_analyzed = false;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000601 }
602
603 bool being_analyzed: 1;
604 bool been_analyzed: 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000605
606 // These bits are set of this node has to know what the preceding
607 // character was.
608 bool follows_word_interest: 1;
609 bool follows_newline_interest: 1;
610 bool follows_start_interest: 1;
611
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000612 bool at_end: 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000613 bool visited: 1;
614};
615
616
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000617class SiblingList {
618 public:
619 SiblingList() : list_(NULL) { }
620 int length() {
621 return list_ == NULL ? 0 : list_->length();
622 }
623 void Ensure(RegExpNode* parent) {
624 if (list_ == NULL) {
625 list_ = new ZoneList<RegExpNode*>(2);
626 list_->Add(parent);
627 }
628 }
629 void Add(RegExpNode* node) { list_->Add(node); }
630 RegExpNode* Get(int index) { return list_->at(index); }
631 private:
632 ZoneList<RegExpNode*>* list_;
633};
634
635
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000636// Details of a quick mask-compare check that can look ahead in the
637// input stream.
638class QuickCheckDetails {
639 public:
640 QuickCheckDetails()
641 : characters_(0),
642 mask_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000643 value_(0),
644 cannot_match_(false) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000645 explicit QuickCheckDetails(int characters)
646 : characters_(characters),
647 mask_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +0000648 value_(0),
649 cannot_match_(false) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000650 bool Rationalize(bool ascii);
651 // Merge in the information from another branch of an alternation.
652 void Merge(QuickCheckDetails* other, int from_index);
653 // Advance the current position by some amount.
654 void Advance(int by, bool ascii);
655 void Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000656 bool cannot_match() { return cannot_match_; }
657 void set_cannot_match() { cannot_match_ = true; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000658 struct Position {
659 Position() : mask(0), value(0), determines_perfectly(false) { }
660 uc16 mask;
661 uc16 value;
662 bool determines_perfectly;
663 };
664 int characters() { return characters_; }
665 void set_characters(int characters) { characters_ = characters; }
666 Position* positions(int index) {
667 ASSERT(index >= 0);
668 ASSERT(index < characters_);
669 return positions_ + index;
670 }
671 uint32_t mask() { return mask_; }
672 uint32_t value() { return value_; }
673
674 private:
675 // How many characters do we have quick check information from. This is
676 // the same for all branches of a choice node.
677 int characters_;
678 Position positions_[4];
679 // These values are the condensate of the above array after Rationalize().
680 uint32_t mask_;
681 uint32_t value_;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000682 // If set to true, there is no way this quick check can match at all.
683 // E.g., if it requires to be at the start of the input, and isn't.
684 bool cannot_match_;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000685};
686
687
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000688class RegExpNode: public ZoneObject {
689 public:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000690 RegExpNode() : first_character_set_(NULL), trace_count_(0) { }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000691 virtual ~RegExpNode();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000692 virtual void Accept(NodeVisitor* visitor) = 0;
693 // Generates a goto to this node or actually generates the code at this point.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000694 virtual void Emit(RegExpCompiler* compiler, Trace* trace) = 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000695 // How many characters must this node consume at a minimum in order to
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000696 // succeed. If we have found at least 'still_to_find' characters that
697 // must be consumed there is no need to ask any following nodes whether
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000698 // they are sure to eat any more characters. The not_at_start argument is
699 // used to indicate that we know we are not at the start of the input. In
700 // this case anchored branches will always fail and can be ignored when
701 // determining how many characters are consumed on success.
702 virtual int EatsAtLeast(int still_to_find,
703 int recursion_depth,
704 bool not_at_start) = 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000705 // Emits some quick code that checks whether the preloaded characters match.
706 // Falls through on certain failure, jumps to the label on possible success.
707 // If the node cannot make a quick check it does nothing and returns false.
708 bool EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +0000709 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000710 bool preload_has_checked_bounds,
711 Label* on_possible_success,
712 QuickCheckDetails* details_return,
713 bool fall_through_on_failure);
714 // For a given number of characters this returns a mask and a value. The
715 // next n characters are anded with the mask and compared with the value.
716 // A comparison failure indicates the node cannot match the next n characters.
717 // A comparison success indicates the node may match.
718 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
719 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000720 int characters_filled_in,
721 bool not_at_start) = 0;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000722 static const int kNodeIsTooComplexForGreedyLoops = -1;
723 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000724 // Only returns the successor for a text node of length 1 that matches any
725 // character and that has no guards on it.
726 virtual RegExpNode* GetSuccessorOfOmnivorousTextNode(
727 RegExpCompiler* compiler) {
728 return NULL;
729 }
730
731 // Collects information on the possible code units (mod 128) that can match if
732 // we look forward. This is used for a Boyer-Moore-like string searching
733 // implementation. TODO(erikcorry): This should share more code with
734 // EatsAtLeast, GetQuickCheckDetails and ComputeFirstCharacterSet.
735 virtual void FillInBMInfo(
736 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
737 UNREACHABLE();
738 }
739
ager@chromium.org8bb60582008-12-11 12:02:20 +0000740 Label* label() { return &label_; }
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000741 // 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 +0000742 // start of the trace) then it cannot be reused. This variable sets a limit
743 // on how often we allow that to happen before we insist on starting a new
744 // trace and generating generic code for a node that can be reused by flushing
745 // the deferred actions in the current trace and generating a goto.
746 static const int kMaxCopiesCodeGenerated = 10;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000747
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000748 NodeInfo* info() { return &info_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000749
750 void AddSibling(RegExpNode* node) { siblings_.Add(node); }
751
752 // Static version of EnsureSibling that expresses the fact that the
753 // result has the same type as the input.
754 template <class C>
755 static C* EnsureSibling(C* node, NodeInfo* info, bool* cloned) {
756 return static_cast<C*>(node->EnsureSibling(info, cloned));
757 }
758
759 SiblingList* siblings() { return &siblings_; }
760 void set_siblings(SiblingList* other) { siblings_ = *other; }
761
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000762 // Return the set of possible next characters recognized by the regexp
763 // (or a safe subset, potentially the set of all characters).
764 ZoneList<CharacterRange>* FirstCharacterSet();
765
766 // Compute (if possible within the budget of traversed nodes) the
767 // possible first characters of the input matched by this node and
768 // its continuation. Returns the remaining budget after the computation.
769 // If the budget is spent, the result is negative, and the cached
770 // first_character_set_ value isn't set.
771 virtual int ComputeFirstCharacterSet(int budget);
772
773 // Get and set the cached first character set value.
774 ZoneList<CharacterRange>* first_character_set() {
775 return first_character_set_;
776 }
777 void set_first_character_set(ZoneList<CharacterRange>* character_set) {
778 first_character_set_ = character_set;
779 }
780
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000781 protected:
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000782 enum LimitResult { DONE, CONTINUE };
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000783 static const int kComputeFirstCharacterSetFail = -1;
784
ager@chromium.org32912102009-01-16 10:38:43 +0000785 LimitResult LimitVersions(RegExpCompiler* compiler, Trace* trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000786
787 // Returns a sibling of this node whose interests and assumptions
788 // match the ones in the given node info. If no sibling exists NULL
789 // is returned.
790 RegExpNode* TryGetSibling(NodeInfo* info);
791
792 // Returns a sibling of this node whose interests match the ones in
793 // the given node info. The info must not contain any assertions.
794 // If no node exists a new one will be created by cloning the current
795 // node. The result will always be an instance of the same concrete
796 // class as this node.
797 RegExpNode* EnsureSibling(NodeInfo* info, bool* cloned);
798
799 // Returns a clone of this node initialized using the copy constructor
800 // of its concrete class. Note that the node may have to be pre-
ager@chromium.org32912102009-01-16 10:38:43 +0000801 // processed before it is on a usable state.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000802 virtual RegExpNode* Clone() = 0;
803
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000804 private:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000805 static const int kFirstCharBudget = 10;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000806 Label label_;
807 NodeInfo info_;
808 SiblingList siblings_;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000809 ZoneList<CharacterRange>* first_character_set_;
ager@chromium.org32912102009-01-16 10:38:43 +0000810 // This variable keeps track of how many times code has been generated for
811 // this node (in different traces). We don't keep track of where the
812 // generated code is located unless the code is generated at the start of
813 // a trace, in which case it is generic and can be reused by flushing the
814 // deferred operations in the current trace and generating a goto.
815 int trace_count_;
816};
817
818
819// A simple closed interval.
820class Interval {
821 public:
822 Interval() : from_(kNone), to_(kNone) { }
823 Interval(int from, int to) : from_(from), to_(to) { }
824 Interval Union(Interval that) {
825 if (that.from_ == kNone)
826 return *this;
827 else if (from_ == kNone)
828 return that;
829 else
830 return Interval(Min(from_, that.from_), Max(to_, that.to_));
831 }
832 bool Contains(int value) {
833 return (from_ <= value) && (value <= to_);
834 }
835 bool is_empty() { return from_ == kNone; }
836 int from() { return from_; }
837 int to() { return to_; }
838 static Interval Empty() { return Interval(); }
839 static const int kNone = -1;
840 private:
841 int from_;
842 int to_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000843};
844
845
846class SeqRegExpNode: public RegExpNode {
847 public:
848 explicit SeqRegExpNode(RegExpNode* on_success)
849 : on_success_(on_success) { }
850 RegExpNode* on_success() { return on_success_; }
851 void set_on_success(RegExpNode* node) { on_success_ = node; }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000852 virtual void FillInBMInfo(
853 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
854 on_success_->FillInBMInfo(offset, bm, not_at_start);
855 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000856 private:
857 RegExpNode* on_success_;
858};
859
860
861class ActionNode: public SeqRegExpNode {
862 public:
863 enum Type {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000864 SET_REGISTER,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000865 INCREMENT_REGISTER,
866 STORE_POSITION,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000867 BEGIN_SUBMATCH,
ager@chromium.org32912102009-01-16 10:38:43 +0000868 POSITIVE_SUBMATCH_SUCCESS,
869 EMPTY_MATCH_CHECK,
870 CLEAR_CAPTURES
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000871 };
ager@chromium.org8bb60582008-12-11 12:02:20 +0000872 static ActionNode* SetRegister(int reg, int val, RegExpNode* on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000873 static ActionNode* IncrementRegister(int reg, RegExpNode* on_success);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000874 static ActionNode* StorePosition(int reg,
875 bool is_capture,
876 RegExpNode* on_success);
ager@chromium.org32912102009-01-16 10:38:43 +0000877 static ActionNode* ClearCaptures(Interval range, RegExpNode* on_success);
878 static ActionNode* BeginSubmatch(int stack_pointer_reg,
879 int position_reg,
880 RegExpNode* on_success);
881 static ActionNode* PositiveSubmatchSuccess(int stack_pointer_reg,
882 int restore_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000883 int clear_capture_count,
884 int clear_capture_from,
ager@chromium.org32912102009-01-16 10:38:43 +0000885 RegExpNode* on_success);
886 static ActionNode* EmptyMatchCheck(int start_register,
887 int repetition_register,
888 int repetition_limit,
889 RegExpNode* on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000890 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000891 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000892 virtual int EatsAtLeast(int still_to_find,
893 int recursion_depth,
894 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000895 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
896 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000897 int filled_in,
898 bool not_at_start) {
899 return on_success()->GetQuickCheckDetails(
900 details, compiler, filled_in, not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000901 }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000902 virtual void FillInBMInfo(
903 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000904 Type type() { return type_; }
905 // TODO(erikcorry): We should allow some action nodes in greedy loops.
906 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000907 virtual ActionNode* Clone() { return new ActionNode(*this); }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000908 virtual int ComputeFirstCharacterSet(int budget);
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000909
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000910 private:
911 union {
912 struct {
913 int reg;
914 int value;
915 } u_store_register;
916 struct {
917 int reg;
918 } u_increment_register;
919 struct {
920 int reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000921 bool is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000922 } u_position_register;
923 struct {
924 int stack_pointer_register;
925 int current_position_register;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000926 int clear_register_count;
927 int clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000928 } u_submatch;
ager@chromium.org32912102009-01-16 10:38:43 +0000929 struct {
930 int start_register;
931 int repetition_register;
932 int repetition_limit;
933 } u_empty_match_check;
934 struct {
935 int range_from;
936 int range_to;
937 } u_clear_captures;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000938 } data_;
939 ActionNode(Type type, RegExpNode* on_success)
940 : SeqRegExpNode(on_success),
941 type_(type) { }
942 Type type_;
943 friend class DotPrinter;
944};
945
946
947class TextNode: public SeqRegExpNode {
948 public:
949 TextNode(ZoneList<TextElement>* elms,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000950 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000951 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000952 elms_(elms) { }
953 TextNode(RegExpCharacterClass* that,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000954 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000955 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000956 elms_(new ZoneList<TextElement>(1)) {
957 elms_->Add(TextElement::CharClass(that));
958 }
959 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000960 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000961 virtual int EatsAtLeast(int still_to_find,
962 int recursion_depth,
963 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000964 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
965 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +0000966 int characters_filled_in,
967 bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000968 ZoneList<TextElement>* elements() { return elms_; }
ager@chromium.org38e4c712009-11-11 09:11:58 +0000969 void MakeCaseIndependent(bool is_ascii);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000970 virtual int GreedyLoopTextLength();
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000971 virtual RegExpNode* GetSuccessorOfOmnivorousTextNode(
972 RegExpCompiler* compiler);
973 virtual void FillInBMInfo(
974 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000975 virtual TextNode* Clone() {
976 TextNode* result = new TextNode(*this);
977 result->CalculateOffsets();
978 return result;
979 }
980 void CalculateOffsets();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000981 virtual int ComputeFirstCharacterSet(int budget);
kmillikin@chromium.org83e16822011-09-13 08:21:47 +0000982
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000983 private:
984 enum TextEmitPassType {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000985 NON_ASCII_MATCH, // Check for characters that can't match.
986 SIMPLE_CHARACTER_MATCH, // Case-dependent single character check.
987 NON_LETTER_CHARACTER_MATCH, // Check characters that have no case equivs.
988 CASE_CHARACTER_MATCH, // Case-independent single character check.
989 CHARACTER_CLASS_MATCH // Character class.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000990 };
ager@chromium.org381abbb2009-02-25 13:23:22 +0000991 static bool SkipPass(int pass, bool ignore_case);
992 static const int kFirstRealPass = SIMPLE_CHARACTER_MATCH;
993 static const int kLastPass = CHARACTER_CLASS_MATCH;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000994 void TextEmitPass(RegExpCompiler* compiler,
995 TextEmitPassType pass,
996 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +0000997 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000998 bool first_element_checked,
999 int* checked_up_to);
1000 int Length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001001 ZoneList<TextElement>* elms_;
1002};
1003
1004
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001005class AssertionNode: public SeqRegExpNode {
1006 public:
1007 enum AssertionNodeType {
1008 AT_END,
1009 AT_START,
1010 AT_BOUNDARY,
1011 AT_NON_BOUNDARY,
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001012 AFTER_NEWLINE,
1013 // Types not directly expressible in regexp syntax.
1014 // Used for modifying a boundary node if its following character is
1015 // known to be word and/or non-word.
1016 AFTER_NONWORD_CHARACTER,
1017 AFTER_WORD_CHARACTER
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001018 };
1019 static AssertionNode* AtEnd(RegExpNode* on_success) {
1020 return new AssertionNode(AT_END, on_success);
1021 }
1022 static AssertionNode* AtStart(RegExpNode* on_success) {
1023 return new AssertionNode(AT_START, on_success);
1024 }
1025 static AssertionNode* AtBoundary(RegExpNode* on_success) {
1026 return new AssertionNode(AT_BOUNDARY, on_success);
1027 }
1028 static AssertionNode* AtNonBoundary(RegExpNode* on_success) {
1029 return new AssertionNode(AT_NON_BOUNDARY, on_success);
1030 }
1031 static AssertionNode* AfterNewline(RegExpNode* on_success) {
1032 return new AssertionNode(AFTER_NEWLINE, on_success);
1033 }
1034 virtual void Accept(NodeVisitor* visitor);
1035 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001036 virtual int EatsAtLeast(int still_to_find,
1037 int recursion_depth,
1038 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001039 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1040 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001041 int filled_in,
1042 bool not_at_start);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001043 virtual void FillInBMInfo(
1044 int offset, BoyerMooreLookahead* bm, bool not_at_start);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001045 virtual int ComputeFirstCharacterSet(int budget);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001046 virtual AssertionNode* Clone() { return new AssertionNode(*this); }
1047 AssertionNodeType type() { return type_; }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001048 void set_type(AssertionNodeType type) { type_ = type; }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001049
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001050 private:
1051 AssertionNode(AssertionNodeType t, RegExpNode* on_success)
1052 : SeqRegExpNode(on_success), type_(t) { }
1053 AssertionNodeType type_;
1054};
1055
1056
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001057class BackReferenceNode: public SeqRegExpNode {
1058 public:
1059 BackReferenceNode(int start_reg,
1060 int end_reg,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001061 RegExpNode* on_success)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001062 : SeqRegExpNode(on_success),
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001063 start_reg_(start_reg),
1064 end_reg_(end_reg) { }
1065 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001066 int start_register() { return start_reg_; }
1067 int end_register() { return end_reg_; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001068 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001069 virtual int EatsAtLeast(int still_to_find,
1070 int recursion_depth,
1071 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001072 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1073 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001074 int characters_filled_in,
1075 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001076 return;
1077 }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001078 virtual void FillInBMInfo(
1079 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
1080 // Working out the set of characters that a backreference can match is too
1081 // hard, so we just say that any character can match.
1082 bm->SetRest(offset);
1083 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001084 virtual BackReferenceNode* Clone() { return new BackReferenceNode(*this); }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001085 virtual int ComputeFirstCharacterSet(int budget);
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001086
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001087 private:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001088 int start_reg_;
1089 int end_reg_;
1090};
1091
1092
1093class EndNode: public RegExpNode {
1094 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +00001095 enum Action { ACCEPT, BACKTRACK, NEGATIVE_SUBMATCH_SUCCESS };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001096 explicit EndNode(Action action) : action_(action) { }
1097 virtual void Accept(NodeVisitor* visitor);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001098 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001099 virtual int EatsAtLeast(int still_to_find,
1100 int recursion_depth,
1101 bool not_at_start) { return 0; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001102 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1103 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001104 int characters_filled_in,
1105 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001106 // Returning 0 from EatsAtLeast should ensure we never get here.
1107 UNREACHABLE();
1108 }
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001109 virtual void FillInBMInfo(
1110 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
1111 // Returning 0 from EatsAtLeast should ensure we never get here.
1112 UNREACHABLE();
1113 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001114 virtual EndNode* Clone() { return new EndNode(*this); }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001115 private:
1116 Action action_;
1117};
1118
1119
ager@chromium.org8bb60582008-12-11 12:02:20 +00001120class NegativeSubmatchSuccess: public EndNode {
1121 public:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001122 NegativeSubmatchSuccess(int stack_pointer_reg,
1123 int position_reg,
1124 int clear_capture_count,
1125 int clear_capture_start)
ager@chromium.org8bb60582008-12-11 12:02:20 +00001126 : EndNode(NEGATIVE_SUBMATCH_SUCCESS),
1127 stack_pointer_register_(stack_pointer_reg),
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001128 current_position_register_(position_reg),
1129 clear_capture_count_(clear_capture_count),
1130 clear_capture_start_(clear_capture_start) { }
1131 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001132
1133 private:
1134 int stack_pointer_register_;
1135 int current_position_register_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001136 int clear_capture_count_;
1137 int clear_capture_start_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001138};
1139
1140
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001141class Guard: public ZoneObject {
1142 public:
1143 enum Relation { LT, GEQ };
1144 Guard(int reg, Relation op, int value)
1145 : reg_(reg),
1146 op_(op),
1147 value_(value) { }
1148 int reg() { return reg_; }
1149 Relation op() { return op_; }
1150 int value() { return value_; }
1151
1152 private:
1153 int reg_;
1154 Relation op_;
1155 int value_;
1156};
1157
1158
1159class GuardedAlternative {
1160 public:
1161 explicit GuardedAlternative(RegExpNode* node) : node_(node), guards_(NULL) { }
1162 void AddGuard(Guard* guard);
1163 RegExpNode* node() { return node_; }
1164 void set_node(RegExpNode* node) { node_ = node; }
1165 ZoneList<Guard*>* guards() { return guards_; }
1166
1167 private:
1168 RegExpNode* node_;
1169 ZoneList<Guard*>* guards_;
1170};
1171
1172
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001173class AlternativeGeneration;
1174
1175
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001176class ChoiceNode: public RegExpNode {
1177 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +00001178 explicit ChoiceNode(int expected_size)
1179 : alternatives_(new ZoneList<GuardedAlternative>(expected_size)),
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001180 table_(NULL),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001181 not_at_start_(false),
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001182 being_calculated_(false) { }
1183 virtual void Accept(NodeVisitor* visitor);
1184 void AddAlternative(GuardedAlternative node) { alternatives()->Add(node); }
1185 ZoneList<GuardedAlternative>* alternatives() { return alternatives_; }
1186 DispatchTable* GetTable(bool ignore_case);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001187 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001188 virtual int EatsAtLeast(int still_to_find,
1189 int recursion_depth,
1190 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001191 int EatsAtLeastHelper(int still_to_find,
1192 int recursion_depth,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001193 RegExpNode* ignore_this_node,
1194 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001195 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1196 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001197 int characters_filled_in,
1198 bool not_at_start);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001199 virtual void FillInBMInfo(
1200 int offset, BoyerMooreLookahead* bm, bool not_at_start);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001201 virtual ChoiceNode* Clone() { return new ChoiceNode(*this); }
1202
1203 bool being_calculated() { return being_calculated_; }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001204 bool not_at_start() { return not_at_start_; }
1205 void set_not_at_start() { not_at_start_ = true; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001206 void set_being_calculated(bool b) { being_calculated_ = b; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001207 virtual bool try_to_emit_quick_check_for_alternative(int i) { return true; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001208
ager@chromium.org8bb60582008-12-11 12:02:20 +00001209 protected:
jkummerow@chromium.org486075a2011-09-07 12:44:28 +00001210 int GreedyLoopTextLengthForAlternative(GuardedAlternative* alternative);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001211 ZoneList<GuardedAlternative>* alternatives_;
1212
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001213 private:
1214 friend class DispatchTableConstructor;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001215 friend class Analysis;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001216 void GenerateGuard(RegExpMacroAssembler* macro_assembler,
ager@chromium.org5ec48922009-05-05 07:25:34 +00001217 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001218 Trace* trace);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001219 int CalculatePreloadCharacters(RegExpCompiler* compiler, int eats_at_least);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001220 void EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001221 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001222 GuardedAlternative alternative,
1223 AlternativeGeneration* alt_gen,
1224 int preload_characters,
1225 bool next_expects_preload);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001226 DispatchTable* table_;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001227 // If true, this node is never checked at the start of the input.
1228 // Allows a new trace to start with at_start() set to false.
1229 bool not_at_start_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001230 bool being_calculated_;
1231};
1232
1233
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001234class NegativeLookaheadChoiceNode: public ChoiceNode {
1235 public:
1236 explicit NegativeLookaheadChoiceNode(GuardedAlternative this_must_fail,
1237 GuardedAlternative then_do_this)
1238 : ChoiceNode(2) {
1239 AddAlternative(this_must_fail);
1240 AddAlternative(then_do_this);
1241 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001242 virtual int EatsAtLeast(int still_to_find,
1243 int recursion_depth,
1244 bool not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001245 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1246 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001247 int characters_filled_in,
1248 bool not_at_start);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001249 virtual void FillInBMInfo(
1250 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
1251 alternatives_->at(1).node()->FillInBMInfo(offset, bm, not_at_start);
1252 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001253 // For a negative lookahead we don't emit the quick check for the
1254 // alternative that is expected to fail. This is because quick check code
1255 // starts by loading enough characters for the alternative that takes fewest
1256 // characters, but on a negative lookahead the negative branch did not take
1257 // part in that calculation (EatsAtLeast) so the assumptions don't hold.
1258 virtual bool try_to_emit_quick_check_for_alternative(int i) { return i != 0; }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001259 virtual int ComputeFirstCharacterSet(int budget);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001260};
1261
1262
ager@chromium.org8bb60582008-12-11 12:02:20 +00001263class LoopChoiceNode: public ChoiceNode {
1264 public:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001265 explicit LoopChoiceNode(bool body_can_be_zero_length)
1266 : ChoiceNode(2),
1267 loop_node_(NULL),
1268 continue_node_(NULL),
1269 body_can_be_zero_length_(body_can_be_zero_length) { }
1270 void AddLoopAlternative(GuardedAlternative alt);
1271 void AddContinueAlternative(GuardedAlternative alt);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001272 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001273 virtual int EatsAtLeast(int still_to_find,
1274 int recursion_depth,
1275 bool not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001276 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1277 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001278 int characters_filled_in,
1279 bool not_at_start);
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001280 virtual void FillInBMInfo(
1281 int offset, BoyerMooreLookahead* bm, bool not_at_start);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001282 virtual int ComputeFirstCharacterSet(int budget);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001283 virtual LoopChoiceNode* Clone() { return new LoopChoiceNode(*this); }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001284 RegExpNode* loop_node() { return loop_node_; }
1285 RegExpNode* continue_node() { return continue_node_; }
1286 bool body_can_be_zero_length() { return body_can_be_zero_length_; }
1287 virtual void Accept(NodeVisitor* visitor);
1288
1289 private:
1290 // AddAlternative is made private for loop nodes because alternatives
1291 // should not be added freely, we need to keep track of which node
1292 // goes back to the node itself.
1293 void AddAlternative(GuardedAlternative node) {
1294 ChoiceNode::AddAlternative(node);
1295 }
1296
1297 RegExpNode* loop_node_;
1298 RegExpNode* continue_node_;
1299 bool body_can_be_zero_length_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001300};
1301
1302
1303// There are many ways to generate code for a node. This class encapsulates
1304// the current way we should be generating. In other words it encapsulates
ager@chromium.org32912102009-01-16 10:38:43 +00001305// the current state of the code generator. The effect of this is that we
1306// generate code for paths that the matcher can take through the regular
1307// expression. A given node in the regexp can be code-generated several times
1308// as it can be part of several traces. For example for the regexp:
1309// /foo(bar|ip)baz/ the code to match baz will be generated twice, once as part
1310// of the foo-bar-baz trace and once as part of the foo-ip-baz trace. The code
1311// to match foo is generated only once (the traces have a common prefix). The
1312// code to store the capture is deferred and generated (twice) after the places
1313// where baz has been matched.
1314class Trace {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001315 public:
iposva@chromium.org245aa852009-02-10 00:49:54 +00001316 // A value for a property that is either known to be true, know to be false,
1317 // or not known.
1318 enum TriBool {
1319 UNKNOWN = -1, FALSE = 0, TRUE = 1
1320 };
1321
ager@chromium.org8bb60582008-12-11 12:02:20 +00001322 class DeferredAction {
1323 public:
1324 DeferredAction(ActionNode::Type type, int reg)
1325 : type_(type), reg_(reg), next_(NULL) { }
1326 DeferredAction* next() { return next_; }
ager@chromium.org32912102009-01-16 10:38:43 +00001327 bool Mentions(int reg);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001328 int reg() { return reg_; }
1329 ActionNode::Type type() { return type_; }
1330 private:
1331 ActionNode::Type type_;
1332 int reg_;
1333 DeferredAction* next_;
ager@chromium.org32912102009-01-16 10:38:43 +00001334 friend class Trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001335 };
1336
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001337 class DeferredCapture : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001338 public:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001339 DeferredCapture(int reg, bool is_capture, Trace* trace)
ager@chromium.org8bb60582008-12-11 12:02:20 +00001340 : DeferredAction(ActionNode::STORE_POSITION, reg),
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001341 cp_offset_(trace->cp_offset()),
1342 is_capture_(is_capture) { }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001343 int cp_offset() { return cp_offset_; }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001344 bool is_capture() { return is_capture_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001345 private:
1346 int cp_offset_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001347 bool is_capture_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001348 void set_cp_offset(int cp_offset) { cp_offset_ = cp_offset; }
1349 };
1350
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001351 class DeferredSetRegister : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001352 public:
1353 DeferredSetRegister(int reg, int value)
1354 : DeferredAction(ActionNode::SET_REGISTER, reg),
1355 value_(value) { }
1356 int value() { return value_; }
1357 private:
1358 int value_;
1359 };
1360
ager@chromium.org32912102009-01-16 10:38:43 +00001361 class DeferredClearCaptures : public DeferredAction {
1362 public:
1363 explicit DeferredClearCaptures(Interval range)
1364 : DeferredAction(ActionNode::CLEAR_CAPTURES, -1),
1365 range_(range) { }
1366 Interval range() { return range_; }
1367 private:
1368 Interval range_;
1369 };
1370
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001371 class DeferredIncrementRegister : public DeferredAction {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001372 public:
1373 explicit DeferredIncrementRegister(int reg)
1374 : DeferredAction(ActionNode::INCREMENT_REGISTER, reg) { }
1375 };
1376
ager@chromium.org32912102009-01-16 10:38:43 +00001377 Trace()
ager@chromium.org8bb60582008-12-11 12:02:20 +00001378 : cp_offset_(0),
1379 actions_(NULL),
1380 backtrack_(NULL),
1381 stop_node_(NULL),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001382 loop_label_(NULL),
1383 characters_preloaded_(0),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001384 bound_checked_up_to_(0),
ager@chromium.org381abbb2009-02-25 13:23:22 +00001385 flush_budget_(100),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001386 at_start_(UNKNOWN) { }
1387
ager@chromium.org32912102009-01-16 10:38:43 +00001388 // End the trace. This involves flushing the deferred actions in the trace
1389 // and pushing a backtrack location onto the backtrack stack. Once this is
1390 // done we can start a new trace or go to one that has already been
1391 // generated.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001392 void Flush(RegExpCompiler* compiler, RegExpNode* successor);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001393 int cp_offset() { return cp_offset_; }
1394 DeferredAction* actions() { return actions_; }
ager@chromium.org32912102009-01-16 10:38:43 +00001395 // A trivial trace is one that has no deferred actions or other state that
1396 // affects the assumptions used when generating code. There is no recorded
1397 // backtrack location in a trivial trace, so with a trivial trace we will
1398 // generate code that, on a failure to match, gets the backtrack location
1399 // from the backtrack stack rather than using a direct jump instruction. We
1400 // always start code generation with a trivial trace and non-trivial traces
1401 // are created as we emit code for nodes or add to the list of deferred
1402 // actions in the trace. The location of the code generated for a node using
1403 // a trivial trace is recorded in a label in the node so that gotos can be
1404 // generated to that code.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001405 bool is_trivial() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001406 return backtrack_ == NULL &&
1407 actions_ == NULL &&
1408 cp_offset_ == 0 &&
1409 characters_preloaded_ == 0 &&
1410 bound_checked_up_to_ == 0 &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001411 quick_check_performed_.characters() == 0 &&
1412 at_start_ == UNKNOWN;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001413 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001414 TriBool at_start() { return at_start_; }
1415 void set_at_start(bool at_start) { at_start_ = at_start ? TRUE : FALSE; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001416 Label* backtrack() { return backtrack_; }
1417 Label* loop_label() { return loop_label_; }
1418 RegExpNode* stop_node() { return stop_node_; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001419 int characters_preloaded() { return characters_preloaded_; }
1420 int bound_checked_up_to() { return bound_checked_up_to_; }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001421 int flush_budget() { return flush_budget_; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001422 QuickCheckDetails* quick_check_performed() { return &quick_check_performed_; }
1423 bool mentions_reg(int reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001424 // Returns true if a deferred position store exists to the specified
1425 // register and stores the offset in the out-parameter. Otherwise
1426 // returns false.
1427 bool GetStoredPosition(int reg, int* cp_offset);
1428 // These set methods and AdvanceCurrentPositionInTrace should be used only on
1429 // new traces - the intention is that traces are immutable after creation.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001430 void add_action(DeferredAction* new_action) {
1431 ASSERT(new_action->next_ == NULL);
1432 new_action->next_ = actions_;
1433 actions_ = new_action;
1434 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001435 void set_backtrack(Label* backtrack) { backtrack_ = backtrack; }
1436 void set_stop_node(RegExpNode* node) { stop_node_ = node; }
1437 void set_loop_label(Label* label) { loop_label_ = label; }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001438 void set_characters_preloaded(int count) { characters_preloaded_ = count; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001439 void set_bound_checked_up_to(int to) { bound_checked_up_to_ = to; }
ager@chromium.org381abbb2009-02-25 13:23:22 +00001440 void set_flush_budget(int to) { flush_budget_ = to; }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001441 void set_quick_check_performed(QuickCheckDetails* d) {
1442 quick_check_performed_ = *d;
1443 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001444 void InvalidateCurrentCharacter();
1445 void AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler);
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001446
ager@chromium.org8bb60582008-12-11 12:02:20 +00001447 private:
1448 int FindAffectedRegisters(OutSet* affected_registers);
1449 void PerformDeferredActions(RegExpMacroAssembler* macro,
1450 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001451 OutSet& affected_registers,
1452 OutSet* registers_to_pop,
1453 OutSet* registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001454 void RestoreAffectedRegisters(RegExpMacroAssembler* macro,
1455 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001456 OutSet& registers_to_pop,
1457 OutSet& registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001458 int cp_offset_;
1459 DeferredAction* actions_;
1460 Label* backtrack_;
1461 RegExpNode* stop_node_;
1462 Label* loop_label_;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001463 int characters_preloaded_;
1464 int bound_checked_up_to_;
1465 QuickCheckDetails quick_check_performed_;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001466 int flush_budget_;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001467 TriBool at_start_;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001468};
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001469
1470
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001471class NodeVisitor {
1472 public:
1473 virtual ~NodeVisitor() { }
1474#define DECLARE_VISIT(Type) \
1475 virtual void Visit##Type(Type##Node* that) = 0;
1476FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1477#undef DECLARE_VISIT
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001478 virtual void VisitLoopChoice(LoopChoiceNode* that) { VisitChoice(that); }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001479};
1480
1481
1482// Node visitor used to add the start set of the alternatives to the
1483// dispatch table of a choice node.
1484class DispatchTableConstructor: public NodeVisitor {
1485 public:
1486 DispatchTableConstructor(DispatchTable* table, bool ignore_case)
1487 : table_(table),
1488 choice_index_(-1),
1489 ignore_case_(ignore_case) { }
1490
1491 void BuildTable(ChoiceNode* node);
1492
1493 void AddRange(CharacterRange range) {
1494 table()->AddRange(range, choice_index_);
1495 }
1496
1497 void AddInverse(ZoneList<CharacterRange>* ranges);
1498
1499#define DECLARE_VISIT(Type) \
1500 virtual void Visit##Type(Type##Node* that);
1501FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1502#undef DECLARE_VISIT
1503
1504 DispatchTable* table() { return table_; }
1505 void set_choice_index(int value) { choice_index_ = value; }
1506
1507 protected:
ager@chromium.org5ec48922009-05-05 07:25:34 +00001508 DispatchTable* table_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001509 int choice_index_;
1510 bool ignore_case_;
1511};
1512
1513
ager@chromium.org8bb60582008-12-11 12:02:20 +00001514// Assertion propagation moves information about assertions such as
1515// \b to the affected nodes. For instance, in /.\b./ information must
1516// be propagated to the first '.' that whatever follows needs to know
1517// if it matched a word or a non-word, and to the second '.' that it
1518// has to check if it succeeds a word or non-word. In this case the
1519// result will be something like:
1520//
1521// +-------+ +------------+
1522// | . | | . |
1523// +-------+ ---> +------------+
1524// | word? | | check word |
1525// +-------+ +------------+
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001526class Analysis: public NodeVisitor {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001527 public:
ager@chromium.org38e4c712009-11-11 09:11:58 +00001528 Analysis(bool ignore_case, bool is_ascii)
1529 : ignore_case_(ignore_case),
1530 is_ascii_(is_ascii),
1531 error_message_(NULL) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001532 void EnsureAnalyzed(RegExpNode* node);
1533
1534#define DECLARE_VISIT(Type) \
1535 virtual void Visit##Type(Type##Node* that);
1536FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1537#undef DECLARE_VISIT
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001538 virtual void VisitLoopChoice(LoopChoiceNode* that);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001539
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001540 bool has_failed() { return error_message_ != NULL; }
1541 const char* error_message() {
1542 ASSERT(error_message_ != NULL);
1543 return error_message_;
1544 }
1545 void fail(const char* error_message) {
1546 error_message_ = error_message;
1547 }
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001548
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001549 private:
1550 bool ignore_case_;
ager@chromium.org38e4c712009-11-11 09:11:58 +00001551 bool is_ascii_;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001552 const char* error_message_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001553
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001554 DISALLOW_IMPLICIT_CONSTRUCTORS(Analysis);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001555};
1556
1557
ager@chromium.org8bb60582008-12-11 12:02:20 +00001558struct RegExpCompileData {
1559 RegExpCompileData()
1560 : tree(NULL),
1561 node(NULL),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001562 simple(true),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001563 contains_anchor(false),
ager@chromium.org8bb60582008-12-11 12:02:20 +00001564 capture_count(0) { }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001565 RegExpTree* tree;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001566 RegExpNode* node;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001567 bool simple;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001568 bool contains_anchor;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001569 Handle<String> error;
1570 int capture_count;
1571};
1572
1573
1574class RegExpEngine: public AllStatic {
1575 public:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001576 struct CompilationResult {
1577 explicit CompilationResult(const char* error_message)
1578 : error_message(error_message),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001579 code(HEAP->the_hole_value()),
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001580 num_registers(0) {}
1581 CompilationResult(Object* code, int registers)
1582 : error_message(NULL),
1583 code(code),
1584 num_registers(registers) {}
1585 const char* error_message;
1586 Object* code;
1587 int num_registers;
1588 };
1589
1590 static CompilationResult Compile(RegExpCompileData* input,
1591 bool ignore_case,
1592 bool multiline,
1593 Handle<String> pattern,
fschneider@chromium.org7d10be52012-04-10 12:30:14 +00001594 Handle<String> sample_subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001595 bool is_ascii);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001596
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001597 static void DotPrint(const char* label, RegExpNode* node, bool ignore_case);
1598};
1599
1600
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001601class OffsetsVector {
1602 public:
ulan@chromium.org812308e2012-02-29 15:58:45 +00001603 inline OffsetsVector(int num_registers, Isolate* isolate)
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001604 : offsets_vector_length_(num_registers) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001605 if (offsets_vector_length_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001606 vector_ = NewArray<int>(offsets_vector_length_);
1607 } else {
ulan@chromium.org812308e2012-02-29 15:58:45 +00001608 vector_ = isolate->jsregexp_static_offsets_vector();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001609 }
1610 }
1611 inline ~OffsetsVector() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001612 if (offsets_vector_length_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001613 DeleteArray(vector_);
1614 vector_ = NULL;
1615 }
1616 }
1617 inline int* vector() { return vector_; }
1618 inline int length() { return offsets_vector_length_; }
1619
1620 static const int kStaticOffsetsVectorSize = 50;
1621
1622 private:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001623 static Address static_offsets_vector_address(Isolate* isolate) {
1624 return reinterpret_cast<Address>(isolate->jsregexp_static_offsets_vector());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001625 }
1626
1627 int* vector_;
1628 int offsets_vector_length_;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001629
1630 friend class ExternalReference;
1631};
1632
1633
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001634} } // namespace v8::internal
1635
1636#endif // V8_JSREGEXP_H_