1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "execution.h"
36 #include "string-search.h"
38 #include "compilation-cache.h"
39 #include "string-stream.h"
41 #include "regexp-macro-assembler.h"
42 #include "regexp-macro-assembler-tracer.h"
43 #include "regexp-macro-assembler-irregexp.h"
44 #include "regexp-stack.h"
46 #ifndef V8_INTERPRETED_REGEXP
47 #if V8_TARGET_ARCH_IA32
48 #include "ia32/regexp-macro-assembler-ia32.h"
49 #elif V8_TARGET_ARCH_X64
50 #include "x64/regexp-macro-assembler-x64.h"
51 #elif V8_TARGET_ARCH_ARM
52 #include "arm/regexp-macro-assembler-arm.h"
53 #elif V8_TARGET_ARCH_MIPS
54 #include "mips/regexp-macro-assembler-mips.h"
56 #error Unsupported target architecture.
60 #include "interpreter-irregexp.h"
66 Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
67 Handle<String> pattern,
69 bool* has_pending_exception) {
70 // Call the construct code with 2 arguments.
71 Handle<Object> argv[] = { pattern, flags };
72 return Execution::New(constructor, ARRAY_SIZE(argv), argv,
73 has_pending_exception);
77 static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
78 int flags = JSRegExp::NONE;
79 for (int i = 0; i < str->length(); i++) {
80 switch (str->Get(i)) {
82 flags |= JSRegExp::IGNORE_CASE;
85 flags |= JSRegExp::GLOBAL;
88 flags |= JSRegExp::MULTILINE;
92 return JSRegExp::Flags(flags);
96 static inline void ThrowRegExpException(Handle<JSRegExp> re,
97 Handle<String> pattern,
98 Handle<String> error_text,
99 const char* message) {
100 Isolate* isolate = re->GetIsolate();
101 Factory* factory = isolate->factory();
102 Handle<FixedArray> elements = factory->NewFixedArray(2);
103 elements->set(0, *pattern);
104 elements->set(1, *error_text);
105 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
106 Handle<Object> regexp_err = factory->NewSyntaxError(message, array);
107 isolate->Throw(*regexp_err);
111 ContainedInLattice AddRange(ContainedInLattice containment,
114 Interval new_range) {
115 ASSERT((ranges_length & 1) == 1);
116 ASSERT(ranges[ranges_length - 1] == String::kMaxUtf16CodeUnit + 1);
117 if (containment == kLatticeUnknown) return containment;
120 for (int i = 0; i < ranges_length; inside = !inside, last = ranges[i], i++) {
121 // Consider the range from last to ranges[i].
122 // We haven't got to the new range yet.
123 if (ranges[i] <= new_range.from()) continue;
124 // New range is wholly inside last-ranges[i]. Note that new_range.to() is
125 // inclusive, but the values in ranges are not.
126 if (last <= new_range.from() && new_range.to() < ranges[i]) {
127 return Combine(containment, inside ? kLatticeIn : kLatticeOut);
129 return kLatticeUnknown;
135 // More makes code generation slower, less makes V8 benchmark score lower.
136 const int kMaxLookaheadForBoyerMoore = 8;
137 // In a 3-character pattern you can maximally step forwards 3 characters
138 // at a time, which is not always enough to pay for the extra logic.
139 const int kPatternTooShortForBoyerMoore = 2;
142 // Identifies the sort of regexps where the regexp engine is faster
143 // than the code used for atom matches.
144 static bool HasFewDifferentCharacters(Handle<String> pattern) {
145 int length = Min(kMaxLookaheadForBoyerMoore, pattern->length());
146 if (length <= kPatternTooShortForBoyerMoore) return false;
147 const int kMod = 128;
148 bool character_found[kMod];
150 memset(&character_found[0], 0, sizeof(character_found));
151 for (int i = 0; i < length; i++) {
152 int ch = (pattern->Get(i) & (kMod - 1));
153 if (!character_found[ch]) {
154 character_found[ch] = true;
156 // We declare a regexp low-alphabet if it has at least 3 times as many
157 // characters as it has different characters.
158 if (different * 3 > length) return false;
165 // Generic RegExp methods. Dispatches to implementation specific methods.
168 Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
169 Handle<String> pattern,
170 Handle<String> flag_str) {
171 Isolate* isolate = re->GetIsolate();
172 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
173 CompilationCache* compilation_cache = isolate->compilation_cache();
174 Handle<FixedArray> cached = compilation_cache->LookupRegExp(pattern, flags);
175 bool in_cache = !cached.is_null();
176 LOG(isolate, RegExpCompileEvent(re, in_cache));
178 Handle<Object> result;
180 re->set_data(*cached);
183 pattern = FlattenGetString(pattern);
184 ZoneScope zone_scope(isolate, DELETE_ON_EXIT);
185 PostponeInterruptsScope postpone(isolate);
186 RegExpCompileData parse_result;
187 FlatStringReader reader(isolate, pattern);
188 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
190 // Throw an exception if we fail to parse the pattern.
191 ThrowRegExpException(re,
195 return Handle<Object>::null();
198 bool has_been_compiled = false;
200 if (parse_result.simple &&
201 !flags.is_ignore_case() &&
202 !HasFewDifferentCharacters(pattern)) {
203 // Parse-tree is a single atom that is equal to the pattern.
204 AtomCompile(re, pattern, flags, pattern);
205 has_been_compiled = true;
206 } else if (parse_result.tree->IsAtom() &&
207 !flags.is_ignore_case() &&
208 parse_result.capture_count == 0) {
209 RegExpAtom* atom = parse_result.tree->AsAtom();
210 Vector<const uc16> atom_pattern = atom->data();
211 Handle<String> atom_string =
212 isolate->factory()->NewStringFromTwoByte(atom_pattern);
213 if (!HasFewDifferentCharacters(atom_string)) {
214 AtomCompile(re, pattern, flags, atom_string);
215 has_been_compiled = true;
218 if (!has_been_compiled) {
219 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
221 ASSERT(re->data()->IsFixedArray());
222 // Compilation succeeded so the data is set on the regexp
223 // and we can store it in the cache.
224 Handle<FixedArray> data(FixedArray::cast(re->data()));
225 compilation_cache->PutRegExp(pattern, flags, data);
231 Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
232 Handle<String> subject,
234 Handle<JSArray> last_match_info) {
235 switch (regexp->TypeTag()) {
237 return AtomExec(regexp, subject, index, last_match_info);
238 case JSRegExp::IRREGEXP: {
239 Handle<Object> result =
240 IrregexpExec(regexp, subject, index, last_match_info);
241 ASSERT(!result.is_null() ||
242 regexp->GetIsolate()->has_pending_exception());
247 return Handle<Object>::null();
252 // RegExp Atom implementation: Simple string search using indexOf.
255 void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
256 Handle<String> pattern,
257 JSRegExp::Flags flags,
258 Handle<String> match_pattern) {
259 re->GetIsolate()->factory()->SetRegExpAtomData(re,
267 static void SetAtomLastCapture(FixedArray* array,
271 NoHandleAllocation no_handles;
272 RegExpImpl::SetLastCaptureCount(array, 2);
273 RegExpImpl::SetLastSubject(array, subject);
274 RegExpImpl::SetLastInput(array, subject);
275 RegExpImpl::SetCapture(array, 0, from);
276 RegExpImpl::SetCapture(array, 1, to);
280 Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
281 Handle<String> subject,
283 Handle<JSArray> last_match_info) {
284 Isolate* isolate = re->GetIsolate();
287 ASSERT(index <= subject->length());
289 if (!subject->IsFlat()) FlattenString(subject);
290 AssertNoAllocation no_heap_allocation; // ensure vectors stay valid
292 String* needle = String::cast(re->DataAt(JSRegExp::kAtomPatternIndex));
293 int needle_len = needle->length();
294 ASSERT(needle->IsFlat());
296 if (needle_len != 0) {
297 if (index + needle_len > subject->length()) {
298 return isolate->factory()->null_value();
301 String::FlatContent needle_content = needle->GetFlatContent();
302 String::FlatContent subject_content = subject->GetFlatContent();
303 ASSERT(needle_content.IsFlat());
304 ASSERT(subject_content.IsFlat());
305 // dispatch on type of strings
306 index = (needle_content.IsAscii()
307 ? (subject_content.IsAscii()
308 ? SearchString(isolate,
309 subject_content.ToAsciiVector(),
310 needle_content.ToAsciiVector(),
312 : SearchString(isolate,
313 subject_content.ToUC16Vector(),
314 needle_content.ToAsciiVector(),
316 : (subject_content.IsAscii()
317 ? SearchString(isolate,
318 subject_content.ToAsciiVector(),
319 needle_content.ToUC16Vector(),
321 : SearchString(isolate,
322 subject_content.ToUC16Vector(),
323 needle_content.ToUC16Vector(),
325 if (index == -1) return isolate->factory()->null_value();
327 ASSERT(last_match_info->HasFastElements());
330 NoHandleAllocation no_handles;
331 FixedArray* array = FixedArray::cast(last_match_info->elements());
332 SetAtomLastCapture(array, *subject, index, index + needle_len);
334 return last_match_info;
338 // Irregexp implementation.
340 // Ensures that the regexp object contains a compiled version of the
341 // source for either ASCII or non-ASCII strings.
342 // If the compiled version doesn't already exist, it is compiled
343 // from the source pattern.
344 // If compilation fails, an exception is thrown and this function
346 bool RegExpImpl::EnsureCompiledIrregexp(
347 Handle<JSRegExp> re, Handle<String> sample_subject, bool is_ascii) {
348 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
349 #ifdef V8_INTERPRETED_REGEXP
350 if (compiled_code->IsByteArray()) return true;
351 #else // V8_INTERPRETED_REGEXP (RegExp native code)
352 if (compiled_code->IsCode()) return true;
354 // We could potentially have marked this as flushable, but have kept
355 // a saved version if we did not flush it yet.
356 Object* saved_code = re->DataAt(JSRegExp::saved_code_index(is_ascii));
357 if (saved_code->IsCode()) {
358 // Reinstate the code in the original place.
359 re->SetDataAt(JSRegExp::code_index(is_ascii), saved_code);
360 ASSERT(compiled_code->IsSmi());
363 return CompileIrregexp(re, sample_subject, is_ascii);
367 static bool CreateRegExpErrorObjectAndThrow(Handle<JSRegExp> re,
369 Handle<String> error_message,
371 Factory* factory = isolate->factory();
372 Handle<FixedArray> elements = factory->NewFixedArray(2);
373 elements->set(0, re->Pattern());
374 elements->set(1, *error_message);
375 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
376 Handle<Object> regexp_err =
377 factory->NewSyntaxError("malformed_regexp", array);
378 isolate->Throw(*regexp_err);
383 bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re,
384 Handle<String> sample_subject,
386 // Compile the RegExp.
387 Isolate* isolate = re->GetIsolate();
388 ZoneScope zone_scope(isolate, DELETE_ON_EXIT);
389 PostponeInterruptsScope postpone(isolate);
390 // If we had a compilation error the last time this is saved at the
392 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
393 // When arriving here entry can only be a smi, either representing an
394 // uncompiled regexp, a previous compilation error, or code that has
396 ASSERT(entry->IsSmi());
397 int entry_value = Smi::cast(entry)->value();
398 ASSERT(entry_value == JSRegExp::kUninitializedValue ||
399 entry_value == JSRegExp::kCompilationErrorValue ||
400 (entry_value < JSRegExp::kCodeAgeMask && entry_value >= 0));
402 if (entry_value == JSRegExp::kCompilationErrorValue) {
403 // A previous compilation failed and threw an error which we store in
404 // the saved code index (we store the error message, not the actual
405 // error). Recreate the error object and throw it.
406 Object* error_string = re->DataAt(JSRegExp::saved_code_index(is_ascii));
407 ASSERT(error_string->IsString());
408 Handle<String> error_message(String::cast(error_string));
409 CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
413 JSRegExp::Flags flags = re->GetFlags();
415 Handle<String> pattern(re->Pattern());
416 if (!pattern->IsFlat()) FlattenString(pattern);
417 RegExpCompileData compile_data;
418 FlatStringReader reader(isolate, pattern);
419 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
421 // Throw an exception if we fail to parse the pattern.
422 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
423 ThrowRegExpException(re,
429 RegExpEngine::CompilationResult result =
430 RegExpEngine::Compile(&compile_data,
431 flags.is_ignore_case(),
432 flags.is_multiline(),
436 if (result.error_message != NULL) {
437 // Unable to compile regexp.
438 Handle<String> error_message =
439 isolate->factory()->NewStringFromUtf8(CStrVector(result.error_message));
440 CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
444 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
445 data->set(JSRegExp::code_index(is_ascii), result.code);
446 int register_max = IrregexpMaxRegisterCount(*data);
447 if (result.num_registers > register_max) {
448 SetIrregexpMaxRegisterCount(*data, result.num_registers);
455 int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
457 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
461 void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
462 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
466 int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
467 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
471 int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
472 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
476 ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
477 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
481 Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
482 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
486 void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
487 Handle<String> pattern,
488 JSRegExp::Flags flags,
490 // Initialize compiled code entries to null.
491 re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
499 int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
500 Handle<String> subject) {
501 if (!subject->IsFlat()) FlattenString(subject);
503 // Check the asciiness of the underlying storage.
504 bool is_ascii = subject->IsAsciiRepresentationUnderneath();
505 if (!EnsureCompiledIrregexp(regexp, subject, is_ascii)) return -1;
507 #ifdef V8_INTERPRETED_REGEXP
508 // Byte-code regexp needs space allocated for all its registers.
509 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
510 #else // V8_INTERPRETED_REGEXP
511 // Native regexp only needs room to output captures. Registers are handled
513 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
514 #endif // V8_INTERPRETED_REGEXP
518 RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(
519 Handle<JSRegExp> regexp,
520 Handle<String> subject,
522 Vector<int> output) {
523 Isolate* isolate = regexp->GetIsolate();
525 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
528 ASSERT(index <= subject->length());
529 ASSERT(subject->IsFlat());
531 bool is_ascii = subject->IsAsciiRepresentationUnderneath();
533 #ifndef V8_INTERPRETED_REGEXP
534 ASSERT(output.length() >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
536 EnsureCompiledIrregexp(regexp, subject, is_ascii);
537 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii), isolate);
538 NativeRegExpMacroAssembler::Result res =
539 NativeRegExpMacroAssembler::Match(code,
545 if (res != NativeRegExpMacroAssembler::RETRY) {
546 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
547 isolate->has_pending_exception());
549 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
551 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
552 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
554 return static_cast<IrregexpResult>(res);
556 // If result is RETRY, the string has changed representation, and we
557 // must restart from scratch.
558 // In this case, it means we must make sure we are prepared to handle
559 // the, potentially, different subject (the string can switch between
560 // being internal and external, and even between being ASCII and UC16,
561 // but the characters are always the same).
562 IrregexpPrepare(regexp, subject);
563 is_ascii = subject->IsAsciiRepresentationUnderneath();
567 #else // V8_INTERPRETED_REGEXP
569 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
570 // We must have done EnsureCompiledIrregexp, so we can get the number of
572 int* register_vector = output.start();
573 int number_of_capture_registers =
574 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
575 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
576 register_vector[i] = -1;
578 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii), isolate);
580 IrregexpResult result = IrregexpInterpreter::Match(isolate,
585 if (result == RE_EXCEPTION) {
586 ASSERT(!isolate->has_pending_exception());
587 isolate->StackOverflow();
590 #endif // V8_INTERPRETED_REGEXP
594 Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
595 Handle<String> subject,
597 Handle<JSArray> last_match_info) {
598 Isolate* isolate = jsregexp->GetIsolate();
599 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
601 // Prepare space for the return values.
602 #ifdef V8_INTERPRETED_REGEXP
604 if (FLAG_trace_regexp_bytecodes) {
605 String* pattern = jsregexp->Pattern();
606 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
607 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
611 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
612 if (required_registers < 0) {
613 // Compiling failed with an exception.
614 ASSERT(isolate->has_pending_exception());
615 return Handle<Object>::null();
618 OffsetsVector registers(required_registers, isolate);
620 IrregexpResult res = RegExpImpl::IrregexpExecOnce(
621 jsregexp, subject, previous_index, Vector<int>(registers.vector(),
622 registers.length()));
623 if (res == RE_SUCCESS) {
624 int capture_register_count =
625 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
626 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
627 AssertNoAllocation no_gc;
628 int* register_vector = registers.vector();
629 FixedArray* array = FixedArray::cast(last_match_info->elements());
630 for (int i = 0; i < capture_register_count; i += 2) {
631 SetCapture(array, i, register_vector[i]);
632 SetCapture(array, i + 1, register_vector[i + 1]);
634 SetLastCaptureCount(array, capture_register_count);
635 SetLastSubject(array, *subject);
636 SetLastInput(array, *subject);
637 return last_match_info;
639 if (res == RE_EXCEPTION) {
640 ASSERT(isolate->has_pending_exception());
641 return Handle<Object>::null();
643 ASSERT(res == RE_FAILURE);
644 return isolate->factory()->null_value();
648 // -------------------------------------------------------------------
649 // Implementation of the Irregexp regular expression engine.
651 // The Irregexp regular expression engine is intended to be a complete
652 // implementation of ECMAScript regular expressions. It generates either
653 // bytecodes or native code.
655 // The Irregexp regexp engine is structured in three steps.
656 // 1) The parser generates an abstract syntax tree. See ast.cc.
657 // 2) From the AST a node network is created. The nodes are all
658 // subclasses of RegExpNode. The nodes represent states when
659 // executing a regular expression. Several optimizations are
660 // performed on the node network.
661 // 3) From the nodes we generate either byte codes or native code
662 // that can actually execute the regular expression (perform
663 // the search). The code generation step is described in more
668 // The nodes are divided into four main categories.
670 // These represent places where the regular expression can
671 // match in more than one way. For example on entry to an
672 // alternation (foo|bar) or a repetition (*, +, ? or {}).
674 // These represent places where some action should be
675 // performed. Examples include recording the current position
676 // in the input string to a register (in order to implement
677 // captures) or other actions on register for example in order
678 // to implement the counters needed for {} repetitions.
680 // These attempt to match some element part of the input string.
681 // Examples of elements include character classes, plain strings
682 // or back references.
684 // These are used to implement the actions required on finding
685 // a successful match or failing to find a match.
687 // The code generated (whether as byte codes or native code) maintains
688 // some state as it runs. This consists of the following elements:
690 // * The capture registers. Used for string captures.
691 // * Other registers. Used for counters etc.
692 // * The current position.
693 // * The stack of backtracking information. Used when a matching node
694 // fails to find a match and needs to try an alternative.
696 // Conceptual regular expression execution model:
698 // There is a simple conceptual model of regular expression execution
699 // which will be presented first. The actual code generated is a more
700 // efficient simulation of the simple conceptual model:
702 // * Choice nodes are implemented as follows:
703 // For each choice except the last {
704 // push current position
705 // push backtrack code location
706 // <generate code to test for choice>
707 // backtrack code location:
708 // pop current position
710 // <generate code to test for last choice>
712 // * Actions nodes are generated as follows
713 // <push affected registers on backtrack stack>
714 // <generate code to perform action>
715 // push backtrack code location
716 // <generate code to test for following nodes>
717 // backtrack code location:
718 // <pop affected registers to restore their state>
719 // <pop backtrack location from stack and go to it>
721 // * Matching nodes are generated as follows:
722 // if input string matches at current position
723 // update current position
724 // <generate code to test for following nodes>
726 // <pop backtrack location from stack and go to it>
728 // Thus it can be seen that the current position is saved and restored
729 // by the choice nodes, whereas the registers are saved and restored by
730 // by the action nodes that manipulate them.
732 // The other interesting aspect of this model is that nodes are generated
733 // at the point where they are needed by a recursive call to Emit(). If
734 // the node has already been code generated then the Emit() call will
735 // generate a jump to the previously generated code instead. In order to
736 // limit recursion it is possible for the Emit() function to put the node
737 // on a work list for later generation and instead generate a jump. The
738 // destination of the jump is resolved later when the code is generated.
740 // Actual regular expression code generation.
742 // Code generation is actually more complicated than the above. In order
743 // to improve the efficiency of the generated code some optimizations are
746 // * Choice nodes have 1-character lookahead.
747 // A choice node looks at the following character and eliminates some of
748 // the choices immediately based on that character. This is not yet
750 // * Simple greedy loops store reduced backtracking information.
751 // A quantifier like /.*foo/m will greedily match the whole input. It will
752 // then need to backtrack to a point where it can match "foo". The naive
753 // implementation of this would push each character position onto the
754 // backtracking stack, then pop them off one by one. This would use space
755 // proportional to the length of the input string. However since the "."
756 // can only match in one way and always has a constant length (in this case
757 // of 1) it suffices to store the current position on the top of the stack
758 // once. Matching now becomes merely incrementing the current position and
759 // backtracking becomes decrementing the current position and checking the
760 // result against the stored current position. This is faster and saves
762 // * The current state is virtualized.
763 // This is used to defer expensive operations until it is clear that they
764 // are needed and to generate code for a node more than once, allowing
765 // specialized an efficient versions of the code to be created. This is
766 // explained in the section below.
768 // Execution state virtualization.
770 // Instead of emitting code, nodes that manipulate the state can record their
771 // manipulation in an object called the Trace. The Trace object can record a
772 // current position offset, an optional backtrack code location on the top of
773 // the virtualized backtrack stack and some register changes. When a node is
774 // to be emitted it can flush the Trace or update it. Flushing the Trace
775 // will emit code to bring the actual state into line with the virtual state.
776 // Avoiding flushing the state can postpone some work (e.g. updates of capture
777 // registers). Postponing work can save time when executing the regular
778 // expression since it may be found that the work never has to be done as a
779 // failure to match can occur. In addition it is much faster to jump to a
780 // known backtrack code location than it is to pop an unknown backtrack
781 // location from the stack and jump there.
783 // The virtual state found in the Trace affects code generation. For example
784 // the virtual state contains the difference between the actual current
785 // position and the virtual current position, and matching code needs to use
786 // this offset to attempt a match in the correct location of the input
787 // string. Therefore code generated for a non-trivial trace is specialized
788 // to that trace. The code generator therefore has the ability to generate
789 // code for each node several times. In order to limit the size of the
790 // generated code there is an arbitrary limit on how many specialized sets of
791 // code may be generated for a given node. If the limit is reached, the
792 // trace is flushed and a generic version of the code for a node is emitted.
793 // This is subsequently used for that node. The code emitted for non-generic
794 // trace is not recorded in the node and so it cannot currently be reused in
795 // the event that code generation is requested for an identical trace.
798 void RegExpTree::AppendToText(RegExpText* text) {
803 void RegExpAtom::AppendToText(RegExpText* text) {
804 text->AddElement(TextElement::Atom(this));
808 void RegExpCharacterClass::AppendToText(RegExpText* text) {
809 text->AddElement(TextElement::CharClass(this));
813 void RegExpText::AppendToText(RegExpText* text) {
814 for (int i = 0; i < elements()->length(); i++)
815 text->AddElement(elements()->at(i));
819 TextElement TextElement::Atom(RegExpAtom* atom) {
820 TextElement result = TextElement(ATOM);
821 result.data.u_atom = atom;
826 TextElement TextElement::CharClass(
827 RegExpCharacterClass* char_class) {
828 TextElement result = TextElement(CHAR_CLASS);
829 result.data.u_char_class = char_class;
834 int TextElement::length() {
836 return data.u_atom->length();
838 ASSERT(type == CHAR_CLASS);
844 DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
845 if (table_ == NULL) {
846 table_ = new DispatchTable();
847 DispatchTableConstructor cons(table_, ignore_case);
848 cons.BuildTable(this);
854 class FrequencyCollator {
856 FrequencyCollator() : total_samples_(0) {
857 for (int i = 0; i < RegExpMacroAssembler::kTableSize; i++) {
858 frequencies_[i] = CharacterFrequency(i);
862 void CountCharacter(int character) {
863 int index = (character & RegExpMacroAssembler::kTableMask);
864 frequencies_[index].Increment();
868 // Does not measure in percent, but rather per-128 (the table size from the
869 // regexp macro assembler).
870 int Frequency(int in_character) {
871 ASSERT((in_character & RegExpMacroAssembler::kTableMask) == in_character);
872 if (total_samples_ < 1) return 1; // Division by zero.
874 (frequencies_[in_character].counter() * 128) / total_samples_;
875 return freq_in_per128;
879 class CharacterFrequency {
881 CharacterFrequency() : counter_(0), character_(-1) { }
882 explicit CharacterFrequency(int character)
883 : counter_(0), character_(character) { }
885 void Increment() { counter_++; }
886 int counter() { return counter_; }
887 int character() { return character_; }
896 CharacterFrequency frequencies_[RegExpMacroAssembler::kTableSize];
901 class RegExpCompiler {
903 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
905 int AllocateRegister() {
906 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
907 reg_exp_too_big_ = true;
908 return next_register_;
910 return next_register_++;
913 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
916 Handle<String> pattern);
918 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
920 static const int kImplementationOffset = 0;
921 static const int kNumberOfRegistersOffset = 0;
922 static const int kCodeOffset = 1;
924 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
925 EndNode* accept() { return accept_; }
927 static const int kMaxRecursion = 100;
928 inline int recursion_depth() { return recursion_depth_; }
929 inline void IncrementRecursionDepth() { recursion_depth_++; }
930 inline void DecrementRecursionDepth() { recursion_depth_--; }
932 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
934 inline bool ignore_case() { return ignore_case_; }
935 inline bool ascii() { return ascii_; }
936 FrequencyCollator* frequency_collator() { return &frequency_collator_; }
938 int current_expansion_factor() { return current_expansion_factor_; }
939 void set_current_expansion_factor(int value) {
940 current_expansion_factor_ = value;
943 static const int kNoRegister = -1;
948 List<RegExpNode*>* work_list_;
949 int recursion_depth_;
950 RegExpMacroAssembler* macro_assembler_;
953 bool reg_exp_too_big_;
954 int current_expansion_factor_;
955 FrequencyCollator frequency_collator_;
959 class RecursionCheck {
961 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
962 compiler->IncrementRecursionDepth();
964 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
966 RegExpCompiler* compiler_;
970 static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
971 return RegExpEngine::CompilationResult("RegExp too big");
975 // Attempts to compile the regexp using an Irregexp code generator. Returns
976 // a fixed array or a null handle depending on whether it succeeded.
977 RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
978 : next_register_(2 * (capture_count + 1)),
981 ignore_case_(ignore_case),
983 reg_exp_too_big_(false),
984 current_expansion_factor_(1),
985 frequency_collator_() {
986 accept_ = new EndNode(EndNode::ACCEPT);
987 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
991 RegExpEngine::CompilationResult RegExpCompiler::Assemble(
992 RegExpMacroAssembler* macro_assembler,
995 Handle<String> pattern) {
996 Heap* heap = pattern->GetHeap();
998 bool use_slow_safe_regexp_compiler = false;
999 if (heap->total_regexp_code_generated() >
1000 RegExpImpl::kRegWxpCompiledLimit &&
1001 heap->isolate()->memory_allocator()->SizeExecutable() >
1002 RegExpImpl::kRegExpExecutableMemoryLimit) {
1003 use_slow_safe_regexp_compiler = true;
1006 macro_assembler->set_slow_safe(use_slow_safe_regexp_compiler);
1009 if (FLAG_trace_regexp_assembler)
1010 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
1013 macro_assembler_ = macro_assembler;
1015 List <RegExpNode*> work_list(0);
1016 work_list_ = &work_list;
1018 macro_assembler_->PushBacktrack(&fail);
1020 start->Emit(this, &new_trace);
1021 macro_assembler_->Bind(&fail);
1022 macro_assembler_->Fail();
1023 while (!work_list.is_empty()) {
1024 work_list.RemoveLast()->Emit(this, &new_trace);
1026 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
1028 Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
1029 heap->IncreaseTotalRegexpCodeGenerated(code->Size());
1032 if (FLAG_print_code) {
1033 Handle<Code>::cast(code)->Disassemble(*pattern->ToCString());
1035 if (FLAG_trace_regexp_assembler) {
1036 delete macro_assembler_;
1039 return RegExpEngine::CompilationResult(*code, next_register_);
1043 bool Trace::DeferredAction::Mentions(int that) {
1044 if (type() == ActionNode::CLEAR_CAPTURES) {
1045 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
1046 return range.Contains(that);
1048 return reg() == that;
1053 bool Trace::mentions_reg(int reg) {
1054 for (DeferredAction* action = actions_;
1056 action = action->next()) {
1057 if (action->Mentions(reg))
1064 bool Trace::GetStoredPosition(int reg, int* cp_offset) {
1065 ASSERT_EQ(0, *cp_offset);
1066 for (DeferredAction* action = actions_;
1068 action = action->next()) {
1069 if (action->Mentions(reg)) {
1070 if (action->type() == ActionNode::STORE_POSITION) {
1071 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
1082 int Trace::FindAffectedRegisters(OutSet* affected_registers) {
1083 int max_register = RegExpCompiler::kNoRegister;
1084 for (DeferredAction* action = actions_;
1086 action = action->next()) {
1087 if (action->type() == ActionNode::CLEAR_CAPTURES) {
1088 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
1089 for (int i = range.from(); i <= range.to(); i++)
1090 affected_registers->Set(i);
1091 if (range.to() > max_register) max_register = range.to();
1093 affected_registers->Set(action->reg());
1094 if (action->reg() > max_register) max_register = action->reg();
1097 return max_register;
1101 void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
1103 OutSet& registers_to_pop,
1104 OutSet& registers_to_clear) {
1105 for (int reg = max_register; reg >= 0; reg--) {
1106 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
1107 else if (registers_to_clear.Get(reg)) {
1109 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
1112 assembler->ClearRegisters(reg, clear_to);
1118 void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
1120 OutSet& affected_registers,
1121 OutSet* registers_to_pop,
1122 OutSet* registers_to_clear) {
1123 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
1124 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
1126 // Count pushes performed to force a stack limit check occasionally.
1129 for (int reg = 0; reg <= max_register; reg++) {
1130 if (!affected_registers.Get(reg)) {
1134 // The chronologically first deferred action in the trace
1135 // is used to infer the action needed to restore a register
1136 // to its previous state (or not, if it's safe to ignore it).
1137 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
1138 DeferredActionUndoType undo_action = IGNORE;
1141 bool absolute = false;
1143 int store_position = -1;
1144 // This is a little tricky because we are scanning the actions in reverse
1145 // historical order (newest first).
1146 for (DeferredAction* action = actions_;
1148 action = action->next()) {
1149 if (action->Mentions(reg)) {
1150 switch (action->type()) {
1151 case ActionNode::SET_REGISTER: {
1152 Trace::DeferredSetRegister* psr =
1153 static_cast<Trace::DeferredSetRegister*>(action);
1155 value += psr->value();
1158 // SET_REGISTER is currently only used for newly introduced loop
1159 // counters. They can have a significant previous value if they
1160 // occour in a loop. TODO(lrn): Propagate this information, so
1161 // we can set undo_action to IGNORE if we know there is no value to
1163 undo_action = RESTORE;
1164 ASSERT_EQ(store_position, -1);
1168 case ActionNode::INCREMENT_REGISTER:
1172 ASSERT_EQ(store_position, -1);
1174 undo_action = RESTORE;
1176 case ActionNode::STORE_POSITION: {
1177 Trace::DeferredCapture* pc =
1178 static_cast<Trace::DeferredCapture*>(action);
1179 if (!clear && store_position == -1) {
1180 store_position = pc->cp_offset();
1183 // For captures we know that stores and clears alternate.
1184 // Other register, are never cleared, and if the occur
1185 // inside a loop, they might be assigned more than once.
1187 // Registers zero and one, aka "capture zero", is
1188 // always set correctly if we succeed. There is no
1189 // need to undo a setting on backtrack, because we
1190 // will set it again or fail.
1191 undo_action = IGNORE;
1193 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1196 ASSERT_EQ(value, 0);
1199 case ActionNode::CLEAR_CAPTURES: {
1200 // Since we're scanning in reverse order, if we've already
1201 // set the position we have to ignore historically earlier
1202 // clearing operations.
1203 if (store_position == -1) {
1206 undo_action = RESTORE;
1208 ASSERT_EQ(value, 0);
1217 // Prepare for the undo-action (e.g., push if it's going to be popped).
1218 if (undo_action == RESTORE) {
1220 RegExpMacroAssembler::StackCheckFlag stack_check =
1221 RegExpMacroAssembler::kNoStackLimitCheck;
1222 if (pushes == push_limit) {
1223 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1227 assembler->PushRegister(reg, stack_check);
1228 registers_to_pop->Set(reg);
1229 } else if (undo_action == CLEAR) {
1230 registers_to_clear->Set(reg);
1232 // Perform the chronologically last action (or accumulated increment)
1233 // for the register.
1234 if (store_position != -1) {
1235 assembler->WriteCurrentPositionToRegister(reg, store_position);
1237 assembler->ClearRegisters(reg, reg);
1238 } else if (absolute) {
1239 assembler->SetRegister(reg, value);
1240 } else if (value != 0) {
1241 assembler->AdvanceRegister(reg, value);
1247 // This is called as we come into a loop choice node and some other tricky
1248 // nodes. It normalizes the state of the code generator to ensure we can
1249 // generate generic code.
1250 void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
1251 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1253 ASSERT(!is_trivial());
1255 if (actions_ == NULL && backtrack() == NULL) {
1256 // Here we just have some deferred cp advances to fix and we are back to
1257 // a normal situation. We may also have to forget some information gained
1258 // through a quick check that was already performed.
1259 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
1260 // Create a new trivial state and generate the node with that.
1262 successor->Emit(compiler, &new_state);
1266 // Generate deferred actions here along with code to undo them again.
1267 OutSet affected_registers;
1269 if (backtrack() != NULL) {
1270 // Here we have a concrete backtrack location. These are set up by choice
1271 // nodes and so they indicate that we have a deferred save of the current
1272 // position which we may need to emit here.
1273 assembler->PushCurrentPosition();
1276 int max_register = FindAffectedRegisters(&affected_registers);
1277 OutSet registers_to_pop;
1278 OutSet registers_to_clear;
1279 PerformDeferredActions(assembler,
1283 ®isters_to_clear);
1284 if (cp_offset_ != 0) {
1285 assembler->AdvanceCurrentPosition(cp_offset_);
1288 // Create a new trivial state and generate the node with that.
1290 assembler->PushBacktrack(&undo);
1292 successor->Emit(compiler, &new_state);
1294 // On backtrack we need to restore state.
1295 assembler->Bind(&undo);
1296 RestoreAffectedRegisters(assembler,
1299 registers_to_clear);
1300 if (backtrack() == NULL) {
1301 assembler->Backtrack();
1303 assembler->PopCurrentPosition();
1304 assembler->GoTo(backtrack());
1309 void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
1310 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1312 // Omit flushing the trace. We discard the entire stack frame anyway.
1314 if (!label()->is_bound()) {
1315 // We are completely independent of the trace, since we ignore it,
1316 // so this code can be used as the generic version.
1317 assembler->Bind(label());
1320 // Throw away everything on the backtrack stack since the start
1321 // of the negative submatch and restore the character position.
1322 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1323 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
1324 if (clear_capture_count_ > 0) {
1325 // Clear any captures that might have been performed during the success
1326 // of the body of the negative look-ahead.
1327 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1328 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1330 // Now that we have unwound the stack we find at the top of the stack the
1331 // backtrack that the BeginSubmatch node got.
1332 assembler->Backtrack();
1336 void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
1337 if (!trace->is_trivial()) {
1338 trace->Flush(compiler, this);
1341 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1342 if (!label()->is_bound()) {
1343 assembler->Bind(label());
1347 assembler->Succeed();
1350 assembler->GoTo(trace->backtrack());
1352 case NEGATIVE_SUBMATCH_SUCCESS:
1353 // This case is handled in a different virtual method.
1360 void GuardedAlternative::AddGuard(Guard* guard) {
1361 if (guards_ == NULL)
1362 guards_ = new ZoneList<Guard*>(1);
1363 guards_->Add(guard);
1367 ActionNode* ActionNode::SetRegister(int reg,
1369 RegExpNode* on_success) {
1370 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
1371 result->data_.u_store_register.reg = reg;
1372 result->data_.u_store_register.value = val;
1377 ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1378 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1379 result->data_.u_increment_register.reg = reg;
1384 ActionNode* ActionNode::StorePosition(int reg,
1386 RegExpNode* on_success) {
1387 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1388 result->data_.u_position_register.reg = reg;
1389 result->data_.u_position_register.is_capture = is_capture;
1394 ActionNode* ActionNode::ClearCaptures(Interval range,
1395 RegExpNode* on_success) {
1396 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1397 result->data_.u_clear_captures.range_from = range.from();
1398 result->data_.u_clear_captures.range_to = range.to();
1403 ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1405 RegExpNode* on_success) {
1406 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1407 result->data_.u_submatch.stack_pointer_register = stack_reg;
1408 result->data_.u_submatch.current_position_register = position_reg;
1413 ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1415 int clear_register_count,
1416 int clear_register_from,
1417 RegExpNode* on_success) {
1418 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
1419 result->data_.u_submatch.stack_pointer_register = stack_reg;
1420 result->data_.u_submatch.current_position_register = position_reg;
1421 result->data_.u_submatch.clear_register_count = clear_register_count;
1422 result->data_.u_submatch.clear_register_from = clear_register_from;
1427 ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1428 int repetition_register,
1429 int repetition_limit,
1430 RegExpNode* on_success) {
1431 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1432 result->data_.u_empty_match_check.start_register = start_register;
1433 result->data_.u_empty_match_check.repetition_register = repetition_register;
1434 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1439 #define DEFINE_ACCEPT(Type) \
1440 void Type##Node::Accept(NodeVisitor* visitor) { \
1441 visitor->Visit##Type(this); \
1443 FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1444 #undef DEFINE_ACCEPT
1447 void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1448 visitor->VisitLoopChoice(this);
1452 // -------------------------------------------------------------------
1456 void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1459 switch (guard->op()) {
1461 ASSERT(!trace->mentions_reg(guard->reg()));
1462 macro_assembler->IfRegisterGE(guard->reg(),
1464 trace->backtrack());
1467 ASSERT(!trace->mentions_reg(guard->reg()));
1468 macro_assembler->IfRegisterLT(guard->reg(),
1470 trace->backtrack());
1476 // Returns the number of characters in the equivalence class, omitting those
1477 // that cannot occur in the source string because it is ASCII.
1478 static int GetCaseIndependentLetters(Isolate* isolate,
1481 unibrow::uchar* letters) {
1483 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
1484 // Unibrow returns 0 or 1 for characters where case independence is
1487 letters[0] = character;
1490 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1493 // The standard requires that non-ASCII characters cannot have ASCII
1494 // character codes in their equivalence class.
1499 static inline bool EmitSimpleCharacter(Isolate* isolate,
1500 RegExpCompiler* compiler,
1506 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1507 bool bound_checked = false;
1509 assembler->LoadCurrentCharacter(
1513 bound_checked = true;
1515 assembler->CheckNotCharacter(c, on_failure);
1516 return bound_checked;
1520 // Only emits non-letters (things that don't have case). Only used for case
1521 // independent matches.
1522 static inline bool EmitAtomNonLetter(Isolate* isolate,
1523 RegExpCompiler* compiler,
1529 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1530 bool ascii = compiler->ascii();
1531 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1532 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
1534 // This can't match. Must be an ASCII subject and a non-ASCII character.
1535 // We do not need to do anything since the ASCII pass already handled this.
1536 return false; // Bounds not checked.
1538 bool checked = false;
1539 // We handle the length > 1 case in a later pass.
1541 if (ascii && c > String::kMaxAsciiCharCodeU) {
1542 // Can't match - see above.
1543 return false; // Bounds not checked.
1546 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1549 macro_assembler->CheckNotCharacter(c, on_failure);
1555 static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
1559 Label* on_failure) {
1562 char_mask = String::kMaxAsciiCharCode;
1564 char_mask = String::kMaxUtf16CodeUnit;
1566 uc16 exor = c1 ^ c2;
1567 // Check whether exor has only one bit set.
1568 if (((exor - 1) & exor) == 0) {
1569 // If c1 and c2 differ only by one bit.
1570 // Ecma262UnCanonicalize always gives the highest number last.
1572 uc16 mask = char_mask ^ exor;
1573 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
1577 uc16 diff = c2 - c1;
1578 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1579 // If the characters differ by 2^n but don't differ by one bit then
1580 // subtract the difference from the found character, then do the or
1581 // trick. We avoid the theoretical case where negative numbers are
1582 // involved in order to simplify code generation.
1583 uc16 mask = char_mask ^ diff;
1584 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1594 typedef bool EmitCharacterFunction(Isolate* isolate,
1595 RegExpCompiler* compiler,
1602 // Only emits letters (things that have case). Only used for case independent
1604 static inline bool EmitAtomLetter(Isolate* isolate,
1605 RegExpCompiler* compiler,
1611 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1612 bool ascii = compiler->ascii();
1613 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1614 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
1615 if (length <= 1) return false;
1616 // We may not need to check against the end of the input string
1617 // if this character lies before a character that matched.
1619 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1622 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1625 if (ShortCutEmitCharacterPair(macro_assembler,
1631 macro_assembler->CheckCharacter(chars[0], &ok);
1632 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1633 macro_assembler->Bind(&ok);
1638 macro_assembler->CheckCharacter(chars[3], &ok);
1641 macro_assembler->CheckCharacter(chars[0], &ok);
1642 macro_assembler->CheckCharacter(chars[1], &ok);
1643 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1644 macro_assembler->Bind(&ok);
1654 static void EmitBoundaryTest(RegExpMacroAssembler* masm,
1656 Label* fall_through,
1657 Label* above_or_equal,
1659 if (below != fall_through) {
1660 masm->CheckCharacterLT(border, below);
1661 if (above_or_equal != fall_through) masm->GoTo(above_or_equal);
1663 masm->CheckCharacterGT(border - 1, above_or_equal);
1668 static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm,
1671 Label* fall_through,
1673 Label* out_of_range) {
1674 if (in_range == fall_through) {
1675 if (first == last) {
1676 masm->CheckNotCharacter(first, out_of_range);
1678 masm->CheckCharacterNotInRange(first, last, out_of_range);
1681 if (first == last) {
1682 masm->CheckCharacter(first, in_range);
1684 masm->CheckCharacterInRange(first, last, in_range);
1686 if (out_of_range != fall_through) masm->GoTo(out_of_range);
1691 // even_label is for ranges[i] to ranges[i + 1] where i - start_index is even.
1692 // odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd.
1693 static void EmitUseLookupTable(
1694 RegExpMacroAssembler* masm,
1695 ZoneList<int>* ranges,
1699 Label* fall_through,
1702 static const int kSize = RegExpMacroAssembler::kTableSize;
1703 static const int kMask = RegExpMacroAssembler::kTableMask;
1705 int base = (min_char & ~kMask);
1708 // Assert that everything is on one kTableSize page.
1709 for (int i = start_index; i <= end_index; i++) {
1710 ASSERT_EQ(ranges->at(i) & ~kMask, base);
1712 ASSERT(start_index == 0 || (ranges->at(start_index - 1) & ~kMask) <= base);
1716 Label* on_bit_clear;
1718 if (even_label == fall_through) {
1719 on_bit_set = odd_label;
1720 on_bit_clear = even_label;
1723 on_bit_set = even_label;
1724 on_bit_clear = odd_label;
1727 for (int i = 0; i < (ranges->at(start_index) & kMask) && i < kSize; i++) {
1732 for (int i = start_index; i < end_index; i++) {
1733 for (j = (ranges->at(i) & kMask); j < (ranges->at(i + 1) & kMask); j++) {
1738 for (int i = j; i < kSize; i++) {
1741 // TODO(erikcorry): Cache these.
1742 Handle<ByteArray> ba = FACTORY->NewByteArray(kSize, TENURED);
1743 for (int i = 0; i < kSize; i++) {
1744 ba->set(i, templ[i]);
1746 masm->CheckBitInTable(ba, on_bit_set);
1747 if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear);
1751 static void CutOutRange(RegExpMacroAssembler* masm,
1752 ZoneList<int>* ranges,
1758 bool odd = (((cut_index - start_index) & 1) == 1);
1759 Label* in_range_label = odd ? odd_label : even_label;
1761 EmitDoubleBoundaryTest(masm,
1762 ranges->at(cut_index),
1763 ranges->at(cut_index + 1) - 1,
1767 ASSERT(!dummy.is_linked());
1768 // Cut out the single range by rewriting the array. This creates a new
1769 // range that is a merger of the two ranges on either side of the one we
1770 // are cutting out. The oddity of the labels is preserved.
1771 for (int j = cut_index; j > start_index; j--) {
1772 ranges->at(j) = ranges->at(j - 1);
1774 for (int j = cut_index + 1; j < end_index; j++) {
1775 ranges->at(j) = ranges->at(j + 1);
1780 // Unicode case. Split the search space into kSize spaces that are handled
1782 static void SplitSearchSpace(ZoneList<int>* ranges,
1785 int* new_start_index,
1788 static const int kSize = RegExpMacroAssembler::kTableSize;
1789 static const int kMask = RegExpMacroAssembler::kTableMask;
1791 int first = ranges->at(start_index);
1792 int last = ranges->at(end_index) - 1;
1794 *new_start_index = start_index;
1795 *border = (ranges->at(start_index) & ~kMask) + kSize;
1796 while (*new_start_index < end_index) {
1797 if (ranges->at(*new_start_index) > *border) break;
1798 (*new_start_index)++;
1800 // new_start_index is the index of the first edge that is beyond the
1801 // current kSize space.
1803 // For very large search spaces we do a binary chop search of the non-ASCII
1804 // space instead of just going to the end of the current kSize space. The
1805 // heuristics are complicated a little by the fact that any 128-character
1806 // encoding space can be quickly tested with a table lookup, so we don't
1807 // wish to do binary chop search at a smaller granularity than that. A
1808 // 128-character space can take up a lot of space in the ranges array if,
1809 // for example, we only want to match every second character (eg. the lower
1810 // case characters on some Unicode pages).
1811 int binary_chop_index = (end_index + start_index) / 2;
1812 // The first test ensures that we get to the code that handles the ASCII
1813 // range with a single not-taken branch, speeding up this important
1814 // character range (even non-ASCII charset-based text has spaces and
1816 if (*border - 1 > String::kMaxAsciiCharCode && // ASCII case.
1817 end_index - start_index > (*new_start_index - start_index) * 2 &&
1818 last - first > kSize * 2 &&
1819 binary_chop_index > *new_start_index &&
1820 ranges->at(binary_chop_index) >= first + 2 * kSize) {
1821 int scan_forward_for_section_border = binary_chop_index;;
1822 int new_border = (ranges->at(binary_chop_index) | kMask) + 1;
1824 while (scan_forward_for_section_border < end_index) {
1825 if (ranges->at(scan_forward_for_section_border) > new_border) {
1826 *new_start_index = scan_forward_for_section_border;
1827 *border = new_border;
1830 scan_forward_for_section_border++;
1834 ASSERT(*new_start_index > start_index);
1835 *new_end_index = *new_start_index - 1;
1836 if (ranges->at(*new_end_index) == *border) {
1839 if (*border >= ranges->at(end_index)) {
1840 *border = ranges->at(end_index);
1841 *new_start_index = end_index; // Won't be used.
1842 *new_end_index = end_index - 1;
1847 // Gets a series of segment boundaries representing a character class. If the
1848 // character is in the range between an even and an odd boundary (counting from
1849 // start_index) then go to even_label, otherwise go to odd_label. We already
1850 // know that the character is in the range of min_char to max_char inclusive.
1851 // Either label can be NULL indicating backtracking. Either label can also be
1852 // equal to the fall_through label.
1853 static void GenerateBranches(RegExpMacroAssembler* masm,
1854 ZoneList<int>* ranges,
1859 Label* fall_through,
1862 int first = ranges->at(start_index);
1863 int last = ranges->at(end_index) - 1;
1865 ASSERT_LT(min_char, first);
1867 // Just need to test if the character is before or on-or-after
1868 // a particular character.
1869 if (start_index == end_index) {
1870 EmitBoundaryTest(masm, first, fall_through, even_label, odd_label);
1874 // Another almost trivial case: There is one interval in the middle that is
1875 // different from the end intervals.
1876 if (start_index + 1 == end_index) {
1877 EmitDoubleBoundaryTest(
1878 masm, first, last, fall_through, even_label, odd_label);
1882 // It's not worth using table lookup if there are very few intervals in the
1884 if (end_index - start_index <= 6) {
1885 // It is faster to test for individual characters, so we look for those
1886 // first, then try arbitrary ranges in the second round.
1887 static int kNoCutIndex = -1;
1888 int cut = kNoCutIndex;
1889 for (int i = start_index; i < end_index; i++) {
1890 if (ranges->at(i) == ranges->at(i + 1) - 1) {
1895 if (cut == kNoCutIndex) cut = start_index;
1897 masm, ranges, start_index, end_index, cut, even_label, odd_label);
1898 ASSERT_GE(end_index - start_index, 2);
1899 GenerateBranches(masm,
1911 // If there are a lot of intervals in the regexp, then we will use tables to
1912 // determine whether the character is inside or outside the character class.
1913 static const int kBits = RegExpMacroAssembler::kTableSizeBits;
1915 if ((max_char >> kBits) == (min_char >> kBits)) {
1916 EmitUseLookupTable(masm,
1927 if ((min_char >> kBits) != (first >> kBits)) {
1928 masm->CheckCharacterLT(first, odd_label);
1929 GenerateBranches(masm,
1941 int new_start_index = 0;
1942 int new_end_index = 0;
1945 SplitSearchSpace(ranges,
1953 Label* above = &handle_rest;
1954 if (border == last + 1) {
1955 // We didn't find any section that started after the limit, so everything
1956 // above the border is one of the terminal labels.
1957 above = (end_index & 1) != (start_index & 1) ? odd_label : even_label;
1958 ASSERT(new_end_index == end_index - 1);
1961 ASSERT_LE(start_index, new_end_index);
1962 ASSERT_LE(new_start_index, end_index);
1963 ASSERT_LT(start_index, new_start_index);
1964 ASSERT_LT(new_end_index, end_index);
1965 ASSERT(new_end_index + 1 == new_start_index ||
1966 (new_end_index + 2 == new_start_index &&
1967 border == ranges->at(new_end_index + 1)));
1968 ASSERT_LT(min_char, border - 1);
1969 ASSERT_LT(border, max_char);
1970 ASSERT_LT(ranges->at(new_end_index), border);
1971 ASSERT(border < ranges->at(new_start_index) ||
1972 (border == ranges->at(new_start_index) &&
1973 new_start_index == end_index &&
1974 new_end_index == end_index - 1 &&
1975 border == last + 1));
1976 ASSERT(new_start_index == 0 || border >= ranges->at(new_start_index - 1));
1978 masm->CheckCharacterGT(border - 1, above);
1980 GenerateBranches(masm,
1989 if (handle_rest.is_linked()) {
1990 masm->Bind(&handle_rest);
1991 bool flip = (new_start_index & 1) != (start_index & 1);
1992 GenerateBranches(masm,
1999 flip ? odd_label : even_label,
2000 flip ? even_label : odd_label);
2005 static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
2006 RegExpCharacterClass* cc,
2012 ZoneList<CharacterRange>* ranges = cc->ranges();
2013 if (!CharacterRange::IsCanonical(ranges)) {
2014 CharacterRange::Canonicalize(ranges);
2019 max_char = String::kMaxAsciiCharCode;
2021 max_char = String::kMaxUtf16CodeUnit;
2024 int range_count = ranges->length();
2026 int last_valid_range = range_count - 1;
2027 while (last_valid_range >= 0) {
2028 CharacterRange& range = ranges->at(last_valid_range);
2029 if (range.from() <= max_char) {
2035 if (last_valid_range < 0) {
2036 if (!cc->is_negated()) {
2037 macro_assembler->GoTo(on_failure);
2040 macro_assembler->CheckPosition(cp_offset, on_failure);
2045 if (last_valid_range == 0 &&
2046 ranges->at(0).IsEverything(max_char)) {
2047 if (cc->is_negated()) {
2048 macro_assembler->GoTo(on_failure);
2050 // This is a common case hit by non-anchored expressions.
2052 macro_assembler->CheckPosition(cp_offset, on_failure);
2057 if (last_valid_range == 0 &&
2058 !cc->is_negated() &&
2059 ranges->at(0).IsEverything(max_char)) {
2060 // This is a common case hit by non-anchored expressions.
2062 macro_assembler->CheckPosition(cp_offset, on_failure);
2068 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
2071 if (cc->is_standard() &&
2072 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
2078 // A new list with ascending entries. Each entry is a code unit
2079 // where there is a boundary between code units that are part of
2080 // the class and code units that are not. Normally we insert an
2081 // entry at zero which goes to the failure label, but if there
2082 // was already one there we fall through for success on that entry.
2083 // Subsequent entries have alternating meaning (success/failure).
2084 ZoneList<int>* range_boundaries = new ZoneList<int>(last_valid_range);
2086 bool zeroth_entry_is_failure = !cc->is_negated();
2088 for (int i = 0; i <= last_valid_range; i++) {
2089 CharacterRange& range = ranges->at(i);
2090 if (range.from() == 0) {
2092 zeroth_entry_is_failure = !zeroth_entry_is_failure;
2094 range_boundaries->Add(range.from());
2096 range_boundaries->Add(range.to() + 1);
2098 int end_index = range_boundaries->length() - 1;
2099 if (range_boundaries->at(end_index) > max_char) {
2104 GenerateBranches(macro_assembler,
2111 zeroth_entry_is_failure ? &fall_through : on_failure,
2112 zeroth_entry_is_failure ? on_failure : &fall_through);
2113 macro_assembler->Bind(&fall_through);
2117 RegExpNode::~RegExpNode() {
2121 RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
2123 // If we are generating a greedy loop then don't stop and don't reuse code.
2124 if (trace->stop_node() != NULL) {
2128 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2129 if (trace->is_trivial()) {
2130 if (label_.is_bound()) {
2131 // We are being asked to generate a generic version, but that's already
2132 // been done so just go to it.
2133 macro_assembler->GoTo(&label_);
2136 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
2137 // To avoid too deep recursion we push the node to the work queue and just
2138 // generate a goto here.
2139 compiler->AddWork(this);
2140 macro_assembler->GoTo(&label_);
2143 // Generate generic version of the node and bind the label for later use.
2144 macro_assembler->Bind(&label_);
2148 // We are being asked to make a non-generic version. Keep track of how many
2149 // non-generic versions we generate so as not to overdo it.
2151 if (FLAG_regexp_optimization &&
2152 trace_count_ < kMaxCopiesCodeGenerated &&
2153 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
2157 // If we get here code has been generated for this node too many times or
2158 // recursion is too deep. Time to switch to a generic version. The code for
2159 // generic versions above can handle deep recursion properly.
2160 trace->Flush(compiler, this);
2165 int ActionNode::EatsAtLeast(int still_to_find,
2166 int recursion_depth,
2167 bool not_at_start) {
2168 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
2169 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
2170 return on_success()->EatsAtLeast(still_to_find,
2171 recursion_depth + 1,
2176 void ActionNode::FillInBMInfo(int offset,
2177 BoyerMooreLookahead* bm,
2178 bool not_at_start) {
2179 if (type_ == BEGIN_SUBMATCH) {
2180 bm->SetRest(offset);
2181 } else if (type_ != POSITIVE_SUBMATCH_SUCCESS) {
2182 on_success()->FillInBMInfo(offset, bm, not_at_start);
2184 SaveBMInfo(bm, not_at_start, offset);
2188 int AssertionNode::EatsAtLeast(int still_to_find,
2189 int recursion_depth,
2190 bool not_at_start) {
2191 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
2192 // If we know we are not at the start and we are asked "how many characters
2193 // will you match if you succeed?" then we can answer anything since false
2194 // implies false. So lets just return the max answer (still_to_find) since
2195 // that won't prevent us from preloading a lot of characters for the other
2196 // branches in the node graph.
2197 if (type() == AT_START && not_at_start) return still_to_find;
2198 return on_success()->EatsAtLeast(still_to_find,
2199 recursion_depth + 1,
2204 void AssertionNode::FillInBMInfo(
2205 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
2206 // Match the behaviour of EatsAtLeast on this node.
2207 if (type() == AT_START && not_at_start) return;
2208 on_success()->FillInBMInfo(offset, bm, not_at_start);
2209 SaveBMInfo(bm, not_at_start, offset);
2213 int BackReferenceNode::EatsAtLeast(int still_to_find,
2214 int recursion_depth,
2215 bool not_at_start) {
2216 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
2217 return on_success()->EatsAtLeast(still_to_find,
2218 recursion_depth + 1,
2223 int TextNode::EatsAtLeast(int still_to_find,
2224 int recursion_depth,
2225 bool not_at_start) {
2226 int answer = Length();
2227 if (answer >= still_to_find) return answer;
2228 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
2229 // We are not at start after this node so we set the last argument to 'true'.
2230 return answer + on_success()->EatsAtLeast(still_to_find - answer,
2231 recursion_depth + 1,
2236 int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
2237 int recursion_depth,
2238 bool not_at_start) {
2239 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
2240 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2242 RegExpNode* node = alternatives_->at(1).node();
2243 return node->EatsAtLeast(still_to_find, recursion_depth + 1, not_at_start);
2247 void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
2248 QuickCheckDetails* details,
2249 RegExpCompiler* compiler,
2251 bool not_at_start) {
2252 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2254 RegExpNode* node = alternatives_->at(1).node();
2255 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
2259 int ChoiceNode::EatsAtLeastHelper(int still_to_find,
2260 int recursion_depth,
2261 RegExpNode* ignore_this_node,
2262 bool not_at_start) {
2263 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
2265 int choice_count = alternatives_->length();
2266 for (int i = 0; i < choice_count; i++) {
2267 RegExpNode* node = alternatives_->at(i).node();
2268 if (node == ignore_this_node) continue;
2269 int node_eats_at_least = node->EatsAtLeast(still_to_find,
2270 recursion_depth + 1,
2272 if (node_eats_at_least < min) min = node_eats_at_least;
2278 int LoopChoiceNode::EatsAtLeast(int still_to_find,
2279 int recursion_depth,
2280 bool not_at_start) {
2281 return EatsAtLeastHelper(still_to_find,
2288 int ChoiceNode::EatsAtLeast(int still_to_find,
2289 int recursion_depth,
2290 bool not_at_start) {
2291 return EatsAtLeastHelper(still_to_find,
2298 // Takes the left-most 1-bit and smears it out, setting all bits to its right.
2299 static inline uint32_t SmearBitsRight(uint32_t v) {
2309 bool QuickCheckDetails::Rationalize(bool asc) {
2310 bool found_useful_op = false;
2313 char_mask = String::kMaxAsciiCharCode;
2315 char_mask = String::kMaxUtf16CodeUnit;
2320 for (int i = 0; i < characters_; i++) {
2321 Position* pos = &positions_[i];
2322 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
2323 found_useful_op = true;
2325 mask_ |= (pos->mask & char_mask) << char_shift;
2326 value_ |= (pos->value & char_mask) << char_shift;
2327 char_shift += asc ? 8 : 16;
2329 return found_useful_op;
2333 bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
2335 bool preload_has_checked_bounds,
2336 Label* on_possible_success,
2337 QuickCheckDetails* details,
2338 bool fall_through_on_failure) {
2339 if (details->characters() == 0) return false;
2340 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
2341 if (details->cannot_match()) return false;
2342 if (!details->Rationalize(compiler->ascii())) return false;
2343 ASSERT(details->characters() == 1 ||
2344 compiler->macro_assembler()->CanReadUnaligned());
2345 uint32_t mask = details->mask();
2346 uint32_t value = details->value();
2348 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2350 if (trace->characters_preloaded() != details->characters()) {
2351 assembler->LoadCurrentCharacter(trace->cp_offset(),
2353 !preload_has_checked_bounds,
2354 details->characters());
2358 bool need_mask = true;
2360 if (details->characters() == 1) {
2361 // If number of characters preloaded is 1 then we used a byte or 16 bit
2362 // load so the value is already masked down.
2364 if (compiler->ascii()) {
2365 char_mask = String::kMaxAsciiCharCode;
2367 char_mask = String::kMaxUtf16CodeUnit;
2369 if ((mask & char_mask) == char_mask) need_mask = false;
2372 // For 2-character preloads in ASCII mode or 1-character preloads in
2373 // TWO_BYTE mode we also use a 16 bit load with zero extend.
2374 if (details->characters() == 2 && compiler->ascii()) {
2375 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
2376 } else if (details->characters() == 1 && !compiler->ascii()) {
2377 if ((mask & 0xffff) == 0xffff) need_mask = false;
2379 if (mask == 0xffffffff) need_mask = false;
2383 if (fall_through_on_failure) {
2385 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
2387 assembler->CheckCharacter(value, on_possible_success);
2391 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
2393 assembler->CheckNotCharacter(value, trace->backtrack());
2400 // Here is the meat of GetQuickCheckDetails (see also the comment on the
2401 // super-class in the .h file).
2403 // We iterate along the text object, building up for each character a
2404 // mask and value that can be used to test for a quick failure to match.
2405 // The masks and values for the positions will be combined into a single
2406 // machine word for the current character width in order to be used in
2407 // generating a quick check.
2408 void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
2409 RegExpCompiler* compiler,
2410 int characters_filled_in,
2411 bool not_at_start) {
2412 Isolate* isolate = Isolate::Current();
2413 ASSERT(characters_filled_in < details->characters());
2414 int characters = details->characters();
2416 if (compiler->ascii()) {
2417 char_mask = String::kMaxAsciiCharCode;
2419 char_mask = String::kMaxUtf16CodeUnit;
2421 for (int k = 0; k < elms_->length(); k++) {
2422 TextElement elm = elms_->at(k);
2423 if (elm.type == TextElement::ATOM) {
2424 Vector<const uc16> quarks = elm.data.u_atom->data();
2425 for (int i = 0; i < characters && i < quarks.length(); i++) {
2426 QuickCheckDetails::Position* pos =
2427 details->positions(characters_filled_in);
2429 if (c > char_mask) {
2430 // If we expect a non-ASCII character from an ASCII string,
2431 // there is no way we can match. Not even case independent
2432 // matching can turn an ASCII character into non-ASCII or
2434 details->set_cannot_match();
2435 pos->determines_perfectly = false;
2438 if (compiler->ignore_case()) {
2439 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
2440 int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
2442 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
2444 // This letter has no case equivalents, so it's nice and simple
2445 // and the mask-compare will determine definitely whether we have
2446 // a match at this character position.
2447 pos->mask = char_mask;
2449 pos->determines_perfectly = true;
2451 uint32_t common_bits = char_mask;
2452 uint32_t bits = chars[0];
2453 for (int j = 1; j < length; j++) {
2454 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
2455 common_bits ^= differing_bits;
2456 bits &= common_bits;
2458 // If length is 2 and common bits has only one zero in it then
2459 // our mask and compare instruction will determine definitely
2460 // whether we have a match at this character position. Otherwise
2461 // it can only be an approximate check.
2462 uint32_t one_zero = (common_bits | ~char_mask);
2463 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
2464 pos->determines_perfectly = true;
2466 pos->mask = common_bits;
2470 // Don't ignore case. Nice simple case where the mask-compare will
2471 // determine definitely whether we have a match at this character
2473 pos->mask = char_mask;
2475 pos->determines_perfectly = true;
2477 characters_filled_in++;
2478 ASSERT(characters_filled_in <= details->characters());
2479 if (characters_filled_in == details->characters()) {
2484 QuickCheckDetails::Position* pos =
2485 details->positions(characters_filled_in);
2486 RegExpCharacterClass* tree = elm.data.u_char_class;
2487 ZoneList<CharacterRange>* ranges = tree->ranges();
2488 if (tree->is_negated()) {
2489 // A quick check uses multi-character mask and compare. There is no
2490 // useful way to incorporate a negative char class into this scheme
2491 // so we just conservatively create a mask and value that will always
2496 int first_range = 0;
2497 while (ranges->at(first_range).from() > char_mask) {
2499 if (first_range == ranges->length()) {
2500 details->set_cannot_match();
2501 pos->determines_perfectly = false;
2505 CharacterRange range = ranges->at(first_range);
2506 uc16 from = range.from();
2507 uc16 to = range.to();
2508 if (to > char_mask) {
2511 uint32_t differing_bits = (from ^ to);
2512 // A mask and compare is only perfect if the differing bits form a
2513 // number like 00011111 with one single block of trailing 1s.
2514 if ((differing_bits & (differing_bits + 1)) == 0 &&
2515 from + differing_bits == to) {
2516 pos->determines_perfectly = true;
2518 uint32_t common_bits = ~SmearBitsRight(differing_bits);
2519 uint32_t bits = (from & common_bits);
2520 for (int i = first_range + 1; i < ranges->length(); i++) {
2521 CharacterRange range = ranges->at(i);
2522 uc16 from = range.from();
2523 uc16 to = range.to();
2524 if (from > char_mask) continue;
2525 if (to > char_mask) to = char_mask;
2526 // Here we are combining more ranges into the mask and compare
2527 // value. With each new range the mask becomes more sparse and
2528 // so the chances of a false positive rise. A character class
2529 // with multiple ranges is assumed never to be equivalent to a
2530 // mask and compare operation.
2531 pos->determines_perfectly = false;
2532 uint32_t new_common_bits = (from ^ to);
2533 new_common_bits = ~SmearBitsRight(new_common_bits);
2534 common_bits &= new_common_bits;
2535 bits &= new_common_bits;
2536 uint32_t differing_bits = (from & common_bits) ^ bits;
2537 common_bits ^= differing_bits;
2538 bits &= common_bits;
2540 pos->mask = common_bits;
2543 characters_filled_in++;
2544 ASSERT(characters_filled_in <= details->characters());
2545 if (characters_filled_in == details->characters()) {
2550 ASSERT(characters_filled_in != details->characters());
2551 if (!details->cannot_match()) {
2552 on_success()-> GetQuickCheckDetails(details,
2554 characters_filled_in,
2560 void QuickCheckDetails::Clear() {
2561 for (int i = 0; i < characters_; i++) {
2562 positions_[i].mask = 0;
2563 positions_[i].value = 0;
2564 positions_[i].determines_perfectly = false;
2570 void QuickCheckDetails::Advance(int by, bool ascii) {
2572 if (by >= characters_) {
2576 for (int i = 0; i < characters_ - by; i++) {
2577 positions_[i] = positions_[by + i];
2579 for (int i = characters_ - by; i < characters_; i++) {
2580 positions_[i].mask = 0;
2581 positions_[i].value = 0;
2582 positions_[i].determines_perfectly = false;
2585 // We could change mask_ and value_ here but we would never advance unless
2586 // they had already been used in a check and they won't be used again because
2587 // it would gain us nothing. So there's no point.
2591 void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2592 ASSERT(characters_ == other->characters_);
2593 if (other->cannot_match_) {
2596 if (cannot_match_) {
2600 for (int i = from_index; i < characters_; i++) {
2601 QuickCheckDetails::Position* pos = positions(i);
2602 QuickCheckDetails::Position* other_pos = other->positions(i);
2603 if (pos->mask != other_pos->mask ||
2604 pos->value != other_pos->value ||
2605 !other_pos->determines_perfectly) {
2606 // Our mask-compare operation will be approximate unless we have the
2607 // exact same operation on both sides of the alternation.
2608 pos->determines_perfectly = false;
2610 pos->mask &= other_pos->mask;
2611 pos->value &= pos->mask;
2612 other_pos->value &= pos->mask;
2613 uc16 differing_bits = (pos->value ^ other_pos->value);
2614 pos->mask &= ~differing_bits;
2615 pos->value &= pos->mask;
2622 explicit VisitMarker(NodeInfo* info) : info_(info) {
2623 ASSERT(!info->visited);
2624 info->visited = true;
2627 info_->visited = false;
2634 RegExpNode* SeqRegExpNode::FilterASCII(int depth) {
2635 if (info()->replacement_calculated) return replacement();
2636 if (depth < 0) return this;
2637 ASSERT(!info()->visited);
2638 VisitMarker marker(info());
2639 return FilterSuccessor(depth - 1);
2643 RegExpNode* SeqRegExpNode::FilterSuccessor(int depth) {
2644 RegExpNode* next = on_success_->FilterASCII(depth - 1);
2645 if (next == NULL) return set_replacement(NULL);
2647 return set_replacement(this);
2651 RegExpNode* TextNode::FilterASCII(int depth) {
2652 if (info()->replacement_calculated) return replacement();
2653 if (depth < 0) return this;
2654 ASSERT(!info()->visited);
2655 VisitMarker marker(info());
2656 int element_count = elms_->length();
2657 for (int i = 0; i < element_count; i++) {
2658 TextElement elm = elms_->at(i);
2659 if (elm.type == TextElement::ATOM) {
2660 Vector<const uc16> quarks = elm.data.u_atom->data();
2661 for (int j = 0; j < quarks.length(); j++) {
2662 // We don't need special handling for case independence
2663 // because of the rule that case independence cannot make
2664 // a non-ASCII character match an ASCII character.
2665 if (quarks[j] > String::kMaxAsciiCharCode) {
2666 return set_replacement(NULL);
2670 ASSERT(elm.type == TextElement::CHAR_CLASS);
2671 RegExpCharacterClass* cc = elm.data.u_char_class;
2672 ZoneList<CharacterRange>* ranges = cc->ranges();
2673 if (!CharacterRange::IsCanonical(ranges)) {
2674 CharacterRange::Canonicalize(ranges);
2676 // Now they are in order so we only need to look at the first.
2677 int range_count = ranges->length();
2678 if (cc->is_negated()) {
2679 if (range_count != 0 &&
2680 ranges->at(0).from() == 0 &&
2681 ranges->at(0).to() >= String::kMaxAsciiCharCode) {
2682 return set_replacement(NULL);
2685 if (range_count == 0 ||
2686 ranges->at(0).from() > String::kMaxAsciiCharCode) {
2687 return set_replacement(NULL);
2692 return FilterSuccessor(depth - 1);
2696 RegExpNode* LoopChoiceNode::FilterASCII(int depth) {
2697 if (info()->replacement_calculated) return replacement();
2698 if (depth < 0) return this;
2699 if (info()->visited) return this;
2701 VisitMarker marker(info());
2703 RegExpNode* continue_replacement = continue_node_->FilterASCII(depth - 1);
2704 // If we can't continue after the loop then there is no sense in doing the
2706 if (continue_replacement == NULL) return set_replacement(NULL);
2709 return ChoiceNode::FilterASCII(depth - 1);
2713 RegExpNode* ChoiceNode::FilterASCII(int depth) {
2714 if (info()->replacement_calculated) return replacement();
2715 if (depth < 0) return this;
2716 if (info()->visited) return this;
2717 VisitMarker marker(info());
2718 int choice_count = alternatives_->length();
2720 RegExpNode* survivor = NULL;
2721 for (int i = 0; i < choice_count; i++) {
2722 GuardedAlternative alternative = alternatives_->at(i);
2723 RegExpNode* replacement = alternative.node()->FilterASCII(depth - 1);
2724 ASSERT(replacement != this); // No missing EMPTY_MATCH_CHECK.
2725 if (replacement != NULL) {
2726 alternatives_->at(i).set_node(replacement);
2728 survivor = replacement;
2731 if (surviving < 2) return set_replacement(survivor);
2733 set_replacement(this);
2734 if (surviving == choice_count) {
2737 // Only some of the nodes survived the filtering. We need to rebuild the
2738 // alternatives list.
2739 ZoneList<GuardedAlternative>* new_alternatives =
2740 new ZoneList<GuardedAlternative>(surviving);
2741 for (int i = 0; i < choice_count; i++) {
2742 RegExpNode* replacement =
2743 alternatives_->at(i).node()->FilterASCII(depth - 1);
2744 if (replacement != NULL) {
2745 alternatives_->at(i).set_node(replacement);
2746 new_alternatives->Add(alternatives_->at(i));
2749 alternatives_ = new_alternatives;
2754 RegExpNode* NegativeLookaheadChoiceNode::FilterASCII(int depth) {
2755 if (info()->replacement_calculated) return replacement();
2756 if (depth < 0) return this;
2757 if (info()->visited) return this;
2758 VisitMarker marker(info());
2759 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2761 RegExpNode* node = alternatives_->at(1).node();
2762 RegExpNode* replacement = node->FilterASCII(depth - 1);
2763 if (replacement == NULL) return set_replacement(NULL);
2764 alternatives_->at(1).set_node(replacement);
2766 RegExpNode* neg_node = alternatives_->at(0).node();
2767 RegExpNode* neg_replacement = neg_node->FilterASCII(depth - 1);
2768 // If the negative lookahead is always going to fail then
2769 // we don't need to check it.
2770 if (neg_replacement == NULL) return set_replacement(replacement);
2771 alternatives_->at(0).set_node(neg_replacement);
2772 return set_replacement(this);
2776 void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2777 RegExpCompiler* compiler,
2778 int characters_filled_in,
2779 bool not_at_start) {
2780 if (body_can_be_zero_length_ || info()->visited) return;
2781 VisitMarker marker(info());
2782 return ChoiceNode::GetQuickCheckDetails(details,
2784 characters_filled_in,
2789 void LoopChoiceNode::FillInBMInfo(
2790 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
2791 if (body_can_be_zero_length_) {
2792 bm->SetRest(offset);
2793 SaveBMInfo(bm, not_at_start, offset);
2796 ChoiceNode::FillInBMInfo(offset, bm, not_at_start);
2797 SaveBMInfo(bm, not_at_start, offset);
2801 void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2802 RegExpCompiler* compiler,
2803 int characters_filled_in,
2804 bool not_at_start) {
2805 not_at_start = (not_at_start || not_at_start_);
2806 int choice_count = alternatives_->length();
2807 ASSERT(choice_count > 0);
2808 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2810 characters_filled_in,
2812 for (int i = 1; i < choice_count; i++) {
2813 QuickCheckDetails new_details(details->characters());
2814 RegExpNode* node = alternatives_->at(i).node();
2815 node->GetQuickCheckDetails(&new_details, compiler,
2816 characters_filled_in,
2818 // Here we merge the quick match details of the two branches.
2819 details->Merge(&new_details, characters_filled_in);
2824 // Check for [0-9A-Z_a-z].
2825 static void EmitWordCheck(RegExpMacroAssembler* assembler,
2828 bool fall_through_on_word) {
2829 if (assembler->CheckSpecialCharacterClass(
2830 fall_through_on_word ? 'w' : 'W',
2831 fall_through_on_word ? non_word : word)) {
2832 // Optimized implementation available.
2835 assembler->CheckCharacterGT('z', non_word);
2836 assembler->CheckCharacterLT('0', non_word);
2837 assembler->CheckCharacterGT('a' - 1, word);
2838 assembler->CheckCharacterLT('9' + 1, word);
2839 assembler->CheckCharacterLT('A', non_word);
2840 assembler->CheckCharacterLT('Z' + 1, word);
2841 if (fall_through_on_word) {
2842 assembler->CheckNotCharacter('_', non_word);
2844 assembler->CheckCharacter('_', word);
2849 // Emit the code to check for a ^ in multiline mode (1-character lookbehind
2850 // that matches newline or the start of input).
2851 static void EmitHat(RegExpCompiler* compiler,
2852 RegExpNode* on_success,
2854 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2855 // We will be loading the previous character into the current character
2857 Trace new_trace(*trace);
2858 new_trace.InvalidateCurrentCharacter();
2861 if (new_trace.cp_offset() == 0) {
2862 // The start of input counts as a newline in this context, so skip to
2863 // ok if we are at the start.
2864 assembler->CheckAtStart(&ok);
2866 // We already checked that we are not at the start of input so it must be
2867 // OK to load the previous character.
2868 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2869 new_trace.backtrack(),
2871 if (!assembler->CheckSpecialCharacterClass('n',
2872 new_trace.backtrack())) {
2873 // Newline means \n, \r, 0x2028 or 0x2029.
2874 if (!compiler->ascii()) {
2875 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2877 assembler->CheckCharacter('\n', &ok);
2878 assembler->CheckNotCharacter('\r', new_trace.backtrack());
2880 assembler->Bind(&ok);
2881 on_success->Emit(compiler, &new_trace);
2885 // Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2886 void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) {
2887 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2888 Trace::TriBool next_is_word_character = Trace::UNKNOWN;
2889 bool not_at_start = (trace->at_start() == Trace::FALSE);
2890 BoyerMooreLookahead* lookahead = bm_info(not_at_start);
2891 if (lookahead == NULL) {
2893 Min(kMaxLookaheadForBoyerMoore,
2894 EatsAtLeast(kMaxLookaheadForBoyerMoore, 0, not_at_start));
2895 if (eats_at_least >= 1) {
2896 BoyerMooreLookahead* bm =
2897 new BoyerMooreLookahead(eats_at_least, compiler);
2898 FillInBMInfo(0, bm, not_at_start);
2899 if (bm->at(0)->is_non_word()) next_is_word_character = Trace::FALSE;
2900 if (bm->at(0)->is_word()) next_is_word_character = Trace::TRUE;
2903 if (lookahead->at(0)->is_non_word()) next_is_word_character = Trace::FALSE;
2904 if (lookahead->at(0)->is_word()) next_is_word_character = Trace::TRUE;
2906 bool at_boundary = (type_ == AssertionNode::AT_BOUNDARY);
2907 if (next_is_word_character == Trace::UNKNOWN) {
2908 Label before_non_word;
2910 if (trace->characters_preloaded() != 1) {
2911 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2913 // Fall through on non-word.
2914 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2915 // Next character is not a word character.
2916 assembler->Bind(&before_non_word);
2918 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
2919 assembler->GoTo(&ok);
2921 assembler->Bind(&before_word);
2922 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
2923 assembler->Bind(&ok);
2924 } else if (next_is_word_character == Trace::TRUE) {
2925 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
2927 ASSERT(next_is_word_character == Trace::FALSE);
2928 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
2933 void AssertionNode::BacktrackIfPrevious(
2934 RegExpCompiler* compiler,
2936 AssertionNode::IfPrevious backtrack_if_previous) {
2937 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2938 Trace new_trace(*trace);
2939 new_trace.InvalidateCurrentCharacter();
2941 Label fall_through, dummy;
2943 Label* non_word = backtrack_if_previous == kIsNonWord ?
2944 new_trace.backtrack() :
2946 Label* word = backtrack_if_previous == kIsNonWord ?
2948 new_trace.backtrack();
2950 if (new_trace.cp_offset() == 0) {
2951 // The start of input counts as a non-word character, so the question is
2952 // decided if we are at the start.
2953 assembler->CheckAtStart(non_word);
2955 // We already checked that we are not at the start of input so it must be
2956 // OK to load the previous character.
2957 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, &dummy, false);
2958 EmitWordCheck(assembler, word, non_word, backtrack_if_previous == kIsNonWord);
2960 assembler->Bind(&fall_through);
2961 on_success()->Emit(compiler, &new_trace);
2965 void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2966 RegExpCompiler* compiler,
2968 bool not_at_start) {
2969 if (type_ == AT_START && not_at_start) {
2970 details->set_cannot_match();
2973 return on_success()->GetQuickCheckDetails(details,
2980 void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2981 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2985 assembler->CheckPosition(trace->cp_offset(), &ok);
2986 assembler->GoTo(trace->backtrack());
2987 assembler->Bind(&ok);
2991 if (trace->at_start() == Trace::FALSE) {
2992 assembler->GoTo(trace->backtrack());
2995 if (trace->at_start() == Trace::UNKNOWN) {
2996 assembler->CheckNotAtStart(trace->backtrack());
2997 Trace at_start_trace = *trace;
2998 at_start_trace.set_at_start(true);
2999 on_success()->Emit(compiler, &at_start_trace);
3005 EmitHat(compiler, on_success(), trace);
3008 case AT_NON_BOUNDARY: {
3009 EmitBoundaryCheck(compiler, trace);
3013 on_success()->Emit(compiler, trace);
3017 static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
3018 if (quick_check == NULL) return false;
3019 if (offset >= quick_check->characters()) return false;
3020 return quick_check->positions(offset)->determines_perfectly;
3024 static void UpdateBoundsCheck(int index, int* checked_up_to) {
3025 if (index > *checked_up_to) {
3026 *checked_up_to = index;
3031 // We call this repeatedly to generate code for each pass over the text node.
3032 // The passes are in increasing order of difficulty because we hope one
3033 // of the first passes will fail in which case we are saved the work of the
3034 // later passes. for example for the case independent regexp /%[asdfghjkl]a/
3035 // we will check the '%' in the first pass, the case independent 'a' in the
3036 // second pass and the character class in the last pass.
3038 // The passes are done from right to left, so for example to test for /bar/
3039 // we will first test for an 'r' with offset 2, then an 'a' with offset 1
3040 // and then a 'b' with offset 0. This means we can avoid the end-of-input
3041 // bounds check most of the time. In the example we only need to check for
3042 // end-of-input when loading the putative 'r'.
3044 // A slight complication involves the fact that the first character may already
3045 // be fetched into a register by the previous node. In this case we want to
3046 // do the test for that character first. We do this in separate passes. The
3047 // 'preloaded' argument indicates that we are doing such a 'pass'. If such a
3048 // pass has been performed then subsequent passes will have true in
3049 // first_element_checked to indicate that that character does not need to be
3052 // In addition to all this we are passed a Trace, which can
3053 // contain an AlternativeGeneration object. In this AlternativeGeneration
3054 // object we can see details of any quick check that was already passed in
3055 // order to get to the code we are now generating. The quick check can involve
3056 // loading characters, which means we do not need to recheck the bounds
3057 // up to the limit the quick check already checked. In addition the quick
3058 // check can have involved a mask and compare operation which may simplify
3059 // or obviate the need for further checks at some character positions.
3060 void TextNode::TextEmitPass(RegExpCompiler* compiler,
3061 TextEmitPassType pass,
3064 bool first_element_checked,
3065 int* checked_up_to) {
3066 Isolate* isolate = Isolate::Current();
3067 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3068 bool ascii = compiler->ascii();
3069 Label* backtrack = trace->backtrack();
3070 QuickCheckDetails* quick_check = trace->quick_check_performed();
3071 int element_count = elms_->length();
3072 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
3073 TextElement elm = elms_->at(i);
3074 int cp_offset = trace->cp_offset() + elm.cp_offset;
3075 if (elm.type == TextElement::ATOM) {
3076 Vector<const uc16> quarks = elm.data.u_atom->data();
3077 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
3078 if (first_element_checked && i == 0 && j == 0) continue;
3079 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
3080 EmitCharacterFunction* emit_function = NULL;
3082 case NON_ASCII_MATCH:
3084 if (quarks[j] > String::kMaxAsciiCharCode) {
3085 assembler->GoTo(backtrack);
3089 case NON_LETTER_CHARACTER_MATCH:
3090 emit_function = &EmitAtomNonLetter;
3092 case SIMPLE_CHARACTER_MATCH:
3093 emit_function = &EmitSimpleCharacter;
3095 case CASE_CHARACTER_MATCH:
3096 emit_function = &EmitAtomLetter;
3101 if (emit_function != NULL) {
3102 bool bound_checked = emit_function(isolate,
3107 *checked_up_to < cp_offset + j,
3109 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
3113 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
3114 if (pass == CHARACTER_CLASS_MATCH) {
3115 if (first_element_checked && i == 0) continue;
3116 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
3117 RegExpCharacterClass* cc = elm.data.u_char_class;
3118 EmitCharClass(assembler,
3123 *checked_up_to < cp_offset,
3125 UpdateBoundsCheck(cp_offset, checked_up_to);
3132 int TextNode::Length() {
3133 TextElement elm = elms_->last();
3134 ASSERT(elm.cp_offset >= 0);
3135 if (elm.type == TextElement::ATOM) {
3136 return elm.cp_offset + elm.data.u_atom->data().length();
3138 return elm.cp_offset + 1;
3143 bool TextNode::SkipPass(int int_pass, bool ignore_case) {
3144 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
3146 return pass == SIMPLE_CHARACTER_MATCH;
3148 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
3153 // This generates the code to match a text node. A text node can contain
3154 // straight character sequences (possibly to be matched in a case-independent
3155 // way) and character classes. For efficiency we do not do this in a single
3156 // pass from left to right. Instead we pass over the text node several times,
3157 // emitting code for some character positions every time. See the comment on
3158 // TextEmitPass for details.
3159 void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3160 LimitResult limit_result = LimitVersions(compiler, trace);
3161 if (limit_result == DONE) return;
3162 ASSERT(limit_result == CONTINUE);
3164 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
3165 compiler->SetRegExpTooBig();
3169 if (compiler->ascii()) {
3171 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
3174 bool first_elt_done = false;
3175 int bound_checked_to = trace->cp_offset() - 1;
3176 bound_checked_to += trace->bound_checked_up_to();
3178 // If a character is preloaded into the current character register then
3180 if (trace->characters_preloaded() == 1) {
3181 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3182 if (!SkipPass(pass, compiler->ignore_case())) {
3183 TextEmitPass(compiler,
3184 static_cast<TextEmitPassType>(pass),
3191 first_elt_done = true;
3194 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3195 if (!SkipPass(pass, compiler->ignore_case())) {
3196 TextEmitPass(compiler,
3197 static_cast<TextEmitPassType>(pass),
3205 Trace successor_trace(*trace);
3206 successor_trace.set_at_start(false);
3207 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
3208 RecursionCheck rc(compiler);
3209 on_success()->Emit(compiler, &successor_trace);
3213 void Trace::InvalidateCurrentCharacter() {
3214 characters_preloaded_ = 0;
3218 void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
3220 // We don't have an instruction for shifting the current character register
3221 // down or for using a shifted value for anything so lets just forget that
3222 // we preloaded any characters into it.
3223 characters_preloaded_ = 0;
3224 // Adjust the offsets of the quick check performed information. This
3225 // information is used to find out what we already determined about the
3226 // characters by means of mask and compare.
3227 quick_check_performed_.Advance(by, compiler->ascii());
3229 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
3230 compiler->SetRegExpTooBig();
3233 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
3237 void TextNode::MakeCaseIndependent(bool is_ascii) {
3238 int element_count = elms_->length();
3239 for (int i = 0; i < element_count; i++) {
3240 TextElement elm = elms_->at(i);
3241 if (elm.type == TextElement::CHAR_CLASS) {
3242 RegExpCharacterClass* cc = elm.data.u_char_class;
3243 // None of the standard character classes is different in the case
3244 // independent case and it slows us down if we don't know that.
3245 if (cc->is_standard()) continue;
3246 ZoneList<CharacterRange>* ranges = cc->ranges();
3247 int range_count = ranges->length();
3248 for (int j = 0; j < range_count; j++) {
3249 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
3256 int TextNode::GreedyLoopTextLength() {
3257 TextElement elm = elms_->at(elms_->length() - 1);
3258 if (elm.type == TextElement::CHAR_CLASS) {
3259 return elm.cp_offset + 1;
3261 return elm.cp_offset + elm.data.u_atom->data().length();
3266 RegExpNode* TextNode::GetSuccessorOfOmnivorousTextNode(
3267 RegExpCompiler* compiler) {
3268 if (elms_->length() != 1) return NULL;
3269 TextElement elm = elms_->at(0);
3270 if (elm.type != TextElement::CHAR_CLASS) return NULL;
3271 RegExpCharacterClass* node = elm.data.u_char_class;
3272 ZoneList<CharacterRange>* ranges = node->ranges();
3273 if (!CharacterRange::IsCanonical(ranges)) {
3274 CharacterRange::Canonicalize(ranges);
3276 if (node->is_negated()) {
3277 return ranges->length() == 0 ? on_success() : NULL;
3279 if (ranges->length() != 1) return NULL;
3281 if (compiler->ascii()) {
3282 max_char = String::kMaxAsciiCharCode;
3284 max_char = String::kMaxUtf16CodeUnit;
3286 return ranges->at(0).IsEverything(max_char) ? on_success() : NULL;
3290 // Finds the fixed match length of a sequence of nodes that goes from
3291 // this alternative and back to this choice node. If there are variable
3292 // length nodes or other complications in the way then return a sentinel
3293 // value indicating that a greedy loop cannot be constructed.
3294 int ChoiceNode::GreedyLoopTextLengthForAlternative(
3295 GuardedAlternative* alternative) {
3297 RegExpNode* node = alternative->node();
3298 // Later we will generate code for all these text nodes using recursion
3299 // so we have to limit the max number.
3300 int recursion_depth = 0;
3301 while (node != this) {
3302 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
3303 return kNodeIsTooComplexForGreedyLoops;
3305 int node_length = node->GreedyLoopTextLength();
3306 if (node_length == kNodeIsTooComplexForGreedyLoops) {
3307 return kNodeIsTooComplexForGreedyLoops;
3309 length += node_length;
3310 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
3311 node = seq_node->on_success();
3317 void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
3318 ASSERT_EQ(loop_node_, NULL);
3319 AddAlternative(alt);
3320 loop_node_ = alt.node();
3324 void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
3325 ASSERT_EQ(continue_node_, NULL);
3326 AddAlternative(alt);
3327 continue_node_ = alt.node();
3331 void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3332 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3333 if (trace->stop_node() == this) {
3335 GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3336 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
3337 // Update the counter-based backtracking info on the stack. This is an
3338 // optimization for greedy loops (see below).
3339 ASSERT(trace->cp_offset() == text_length);
3340 macro_assembler->AdvanceCurrentPosition(text_length);
3341 macro_assembler->GoTo(trace->loop_label());
3344 ASSERT(trace->stop_node() == NULL);
3345 if (!trace->is_trivial()) {
3346 trace->Flush(compiler, this);
3349 ChoiceNode::Emit(compiler, trace);
3353 int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
3354 int eats_at_least) {
3355 int preload_characters = Min(4, eats_at_least);
3356 if (compiler->macro_assembler()->CanReadUnaligned()) {
3357 bool ascii = compiler->ascii();
3359 if (preload_characters > 4) preload_characters = 4;
3360 // We can't preload 3 characters because there is no machine instruction
3361 // to do that. We can't just load 4 because we could be reading
3362 // beyond the end of the string, which could cause a memory fault.
3363 if (preload_characters == 3) preload_characters = 2;
3365 if (preload_characters > 2) preload_characters = 2;
3368 if (preload_characters > 1) preload_characters = 1;
3370 return preload_characters;
3374 // This class is used when generating the alternatives in a choice node. It
3375 // records the way the alternative is being code generated.
3376 class AlternativeGeneration: public Malloced {
3378 AlternativeGeneration()
3379 : possible_success(),
3380 expects_preload(false),
3382 quick_check_details() { }
3383 Label possible_success;
3384 bool expects_preload;
3386 QuickCheckDetails quick_check_details;
3390 // Creates a list of AlternativeGenerations. If the list has a reasonable
3391 // size then it is on the stack, otherwise the excess is on the heap.
3392 class AlternativeGenerationList {
3394 explicit AlternativeGenerationList(int count)
3395 : alt_gens_(count) {
3396 for (int i = 0; i < count && i < kAFew; i++) {
3397 alt_gens_.Add(a_few_alt_gens_ + i);
3399 for (int i = kAFew; i < count; i++) {
3400 alt_gens_.Add(new AlternativeGeneration());
3403 ~AlternativeGenerationList() {
3404 for (int i = kAFew; i < alt_gens_.length(); i++) {
3405 delete alt_gens_[i];
3406 alt_gens_[i] = NULL;
3410 AlternativeGeneration* at(int i) {
3411 return alt_gens_[i];
3415 static const int kAFew = 10;
3416 ZoneList<AlternativeGeneration*> alt_gens_;
3417 AlternativeGeneration a_few_alt_gens_[kAFew];
3421 // The '2' variant is has inclusive from and exclusive to.
3422 static const int kSpaceRanges[] = { '\t', '\r' + 1, ' ', ' ' + 1, 0x00A0,
3423 0x00A1, 0x1680, 0x1681, 0x180E, 0x180F, 0x2000, 0x200B, 0x2028, 0x202A,
3424 0x202F, 0x2030, 0x205F, 0x2060, 0x3000, 0x3001, 0xFEFF, 0xFF00, 0x10000 };
3425 static const int kSpaceRangeCount = ARRAY_SIZE(kSpaceRanges);
3427 static const int kWordRanges[] = {
3428 '0', '9' + 1, 'A', 'Z' + 1, '_', '_' + 1, 'a', 'z' + 1, 0x10000 };
3429 static const int kWordRangeCount = ARRAY_SIZE(kWordRanges);
3430 static const int kDigitRanges[] = { '0', '9' + 1, 0x10000 };
3431 static const int kDigitRangeCount = ARRAY_SIZE(kDigitRanges);
3432 static const int kSurrogateRanges[] = { 0xd800, 0xe000, 0x10000 };
3433 static const int kSurrogateRangeCount = ARRAY_SIZE(kSurrogateRanges);
3434 static const int kLineTerminatorRanges[] = { 0x000A, 0x000B, 0x000D, 0x000E,
3435 0x2028, 0x202A, 0x10000 };
3436 static const int kLineTerminatorRangeCount = ARRAY_SIZE(kLineTerminatorRanges);
3439 void BoyerMoorePositionInfo::Set(int character) {
3440 SetInterval(Interval(character, character));
3444 void BoyerMoorePositionInfo::SetInterval(const Interval& interval) {
3445 s_ = AddRange(s_, kSpaceRanges, kSpaceRangeCount, interval);
3446 w_ = AddRange(w_, kWordRanges, kWordRangeCount, interval);
3447 d_ = AddRange(d_, kDigitRanges, kDigitRangeCount, interval);
3449 AddRange(surrogate_, kSurrogateRanges, kSurrogateRangeCount, interval);
3450 if (interval.to() - interval.from() >= kMapSize - 1) {
3451 if (map_count_ != kMapSize) {
3452 map_count_ = kMapSize;
3453 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3457 for (int i = interval.from(); i <= interval.to(); i++) {
3458 int mod_character = (i & kMask);
3459 if (!map_->at(mod_character)) {
3461 map_->at(mod_character) = true;
3463 if (map_count_ == kMapSize) return;
3468 void BoyerMoorePositionInfo::SetAll() {
3469 s_ = w_ = d_ = kLatticeUnknown;
3470 if (map_count_ != kMapSize) {
3471 map_count_ = kMapSize;
3472 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3477 BoyerMooreLookahead::BoyerMooreLookahead(
3478 int length, RegExpCompiler* compiler)
3480 compiler_(compiler) {
3481 if (compiler->ascii()) {
3482 max_char_ = String::kMaxAsciiCharCode;
3484 max_char_ = String::kMaxUtf16CodeUnit;
3486 bitmaps_ = new ZoneList<BoyerMoorePositionInfo*>(length);
3487 for (int i = 0; i < length; i++) {
3488 bitmaps_->Add(new BoyerMoorePositionInfo());
3493 // Find the longest range of lookahead that has the fewest number of different
3494 // characters that can occur at a given position. Since we are optimizing two
3495 // different parameters at once this is a tradeoff.
3496 bool BoyerMooreLookahead::FindWorthwhileInterval(int* from, int* to) {
3497 int biggest_points = 0;
3498 // If more than 32 characters out of 128 can occur it is unlikely that we can
3499 // be lucky enough to step forwards much of the time.
3500 const int kMaxMax = 32;
3501 for (int max_number_of_chars = 4;
3502 max_number_of_chars < kMaxMax;
3503 max_number_of_chars *= 2) {
3505 FindBestInterval(max_number_of_chars, biggest_points, from, to);
3507 if (biggest_points == 0) return false;
3512 // Find the highest-points range between 0 and length_ where the character
3513 // information is not too vague. 'Too vague' means that there are more than
3514 // max_number_of_chars that can occur at this position. Calculates the number
3515 // of points as the product of width-of-the-range and
3516 // probability-of-finding-one-of-the-characters, where the probability is
3517 // calculated using the frequency distribution of the sample subject string.
3518 int BoyerMooreLookahead::FindBestInterval(
3519 int max_number_of_chars, int old_biggest_points, int* from, int* to) {
3520 int biggest_points = old_biggest_points;
3521 static const int kSize = RegExpMacroAssembler::kTableSize;
3522 for (int i = 0; i < length_; ) {
3523 while (i < length_ && Count(i) > max_number_of_chars) i++;
3524 if (i == length_) break;
3525 int remembered_from = i;
3526 bool union_map[kSize];
3527 for (int j = 0; j < kSize; j++) union_map[j] = false;
3528 while (i < length_ && Count(i) <= max_number_of_chars) {
3529 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3530 for (int j = 0; j < kSize; j++) union_map[j] |= map->at(j);
3534 for (int j = 0; j < kSize; j++) {
3536 // Add 1 to the frequency to give a small per-character boost for
3537 // the cases where our sampling is not good enough and many
3538 // characters have a frequency of zero. This means the frequency
3539 // can theoretically be up to 2*kSize though we treat it mostly as
3540 // a fraction of kSize.
3541 frequency += compiler_->frequency_collator()->Frequency(j) + 1;
3544 // We use the probability of skipping times the distance we are skipping to
3545 // judge the effectiveness of this. Actually we have a cut-off: By
3546 // dividing by 2 we switch off the skipping if the probability of skipping
3547 // is less than 50%. This is because the multibyte mask-and-compare
3548 // skipping in quickcheck is more likely to do well on this case.
3549 bool in_quickcheck_range = ((i - remembered_from < 4) ||
3550 (compiler_->ascii() ? remembered_from <= 4 : remembered_from <= 2));
3551 // Called 'probability' but it is only a rough estimate and can actually
3552 // be outside the 0-kSize range.
3553 int probability = (in_quickcheck_range ? kSize / 2 : kSize) - frequency;
3554 int points = (i - remembered_from) * probability;
3555 if (points > biggest_points) {
3556 *from = remembered_from;
3558 biggest_points = points;
3561 return biggest_points;
3565 // Take all the characters that will not prevent a successful match if they
3566 // occur in the subject string in the range between min_lookahead and
3567 // max_lookahead (inclusive) measured from the current position. If the
3568 // character at max_lookahead offset is not one of these characters, then we
3569 // can safely skip forwards by the number of characters in the range.
3570 int BoyerMooreLookahead::GetSkipTable(int min_lookahead,
3572 Handle<ByteArray> boolean_skip_table) {
3573 const int kSize = RegExpMacroAssembler::kTableSize;
3575 const int kSkipArrayEntry = 0;
3576 const int kDontSkipArrayEntry = 1;
3578 for (int i = 0; i < kSize; i++) {
3579 boolean_skip_table->set(i, kSkipArrayEntry);
3581 int skip = max_lookahead + 1 - min_lookahead;
3583 for (int i = max_lookahead; i >= min_lookahead; i--) {
3584 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3585 for (int j = 0; j < kSize; j++) {
3587 boolean_skip_table->set(j, kDontSkipArrayEntry);
3596 // See comment above on the implementation of GetSkipTable.
3597 bool BoyerMooreLookahead::EmitSkipInstructions(RegExpMacroAssembler* masm) {
3598 const int kSize = RegExpMacroAssembler::kTableSize;
3600 int min_lookahead = 0;
3601 int max_lookahead = 0;
3603 if (!FindWorthwhileInterval(&min_lookahead, &max_lookahead)) return false;
3605 bool found_single_character = false;
3606 int single_character = 0;
3607 for (int i = max_lookahead; i >= min_lookahead; i--) {
3608 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3609 if (map->map_count() > 1 ||
3610 (found_single_character && map->map_count() != 0)) {
3611 found_single_character = false;
3614 for (int j = 0; j < kSize; j++) {
3616 found_single_character = true;
3617 single_character = j;
3623 int lookahead_width = max_lookahead + 1 - min_lookahead;
3625 if (found_single_character && lookahead_width == 1 && max_lookahead < 3) {
3626 // The mask-compare can probably handle this better.
3630 if (found_single_character) {
3633 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3634 if (max_char_ > kSize) {
3635 masm->CheckCharacterAfterAnd(single_character,
3636 RegExpMacroAssembler::kTableMask,
3639 masm->CheckCharacter(single_character, &cont);
3641 masm->AdvanceCurrentPosition(lookahead_width);
3647 Handle<ByteArray> boolean_skip_table =
3648 FACTORY->NewByteArray(kSize, TENURED);
3649 int skip_distance = GetSkipTable(
3650 min_lookahead, max_lookahead, boolean_skip_table);
3651 ASSERT(skip_distance != 0);
3655 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3656 masm->CheckBitInTable(boolean_skip_table, &cont);
3657 masm->AdvanceCurrentPosition(skip_distance);
3665 /* Code generation for choice nodes.
3667 * We generate quick checks that do a mask and compare to eliminate a
3668 * choice. If the quick check succeeds then it jumps to the continuation to
3669 * do slow checks and check subsequent nodes. If it fails (the common case)
3670 * it falls through to the next choice.
3672 * Here is the desired flow graph. Nodes directly below each other imply
3673 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
3674 * 3 doesn't have a quick check so we have to call the slow check.
3675 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
3676 * regexp continuation is generated directly after the Sn node, up to the
3677 * next GoTo if we decide to reuse some already generated code. Some
3678 * nodes expect preload_characters to be preloaded into the current
3679 * character register. R nodes do this preloading. Vertices are marked
3680 * F for failures and S for success (possible success in the case of quick
3681 * nodes). L, V, < and > are used as arrow heads.
3715 * For greedy loops we reverse our expectation and expect to match rather
3716 * than fail. Therefore we want the loop code to look like this (U is the
3717 * unwind code that steps back in the greedy loop). The following alternatives
3718 * look the same as above.
3743 void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3744 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3745 int choice_count = alternatives_->length();
3747 for (int i = 0; i < choice_count - 1; i++) {
3748 GuardedAlternative alternative = alternatives_->at(i);
3749 ZoneList<Guard*>* guards = alternative.guards();
3750 int guard_count = (guards == NULL) ? 0 : guards->length();
3751 for (int j = 0; j < guard_count; j++) {
3752 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
3757 LimitResult limit_result = LimitVersions(compiler, trace);
3758 if (limit_result == DONE) return;
3759 ASSERT(limit_result == CONTINUE);
3761 int new_flush_budget = trace->flush_budget() / choice_count;
3762 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
3763 trace->Flush(compiler, this);
3767 RecursionCheck rc(compiler);
3769 Trace* current_trace = trace;
3771 int text_length = GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3772 bool greedy_loop = false;
3773 Label greedy_loop_label;
3774 Trace counter_backtrack_trace;
3775 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
3776 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
3778 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
3779 // Here we have special handling for greedy loops containing only text nodes
3780 // and other simple nodes. These are handled by pushing the current
3781 // position on the stack and then incrementing the current position each
3782 // time around the switch. On backtrack we decrement the current position
3783 // and check it against the pushed value. This avoids pushing backtrack
3784 // information for each iteration of the loop, which could take up a lot of
3787 ASSERT(trace->stop_node() == NULL);
3788 macro_assembler->PushCurrentPosition();
3789 current_trace = &counter_backtrack_trace;
3790 Label greedy_match_failed;
3791 Trace greedy_match_trace;
3792 if (not_at_start()) greedy_match_trace.set_at_start(false);
3793 greedy_match_trace.set_backtrack(&greedy_match_failed);
3795 macro_assembler->Bind(&loop_label);
3796 greedy_match_trace.set_stop_node(this);
3797 greedy_match_trace.set_loop_label(&loop_label);
3798 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
3799 macro_assembler->Bind(&greedy_match_failed);
3802 Label second_choice; // For use in greedy matches.
3803 macro_assembler->Bind(&second_choice);
3805 int first_normal_choice = greedy_loop ? 1 : 0;
3807 bool not_at_start = current_trace->at_start() == Trace::FALSE;
3808 const int kEatsAtLeastNotYetInitialized = -1;
3809 int eats_at_least = kEatsAtLeastNotYetInitialized;
3811 bool skip_was_emitted = false;
3813 if (!greedy_loop && choice_count == 2) {
3814 GuardedAlternative alt1 = alternatives_->at(1);
3815 if (alt1.guards() == NULL || alt1.guards()->length() == 0) {
3816 RegExpNode* eats_anything_node = alt1.node();
3817 if (eats_anything_node->GetSuccessorOfOmnivorousTextNode(compiler) ==
3819 // At this point we know that we are at a non-greedy loop that will eat
3820 // any character one at a time. Any non-anchored regexp has such a
3821 // loop prepended to it in order to find where it starts. We look for
3822 // a pattern of the form ...abc... where we can look 6 characters ahead
3823 // and step forwards 3 if the character is not one of abc. Abc need
3824 // not be atoms, they can be any reasonably limited character class or
3825 // small alternation.
3826 ASSERT(trace->is_trivial()); // This is the case on LoopChoiceNodes.
3827 BoyerMooreLookahead* lookahead = bm_info(not_at_start);
3828 if (lookahead == NULL) {
3830 Min(kMaxLookaheadForBoyerMoore,
3831 EatsAtLeast(kMaxLookaheadForBoyerMoore, 0, not_at_start));
3832 if (eats_at_least >= 1) {
3833 BoyerMooreLookahead* bm =
3834 new BoyerMooreLookahead(eats_at_least, compiler);
3835 GuardedAlternative alt0 = alternatives_->at(0);
3836 alt0.node()->FillInBMInfo(0, bm, not_at_start);
3837 skip_was_emitted = bm->EmitSkipInstructions(macro_assembler);
3840 skip_was_emitted = lookahead->EmitSkipInstructions(macro_assembler);
3846 if (eats_at_least == kEatsAtLeastNotYetInitialized) {
3847 // Save some time by looking at most one machine word ahead.
3848 eats_at_least = EatsAtLeast(compiler->ascii() ? 4 : 2, 0, not_at_start);
3850 int preload_characters = CalculatePreloadCharacters(compiler, eats_at_least);
3852 bool preload_is_current = !skip_was_emitted &&
3853 (current_trace->characters_preloaded() == preload_characters);
3854 bool preload_has_checked_bounds = preload_is_current;
3856 AlternativeGenerationList alt_gens(choice_count);
3858 // For now we just call all choices one after the other. The idea ultimately
3859 // is to use the Dispatch table to try only the relevant ones.
3860 for (int i = first_normal_choice; i < choice_count; i++) {
3861 GuardedAlternative alternative = alternatives_->at(i);
3862 AlternativeGeneration* alt_gen = alt_gens.at(i);
3863 alt_gen->quick_check_details.set_characters(preload_characters);
3864 ZoneList<Guard*>* guards = alternative.guards();
3865 int guard_count = (guards == NULL) ? 0 : guards->length();
3866 Trace new_trace(*current_trace);
3867 new_trace.set_characters_preloaded(preload_is_current ?
3868 preload_characters :
3870 if (preload_has_checked_bounds) {
3871 new_trace.set_bound_checked_up_to(preload_characters);
3873 new_trace.quick_check_performed()->Clear();
3874 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
3875 alt_gen->expects_preload = preload_is_current;
3876 bool generate_full_check_inline = false;
3877 if (FLAG_regexp_optimization &&
3878 try_to_emit_quick_check_for_alternative(i) &&
3879 alternative.node()->EmitQuickCheck(compiler,
3881 preload_has_checked_bounds,
3882 &alt_gen->possible_success,
3883 &alt_gen->quick_check_details,
3884 i < choice_count - 1)) {
3885 // Quick check was generated for this choice.
3886 preload_is_current = true;
3887 preload_has_checked_bounds = true;
3888 // On the last choice in the ChoiceNode we generated the quick
3889 // check to fall through on possible success. So now we need to
3890 // generate the full check inline.
3891 if (i == choice_count - 1) {
3892 macro_assembler->Bind(&alt_gen->possible_success);
3893 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
3894 new_trace.set_characters_preloaded(preload_characters);
3895 new_trace.set_bound_checked_up_to(preload_characters);
3896 generate_full_check_inline = true;
3898 } else if (alt_gen->quick_check_details.cannot_match()) {
3899 if (i == choice_count - 1 && !greedy_loop) {
3900 macro_assembler->GoTo(trace->backtrack());
3904 // No quick check was generated. Put the full code here.
3905 // If this is not the first choice then there could be slow checks from
3906 // previous cases that go here when they fail. There's no reason to
3907 // insist that they preload characters since the slow check we are about
3908 // to generate probably can't use it.
3909 if (i != first_normal_choice) {
3910 alt_gen->expects_preload = false;
3911 new_trace.InvalidateCurrentCharacter();
3913 if (i < choice_count - 1) {
3914 new_trace.set_backtrack(&alt_gen->after);
3916 generate_full_check_inline = true;
3918 if (generate_full_check_inline) {
3919 if (new_trace.actions() != NULL) {
3920 new_trace.set_flush_budget(new_flush_budget);
3922 for (int j = 0; j < guard_count; j++) {
3923 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
3925 alternative.node()->Emit(compiler, &new_trace);
3926 preload_is_current = false;
3928 macro_assembler->Bind(&alt_gen->after);
3931 macro_assembler->Bind(&greedy_loop_label);
3932 // If we have unwound to the bottom then backtrack.
3933 macro_assembler->CheckGreedyLoop(trace->backtrack());
3934 // Otherwise try the second priority at an earlier position.
3935 macro_assembler->AdvanceCurrentPosition(-text_length);
3936 macro_assembler->GoTo(&second_choice);
3939 // At this point we need to generate slow checks for the alternatives where
3940 // the quick check was inlined. We can recognize these because the associated
3942 for (int i = first_normal_choice; i < choice_count - 1; i++) {
3943 AlternativeGeneration* alt_gen = alt_gens.at(i);
3944 Trace new_trace(*current_trace);
3945 // If there are actions to be flushed we have to limit how many times
3946 // they are flushed. Take the budget of the parent trace and distribute
3947 // it fairly amongst the children.
3948 if (new_trace.actions() != NULL) {
3949 new_trace.set_flush_budget(new_flush_budget);
3951 EmitOutOfLineContinuation(compiler,
3953 alternatives_->at(i),
3956 alt_gens.at(i + 1)->expects_preload);
3961 void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
3963 GuardedAlternative alternative,
3964 AlternativeGeneration* alt_gen,
3965 int preload_characters,
3966 bool next_expects_preload) {
3967 if (!alt_gen->possible_success.is_linked()) return;
3969 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3970 macro_assembler->Bind(&alt_gen->possible_success);
3971 Trace out_of_line_trace(*trace);
3972 out_of_line_trace.set_characters_preloaded(preload_characters);
3973 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
3974 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
3975 ZoneList<Guard*>* guards = alternative.guards();
3976 int guard_count = (guards == NULL) ? 0 : guards->length();
3977 if (next_expects_preload) {
3978 Label reload_current_char;
3979 out_of_line_trace.set_backtrack(&reload_current_char);
3980 for (int j = 0; j < guard_count; j++) {
3981 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
3983 alternative.node()->Emit(compiler, &out_of_line_trace);
3984 macro_assembler->Bind(&reload_current_char);
3985 // Reload the current character, since the next quick check expects that.
3986 // We don't need to check bounds here because we only get into this
3987 // code through a quick check which already did the checked load.
3988 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
3991 preload_characters);
3992 macro_assembler->GoTo(&(alt_gen->after));
3994 out_of_line_trace.set_backtrack(&(alt_gen->after));
3995 for (int j = 0; j < guard_count; j++) {
3996 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
3998 alternative.node()->Emit(compiler, &out_of_line_trace);
4003 void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4004 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4005 LimitResult limit_result = LimitVersions(compiler, trace);
4006 if (limit_result == DONE) return;
4007 ASSERT(limit_result == CONTINUE);
4009 RecursionCheck rc(compiler);
4012 case STORE_POSITION: {
4013 Trace::DeferredCapture
4014 new_capture(data_.u_position_register.reg,
4015 data_.u_position_register.is_capture,
4017 Trace new_trace = *trace;
4018 new_trace.add_action(&new_capture);
4019 on_success()->Emit(compiler, &new_trace);
4022 case INCREMENT_REGISTER: {
4023 Trace::DeferredIncrementRegister
4024 new_increment(data_.u_increment_register.reg);
4025 Trace new_trace = *trace;
4026 new_trace.add_action(&new_increment);
4027 on_success()->Emit(compiler, &new_trace);
4030 case SET_REGISTER: {
4031 Trace::DeferredSetRegister
4032 new_set(data_.u_store_register.reg, data_.u_store_register.value);
4033 Trace new_trace = *trace;
4034 new_trace.add_action(&new_set);
4035 on_success()->Emit(compiler, &new_trace);
4038 case CLEAR_CAPTURES: {
4039 Trace::DeferredClearCaptures
4040 new_capture(Interval(data_.u_clear_captures.range_from,
4041 data_.u_clear_captures.range_to));
4042 Trace new_trace = *trace;
4043 new_trace.add_action(&new_capture);
4044 on_success()->Emit(compiler, &new_trace);
4047 case BEGIN_SUBMATCH:
4048 if (!trace->is_trivial()) {
4049 trace->Flush(compiler, this);
4051 assembler->WriteCurrentPositionToRegister(
4052 data_.u_submatch.current_position_register, 0);
4053 assembler->WriteStackPointerToRegister(
4054 data_.u_submatch.stack_pointer_register);
4055 on_success()->Emit(compiler, trace);
4058 case EMPTY_MATCH_CHECK: {
4059 int start_pos_reg = data_.u_empty_match_check.start_register;
4061 int rep_reg = data_.u_empty_match_check.repetition_register;
4062 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
4063 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
4064 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
4065 // If we know we haven't advanced and there is no minimum we
4066 // can just backtrack immediately.
4067 assembler->GoTo(trace->backtrack());
4068 } else if (know_dist && stored_pos < trace->cp_offset()) {
4069 // If we know we've advanced we can generate the continuation
4071 on_success()->Emit(compiler, trace);
4072 } else if (!trace->is_trivial()) {
4073 trace->Flush(compiler, this);
4075 Label skip_empty_check;
4076 // If we have a minimum number of repetitions we check the current
4077 // number first and skip the empty check if it's not enough.
4079 int limit = data_.u_empty_match_check.repetition_limit;
4080 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
4082 // If the match is empty we bail out, otherwise we fall through
4083 // to the on-success continuation.
4084 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
4085 trace->backtrack());
4086 assembler->Bind(&skip_empty_check);
4087 on_success()->Emit(compiler, trace);
4091 case POSITIVE_SUBMATCH_SUCCESS: {
4092 if (!trace->is_trivial()) {
4093 trace->Flush(compiler, this);
4096 assembler->ReadCurrentPositionFromRegister(
4097 data_.u_submatch.current_position_register);
4098 assembler->ReadStackPointerFromRegister(
4099 data_.u_submatch.stack_pointer_register);
4100 int clear_register_count = data_.u_submatch.clear_register_count;
4101 if (clear_register_count == 0) {
4102 on_success()->Emit(compiler, trace);
4105 int clear_registers_from = data_.u_submatch.clear_register_from;
4106 Label clear_registers_backtrack;
4107 Trace new_trace = *trace;
4108 new_trace.set_backtrack(&clear_registers_backtrack);
4109 on_success()->Emit(compiler, &new_trace);
4111 assembler->Bind(&clear_registers_backtrack);
4112 int clear_registers_to = clear_registers_from + clear_register_count - 1;
4113 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
4115 ASSERT(trace->backtrack() == NULL);
4116 assembler->Backtrack();
4125 void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4126 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4127 if (!trace->is_trivial()) {
4128 trace->Flush(compiler, this);
4132 LimitResult limit_result = LimitVersions(compiler, trace);
4133 if (limit_result == DONE) return;
4134 ASSERT(limit_result == CONTINUE);
4136 RecursionCheck rc(compiler);
4138 ASSERT_EQ(start_reg_ + 1, end_reg_);
4139 if (compiler->ignore_case()) {
4140 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
4141 trace->backtrack());
4143 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
4145 on_success()->Emit(compiler, trace);
4149 // -------------------------------------------------------------------
4156 class DotPrinter: public NodeVisitor {
4158 explicit DotPrinter(bool ignore_case)
4159 : ignore_case_(ignore_case),
4160 stream_(&alloc_) { }
4161 void PrintNode(const char* label, RegExpNode* node);
4162 void Visit(RegExpNode* node);
4163 void PrintAttributes(RegExpNode* from);
4164 StringStream* stream() { return &stream_; }
4165 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
4166 #define DECLARE_VISIT(Type) \
4167 virtual void Visit##Type(Type##Node* that);
4168 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
4169 #undef DECLARE_VISIT
4172 HeapStringAllocator alloc_;
4173 StringStream stream_;
4177 void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
4178 stream()->Add("digraph G {\n graph [label=\"");
4179 for (int i = 0; label[i]; i++) {
4182 stream()->Add("\\\\");
4185 stream()->Add("\"");
4188 stream()->Put(label[i]);
4192 stream()->Add("\"];\n");
4194 stream()->Add("}\n");
4195 printf("%s", *(stream()->ToCString()));
4199 void DotPrinter::Visit(RegExpNode* node) {
4200 if (node->info()->visited) return;
4201 node->info()->visited = true;
4206 void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
4207 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
4212 class TableEntryBodyPrinter {
4214 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
4215 : stream_(stream), choice_(choice) { }
4216 void Call(uc16 from, DispatchTable::Entry entry) {
4217 OutSet* out_set = entry.out_set();
4218 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4219 if (out_set->Get(i)) {
4220 stream()->Add(" n%p:s%io%i -> n%p;\n",
4224 choice()->alternatives()->at(i).node());
4229 StringStream* stream() { return stream_; }
4230 ChoiceNode* choice() { return choice_; }
4231 StringStream* stream_;
4232 ChoiceNode* choice_;
4236 class TableEntryHeaderPrinter {
4238 explicit TableEntryHeaderPrinter(StringStream* stream)
4239 : first_(true), stream_(stream) { }
4240 void Call(uc16 from, DispatchTable::Entry entry) {
4246 stream()->Add("{\\%k-\\%k|{", from, entry.to());
4247 OutSet* out_set = entry.out_set();
4249 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4250 if (out_set->Get(i)) {
4251 if (priority > 0) stream()->Add("|");
4252 stream()->Add("<s%io%i> %i", from, i, priority);
4256 stream()->Add("}}");
4261 StringStream* stream() { return stream_; }
4262 StringStream* stream_;
4266 class AttributePrinter {
4268 explicit AttributePrinter(DotPrinter* out)
4269 : out_(out), first_(true) { }
4270 void PrintSeparator() {
4274 out_->stream()->Add("|");
4277 void PrintBit(const char* name, bool value) {
4280 out_->stream()->Add("{%s}", name);
4282 void PrintPositive(const char* name, int value) {
4283 if (value < 0) return;
4285 out_->stream()->Add("{%s|%x}", name, value);
4293 void DotPrinter::PrintAttributes(RegExpNode* that) {
4294 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
4295 "margin=0.1, fontsize=10, label=\"{",
4297 AttributePrinter printer(this);
4298 NodeInfo* info = that->info();
4299 printer.PrintBit("NI", info->follows_newline_interest);
4300 printer.PrintBit("WI", info->follows_word_interest);
4301 printer.PrintBit("SI", info->follows_start_interest);
4302 Label* label = that->label();
4303 if (label->is_bound())
4304 printer.PrintPositive("@", label->pos());
4305 stream()->Add("}\"];\n");
4306 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
4307 "arrowhead=none];\n", that, that);
4311 static const bool kPrintDispatchTable = false;
4312 void DotPrinter::VisitChoice(ChoiceNode* that) {
4313 if (kPrintDispatchTable) {
4314 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
4315 TableEntryHeaderPrinter header_printer(stream());
4316 that->GetTable(ignore_case_)->ForEach(&header_printer);
4317 stream()->Add("\"]\n", that);
4318 PrintAttributes(that);
4319 TableEntryBodyPrinter body_printer(stream(), that);
4320 that->GetTable(ignore_case_)->ForEach(&body_printer);
4322 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
4323 for (int i = 0; i < that->alternatives()->length(); i++) {
4324 GuardedAlternative alt = that->alternatives()->at(i);
4325 stream()->Add(" n%p -> n%p;\n", that, alt.node());
4328 for (int i = 0; i < that->alternatives()->length(); i++) {
4329 GuardedAlternative alt = that->alternatives()->at(i);
4330 alt.node()->Accept(this);
4335 void DotPrinter::VisitText(TextNode* that) {
4336 stream()->Add(" n%p [label=\"", that);
4337 for (int i = 0; i < that->elements()->length(); i++) {
4338 if (i > 0) stream()->Add(" ");
4339 TextElement elm = that->elements()->at(i);
4341 case TextElement::ATOM: {
4342 stream()->Add("'%w'", elm.data.u_atom->data());
4345 case TextElement::CHAR_CLASS: {
4346 RegExpCharacterClass* node = elm.data.u_char_class;
4348 if (node->is_negated())
4350 for (int j = 0; j < node->ranges()->length(); j++) {
4351 CharacterRange range = node->ranges()->at(j);
4352 stream()->Add("%k-%k", range.from(), range.to());
4361 stream()->Add("\", shape=box, peripheries=2];\n");
4362 PrintAttributes(that);
4363 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
4364 Visit(that->on_success());
4368 void DotPrinter::VisitBackReference(BackReferenceNode* that) {
4369 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
4371 that->start_register(),
4372 that->end_register());
4373 PrintAttributes(that);
4374 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
4375 Visit(that->on_success());
4379 void DotPrinter::VisitEnd(EndNode* that) {
4380 stream()->Add(" n%p [style=bold, shape=point];\n", that);
4381 PrintAttributes(that);
4385 void DotPrinter::VisitAssertion(AssertionNode* that) {
4386 stream()->Add(" n%p [", that);
4387 switch (that->type()) {
4388 case AssertionNode::AT_END:
4389 stream()->Add("label=\"$\", shape=septagon");
4391 case AssertionNode::AT_START:
4392 stream()->Add("label=\"^\", shape=septagon");
4394 case AssertionNode::AT_BOUNDARY:
4395 stream()->Add("label=\"\\b\", shape=septagon");
4397 case AssertionNode::AT_NON_BOUNDARY:
4398 stream()->Add("label=\"\\B\", shape=septagon");
4400 case AssertionNode::AFTER_NEWLINE:
4401 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
4404 stream()->Add("];\n");
4405 PrintAttributes(that);
4406 RegExpNode* successor = that->on_success();
4407 stream()->Add(" n%p -> n%p;\n", that, successor);
4412 void DotPrinter::VisitAction(ActionNode* that) {
4413 stream()->Add(" n%p [", that);
4414 switch (that->type_) {
4415 case ActionNode::SET_REGISTER:
4416 stream()->Add("label=\"$%i:=%i\", shape=octagon",
4417 that->data_.u_store_register.reg,
4418 that->data_.u_store_register.value);
4420 case ActionNode::INCREMENT_REGISTER:
4421 stream()->Add("label=\"$%i++\", shape=octagon",
4422 that->data_.u_increment_register.reg);
4424 case ActionNode::STORE_POSITION:
4425 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
4426 that->data_.u_position_register.reg);
4428 case ActionNode::BEGIN_SUBMATCH:
4429 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
4430 that->data_.u_submatch.current_position_register);
4432 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
4433 stream()->Add("label=\"escape\", shape=septagon");
4435 case ActionNode::EMPTY_MATCH_CHECK:
4436 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
4437 that->data_.u_empty_match_check.start_register,
4438 that->data_.u_empty_match_check.repetition_register,
4439 that->data_.u_empty_match_check.repetition_limit);
4441 case ActionNode::CLEAR_CAPTURES: {
4442 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
4443 that->data_.u_clear_captures.range_from,
4444 that->data_.u_clear_captures.range_to);
4448 stream()->Add("];\n");
4449 PrintAttributes(that);
4450 RegExpNode* successor = that->on_success();
4451 stream()->Add(" n%p -> n%p;\n", that, successor);
4456 class DispatchTableDumper {
4458 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
4459 void Call(uc16 key, DispatchTable::Entry entry);
4460 StringStream* stream() { return stream_; }
4462 StringStream* stream_;
4466 void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
4467 stream()->Add("[%k-%k]: {", key, entry.to());
4468 OutSet* set = entry.out_set();
4470 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4475 stream()->Add(", ");
4477 stream()->Add("%i", i);
4480 stream()->Add("}\n");
4484 void DispatchTable::Dump() {
4485 HeapStringAllocator alloc;
4486 StringStream stream(&alloc);
4487 DispatchTableDumper dumper(&stream);
4488 tree()->ForEach(&dumper);
4489 OS::PrintError("%s", *stream.ToCString());
4493 void RegExpEngine::DotPrint(const char* label,
4496 DotPrinter printer(ignore_case);
4497 printer.PrintNode(label, node);
4504 // -------------------------------------------------------------------
4505 // Tree to graph conversion
4507 RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
4508 RegExpNode* on_success) {
4509 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
4510 elms->Add(TextElement::Atom(this));
4511 return new TextNode(elms, on_success);
4515 RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
4516 RegExpNode* on_success) {
4517 return new TextNode(elements(), on_success);
4521 static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
4522 const int* special_class,
4524 length--; // Remove final 0x10000.
4525 ASSERT(special_class[length] == 0x10000);
4526 ASSERT(ranges->length() != 0);
4527 ASSERT(length != 0);
4528 ASSERT(special_class[0] != 0);
4529 if (ranges->length() != (length >> 1) + 1) {
4532 CharacterRange range = ranges->at(0);
4533 if (range.from() != 0) {
4536 for (int i = 0; i < length; i += 2) {
4537 if (special_class[i] != (range.to() + 1)) {
4540 range = ranges->at((i >> 1) + 1);
4541 if (special_class[i+1] != range.from()) {
4545 if (range.to() != 0xffff) {
4552 static bool CompareRanges(ZoneList<CharacterRange>* ranges,
4553 const int* special_class,
4555 length--; // Remove final 0x10000.
4556 ASSERT(special_class[length] == 0x10000);
4557 if (ranges->length() * 2 != length) {
4560 for (int i = 0; i < length; i += 2) {
4561 CharacterRange range = ranges->at(i >> 1);
4562 if (range.from() != special_class[i] ||
4563 range.to() != special_class[i + 1] - 1) {
4571 bool RegExpCharacterClass::is_standard() {
4572 // TODO(lrn): Remove need for this function, by not throwing away information
4577 if (set_.is_standard()) {
4580 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
4581 set_.set_standard_set_type('s');
4584 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
4585 set_.set_standard_set_type('S');
4588 if (CompareInverseRanges(set_.ranges(),
4589 kLineTerminatorRanges,
4590 kLineTerminatorRangeCount)) {
4591 set_.set_standard_set_type('.');
4594 if (CompareRanges(set_.ranges(),
4595 kLineTerminatorRanges,
4596 kLineTerminatorRangeCount)) {
4597 set_.set_standard_set_type('n');
4600 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
4601 set_.set_standard_set_type('w');
4604 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
4605 set_.set_standard_set_type('W');
4612 RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
4613 RegExpNode* on_success) {
4614 return new TextNode(this, on_success);
4618 RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
4619 RegExpNode* on_success) {
4620 ZoneList<RegExpTree*>* alternatives = this->alternatives();
4621 int length = alternatives->length();
4622 ChoiceNode* result = new ChoiceNode(length);
4623 for (int i = 0; i < length; i++) {
4624 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
4626 result->AddAlternative(alternative);
4632 RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
4633 RegExpNode* on_success) {
4634 return ToNode(min(),
4643 // Scoped object to keep track of how much we unroll quantifier loops in the
4644 // regexp graph generator.
4645 class RegExpExpansionLimiter {
4647 static const int kMaxExpansionFactor = 6;
4648 RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
4649 : compiler_(compiler),
4650 saved_expansion_factor_(compiler->current_expansion_factor()),
4651 ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
4653 if (ok_to_expand_) {
4654 if (factor > kMaxExpansionFactor) {
4655 // Avoid integer overflow of the current expansion factor.
4656 ok_to_expand_ = false;
4657 compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
4659 int new_factor = saved_expansion_factor_ * factor;
4660 ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
4661 compiler->set_current_expansion_factor(new_factor);
4666 ~RegExpExpansionLimiter() {
4667 compiler_->set_current_expansion_factor(saved_expansion_factor_);
4670 bool ok_to_expand() { return ok_to_expand_; }
4673 RegExpCompiler* compiler_;
4674 int saved_expansion_factor_;
4677 DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
4681 RegExpNode* RegExpQuantifier::ToNode(int min,
4685 RegExpCompiler* compiler,
4686 RegExpNode* on_success,
4687 bool not_at_start) {
4688 // x{f, t} becomes this:
4694 // (r=0)-->(?)---/ [if r < t]
4696 // [if r >= f] \----> ...
4699 // 15.10.2.5 RepeatMatcher algorithm.
4700 // The parser has already eliminated the case where max is 0. In the case
4701 // where max_match is zero the parser has removed the quantifier if min was
4702 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
4704 // If we know that we cannot match zero length then things are a little
4705 // simpler since we don't need to make the special zero length match check
4706 // from step 2.1. If the min and max are small we can unroll a little in
4708 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
4709 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
4710 if (max == 0) return on_success; // This can happen due to recursion.
4711 bool body_can_be_empty = (body->min_match() == 0);
4712 int body_start_reg = RegExpCompiler::kNoRegister;
4713 Interval capture_registers = body->CaptureRegisters();
4714 bool needs_capture_clearing = !capture_registers.is_empty();
4715 if (body_can_be_empty) {
4716 body_start_reg = compiler->AllocateRegister();
4717 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
4718 // Only unroll if there are no captures and the body can't be
4721 RegExpExpansionLimiter limiter(
4722 compiler, min + ((max != min) ? 1 : 0));
4723 if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
4724 int new_max = (max == kInfinity) ? max : max - min;
4725 // Recurse once to get the loop or optional matches after the fixed
4727 RegExpNode* answer = ToNode(
4728 0, new_max, is_greedy, body, compiler, on_success, true);
4729 // Unroll the forced matches from 0 to min. This can cause chains of
4730 // TextNodes (which the parser does not generate). These should be
4731 // combined if it turns out they hinder good code generation.
4732 for (int i = 0; i < min; i++) {
4733 answer = body->ToNode(compiler, answer);
4738 if (max <= kMaxUnrolledMaxMatches && min == 0) {
4739 ASSERT(max > 0); // Due to the 'if' above.
4740 RegExpExpansionLimiter limiter(compiler, max);
4741 if (limiter.ok_to_expand()) {
4742 // Unroll the optional matches up to max.
4743 RegExpNode* answer = on_success;
4744 for (int i = 0; i < max; i++) {
4745 ChoiceNode* alternation = new ChoiceNode(2);
4747 alternation->AddAlternative(
4748 GuardedAlternative(body->ToNode(compiler, answer)));
4749 alternation->AddAlternative(GuardedAlternative(on_success));
4751 alternation->AddAlternative(GuardedAlternative(on_success));
4752 alternation->AddAlternative(
4753 GuardedAlternative(body->ToNode(compiler, answer)));
4755 answer = alternation;
4756 if (not_at_start) alternation->set_not_at_start();
4762 bool has_min = min > 0;
4763 bool has_max = max < RegExpTree::kInfinity;
4764 bool needs_counter = has_min || has_max;
4765 int reg_ctr = needs_counter
4766 ? compiler->AllocateRegister()
4767 : RegExpCompiler::kNoRegister;
4768 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
4769 if (not_at_start) center->set_not_at_start();
4770 RegExpNode* loop_return = needs_counter
4771 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
4772 : static_cast<RegExpNode*>(center);
4773 if (body_can_be_empty) {
4774 // If the body can be empty we need to check if it was and then
4776 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
4781 RegExpNode* body_node = body->ToNode(compiler, loop_return);
4782 if (body_can_be_empty) {
4783 // If the body can be empty we need to store the start position
4784 // so we can bail out if it was empty.
4785 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
4787 if (needs_capture_clearing) {
4788 // Before entering the body of this loop we need to clear captures.
4789 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
4791 GuardedAlternative body_alt(body_node);
4793 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
4794 body_alt.AddGuard(body_guard);
4796 GuardedAlternative rest_alt(on_success);
4798 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
4799 rest_alt.AddGuard(rest_guard);
4802 center->AddLoopAlternative(body_alt);
4803 center->AddContinueAlternative(rest_alt);
4805 center->AddContinueAlternative(rest_alt);
4806 center->AddLoopAlternative(body_alt);
4808 if (needs_counter) {
4809 return ActionNode::SetRegister(reg_ctr, 0, center);
4816 RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
4817 RegExpNode* on_success) {
4821 return AssertionNode::AfterNewline(on_success);
4822 case START_OF_INPUT:
4823 return AssertionNode::AtStart(on_success);
4825 return AssertionNode::AtBoundary(on_success);
4827 return AssertionNode::AtNonBoundary(on_success);
4829 return AssertionNode::AtEnd(on_success);
4831 // Compile $ in multiline regexps as an alternation with a positive
4832 // lookahead in one side and an end-of-input on the other side.
4833 // We need two registers for the lookahead.
4834 int stack_pointer_register = compiler->AllocateRegister();
4835 int position_register = compiler->AllocateRegister();
4836 // The ChoiceNode to distinguish between a newline and end-of-input.
4837 ChoiceNode* result = new ChoiceNode(2);
4838 // Create a newline atom.
4839 ZoneList<CharacterRange>* newline_ranges =
4840 new ZoneList<CharacterRange>(3);
4841 CharacterRange::AddClassEscape('n', newline_ranges);
4842 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
4843 TextNode* newline_matcher = new TextNode(
4845 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
4847 0, // No captures inside.
4848 -1, // Ignored if no captures.
4850 // Create an end-of-input matcher.
4851 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
4852 stack_pointer_register,
4855 // Add the two alternatives to the ChoiceNode.
4856 GuardedAlternative eol_alternative(end_of_line);
4857 result->AddAlternative(eol_alternative);
4858 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
4859 result->AddAlternative(end_alternative);
4869 RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
4870 RegExpNode* on_success) {
4871 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
4872 RegExpCapture::EndRegister(index()),
4877 RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
4878 RegExpNode* on_success) {
4883 RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
4884 RegExpNode* on_success) {
4885 int stack_pointer_register = compiler->AllocateRegister();
4886 int position_register = compiler->AllocateRegister();
4888 const int registers_per_capture = 2;
4889 const int register_of_first_capture = 2;
4890 int register_count = capture_count_ * registers_per_capture;
4891 int register_start =
4892 register_of_first_capture + capture_from_ * registers_per_capture;
4894 RegExpNode* success;
4895 if (is_positive()) {
4896 RegExpNode* node = ActionNode::BeginSubmatch(
4897 stack_pointer_register,
4901 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
4908 // We use a ChoiceNode for a negative lookahead because it has most of
4909 // the characteristics we need. It has the body of the lookahead as its
4910 // first alternative and the expression after the lookahead of the second
4911 // alternative. If the first alternative succeeds then the
4912 // NegativeSubmatchSuccess will unwind the stack including everything the
4913 // choice node set up and backtrack. If the first alternative fails then
4914 // the second alternative is tried, which is exactly the desired result
4915 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
4916 // ChoiceNode that knows to ignore the first exit when calculating quick
4918 GuardedAlternative body_alt(
4921 success = new NegativeSubmatchSuccess(stack_pointer_register,
4925 ChoiceNode* choice_node =
4926 new NegativeLookaheadChoiceNode(body_alt,
4927 GuardedAlternative(on_success));
4928 return ActionNode::BeginSubmatch(stack_pointer_register,
4935 RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
4936 RegExpNode* on_success) {
4937 return ToNode(body(), index(), compiler, on_success);
4941 RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
4943 RegExpCompiler* compiler,
4944 RegExpNode* on_success) {
4945 int start_reg = RegExpCapture::StartRegister(index);
4946 int end_reg = RegExpCapture::EndRegister(index);
4947 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
4948 RegExpNode* body_node = body->ToNode(compiler, store_end);
4949 return ActionNode::StorePosition(start_reg, true, body_node);
4953 RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
4954 RegExpNode* on_success) {
4955 ZoneList<RegExpTree*>* children = nodes();
4956 RegExpNode* current = on_success;
4957 for (int i = children->length() - 1; i >= 0; i--) {
4958 current = children->at(i)->ToNode(compiler, current);
4964 static void AddClass(const int* elmv,
4966 ZoneList<CharacterRange>* ranges) {
4968 ASSERT(elmv[elmc] == 0x10000);
4969 for (int i = 0; i < elmc; i += 2) {
4970 ASSERT(elmv[i] < elmv[i + 1]);
4971 ranges->Add(CharacterRange(elmv[i], elmv[i + 1] - 1));
4976 static void AddClassNegated(const int *elmv,
4978 ZoneList<CharacterRange>* ranges) {
4980 ASSERT(elmv[elmc] == 0x10000);
4981 ASSERT(elmv[0] != 0x0000);
4982 ASSERT(elmv[elmc-1] != String::kMaxUtf16CodeUnit);
4984 for (int i = 0; i < elmc; i += 2) {
4985 ASSERT(last <= elmv[i] - 1);
4986 ASSERT(elmv[i] < elmv[i + 1]);
4987 ranges->Add(CharacterRange(last, elmv[i] - 1));
4990 ranges->Add(CharacterRange(last, String::kMaxUtf16CodeUnit));
4994 void CharacterRange::AddClassEscape(uc16 type,
4995 ZoneList<CharacterRange>* ranges) {
4998 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
5001 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
5004 AddClass(kWordRanges, kWordRangeCount, ranges);
5007 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
5010 AddClass(kDigitRanges, kDigitRangeCount, ranges);
5013 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
5016 AddClassNegated(kLineTerminatorRanges,
5017 kLineTerminatorRangeCount,
5020 // This is not a character range as defined by the spec but a
5021 // convenient shorthand for a character class that matches any
5024 ranges->Add(CharacterRange::Everything());
5026 // This is the set of characters matched by the $ and ^ symbols
5027 // in multiline mode.
5029 AddClass(kLineTerminatorRanges,
5030 kLineTerminatorRangeCount,
5039 Vector<const int> CharacterRange::GetWordBounds() {
5040 return Vector<const int>(kWordRanges, kWordRangeCount - 1);
5044 class CharacterRangeSplitter {
5046 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
5047 ZoneList<CharacterRange>** excluded)
5048 : included_(included),
5049 excluded_(excluded) { }
5050 void Call(uc16 from, DispatchTable::Entry entry);
5052 static const int kInBase = 0;
5053 static const int kInOverlay = 1;
5056 ZoneList<CharacterRange>** included_;
5057 ZoneList<CharacterRange>** excluded_;
5061 void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
5062 if (!entry.out_set()->Get(kInBase)) return;
5063 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
5066 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
5067 (*target)->Add(CharacterRange(entry.from(), entry.to()));
5071 void CharacterRange::Split(ZoneList<CharacterRange>* base,
5072 Vector<const int> overlay,
5073 ZoneList<CharacterRange>** included,
5074 ZoneList<CharacterRange>** excluded) {
5075 ASSERT_EQ(NULL, *included);
5076 ASSERT_EQ(NULL, *excluded);
5077 DispatchTable table;
5078 for (int i = 0; i < base->length(); i++)
5079 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
5080 for (int i = 0; i < overlay.length(); i += 2) {
5081 table.AddRange(CharacterRange(overlay[i], overlay[i + 1] - 1),
5082 CharacterRangeSplitter::kInOverlay);
5084 CharacterRangeSplitter callback(included, excluded);
5085 table.ForEach(&callback);
5089 void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
5091 Isolate* isolate = Isolate::Current();
5092 uc16 bottom = from();
5095 if (bottom > String::kMaxAsciiCharCode) return;
5096 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
5098 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5099 if (top == bottom) {
5100 // If this is a singleton we just expand the one character.
5101 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
5102 for (int i = 0; i < length; i++) {
5103 uc32 chr = chars[i];
5104 if (chr != bottom) {
5105 ranges->Add(CharacterRange::Singleton(chars[i]));
5109 // If this is a range we expand the characters block by block,
5110 // expanding contiguous subranges (blocks) one at a time.
5111 // The approach is as follows. For a given start character we
5112 // look up the remainder of the block that contains it (represented
5113 // by the end point), for instance we find 'z' if the character
5114 // is 'c'. A block is characterized by the property
5115 // that all characters uncanonicalize in the same way, except that
5116 // each entry in the result is incremented by the distance from the first
5117 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
5118 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
5119 // Once we've found the end point we look up its uncanonicalization
5120 // and produce a range for each element. For instance for [c-f]
5121 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
5122 // add a range if it is not already contained in the input, so [c-f]
5123 // will be skipped but [C-F] will be added. If this range is not
5124 // completely contained in a block we do this for all the blocks
5125 // covered by the range (handling characters that is not in a block
5126 // as a "singleton block").
5127 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5129 while (pos <= top) {
5130 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
5135 ASSERT_EQ(1, length);
5136 block_end = range[0];
5138 int end = (block_end > top) ? top : block_end;
5139 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
5140 for (int i = 0; i < length; i++) {
5142 uc16 range_from = c - (block_end - pos);
5143 uc16 range_to = c - (block_end - end);
5144 if (!(bottom <= range_from && range_to <= top)) {
5145 ranges->Add(CharacterRange(range_from, range_to));
5154 bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
5155 ASSERT_NOT_NULL(ranges);
5156 int n = ranges->length();
5157 if (n <= 1) return true;
5158 int max = ranges->at(0).to();
5159 for (int i = 1; i < n; i++) {
5160 CharacterRange next_range = ranges->at(i);
5161 if (next_range.from() <= max + 1) return false;
5162 max = next_range.to();
5168 ZoneList<CharacterRange>* CharacterSet::ranges() {
5169 if (ranges_ == NULL) {
5170 ranges_ = new ZoneList<CharacterRange>(2);
5171 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
5177 // Move a number of elements in a zonelist to another position
5178 // in the same list. Handles overlapping source and target areas.
5179 static void MoveRanges(ZoneList<CharacterRange>* list,
5183 // Ranges are potentially overlapping.
5185 for (int i = count - 1; i >= 0; i--) {
5186 list->at(to + i) = list->at(from + i);
5189 for (int i = 0; i < count; i++) {
5190 list->at(to + i) = list->at(from + i);
5196 static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
5198 CharacterRange insert) {
5199 // Inserts a range into list[0..count[, which must be sorted
5200 // by from value and non-overlapping and non-adjacent, using at most
5201 // list[0..count] for the result. Returns the number of resulting
5202 // canonicalized ranges. Inserting a range may collapse existing ranges into
5203 // fewer ranges, so the return value can be anything in the range 1..count+1.
5204 uc16 from = insert.from();
5205 uc16 to = insert.to();
5207 int end_pos = count;
5208 for (int i = count - 1; i >= 0; i--) {
5209 CharacterRange current = list->at(i);
5210 if (current.from() > to + 1) {
5212 } else if (current.to() + 1 < from) {
5218 // Inserted range overlaps, or is adjacent to, ranges at positions
5219 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
5220 // not affected by the insertion.
5221 // If start_pos == end_pos, the range must be inserted before start_pos.
5222 // if start_pos < end_pos, the entire range from start_pos to end_pos
5223 // must be merged with the insert range.
5225 if (start_pos == end_pos) {
5226 // Insert between existing ranges at position start_pos.
5227 if (start_pos < count) {
5228 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
5230 list->at(start_pos) = insert;
5233 if (start_pos + 1 == end_pos) {
5234 // Replace single existing range at position start_pos.
5235 CharacterRange to_replace = list->at(start_pos);
5236 int new_from = Min(to_replace.from(), from);
5237 int new_to = Max(to_replace.to(), to);
5238 list->at(start_pos) = CharacterRange(new_from, new_to);
5241 // Replace a number of existing ranges from start_pos to end_pos - 1.
5242 // Move the remaining ranges down.
5244 int new_from = Min(list->at(start_pos).from(), from);
5245 int new_to = Max(list->at(end_pos - 1).to(), to);
5246 if (end_pos < count) {
5247 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
5249 list->at(start_pos) = CharacterRange(new_from, new_to);
5250 return count - (end_pos - start_pos) + 1;
5254 void CharacterSet::Canonicalize() {
5255 // Special/default classes are always considered canonical. The result
5256 // of calling ranges() will be sorted.
5257 if (ranges_ == NULL) return;
5258 CharacterRange::Canonicalize(ranges_);
5262 void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
5263 if (character_ranges->length() <= 1) return;
5264 // Check whether ranges are already canonical (increasing, non-overlapping,
5266 int n = character_ranges->length();
5267 int max = character_ranges->at(0).to();
5270 CharacterRange current = character_ranges->at(i);
5271 if (current.from() <= max + 1) {
5277 // Canonical until the i'th range. If that's all of them, we are done.
5280 // The ranges at index i and forward are not canonicalized. Make them so by
5281 // doing the equivalent of insertion sort (inserting each into the previous
5283 // Notice that inserting a range can reduce the number of ranges in the
5284 // result due to combining of adjacent and overlapping ranges.
5285 int read = i; // Range to insert.
5286 int num_canonical = i; // Length of canonicalized part of list.
5288 num_canonical = InsertRangeInCanonicalList(character_ranges,
5290 character_ranges->at(read));
5293 character_ranges->Rewind(num_canonical);
5295 ASSERT(CharacterRange::IsCanonical(character_ranges));
5299 void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
5300 ZoneList<CharacterRange>* negated_ranges) {
5301 ASSERT(CharacterRange::IsCanonical(ranges));
5302 ASSERT_EQ(0, negated_ranges->length());
5303 int range_count = ranges->length();
5306 if (range_count > 0 && ranges->at(0).from() == 0) {
5307 from = ranges->at(0).to();
5310 while (i < range_count) {
5311 CharacterRange range = ranges->at(i);
5312 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
5316 if (from < String::kMaxUtf16CodeUnit) {
5317 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUtf16CodeUnit));
5322 // -------------------------------------------------------------------
5326 OutSet* OutSet::Extend(unsigned value) {
5329 if (successors() != NULL) {
5330 for (int i = 0; i < successors()->length(); i++) {
5331 OutSet* successor = successors()->at(i);
5332 if (successor->Get(value))
5336 successors_ = new ZoneList<OutSet*>(2);
5338 OutSet* result = new OutSet(first_, remaining_);
5340 successors()->Add(result);
5345 void OutSet::Set(unsigned value) {
5346 if (value < kFirstLimit) {
5347 first_ |= (1 << value);
5349 if (remaining_ == NULL)
5350 remaining_ = new ZoneList<unsigned>(1);
5351 if (remaining_->is_empty() || !remaining_->Contains(value))
5352 remaining_->Add(value);
5357 bool OutSet::Get(unsigned value) {
5358 if (value < kFirstLimit) {
5359 return (first_ & (1 << value)) != 0;
5360 } else if (remaining_ == NULL) {
5363 return remaining_->Contains(value);
5368 const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
5371 void DispatchTable::AddRange(CharacterRange full_range, int value) {
5372 CharacterRange current = full_range;
5373 if (tree()->is_empty()) {
5374 // If this is the first range we just insert into the table.
5375 ZoneSplayTree<Config>::Locator loc;
5376 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
5377 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
5380 // First see if there is a range to the left of this one that
5382 ZoneSplayTree<Config>::Locator loc;
5383 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
5384 Entry* entry = &loc.value();
5385 // If we've found a range that overlaps with this one, and it
5386 // starts strictly to the left of this one, we have to fix it
5387 // because the following code only handles ranges that start on
5388 // or after the start point of the range we're adding.
5389 if (entry->from() < current.from() && entry->to() >= current.from()) {
5390 // Snap the overlapping range in half around the start point of
5391 // the range we're adding.
5392 CharacterRange left(entry->from(), current.from() - 1);
5393 CharacterRange right(current.from(), entry->to());
5394 // The left part of the overlapping range doesn't overlap.
5395 // Truncate the whole entry to be just the left part.
5396 entry->set_to(left.to());
5397 // The right part is the one that overlaps. We add this part
5398 // to the map and let the next step deal with merging it with
5399 // the range we're adding.
5400 ZoneSplayTree<Config>::Locator loc;
5401 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
5402 loc.set_value(Entry(right.from(),
5407 while (current.is_valid()) {
5408 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
5409 (loc.value().from() <= current.to()) &&
5410 (loc.value().to() >= current.from())) {
5411 Entry* entry = &loc.value();
5412 // We have overlap. If there is space between the start point of
5413 // the range we're adding and where the overlapping range starts
5414 // then we have to add a range covering just that space.
5415 if (current.from() < entry->from()) {
5416 ZoneSplayTree<Config>::Locator ins;
5417 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
5418 ins.set_value(Entry(current.from(),
5420 empty()->Extend(value)));
5421 current.set_from(entry->from());
5423 ASSERT_EQ(current.from(), entry->from());
5424 // If the overlapping range extends beyond the one we want to add
5425 // we have to snap the right part off and add it separately.
5426 if (entry->to() > current.to()) {
5427 ZoneSplayTree<Config>::Locator ins;
5428 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
5429 ins.set_value(Entry(current.to() + 1,
5432 entry->set_to(current.to());
5434 ASSERT(entry->to() <= current.to());
5435 // The overlapping range is now completely contained by the range
5436 // we're adding so we can just update it and move the start point
5437 // of the range we're adding just past it.
5438 entry->AddValue(value);
5439 // Bail out if the last interval ended at 0xFFFF since otherwise
5440 // adding 1 will wrap around to 0.
5441 if (entry->to() == String::kMaxUtf16CodeUnit)
5443 ASSERT(entry->to() + 1 > current.from());
5444 current.set_from(entry->to() + 1);
5446 // There is no overlap so we can just add the range
5447 ZoneSplayTree<Config>::Locator ins;
5448 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
5449 ins.set_value(Entry(current.from(),
5451 empty()->Extend(value)));
5458 OutSet* DispatchTable::Get(uc16 value) {
5459 ZoneSplayTree<Config>::Locator loc;
5460 if (!tree()->FindGreatestLessThan(value, &loc))
5462 Entry* entry = &loc.value();
5463 if (value <= entry->to())
5464 return entry->out_set();
5470 // -------------------------------------------------------------------
5474 void Analysis::EnsureAnalyzed(RegExpNode* that) {
5475 StackLimitCheck check(Isolate::Current());
5476 if (check.HasOverflowed()) {
5477 fail("Stack overflow");
5480 if (that->info()->been_analyzed || that->info()->being_analyzed)
5482 that->info()->being_analyzed = true;
5484 that->info()->being_analyzed = false;
5485 that->info()->been_analyzed = true;
5489 void Analysis::VisitEnd(EndNode* that) {
5494 void TextNode::CalculateOffsets() {
5495 int element_count = elements()->length();
5496 // Set up the offsets of the elements relative to the start. This is a fixed
5497 // quantity since a TextNode can only contain fixed-width things.
5499 for (int i = 0; i < element_count; i++) {
5500 TextElement& elm = elements()->at(i);
5501 elm.cp_offset = cp_offset;
5502 if (elm.type == TextElement::ATOM) {
5503 cp_offset += elm.data.u_atom->data().length();
5511 void Analysis::VisitText(TextNode* that) {
5513 that->MakeCaseIndependent(is_ascii_);
5515 EnsureAnalyzed(that->on_success());
5516 if (!has_failed()) {
5517 that->CalculateOffsets();
5522 void Analysis::VisitAction(ActionNode* that) {
5523 RegExpNode* target = that->on_success();
5524 EnsureAnalyzed(target);
5525 if (!has_failed()) {
5526 // If the next node is interested in what it follows then this node
5527 // has to be interested too so it can pass the information on.
5528 that->info()->AddFromFollowing(target->info());
5533 void Analysis::VisitChoice(ChoiceNode* that) {
5534 NodeInfo* info = that->info();
5535 for (int i = 0; i < that->alternatives()->length(); i++) {
5536 RegExpNode* node = that->alternatives()->at(i).node();
5537 EnsureAnalyzed(node);
5538 if (has_failed()) return;
5539 // Anything the following nodes need to know has to be known by
5540 // this node also, so it can pass it on.
5541 info->AddFromFollowing(node->info());
5546 void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
5547 NodeInfo* info = that->info();
5548 for (int i = 0; i < that->alternatives()->length(); i++) {
5549 RegExpNode* node = that->alternatives()->at(i).node();
5550 if (node != that->loop_node()) {
5551 EnsureAnalyzed(node);
5552 if (has_failed()) return;
5553 info->AddFromFollowing(node->info());
5556 // Check the loop last since it may need the value of this node
5557 // to get a correct result.
5558 EnsureAnalyzed(that->loop_node());
5559 if (!has_failed()) {
5560 info->AddFromFollowing(that->loop_node()->info());
5565 void Analysis::VisitBackReference(BackReferenceNode* that) {
5566 EnsureAnalyzed(that->on_success());
5570 void Analysis::VisitAssertion(AssertionNode* that) {
5571 EnsureAnalyzed(that->on_success());
5575 void BackReferenceNode::FillInBMInfo(
5576 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
5577 // Working out the set of characters that a backreference can match is too
5578 // hard, so we just say that any character can match.
5579 bm->SetRest(offset);
5580 SaveBMInfo(bm, not_at_start, offset);
5584 STATIC_ASSERT(BoyerMoorePositionInfo::kMapSize ==
5585 RegExpMacroAssembler::kTableSize);
5588 void ChoiceNode::FillInBMInfo(
5589 int offset, BoyerMooreLookahead* bm, bool not_at_start) {
5590 ZoneList<GuardedAlternative>* alts = alternatives();
5591 for (int i = 0; i < alts->length(); i++) {
5592 GuardedAlternative& alt = alts->at(i);
5593 if (alt.guards() != NULL && alt.guards()->length() != 0) {
5594 bm->SetRest(offset); // Give up trying to fill in info.
5595 SaveBMInfo(bm, not_at_start, offset);
5598 alt.node()->FillInBMInfo(offset, bm, not_at_start);
5600 SaveBMInfo(bm, not_at_start, offset);
5604 void TextNode::FillInBMInfo(
5605 int initial_offset, BoyerMooreLookahead* bm, bool not_at_start) {
5606 if (initial_offset >= bm->length()) return;
5607 int offset = initial_offset;
5608 int max_char = bm->max_char();
5609 for (int i = 0; i < elements()->length(); i++) {
5610 if (offset >= bm->length()) {
5611 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5614 TextElement text = elements()->at(i);
5615 if (text.type == TextElement::ATOM) {
5616 RegExpAtom* atom = text.data.u_atom;
5617 for (int j = 0; j < atom->length(); j++, offset++) {
5618 if (offset >= bm->length()) {
5619 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5622 uc16 character = atom->data()[j];
5623 if (bm->compiler()->ignore_case()) {
5624 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5625 int length = GetCaseIndependentLetters(
5628 bm->max_char() == String::kMaxAsciiCharCode,
5630 for (int j = 0; j < length; j++) {
5631 bm->Set(offset, chars[j]);
5634 if (character <= max_char) bm->Set(offset, character);
5638 ASSERT(text.type == TextElement::CHAR_CLASS);
5639 RegExpCharacterClass* char_class = text.data.u_char_class;
5640 ZoneList<CharacterRange>* ranges = char_class->ranges();
5641 if (char_class->is_negated()) {
5644 for (int k = 0; k < ranges->length(); k++) {
5645 CharacterRange& range = ranges->at(k);
5646 if (range.from() > max_char) continue;
5647 int to = Min(max_char, static_cast<int>(range.to()));
5648 bm->SetInterval(offset, Interval(range.from(), to));
5654 if (offset >= bm->length()) {
5655 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5658 on_success()->FillInBMInfo(offset,
5660 true); // Not at start after a text node.
5661 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5665 // -------------------------------------------------------------------
5666 // Dispatch table construction
5669 void DispatchTableConstructor::VisitEnd(EndNode* that) {
5670 AddRange(CharacterRange::Everything());
5674 void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5675 node->set_being_calculated(true);
5676 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5677 for (int i = 0; i < alternatives->length(); i++) {
5678 set_choice_index(i);
5679 alternatives->at(i).node()->Accept(this);
5681 node->set_being_calculated(false);
5685 class AddDispatchRange {
5687 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5688 : constructor_(constructor) { }
5689 void Call(uc32 from, DispatchTable::Entry entry);
5691 DispatchTableConstructor* constructor_;
5695 void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5696 CharacterRange range(from, entry.to());
5697 constructor_->AddRange(range);
5701 void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5702 if (node->being_calculated())
5704 DispatchTable* table = node->GetTable(ignore_case_);
5705 AddDispatchRange adder(this);
5706 table->ForEach(&adder);
5710 void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5711 // TODO(160): Find the node that we refer back to and propagate its start
5712 // set back to here. For now we just accept anything.
5713 AddRange(CharacterRange::Everything());
5717 void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5718 RegExpNode* target = that->on_success();
5719 target->Accept(this);
5723 static int CompareRangeByFrom(const CharacterRange* a,
5724 const CharacterRange* b) {
5725 return Compare<uc16>(a->from(), b->from());
5729 void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5730 ranges->Sort(CompareRangeByFrom);
5732 for (int i = 0; i < ranges->length(); i++) {
5733 CharacterRange range = ranges->at(i);
5734 if (last < range.from())
5735 AddRange(CharacterRange(last, range.from() - 1));
5736 if (range.to() >= last) {
5737 if (range.to() == String::kMaxUtf16CodeUnit) {
5740 last = range.to() + 1;
5744 AddRange(CharacterRange(last, String::kMaxUtf16CodeUnit));
5748 void DispatchTableConstructor::VisitText(TextNode* that) {
5749 TextElement elm = that->elements()->at(0);
5751 case TextElement::ATOM: {
5752 uc16 c = elm.data.u_atom->data()[0];
5753 AddRange(CharacterRange(c, c));
5756 case TextElement::CHAR_CLASS: {
5757 RegExpCharacterClass* tree = elm.data.u_char_class;
5758 ZoneList<CharacterRange>* ranges = tree->ranges();
5759 if (tree->is_negated()) {
5762 for (int i = 0; i < ranges->length(); i++)
5763 AddRange(ranges->at(i));
5774 void DispatchTableConstructor::VisitAction(ActionNode* that) {
5775 RegExpNode* target = that->on_success();
5776 target->Accept(this);
5780 RegExpEngine::CompilationResult RegExpEngine::Compile(
5781 RegExpCompileData* data,
5784 Handle<String> pattern,
5785 Handle<String> sample_subject,
5787 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
5788 return IrregexpRegExpTooBig();
5790 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
5792 // Sample some characters from the middle of the string.
5793 static const int kSampleSize = 128;
5795 FlattenString(sample_subject);
5796 int chars_sampled = 0;
5797 int half_way = (sample_subject->length() - kSampleSize) / 2;
5798 for (int i = Max(0, half_way);
5799 i < sample_subject->length() && chars_sampled < kSampleSize;
5800 i++, chars_sampled++) {
5801 compiler.frequency_collator()->CountCharacter(sample_subject->Get(i));
5804 // Wrap the body of the regexp in capture #0.
5805 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
5809 RegExpNode* node = captured_body;
5810 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
5811 bool is_start_anchored = data->tree->IsAnchoredAtStart();
5812 int max_length = data->tree->max_match();
5813 if (!is_start_anchored) {
5814 // Add a .*? at the beginning, outside the body capture, unless
5815 // this expression is anchored at the beginning.
5816 RegExpNode* loop_node =
5817 RegExpQuantifier::ToNode(0,
5818 RegExpTree::kInfinity,
5820 new RegExpCharacterClass('*'),
5823 data->contains_anchor);
5825 if (data->contains_anchor) {
5826 // Unroll loop once, to take care of the case that might start
5827 // at the start of input.
5828 ChoiceNode* first_step_node = new ChoiceNode(2);
5829 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5830 first_step_node->AddAlternative(GuardedAlternative(
5831 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5832 node = first_step_node;
5838 node = node->FilterASCII(RegExpCompiler::kMaxRecursion);
5839 // Do it again to propagate the new nodes to places where they were not
5840 // put because they had not been calculated yet.
5841 if (node != NULL) node = node->FilterASCII(RegExpCompiler::kMaxRecursion);
5844 if (node == NULL) node = new EndNode(EndNode::BACKTRACK);
5846 Analysis analysis(ignore_case, is_ascii);
5847 analysis.EnsureAnalyzed(node);
5848 if (analysis.has_failed()) {
5849 const char* error_message = analysis.error_message();
5850 return CompilationResult(error_message);
5853 // Create the correct assembler for the architecture.
5854 #ifndef V8_INTERPRETED_REGEXP
5855 // Native regexp implementation.
5857 NativeRegExpMacroAssembler::Mode mode =
5858 is_ascii ? NativeRegExpMacroAssembler::ASCII
5859 : NativeRegExpMacroAssembler::UC16;
5861 #if V8_TARGET_ARCH_IA32
5862 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5863 #elif V8_TARGET_ARCH_X64
5864 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5865 #elif V8_TARGET_ARCH_ARM
5866 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
5867 #elif V8_TARGET_ARCH_MIPS
5868 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2);
5871 #else // V8_INTERPRETED_REGEXP
5872 // Interpreted regexp implementation.
5873 EmbeddedVector<byte, 1024> codes;
5874 RegExpMacroAssemblerIrregexp macro_assembler(codes);
5875 #endif // V8_INTERPRETED_REGEXP
5877 // Inserted here, instead of in Assembler, because it depends on information
5878 // in the AST that isn't replicated in the Node structure.
5879 static const int kMaxBacksearchLimit = 1024;
5880 if (is_end_anchored &&
5881 !is_start_anchored &&
5882 max_length < kMaxBacksearchLimit) {
5883 macro_assembler.SetCurrentPositionFromEnd(max_length);
5886 return compiler.Assemble(¯o_assembler,
5888 data->capture_count,
5893 }} // namespace v8::internal