1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_REGEXP_JSREGEXP_H_
6 #define V8_REGEXP_JSREGEXP_H_
7
8 #include "src/allocation.h"
9 #include "src/assembler.h"
10 #include "src/regexp/regexp-ast.h"
11
12 namespace v8 {
13 namespace internal {
14
15 class NodeVisitor;
16 class RegExpCompiler;
17 class RegExpMacroAssembler;
18 class RegExpNode;
19 class RegExpTree;
20 class BoyerMooreLookahead;
21
22 class RegExpImpl {
23 public:
24 // Whether V8 is compiled with native regexp support or not.
UsesNativeRegExp()25 static bool UsesNativeRegExp() {
26 #ifdef V8_INTERPRETED_REGEXP
27 return false;
28 #else
29 return true;
30 #endif
31 }
32
33 // Returns a string representation of a regular expression.
34 // Implements RegExp.prototype.toString, see ECMA-262 section 15.10.6.4.
35 // This function calls the garbage collector if necessary.
36 static Handle<String> ToString(Handle<Object> value);
37
38 // Parses the RegExp pattern and prepares the JSRegExp object with
39 // generic data and choice of implementation - as well as what
40 // the implementation wants to store in the data field.
41 // Returns false if compilation fails.
42 MUST_USE_RESULT static MaybeHandle<Object> Compile(Handle<JSRegExp> re,
43 Handle<String> pattern,
44 JSRegExp::Flags flags);
45
46 // See ECMA-262 section 15.10.6.2.
47 // This function calls the garbage collector if necessary.
48 MUST_USE_RESULT static MaybeHandle<Object> Exec(
49 Handle<JSRegExp> regexp,
50 Handle<String> subject,
51 int index,
52 Handle<JSArray> lastMatchInfo);
53
54 // Prepares a JSRegExp object with Irregexp-specific data.
55 static void IrregexpInitialize(Handle<JSRegExp> re,
56 Handle<String> pattern,
57 JSRegExp::Flags flags,
58 int capture_register_count);
59
60
61 static void AtomCompile(Handle<JSRegExp> re,
62 Handle<String> pattern,
63 JSRegExp::Flags flags,
64 Handle<String> match_pattern);
65
66
67 static int AtomExecRaw(Handle<JSRegExp> regexp,
68 Handle<String> subject,
69 int index,
70 int32_t* output,
71 int output_size);
72
73
74 static Handle<Object> AtomExec(Handle<JSRegExp> regexp,
75 Handle<String> subject,
76 int index,
77 Handle<JSArray> lastMatchInfo);
78
79 enum IrregexpResult { RE_FAILURE = 0, RE_SUCCESS = 1, RE_EXCEPTION = -1 };
80
81 // Prepare a RegExp for being executed one or more times (using
82 // IrregexpExecOnce) on the subject.
83 // This ensures that the regexp is compiled for the subject, and that
84 // the subject is flat.
85 // Returns the number of integer spaces required by IrregexpExecOnce
86 // as its "registers" argument. If the regexp cannot be compiled,
87 // an exception is set as pending, and this function returns negative.
88 static int IrregexpPrepare(Handle<JSRegExp> regexp,
89 Handle<String> subject);
90
91 // Execute a regular expression on the subject, starting from index.
92 // If matching succeeds, return the number of matches. This can be larger
93 // than one in the case of global regular expressions.
94 // The captures and subcaptures are stored into the registers vector.
95 // If matching fails, returns RE_FAILURE.
96 // If execution fails, sets a pending exception and returns RE_EXCEPTION.
97 static int IrregexpExecRaw(Handle<JSRegExp> regexp,
98 Handle<String> subject,
99 int index,
100 int32_t* output,
101 int output_size);
102
103 // Execute an Irregexp bytecode pattern.
104 // On a successful match, the result is a JSArray containing
105 // captured positions. On a failure, the result is the null value.
106 // Returns an empty handle in case of an exception.
107 MUST_USE_RESULT static MaybeHandle<Object> IrregexpExec(
108 Handle<JSRegExp> regexp,
109 Handle<String> subject,
110 int index,
111 Handle<JSArray> lastMatchInfo);
112
113 // Set last match info. If match is NULL, then setting captures is omitted.
114 static Handle<JSArray> SetLastMatchInfo(Handle<JSArray> last_match_info,
115 Handle<String> subject,
116 int capture_count,
117 int32_t* match);
118
119
120 class GlobalCache {
121 public:
122 GlobalCache(Handle<JSRegExp> regexp,
123 Handle<String> subject,
124 bool is_global,
125 Isolate* isolate);
126
127 INLINE(~GlobalCache());
128
129 // Fetch the next entry in the cache for global regexp match results.
130 // This does not set the last match info. Upon failure, NULL is returned.
131 // The cause can be checked with Result(). The previous
132 // result is still in available in memory when a failure happens.
133 INLINE(int32_t* FetchNext());
134
135 INLINE(int32_t* LastSuccessfulMatch());
136
INLINE(bool HasException ())137 INLINE(bool HasException()) { return num_matches_ < 0; }
138
139 private:
140 int num_matches_;
141 int max_matches_;
142 int current_match_index_;
143 int registers_per_match_;
144 // Pointer to the last set of captures.
145 int32_t* register_array_;
146 int register_array_size_;
147 Handle<JSRegExp> regexp_;
148 Handle<String> subject_;
149 };
150
151
152 // Array index in the lastMatchInfo array.
153 static const int kLastCaptureCount = 0;
154 static const int kLastSubject = 1;
155 static const int kLastInput = 2;
156 static const int kFirstCapture = 3;
157 static const int kLastMatchOverhead = 3;
158
159 // Direct offset into the lastMatchInfo array.
160 static const int kLastCaptureCountOffset =
161 FixedArray::kHeaderSize + kLastCaptureCount * kPointerSize;
162 static const int kLastSubjectOffset =
163 FixedArray::kHeaderSize + kLastSubject * kPointerSize;
164 static const int kLastInputOffset =
165 FixedArray::kHeaderSize + kLastInput * kPointerSize;
166 static const int kFirstCaptureOffset =
167 FixedArray::kHeaderSize + kFirstCapture * kPointerSize;
168
169 // Used to access the lastMatchInfo array.
GetCapture(FixedArray * array,int index)170 static int GetCapture(FixedArray* array, int index) {
171 return Smi::cast(array->get(index + kFirstCapture))->value();
172 }
173
SetLastCaptureCount(FixedArray * array,int to)174 static void SetLastCaptureCount(FixedArray* array, int to) {
175 array->set(kLastCaptureCount, Smi::FromInt(to));
176 }
177
SetLastSubject(FixedArray * array,String * to)178 static void SetLastSubject(FixedArray* array, String* to) {
179 array->set(kLastSubject, to);
180 }
181
SetLastInput(FixedArray * array,String * to)182 static void SetLastInput(FixedArray* array, String* to) {
183 array->set(kLastInput, to);
184 }
185
SetCapture(FixedArray * array,int index,int to)186 static void SetCapture(FixedArray* array, int index, int to) {
187 array->set(index + kFirstCapture, Smi::FromInt(to));
188 }
189
GetLastCaptureCount(FixedArray * array)190 static int GetLastCaptureCount(FixedArray* array) {
191 return Smi::cast(array->get(kLastCaptureCount))->value();
192 }
193
194 // For acting on the JSRegExp data FixedArray.
195 static int IrregexpMaxRegisterCount(FixedArray* re);
196 static void SetIrregexpMaxRegisterCount(FixedArray* re, int value);
197 static int IrregexpNumberOfCaptures(FixedArray* re);
198 static int IrregexpNumberOfRegisters(FixedArray* re);
199 static ByteArray* IrregexpByteCode(FixedArray* re, bool is_one_byte);
200 static Code* IrregexpNativeCode(FixedArray* re, bool is_one_byte);
201
202 // Limit the space regexps take up on the heap. In order to limit this we
203 // would like to keep track of the amount of regexp code on the heap. This
204 // is not tracked, however. As a conservative approximation we track the
205 // total regexp code compiled including code that has subsequently been freed
206 // and the total executable memory at any point.
207 static const int kRegExpExecutableMemoryLimit = 16 * MB;
208 static const int kRegExpCompiledLimit = 1 * MB;
209 static const int kRegExpTooLargeToOptimize = 20 * KB;
210
211 private:
212 static bool CompileIrregexp(Handle<JSRegExp> re,
213 Handle<String> sample_subject, bool is_one_byte);
214 static inline bool EnsureCompiledIrregexp(Handle<JSRegExp> re,
215 Handle<String> sample_subject,
216 bool is_one_byte);
217 };
218
219
220 // Represents the location of one element relative to the intersection of
221 // two sets. Corresponds to the four areas of a Venn diagram.
222 enum ElementInSetsRelation {
223 kInsideNone = 0,
224 kInsideFirst = 1,
225 kInsideSecond = 2,
226 kInsideBoth = 3
227 };
228
229
230 // A set of unsigned integers that behaves especially well on small
231 // integers (< 32). May do zone-allocation.
232 class OutSet: public ZoneObject {
233 public:
OutSet()234 OutSet() : first_(0), remaining_(NULL), successors_(NULL) { }
235 OutSet* Extend(unsigned value, Zone* zone);
236 bool Get(unsigned value) const;
237 static const unsigned kFirstLimit = 32;
238
239 private:
240 // Destructively set a value in this set. In most cases you want
241 // to use Extend instead to ensure that only one instance exists
242 // that contains the same values.
243 void Set(unsigned value, Zone* zone);
244
245 // The successors are a list of sets that contain the same values
246 // as this set and the one more value that is not present in this
247 // set.
successors(Zone * zone)248 ZoneList<OutSet*>* successors(Zone* zone) { return successors_; }
249
OutSet(uint32_t first,ZoneList<unsigned> * remaining)250 OutSet(uint32_t first, ZoneList<unsigned>* remaining)
251 : first_(first), remaining_(remaining), successors_(NULL) { }
252 uint32_t first_;
253 ZoneList<unsigned>* remaining_;
254 ZoneList<OutSet*>* successors_;
255 friend class Trace;
256 };
257
258
259 // A mapping from integers, specified as ranges, to a set of integers.
260 // Used for mapping character ranges to choices.
261 class DispatchTable : public ZoneObject {
262 public:
DispatchTable(Zone * zone)263 explicit DispatchTable(Zone* zone) : tree_(zone) { }
264
265 class Entry {
266 public:
Entry()267 Entry() : from_(0), to_(0), out_set_(NULL) { }
Entry(uc16 from,uc16 to,OutSet * out_set)268 Entry(uc16 from, uc16 to, OutSet* out_set)
269 : from_(from), to_(to), out_set_(out_set) { }
from()270 uc16 from() { return from_; }
to()271 uc16 to() { return to_; }
set_to(uc16 value)272 void set_to(uc16 value) { to_ = value; }
AddValue(int value,Zone * zone)273 void AddValue(int value, Zone* zone) {
274 out_set_ = out_set_->Extend(value, zone);
275 }
out_set()276 OutSet* out_set() { return out_set_; }
277 private:
278 uc16 from_;
279 uc16 to_;
280 OutSet* out_set_;
281 };
282
283 class Config {
284 public:
285 typedef uc16 Key;
286 typedef Entry Value;
287 static const uc16 kNoKey;
NoValue()288 static const Entry NoValue() { return Value(); }
Compare(uc16 a,uc16 b)289 static inline int Compare(uc16 a, uc16 b) {
290 if (a == b)
291 return 0;
292 else if (a < b)
293 return -1;
294 else
295 return 1;
296 }
297 };
298
299 void AddRange(CharacterRange range, int value, Zone* zone);
300 OutSet* Get(uc16 value);
301 void Dump();
302
303 template <typename Callback>
ForEach(Callback * callback)304 void ForEach(Callback* callback) {
305 return tree()->ForEach(callback);
306 }
307
308 private:
309 // There can't be a static empty set since it allocates its
310 // successors in a zone and caches them.
empty()311 OutSet* empty() { return &empty_; }
312 OutSet empty_;
tree()313 ZoneSplayTree<Config>* tree() { return &tree_; }
314 ZoneSplayTree<Config> tree_;
315 };
316
317
318 #define FOR_EACH_NODE_TYPE(VISIT) \
319 VISIT(End) \
320 VISIT(Action) \
321 VISIT(Choice) \
322 VISIT(BackReference) \
323 VISIT(Assertion) \
324 VISIT(Text)
325
326
327 class Trace;
328 struct PreloadState;
329 class GreedyLoopState;
330 class AlternativeGenerationList;
331
332 struct NodeInfo {
NodeInfoNodeInfo333 NodeInfo()
334 : being_analyzed(false),
335 been_analyzed(false),
336 follows_word_interest(false),
337 follows_newline_interest(false),
338 follows_start_interest(false),
339 at_end(false),
340 visited(false),
341 replacement_calculated(false) { }
342
343 // Returns true if the interests and assumptions of this node
344 // matches the given one.
MatchesNodeInfo345 bool Matches(NodeInfo* that) {
346 return (at_end == that->at_end) &&
347 (follows_word_interest == that->follows_word_interest) &&
348 (follows_newline_interest == that->follows_newline_interest) &&
349 (follows_start_interest == that->follows_start_interest);
350 }
351
352 // Updates the interests of this node given the interests of the
353 // node preceding it.
AddFromPrecedingNodeInfo354 void AddFromPreceding(NodeInfo* that) {
355 at_end |= that->at_end;
356 follows_word_interest |= that->follows_word_interest;
357 follows_newline_interest |= that->follows_newline_interest;
358 follows_start_interest |= that->follows_start_interest;
359 }
360
HasLookbehindNodeInfo361 bool HasLookbehind() {
362 return follows_word_interest ||
363 follows_newline_interest ||
364 follows_start_interest;
365 }
366
367 // Sets the interests of this node to include the interests of the
368 // following node.
AddFromFollowingNodeInfo369 void AddFromFollowing(NodeInfo* that) {
370 follows_word_interest |= that->follows_word_interest;
371 follows_newline_interest |= that->follows_newline_interest;
372 follows_start_interest |= that->follows_start_interest;
373 }
374
ResetCompilationStateNodeInfo375 void ResetCompilationState() {
376 being_analyzed = false;
377 been_analyzed = false;
378 }
379
380 bool being_analyzed: 1;
381 bool been_analyzed: 1;
382
383 // These bits are set of this node has to know what the preceding
384 // character was.
385 bool follows_word_interest: 1;
386 bool follows_newline_interest: 1;
387 bool follows_start_interest: 1;
388
389 bool at_end: 1;
390 bool visited: 1;
391 bool replacement_calculated: 1;
392 };
393
394
395 // Details of a quick mask-compare check that can look ahead in the
396 // input stream.
397 class QuickCheckDetails {
398 public:
QuickCheckDetails()399 QuickCheckDetails()
400 : characters_(0),
401 mask_(0),
402 value_(0),
403 cannot_match_(false) { }
QuickCheckDetails(int characters)404 explicit QuickCheckDetails(int characters)
405 : characters_(characters),
406 mask_(0),
407 value_(0),
408 cannot_match_(false) { }
409 bool Rationalize(bool one_byte);
410 // Merge in the information from another branch of an alternation.
411 void Merge(QuickCheckDetails* other, int from_index);
412 // Advance the current position by some amount.
413 void Advance(int by, bool one_byte);
414 void Clear();
cannot_match()415 bool cannot_match() { return cannot_match_; }
set_cannot_match()416 void set_cannot_match() { cannot_match_ = true; }
417 struct Position {
PositionPosition418 Position() : mask(0), value(0), determines_perfectly(false) { }
419 uc16 mask;
420 uc16 value;
421 bool determines_perfectly;
422 };
characters()423 int characters() { return characters_; }
set_characters(int characters)424 void set_characters(int characters) { characters_ = characters; }
positions(int index)425 Position* positions(int index) {
426 DCHECK(index >= 0);
427 DCHECK(index < characters_);
428 return positions_ + index;
429 }
mask()430 uint32_t mask() { return mask_; }
value()431 uint32_t value() { return value_; }
432
433 private:
434 // How many characters do we have quick check information from. This is
435 // the same for all branches of a choice node.
436 int characters_;
437 Position positions_[4];
438 // These values are the condensate of the above array after Rationalize().
439 uint32_t mask_;
440 uint32_t value_;
441 // If set to true, there is no way this quick check can match at all.
442 // E.g., if it requires to be at the start of the input, and isn't.
443 bool cannot_match_;
444 };
445
446
447 extern int kUninitializedRegExpNodePlaceHolder;
448
449
450 class RegExpNode: public ZoneObject {
451 public:
RegExpNode(Zone * zone)452 explicit RegExpNode(Zone* zone)
453 : replacement_(NULL), on_work_list_(false), trace_count_(0), zone_(zone) {
454 bm_info_[0] = bm_info_[1] = NULL;
455 }
456 virtual ~RegExpNode();
457 virtual void Accept(NodeVisitor* visitor) = 0;
458 // Generates a goto to this node or actually generates the code at this point.
459 virtual void Emit(RegExpCompiler* compiler, Trace* trace) = 0;
460 // How many characters must this node consume at a minimum in order to
461 // succeed. If we have found at least 'still_to_find' characters that
462 // must be consumed there is no need to ask any following nodes whether
463 // they are sure to eat any more characters. The not_at_start argument is
464 // used to indicate that we know we are not at the start of the input. In
465 // this case anchored branches will always fail and can be ignored when
466 // determining how many characters are consumed on success.
467 virtual int EatsAtLeast(int still_to_find, int budget, bool not_at_start) = 0;
468 // Emits some quick code that checks whether the preloaded characters match.
469 // Falls through on certain failure, jumps to the label on possible success.
470 // If the node cannot make a quick check it does nothing and returns false.
471 bool EmitQuickCheck(RegExpCompiler* compiler,
472 Trace* bounds_check_trace,
473 Trace* trace,
474 bool preload_has_checked_bounds,
475 Label* on_possible_success,
476 QuickCheckDetails* details_return,
477 bool fall_through_on_failure);
478 // For a given number of characters this returns a mask and a value. The
479 // next n characters are anded with the mask and compared with the value.
480 // A comparison failure indicates the node cannot match the next n characters.
481 // A comparison success indicates the node may match.
482 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
483 RegExpCompiler* compiler,
484 int characters_filled_in,
485 bool not_at_start) = 0;
486 static const int kNodeIsTooComplexForGreedyLoops = kMinInt;
GreedyLoopTextLength()487 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
488 // Only returns the successor for a text node of length 1 that matches any
489 // character and that has no guards on it.
GetSuccessorOfOmnivorousTextNode(RegExpCompiler * compiler)490 virtual RegExpNode* GetSuccessorOfOmnivorousTextNode(
491 RegExpCompiler* compiler) {
492 return NULL;
493 }
494
495 // Collects information on the possible code units (mod 128) that can match if
496 // we look forward. This is used for a Boyer-Moore-like string searching
497 // implementation. TODO(erikcorry): This should share more code with
498 // EatsAtLeast, GetQuickCheckDetails. The budget argument is used to limit
499 // the number of nodes we are willing to look at in order to create this data.
500 static const int kRecursionBudget = 200;
501 bool KeepRecursing(RegExpCompiler* compiler);
FillInBMInfo(Isolate * isolate,int offset,int budget,BoyerMooreLookahead * bm,bool not_at_start)502 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
503 BoyerMooreLookahead* bm, bool not_at_start) {
504 UNREACHABLE();
505 }
506
507 // If we know that the input is one-byte then there are some nodes that can
508 // never match. This method returns a node that can be substituted for
509 // itself, or NULL if the node can never match.
FilterOneByte(int depth,bool ignore_case)510 virtual RegExpNode* FilterOneByte(int depth, bool ignore_case) {
511 return this;
512 }
513 // Helper for FilterOneByte.
replacement()514 RegExpNode* replacement() {
515 DCHECK(info()->replacement_calculated);
516 return replacement_;
517 }
set_replacement(RegExpNode * replacement)518 RegExpNode* set_replacement(RegExpNode* replacement) {
519 info()->replacement_calculated = true;
520 replacement_ = replacement;
521 return replacement; // For convenience.
522 }
523
524 // We want to avoid recalculating the lookahead info, so we store it on the
525 // node. Only info that is for this node is stored. We can tell that the
526 // info is for this node when offset == 0, so the information is calculated
527 // relative to this node.
SaveBMInfo(BoyerMooreLookahead * bm,bool not_at_start,int offset)528 void SaveBMInfo(BoyerMooreLookahead* bm, bool not_at_start, int offset) {
529 if (offset == 0) set_bm_info(not_at_start, bm);
530 }
531
label()532 Label* label() { return &label_; }
533 // If non-generic code is generated for a node (i.e. the node is not at the
534 // start of the trace) then it cannot be reused. This variable sets a limit
535 // on how often we allow that to happen before we insist on starting a new
536 // trace and generating generic code for a node that can be reused by flushing
537 // the deferred actions in the current trace and generating a goto.
538 static const int kMaxCopiesCodeGenerated = 10;
539
on_work_list()540 bool on_work_list() { return on_work_list_; }
set_on_work_list(bool value)541 void set_on_work_list(bool value) { on_work_list_ = value; }
542
info()543 NodeInfo* info() { return &info_; }
544
bm_info(bool not_at_start)545 BoyerMooreLookahead* bm_info(bool not_at_start) {
546 return bm_info_[not_at_start ? 1 : 0];
547 }
548
zone()549 Zone* zone() const { return zone_; }
550
551 protected:
552 enum LimitResult { DONE, CONTINUE };
553 RegExpNode* replacement_;
554
555 LimitResult LimitVersions(RegExpCompiler* compiler, Trace* trace);
556
set_bm_info(bool not_at_start,BoyerMooreLookahead * bm)557 void set_bm_info(bool not_at_start, BoyerMooreLookahead* bm) {
558 bm_info_[not_at_start ? 1 : 0] = bm;
559 }
560
561 private:
562 static const int kFirstCharBudget = 10;
563 Label label_;
564 bool on_work_list_;
565 NodeInfo info_;
566 // This variable keeps track of how many times code has been generated for
567 // this node (in different traces). We don't keep track of where the
568 // generated code is located unless the code is generated at the start of
569 // a trace, in which case it is generic and can be reused by flushing the
570 // deferred operations in the current trace and generating a goto.
571 int trace_count_;
572 BoyerMooreLookahead* bm_info_[2];
573
574 Zone* zone_;
575 };
576
577
578 class SeqRegExpNode: public RegExpNode {
579 public:
SeqRegExpNode(RegExpNode * on_success)580 explicit SeqRegExpNode(RegExpNode* on_success)
581 : RegExpNode(on_success->zone()), on_success_(on_success) { }
on_success()582 RegExpNode* on_success() { return on_success_; }
set_on_success(RegExpNode * node)583 void set_on_success(RegExpNode* node) { on_success_ = node; }
584 virtual RegExpNode* FilterOneByte(int depth, bool ignore_case);
FillInBMInfo(Isolate * isolate,int offset,int budget,BoyerMooreLookahead * bm,bool not_at_start)585 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
586 BoyerMooreLookahead* bm, bool not_at_start) {
587 on_success_->FillInBMInfo(isolate, offset, budget - 1, bm, not_at_start);
588 if (offset == 0) set_bm_info(not_at_start, bm);
589 }
590
591 protected:
592 RegExpNode* FilterSuccessor(int depth, bool ignore_case);
593
594 private:
595 RegExpNode* on_success_;
596 };
597
598
599 class ActionNode: public SeqRegExpNode {
600 public:
601 enum ActionType {
602 SET_REGISTER,
603 INCREMENT_REGISTER,
604 STORE_POSITION,
605 BEGIN_SUBMATCH,
606 POSITIVE_SUBMATCH_SUCCESS,
607 EMPTY_MATCH_CHECK,
608 CLEAR_CAPTURES
609 };
610 static ActionNode* SetRegister(int reg, int val, RegExpNode* on_success);
611 static ActionNode* IncrementRegister(int reg, RegExpNode* on_success);
612 static ActionNode* StorePosition(int reg,
613 bool is_capture,
614 RegExpNode* on_success);
615 static ActionNode* ClearCaptures(Interval range, RegExpNode* on_success);
616 static ActionNode* BeginSubmatch(int stack_pointer_reg,
617 int position_reg,
618 RegExpNode* on_success);
619 static ActionNode* PositiveSubmatchSuccess(int stack_pointer_reg,
620 int restore_reg,
621 int clear_capture_count,
622 int clear_capture_from,
623 RegExpNode* on_success);
624 static ActionNode* EmptyMatchCheck(int start_register,
625 int repetition_register,
626 int repetition_limit,
627 RegExpNode* on_success);
628 virtual void Accept(NodeVisitor* visitor);
629 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
630 virtual int EatsAtLeast(int still_to_find, int budget, bool not_at_start);
GetQuickCheckDetails(QuickCheckDetails * details,RegExpCompiler * compiler,int filled_in,bool not_at_start)631 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
632 RegExpCompiler* compiler,
633 int filled_in,
634 bool not_at_start) {
635 return on_success()->GetQuickCheckDetails(
636 details, compiler, filled_in, not_at_start);
637 }
638 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
639 BoyerMooreLookahead* bm, bool not_at_start);
action_type()640 ActionType action_type() { return action_type_; }
641 // TODO(erikcorry): We should allow some action nodes in greedy loops.
GreedyLoopTextLength()642 virtual int GreedyLoopTextLength() { return kNodeIsTooComplexForGreedyLoops; }
643
644 private:
645 union {
646 struct {
647 int reg;
648 int value;
649 } u_store_register;
650 struct {
651 int reg;
652 } u_increment_register;
653 struct {
654 int reg;
655 bool is_capture;
656 } u_position_register;
657 struct {
658 int stack_pointer_register;
659 int current_position_register;
660 int clear_register_count;
661 int clear_register_from;
662 } u_submatch;
663 struct {
664 int start_register;
665 int repetition_register;
666 int repetition_limit;
667 } u_empty_match_check;
668 struct {
669 int range_from;
670 int range_to;
671 } u_clear_captures;
672 } data_;
ActionNode(ActionType action_type,RegExpNode * on_success)673 ActionNode(ActionType action_type, RegExpNode* on_success)
674 : SeqRegExpNode(on_success),
675 action_type_(action_type) { }
676 ActionType action_type_;
677 friend class DotPrinter;
678 };
679
680
681 class TextNode: public SeqRegExpNode {
682 public:
TextNode(ZoneList<TextElement> * elms,bool read_backward,RegExpNode * on_success)683 TextNode(ZoneList<TextElement>* elms, bool read_backward,
684 RegExpNode* on_success)
685 : SeqRegExpNode(on_success), elms_(elms), read_backward_(read_backward) {}
TextNode(RegExpCharacterClass * that,bool read_backward,RegExpNode * on_success)686 TextNode(RegExpCharacterClass* that, bool read_backward,
687 RegExpNode* on_success)
688 : SeqRegExpNode(on_success),
689 elms_(new (zone()) ZoneList<TextElement>(1, zone())),
690 read_backward_(read_backward) {
691 elms_->Add(TextElement::CharClass(that), zone());
692 }
693 virtual void Accept(NodeVisitor* visitor);
694 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
695 virtual int EatsAtLeast(int still_to_find, int budget, bool not_at_start);
696 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
697 RegExpCompiler* compiler,
698 int characters_filled_in,
699 bool not_at_start);
elements()700 ZoneList<TextElement>* elements() { return elms_; }
read_backward()701 bool read_backward() { return read_backward_; }
702 void MakeCaseIndependent(Isolate* isolate, bool is_one_byte);
703 virtual int GreedyLoopTextLength();
704 virtual RegExpNode* GetSuccessorOfOmnivorousTextNode(
705 RegExpCompiler* compiler);
706 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
707 BoyerMooreLookahead* bm, bool not_at_start);
708 void CalculateOffsets();
709 virtual RegExpNode* FilterOneByte(int depth, bool ignore_case);
710
711 private:
712 enum TextEmitPassType {
713 NON_LATIN1_MATCH, // Check for characters that can't match.
714 SIMPLE_CHARACTER_MATCH, // Case-dependent single character check.
715 NON_LETTER_CHARACTER_MATCH, // Check characters that have no case equivs.
716 CASE_CHARACTER_MATCH, // Case-independent single character check.
717 CHARACTER_CLASS_MATCH // Character class.
718 };
719 static bool SkipPass(int pass, bool ignore_case);
720 static const int kFirstRealPass = SIMPLE_CHARACTER_MATCH;
721 static const int kLastPass = CHARACTER_CLASS_MATCH;
722 void TextEmitPass(RegExpCompiler* compiler,
723 TextEmitPassType pass,
724 bool preloaded,
725 Trace* trace,
726 bool first_element_checked,
727 int* checked_up_to);
728 int Length();
729 ZoneList<TextElement>* elms_;
730 bool read_backward_;
731 };
732
733
734 class AssertionNode: public SeqRegExpNode {
735 public:
736 enum AssertionType {
737 AT_END,
738 AT_START,
739 AT_BOUNDARY,
740 AT_NON_BOUNDARY,
741 AFTER_NEWLINE
742 };
AtEnd(RegExpNode * on_success)743 static AssertionNode* AtEnd(RegExpNode* on_success) {
744 return new(on_success->zone()) AssertionNode(AT_END, on_success);
745 }
AtStart(RegExpNode * on_success)746 static AssertionNode* AtStart(RegExpNode* on_success) {
747 return new(on_success->zone()) AssertionNode(AT_START, on_success);
748 }
AtBoundary(RegExpNode * on_success)749 static AssertionNode* AtBoundary(RegExpNode* on_success) {
750 return new(on_success->zone()) AssertionNode(AT_BOUNDARY, on_success);
751 }
AtNonBoundary(RegExpNode * on_success)752 static AssertionNode* AtNonBoundary(RegExpNode* on_success) {
753 return new(on_success->zone()) AssertionNode(AT_NON_BOUNDARY, on_success);
754 }
AfterNewline(RegExpNode * on_success)755 static AssertionNode* AfterNewline(RegExpNode* on_success) {
756 return new(on_success->zone()) AssertionNode(AFTER_NEWLINE, on_success);
757 }
758 virtual void Accept(NodeVisitor* visitor);
759 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
760 virtual int EatsAtLeast(int still_to_find, int budget, bool not_at_start);
761 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
762 RegExpCompiler* compiler,
763 int filled_in,
764 bool not_at_start);
765 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
766 BoyerMooreLookahead* bm, bool not_at_start);
assertion_type()767 AssertionType assertion_type() { return assertion_type_; }
768
769 private:
770 void EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace);
771 enum IfPrevious { kIsNonWord, kIsWord };
772 void BacktrackIfPrevious(RegExpCompiler* compiler,
773 Trace* trace,
774 IfPrevious backtrack_if_previous);
AssertionNode(AssertionType t,RegExpNode * on_success)775 AssertionNode(AssertionType t, RegExpNode* on_success)
776 : SeqRegExpNode(on_success), assertion_type_(t) { }
777 AssertionType assertion_type_;
778 };
779
780
781 class BackReferenceNode: public SeqRegExpNode {
782 public:
BackReferenceNode(int start_reg,int end_reg,bool read_backward,RegExpNode * on_success)783 BackReferenceNode(int start_reg, int end_reg, bool read_backward,
784 RegExpNode* on_success)
785 : SeqRegExpNode(on_success),
786 start_reg_(start_reg),
787 end_reg_(end_reg),
788 read_backward_(read_backward) {}
789 virtual void Accept(NodeVisitor* visitor);
start_register()790 int start_register() { return start_reg_; }
end_register()791 int end_register() { return end_reg_; }
read_backward()792 bool read_backward() { return read_backward_; }
793 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
794 virtual int EatsAtLeast(int still_to_find,
795 int recursion_depth,
796 bool not_at_start);
GetQuickCheckDetails(QuickCheckDetails * details,RegExpCompiler * compiler,int characters_filled_in,bool not_at_start)797 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
798 RegExpCompiler* compiler,
799 int characters_filled_in,
800 bool not_at_start) {
801 return;
802 }
803 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
804 BoyerMooreLookahead* bm, bool not_at_start);
805
806 private:
807 int start_reg_;
808 int end_reg_;
809 bool read_backward_;
810 };
811
812
813 class EndNode: public RegExpNode {
814 public:
815 enum Action { ACCEPT, BACKTRACK, NEGATIVE_SUBMATCH_SUCCESS };
EndNode(Action action,Zone * zone)816 explicit EndNode(Action action, Zone* zone)
817 : RegExpNode(zone), action_(action) { }
818 virtual void Accept(NodeVisitor* visitor);
819 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
EatsAtLeast(int still_to_find,int recursion_depth,bool not_at_start)820 virtual int EatsAtLeast(int still_to_find,
821 int recursion_depth,
822 bool not_at_start) { return 0; }
GetQuickCheckDetails(QuickCheckDetails * details,RegExpCompiler * compiler,int characters_filled_in,bool not_at_start)823 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
824 RegExpCompiler* compiler,
825 int characters_filled_in,
826 bool not_at_start) {
827 // Returning 0 from EatsAtLeast should ensure we never get here.
828 UNREACHABLE();
829 }
FillInBMInfo(Isolate * isolate,int offset,int budget,BoyerMooreLookahead * bm,bool not_at_start)830 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
831 BoyerMooreLookahead* bm, bool not_at_start) {
832 // Returning 0 from EatsAtLeast should ensure we never get here.
833 UNREACHABLE();
834 }
835
836 private:
837 Action action_;
838 };
839
840
841 class NegativeSubmatchSuccess: public EndNode {
842 public:
NegativeSubmatchSuccess(int stack_pointer_reg,int position_reg,int clear_capture_count,int clear_capture_start,Zone * zone)843 NegativeSubmatchSuccess(int stack_pointer_reg,
844 int position_reg,
845 int clear_capture_count,
846 int clear_capture_start,
847 Zone* zone)
848 : EndNode(NEGATIVE_SUBMATCH_SUCCESS, zone),
849 stack_pointer_register_(stack_pointer_reg),
850 current_position_register_(position_reg),
851 clear_capture_count_(clear_capture_count),
852 clear_capture_start_(clear_capture_start) { }
853 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
854
855 private:
856 int stack_pointer_register_;
857 int current_position_register_;
858 int clear_capture_count_;
859 int clear_capture_start_;
860 };
861
862
863 class Guard: public ZoneObject {
864 public:
865 enum Relation { LT, GEQ };
Guard(int reg,Relation op,int value)866 Guard(int reg, Relation op, int value)
867 : reg_(reg),
868 op_(op),
869 value_(value) { }
reg()870 int reg() { return reg_; }
op()871 Relation op() { return op_; }
value()872 int value() { return value_; }
873
874 private:
875 int reg_;
876 Relation op_;
877 int value_;
878 };
879
880
881 class GuardedAlternative {
882 public:
GuardedAlternative(RegExpNode * node)883 explicit GuardedAlternative(RegExpNode* node) : node_(node), guards_(NULL) { }
884 void AddGuard(Guard* guard, Zone* zone);
node()885 RegExpNode* node() { return node_; }
set_node(RegExpNode * node)886 void set_node(RegExpNode* node) { node_ = node; }
guards()887 ZoneList<Guard*>* guards() { return guards_; }
888
889 private:
890 RegExpNode* node_;
891 ZoneList<Guard*>* guards_;
892 };
893
894
895 class AlternativeGeneration;
896
897
898 class ChoiceNode: public RegExpNode {
899 public:
ChoiceNode(int expected_size,Zone * zone)900 explicit ChoiceNode(int expected_size, Zone* zone)
901 : RegExpNode(zone),
902 alternatives_(new(zone)
903 ZoneList<GuardedAlternative>(expected_size, zone)),
904 table_(NULL),
905 not_at_start_(false),
906 being_calculated_(false) { }
907 virtual void Accept(NodeVisitor* visitor);
AddAlternative(GuardedAlternative node)908 void AddAlternative(GuardedAlternative node) {
909 alternatives()->Add(node, zone());
910 }
alternatives()911 ZoneList<GuardedAlternative>* alternatives() { return alternatives_; }
912 DispatchTable* GetTable(bool ignore_case);
913 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
914 virtual int EatsAtLeast(int still_to_find, int budget, bool not_at_start);
915 int EatsAtLeastHelper(int still_to_find,
916 int budget,
917 RegExpNode* ignore_this_node,
918 bool not_at_start);
919 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
920 RegExpCompiler* compiler,
921 int characters_filled_in,
922 bool not_at_start);
923 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
924 BoyerMooreLookahead* bm, bool not_at_start);
925
being_calculated()926 bool being_calculated() { return being_calculated_; }
not_at_start()927 bool not_at_start() { return not_at_start_; }
set_not_at_start()928 void set_not_at_start() { not_at_start_ = true; }
set_being_calculated(bool b)929 void set_being_calculated(bool b) { being_calculated_ = b; }
try_to_emit_quick_check_for_alternative(bool is_first)930 virtual bool try_to_emit_quick_check_for_alternative(bool is_first) {
931 return true;
932 }
933 virtual RegExpNode* FilterOneByte(int depth, bool ignore_case);
read_backward()934 virtual bool read_backward() { return false; }
935
936 protected:
937 int GreedyLoopTextLengthForAlternative(GuardedAlternative* alternative);
938 ZoneList<GuardedAlternative>* alternatives_;
939
940 private:
941 friend class DispatchTableConstructor;
942 friend class Analysis;
943 void GenerateGuard(RegExpMacroAssembler* macro_assembler,
944 Guard* guard,
945 Trace* trace);
946 int CalculatePreloadCharacters(RegExpCompiler* compiler, int eats_at_least);
947 void EmitOutOfLineContinuation(RegExpCompiler* compiler,
948 Trace* trace,
949 GuardedAlternative alternative,
950 AlternativeGeneration* alt_gen,
951 int preload_characters,
952 bool next_expects_preload);
953 void SetUpPreLoad(RegExpCompiler* compiler,
954 Trace* current_trace,
955 PreloadState* preloads);
956 void AssertGuardsMentionRegisters(Trace* trace);
957 int EmitOptimizedUnanchoredSearch(RegExpCompiler* compiler, Trace* trace);
958 Trace* EmitGreedyLoop(RegExpCompiler* compiler,
959 Trace* trace,
960 AlternativeGenerationList* alt_gens,
961 PreloadState* preloads,
962 GreedyLoopState* greedy_loop_state,
963 int text_length);
964 void EmitChoices(RegExpCompiler* compiler,
965 AlternativeGenerationList* alt_gens,
966 int first_choice,
967 Trace* trace,
968 PreloadState* preloads);
969 DispatchTable* table_;
970 // If true, this node is never checked at the start of the input.
971 // Allows a new trace to start with at_start() set to false.
972 bool not_at_start_;
973 bool being_calculated_;
974 };
975
976
977 class NegativeLookaroundChoiceNode : public ChoiceNode {
978 public:
NegativeLookaroundChoiceNode(GuardedAlternative this_must_fail,GuardedAlternative then_do_this,Zone * zone)979 explicit NegativeLookaroundChoiceNode(GuardedAlternative this_must_fail,
980 GuardedAlternative then_do_this,
981 Zone* zone)
982 : ChoiceNode(2, zone) {
983 AddAlternative(this_must_fail);
984 AddAlternative(then_do_this);
985 }
986 virtual int EatsAtLeast(int still_to_find, int budget, bool not_at_start);
987 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
988 RegExpCompiler* compiler,
989 int characters_filled_in,
990 bool not_at_start);
FillInBMInfo(Isolate * isolate,int offset,int budget,BoyerMooreLookahead * bm,bool not_at_start)991 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
992 BoyerMooreLookahead* bm, bool not_at_start) {
993 alternatives_->at(1).node()->FillInBMInfo(isolate, offset, budget - 1, bm,
994 not_at_start);
995 if (offset == 0) set_bm_info(not_at_start, bm);
996 }
997 // For a negative lookahead we don't emit the quick check for the
998 // alternative that is expected to fail. This is because quick check code
999 // starts by loading enough characters for the alternative that takes fewest
1000 // characters, but on a negative lookahead the negative branch did not take
1001 // part in that calculation (EatsAtLeast) so the assumptions don't hold.
try_to_emit_quick_check_for_alternative(bool is_first)1002 virtual bool try_to_emit_quick_check_for_alternative(bool is_first) {
1003 return !is_first;
1004 }
1005 virtual RegExpNode* FilterOneByte(int depth, bool ignore_case);
1006 };
1007
1008
1009 class LoopChoiceNode: public ChoiceNode {
1010 public:
LoopChoiceNode(bool body_can_be_zero_length,bool read_backward,Zone * zone)1011 LoopChoiceNode(bool body_can_be_zero_length, bool read_backward, Zone* zone)
1012 : ChoiceNode(2, zone),
1013 loop_node_(NULL),
1014 continue_node_(NULL),
1015 body_can_be_zero_length_(body_can_be_zero_length),
1016 read_backward_(read_backward) {}
1017 void AddLoopAlternative(GuardedAlternative alt);
1018 void AddContinueAlternative(GuardedAlternative alt);
1019 virtual void Emit(RegExpCompiler* compiler, Trace* trace);
1020 virtual int EatsAtLeast(int still_to_find, int budget, bool not_at_start);
1021 virtual void GetQuickCheckDetails(QuickCheckDetails* details,
1022 RegExpCompiler* compiler,
1023 int characters_filled_in,
1024 bool not_at_start);
1025 virtual void FillInBMInfo(Isolate* isolate, int offset, int budget,
1026 BoyerMooreLookahead* bm, bool not_at_start);
loop_node()1027 RegExpNode* loop_node() { return loop_node_; }
continue_node()1028 RegExpNode* continue_node() { return continue_node_; }
body_can_be_zero_length()1029 bool body_can_be_zero_length() { return body_can_be_zero_length_; }
read_backward()1030 virtual bool read_backward() { return read_backward_; }
1031 virtual void Accept(NodeVisitor* visitor);
1032 virtual RegExpNode* FilterOneByte(int depth, bool ignore_case);
1033
1034 private:
1035 // AddAlternative is made private for loop nodes because alternatives
1036 // should not be added freely, we need to keep track of which node
1037 // goes back to the node itself.
AddAlternative(GuardedAlternative node)1038 void AddAlternative(GuardedAlternative node) {
1039 ChoiceNode::AddAlternative(node);
1040 }
1041
1042 RegExpNode* loop_node_;
1043 RegExpNode* continue_node_;
1044 bool body_can_be_zero_length_;
1045 bool read_backward_;
1046 };
1047
1048
1049 // Improve the speed that we scan for an initial point where a non-anchored
1050 // regexp can match by using a Boyer-Moore-like table. This is done by
1051 // identifying non-greedy non-capturing loops in the nodes that eat any
1052 // character one at a time. For example in the middle of the regexp
1053 // /foo[\s\S]*?bar/ we find such a loop. There is also such a loop implicitly
1054 // inserted at the start of any non-anchored regexp.
1055 //
1056 // When we have found such a loop we look ahead in the nodes to find the set of
1057 // characters that can come at given distances. For example for the regexp
1058 // /.?foo/ we know that there are at least 3 characters ahead of us, and the
1059 // sets of characters that can occur are [any, [f, o], [o]]. We find a range in
1060 // the lookahead info where the set of characters is reasonably constrained. In
1061 // our example this is from index 1 to 2 (0 is not constrained). We can now
1062 // look 3 characters ahead and if we don't find one of [f, o] (the union of
1063 // [f, o] and [o]) then we can skip forwards by the range size (in this case 2).
1064 //
1065 // For Unicode input strings we do the same, but modulo 128.
1066 //
1067 // We also look at the first string fed to the regexp and use that to get a hint
1068 // of the character frequencies in the inputs. This affects the assessment of
1069 // whether the set of characters is 'reasonably constrained'.
1070 //
1071 // We also have another lookahead mechanism (called quick check in the code),
1072 // which uses a wide load of multiple characters followed by a mask and compare
1073 // to determine whether a match is possible at this point.
1074 enum ContainedInLattice {
1075 kNotYet = 0,
1076 kLatticeIn = 1,
1077 kLatticeOut = 2,
1078 kLatticeUnknown = 3 // Can also mean both in and out.
1079 };
1080
1081
Combine(ContainedInLattice a,ContainedInLattice b)1082 inline ContainedInLattice Combine(ContainedInLattice a, ContainedInLattice b) {
1083 return static_cast<ContainedInLattice>(a | b);
1084 }
1085
1086
1087 ContainedInLattice AddRange(ContainedInLattice a,
1088 const int* ranges,
1089 int ranges_size,
1090 Interval new_range);
1091
1092
1093 class BoyerMoorePositionInfo : public ZoneObject {
1094 public:
BoyerMoorePositionInfo(Zone * zone)1095 explicit BoyerMoorePositionInfo(Zone* zone)
1096 : map_(new(zone) ZoneList<bool>(kMapSize, zone)),
1097 map_count_(0),
1098 w_(kNotYet),
1099 s_(kNotYet),
1100 d_(kNotYet),
1101 surrogate_(kNotYet) {
1102 for (int i = 0; i < kMapSize; i++) {
1103 map_->Add(false, zone);
1104 }
1105 }
1106
at(int i)1107 bool& at(int i) { return map_->at(i); }
1108
1109 static const int kMapSize = 128;
1110 static const int kMask = kMapSize - 1;
1111
map_count()1112 int map_count() const { return map_count_; }
1113
1114 void Set(int character);
1115 void SetInterval(const Interval& interval);
1116 void SetAll();
is_non_word()1117 bool is_non_word() { return w_ == kLatticeOut; }
is_word()1118 bool is_word() { return w_ == kLatticeIn; }
1119
1120 private:
1121 ZoneList<bool>* map_;
1122 int map_count_; // Number of set bits in the map.
1123 ContainedInLattice w_; // The \w character class.
1124 ContainedInLattice s_; // The \s character class.
1125 ContainedInLattice d_; // The \d character class.
1126 ContainedInLattice surrogate_; // Surrogate UTF-16 code units.
1127 };
1128
1129
1130 class BoyerMooreLookahead : public ZoneObject {
1131 public:
1132 BoyerMooreLookahead(int length, RegExpCompiler* compiler, Zone* zone);
1133
length()1134 int length() { return length_; }
max_char()1135 int max_char() { return max_char_; }
compiler()1136 RegExpCompiler* compiler() { return compiler_; }
1137
Count(int map_number)1138 int Count(int map_number) {
1139 return bitmaps_->at(map_number)->map_count();
1140 }
1141
at(int i)1142 BoyerMoorePositionInfo* at(int i) { return bitmaps_->at(i); }
1143
Set(int map_number,int character)1144 void Set(int map_number, int character) {
1145 if (character > max_char_) return;
1146 BoyerMoorePositionInfo* info = bitmaps_->at(map_number);
1147 info->Set(character);
1148 }
1149
SetInterval(int map_number,const Interval & interval)1150 void SetInterval(int map_number, const Interval& interval) {
1151 if (interval.from() > max_char_) return;
1152 BoyerMoorePositionInfo* info = bitmaps_->at(map_number);
1153 if (interval.to() > max_char_) {
1154 info->SetInterval(Interval(interval.from(), max_char_));
1155 } else {
1156 info->SetInterval(interval);
1157 }
1158 }
1159
SetAll(int map_number)1160 void SetAll(int map_number) {
1161 bitmaps_->at(map_number)->SetAll();
1162 }
1163
SetRest(int from_map)1164 void SetRest(int from_map) {
1165 for (int i = from_map; i < length_; i++) SetAll(i);
1166 }
1167 void EmitSkipInstructions(RegExpMacroAssembler* masm);
1168
1169 private:
1170 // This is the value obtained by EatsAtLeast. If we do not have at least this
1171 // many characters left in the sample string then the match is bound to fail.
1172 // Therefore it is OK to read a character this far ahead of the current match
1173 // point.
1174 int length_;
1175 RegExpCompiler* compiler_;
1176 // 0xff for Latin1, 0xffff for UTF-16.
1177 int max_char_;
1178 ZoneList<BoyerMoorePositionInfo*>* bitmaps_;
1179
1180 int GetSkipTable(int min_lookahead,
1181 int max_lookahead,
1182 Handle<ByteArray> boolean_skip_table);
1183 bool FindWorthwhileInterval(int* from, int* to);
1184 int FindBestInterval(
1185 int max_number_of_chars, int old_biggest_points, int* from, int* to);
1186 };
1187
1188
1189 // There are many ways to generate code for a node. This class encapsulates
1190 // the current way we should be generating. In other words it encapsulates
1191 // the current state of the code generator. The effect of this is that we
1192 // generate code for paths that the matcher can take through the regular
1193 // expression. A given node in the regexp can be code-generated several times
1194 // as it can be part of several traces. For example for the regexp:
1195 // /foo(bar|ip)baz/ the code to match baz will be generated twice, once as part
1196 // of the foo-bar-baz trace and once as part of the foo-ip-baz trace. The code
1197 // to match foo is generated only once (the traces have a common prefix). The
1198 // code to store the capture is deferred and generated (twice) after the places
1199 // where baz has been matched.
1200 class Trace {
1201 public:
1202 // A value for a property that is either known to be true, know to be false,
1203 // or not known.
1204 enum TriBool {
1205 UNKNOWN = -1, FALSE_VALUE = 0, TRUE_VALUE = 1
1206 };
1207
1208 class DeferredAction {
1209 public:
DeferredAction(ActionNode::ActionType action_type,int reg)1210 DeferredAction(ActionNode::ActionType action_type, int reg)
1211 : action_type_(action_type), reg_(reg), next_(NULL) { }
next()1212 DeferredAction* next() { return next_; }
1213 bool Mentions(int reg);
reg()1214 int reg() { return reg_; }
action_type()1215 ActionNode::ActionType action_type() { return action_type_; }
1216 private:
1217 ActionNode::ActionType action_type_;
1218 int reg_;
1219 DeferredAction* next_;
1220 friend class Trace;
1221 };
1222
1223 class DeferredCapture : public DeferredAction {
1224 public:
DeferredCapture(int reg,bool is_capture,Trace * trace)1225 DeferredCapture(int reg, bool is_capture, Trace* trace)
1226 : DeferredAction(ActionNode::STORE_POSITION, reg),
1227 cp_offset_(trace->cp_offset()),
1228 is_capture_(is_capture) { }
cp_offset()1229 int cp_offset() { return cp_offset_; }
is_capture()1230 bool is_capture() { return is_capture_; }
1231 private:
1232 int cp_offset_;
1233 bool is_capture_;
set_cp_offset(int cp_offset)1234 void set_cp_offset(int cp_offset) { cp_offset_ = cp_offset; }
1235 };
1236
1237 class DeferredSetRegister : public DeferredAction {
1238 public:
DeferredSetRegister(int reg,int value)1239 DeferredSetRegister(int reg, int value)
1240 : DeferredAction(ActionNode::SET_REGISTER, reg),
1241 value_(value) { }
value()1242 int value() { return value_; }
1243 private:
1244 int value_;
1245 };
1246
1247 class DeferredClearCaptures : public DeferredAction {
1248 public:
DeferredClearCaptures(Interval range)1249 explicit DeferredClearCaptures(Interval range)
1250 : DeferredAction(ActionNode::CLEAR_CAPTURES, -1),
1251 range_(range) { }
range()1252 Interval range() { return range_; }
1253 private:
1254 Interval range_;
1255 };
1256
1257 class DeferredIncrementRegister : public DeferredAction {
1258 public:
DeferredIncrementRegister(int reg)1259 explicit DeferredIncrementRegister(int reg)
1260 : DeferredAction(ActionNode::INCREMENT_REGISTER, reg) { }
1261 };
1262
Trace()1263 Trace()
1264 : cp_offset_(0),
1265 actions_(NULL),
1266 backtrack_(NULL),
1267 stop_node_(NULL),
1268 loop_label_(NULL),
1269 characters_preloaded_(0),
1270 bound_checked_up_to_(0),
1271 flush_budget_(100),
1272 at_start_(UNKNOWN) { }
1273
1274 // End the trace. This involves flushing the deferred actions in the trace
1275 // and pushing a backtrack location onto the backtrack stack. Once this is
1276 // done we can start a new trace or go to one that has already been
1277 // generated.
1278 void Flush(RegExpCompiler* compiler, RegExpNode* successor);
cp_offset()1279 int cp_offset() { return cp_offset_; }
actions()1280 DeferredAction* actions() { return actions_; }
1281 // A trivial trace is one that has no deferred actions or other state that
1282 // affects the assumptions used when generating code. There is no recorded
1283 // backtrack location in a trivial trace, so with a trivial trace we will
1284 // generate code that, on a failure to match, gets the backtrack location
1285 // from the backtrack stack rather than using a direct jump instruction. We
1286 // always start code generation with a trivial trace and non-trivial traces
1287 // are created as we emit code for nodes or add to the list of deferred
1288 // actions in the trace. The location of the code generated for a node using
1289 // a trivial trace is recorded in a label in the node so that gotos can be
1290 // generated to that code.
is_trivial()1291 bool is_trivial() {
1292 return backtrack_ == NULL &&
1293 actions_ == NULL &&
1294 cp_offset_ == 0 &&
1295 characters_preloaded_ == 0 &&
1296 bound_checked_up_to_ == 0 &&
1297 quick_check_performed_.characters() == 0 &&
1298 at_start_ == UNKNOWN;
1299 }
at_start()1300 TriBool at_start() { return at_start_; }
set_at_start(TriBool at_start)1301 void set_at_start(TriBool at_start) { at_start_ = at_start; }
backtrack()1302 Label* backtrack() { return backtrack_; }
loop_label()1303 Label* loop_label() { return loop_label_; }
stop_node()1304 RegExpNode* stop_node() { return stop_node_; }
characters_preloaded()1305 int characters_preloaded() { return characters_preloaded_; }
bound_checked_up_to()1306 int bound_checked_up_to() { return bound_checked_up_to_; }
flush_budget()1307 int flush_budget() { return flush_budget_; }
quick_check_performed()1308 QuickCheckDetails* quick_check_performed() { return &quick_check_performed_; }
1309 bool mentions_reg(int reg);
1310 // Returns true if a deferred position store exists to the specified
1311 // register and stores the offset in the out-parameter. Otherwise
1312 // returns false.
1313 bool GetStoredPosition(int reg, int* cp_offset);
1314 // These set methods and AdvanceCurrentPositionInTrace should be used only on
1315 // new traces - the intention is that traces are immutable after creation.
add_action(DeferredAction * new_action)1316 void add_action(DeferredAction* new_action) {
1317 DCHECK(new_action->next_ == NULL);
1318 new_action->next_ = actions_;
1319 actions_ = new_action;
1320 }
set_backtrack(Label * backtrack)1321 void set_backtrack(Label* backtrack) { backtrack_ = backtrack; }
set_stop_node(RegExpNode * node)1322 void set_stop_node(RegExpNode* node) { stop_node_ = node; }
set_loop_label(Label * label)1323 void set_loop_label(Label* label) { loop_label_ = label; }
set_characters_preloaded(int count)1324 void set_characters_preloaded(int count) { characters_preloaded_ = count; }
set_bound_checked_up_to(int to)1325 void set_bound_checked_up_to(int to) { bound_checked_up_to_ = to; }
set_flush_budget(int to)1326 void set_flush_budget(int to) { flush_budget_ = to; }
set_quick_check_performed(QuickCheckDetails * d)1327 void set_quick_check_performed(QuickCheckDetails* d) {
1328 quick_check_performed_ = *d;
1329 }
1330 void InvalidateCurrentCharacter();
1331 void AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler);
1332
1333 private:
1334 int FindAffectedRegisters(OutSet* affected_registers, Zone* zone);
1335 void PerformDeferredActions(RegExpMacroAssembler* macro,
1336 int max_register,
1337 const OutSet& affected_registers,
1338 OutSet* registers_to_pop,
1339 OutSet* registers_to_clear,
1340 Zone* zone);
1341 void RestoreAffectedRegisters(RegExpMacroAssembler* macro,
1342 int max_register,
1343 const OutSet& registers_to_pop,
1344 const OutSet& registers_to_clear);
1345 int cp_offset_;
1346 DeferredAction* actions_;
1347 Label* backtrack_;
1348 RegExpNode* stop_node_;
1349 Label* loop_label_;
1350 int characters_preloaded_;
1351 int bound_checked_up_to_;
1352 QuickCheckDetails quick_check_performed_;
1353 int flush_budget_;
1354 TriBool at_start_;
1355 };
1356
1357
1358 class GreedyLoopState {
1359 public:
1360 explicit GreedyLoopState(bool not_at_start);
1361
label()1362 Label* label() { return &label_; }
counter_backtrack_trace()1363 Trace* counter_backtrack_trace() { return &counter_backtrack_trace_; }
1364
1365 private:
1366 Label label_;
1367 Trace counter_backtrack_trace_;
1368 };
1369
1370
1371 struct PreloadState {
1372 static const int kEatsAtLeastNotYetInitialized = -1;
1373 bool preload_is_current_;
1374 bool preload_has_checked_bounds_;
1375 int preload_characters_;
1376 int eats_at_least_;
initPreloadState1377 void init() {
1378 eats_at_least_ = kEatsAtLeastNotYetInitialized;
1379 }
1380 };
1381
1382
1383 class NodeVisitor {
1384 public:
~NodeVisitor()1385 virtual ~NodeVisitor() { }
1386 #define DECLARE_VISIT(Type) \
1387 virtual void Visit##Type(Type##Node* that) = 0;
FOR_EACH_NODE_TYPE(DECLARE_VISIT)1388 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1389 #undef DECLARE_VISIT
1390 virtual void VisitLoopChoice(LoopChoiceNode* that) { VisitChoice(that); }
1391 };
1392
1393
1394 // Node visitor used to add the start set of the alternatives to the
1395 // dispatch table of a choice node.
1396 class DispatchTableConstructor: public NodeVisitor {
1397 public:
DispatchTableConstructor(DispatchTable * table,bool ignore_case,Zone * zone)1398 DispatchTableConstructor(DispatchTable* table, bool ignore_case,
1399 Zone* zone)
1400 : table_(table),
1401 choice_index_(-1),
1402 ignore_case_(ignore_case),
1403 zone_(zone) { }
1404
1405 void BuildTable(ChoiceNode* node);
1406
AddRange(CharacterRange range)1407 void AddRange(CharacterRange range) {
1408 table()->AddRange(range, choice_index_, zone_);
1409 }
1410
1411 void AddInverse(ZoneList<CharacterRange>* ranges);
1412
1413 #define DECLARE_VISIT(Type) \
1414 virtual void Visit##Type(Type##Node* that);
FOR_EACH_NODE_TYPE(DECLARE_VISIT)1415 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1416 #undef DECLARE_VISIT
1417
1418 DispatchTable* table() { return table_; }
set_choice_index(int value)1419 void set_choice_index(int value) { choice_index_ = value; }
1420
1421 protected:
1422 DispatchTable* table_;
1423 int choice_index_;
1424 bool ignore_case_;
1425 Zone* zone_;
1426 };
1427
1428
1429 // Assertion propagation moves information about assertions such as
1430 // \b to the affected nodes. For instance, in /.\b./ information must
1431 // be propagated to the first '.' that whatever follows needs to know
1432 // if it matched a word or a non-word, and to the second '.' that it
1433 // has to check if it succeeds a word or non-word. In this case the
1434 // result will be something like:
1435 //
1436 // +-------+ +------------+
1437 // | . | | . |
1438 // +-------+ ---> +------------+
1439 // | word? | | check word |
1440 // +-------+ +------------+
1441 class Analysis: public NodeVisitor {
1442 public:
Analysis(Isolate * isolate,bool ignore_case,bool is_one_byte)1443 Analysis(Isolate* isolate, bool ignore_case, bool is_one_byte)
1444 : isolate_(isolate),
1445 ignore_case_(ignore_case),
1446 is_one_byte_(is_one_byte),
1447 error_message_(NULL) {}
1448 void EnsureAnalyzed(RegExpNode* node);
1449
1450 #define DECLARE_VISIT(Type) \
1451 virtual void Visit##Type(Type##Node* that);
1452 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
1453 #undef DECLARE_VISIT
1454 virtual void VisitLoopChoice(LoopChoiceNode* that);
1455
has_failed()1456 bool has_failed() { return error_message_ != NULL; }
error_message()1457 const char* error_message() {
1458 DCHECK(error_message_ != NULL);
1459 return error_message_;
1460 }
fail(const char * error_message)1461 void fail(const char* error_message) {
1462 error_message_ = error_message;
1463 }
1464
isolate()1465 Isolate* isolate() const { return isolate_; }
1466
1467 private:
1468 Isolate* isolate_;
1469 bool ignore_case_;
1470 bool is_one_byte_;
1471 const char* error_message_;
1472
1473 DISALLOW_IMPLICIT_CONSTRUCTORS(Analysis);
1474 };
1475
1476
1477 struct RegExpCompileData {
RegExpCompileDataRegExpCompileData1478 RegExpCompileData()
1479 : tree(NULL),
1480 node(NULL),
1481 simple(true),
1482 contains_anchor(false),
1483 capture_count(0) { }
1484 RegExpTree* tree;
1485 RegExpNode* node;
1486 bool simple;
1487 bool contains_anchor;
1488 Handle<String> error;
1489 int capture_count;
1490 };
1491
1492
1493 class RegExpEngine: public AllStatic {
1494 public:
1495 struct CompilationResult {
CompilationResultCompilationResult1496 CompilationResult(Isolate* isolate, const char* error_message)
1497 : error_message(error_message),
1498 code(isolate->heap()->the_hole_value()),
1499 num_registers(0) {}
CompilationResultCompilationResult1500 CompilationResult(Object* code, int registers)
1501 : error_message(NULL), code(code), num_registers(registers) {}
1502 const char* error_message;
1503 Object* code;
1504 int num_registers;
1505 };
1506
1507 static CompilationResult Compile(Isolate* isolate, Zone* zone,
1508 RegExpCompileData* input, bool ignore_case,
1509 bool global, bool multiline, bool sticky,
1510 Handle<String> pattern,
1511 Handle<String> sample_subject,
1512 bool is_one_byte);
1513
1514 static bool TooMuchRegExpCode(Handle<String> pattern);
1515
1516 static void DotPrint(const char* label, RegExpNode* node, bool ignore_case);
1517 };
1518
1519
1520 class RegExpResultsCache : public AllStatic {
1521 public:
1522 enum ResultsCacheType { REGEXP_MULTIPLE_INDICES, STRING_SPLIT_SUBSTRINGS };
1523
1524 // Attempt to retrieve a cached result. On failure, 0 is returned as a Smi.
1525 // On success, the returned result is guaranteed to be a COW-array.
1526 static Object* Lookup(Heap* heap, String* key_string, Object* key_pattern,
1527 FixedArray** last_match_out, ResultsCacheType type);
1528 // Attempt to add value_array to the cache specified by type. On success,
1529 // value_array is turned into a COW-array.
1530 static void Enter(Isolate* isolate, Handle<String> key_string,
1531 Handle<Object> key_pattern, Handle<FixedArray> value_array,
1532 Handle<FixedArray> last_match_cache, ResultsCacheType type);
1533 static void Clear(FixedArray* cache);
1534 static const int kRegExpResultsCacheSize = 0x100;
1535
1536 private:
1537 static const int kArrayEntriesPerCacheEntry = 4;
1538 static const int kStringOffset = 0;
1539 static const int kPatternOffset = 1;
1540 static const int kArrayOffset = 2;
1541 static const int kLastMatchOffset = 3;
1542 };
1543
1544 } // namespace internal
1545 } // namespace v8
1546
1547 #endif // V8_REGEXP_JSREGEXP_H_
1548