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