blob: 3e9c5eab9a51a3a8595106c795b73fbd8825b662 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2009 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
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "ast.h"
31#include "compiler.h"
32#include "execution.h"
33#include "factory.h"
34#include "jsregexp.h"
35#include "platform.h"
36#include "runtime.h"
37#include "top.h"
38#include "compilation-cache.h"
39#include "string-stream.h"
40#include "parser.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"
45
Steve Block6ded16b2010-05-10 14:33:55 +010046#ifndef V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +000047#if V8_TARGET_ARCH_IA32
Steve Blocka7e24c12009-10-30 11:49:00 +000048#include "ia32/regexp-macro-assembler-ia32.h"
49#elif V8_TARGET_ARCH_X64
Steve Blocka7e24c12009-10-30 11:49:00 +000050#include "x64/regexp-macro-assembler-x64.h"
51#elif V8_TARGET_ARCH_ARM
Steve Blocka7e24c12009-10-30 11:49:00 +000052#include "arm/regexp-macro-assembler-arm.h"
53#else
54#error Unsupported target architecture.
55#endif
56#endif
57
58#include "interpreter-irregexp.h"
59
60
61namespace v8 {
62namespace internal {
63
64
65Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
66 Handle<String> pattern,
67 Handle<String> flags,
68 bool* has_pending_exception) {
Steve Blocka7e24c12009-10-30 11:49:00 +000069 // Call the construct code with 2 arguments.
70 Object** argv[2] = { Handle<Object>::cast(pattern).location(),
71 Handle<Object>::cast(flags).location() };
72 return Execution::New(constructor, 2, argv, has_pending_exception);
73}
74
75
76static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
77 int flags = JSRegExp::NONE;
78 for (int i = 0; i < str->length(); i++) {
79 switch (str->Get(i)) {
80 case 'i':
81 flags |= JSRegExp::IGNORE_CASE;
82 break;
83 case 'g':
84 flags |= JSRegExp::GLOBAL;
85 break;
86 case 'm':
87 flags |= JSRegExp::MULTILINE;
88 break;
89 }
90 }
91 return JSRegExp::Flags(flags);
92}
93
94
95static inline void ThrowRegExpException(Handle<JSRegExp> re,
96 Handle<String> pattern,
97 Handle<String> error_text,
98 const char* message) {
99 Handle<JSArray> array = Factory::NewJSArray(2);
100 SetElement(array, 0, pattern);
101 SetElement(array, 1, error_text);
102 Handle<Object> regexp_err = Factory::NewSyntaxError(message, array);
103 Top::Throw(*regexp_err);
104}
105
106
107// Generic RegExp methods. Dispatches to implementation specific methods.
108
109
Steve Blocka7e24c12009-10-30 11:49:00 +0000110Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
111 Handle<String> pattern,
112 Handle<String> flag_str) {
113 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
114 Handle<FixedArray> cached = CompilationCache::LookupRegExp(pattern, flags);
115 bool in_cache = !cached.is_null();
116 LOG(RegExpCompileEvent(re, in_cache));
117
118 Handle<Object> result;
119 if (in_cache) {
120 re->set_data(*cached);
121 return re;
122 }
123 FlattenString(pattern);
124 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
Steve Block6ded16b2010-05-10 14:33:55 +0100125 PostponeInterruptsScope postpone;
Steve Blocka7e24c12009-10-30 11:49:00 +0000126 RegExpCompileData parse_result;
127 FlatStringReader reader(pattern);
128 if (!ParseRegExp(&reader, flags.is_multiline(), &parse_result)) {
129 // Throw an exception if we fail to parse the pattern.
130 ThrowRegExpException(re,
131 pattern,
132 parse_result.error,
133 "malformed_regexp");
134 return Handle<Object>::null();
135 }
136
137 if (parse_result.simple && !flags.is_ignore_case()) {
138 // Parse-tree is a single atom that is equal to the pattern.
139 AtomCompile(re, pattern, flags, pattern);
140 } else if (parse_result.tree->IsAtom() &&
141 !flags.is_ignore_case() &&
142 parse_result.capture_count == 0) {
143 RegExpAtom* atom = parse_result.tree->AsAtom();
144 Vector<const uc16> atom_pattern = atom->data();
145 Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern);
146 AtomCompile(re, pattern, flags, atom_string);
147 } else {
Steve Block6ded16b2010-05-10 14:33:55 +0100148 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
Steve Blocka7e24c12009-10-30 11:49:00 +0000149 }
150 ASSERT(re->data()->IsFixedArray());
151 // Compilation succeeded so the data is set on the regexp
152 // and we can store it in the cache.
153 Handle<FixedArray> data(FixedArray::cast(re->data()));
154 CompilationCache::PutRegExp(pattern, flags, data);
155
156 return re;
157}
158
159
160Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
161 Handle<String> subject,
162 int index,
163 Handle<JSArray> last_match_info) {
164 switch (regexp->TypeTag()) {
165 case JSRegExp::ATOM:
166 return AtomExec(regexp, subject, index, last_match_info);
167 case JSRegExp::IRREGEXP: {
168 Handle<Object> result =
169 IrregexpExec(regexp, subject, index, last_match_info);
170 ASSERT(!result.is_null() || Top::has_pending_exception());
171 return result;
172 }
173 default:
174 UNREACHABLE();
175 return Handle<Object>::null();
176 }
177}
178
179
180// RegExp Atom implementation: Simple string search using indexOf.
181
182
183void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
184 Handle<String> pattern,
185 JSRegExp::Flags flags,
186 Handle<String> match_pattern) {
187 Factory::SetRegExpAtomData(re,
188 JSRegExp::ATOM,
189 pattern,
190 flags,
191 match_pattern);
192}
193
194
195static void SetAtomLastCapture(FixedArray* array,
196 String* subject,
197 int from,
198 int to) {
199 NoHandleAllocation no_handles;
200 RegExpImpl::SetLastCaptureCount(array, 2);
201 RegExpImpl::SetLastSubject(array, subject);
202 RegExpImpl::SetLastInput(array, subject);
203 RegExpImpl::SetCapture(array, 0, from);
204 RegExpImpl::SetCapture(array, 1, to);
205}
206
207
208Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
209 Handle<String> subject,
210 int index,
211 Handle<JSArray> last_match_info) {
212 Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex)));
213
214 uint32_t start_index = index;
215
216 int value = Runtime::StringMatch(subject, needle, start_index);
217 if (value == -1) return Factory::null_value();
218 ASSERT(last_match_info->HasFastElements());
219
220 {
221 NoHandleAllocation no_handles;
222 FixedArray* array = FixedArray::cast(last_match_info->elements());
223 SetAtomLastCapture(array, *subject, value, value + needle->length());
224 }
225 return last_match_info;
226}
227
228
229// Irregexp implementation.
230
231// Ensures that the regexp object contains a compiled version of the
232// source for either ASCII or non-ASCII strings.
233// If the compiled version doesn't already exist, it is compiled
234// from the source pattern.
235// If compilation fails, an exception is thrown and this function
236// returns false.
237bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
238 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
Steve Block6ded16b2010-05-10 14:33:55 +0100239#ifdef V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +0000240 if (compiled_code->IsByteArray()) return true;
Steve Block6ded16b2010-05-10 14:33:55 +0100241#else // V8_INTERPRETED_REGEXP (RegExp native code)
242 if (compiled_code->IsCode()) return true;
Steve Blocka7e24c12009-10-30 11:49:00 +0000243#endif
244 return CompileIrregexp(re, is_ascii);
245}
246
247
248bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
249 // Compile the RegExp.
250 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
Steve Block6ded16b2010-05-10 14:33:55 +0100251 PostponeInterruptsScope postpone;
Steve Blocka7e24c12009-10-30 11:49:00 +0000252 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
253 if (entry->IsJSObject()) {
254 // If it's a JSObject, a previous compilation failed and threw this object.
255 // Re-throw the object without trying again.
256 Top::Throw(entry);
257 return false;
258 }
259 ASSERT(entry->IsTheHole());
260
261 JSRegExp::Flags flags = re->GetFlags();
262
263 Handle<String> pattern(re->Pattern());
264 if (!pattern->IsFlat()) {
265 FlattenString(pattern);
266 }
267
268 RegExpCompileData compile_data;
269 FlatStringReader reader(pattern);
270 if (!ParseRegExp(&reader, flags.is_multiline(), &compile_data)) {
271 // Throw an exception if we fail to parse the pattern.
272 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
273 ThrowRegExpException(re,
274 pattern,
275 compile_data.error,
276 "malformed_regexp");
277 return false;
278 }
279 RegExpEngine::CompilationResult result =
280 RegExpEngine::Compile(&compile_data,
281 flags.is_ignore_case(),
282 flags.is_multiline(),
283 pattern,
284 is_ascii);
285 if (result.error_message != NULL) {
286 // Unable to compile regexp.
287 Handle<JSArray> array = Factory::NewJSArray(2);
288 SetElement(array, 0, pattern);
289 SetElement(array,
290 1,
291 Factory::NewStringFromUtf8(CStrVector(result.error_message)));
292 Handle<Object> regexp_err =
293 Factory::NewSyntaxError("malformed_regexp", array);
294 Top::Throw(*regexp_err);
295 re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err);
296 return false;
297 }
298
299 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
300 data->set(JSRegExp::code_index(is_ascii), result.code);
301 int register_max = IrregexpMaxRegisterCount(*data);
302 if (result.num_registers > register_max) {
303 SetIrregexpMaxRegisterCount(*data, result.num_registers);
304 }
305
306 return true;
307}
308
309
310int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
311 return Smi::cast(
312 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
313}
314
315
316void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
317 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
318}
319
320
321int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
322 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
323}
324
325
326int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
327 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
328}
329
330
331ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
332 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
333}
334
335
336Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
337 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
338}
339
340
Steve Block6ded16b2010-05-10 14:33:55 +0100341void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
342 Handle<String> pattern,
343 JSRegExp::Flags flags,
344 int capture_count) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000345 // Initialize compiled code entries to null.
346 Factory::SetRegExpIrregexpData(re,
347 JSRegExp::IRREGEXP,
348 pattern,
349 flags,
350 capture_count);
351}
352
353
Steve Block6ded16b2010-05-10 14:33:55 +0100354int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
355 Handle<String> subject) {
356 if (!subject->IsFlat()) {
357 FlattenString(subject);
358 }
359 bool is_ascii = subject->IsAsciiRepresentation();
360 if (!EnsureCompiledIrregexp(regexp, is_ascii)) {
361 return -1;
362 }
363#ifdef V8_INTERPRETED_REGEXP
364 // Byte-code regexp needs space allocated for all its registers.
365 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
366#else // V8_INTERPRETED_REGEXP
367 // Native regexp only needs room to output captures. Registers are handled
368 // internally.
369 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
370#endif // V8_INTERPRETED_REGEXP
371}
372
373
374RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(Handle<JSRegExp> regexp,
375 Handle<String> subject,
376 int index,
377 Vector<int> output) {
378 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()));
379
380 ASSERT(index >= 0);
381 ASSERT(index <= subject->length());
382 ASSERT(subject->IsFlat());
383
384#ifndef V8_INTERPRETED_REGEXP
385 ASSERT(output.length() >=
386 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
387 do {
388 bool is_ascii = subject->IsAsciiRepresentation();
389 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii));
390 NativeRegExpMacroAssembler::Result res =
391 NativeRegExpMacroAssembler::Match(code,
392 subject,
393 output.start(),
394 output.length(),
395 index);
396 if (res != NativeRegExpMacroAssembler::RETRY) {
397 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
398 Top::has_pending_exception());
399 STATIC_ASSERT(
400 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
401 STATIC_ASSERT(
402 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
403 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
404 == RE_EXCEPTION);
405 return static_cast<IrregexpResult>(res);
406 }
407 // If result is RETRY, the string has changed representation, and we
408 // must restart from scratch.
409 // In this case, it means we must make sure we are prepared to handle
410 // the, potentially, differen subject (the string can switch between
411 // being internal and external, and even between being ASCII and UC16,
412 // but the characters are always the same).
413 IrregexpPrepare(regexp, subject);
414 } while (true);
415 UNREACHABLE();
416 return RE_EXCEPTION;
417#else // V8_INTERPRETED_REGEXP
418
419 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
420 bool is_ascii = subject->IsAsciiRepresentation();
421 // We must have done EnsureCompiledIrregexp, so we can get the number of
422 // registers.
423 int* register_vector = output.start();
424 int number_of_capture_registers =
425 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
426 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
427 register_vector[i] = -1;
428 }
429 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii));
430
431 if (IrregexpInterpreter::Match(byte_codes,
432 subject,
433 register_vector,
434 index)) {
435 return RE_SUCCESS;
436 }
437 return RE_FAILURE;
438#endif // V8_INTERPRETED_REGEXP
439}
440
441
Steve Blocka7e24c12009-10-30 11:49:00 +0000442Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
443 Handle<String> subject,
444 int previous_index,
445 Handle<JSArray> last_match_info) {
446 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
447
448 // Prepare space for the return values.
Steve Block6ded16b2010-05-10 14:33:55 +0100449#ifdef V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +0000450#ifdef DEBUG
451 if (FLAG_trace_regexp_bytecodes) {
452 String* pattern = jsregexp->Pattern();
453 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
454 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
455 }
456#endif
457#endif
Steve Block6ded16b2010-05-10 14:33:55 +0100458 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
459 if (required_registers < 0) {
460 // Compiling failed with an exception.
Steve Blocka7e24c12009-10-30 11:49:00 +0000461 ASSERT(Top::has_pending_exception());
462 return Handle<Object>::null();
463 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000464
Steve Block6ded16b2010-05-10 14:33:55 +0100465 OffsetsVector registers(required_registers);
Steve Blocka7e24c12009-10-30 11:49:00 +0000466
Steve Block6ded16b2010-05-10 14:33:55 +0100467 IrregexpResult res = IrregexpExecOnce(jsregexp,
468 subject,
469 previous_index,
470 Vector<int>(registers.vector(),
471 registers.length()));
472 if (res == RE_SUCCESS) {
473 int capture_register_count =
474 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
475 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
476 AssertNoAllocation no_gc;
477 int* register_vector = registers.vector();
478 FixedArray* array = FixedArray::cast(last_match_info->elements());
479 for (int i = 0; i < capture_register_count; i += 2) {
480 SetCapture(array, i, register_vector[i]);
481 SetCapture(array, i + 1, register_vector[i + 1]);
Leon Clarkee46be812010-01-19 14:06:41 +0000482 }
Steve Block6ded16b2010-05-10 14:33:55 +0100483 SetLastCaptureCount(array, capture_register_count);
484 SetLastSubject(array, *subject);
485 SetLastInput(array, *subject);
486 return last_match_info;
Steve Blocka7e24c12009-10-30 11:49:00 +0000487 }
Steve Block6ded16b2010-05-10 14:33:55 +0100488 if (res == RE_EXCEPTION) {
489 ASSERT(Top::has_pending_exception());
Steve Blocka7e24c12009-10-30 11:49:00 +0000490 return Handle<Object>::null();
491 }
Steve Block6ded16b2010-05-10 14:33:55 +0100492 ASSERT(res == RE_FAILURE);
493 return Factory::null_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000494}
495
496
497// -------------------------------------------------------------------
498// Implementation of the Irregexp regular expression engine.
499//
500// The Irregexp regular expression engine is intended to be a complete
501// implementation of ECMAScript regular expressions. It generates either
502// bytecodes or native code.
503
504// The Irregexp regexp engine is structured in three steps.
505// 1) The parser generates an abstract syntax tree. See ast.cc.
506// 2) From the AST a node network is created. The nodes are all
507// subclasses of RegExpNode. The nodes represent states when
508// executing a regular expression. Several optimizations are
509// performed on the node network.
510// 3) From the nodes we generate either byte codes or native code
511// that can actually execute the regular expression (perform
512// the search). The code generation step is described in more
513// detail below.
514
515// Code generation.
516//
517// The nodes are divided into four main categories.
518// * Choice nodes
519// These represent places where the regular expression can
520// match in more than one way. For example on entry to an
521// alternation (foo|bar) or a repetition (*, +, ? or {}).
522// * Action nodes
523// These represent places where some action should be
524// performed. Examples include recording the current position
525// in the input string to a register (in order to implement
526// captures) or other actions on register for example in order
527// to implement the counters needed for {} repetitions.
528// * Matching nodes
529// These attempt to match some element part of the input string.
530// Examples of elements include character classes, plain strings
531// or back references.
532// * End nodes
533// These are used to implement the actions required on finding
534// a successful match or failing to find a match.
535//
536// The code generated (whether as byte codes or native code) maintains
537// some state as it runs. This consists of the following elements:
538//
539// * The capture registers. Used for string captures.
540// * Other registers. Used for counters etc.
541// * The current position.
542// * The stack of backtracking information. Used when a matching node
543// fails to find a match and needs to try an alternative.
544//
545// Conceptual regular expression execution model:
546//
547// There is a simple conceptual model of regular expression execution
548// which will be presented first. The actual code generated is a more
549// efficient simulation of the simple conceptual model:
550//
551// * Choice nodes are implemented as follows:
552// For each choice except the last {
553// push current position
554// push backtrack code location
555// <generate code to test for choice>
556// backtrack code location:
557// pop current position
558// }
559// <generate code to test for last choice>
560//
561// * Actions nodes are generated as follows
562// <push affected registers on backtrack stack>
563// <generate code to perform action>
564// push backtrack code location
565// <generate code to test for following nodes>
566// backtrack code location:
567// <pop affected registers to restore their state>
568// <pop backtrack location from stack and go to it>
569//
570// * Matching nodes are generated as follows:
571// if input string matches at current position
572// update current position
573// <generate code to test for following nodes>
574// else
575// <pop backtrack location from stack and go to it>
576//
577// Thus it can be seen that the current position is saved and restored
578// by the choice nodes, whereas the registers are saved and restored by
579// by the action nodes that manipulate them.
580//
581// The other interesting aspect of this model is that nodes are generated
582// at the point where they are needed by a recursive call to Emit(). If
583// the node has already been code generated then the Emit() call will
584// generate a jump to the previously generated code instead. In order to
585// limit recursion it is possible for the Emit() function to put the node
586// on a work list for later generation and instead generate a jump. The
587// destination of the jump is resolved later when the code is generated.
588//
589// Actual regular expression code generation.
590//
591// Code generation is actually more complicated than the above. In order
592// to improve the efficiency of the generated code some optimizations are
593// performed
594//
595// * Choice nodes have 1-character lookahead.
596// A choice node looks at the following character and eliminates some of
597// the choices immediately based on that character. This is not yet
598// implemented.
599// * Simple greedy loops store reduced backtracking information.
600// A quantifier like /.*foo/m will greedily match the whole input. It will
601// then need to backtrack to a point where it can match "foo". The naive
602// implementation of this would push each character position onto the
603// backtracking stack, then pop them off one by one. This would use space
604// proportional to the length of the input string. However since the "."
605// can only match in one way and always has a constant length (in this case
606// of 1) it suffices to store the current position on the top of the stack
607// once. Matching now becomes merely incrementing the current position and
608// backtracking becomes decrementing the current position and checking the
609// result against the stored current position. This is faster and saves
610// space.
611// * The current state is virtualized.
612// This is used to defer expensive operations until it is clear that they
613// are needed and to generate code for a node more than once, allowing
614// specialized an efficient versions of the code to be created. This is
615// explained in the section below.
616//
617// Execution state virtualization.
618//
619// Instead of emitting code, nodes that manipulate the state can record their
620// manipulation in an object called the Trace. The Trace object can record a
621// current position offset, an optional backtrack code location on the top of
622// the virtualized backtrack stack and some register changes. When a node is
623// to be emitted it can flush the Trace or update it. Flushing the Trace
624// will emit code to bring the actual state into line with the virtual state.
625// Avoiding flushing the state can postpone some work (eg updates of capture
626// registers). Postponing work can save time when executing the regular
627// expression since it may be found that the work never has to be done as a
628// failure to match can occur. In addition it is much faster to jump to a
629// known backtrack code location than it is to pop an unknown backtrack
630// location from the stack and jump there.
631//
632// The virtual state found in the Trace affects code generation. For example
633// the virtual state contains the difference between the actual current
634// position and the virtual current position, and matching code needs to use
635// this offset to attempt a match in the correct location of the input
636// string. Therefore code generated for a non-trivial trace is specialized
637// to that trace. The code generator therefore has the ability to generate
638// code for each node several times. In order to limit the size of the
639// generated code there is an arbitrary limit on how many specialized sets of
640// code may be generated for a given node. If the limit is reached, the
641// trace is flushed and a generic version of the code for a node is emitted.
642// This is subsequently used for that node. The code emitted for non-generic
643// trace is not recorded in the node and so it cannot currently be reused in
644// the event that code generation is requested for an identical trace.
645
646
647void RegExpTree::AppendToText(RegExpText* text) {
648 UNREACHABLE();
649}
650
651
652void RegExpAtom::AppendToText(RegExpText* text) {
653 text->AddElement(TextElement::Atom(this));
654}
655
656
657void RegExpCharacterClass::AppendToText(RegExpText* text) {
658 text->AddElement(TextElement::CharClass(this));
659}
660
661
662void RegExpText::AppendToText(RegExpText* text) {
663 for (int i = 0; i < elements()->length(); i++)
664 text->AddElement(elements()->at(i));
665}
666
667
668TextElement TextElement::Atom(RegExpAtom* atom) {
669 TextElement result = TextElement(ATOM);
670 result.data.u_atom = atom;
671 return result;
672}
673
674
675TextElement TextElement::CharClass(
676 RegExpCharacterClass* char_class) {
677 TextElement result = TextElement(CHAR_CLASS);
678 result.data.u_char_class = char_class;
679 return result;
680}
681
682
683int TextElement::length() {
684 if (type == ATOM) {
685 return data.u_atom->length();
686 } else {
687 ASSERT(type == CHAR_CLASS);
688 return 1;
689 }
690}
691
692
693DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
694 if (table_ == NULL) {
695 table_ = new DispatchTable();
696 DispatchTableConstructor cons(table_, ignore_case);
697 cons.BuildTable(this);
698 }
699 return table_;
700}
701
702
703class RegExpCompiler {
704 public:
705 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
706
707 int AllocateRegister() {
708 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
709 reg_exp_too_big_ = true;
710 return next_register_;
711 }
712 return next_register_++;
713 }
714
715 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
716 RegExpNode* start,
717 int capture_count,
718 Handle<String> pattern);
719
720 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
721
722 static const int kImplementationOffset = 0;
723 static const int kNumberOfRegistersOffset = 0;
724 static const int kCodeOffset = 1;
725
726 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
727 EndNode* accept() { return accept_; }
728
729 static const int kMaxRecursion = 100;
730 inline int recursion_depth() { return recursion_depth_; }
731 inline void IncrementRecursionDepth() { recursion_depth_++; }
732 inline void DecrementRecursionDepth() { recursion_depth_--; }
733
734 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
735
736 inline bool ignore_case() { return ignore_case_; }
737 inline bool ascii() { return ascii_; }
738
739 static const int kNoRegister = -1;
740 private:
741 EndNode* accept_;
742 int next_register_;
743 List<RegExpNode*>* work_list_;
744 int recursion_depth_;
745 RegExpMacroAssembler* macro_assembler_;
746 bool ignore_case_;
747 bool ascii_;
748 bool reg_exp_too_big_;
749};
750
751
752class RecursionCheck {
753 public:
754 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
755 compiler->IncrementRecursionDepth();
756 }
757 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
758 private:
759 RegExpCompiler* compiler_;
760};
761
762
763static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
764 return RegExpEngine::CompilationResult("RegExp too big");
765}
766
767
768// Attempts to compile the regexp using an Irregexp code generator. Returns
769// a fixed array or a null handle depending on whether it succeeded.
770RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
771 : next_register_(2 * (capture_count + 1)),
772 work_list_(NULL),
773 recursion_depth_(0),
774 ignore_case_(ignore_case),
775 ascii_(ascii),
776 reg_exp_too_big_(false) {
777 accept_ = new EndNode(EndNode::ACCEPT);
778 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
779}
780
781
782RegExpEngine::CompilationResult RegExpCompiler::Assemble(
783 RegExpMacroAssembler* macro_assembler,
784 RegExpNode* start,
785 int capture_count,
786 Handle<String> pattern) {
787#ifdef DEBUG
788 if (FLAG_trace_regexp_assembler)
789 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
790 else
791#endif
792 macro_assembler_ = macro_assembler;
793 List <RegExpNode*> work_list(0);
794 work_list_ = &work_list;
795 Label fail;
796 macro_assembler_->PushBacktrack(&fail);
797 Trace new_trace;
798 start->Emit(this, &new_trace);
799 macro_assembler_->Bind(&fail);
800 macro_assembler_->Fail();
801 while (!work_list.is_empty()) {
802 work_list.RemoveLast()->Emit(this, &new_trace);
803 }
804 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
805
806 Handle<Object> code = macro_assembler_->GetCode(pattern);
807
808 work_list_ = NULL;
809#ifdef DEBUG
810 if (FLAG_trace_regexp_assembler) {
811 delete macro_assembler_;
812 }
813#endif
814 return RegExpEngine::CompilationResult(*code, next_register_);
815}
816
817
818bool Trace::DeferredAction::Mentions(int that) {
819 if (type() == ActionNode::CLEAR_CAPTURES) {
820 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
821 return range.Contains(that);
822 } else {
823 return reg() == that;
824 }
825}
826
827
828bool Trace::mentions_reg(int reg) {
829 for (DeferredAction* action = actions_;
830 action != NULL;
831 action = action->next()) {
832 if (action->Mentions(reg))
833 return true;
834 }
835 return false;
836}
837
838
839bool Trace::GetStoredPosition(int reg, int* cp_offset) {
840 ASSERT_EQ(0, *cp_offset);
841 for (DeferredAction* action = actions_;
842 action != NULL;
843 action = action->next()) {
844 if (action->Mentions(reg)) {
845 if (action->type() == ActionNode::STORE_POSITION) {
846 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
847 return true;
848 } else {
849 return false;
850 }
851 }
852 }
853 return false;
854}
855
856
857int Trace::FindAffectedRegisters(OutSet* affected_registers) {
858 int max_register = RegExpCompiler::kNoRegister;
859 for (DeferredAction* action = actions_;
860 action != NULL;
861 action = action->next()) {
862 if (action->type() == ActionNode::CLEAR_CAPTURES) {
863 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
864 for (int i = range.from(); i <= range.to(); i++)
865 affected_registers->Set(i);
866 if (range.to() > max_register) max_register = range.to();
867 } else {
868 affected_registers->Set(action->reg());
869 if (action->reg() > max_register) max_register = action->reg();
870 }
871 }
872 return max_register;
873}
874
875
876void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
877 int max_register,
878 OutSet& registers_to_pop,
879 OutSet& registers_to_clear) {
880 for (int reg = max_register; reg >= 0; reg--) {
881 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
882 else if (registers_to_clear.Get(reg)) {
883 int clear_to = reg;
884 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
885 reg--;
886 }
887 assembler->ClearRegisters(reg, clear_to);
888 }
889 }
890}
891
892
893void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
894 int max_register,
895 OutSet& affected_registers,
896 OutSet* registers_to_pop,
897 OutSet* registers_to_clear) {
898 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
899 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
900
901 // Count pushes performed to force a stack limit check occasionally.
902 int pushes = 0;
903
904 for (int reg = 0; reg <= max_register; reg++) {
905 if (!affected_registers.Get(reg)) {
906 continue;
907 }
908
909 // The chronologically first deferred action in the trace
910 // is used to infer the action needed to restore a register
911 // to its previous state (or not, if it's safe to ignore it).
912 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
913 DeferredActionUndoType undo_action = IGNORE;
914
915 int value = 0;
916 bool absolute = false;
917 bool clear = false;
918 int store_position = -1;
919 // This is a little tricky because we are scanning the actions in reverse
920 // historical order (newest first).
921 for (DeferredAction* action = actions_;
922 action != NULL;
923 action = action->next()) {
924 if (action->Mentions(reg)) {
925 switch (action->type()) {
926 case ActionNode::SET_REGISTER: {
927 Trace::DeferredSetRegister* psr =
928 static_cast<Trace::DeferredSetRegister*>(action);
929 if (!absolute) {
930 value += psr->value();
931 absolute = true;
932 }
933 // SET_REGISTER is currently only used for newly introduced loop
934 // counters. They can have a significant previous value if they
935 // occour in a loop. TODO(lrn): Propagate this information, so
936 // we can set undo_action to IGNORE if we know there is no value to
937 // restore.
938 undo_action = RESTORE;
939 ASSERT_EQ(store_position, -1);
940 ASSERT(!clear);
941 break;
942 }
943 case ActionNode::INCREMENT_REGISTER:
944 if (!absolute) {
945 value++;
946 }
947 ASSERT_EQ(store_position, -1);
948 ASSERT(!clear);
949 undo_action = RESTORE;
950 break;
951 case ActionNode::STORE_POSITION: {
952 Trace::DeferredCapture* pc =
953 static_cast<Trace::DeferredCapture*>(action);
954 if (!clear && store_position == -1) {
955 store_position = pc->cp_offset();
956 }
957
958 // For captures we know that stores and clears alternate.
959 // Other register, are never cleared, and if the occur
960 // inside a loop, they might be assigned more than once.
961 if (reg <= 1) {
962 // Registers zero and one, aka "capture zero", is
963 // always set correctly if we succeed. There is no
964 // need to undo a setting on backtrack, because we
965 // will set it again or fail.
966 undo_action = IGNORE;
967 } else {
968 undo_action = pc->is_capture() ? CLEAR : RESTORE;
969 }
970 ASSERT(!absolute);
971 ASSERT_EQ(value, 0);
972 break;
973 }
974 case ActionNode::CLEAR_CAPTURES: {
975 // Since we're scanning in reverse order, if we've already
976 // set the position we have to ignore historically earlier
977 // clearing operations.
978 if (store_position == -1) {
979 clear = true;
980 }
981 undo_action = RESTORE;
982 ASSERT(!absolute);
983 ASSERT_EQ(value, 0);
984 break;
985 }
986 default:
987 UNREACHABLE();
988 break;
989 }
990 }
991 }
992 // Prepare for the undo-action (e.g., push if it's going to be popped).
993 if (undo_action == RESTORE) {
994 pushes++;
995 RegExpMacroAssembler::StackCheckFlag stack_check =
996 RegExpMacroAssembler::kNoStackLimitCheck;
997 if (pushes == push_limit) {
998 stack_check = RegExpMacroAssembler::kCheckStackLimit;
999 pushes = 0;
1000 }
1001
1002 assembler->PushRegister(reg, stack_check);
1003 registers_to_pop->Set(reg);
1004 } else if (undo_action == CLEAR) {
1005 registers_to_clear->Set(reg);
1006 }
1007 // Perform the chronologically last action (or accumulated increment)
1008 // for the register.
1009 if (store_position != -1) {
1010 assembler->WriteCurrentPositionToRegister(reg, store_position);
1011 } else if (clear) {
1012 assembler->ClearRegisters(reg, reg);
1013 } else if (absolute) {
1014 assembler->SetRegister(reg, value);
1015 } else if (value != 0) {
1016 assembler->AdvanceRegister(reg, value);
1017 }
1018 }
1019}
1020
1021
1022// This is called as we come into a loop choice node and some other tricky
1023// nodes. It normalizes the state of the code generator to ensure we can
1024// generate generic code.
1025void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
1026 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1027
1028 ASSERT(!is_trivial());
1029
1030 if (actions_ == NULL && backtrack() == NULL) {
1031 // Here we just have some deferred cp advances to fix and we are back to
1032 // a normal situation. We may also have to forget some information gained
1033 // through a quick check that was already performed.
1034 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
1035 // Create a new trivial state and generate the node with that.
1036 Trace new_state;
1037 successor->Emit(compiler, &new_state);
1038 return;
1039 }
1040
1041 // Generate deferred actions here along with code to undo them again.
1042 OutSet affected_registers;
1043
1044 if (backtrack() != NULL) {
1045 // Here we have a concrete backtrack location. These are set up by choice
1046 // nodes and so they indicate that we have a deferred save of the current
1047 // position which we may need to emit here.
1048 assembler->PushCurrentPosition();
1049 }
1050
1051 int max_register = FindAffectedRegisters(&affected_registers);
1052 OutSet registers_to_pop;
1053 OutSet registers_to_clear;
1054 PerformDeferredActions(assembler,
1055 max_register,
1056 affected_registers,
1057 &registers_to_pop,
1058 &registers_to_clear);
1059 if (cp_offset_ != 0) {
1060 assembler->AdvanceCurrentPosition(cp_offset_);
1061 }
1062
1063 // Create a new trivial state and generate the node with that.
1064 Label undo;
1065 assembler->PushBacktrack(&undo);
1066 Trace new_state;
1067 successor->Emit(compiler, &new_state);
1068
1069 // On backtrack we need to restore state.
1070 assembler->Bind(&undo);
1071 RestoreAffectedRegisters(assembler,
1072 max_register,
1073 registers_to_pop,
1074 registers_to_clear);
1075 if (backtrack() == NULL) {
1076 assembler->Backtrack();
1077 } else {
1078 assembler->PopCurrentPosition();
1079 assembler->GoTo(backtrack());
1080 }
1081}
1082
1083
1084void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
1085 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1086
1087 // Omit flushing the trace. We discard the entire stack frame anyway.
1088
1089 if (!label()->is_bound()) {
1090 // We are completely independent of the trace, since we ignore it,
1091 // so this code can be used as the generic version.
1092 assembler->Bind(label());
1093 }
1094
1095 // Throw away everything on the backtrack stack since the start
1096 // of the negative submatch and restore the character position.
1097 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1098 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
1099 if (clear_capture_count_ > 0) {
1100 // Clear any captures that might have been performed during the success
1101 // of the body of the negative look-ahead.
1102 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1103 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1104 }
1105 // Now that we have unwound the stack we find at the top of the stack the
1106 // backtrack that the BeginSubmatch node got.
1107 assembler->Backtrack();
1108}
1109
1110
1111void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
1112 if (!trace->is_trivial()) {
1113 trace->Flush(compiler, this);
1114 return;
1115 }
1116 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1117 if (!label()->is_bound()) {
1118 assembler->Bind(label());
1119 }
1120 switch (action_) {
1121 case ACCEPT:
1122 assembler->Succeed();
1123 return;
1124 case BACKTRACK:
1125 assembler->GoTo(trace->backtrack());
1126 return;
1127 case NEGATIVE_SUBMATCH_SUCCESS:
1128 // This case is handled in a different virtual method.
1129 UNREACHABLE();
1130 }
1131 UNIMPLEMENTED();
1132}
1133
1134
1135void GuardedAlternative::AddGuard(Guard* guard) {
1136 if (guards_ == NULL)
1137 guards_ = new ZoneList<Guard*>(1);
1138 guards_->Add(guard);
1139}
1140
1141
1142ActionNode* ActionNode::SetRegister(int reg,
1143 int val,
1144 RegExpNode* on_success) {
1145 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
1146 result->data_.u_store_register.reg = reg;
1147 result->data_.u_store_register.value = val;
1148 return result;
1149}
1150
1151
1152ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1153 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1154 result->data_.u_increment_register.reg = reg;
1155 return result;
1156}
1157
1158
1159ActionNode* ActionNode::StorePosition(int reg,
1160 bool is_capture,
1161 RegExpNode* on_success) {
1162 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1163 result->data_.u_position_register.reg = reg;
1164 result->data_.u_position_register.is_capture = is_capture;
1165 return result;
1166}
1167
1168
1169ActionNode* ActionNode::ClearCaptures(Interval range,
1170 RegExpNode* on_success) {
1171 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1172 result->data_.u_clear_captures.range_from = range.from();
1173 result->data_.u_clear_captures.range_to = range.to();
1174 return result;
1175}
1176
1177
1178ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1179 int position_reg,
1180 RegExpNode* on_success) {
1181 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1182 result->data_.u_submatch.stack_pointer_register = stack_reg;
1183 result->data_.u_submatch.current_position_register = position_reg;
1184 return result;
1185}
1186
1187
1188ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1189 int position_reg,
1190 int clear_register_count,
1191 int clear_register_from,
1192 RegExpNode* on_success) {
1193 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
1194 result->data_.u_submatch.stack_pointer_register = stack_reg;
1195 result->data_.u_submatch.current_position_register = position_reg;
1196 result->data_.u_submatch.clear_register_count = clear_register_count;
1197 result->data_.u_submatch.clear_register_from = clear_register_from;
1198 return result;
1199}
1200
1201
1202ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1203 int repetition_register,
1204 int repetition_limit,
1205 RegExpNode* on_success) {
1206 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1207 result->data_.u_empty_match_check.start_register = start_register;
1208 result->data_.u_empty_match_check.repetition_register = repetition_register;
1209 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1210 return result;
1211}
1212
1213
1214#define DEFINE_ACCEPT(Type) \
1215 void Type##Node::Accept(NodeVisitor* visitor) { \
1216 visitor->Visit##Type(this); \
1217 }
1218FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1219#undef DEFINE_ACCEPT
1220
1221
1222void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1223 visitor->VisitLoopChoice(this);
1224}
1225
1226
1227// -------------------------------------------------------------------
1228// Emit code.
1229
1230
1231void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1232 Guard* guard,
1233 Trace* trace) {
1234 switch (guard->op()) {
1235 case Guard::LT:
1236 ASSERT(!trace->mentions_reg(guard->reg()));
1237 macro_assembler->IfRegisterGE(guard->reg(),
1238 guard->value(),
1239 trace->backtrack());
1240 break;
1241 case Guard::GEQ:
1242 ASSERT(!trace->mentions_reg(guard->reg()));
1243 macro_assembler->IfRegisterLT(guard->reg(),
1244 guard->value(),
1245 trace->backtrack());
1246 break;
1247 }
1248}
1249
1250
1251static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1252static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1253
1254
1255// Returns the number of characters in the equivalence class, omitting those
1256// that cannot occur in the source string because it is ASCII.
1257static int GetCaseIndependentLetters(uc16 character,
1258 bool ascii_subject,
1259 unibrow::uchar* letters) {
1260 int length = uncanonicalize.get(character, '\0', letters);
1261 // Unibrow returns 0 or 1 for characters where case independependence is
1262 // trivial.
1263 if (length == 0) {
1264 letters[0] = character;
1265 length = 1;
1266 }
1267 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1268 return length;
1269 }
1270 // The standard requires that non-ASCII characters cannot have ASCII
1271 // character codes in their equivalence class.
1272 return 0;
1273}
1274
1275
1276static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1277 uc16 c,
1278 Label* on_failure,
1279 int cp_offset,
1280 bool check,
1281 bool preloaded) {
1282 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1283 bool bound_checked = false;
1284 if (!preloaded) {
1285 assembler->LoadCurrentCharacter(
1286 cp_offset,
1287 on_failure,
1288 check);
1289 bound_checked = true;
1290 }
1291 assembler->CheckNotCharacter(c, on_failure);
1292 return bound_checked;
1293}
1294
1295
1296// Only emits non-letters (things that don't have case). Only used for case
1297// independent matches.
1298static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1299 uc16 c,
1300 Label* on_failure,
1301 int cp_offset,
1302 bool check,
1303 bool preloaded) {
1304 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1305 bool ascii = compiler->ascii();
1306 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1307 int length = GetCaseIndependentLetters(c, ascii, chars);
1308 if (length < 1) {
1309 // This can't match. Must be an ASCII subject and a non-ASCII character.
1310 // We do not need to do anything since the ASCII pass already handled this.
1311 return false; // Bounds not checked.
1312 }
1313 bool checked = false;
1314 // We handle the length > 1 case in a later pass.
1315 if (length == 1) {
1316 if (ascii && c > String::kMaxAsciiCharCodeU) {
1317 // Can't match - see above.
1318 return false; // Bounds not checked.
1319 }
1320 if (!preloaded) {
1321 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1322 checked = check;
1323 }
1324 macro_assembler->CheckNotCharacter(c, on_failure);
1325 }
1326 return checked;
1327}
1328
1329
1330static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
1331 bool ascii,
1332 uc16 c1,
1333 uc16 c2,
1334 Label* on_failure) {
1335 uc16 char_mask;
1336 if (ascii) {
1337 char_mask = String::kMaxAsciiCharCode;
1338 } else {
1339 char_mask = String::kMaxUC16CharCode;
1340 }
1341 uc16 exor = c1 ^ c2;
1342 // Check whether exor has only one bit set.
1343 if (((exor - 1) & exor) == 0) {
1344 // If c1 and c2 differ only by one bit.
1345 // Ecma262UnCanonicalize always gives the highest number last.
1346 ASSERT(c2 > c1);
1347 uc16 mask = char_mask ^ exor;
1348 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
1349 return true;
1350 }
1351 ASSERT(c2 > c1);
1352 uc16 diff = c2 - c1;
1353 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1354 // If the characters differ by 2^n but don't differ by one bit then
1355 // subtract the difference from the found character, then do the or
1356 // trick. We avoid the theoretical case where negative numbers are
1357 // involved in order to simplify code generation.
1358 uc16 mask = char_mask ^ diff;
1359 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1360 diff,
1361 mask,
1362 on_failure);
1363 return true;
1364 }
1365 return false;
1366}
1367
1368
1369typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1370 uc16 c,
1371 Label* on_failure,
1372 int cp_offset,
1373 bool check,
1374 bool preloaded);
1375
1376// Only emits letters (things that have case). Only used for case independent
1377// matches.
1378static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1379 uc16 c,
1380 Label* on_failure,
1381 int cp_offset,
1382 bool check,
1383 bool preloaded) {
1384 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1385 bool ascii = compiler->ascii();
1386 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1387 int length = GetCaseIndependentLetters(c, ascii, chars);
1388 if (length <= 1) return false;
1389 // We may not need to check against the end of the input string
1390 // if this character lies before a character that matched.
1391 if (!preloaded) {
1392 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1393 }
1394 Label ok;
1395 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1396 switch (length) {
1397 case 2: {
1398 if (ShortCutEmitCharacterPair(macro_assembler,
1399 ascii,
1400 chars[0],
1401 chars[1],
1402 on_failure)) {
1403 } else {
1404 macro_assembler->CheckCharacter(chars[0], &ok);
1405 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1406 macro_assembler->Bind(&ok);
1407 }
1408 break;
1409 }
1410 case 4:
1411 macro_assembler->CheckCharacter(chars[3], &ok);
1412 // Fall through!
1413 case 3:
1414 macro_assembler->CheckCharacter(chars[0], &ok);
1415 macro_assembler->CheckCharacter(chars[1], &ok);
1416 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1417 macro_assembler->Bind(&ok);
1418 break;
1419 default:
1420 UNREACHABLE();
1421 break;
1422 }
1423 return true;
1424}
1425
1426
1427static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1428 RegExpCharacterClass* cc,
1429 bool ascii,
1430 Label* on_failure,
1431 int cp_offset,
1432 bool check_offset,
1433 bool preloaded) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001434 ZoneList<CharacterRange>* ranges = cc->ranges();
1435 int max_char;
1436 if (ascii) {
1437 max_char = String::kMaxAsciiCharCode;
1438 } else {
1439 max_char = String::kMaxUC16CharCode;
1440 }
1441
1442 Label success;
1443
1444 Label* char_is_in_class =
1445 cc->is_negated() ? on_failure : &success;
1446
1447 int range_count = ranges->length();
1448
1449 int last_valid_range = range_count - 1;
1450 while (last_valid_range >= 0) {
1451 CharacterRange& range = ranges->at(last_valid_range);
1452 if (range.from() <= max_char) {
1453 break;
1454 }
1455 last_valid_range--;
1456 }
1457
1458 if (last_valid_range < 0) {
1459 if (!cc->is_negated()) {
1460 // TODO(plesner): We can remove this when the node level does our
1461 // ASCII optimizations for us.
1462 macro_assembler->GoTo(on_failure);
1463 }
1464 if (check_offset) {
1465 macro_assembler->CheckPosition(cp_offset, on_failure);
1466 }
1467 return;
1468 }
1469
1470 if (last_valid_range == 0 &&
1471 !cc->is_negated() &&
1472 ranges->at(0).IsEverything(max_char)) {
1473 // This is a common case hit by non-anchored expressions.
1474 if (check_offset) {
1475 macro_assembler->CheckPosition(cp_offset, on_failure);
1476 }
1477 return;
1478 }
1479
1480 if (!preloaded) {
1481 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
1482 }
1483
Leon Clarkee46be812010-01-19 14:06:41 +00001484 if (cc->is_standard() &&
1485 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1486 on_failure)) {
1487 return;
1488 }
1489
Steve Blocka7e24c12009-10-30 11:49:00 +00001490 for (int i = 0; i < last_valid_range; i++) {
1491 CharacterRange& range = ranges->at(i);
1492 Label next_range;
1493 uc16 from = range.from();
1494 uc16 to = range.to();
1495 if (from > max_char) {
1496 continue;
1497 }
1498 if (to > max_char) to = max_char;
1499 if (to == from) {
1500 macro_assembler->CheckCharacter(to, char_is_in_class);
1501 } else {
1502 if (from != 0) {
1503 macro_assembler->CheckCharacterLT(from, &next_range);
1504 }
1505 if (to != max_char) {
1506 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1507 } else {
1508 macro_assembler->GoTo(char_is_in_class);
1509 }
1510 }
1511 macro_assembler->Bind(&next_range);
1512 }
1513
1514 CharacterRange& range = ranges->at(last_valid_range);
1515 uc16 from = range.from();
1516 uc16 to = range.to();
1517
1518 if (to > max_char) to = max_char;
1519 ASSERT(to >= from);
1520
1521 if (to == from) {
1522 if (cc->is_negated()) {
1523 macro_assembler->CheckCharacter(to, on_failure);
1524 } else {
1525 macro_assembler->CheckNotCharacter(to, on_failure);
1526 }
1527 } else {
1528 if (from != 0) {
1529 if (cc->is_negated()) {
1530 macro_assembler->CheckCharacterLT(from, &success);
1531 } else {
1532 macro_assembler->CheckCharacterLT(from, on_failure);
1533 }
1534 }
1535 if (to != String::kMaxUC16CharCode) {
1536 if (cc->is_negated()) {
1537 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1538 } else {
1539 macro_assembler->CheckCharacterGT(to, on_failure);
1540 }
1541 } else {
1542 if (cc->is_negated()) {
1543 macro_assembler->GoTo(on_failure);
1544 }
1545 }
1546 }
1547 macro_assembler->Bind(&success);
1548}
1549
1550
1551RegExpNode::~RegExpNode() {
1552}
1553
1554
1555RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
1556 Trace* trace) {
1557 // If we are generating a greedy loop then don't stop and don't reuse code.
1558 if (trace->stop_node() != NULL) {
1559 return CONTINUE;
1560 }
1561
1562 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1563 if (trace->is_trivial()) {
1564 if (label_.is_bound()) {
1565 // We are being asked to generate a generic version, but that's already
1566 // been done so just go to it.
1567 macro_assembler->GoTo(&label_);
1568 return DONE;
1569 }
1570 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1571 // To avoid too deep recursion we push the node to the work queue and just
1572 // generate a goto here.
1573 compiler->AddWork(this);
1574 macro_assembler->GoTo(&label_);
1575 return DONE;
1576 }
1577 // Generate generic version of the node and bind the label for later use.
1578 macro_assembler->Bind(&label_);
1579 return CONTINUE;
1580 }
1581
1582 // We are being asked to make a non-generic version. Keep track of how many
1583 // non-generic versions we generate so as not to overdo it.
1584 trace_count_++;
1585 if (FLAG_regexp_optimization &&
1586 trace_count_ < kMaxCopiesCodeGenerated &&
1587 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1588 return CONTINUE;
1589 }
1590
1591 // If we get here code has been generated for this node too many times or
1592 // recursion is too deep. Time to switch to a generic version. The code for
1593 // generic versions above can handle deep recursion properly.
1594 trace->Flush(compiler, this);
1595 return DONE;
1596}
1597
1598
1599int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1600 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1601 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
1602 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1603}
1604
1605
1606int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1607 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1608 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1609}
1610
1611
1612int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1613 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1614 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1615}
1616
1617
1618int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1619 int answer = Length();
1620 if (answer >= still_to_find) return answer;
1621 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
1622 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1623 recursion_depth + 1);
1624}
1625
1626
Leon Clarkee46be812010-01-19 14:06:41 +00001627int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
1628 int recursion_depth) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001629 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1630 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1631 // afterwards.
1632 RegExpNode* node = alternatives_->at(1).node();
1633 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1634}
1635
1636
1637void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1638 QuickCheckDetails* details,
1639 RegExpCompiler* compiler,
1640 int filled_in,
1641 bool not_at_start) {
1642 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1643 // afterwards.
1644 RegExpNode* node = alternatives_->at(1).node();
1645 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
1646}
1647
1648
1649int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1650 int recursion_depth,
1651 RegExpNode* ignore_this_node) {
1652 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1653 int min = 100;
1654 int choice_count = alternatives_->length();
1655 for (int i = 0; i < choice_count; i++) {
1656 RegExpNode* node = alternatives_->at(i).node();
1657 if (node == ignore_this_node) continue;
1658 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1659 recursion_depth + 1);
1660 if (node_eats_at_least < min) min = node_eats_at_least;
1661 }
1662 return min;
1663}
1664
1665
1666int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1667 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
1668}
1669
1670
1671int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1672 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
1673}
1674
1675
1676// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1677static inline uint32_t SmearBitsRight(uint32_t v) {
1678 v |= v >> 1;
1679 v |= v >> 2;
1680 v |= v >> 4;
1681 v |= v >> 8;
1682 v |= v >> 16;
1683 return v;
1684}
1685
1686
1687bool QuickCheckDetails::Rationalize(bool asc) {
1688 bool found_useful_op = false;
1689 uint32_t char_mask;
1690 if (asc) {
1691 char_mask = String::kMaxAsciiCharCode;
1692 } else {
1693 char_mask = String::kMaxUC16CharCode;
1694 }
1695 mask_ = 0;
1696 value_ = 0;
1697 int char_shift = 0;
1698 for (int i = 0; i < characters_; i++) {
1699 Position* pos = &positions_[i];
1700 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1701 found_useful_op = true;
1702 }
1703 mask_ |= (pos->mask & char_mask) << char_shift;
1704 value_ |= (pos->value & char_mask) << char_shift;
1705 char_shift += asc ? 8 : 16;
1706 }
1707 return found_useful_op;
1708}
1709
1710
1711bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
1712 Trace* trace,
1713 bool preload_has_checked_bounds,
1714 Label* on_possible_success,
1715 QuickCheckDetails* details,
1716 bool fall_through_on_failure) {
1717 if (details->characters() == 0) return false;
1718 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1719 if (details->cannot_match()) return false;
1720 if (!details->Rationalize(compiler->ascii())) return false;
1721 ASSERT(details->characters() == 1 ||
1722 compiler->macro_assembler()->CanReadUnaligned());
1723 uint32_t mask = details->mask();
1724 uint32_t value = details->value();
1725
1726 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1727
1728 if (trace->characters_preloaded() != details->characters()) {
1729 assembler->LoadCurrentCharacter(trace->cp_offset(),
1730 trace->backtrack(),
1731 !preload_has_checked_bounds,
1732 details->characters());
1733 }
1734
1735
1736 bool need_mask = true;
1737
1738 if (details->characters() == 1) {
1739 // If number of characters preloaded is 1 then we used a byte or 16 bit
1740 // load so the value is already masked down.
1741 uint32_t char_mask;
1742 if (compiler->ascii()) {
1743 char_mask = String::kMaxAsciiCharCode;
1744 } else {
1745 char_mask = String::kMaxUC16CharCode;
1746 }
1747 if ((mask & char_mask) == char_mask) need_mask = false;
1748 mask &= char_mask;
1749 } else {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001750 // For 2-character preloads in ASCII mode or 1-character preloads in
1751 // TWO_BYTE mode we also use a 16 bit load with zero extend.
Steve Blocka7e24c12009-10-30 11:49:00 +00001752 if (details->characters() == 2 && compiler->ascii()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001753 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1754 } else if (details->characters() == 1 && !compiler->ascii()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001755 if ((mask & 0xffff) == 0xffff) need_mask = false;
1756 } else {
1757 if (mask == 0xffffffff) need_mask = false;
1758 }
1759 }
1760
1761 if (fall_through_on_failure) {
1762 if (need_mask) {
1763 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1764 } else {
1765 assembler->CheckCharacter(value, on_possible_success);
1766 }
1767 } else {
1768 if (need_mask) {
1769 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
1770 } else {
1771 assembler->CheckNotCharacter(value, trace->backtrack());
1772 }
1773 }
1774 return true;
1775}
1776
1777
1778// Here is the meat of GetQuickCheckDetails (see also the comment on the
1779// super-class in the .h file).
1780//
1781// We iterate along the text object, building up for each character a
1782// mask and value that can be used to test for a quick failure to match.
1783// The masks and values for the positions will be combined into a single
1784// machine word for the current character width in order to be used in
1785// generating a quick check.
1786void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1787 RegExpCompiler* compiler,
1788 int characters_filled_in,
1789 bool not_at_start) {
1790 ASSERT(characters_filled_in < details->characters());
1791 int characters = details->characters();
1792 int char_mask;
1793 int char_shift;
1794 if (compiler->ascii()) {
1795 char_mask = String::kMaxAsciiCharCode;
1796 char_shift = 8;
1797 } else {
1798 char_mask = String::kMaxUC16CharCode;
1799 char_shift = 16;
1800 }
1801 for (int k = 0; k < elms_->length(); k++) {
1802 TextElement elm = elms_->at(k);
1803 if (elm.type == TextElement::ATOM) {
1804 Vector<const uc16> quarks = elm.data.u_atom->data();
1805 for (int i = 0; i < characters && i < quarks.length(); i++) {
1806 QuickCheckDetails::Position* pos =
1807 details->positions(characters_filled_in);
1808 uc16 c = quarks[i];
1809 if (c > char_mask) {
1810 // If we expect a non-ASCII character from an ASCII string,
1811 // there is no way we can match. Not even case independent
1812 // matching can turn an ASCII character into non-ASCII or
1813 // vice versa.
1814 details->set_cannot_match();
1815 pos->determines_perfectly = false;
1816 return;
1817 }
1818 if (compiler->ignore_case()) {
1819 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1820 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1821 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1822 if (length == 1) {
1823 // This letter has no case equivalents, so it's nice and simple
1824 // and the mask-compare will determine definitely whether we have
1825 // a match at this character position.
1826 pos->mask = char_mask;
1827 pos->value = c;
1828 pos->determines_perfectly = true;
1829 } else {
1830 uint32_t common_bits = char_mask;
1831 uint32_t bits = chars[0];
1832 for (int j = 1; j < length; j++) {
1833 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1834 common_bits ^= differing_bits;
1835 bits &= common_bits;
1836 }
1837 // If length is 2 and common bits has only one zero in it then
1838 // our mask and compare instruction will determine definitely
1839 // whether we have a match at this character position. Otherwise
1840 // it can only be an approximate check.
1841 uint32_t one_zero = (common_bits | ~char_mask);
1842 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1843 pos->determines_perfectly = true;
1844 }
1845 pos->mask = common_bits;
1846 pos->value = bits;
1847 }
1848 } else {
1849 // Don't ignore case. Nice simple case where the mask-compare will
1850 // determine definitely whether we have a match at this character
1851 // position.
1852 pos->mask = char_mask;
1853 pos->value = c;
1854 pos->determines_perfectly = true;
1855 }
1856 characters_filled_in++;
1857 ASSERT(characters_filled_in <= details->characters());
1858 if (characters_filled_in == details->characters()) {
1859 return;
1860 }
1861 }
1862 } else {
1863 QuickCheckDetails::Position* pos =
1864 details->positions(characters_filled_in);
1865 RegExpCharacterClass* tree = elm.data.u_char_class;
1866 ZoneList<CharacterRange>* ranges = tree->ranges();
1867 if (tree->is_negated()) {
1868 // A quick check uses multi-character mask and compare. There is no
1869 // useful way to incorporate a negative char class into this scheme
1870 // so we just conservatively create a mask and value that will always
1871 // succeed.
1872 pos->mask = 0;
1873 pos->value = 0;
1874 } else {
1875 int first_range = 0;
1876 while (ranges->at(first_range).from() > char_mask) {
1877 first_range++;
1878 if (first_range == ranges->length()) {
1879 details->set_cannot_match();
1880 pos->determines_perfectly = false;
1881 return;
1882 }
1883 }
1884 CharacterRange range = ranges->at(first_range);
1885 uc16 from = range.from();
1886 uc16 to = range.to();
1887 if (to > char_mask) {
1888 to = char_mask;
1889 }
1890 uint32_t differing_bits = (from ^ to);
1891 // A mask and compare is only perfect if the differing bits form a
1892 // number like 00011111 with one single block of trailing 1s.
1893 if ((differing_bits & (differing_bits + 1)) == 0 &&
1894 from + differing_bits == to) {
1895 pos->determines_perfectly = true;
1896 }
1897 uint32_t common_bits = ~SmearBitsRight(differing_bits);
1898 uint32_t bits = (from & common_bits);
1899 for (int i = first_range + 1; i < ranges->length(); i++) {
1900 CharacterRange range = ranges->at(i);
1901 uc16 from = range.from();
1902 uc16 to = range.to();
1903 if (from > char_mask) continue;
1904 if (to > char_mask) to = char_mask;
1905 // Here we are combining more ranges into the mask and compare
1906 // value. With each new range the mask becomes more sparse and
1907 // so the chances of a false positive rise. A character class
1908 // with multiple ranges is assumed never to be equivalent to a
1909 // mask and compare operation.
1910 pos->determines_perfectly = false;
1911 uint32_t new_common_bits = (from ^ to);
1912 new_common_bits = ~SmearBitsRight(new_common_bits);
1913 common_bits &= new_common_bits;
1914 bits &= new_common_bits;
1915 uint32_t differing_bits = (from & common_bits) ^ bits;
1916 common_bits ^= differing_bits;
1917 bits &= common_bits;
1918 }
1919 pos->mask = common_bits;
1920 pos->value = bits;
1921 }
1922 characters_filled_in++;
1923 ASSERT(characters_filled_in <= details->characters());
1924 if (characters_filled_in == details->characters()) {
1925 return;
1926 }
1927 }
1928 }
1929 ASSERT(characters_filled_in != details->characters());
1930 on_success()-> GetQuickCheckDetails(details,
1931 compiler,
1932 characters_filled_in,
1933 true);
1934}
1935
1936
1937void QuickCheckDetails::Clear() {
1938 for (int i = 0; i < characters_; i++) {
1939 positions_[i].mask = 0;
1940 positions_[i].value = 0;
1941 positions_[i].determines_perfectly = false;
1942 }
1943 characters_ = 0;
1944}
1945
1946
1947void QuickCheckDetails::Advance(int by, bool ascii) {
1948 ASSERT(by >= 0);
1949 if (by >= characters_) {
1950 Clear();
1951 return;
1952 }
1953 for (int i = 0; i < characters_ - by; i++) {
1954 positions_[i] = positions_[by + i];
1955 }
1956 for (int i = characters_ - by; i < characters_; i++) {
1957 positions_[i].mask = 0;
1958 positions_[i].value = 0;
1959 positions_[i].determines_perfectly = false;
1960 }
1961 characters_ -= by;
1962 // We could change mask_ and value_ here but we would never advance unless
1963 // they had already been used in a check and they won't be used again because
1964 // it would gain us nothing. So there's no point.
1965}
1966
1967
1968void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1969 ASSERT(characters_ == other->characters_);
1970 if (other->cannot_match_) {
1971 return;
1972 }
1973 if (cannot_match_) {
1974 *this = *other;
1975 return;
1976 }
1977 for (int i = from_index; i < characters_; i++) {
1978 QuickCheckDetails::Position* pos = positions(i);
1979 QuickCheckDetails::Position* other_pos = other->positions(i);
1980 if (pos->mask != other_pos->mask ||
1981 pos->value != other_pos->value ||
1982 !other_pos->determines_perfectly) {
1983 // Our mask-compare operation will be approximate unless we have the
1984 // exact same operation on both sides of the alternation.
1985 pos->determines_perfectly = false;
1986 }
1987 pos->mask &= other_pos->mask;
1988 pos->value &= pos->mask;
1989 other_pos->value &= pos->mask;
1990 uc16 differing_bits = (pos->value ^ other_pos->value);
1991 pos->mask &= ~differing_bits;
1992 pos->value &= pos->mask;
1993 }
1994}
1995
1996
1997class VisitMarker {
1998 public:
1999 explicit VisitMarker(NodeInfo* info) : info_(info) {
2000 ASSERT(!info->visited);
2001 info->visited = true;
2002 }
2003 ~VisitMarker() {
2004 info_->visited = false;
2005 }
2006 private:
2007 NodeInfo* info_;
2008};
2009
2010
2011void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2012 RegExpCompiler* compiler,
2013 int characters_filled_in,
2014 bool not_at_start) {
2015 if (body_can_be_zero_length_ || info()->visited) return;
2016 VisitMarker marker(info());
2017 return ChoiceNode::GetQuickCheckDetails(details,
2018 compiler,
2019 characters_filled_in,
2020 not_at_start);
2021}
2022
2023
2024void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2025 RegExpCompiler* compiler,
2026 int characters_filled_in,
2027 bool not_at_start) {
2028 not_at_start = (not_at_start || not_at_start_);
2029 int choice_count = alternatives_->length();
2030 ASSERT(choice_count > 0);
2031 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2032 compiler,
2033 characters_filled_in,
2034 not_at_start);
2035 for (int i = 1; i < choice_count; i++) {
2036 QuickCheckDetails new_details(details->characters());
2037 RegExpNode* node = alternatives_->at(i).node();
2038 node->GetQuickCheckDetails(&new_details, compiler,
2039 characters_filled_in,
2040 not_at_start);
2041 // Here we merge the quick match details of the two branches.
2042 details->Merge(&new_details, characters_filled_in);
2043 }
2044}
2045
2046
2047// Check for [0-9A-Z_a-z].
2048static void EmitWordCheck(RegExpMacroAssembler* assembler,
2049 Label* word,
2050 Label* non_word,
2051 bool fall_through_on_word) {
Leon Clarkee46be812010-01-19 14:06:41 +00002052 if (assembler->CheckSpecialCharacterClass(
2053 fall_through_on_word ? 'w' : 'W',
2054 fall_through_on_word ? non_word : word)) {
2055 // Optimized implementation available.
2056 return;
2057 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002058 assembler->CheckCharacterGT('z', non_word);
2059 assembler->CheckCharacterLT('0', non_word);
2060 assembler->CheckCharacterGT('a' - 1, word);
2061 assembler->CheckCharacterLT('9' + 1, word);
2062 assembler->CheckCharacterLT('A', non_word);
2063 assembler->CheckCharacterLT('Z' + 1, word);
2064 if (fall_through_on_word) {
2065 assembler->CheckNotCharacter('_', non_word);
2066 } else {
2067 assembler->CheckCharacter('_', word);
2068 }
2069}
2070
2071
2072// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2073// that matches newline or the start of input).
2074static void EmitHat(RegExpCompiler* compiler,
2075 RegExpNode* on_success,
2076 Trace* trace) {
2077 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2078 // We will be loading the previous character into the current character
2079 // register.
2080 Trace new_trace(*trace);
2081 new_trace.InvalidateCurrentCharacter();
2082
2083 Label ok;
2084 if (new_trace.cp_offset() == 0) {
2085 // The start of input counts as a newline in this context, so skip to
2086 // ok if we are at the start.
2087 assembler->CheckAtStart(&ok);
2088 }
2089 // We already checked that we are not at the start of input so it must be
2090 // OK to load the previous character.
2091 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2092 new_trace.backtrack(),
2093 false);
Leon Clarkee46be812010-01-19 14:06:41 +00002094 if (!assembler->CheckSpecialCharacterClass('n',
2095 new_trace.backtrack())) {
2096 // Newline means \n, \r, 0x2028 or 0x2029.
2097 if (!compiler->ascii()) {
2098 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2099 }
2100 assembler->CheckCharacter('\n', &ok);
2101 assembler->CheckNotCharacter('\r', new_trace.backtrack());
Steve Blocka7e24c12009-10-30 11:49:00 +00002102 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002103 assembler->Bind(&ok);
2104 on_success->Emit(compiler, &new_trace);
2105}
2106
2107
Leon Clarkee46be812010-01-19 14:06:41 +00002108// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2109// when we know whether the next character must be a word character or not.
2110static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2111 RegExpCompiler* compiler,
2112 RegExpNode* on_success,
2113 Trace* trace) {
2114 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2115 Label done;
2116
2117 Trace new_trace(*trace);
2118
2119 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2120 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2121 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2122
2123 // Check whether previous character was a word character.
2124 switch (trace->at_start()) {
2125 case Trace::TRUE:
2126 if (expect_word_character) {
2127 assembler->GoTo(on_non_word);
2128 }
2129 break;
2130 case Trace::UNKNOWN:
2131 ASSERT_EQ(0, trace->cp_offset());
2132 assembler->CheckAtStart(on_non_word);
2133 // Fall through.
2134 case Trace::FALSE:
2135 int prev_char_offset = trace->cp_offset() - 1;
2136 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2137 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2138 // We may or may not have loaded the previous character.
2139 new_trace.InvalidateCurrentCharacter();
2140 }
2141
2142 assembler->Bind(&done);
2143
2144 on_success->Emit(compiler, &new_trace);
2145}
2146
2147
Steve Blocka7e24c12009-10-30 11:49:00 +00002148// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2149static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2150 RegExpCompiler* compiler,
2151 RegExpNode* on_success,
2152 Trace* trace) {
2153 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2154 Label before_non_word;
2155 Label before_word;
2156 if (trace->characters_preloaded() != 1) {
2157 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2158 }
2159 // Fall through on non-word.
2160 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2161
2162 // We will be loading the previous character into the current character
2163 // register.
2164 Trace new_trace(*trace);
2165 new_trace.InvalidateCurrentCharacter();
2166
2167 Label ok;
2168 Label* boundary;
2169 Label* not_boundary;
2170 if (type == AssertionNode::AT_BOUNDARY) {
2171 boundary = &ok;
2172 not_boundary = new_trace.backtrack();
2173 } else {
2174 not_boundary = &ok;
2175 boundary = new_trace.backtrack();
2176 }
2177
2178 // Next character is not a word character.
2179 assembler->Bind(&before_non_word);
2180 if (new_trace.cp_offset() == 0) {
2181 // The start of input counts as a non-word character, so the question is
2182 // decided if we are at the start.
2183 assembler->CheckAtStart(not_boundary);
2184 }
2185 // We already checked that we are not at the start of input so it must be
2186 // OK to load the previous character.
2187 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2188 &ok, // Unused dummy label in this call.
2189 false);
2190 // Fall through on non-word.
2191 EmitWordCheck(assembler, boundary, not_boundary, false);
2192 assembler->GoTo(not_boundary);
2193
2194 // Next character is a word character.
2195 assembler->Bind(&before_word);
2196 if (new_trace.cp_offset() == 0) {
2197 // The start of input counts as a non-word character, so the question is
2198 // decided if we are at the start.
2199 assembler->CheckAtStart(boundary);
2200 }
2201 // We already checked that we are not at the start of input so it must be
2202 // OK to load the previous character.
2203 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2204 &ok, // Unused dummy label in this call.
2205 false);
2206 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2207 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2208
2209 assembler->Bind(&ok);
2210
2211 on_success->Emit(compiler, &new_trace);
2212}
2213
2214
2215void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2216 RegExpCompiler* compiler,
2217 int filled_in,
2218 bool not_at_start) {
2219 if (type_ == AT_START && not_at_start) {
2220 details->set_cannot_match();
2221 return;
2222 }
2223 return on_success()->GetQuickCheckDetails(details,
2224 compiler,
2225 filled_in,
2226 not_at_start);
2227}
2228
2229
2230void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2231 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2232 switch (type_) {
2233 case AT_END: {
2234 Label ok;
2235 assembler->CheckPosition(trace->cp_offset(), &ok);
2236 assembler->GoTo(trace->backtrack());
2237 assembler->Bind(&ok);
2238 break;
2239 }
2240 case AT_START: {
2241 if (trace->at_start() == Trace::FALSE) {
2242 assembler->GoTo(trace->backtrack());
2243 return;
2244 }
2245 if (trace->at_start() == Trace::UNKNOWN) {
2246 assembler->CheckNotAtStart(trace->backtrack());
2247 Trace at_start_trace = *trace;
2248 at_start_trace.set_at_start(true);
2249 on_success()->Emit(compiler, &at_start_trace);
2250 return;
2251 }
2252 }
2253 break;
2254 case AFTER_NEWLINE:
2255 EmitHat(compiler, on_success(), trace);
2256 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002257 case AT_BOUNDARY:
Leon Clarkee46be812010-01-19 14:06:41 +00002258 case AT_NON_BOUNDARY: {
Steve Blocka7e24c12009-10-30 11:49:00 +00002259 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2260 return;
Leon Clarkee46be812010-01-19 14:06:41 +00002261 }
2262 case AFTER_WORD_CHARACTER:
2263 case AFTER_NONWORD_CHARACTER: {
2264 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2265 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002266 }
2267 on_success()->Emit(compiler, trace);
2268}
2269
2270
2271static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2272 if (quick_check == NULL) return false;
2273 if (offset >= quick_check->characters()) return false;
2274 return quick_check->positions(offset)->determines_perfectly;
2275}
2276
2277
2278static void UpdateBoundsCheck(int index, int* checked_up_to) {
2279 if (index > *checked_up_to) {
2280 *checked_up_to = index;
2281 }
2282}
2283
2284
2285// We call this repeatedly to generate code for each pass over the text node.
2286// The passes are in increasing order of difficulty because we hope one
2287// of the first passes will fail in which case we are saved the work of the
2288// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2289// we will check the '%' in the first pass, the case independent 'a' in the
2290// second pass and the character class in the last pass.
2291//
2292// The passes are done from right to left, so for example to test for /bar/
2293// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2294// and then a 'b' with offset 0. This means we can avoid the end-of-input
2295// bounds check most of the time. In the example we only need to check for
2296// end-of-input when loading the putative 'r'.
2297//
2298// A slight complication involves the fact that the first character may already
2299// be fetched into a register by the previous node. In this case we want to
2300// do the test for that character first. We do this in separate passes. The
2301// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2302// pass has been performed then subsequent passes will have true in
2303// first_element_checked to indicate that that character does not need to be
2304// checked again.
2305//
2306// In addition to all this we are passed a Trace, which can
2307// contain an AlternativeGeneration object. In this AlternativeGeneration
2308// object we can see details of any quick check that was already passed in
2309// order to get to the code we are now generating. The quick check can involve
2310// loading characters, which means we do not need to recheck the bounds
2311// up to the limit the quick check already checked. In addition the quick
2312// check can have involved a mask and compare operation which may simplify
2313// or obviate the need for further checks at some character positions.
2314void TextNode::TextEmitPass(RegExpCompiler* compiler,
2315 TextEmitPassType pass,
2316 bool preloaded,
2317 Trace* trace,
2318 bool first_element_checked,
2319 int* checked_up_to) {
2320 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2321 bool ascii = compiler->ascii();
2322 Label* backtrack = trace->backtrack();
2323 QuickCheckDetails* quick_check = trace->quick_check_performed();
2324 int element_count = elms_->length();
2325 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2326 TextElement elm = elms_->at(i);
2327 int cp_offset = trace->cp_offset() + elm.cp_offset;
2328 if (elm.type == TextElement::ATOM) {
2329 Vector<const uc16> quarks = elm.data.u_atom->data();
2330 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2331 if (first_element_checked && i == 0 && j == 0) continue;
2332 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2333 EmitCharacterFunction* emit_function = NULL;
2334 switch (pass) {
2335 case NON_ASCII_MATCH:
2336 ASSERT(ascii);
2337 if (quarks[j] > String::kMaxAsciiCharCode) {
2338 assembler->GoTo(backtrack);
2339 return;
2340 }
2341 break;
2342 case NON_LETTER_CHARACTER_MATCH:
2343 emit_function = &EmitAtomNonLetter;
2344 break;
2345 case SIMPLE_CHARACTER_MATCH:
2346 emit_function = &EmitSimpleCharacter;
2347 break;
2348 case CASE_CHARACTER_MATCH:
2349 emit_function = &EmitAtomLetter;
2350 break;
2351 default:
2352 break;
2353 }
2354 if (emit_function != NULL) {
2355 bool bound_checked = emit_function(compiler,
2356 quarks[j],
2357 backtrack,
2358 cp_offset + j,
2359 *checked_up_to < cp_offset + j,
2360 preloaded);
2361 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
2362 }
2363 }
2364 } else {
2365 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
2366 if (pass == CHARACTER_CLASS_MATCH) {
2367 if (first_element_checked && i == 0) continue;
2368 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
2369 RegExpCharacterClass* cc = elm.data.u_char_class;
2370 EmitCharClass(assembler,
2371 cc,
2372 ascii,
2373 backtrack,
2374 cp_offset,
2375 *checked_up_to < cp_offset,
2376 preloaded);
2377 UpdateBoundsCheck(cp_offset, checked_up_to);
2378 }
2379 }
2380 }
2381}
2382
2383
2384int TextNode::Length() {
2385 TextElement elm = elms_->last();
2386 ASSERT(elm.cp_offset >= 0);
2387 if (elm.type == TextElement::ATOM) {
2388 return elm.cp_offset + elm.data.u_atom->data().length();
2389 } else {
2390 return elm.cp_offset + 1;
2391 }
2392}
2393
2394
2395bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2396 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2397 if (ignore_case) {
2398 return pass == SIMPLE_CHARACTER_MATCH;
2399 } else {
2400 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2401 }
2402}
2403
2404
2405// This generates the code to match a text node. A text node can contain
2406// straight character sequences (possibly to be matched in a case-independent
2407// way) and character classes. For efficiency we do not do this in a single
2408// pass from left to right. Instead we pass over the text node several times,
2409// emitting code for some character positions every time. See the comment on
2410// TextEmitPass for details.
2411void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2412 LimitResult limit_result = LimitVersions(compiler, trace);
2413 if (limit_result == DONE) return;
2414 ASSERT(limit_result == CONTINUE);
2415
2416 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2417 compiler->SetRegExpTooBig();
2418 return;
2419 }
2420
2421 if (compiler->ascii()) {
2422 int dummy = 0;
2423 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
2424 }
2425
2426 bool first_elt_done = false;
2427 int bound_checked_to = trace->cp_offset() - 1;
2428 bound_checked_to += trace->bound_checked_up_to();
2429
2430 // If a character is preloaded into the current character register then
2431 // check that now.
2432 if (trace->characters_preloaded() == 1) {
2433 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2434 if (!SkipPass(pass, compiler->ignore_case())) {
2435 TextEmitPass(compiler,
2436 static_cast<TextEmitPassType>(pass),
2437 true,
2438 trace,
2439 false,
2440 &bound_checked_to);
2441 }
2442 }
2443 first_elt_done = true;
2444 }
2445
2446 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2447 if (!SkipPass(pass, compiler->ignore_case())) {
2448 TextEmitPass(compiler,
2449 static_cast<TextEmitPassType>(pass),
2450 false,
2451 trace,
2452 first_elt_done,
2453 &bound_checked_to);
2454 }
2455 }
2456
2457 Trace successor_trace(*trace);
2458 successor_trace.set_at_start(false);
2459 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
2460 RecursionCheck rc(compiler);
2461 on_success()->Emit(compiler, &successor_trace);
2462}
2463
2464
2465void Trace::InvalidateCurrentCharacter() {
2466 characters_preloaded_ = 0;
2467}
2468
2469
2470void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
2471 ASSERT(by > 0);
2472 // We don't have an instruction for shifting the current character register
2473 // down or for using a shifted value for anything so lets just forget that
2474 // we preloaded any characters into it.
2475 characters_preloaded_ = 0;
2476 // Adjust the offsets of the quick check performed information. This
2477 // information is used to find out what we already determined about the
2478 // characters by means of mask and compare.
2479 quick_check_performed_.Advance(by, compiler->ascii());
2480 cp_offset_ += by;
2481 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2482 compiler->SetRegExpTooBig();
2483 cp_offset_ = 0;
2484 }
2485 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
2486}
2487
2488
Steve Blockd0582a62009-12-15 09:54:21 +00002489void TextNode::MakeCaseIndependent(bool is_ascii) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002490 int element_count = elms_->length();
2491 for (int i = 0; i < element_count; i++) {
2492 TextElement elm = elms_->at(i);
2493 if (elm.type == TextElement::CHAR_CLASS) {
2494 RegExpCharacterClass* cc = elm.data.u_char_class;
Steve Blockd0582a62009-12-15 09:54:21 +00002495 // None of the standard character classses is different in the case
2496 // independent case and it slows us down if we don't know that.
2497 if (cc->is_standard()) continue;
Steve Blocka7e24c12009-10-30 11:49:00 +00002498 ZoneList<CharacterRange>* ranges = cc->ranges();
2499 int range_count = ranges->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002500 for (int j = 0; j < range_count; j++) {
2501 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
Steve Blocka7e24c12009-10-30 11:49:00 +00002502 }
2503 }
2504 }
2505}
2506
2507
2508int TextNode::GreedyLoopTextLength() {
2509 TextElement elm = elms_->at(elms_->length() - 1);
2510 if (elm.type == TextElement::CHAR_CLASS) {
2511 return elm.cp_offset + 1;
2512 } else {
2513 return elm.cp_offset + elm.data.u_atom->data().length();
2514 }
2515}
2516
2517
2518// Finds the fixed match length of a sequence of nodes that goes from
2519// this alternative and back to this choice node. If there are variable
2520// length nodes or other complications in the way then return a sentinel
2521// value indicating that a greedy loop cannot be constructed.
2522int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2523 int length = 0;
2524 RegExpNode* node = alternative->node();
2525 // Later we will generate code for all these text nodes using recursion
2526 // so we have to limit the max number.
2527 int recursion_depth = 0;
2528 while (node != this) {
2529 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2530 return kNodeIsTooComplexForGreedyLoops;
2531 }
2532 int node_length = node->GreedyLoopTextLength();
2533 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2534 return kNodeIsTooComplexForGreedyLoops;
2535 }
2536 length += node_length;
2537 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2538 node = seq_node->on_success();
2539 }
2540 return length;
2541}
2542
2543
2544void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2545 ASSERT_EQ(loop_node_, NULL);
2546 AddAlternative(alt);
2547 loop_node_ = alt.node();
2548}
2549
2550
2551void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2552 ASSERT_EQ(continue_node_, NULL);
2553 AddAlternative(alt);
2554 continue_node_ = alt.node();
2555}
2556
2557
2558void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2559 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2560 if (trace->stop_node() == this) {
2561 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2562 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2563 // Update the counter-based backtracking info on the stack. This is an
2564 // optimization for greedy loops (see below).
2565 ASSERT(trace->cp_offset() == text_length);
2566 macro_assembler->AdvanceCurrentPosition(text_length);
2567 macro_assembler->GoTo(trace->loop_label());
2568 return;
2569 }
2570 ASSERT(trace->stop_node() == NULL);
2571 if (!trace->is_trivial()) {
2572 trace->Flush(compiler, this);
2573 return;
2574 }
2575 ChoiceNode::Emit(compiler, trace);
2576}
2577
2578
2579int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
2580 int preload_characters = EatsAtLeast(4, 0);
2581 if (compiler->macro_assembler()->CanReadUnaligned()) {
2582 bool ascii = compiler->ascii();
2583 if (ascii) {
2584 if (preload_characters > 4) preload_characters = 4;
2585 // We can't preload 3 characters because there is no machine instruction
2586 // to do that. We can't just load 4 because we could be reading
2587 // beyond the end of the string, which could cause a memory fault.
2588 if (preload_characters == 3) preload_characters = 2;
2589 } else {
2590 if (preload_characters > 2) preload_characters = 2;
2591 }
2592 } else {
2593 if (preload_characters > 1) preload_characters = 1;
2594 }
2595 return preload_characters;
2596}
2597
2598
2599// This class is used when generating the alternatives in a choice node. It
2600// records the way the alternative is being code generated.
2601class AlternativeGeneration: public Malloced {
2602 public:
2603 AlternativeGeneration()
2604 : possible_success(),
2605 expects_preload(false),
2606 after(),
2607 quick_check_details() { }
2608 Label possible_success;
2609 bool expects_preload;
2610 Label after;
2611 QuickCheckDetails quick_check_details;
2612};
2613
2614
2615// Creates a list of AlternativeGenerations. If the list has a reasonable
2616// size then it is on the stack, otherwise the excess is on the heap.
2617class AlternativeGenerationList {
2618 public:
2619 explicit AlternativeGenerationList(int count)
2620 : alt_gens_(count) {
2621 for (int i = 0; i < count && i < kAFew; i++) {
2622 alt_gens_.Add(a_few_alt_gens_ + i);
2623 }
2624 for (int i = kAFew; i < count; i++) {
2625 alt_gens_.Add(new AlternativeGeneration());
2626 }
2627 }
2628 ~AlternativeGenerationList() {
2629 for (int i = kAFew; i < alt_gens_.length(); i++) {
2630 delete alt_gens_[i];
2631 alt_gens_[i] = NULL;
2632 }
2633 }
2634
2635 AlternativeGeneration* at(int i) {
2636 return alt_gens_[i];
2637 }
2638 private:
2639 static const int kAFew = 10;
2640 ZoneList<AlternativeGeneration*> alt_gens_;
2641 AlternativeGeneration a_few_alt_gens_[kAFew];
2642};
2643
2644
2645/* Code generation for choice nodes.
2646 *
2647 * We generate quick checks that do a mask and compare to eliminate a
2648 * choice. If the quick check succeeds then it jumps to the continuation to
2649 * do slow checks and check subsequent nodes. If it fails (the common case)
2650 * it falls through to the next choice.
2651 *
2652 * Here is the desired flow graph. Nodes directly below each other imply
2653 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2654 * 3 doesn't have a quick check so we have to call the slow check.
2655 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2656 * regexp continuation is generated directly after the Sn node, up to the
2657 * next GoTo if we decide to reuse some already generated code. Some
2658 * nodes expect preload_characters to be preloaded into the current
2659 * character register. R nodes do this preloading. Vertices are marked
2660 * F for failures and S for success (possible success in the case of quick
2661 * nodes). L, V, < and > are used as arrow heads.
2662 *
2663 * ----------> R
2664 * |
2665 * V
2666 * Q1 -----> S1
2667 * | S /
2668 * F| /
2669 * | F/
2670 * | /
2671 * | R
2672 * | /
2673 * V L
2674 * Q2 -----> S2
2675 * | S /
2676 * F| /
2677 * | F/
2678 * | /
2679 * | R
2680 * | /
2681 * V L
2682 * S3
2683 * |
2684 * F|
2685 * |
2686 * R
2687 * |
2688 * backtrack V
2689 * <----------Q4
2690 * \ F |
2691 * \ |S
2692 * \ F V
2693 * \-----S4
2694 *
2695 * For greedy loops we reverse our expectation and expect to match rather
2696 * than fail. Therefore we want the loop code to look like this (U is the
2697 * unwind code that steps back in the greedy loop). The following alternatives
2698 * look the same as above.
2699 * _____
2700 * / \
2701 * V |
2702 * ----------> S1 |
2703 * /| |
2704 * / |S |
2705 * F/ \_____/
2706 * /
2707 * |<-----------
2708 * | \
2709 * V \
2710 * Q2 ---> S2 \
2711 * | S / |
2712 * F| / |
2713 * | F/ |
2714 * | / |
2715 * | R |
2716 * | / |
2717 * F VL |
2718 * <------U |
2719 * back |S |
2720 * \______________/
2721 */
2722
2723
2724void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2725 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2726 int choice_count = alternatives_->length();
2727#ifdef DEBUG
2728 for (int i = 0; i < choice_count - 1; i++) {
2729 GuardedAlternative alternative = alternatives_->at(i);
2730 ZoneList<Guard*>* guards = alternative.guards();
2731 int guard_count = (guards == NULL) ? 0 : guards->length();
2732 for (int j = 0; j < guard_count; j++) {
2733 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
2734 }
2735 }
2736#endif
2737
2738 LimitResult limit_result = LimitVersions(compiler, trace);
2739 if (limit_result == DONE) return;
2740 ASSERT(limit_result == CONTINUE);
2741
2742 int new_flush_budget = trace->flush_budget() / choice_count;
2743 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2744 trace->Flush(compiler, this);
2745 return;
2746 }
2747
2748 RecursionCheck rc(compiler);
2749
2750 Trace* current_trace = trace;
2751
2752 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2753 bool greedy_loop = false;
2754 Label greedy_loop_label;
2755 Trace counter_backtrack_trace;
2756 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
2757 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2758
2759 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2760 // Here we have special handling for greedy loops containing only text nodes
2761 // and other simple nodes. These are handled by pushing the current
2762 // position on the stack and then incrementing the current position each
2763 // time around the switch. On backtrack we decrement the current position
2764 // and check it against the pushed value. This avoids pushing backtrack
2765 // information for each iteration of the loop, which could take up a lot of
2766 // space.
2767 greedy_loop = true;
2768 ASSERT(trace->stop_node() == NULL);
2769 macro_assembler->PushCurrentPosition();
2770 current_trace = &counter_backtrack_trace;
2771 Label greedy_match_failed;
2772 Trace greedy_match_trace;
2773 if (not_at_start()) greedy_match_trace.set_at_start(false);
2774 greedy_match_trace.set_backtrack(&greedy_match_failed);
2775 Label loop_label;
2776 macro_assembler->Bind(&loop_label);
2777 greedy_match_trace.set_stop_node(this);
2778 greedy_match_trace.set_loop_label(&loop_label);
2779 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
2780 macro_assembler->Bind(&greedy_match_failed);
2781 }
2782
2783 Label second_choice; // For use in greedy matches.
2784 macro_assembler->Bind(&second_choice);
2785
2786 int first_normal_choice = greedy_loop ? 1 : 0;
2787
2788 int preload_characters = CalculatePreloadCharacters(compiler);
2789 bool preload_is_current =
2790 (current_trace->characters_preloaded() == preload_characters);
2791 bool preload_has_checked_bounds = preload_is_current;
2792
2793 AlternativeGenerationList alt_gens(choice_count);
2794
2795 // For now we just call all choices one after the other. The idea ultimately
2796 // is to use the Dispatch table to try only the relevant ones.
2797 for (int i = first_normal_choice; i < choice_count; i++) {
2798 GuardedAlternative alternative = alternatives_->at(i);
2799 AlternativeGeneration* alt_gen = alt_gens.at(i);
2800 alt_gen->quick_check_details.set_characters(preload_characters);
2801 ZoneList<Guard*>* guards = alternative.guards();
2802 int guard_count = (guards == NULL) ? 0 : guards->length();
2803 Trace new_trace(*current_trace);
2804 new_trace.set_characters_preloaded(preload_is_current ?
2805 preload_characters :
2806 0);
2807 if (preload_has_checked_bounds) {
2808 new_trace.set_bound_checked_up_to(preload_characters);
2809 }
2810 new_trace.quick_check_performed()->Clear();
2811 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
2812 alt_gen->expects_preload = preload_is_current;
2813 bool generate_full_check_inline = false;
2814 if (FLAG_regexp_optimization &&
2815 try_to_emit_quick_check_for_alternative(i) &&
2816 alternative.node()->EmitQuickCheck(compiler,
2817 &new_trace,
2818 preload_has_checked_bounds,
2819 &alt_gen->possible_success,
2820 &alt_gen->quick_check_details,
2821 i < choice_count - 1)) {
2822 // Quick check was generated for this choice.
2823 preload_is_current = true;
2824 preload_has_checked_bounds = true;
2825 // On the last choice in the ChoiceNode we generated the quick
2826 // check to fall through on possible success. So now we need to
2827 // generate the full check inline.
2828 if (i == choice_count - 1) {
2829 macro_assembler->Bind(&alt_gen->possible_success);
2830 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2831 new_trace.set_characters_preloaded(preload_characters);
2832 new_trace.set_bound_checked_up_to(preload_characters);
2833 generate_full_check_inline = true;
2834 }
2835 } else if (alt_gen->quick_check_details.cannot_match()) {
2836 if (i == choice_count - 1 && !greedy_loop) {
2837 macro_assembler->GoTo(trace->backtrack());
2838 }
2839 continue;
2840 } else {
2841 // No quick check was generated. Put the full code here.
2842 // If this is not the first choice then there could be slow checks from
2843 // previous cases that go here when they fail. There's no reason to
2844 // insist that they preload characters since the slow check we are about
2845 // to generate probably can't use it.
2846 if (i != first_normal_choice) {
2847 alt_gen->expects_preload = false;
Leon Clarkee46be812010-01-19 14:06:41 +00002848 new_trace.InvalidateCurrentCharacter();
Steve Blocka7e24c12009-10-30 11:49:00 +00002849 }
2850 if (i < choice_count - 1) {
2851 new_trace.set_backtrack(&alt_gen->after);
2852 }
2853 generate_full_check_inline = true;
2854 }
2855 if (generate_full_check_inline) {
2856 if (new_trace.actions() != NULL) {
2857 new_trace.set_flush_budget(new_flush_budget);
2858 }
2859 for (int j = 0; j < guard_count; j++) {
2860 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
2861 }
2862 alternative.node()->Emit(compiler, &new_trace);
2863 preload_is_current = false;
2864 }
2865 macro_assembler->Bind(&alt_gen->after);
2866 }
2867 if (greedy_loop) {
2868 macro_assembler->Bind(&greedy_loop_label);
2869 // If we have unwound to the bottom then backtrack.
2870 macro_assembler->CheckGreedyLoop(trace->backtrack());
2871 // Otherwise try the second priority at an earlier position.
2872 macro_assembler->AdvanceCurrentPosition(-text_length);
2873 macro_assembler->GoTo(&second_choice);
2874 }
2875
2876 // At this point we need to generate slow checks for the alternatives where
2877 // the quick check was inlined. We can recognize these because the associated
2878 // label was bound.
2879 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2880 AlternativeGeneration* alt_gen = alt_gens.at(i);
2881 Trace new_trace(*current_trace);
2882 // If there are actions to be flushed we have to limit how many times
2883 // they are flushed. Take the budget of the parent trace and distribute
2884 // it fairly amongst the children.
2885 if (new_trace.actions() != NULL) {
2886 new_trace.set_flush_budget(new_flush_budget);
2887 }
2888 EmitOutOfLineContinuation(compiler,
2889 &new_trace,
2890 alternatives_->at(i),
2891 alt_gen,
2892 preload_characters,
2893 alt_gens.at(i + 1)->expects_preload);
2894 }
2895}
2896
2897
2898void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
2899 Trace* trace,
2900 GuardedAlternative alternative,
2901 AlternativeGeneration* alt_gen,
2902 int preload_characters,
2903 bool next_expects_preload) {
2904 if (!alt_gen->possible_success.is_linked()) return;
2905
2906 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2907 macro_assembler->Bind(&alt_gen->possible_success);
2908 Trace out_of_line_trace(*trace);
2909 out_of_line_trace.set_characters_preloaded(preload_characters);
2910 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2911 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
2912 ZoneList<Guard*>* guards = alternative.guards();
2913 int guard_count = (guards == NULL) ? 0 : guards->length();
2914 if (next_expects_preload) {
2915 Label reload_current_char;
2916 out_of_line_trace.set_backtrack(&reload_current_char);
2917 for (int j = 0; j < guard_count; j++) {
2918 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
2919 }
2920 alternative.node()->Emit(compiler, &out_of_line_trace);
2921 macro_assembler->Bind(&reload_current_char);
2922 // Reload the current character, since the next quick check expects that.
2923 // We don't need to check bounds here because we only get into this
2924 // code through a quick check which already did the checked load.
2925 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
2926 NULL,
2927 false,
2928 preload_characters);
2929 macro_assembler->GoTo(&(alt_gen->after));
2930 } else {
2931 out_of_line_trace.set_backtrack(&(alt_gen->after));
2932 for (int j = 0; j < guard_count; j++) {
2933 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
2934 }
2935 alternative.node()->Emit(compiler, &out_of_line_trace);
2936 }
2937}
2938
2939
2940void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2941 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2942 LimitResult limit_result = LimitVersions(compiler, trace);
2943 if (limit_result == DONE) return;
2944 ASSERT(limit_result == CONTINUE);
2945
2946 RecursionCheck rc(compiler);
2947
2948 switch (type_) {
2949 case STORE_POSITION: {
2950 Trace::DeferredCapture
2951 new_capture(data_.u_position_register.reg,
2952 data_.u_position_register.is_capture,
2953 trace);
2954 Trace new_trace = *trace;
2955 new_trace.add_action(&new_capture);
2956 on_success()->Emit(compiler, &new_trace);
2957 break;
2958 }
2959 case INCREMENT_REGISTER: {
2960 Trace::DeferredIncrementRegister
2961 new_increment(data_.u_increment_register.reg);
2962 Trace new_trace = *trace;
2963 new_trace.add_action(&new_increment);
2964 on_success()->Emit(compiler, &new_trace);
2965 break;
2966 }
2967 case SET_REGISTER: {
2968 Trace::DeferredSetRegister
2969 new_set(data_.u_store_register.reg, data_.u_store_register.value);
2970 Trace new_trace = *trace;
2971 new_trace.add_action(&new_set);
2972 on_success()->Emit(compiler, &new_trace);
2973 break;
2974 }
2975 case CLEAR_CAPTURES: {
2976 Trace::DeferredClearCaptures
2977 new_capture(Interval(data_.u_clear_captures.range_from,
2978 data_.u_clear_captures.range_to));
2979 Trace new_trace = *trace;
2980 new_trace.add_action(&new_capture);
2981 on_success()->Emit(compiler, &new_trace);
2982 break;
2983 }
2984 case BEGIN_SUBMATCH:
2985 if (!trace->is_trivial()) {
2986 trace->Flush(compiler, this);
2987 } else {
2988 assembler->WriteCurrentPositionToRegister(
2989 data_.u_submatch.current_position_register, 0);
2990 assembler->WriteStackPointerToRegister(
2991 data_.u_submatch.stack_pointer_register);
2992 on_success()->Emit(compiler, trace);
2993 }
2994 break;
2995 case EMPTY_MATCH_CHECK: {
2996 int start_pos_reg = data_.u_empty_match_check.start_register;
2997 int stored_pos = 0;
2998 int rep_reg = data_.u_empty_match_check.repetition_register;
2999 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3000 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3001 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3002 // If we know we haven't advanced and there is no minimum we
3003 // can just backtrack immediately.
3004 assembler->GoTo(trace->backtrack());
3005 } else if (know_dist && stored_pos < trace->cp_offset()) {
3006 // If we know we've advanced we can generate the continuation
3007 // immediately.
3008 on_success()->Emit(compiler, trace);
3009 } else if (!trace->is_trivial()) {
3010 trace->Flush(compiler, this);
3011 } else {
3012 Label skip_empty_check;
3013 // If we have a minimum number of repetitions we check the current
3014 // number first and skip the empty check if it's not enough.
3015 if (has_minimum) {
3016 int limit = data_.u_empty_match_check.repetition_limit;
3017 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3018 }
3019 // If the match is empty we bail out, otherwise we fall through
3020 // to the on-success continuation.
3021 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3022 trace->backtrack());
3023 assembler->Bind(&skip_empty_check);
3024 on_success()->Emit(compiler, trace);
3025 }
3026 break;
3027 }
3028 case POSITIVE_SUBMATCH_SUCCESS: {
3029 if (!trace->is_trivial()) {
3030 trace->Flush(compiler, this);
3031 return;
3032 }
3033 assembler->ReadCurrentPositionFromRegister(
3034 data_.u_submatch.current_position_register);
3035 assembler->ReadStackPointerFromRegister(
3036 data_.u_submatch.stack_pointer_register);
3037 int clear_register_count = data_.u_submatch.clear_register_count;
3038 if (clear_register_count == 0) {
3039 on_success()->Emit(compiler, trace);
3040 return;
3041 }
3042 int clear_registers_from = data_.u_submatch.clear_register_from;
3043 Label clear_registers_backtrack;
3044 Trace new_trace = *trace;
3045 new_trace.set_backtrack(&clear_registers_backtrack);
3046 on_success()->Emit(compiler, &new_trace);
3047
3048 assembler->Bind(&clear_registers_backtrack);
3049 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3050 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3051
3052 ASSERT(trace->backtrack() == NULL);
3053 assembler->Backtrack();
3054 return;
3055 }
3056 default:
3057 UNREACHABLE();
3058 }
3059}
3060
3061
3062void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3063 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3064 if (!trace->is_trivial()) {
3065 trace->Flush(compiler, this);
3066 return;
3067 }
3068
3069 LimitResult limit_result = LimitVersions(compiler, trace);
3070 if (limit_result == DONE) return;
3071 ASSERT(limit_result == CONTINUE);
3072
3073 RecursionCheck rc(compiler);
3074
3075 ASSERT_EQ(start_reg_ + 1, end_reg_);
3076 if (compiler->ignore_case()) {
3077 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3078 trace->backtrack());
3079 } else {
3080 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
3081 }
3082 on_success()->Emit(compiler, trace);
3083}
3084
3085
3086// -------------------------------------------------------------------
3087// Dot/dotty output
3088
3089
3090#ifdef DEBUG
3091
3092
3093class DotPrinter: public NodeVisitor {
3094 public:
3095 explicit DotPrinter(bool ignore_case)
3096 : ignore_case_(ignore_case),
3097 stream_(&alloc_) { }
3098 void PrintNode(const char* label, RegExpNode* node);
3099 void Visit(RegExpNode* node);
3100 void PrintAttributes(RegExpNode* from);
3101 StringStream* stream() { return &stream_; }
3102 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
3103#define DECLARE_VISIT(Type) \
3104 virtual void Visit##Type(Type##Node* that);
3105FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3106#undef DECLARE_VISIT
3107 private:
3108 bool ignore_case_;
3109 HeapStringAllocator alloc_;
3110 StringStream stream_;
3111};
3112
3113
3114void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3115 stream()->Add("digraph G {\n graph [label=\"");
3116 for (int i = 0; label[i]; i++) {
3117 switch (label[i]) {
3118 case '\\':
3119 stream()->Add("\\\\");
3120 break;
3121 case '"':
3122 stream()->Add("\"");
3123 break;
3124 default:
3125 stream()->Put(label[i]);
3126 break;
3127 }
3128 }
3129 stream()->Add("\"];\n");
3130 Visit(node);
3131 stream()->Add("}\n");
3132 printf("%s", *(stream()->ToCString()));
3133}
3134
3135
3136void DotPrinter::Visit(RegExpNode* node) {
3137 if (node->info()->visited) return;
3138 node->info()->visited = true;
3139 node->Accept(this);
3140}
3141
3142
3143void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
3144 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3145 Visit(on_failure);
3146}
3147
3148
3149class TableEntryBodyPrinter {
3150 public:
3151 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3152 : stream_(stream), choice_(choice) { }
3153 void Call(uc16 from, DispatchTable::Entry entry) {
3154 OutSet* out_set = entry.out_set();
3155 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3156 if (out_set->Get(i)) {
3157 stream()->Add(" n%p:s%io%i -> n%p;\n",
3158 choice(),
3159 from,
3160 i,
3161 choice()->alternatives()->at(i).node());
3162 }
3163 }
3164 }
3165 private:
3166 StringStream* stream() { return stream_; }
3167 ChoiceNode* choice() { return choice_; }
3168 StringStream* stream_;
3169 ChoiceNode* choice_;
3170};
3171
3172
3173class TableEntryHeaderPrinter {
3174 public:
3175 explicit TableEntryHeaderPrinter(StringStream* stream)
3176 : first_(true), stream_(stream) { }
3177 void Call(uc16 from, DispatchTable::Entry entry) {
3178 if (first_) {
3179 first_ = false;
3180 } else {
3181 stream()->Add("|");
3182 }
3183 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3184 OutSet* out_set = entry.out_set();
3185 int priority = 0;
3186 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3187 if (out_set->Get(i)) {
3188 if (priority > 0) stream()->Add("|");
3189 stream()->Add("<s%io%i> %i", from, i, priority);
3190 priority++;
3191 }
3192 }
3193 stream()->Add("}}");
3194 }
3195 private:
3196 bool first_;
3197 StringStream* stream() { return stream_; }
3198 StringStream* stream_;
3199};
3200
3201
3202class AttributePrinter {
3203 public:
3204 explicit AttributePrinter(DotPrinter* out)
3205 : out_(out), first_(true) { }
3206 void PrintSeparator() {
3207 if (first_) {
3208 first_ = false;
3209 } else {
3210 out_->stream()->Add("|");
3211 }
3212 }
3213 void PrintBit(const char* name, bool value) {
3214 if (!value) return;
3215 PrintSeparator();
3216 out_->stream()->Add("{%s}", name);
3217 }
3218 void PrintPositive(const char* name, int value) {
3219 if (value < 0) return;
3220 PrintSeparator();
3221 out_->stream()->Add("{%s|%x}", name, value);
3222 }
3223 private:
3224 DotPrinter* out_;
3225 bool first_;
3226};
3227
3228
3229void DotPrinter::PrintAttributes(RegExpNode* that) {
3230 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3231 "margin=0.1, fontsize=10, label=\"{",
3232 that);
3233 AttributePrinter printer(this);
3234 NodeInfo* info = that->info();
3235 printer.PrintBit("NI", info->follows_newline_interest);
3236 printer.PrintBit("WI", info->follows_word_interest);
3237 printer.PrintBit("SI", info->follows_start_interest);
3238 Label* label = that->label();
3239 if (label->is_bound())
3240 printer.PrintPositive("@", label->pos());
3241 stream()->Add("}\"];\n");
3242 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3243 "arrowhead=none];\n", that, that);
3244}
3245
3246
3247static const bool kPrintDispatchTable = false;
3248void DotPrinter::VisitChoice(ChoiceNode* that) {
3249 if (kPrintDispatchTable) {
3250 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3251 TableEntryHeaderPrinter header_printer(stream());
3252 that->GetTable(ignore_case_)->ForEach(&header_printer);
3253 stream()->Add("\"]\n", that);
3254 PrintAttributes(that);
3255 TableEntryBodyPrinter body_printer(stream(), that);
3256 that->GetTable(ignore_case_)->ForEach(&body_printer);
3257 } else {
3258 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3259 for (int i = 0; i < that->alternatives()->length(); i++) {
3260 GuardedAlternative alt = that->alternatives()->at(i);
3261 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3262 }
3263 }
3264 for (int i = 0; i < that->alternatives()->length(); i++) {
3265 GuardedAlternative alt = that->alternatives()->at(i);
3266 alt.node()->Accept(this);
3267 }
3268}
3269
3270
3271void DotPrinter::VisitText(TextNode* that) {
3272 stream()->Add(" n%p [label=\"", that);
3273 for (int i = 0; i < that->elements()->length(); i++) {
3274 if (i > 0) stream()->Add(" ");
3275 TextElement elm = that->elements()->at(i);
3276 switch (elm.type) {
3277 case TextElement::ATOM: {
3278 stream()->Add("'%w'", elm.data.u_atom->data());
3279 break;
3280 }
3281 case TextElement::CHAR_CLASS: {
3282 RegExpCharacterClass* node = elm.data.u_char_class;
3283 stream()->Add("[");
3284 if (node->is_negated())
3285 stream()->Add("^");
3286 for (int j = 0; j < node->ranges()->length(); j++) {
3287 CharacterRange range = node->ranges()->at(j);
3288 stream()->Add("%k-%k", range.from(), range.to());
3289 }
3290 stream()->Add("]");
3291 break;
3292 }
3293 default:
3294 UNREACHABLE();
3295 }
3296 }
3297 stream()->Add("\", shape=box, peripheries=2];\n");
3298 PrintAttributes(that);
3299 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3300 Visit(that->on_success());
3301}
3302
3303
3304void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3305 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3306 that,
3307 that->start_register(),
3308 that->end_register());
3309 PrintAttributes(that);
3310 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3311 Visit(that->on_success());
3312}
3313
3314
3315void DotPrinter::VisitEnd(EndNode* that) {
3316 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3317 PrintAttributes(that);
3318}
3319
3320
3321void DotPrinter::VisitAssertion(AssertionNode* that) {
3322 stream()->Add(" n%p [", that);
3323 switch (that->type()) {
3324 case AssertionNode::AT_END:
3325 stream()->Add("label=\"$\", shape=septagon");
3326 break;
3327 case AssertionNode::AT_START:
3328 stream()->Add("label=\"^\", shape=septagon");
3329 break;
3330 case AssertionNode::AT_BOUNDARY:
3331 stream()->Add("label=\"\\b\", shape=septagon");
3332 break;
3333 case AssertionNode::AT_NON_BOUNDARY:
3334 stream()->Add("label=\"\\B\", shape=septagon");
3335 break;
3336 case AssertionNode::AFTER_NEWLINE:
3337 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3338 break;
Leon Clarkee46be812010-01-19 14:06:41 +00003339 case AssertionNode::AFTER_WORD_CHARACTER:
3340 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3341 break;
3342 case AssertionNode::AFTER_NONWORD_CHARACTER:
3343 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3344 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00003345 }
3346 stream()->Add("];\n");
3347 PrintAttributes(that);
3348 RegExpNode* successor = that->on_success();
3349 stream()->Add(" n%p -> n%p;\n", that, successor);
3350 Visit(successor);
3351}
3352
3353
3354void DotPrinter::VisitAction(ActionNode* that) {
3355 stream()->Add(" n%p [", that);
3356 switch (that->type_) {
3357 case ActionNode::SET_REGISTER:
3358 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3359 that->data_.u_store_register.reg,
3360 that->data_.u_store_register.value);
3361 break;
3362 case ActionNode::INCREMENT_REGISTER:
3363 stream()->Add("label=\"$%i++\", shape=octagon",
3364 that->data_.u_increment_register.reg);
3365 break;
3366 case ActionNode::STORE_POSITION:
3367 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3368 that->data_.u_position_register.reg);
3369 break;
3370 case ActionNode::BEGIN_SUBMATCH:
3371 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3372 that->data_.u_submatch.current_position_register);
3373 break;
3374 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
3375 stream()->Add("label=\"escape\", shape=septagon");
3376 break;
3377 case ActionNode::EMPTY_MATCH_CHECK:
3378 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3379 that->data_.u_empty_match_check.start_register,
3380 that->data_.u_empty_match_check.repetition_register,
3381 that->data_.u_empty_match_check.repetition_limit);
3382 break;
3383 case ActionNode::CLEAR_CAPTURES: {
3384 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3385 that->data_.u_clear_captures.range_from,
3386 that->data_.u_clear_captures.range_to);
3387 break;
3388 }
3389 }
3390 stream()->Add("];\n");
3391 PrintAttributes(that);
3392 RegExpNode* successor = that->on_success();
3393 stream()->Add(" n%p -> n%p;\n", that, successor);
3394 Visit(successor);
3395}
3396
3397
3398class DispatchTableDumper {
3399 public:
3400 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3401 void Call(uc16 key, DispatchTable::Entry entry);
3402 StringStream* stream() { return stream_; }
3403 private:
3404 StringStream* stream_;
3405};
3406
3407
3408void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3409 stream()->Add("[%k-%k]: {", key, entry.to());
3410 OutSet* set = entry.out_set();
3411 bool first = true;
3412 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3413 if (set->Get(i)) {
3414 if (first) {
3415 first = false;
3416 } else {
3417 stream()->Add(", ");
3418 }
3419 stream()->Add("%i", i);
3420 }
3421 }
3422 stream()->Add("}\n");
3423}
3424
3425
3426void DispatchTable::Dump() {
3427 HeapStringAllocator alloc;
3428 StringStream stream(&alloc);
3429 DispatchTableDumper dumper(&stream);
3430 tree()->ForEach(&dumper);
3431 OS::PrintError("%s", *stream.ToCString());
3432}
3433
3434
3435void RegExpEngine::DotPrint(const char* label,
3436 RegExpNode* node,
3437 bool ignore_case) {
3438 DotPrinter printer(ignore_case);
3439 printer.PrintNode(label, node);
3440}
3441
3442
3443#endif // DEBUG
3444
3445
3446// -------------------------------------------------------------------
3447// Tree to graph conversion
3448
3449static const int kSpaceRangeCount = 20;
3450static const int kSpaceRangeAsciiCount = 4;
3451static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3452 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3453 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3454
3455static const int kWordRangeCount = 8;
3456static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3457 '_', 'a', 'z' };
3458
3459static const int kDigitRangeCount = 2;
3460static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3461
3462static const int kLineTerminatorRangeCount = 6;
3463static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3464 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
3465
3466RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
3467 RegExpNode* on_success) {
3468 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3469 elms->Add(TextElement::Atom(this));
3470 return new TextNode(elms, on_success);
3471}
3472
3473
3474RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
3475 RegExpNode* on_success) {
3476 return new TextNode(elements(), on_success);
3477}
3478
3479static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3480 const uc16* special_class,
3481 int length) {
3482 ASSERT(ranges->length() != 0);
3483 ASSERT(length != 0);
3484 ASSERT(special_class[0] != 0);
3485 if (ranges->length() != (length >> 1) + 1) {
3486 return false;
3487 }
3488 CharacterRange range = ranges->at(0);
3489 if (range.from() != 0) {
3490 return false;
3491 }
3492 for (int i = 0; i < length; i += 2) {
3493 if (special_class[i] != (range.to() + 1)) {
3494 return false;
3495 }
3496 range = ranges->at((i >> 1) + 1);
3497 if (special_class[i+1] != range.from() - 1) {
3498 return false;
3499 }
3500 }
3501 if (range.to() != 0xffff) {
3502 return false;
3503 }
3504 return true;
3505}
3506
3507
3508static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3509 const uc16* special_class,
3510 int length) {
3511 if (ranges->length() * 2 != length) {
3512 return false;
3513 }
3514 for (int i = 0; i < length; i += 2) {
3515 CharacterRange range = ranges->at(i >> 1);
3516 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3517 return false;
3518 }
3519 }
3520 return true;
3521}
3522
3523
3524bool RegExpCharacterClass::is_standard() {
3525 // TODO(lrn): Remove need for this function, by not throwing away information
3526 // along the way.
3527 if (is_negated_) {
3528 return false;
3529 }
3530 if (set_.is_standard()) {
3531 return true;
3532 }
3533 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3534 set_.set_standard_set_type('s');
3535 return true;
3536 }
3537 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3538 set_.set_standard_set_type('S');
3539 return true;
3540 }
3541 if (CompareInverseRanges(set_.ranges(),
3542 kLineTerminatorRanges,
3543 kLineTerminatorRangeCount)) {
3544 set_.set_standard_set_type('.');
3545 return true;
3546 }
Leon Clarkee46be812010-01-19 14:06:41 +00003547 if (CompareRanges(set_.ranges(),
3548 kLineTerminatorRanges,
3549 kLineTerminatorRangeCount)) {
3550 set_.set_standard_set_type('n');
3551 return true;
3552 }
3553 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3554 set_.set_standard_set_type('w');
3555 return true;
3556 }
3557 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3558 set_.set_standard_set_type('W');
3559 return true;
3560 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003561 return false;
3562}
3563
3564
3565RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
3566 RegExpNode* on_success) {
3567 return new TextNode(this, on_success);
3568}
3569
3570
3571RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
3572 RegExpNode* on_success) {
3573 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3574 int length = alternatives->length();
3575 ChoiceNode* result = new ChoiceNode(length);
3576 for (int i = 0; i < length; i++) {
3577 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
3578 on_success));
3579 result->AddAlternative(alternative);
3580 }
3581 return result;
3582}
3583
3584
3585RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
3586 RegExpNode* on_success) {
3587 return ToNode(min(),
3588 max(),
3589 is_greedy(),
3590 body(),
3591 compiler,
3592 on_success);
3593}
3594
3595
3596RegExpNode* RegExpQuantifier::ToNode(int min,
3597 int max,
3598 bool is_greedy,
3599 RegExpTree* body,
3600 RegExpCompiler* compiler,
3601 RegExpNode* on_success,
3602 bool not_at_start) {
3603 // x{f, t} becomes this:
3604 //
3605 // (r++)<-.
3606 // | `
3607 // | (x)
3608 // v ^
3609 // (r=0)-->(?)---/ [if r < t]
3610 // |
3611 // [if r >= f] \----> ...
3612 //
3613
3614 // 15.10.2.5 RepeatMatcher algorithm.
3615 // The parser has already eliminated the case where max is 0. In the case
3616 // where max_match is zero the parser has removed the quantifier if min was
3617 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3618
3619 // If we know that we cannot match zero length then things are a little
3620 // simpler since we don't need to make the special zero length match check
3621 // from step 2.1. If the min and max are small we can unroll a little in
3622 // this case.
3623 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3624 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3625 if (max == 0) return on_success; // This can happen due to recursion.
3626 bool body_can_be_empty = (body->min_match() == 0);
3627 int body_start_reg = RegExpCompiler::kNoRegister;
3628 Interval capture_registers = body->CaptureRegisters();
3629 bool needs_capture_clearing = !capture_registers.is_empty();
3630 if (body_can_be_empty) {
3631 body_start_reg = compiler->AllocateRegister();
3632 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
3633 // Only unroll if there are no captures and the body can't be
3634 // empty.
3635 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3636 int new_max = (max == kInfinity) ? max : max - min;
3637 // Recurse once to get the loop or optional matches after the fixed ones.
3638 RegExpNode* answer = ToNode(
3639 0, new_max, is_greedy, body, compiler, on_success, true);
3640 // Unroll the forced matches from 0 to min. This can cause chains of
3641 // TextNodes (which the parser does not generate). These should be
3642 // combined if it turns out they hinder good code generation.
3643 for (int i = 0; i < min; i++) {
3644 answer = body->ToNode(compiler, answer);
3645 }
3646 return answer;
3647 }
3648 if (max <= kMaxUnrolledMaxMatches) {
3649 ASSERT(min == 0);
3650 // Unroll the optional matches up to max.
3651 RegExpNode* answer = on_success;
3652 for (int i = 0; i < max; i++) {
3653 ChoiceNode* alternation = new ChoiceNode(2);
3654 if (is_greedy) {
3655 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3656 answer)));
3657 alternation->AddAlternative(GuardedAlternative(on_success));
3658 } else {
3659 alternation->AddAlternative(GuardedAlternative(on_success));
3660 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3661 answer)));
3662 }
3663 answer = alternation;
3664 if (not_at_start) alternation->set_not_at_start();
3665 }
3666 return answer;
3667 }
3668 }
3669 bool has_min = min > 0;
3670 bool has_max = max < RegExpTree::kInfinity;
3671 bool needs_counter = has_min || has_max;
3672 int reg_ctr = needs_counter
3673 ? compiler->AllocateRegister()
3674 : RegExpCompiler::kNoRegister;
3675 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
3676 if (not_at_start) center->set_not_at_start();
3677 RegExpNode* loop_return = needs_counter
3678 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3679 : static_cast<RegExpNode*>(center);
3680 if (body_can_be_empty) {
3681 // If the body can be empty we need to check if it was and then
3682 // backtrack.
3683 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3684 reg_ctr,
3685 min,
3686 loop_return);
3687 }
3688 RegExpNode* body_node = body->ToNode(compiler, loop_return);
3689 if (body_can_be_empty) {
3690 // If the body can be empty we need to store the start position
3691 // so we can bail out if it was empty.
3692 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
3693 }
3694 if (needs_capture_clearing) {
3695 // Before entering the body of this loop we need to clear captures.
3696 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3697 }
3698 GuardedAlternative body_alt(body_node);
3699 if (has_max) {
3700 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3701 body_alt.AddGuard(body_guard);
3702 }
3703 GuardedAlternative rest_alt(on_success);
3704 if (has_min) {
3705 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3706 rest_alt.AddGuard(rest_guard);
3707 }
3708 if (is_greedy) {
3709 center->AddLoopAlternative(body_alt);
3710 center->AddContinueAlternative(rest_alt);
3711 } else {
3712 center->AddContinueAlternative(rest_alt);
3713 center->AddLoopAlternative(body_alt);
3714 }
3715 if (needs_counter) {
3716 return ActionNode::SetRegister(reg_ctr, 0, center);
3717 } else {
3718 return center;
3719 }
3720}
3721
3722
3723RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
3724 RegExpNode* on_success) {
3725 NodeInfo info;
3726 switch (type()) {
3727 case START_OF_LINE:
3728 return AssertionNode::AfterNewline(on_success);
3729 case START_OF_INPUT:
3730 return AssertionNode::AtStart(on_success);
3731 case BOUNDARY:
3732 return AssertionNode::AtBoundary(on_success);
3733 case NON_BOUNDARY:
3734 return AssertionNode::AtNonBoundary(on_success);
3735 case END_OF_INPUT:
3736 return AssertionNode::AtEnd(on_success);
3737 case END_OF_LINE: {
3738 // Compile $ in multiline regexps as an alternation with a positive
3739 // lookahead in one side and an end-of-input on the other side.
3740 // We need two registers for the lookahead.
3741 int stack_pointer_register = compiler->AllocateRegister();
3742 int position_register = compiler->AllocateRegister();
3743 // The ChoiceNode to distinguish between a newline and end-of-input.
3744 ChoiceNode* result = new ChoiceNode(2);
3745 // Create a newline atom.
3746 ZoneList<CharacterRange>* newline_ranges =
3747 new ZoneList<CharacterRange>(3);
3748 CharacterRange::AddClassEscape('n', newline_ranges);
3749 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3750 TextNode* newline_matcher = new TextNode(
3751 newline_atom,
3752 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3753 position_register,
3754 0, // No captures inside.
3755 -1, // Ignored if no captures.
3756 on_success));
3757 // Create an end-of-input matcher.
3758 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3759 stack_pointer_register,
3760 position_register,
3761 newline_matcher);
3762 // Add the two alternatives to the ChoiceNode.
3763 GuardedAlternative eol_alternative(end_of_line);
3764 result->AddAlternative(eol_alternative);
3765 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3766 result->AddAlternative(end_alternative);
3767 return result;
3768 }
3769 default:
3770 UNREACHABLE();
3771 }
3772 return on_success;
3773}
3774
3775
3776RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
3777 RegExpNode* on_success) {
3778 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3779 RegExpCapture::EndRegister(index()),
3780 on_success);
3781}
3782
3783
3784RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
3785 RegExpNode* on_success) {
3786 return on_success;
3787}
3788
3789
3790RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
3791 RegExpNode* on_success) {
3792 int stack_pointer_register = compiler->AllocateRegister();
3793 int position_register = compiler->AllocateRegister();
3794
3795 const int registers_per_capture = 2;
3796 const int register_of_first_capture = 2;
3797 int register_count = capture_count_ * registers_per_capture;
3798 int register_start =
3799 register_of_first_capture + capture_from_ * registers_per_capture;
3800
3801 RegExpNode* success;
3802 if (is_positive()) {
3803 RegExpNode* node = ActionNode::BeginSubmatch(
3804 stack_pointer_register,
3805 position_register,
3806 body()->ToNode(
3807 compiler,
3808 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3809 position_register,
3810 register_count,
3811 register_start,
3812 on_success)));
3813 return node;
3814 } else {
3815 // We use a ChoiceNode for a negative lookahead because it has most of
3816 // the characteristics we need. It has the body of the lookahead as its
3817 // first alternative and the expression after the lookahead of the second
3818 // alternative. If the first alternative succeeds then the
3819 // NegativeSubmatchSuccess will unwind the stack including everything the
3820 // choice node set up and backtrack. If the first alternative fails then
3821 // the second alternative is tried, which is exactly the desired result
3822 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3823 // ChoiceNode that knows to ignore the first exit when calculating quick
3824 // checks.
3825 GuardedAlternative body_alt(
3826 body()->ToNode(
3827 compiler,
3828 success = new NegativeSubmatchSuccess(stack_pointer_register,
3829 position_register,
3830 register_count,
3831 register_start)));
3832 ChoiceNode* choice_node =
3833 new NegativeLookaheadChoiceNode(body_alt,
3834 GuardedAlternative(on_success));
3835 return ActionNode::BeginSubmatch(stack_pointer_register,
3836 position_register,
3837 choice_node);
3838 }
3839}
3840
3841
3842RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
3843 RegExpNode* on_success) {
3844 return ToNode(body(), index(), compiler, on_success);
3845}
3846
3847
3848RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3849 int index,
3850 RegExpCompiler* compiler,
3851 RegExpNode* on_success) {
3852 int start_reg = RegExpCapture::StartRegister(index);
3853 int end_reg = RegExpCapture::EndRegister(index);
3854 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
3855 RegExpNode* body_node = body->ToNode(compiler, store_end);
3856 return ActionNode::StorePosition(start_reg, true, body_node);
3857}
3858
3859
3860RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
3861 RegExpNode* on_success) {
3862 ZoneList<RegExpTree*>* children = nodes();
3863 RegExpNode* current = on_success;
3864 for (int i = children->length() - 1; i >= 0; i--) {
3865 current = children->at(i)->ToNode(compiler, current);
3866 }
3867 return current;
3868}
3869
3870
3871static void AddClass(const uc16* elmv,
3872 int elmc,
3873 ZoneList<CharacterRange>* ranges) {
3874 for (int i = 0; i < elmc; i += 2) {
3875 ASSERT(elmv[i] <= elmv[i + 1]);
3876 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3877 }
3878}
3879
3880
3881static void AddClassNegated(const uc16 *elmv,
3882 int elmc,
3883 ZoneList<CharacterRange>* ranges) {
3884 ASSERT(elmv[0] != 0x0000);
3885 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
3886 uc16 last = 0x0000;
3887 for (int i = 0; i < elmc; i += 2) {
3888 ASSERT(last <= elmv[i] - 1);
3889 ASSERT(elmv[i] <= elmv[i + 1]);
3890 ranges->Add(CharacterRange(last, elmv[i] - 1));
3891 last = elmv[i + 1] + 1;
3892 }
3893 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
3894}
3895
3896
3897void CharacterRange::AddClassEscape(uc16 type,
3898 ZoneList<CharacterRange>* ranges) {
3899 switch (type) {
3900 case 's':
3901 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3902 break;
3903 case 'S':
3904 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3905 break;
3906 case 'w':
3907 AddClass(kWordRanges, kWordRangeCount, ranges);
3908 break;
3909 case 'W':
3910 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3911 break;
3912 case 'd':
3913 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3914 break;
3915 case 'D':
3916 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3917 break;
3918 case '.':
3919 AddClassNegated(kLineTerminatorRanges,
3920 kLineTerminatorRangeCount,
3921 ranges);
3922 break;
3923 // This is not a character range as defined by the spec but a
3924 // convenient shorthand for a character class that matches any
3925 // character.
3926 case '*':
3927 ranges->Add(CharacterRange::Everything());
3928 break;
3929 // This is the set of characters matched by the $ and ^ symbols
3930 // in multiline mode.
3931 case 'n':
3932 AddClass(kLineTerminatorRanges,
3933 kLineTerminatorRangeCount,
3934 ranges);
3935 break;
3936 default:
3937 UNREACHABLE();
3938 }
3939}
3940
3941
3942Vector<const uc16> CharacterRange::GetWordBounds() {
3943 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3944}
3945
3946
3947class CharacterRangeSplitter {
3948 public:
3949 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3950 ZoneList<CharacterRange>** excluded)
3951 : included_(included),
3952 excluded_(excluded) { }
3953 void Call(uc16 from, DispatchTable::Entry entry);
3954
3955 static const int kInBase = 0;
3956 static const int kInOverlay = 1;
3957
3958 private:
3959 ZoneList<CharacterRange>** included_;
3960 ZoneList<CharacterRange>** excluded_;
3961};
3962
3963
3964void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3965 if (!entry.out_set()->Get(kInBase)) return;
3966 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3967 ? included_
3968 : excluded_;
3969 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3970 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3971}
3972
3973
3974void CharacterRange::Split(ZoneList<CharacterRange>* base,
3975 Vector<const uc16> overlay,
3976 ZoneList<CharacterRange>** included,
3977 ZoneList<CharacterRange>** excluded) {
3978 ASSERT_EQ(NULL, *included);
3979 ASSERT_EQ(NULL, *excluded);
3980 DispatchTable table;
3981 for (int i = 0; i < base->length(); i++)
3982 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3983 for (int i = 0; i < overlay.length(); i += 2) {
3984 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
3985 CharacterRangeSplitter::kInOverlay);
3986 }
3987 CharacterRangeSplitter callback(included, excluded);
3988 table.ForEach(&callback);
3989}
3990
3991
Steve Blockd0582a62009-12-15 09:54:21 +00003992static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
3993 int bottom,
3994 int top);
3995
3996
3997void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
3998 bool is_ascii) {
3999 uc16 bottom = from();
4000 uc16 top = to();
4001 if (is_ascii) {
4002 if (bottom > String::kMaxAsciiCharCode) return;
4003 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4004 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004005 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
Steve Blockd0582a62009-12-15 09:54:21 +00004006 if (top == bottom) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004007 // If this is a singleton we just expand the one character.
Steve Blockd0582a62009-12-15 09:54:21 +00004008 int length = uncanonicalize.get(bottom, '\0', chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004009 for (int i = 0; i < length; i++) {
4010 uc32 chr = chars[i];
Steve Blockd0582a62009-12-15 09:54:21 +00004011 if (chr != bottom) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004012 ranges->Add(CharacterRange::Singleton(chars[i]));
4013 }
4014 }
Steve Blockd0582a62009-12-15 09:54:21 +00004015 } else if (bottom <= kRangeCanonicalizeMax &&
4016 top <= kRangeCanonicalizeMax) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004017 // If this is a range we expand the characters block by block,
4018 // expanding contiguous subranges (blocks) one at a time.
4019 // The approach is as follows. For a given start character we
4020 // look up the block that contains it, for instance 'a' if the
4021 // start character is 'c'. A block is characterized by the property
4022 // that all characters uncanonicalize in the same way as the first
4023 // element, except that each entry in the result is incremented
4024 // by the distance from the first element. So a-z is a block
4025 // because 'a' uncanonicalizes to ['a', 'A'] and the k'th letter
4026 // uncanonicalizes to ['a' + k, 'A' + k].
4027 // Once we've found the start point we look up its uncanonicalization
4028 // and produce a range for each element. For instance for [c-f]
4029 // we look up ['a', 'A'] and produce [c-f] and [C-F]. We then only
4030 // add a range if it is not already contained in the input, so [c-f]
4031 // will be skipped but [C-F] will be added. If this range is not
4032 // completely contained in a block we do this for all the blocks
4033 // covered by the range.
4034 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
Steve Blockd0582a62009-12-15 09:54:21 +00004035 // First, look up the block that contains the 'bottom' character.
4036 int length = canonrange.get(bottom, '\0', range);
Steve Blocka7e24c12009-10-30 11:49:00 +00004037 if (length == 0) {
Steve Blockd0582a62009-12-15 09:54:21 +00004038 range[0] = bottom;
Steve Blocka7e24c12009-10-30 11:49:00 +00004039 } else {
4040 ASSERT_EQ(1, length);
4041 }
Steve Blockd0582a62009-12-15 09:54:21 +00004042 int pos = bottom;
Steve Blocka7e24c12009-10-30 11:49:00 +00004043 // The start of the current block. Note that except for the first
4044 // iteration 'start' is always equal to 'pos'.
4045 int start;
4046 // If it is not the start point of a block the entry contains the
4047 // offset of the character from the start point.
4048 if ((range[0] & kStartMarker) == 0) {
4049 start = pos - range[0];
4050 } else {
4051 start = pos;
4052 }
Steve Blockd0582a62009-12-15 09:54:21 +00004053 // Then we add the ranges one at a time, incrementing the current
Steve Blocka7e24c12009-10-30 11:49:00 +00004054 // position to be after the last block each time. The position
4055 // always points to the start of a block.
Steve Blockd0582a62009-12-15 09:54:21 +00004056 while (pos < top) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004057 length = canonrange.get(start, '\0', range);
4058 if (length == 0) {
4059 range[0] = start;
4060 } else {
4061 ASSERT_EQ(1, length);
4062 }
4063 ASSERT((range[0] & kStartMarker) != 0);
4064 // The start point of a block contains the distance to the end
4065 // of the range.
4066 int block_end = start + (range[0] & kPayloadMask) - 1;
Steve Blockd0582a62009-12-15 09:54:21 +00004067 int end = (block_end > top) ? top : block_end;
Steve Blocka7e24c12009-10-30 11:49:00 +00004068 length = uncanonicalize.get(start, '\0', range);
4069 for (int i = 0; i < length; i++) {
4070 uc32 c = range[i];
4071 uc16 range_from = c + (pos - start);
4072 uc16 range_to = c + (end - start);
Steve Blockd0582a62009-12-15 09:54:21 +00004073 if (!(bottom <= range_from && range_to <= top)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004074 ranges->Add(CharacterRange(range_from, range_to));
4075 }
4076 }
4077 start = pos = block_end + 1;
4078 }
4079 } else {
Steve Blockd0582a62009-12-15 09:54:21 +00004080 // Unibrow ranges don't work for high characters due to the "2^11 bug".
4081 // Therefore we do something dumber for these ranges.
4082 AddUncanonicals(ranges, bottom, top);
4083 }
4084}
4085
4086
Leon Clarkee46be812010-01-19 14:06:41 +00004087bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4088 ASSERT_NOT_NULL(ranges);
4089 int n = ranges->length();
4090 if (n <= 1) return true;
4091 int max = ranges->at(0).to();
4092 for (int i = 1; i < n; i++) {
4093 CharacterRange next_range = ranges->at(i);
4094 if (next_range.from() <= max + 1) return false;
4095 max = next_range.to();
4096 }
4097 return true;
4098}
4099
4100SetRelation CharacterRange::WordCharacterRelation(
4101 ZoneList<CharacterRange>* range) {
4102 ASSERT(IsCanonical(range));
4103 int i = 0; // Word character range index.
4104 int j = 0; // Argument range index.
4105 ASSERT_NE(0, kWordRangeCount);
4106 SetRelation result;
4107 if (range->length() == 0) {
4108 result.SetElementsInSecondSet();
4109 return result;
4110 }
4111 CharacterRange argument_range = range->at(0);
4112 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4113 while (i < kWordRangeCount && j < range->length()) {
4114 // Check the two ranges for the five cases:
4115 // - no overlap.
4116 // - partial overlap (there are elements in both ranges that isn't
4117 // in the other, and there are also elements that are in both).
4118 // - argument range entirely inside word range.
4119 // - word range entirely inside argument range.
4120 // - ranges are completely equal.
4121
4122 // First check for no overlap. The earlier range is not in the other set.
4123 if (argument_range.from() > word_range.to()) {
4124 // Ranges are disjoint. The earlier word range contains elements that
4125 // cannot be in the argument set.
4126 result.SetElementsInSecondSet();
4127 } else if (word_range.from() > argument_range.to()) {
4128 // Ranges are disjoint. The earlier argument range contains elements that
4129 // cannot be in the word set.
4130 result.SetElementsInFirstSet();
4131 } else if (word_range.from() <= argument_range.from() &&
4132 word_range.to() >= argument_range.from()) {
4133 result.SetElementsInBothSets();
4134 // argument range completely inside word range.
4135 if (word_range.from() < argument_range.from() ||
4136 word_range.to() > argument_range.from()) {
4137 result.SetElementsInSecondSet();
4138 }
4139 } else if (word_range.from() >= argument_range.from() &&
4140 word_range.to() <= argument_range.from()) {
4141 result.SetElementsInBothSets();
4142 result.SetElementsInFirstSet();
4143 } else {
4144 // There is overlap, and neither is a subrange of the other
4145 result.SetElementsInFirstSet();
4146 result.SetElementsInSecondSet();
4147 result.SetElementsInBothSets();
4148 }
4149 if (result.NonTrivialIntersection()) {
4150 // The result is as (im)precise as we can possibly make it.
4151 return result;
4152 }
4153 // Progress the range(s) with minimal to-character.
4154 uc16 word_to = word_range.to();
4155 uc16 argument_to = argument_range.to();
4156 if (argument_to <= word_to) {
4157 j++;
4158 if (j < range->length()) {
4159 argument_range = range->at(j);
4160 }
4161 }
4162 if (word_to <= argument_to) {
4163 i += 2;
4164 if (i < kWordRangeCount) {
4165 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4166 }
4167 }
4168 }
4169 // Check if anything wasn't compared in the loop.
4170 if (i < kWordRangeCount) {
4171 // word range contains something not in argument range.
4172 result.SetElementsInSecondSet();
4173 } else if (j < range->length()) {
4174 // Argument range contains something not in word range.
4175 result.SetElementsInFirstSet();
4176 }
4177
4178 return result;
4179}
4180
4181
Steve Blockd0582a62009-12-15 09:54:21 +00004182static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4183 int bottom,
4184 int top) {
4185 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4186 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4187 // this table is correct.
4188 // 0x0600 - 0x0fff
4189 // 0x1100 - 0x1cff
4190 // 0x2000 - 0x20ff
4191 // 0x2200 - 0x23ff
4192 // 0x2500 - 0x2bff
4193 // 0x2e00 - 0xa5ff
4194 // 0xa800 - 0xfaff
4195 // 0xfc00 - 0xfeff
4196 const int boundary_count = 18;
4197 // The ASCII boundary and the kRangeCanonicalizeMax boundary are also in this
4198 // array. This is to split up big ranges and not because they actually denote
4199 // a case-mapping-free-zone.
4200 ASSERT(CharacterRange::kRangeCanonicalizeMax < 0x600);
4201 const int kFirstRealCaselessZoneIndex = 2;
4202 int boundaries[] = {0x80, CharacterRange::kRangeCanonicalizeMax,
4203 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4204 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4205
4206 // Special ASCII rule from spec can save us some work here.
4207 if (bottom == 0x80 && top == 0xffff) return;
4208
4209 // We have optimized support for this range.
4210 if (top <= CharacterRange::kRangeCanonicalizeMax) {
4211 CharacterRange range(bottom, top);
4212 range.AddCaseEquivalents(ranges, false);
4213 return;
4214 }
4215
4216 // Split up very large ranges. This helps remove ranges where there are no
4217 // case mappings.
4218 for (int i = 0; i < boundary_count; i++) {
4219 if (bottom < boundaries[i] && top >= boundaries[i]) {
4220 AddUncanonicals(ranges, bottom, boundaries[i] - 1);
4221 AddUncanonicals(ranges, boundaries[i], top);
4222 return;
4223 }
4224 }
4225
4226 // If we are completely in a zone with no case mappings then we are done.
4227 // We start at 2 so as not to except the ASCII range from mappings.
4228 for (int i = kFirstRealCaselessZoneIndex; i < boundary_count; i += 2) {
4229 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4230#ifdef DEBUG
4231 for (int j = bottom; j <= top; j++) {
4232 unsigned current_char = j;
4233 int length = uncanonicalize.get(current_char, '\0', chars);
4234 for (int k = 0; k < length; k++) {
4235 ASSERT(chars[k] == current_char);
4236 }
4237 }
4238#endif
4239 return;
4240 }
4241 }
4242
4243 // Step through the range finding equivalent characters.
4244 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4245 for (int i = bottom; i <= top; i++) {
4246 int length = uncanonicalize.get(i, '\0', chars);
4247 for (int j = 0; j < length; j++) {
4248 uc32 chr = chars[j];
4249 if (chr != i && (chr < bottom || chr > top)) {
4250 characters->Add(chr);
4251 }
4252 }
4253 }
4254
4255 // Step through the equivalent characters finding simple ranges and
4256 // adding ranges to the character class.
4257 if (characters->length() > 0) {
4258 int new_from = characters->at(0);
4259 int new_to = new_from;
4260 for (int i = 1; i < characters->length(); i++) {
4261 int chr = characters->at(i);
4262 if (chr == new_to + 1) {
4263 new_to++;
4264 } else {
4265 if (new_to == new_from) {
4266 ranges->Add(CharacterRange::Singleton(new_from));
4267 } else {
4268 ranges->Add(CharacterRange(new_from, new_to));
4269 }
4270 new_from = new_to = chr;
4271 }
4272 }
4273 if (new_to == new_from) {
4274 ranges->Add(CharacterRange::Singleton(new_from));
4275 } else {
4276 ranges->Add(CharacterRange(new_from, new_to));
4277 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004278 }
4279}
4280
4281
4282ZoneList<CharacterRange>* CharacterSet::ranges() {
4283 if (ranges_ == NULL) {
4284 ranges_ = new ZoneList<CharacterRange>(2);
4285 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4286 }
4287 return ranges_;
4288}
4289
4290
Leon Clarkee46be812010-01-19 14:06:41 +00004291// Move a number of elements in a zonelist to another position
4292// in the same list. Handles overlapping source and target areas.
4293static void MoveRanges(ZoneList<CharacterRange>* list,
4294 int from,
4295 int to,
4296 int count) {
4297 // Ranges are potentially overlapping.
4298 if (from < to) {
4299 for (int i = count - 1; i >= 0; i--) {
4300 list->at(to + i) = list->at(from + i);
4301 }
4302 } else {
4303 for (int i = 0; i < count; i++) {
4304 list->at(to + i) = list->at(from + i);
4305 }
4306 }
4307}
4308
4309
4310static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4311 int count,
4312 CharacterRange insert) {
4313 // Inserts a range into list[0..count[, which must be sorted
4314 // by from value and non-overlapping and non-adjacent, using at most
4315 // list[0..count] for the result. Returns the number of resulting
4316 // canonicalized ranges. Inserting a range may collapse existing ranges into
4317 // fewer ranges, so the return value can be anything in the range 1..count+1.
4318 uc16 from = insert.from();
4319 uc16 to = insert.to();
4320 int start_pos = 0;
4321 int end_pos = count;
4322 for (int i = count - 1; i >= 0; i--) {
4323 CharacterRange current = list->at(i);
4324 if (current.from() > to + 1) {
4325 end_pos = i;
4326 } else if (current.to() + 1 < from) {
4327 start_pos = i + 1;
4328 break;
4329 }
4330 }
4331
4332 // Inserted range overlaps, or is adjacent to, ranges at positions
4333 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4334 // not affected by the insertion.
4335 // If start_pos == end_pos, the range must be inserted before start_pos.
4336 // if start_pos < end_pos, the entire range from start_pos to end_pos
4337 // must be merged with the insert range.
4338
4339 if (start_pos == end_pos) {
4340 // Insert between existing ranges at position start_pos.
4341 if (start_pos < count) {
4342 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4343 }
4344 list->at(start_pos) = insert;
4345 return count + 1;
4346 }
4347 if (start_pos + 1 == end_pos) {
4348 // Replace single existing range at position start_pos.
4349 CharacterRange to_replace = list->at(start_pos);
4350 int new_from = Min(to_replace.from(), from);
4351 int new_to = Max(to_replace.to(), to);
4352 list->at(start_pos) = CharacterRange(new_from, new_to);
4353 return count;
4354 }
4355 // Replace a number of existing ranges from start_pos to end_pos - 1.
4356 // Move the remaining ranges down.
4357
4358 int new_from = Min(list->at(start_pos).from(), from);
4359 int new_to = Max(list->at(end_pos - 1).to(), to);
4360 if (end_pos < count) {
4361 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4362 }
4363 list->at(start_pos) = CharacterRange(new_from, new_to);
4364 return count - (end_pos - start_pos) + 1;
4365}
4366
4367
4368void CharacterSet::Canonicalize() {
4369 // Special/default classes are always considered canonical. The result
4370 // of calling ranges() will be sorted.
4371 if (ranges_ == NULL) return;
4372 CharacterRange::Canonicalize(ranges_);
4373}
4374
4375
4376void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4377 if (character_ranges->length() <= 1) return;
4378 // Check whether ranges are already canonical (increasing, non-overlapping,
4379 // non-adjacent).
4380 int n = character_ranges->length();
4381 int max = character_ranges->at(0).to();
4382 int i = 1;
4383 while (i < n) {
4384 CharacterRange current = character_ranges->at(i);
4385 if (current.from() <= max + 1) {
4386 break;
4387 }
4388 max = current.to();
4389 i++;
4390 }
4391 // Canonical until the i'th range. If that's all of them, we are done.
4392 if (i == n) return;
4393
4394 // The ranges at index i and forward are not canonicalized. Make them so by
4395 // doing the equivalent of insertion sort (inserting each into the previous
4396 // list, in order).
4397 // Notice that inserting a range can reduce the number of ranges in the
4398 // result due to combining of adjacent and overlapping ranges.
4399 int read = i; // Range to insert.
4400 int num_canonical = i; // Length of canonicalized part of list.
4401 do {
4402 num_canonical = InsertRangeInCanonicalList(character_ranges,
4403 num_canonical,
4404 character_ranges->at(read));
4405 read++;
4406 } while (read < n);
4407 character_ranges->Rewind(num_canonical);
4408
4409 ASSERT(CharacterRange::IsCanonical(character_ranges));
4410}
4411
4412
4413// Utility function for CharacterRange::Merge. Adds a range at the end of
4414// a canonicalized range list, if necessary merging the range with the last
4415// range of the list.
4416static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4417 if (set == NULL) return;
4418 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4419 int n = set->length();
4420 if (n > 0) {
4421 CharacterRange lastRange = set->at(n - 1);
4422 if (lastRange.to() == range.from() - 1) {
4423 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4424 return;
4425 }
4426 }
4427 set->Add(range);
4428}
4429
4430
4431static void AddRangeToSelectedSet(int selector,
4432 ZoneList<CharacterRange>* first_set,
4433 ZoneList<CharacterRange>* second_set,
4434 ZoneList<CharacterRange>* intersection_set,
4435 CharacterRange range) {
4436 switch (selector) {
4437 case kInsideFirst:
4438 AddRangeToSet(first_set, range);
4439 break;
4440 case kInsideSecond:
4441 AddRangeToSet(second_set, range);
4442 break;
4443 case kInsideBoth:
4444 AddRangeToSet(intersection_set, range);
4445 break;
4446 }
4447}
4448
4449
4450
4451void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4452 ZoneList<CharacterRange>* second_set,
4453 ZoneList<CharacterRange>* first_set_only_out,
4454 ZoneList<CharacterRange>* second_set_only_out,
4455 ZoneList<CharacterRange>* both_sets_out) {
4456 // Inputs are canonicalized.
4457 ASSERT(CharacterRange::IsCanonical(first_set));
4458 ASSERT(CharacterRange::IsCanonical(second_set));
4459 // Outputs are empty, if applicable.
4460 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4461 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4462 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4463
4464 // Merge sets by iterating through the lists in order of lowest "from" value,
4465 // and putting intervals into one of three sets.
4466
4467 if (first_set->length() == 0) {
4468 second_set_only_out->AddAll(*second_set);
4469 return;
4470 }
4471 if (second_set->length() == 0) {
4472 first_set_only_out->AddAll(*first_set);
4473 return;
4474 }
4475 // Indices into input lists.
4476 int i1 = 0;
4477 int i2 = 0;
4478 // Cache length of input lists.
4479 int n1 = first_set->length();
4480 int n2 = second_set->length();
4481 // Current range. May be invalid if state is kInsideNone.
4482 int from = 0;
4483 int to = -1;
4484 // Where current range comes from.
4485 int state = kInsideNone;
4486
4487 while (i1 < n1 || i2 < n2) {
4488 CharacterRange next_range;
4489 int range_source;
Leon Clarked91b9f72010-01-27 17:25:45 +00004490 if (i2 == n2 ||
4491 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4492 // Next smallest element is in first set.
Leon Clarkee46be812010-01-19 14:06:41 +00004493 next_range = first_set->at(i1++);
4494 range_source = kInsideFirst;
4495 } else {
Leon Clarked91b9f72010-01-27 17:25:45 +00004496 // Next smallest element is in second set.
Leon Clarkee46be812010-01-19 14:06:41 +00004497 next_range = second_set->at(i2++);
4498 range_source = kInsideSecond;
4499 }
4500 if (to < next_range.from()) {
4501 // Ranges disjoint: |current| |next|
4502 AddRangeToSelectedSet(state,
4503 first_set_only_out,
4504 second_set_only_out,
4505 both_sets_out,
4506 CharacterRange(from, to));
4507 from = next_range.from();
4508 to = next_range.to();
4509 state = range_source;
4510 } else {
4511 if (from < next_range.from()) {
4512 AddRangeToSelectedSet(state,
4513 first_set_only_out,
4514 second_set_only_out,
4515 both_sets_out,
4516 CharacterRange(from, next_range.from()-1));
4517 }
4518 if (to < next_range.to()) {
4519 // Ranges overlap: |current|
4520 // |next|
4521 AddRangeToSelectedSet(state | range_source,
4522 first_set_only_out,
4523 second_set_only_out,
4524 both_sets_out,
4525 CharacterRange(next_range.from(), to));
4526 from = to + 1;
4527 to = next_range.to();
4528 state = range_source;
4529 } else {
4530 // Range included: |current| , possibly ending at same character.
4531 // |next|
4532 AddRangeToSelectedSet(
4533 state | range_source,
4534 first_set_only_out,
4535 second_set_only_out,
4536 both_sets_out,
4537 CharacterRange(next_range.from(), next_range.to()));
4538 from = next_range.to() + 1;
4539 // If ranges end at same character, both ranges are consumed completely.
4540 if (next_range.to() == to) state = kInsideNone;
4541 }
4542 }
4543 }
4544 AddRangeToSelectedSet(state,
4545 first_set_only_out,
4546 second_set_only_out,
4547 both_sets_out,
4548 CharacterRange(from, to));
4549}
4550
4551
4552void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4553 ZoneList<CharacterRange>* negated_ranges) {
4554 ASSERT(CharacterRange::IsCanonical(ranges));
4555 ASSERT_EQ(0, negated_ranges->length());
4556 int range_count = ranges->length();
4557 uc16 from = 0;
4558 int i = 0;
4559 if (range_count > 0 && ranges->at(0).from() == 0) {
4560 from = ranges->at(0).to();
4561 i = 1;
4562 }
4563 while (i < range_count) {
4564 CharacterRange range = ranges->at(i);
4565 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4566 from = range.to();
4567 i++;
4568 }
4569 if (from < String::kMaxUC16CharCode) {
4570 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4571 }
4572}
4573
4574
Steve Blocka7e24c12009-10-30 11:49:00 +00004575
4576// -------------------------------------------------------------------
4577// Interest propagation
4578
4579
4580RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4581 for (int i = 0; i < siblings_.length(); i++) {
4582 RegExpNode* sibling = siblings_.Get(i);
4583 if (sibling->info()->Matches(info))
4584 return sibling;
4585 }
4586 return NULL;
4587}
4588
4589
4590RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4591 ASSERT_EQ(false, *cloned);
4592 siblings_.Ensure(this);
4593 RegExpNode* result = TryGetSibling(info);
4594 if (result != NULL) return result;
4595 result = this->Clone();
4596 NodeInfo* new_info = result->info();
4597 new_info->ResetCompilationState();
4598 new_info->AddFromPreceding(info);
4599 AddSibling(result);
4600 *cloned = true;
4601 return result;
4602}
4603
4604
4605template <class C>
4606static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4607 NodeInfo full_info(*node->info());
4608 full_info.AddFromPreceding(info);
4609 bool cloned = false;
4610 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4611}
4612
4613
4614// -------------------------------------------------------------------
4615// Splay tree
4616
4617
4618OutSet* OutSet::Extend(unsigned value) {
4619 if (Get(value))
4620 return this;
4621 if (successors() != NULL) {
4622 for (int i = 0; i < successors()->length(); i++) {
4623 OutSet* successor = successors()->at(i);
4624 if (successor->Get(value))
4625 return successor;
4626 }
4627 } else {
4628 successors_ = new ZoneList<OutSet*>(2);
4629 }
4630 OutSet* result = new OutSet(first_, remaining_);
4631 result->Set(value);
4632 successors()->Add(result);
4633 return result;
4634}
4635
4636
4637void OutSet::Set(unsigned value) {
4638 if (value < kFirstLimit) {
4639 first_ |= (1 << value);
4640 } else {
4641 if (remaining_ == NULL)
4642 remaining_ = new ZoneList<unsigned>(1);
4643 if (remaining_->is_empty() || !remaining_->Contains(value))
4644 remaining_->Add(value);
4645 }
4646}
4647
4648
4649bool OutSet::Get(unsigned value) {
4650 if (value < kFirstLimit) {
4651 return (first_ & (1 << value)) != 0;
4652 } else if (remaining_ == NULL) {
4653 return false;
4654 } else {
4655 return remaining_->Contains(value);
4656 }
4657}
4658
4659
4660const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4661const DispatchTable::Entry DispatchTable::Config::kNoValue;
4662
4663
4664void DispatchTable::AddRange(CharacterRange full_range, int value) {
4665 CharacterRange current = full_range;
4666 if (tree()->is_empty()) {
4667 // If this is the first range we just insert into the table.
4668 ZoneSplayTree<Config>::Locator loc;
4669 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4670 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4671 return;
4672 }
4673 // First see if there is a range to the left of this one that
4674 // overlaps.
4675 ZoneSplayTree<Config>::Locator loc;
4676 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4677 Entry* entry = &loc.value();
4678 // If we've found a range that overlaps with this one, and it
4679 // starts strictly to the left of this one, we have to fix it
4680 // because the following code only handles ranges that start on
4681 // or after the start point of the range we're adding.
4682 if (entry->from() < current.from() && entry->to() >= current.from()) {
4683 // Snap the overlapping range in half around the start point of
4684 // the range we're adding.
4685 CharacterRange left(entry->from(), current.from() - 1);
4686 CharacterRange right(current.from(), entry->to());
4687 // The left part of the overlapping range doesn't overlap.
4688 // Truncate the whole entry to be just the left part.
4689 entry->set_to(left.to());
4690 // The right part is the one that overlaps. We add this part
4691 // to the map and let the next step deal with merging it with
4692 // the range we're adding.
4693 ZoneSplayTree<Config>::Locator loc;
4694 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4695 loc.set_value(Entry(right.from(),
4696 right.to(),
4697 entry->out_set()));
4698 }
4699 }
4700 while (current.is_valid()) {
4701 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4702 (loc.value().from() <= current.to()) &&
4703 (loc.value().to() >= current.from())) {
4704 Entry* entry = &loc.value();
4705 // We have overlap. If there is space between the start point of
4706 // the range we're adding and where the overlapping range starts
4707 // then we have to add a range covering just that space.
4708 if (current.from() < entry->from()) {
4709 ZoneSplayTree<Config>::Locator ins;
4710 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4711 ins.set_value(Entry(current.from(),
4712 entry->from() - 1,
4713 empty()->Extend(value)));
4714 current.set_from(entry->from());
4715 }
4716 ASSERT_EQ(current.from(), entry->from());
4717 // If the overlapping range extends beyond the one we want to add
4718 // we have to snap the right part off and add it separately.
4719 if (entry->to() > current.to()) {
4720 ZoneSplayTree<Config>::Locator ins;
4721 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4722 ins.set_value(Entry(current.to() + 1,
4723 entry->to(),
4724 entry->out_set()));
4725 entry->set_to(current.to());
4726 }
4727 ASSERT(entry->to() <= current.to());
4728 // The overlapping range is now completely contained by the range
4729 // we're adding so we can just update it and move the start point
4730 // of the range we're adding just past it.
4731 entry->AddValue(value);
4732 // Bail out if the last interval ended at 0xFFFF since otherwise
4733 // adding 1 will wrap around to 0.
4734 if (entry->to() == String::kMaxUC16CharCode)
4735 break;
4736 ASSERT(entry->to() + 1 > current.from());
4737 current.set_from(entry->to() + 1);
4738 } else {
4739 // There is no overlap so we can just add the range
4740 ZoneSplayTree<Config>::Locator ins;
4741 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4742 ins.set_value(Entry(current.from(),
4743 current.to(),
4744 empty()->Extend(value)));
4745 break;
4746 }
4747 }
4748}
4749
4750
4751OutSet* DispatchTable::Get(uc16 value) {
4752 ZoneSplayTree<Config>::Locator loc;
4753 if (!tree()->FindGreatestLessThan(value, &loc))
4754 return empty();
4755 Entry* entry = &loc.value();
4756 if (value <= entry->to())
4757 return entry->out_set();
4758 else
4759 return empty();
4760}
4761
4762
4763// -------------------------------------------------------------------
4764// Analysis
4765
4766
4767void Analysis::EnsureAnalyzed(RegExpNode* that) {
4768 StackLimitCheck check;
4769 if (check.HasOverflowed()) {
4770 fail("Stack overflow");
4771 return;
4772 }
4773 if (that->info()->been_analyzed || that->info()->being_analyzed)
4774 return;
4775 that->info()->being_analyzed = true;
4776 that->Accept(this);
4777 that->info()->being_analyzed = false;
4778 that->info()->been_analyzed = true;
4779}
4780
4781
4782void Analysis::VisitEnd(EndNode* that) {
4783 // nothing to do
4784}
4785
4786
4787void TextNode::CalculateOffsets() {
4788 int element_count = elements()->length();
4789 // Set up the offsets of the elements relative to the start. This is a fixed
4790 // quantity since a TextNode can only contain fixed-width things.
4791 int cp_offset = 0;
4792 for (int i = 0; i < element_count; i++) {
4793 TextElement& elm = elements()->at(i);
4794 elm.cp_offset = cp_offset;
4795 if (elm.type == TextElement::ATOM) {
4796 cp_offset += elm.data.u_atom->data().length();
4797 } else {
4798 cp_offset++;
4799 Vector<const uc16> quarks = elm.data.u_atom->data();
4800 }
4801 }
4802}
4803
4804
4805void Analysis::VisitText(TextNode* that) {
4806 if (ignore_case_) {
Steve Blockd0582a62009-12-15 09:54:21 +00004807 that->MakeCaseIndependent(is_ascii_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004808 }
4809 EnsureAnalyzed(that->on_success());
4810 if (!has_failed()) {
4811 that->CalculateOffsets();
4812 }
4813}
4814
4815
4816void Analysis::VisitAction(ActionNode* that) {
4817 RegExpNode* target = that->on_success();
4818 EnsureAnalyzed(target);
4819 if (!has_failed()) {
4820 // If the next node is interested in what it follows then this node
4821 // has to be interested too so it can pass the information on.
4822 that->info()->AddFromFollowing(target->info());
4823 }
4824}
4825
4826
4827void Analysis::VisitChoice(ChoiceNode* that) {
4828 NodeInfo* info = that->info();
4829 for (int i = 0; i < that->alternatives()->length(); i++) {
4830 RegExpNode* node = that->alternatives()->at(i).node();
4831 EnsureAnalyzed(node);
4832 if (has_failed()) return;
4833 // Anything the following nodes need to know has to be known by
4834 // this node also, so it can pass it on.
4835 info->AddFromFollowing(node->info());
4836 }
4837}
4838
4839
4840void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4841 NodeInfo* info = that->info();
4842 for (int i = 0; i < that->alternatives()->length(); i++) {
4843 RegExpNode* node = that->alternatives()->at(i).node();
4844 if (node != that->loop_node()) {
4845 EnsureAnalyzed(node);
4846 if (has_failed()) return;
4847 info->AddFromFollowing(node->info());
4848 }
4849 }
4850 // Check the loop last since it may need the value of this node
4851 // to get a correct result.
4852 EnsureAnalyzed(that->loop_node());
4853 if (!has_failed()) {
4854 info->AddFromFollowing(that->loop_node()->info());
4855 }
4856}
4857
4858
4859void Analysis::VisitBackReference(BackReferenceNode* that) {
4860 EnsureAnalyzed(that->on_success());
4861}
4862
4863
4864void Analysis::VisitAssertion(AssertionNode* that) {
4865 EnsureAnalyzed(that->on_success());
Leon Clarkee46be812010-01-19 14:06:41 +00004866 AssertionNode::AssertionNodeType type = that->type();
4867 if (type == AssertionNode::AT_BOUNDARY ||
4868 type == AssertionNode::AT_NON_BOUNDARY) {
4869 // Check if the following character is known to be a word character
4870 // or known to not be a word character.
4871 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4872
4873 CharacterRange::Canonicalize(following_chars);
4874
4875 SetRelation word_relation =
4876 CharacterRange::WordCharacterRelation(following_chars);
Andrei Popescu6d3d5a32010-04-27 19:40:12 +01004877 if (word_relation.Disjoint()) {
4878 // Includes the case where following_chars is empty (e.g., end-of-input).
Leon Clarkee46be812010-01-19 14:06:41 +00004879 // Following character is definitely *not* a word character.
4880 type = (type == AssertionNode::AT_BOUNDARY) ?
Andrei Popescu6d3d5a32010-04-27 19:40:12 +01004881 AssertionNode::AFTER_WORD_CHARACTER :
4882 AssertionNode::AFTER_NONWORD_CHARACTER;
4883 that->set_type(type);
4884 } else if (word_relation.ContainedIn()) {
4885 // Following character is definitely a word character.
4886 type = (type == AssertionNode::AT_BOUNDARY) ?
4887 AssertionNode::AFTER_NONWORD_CHARACTER :
4888 AssertionNode::AFTER_WORD_CHARACTER;
Leon Clarkee46be812010-01-19 14:06:41 +00004889 that->set_type(type);
4890 }
4891 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004892}
4893
4894
Leon Clarkee46be812010-01-19 14:06:41 +00004895ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4896 if (first_character_set_ == NULL) {
4897 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4898 // If we can't find an exact solution within the budget, we
4899 // set the value to the set of every character, i.e., all characters
4900 // are possible.
4901 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4902 all_set->Add(CharacterRange::Everything());
4903 first_character_set_ = all_set;
4904 }
4905 }
4906 return first_character_set_;
4907}
4908
4909
4910int RegExpNode::ComputeFirstCharacterSet(int budget) {
4911 // Default behavior is to not be able to determine the first character.
4912 return kComputeFirstCharacterSetFail;
4913}
4914
4915
4916int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
4917 budget--;
4918 if (budget >= 0) {
4919 // Find loop min-iteration. It's the value of the guarded choice node
4920 // with a GEQ guard, if any.
4921 int min_repetition = 0;
4922
4923 for (int i = 0; i <= 1; i++) {
4924 GuardedAlternative alternative = alternatives()->at(i);
4925 ZoneList<Guard*>* guards = alternative.guards();
4926 if (guards != NULL && guards->length() > 0) {
4927 Guard* guard = guards->at(0);
4928 if (guard->op() == Guard::GEQ) {
4929 min_repetition = guard->value();
4930 break;
4931 }
4932 }
4933 }
4934
4935 budget = loop_node()->ComputeFirstCharacterSet(budget);
4936 if (budget >= 0) {
4937 ZoneList<CharacterRange>* character_set =
4938 loop_node()->first_character_set();
4939 if (body_can_be_zero_length() || min_repetition == 0) {
4940 budget = continue_node()->ComputeFirstCharacterSet(budget);
4941 if (budget < 0) return budget;
4942 ZoneList<CharacterRange>* body_set =
4943 continue_node()->first_character_set();
4944 ZoneList<CharacterRange>* union_set =
4945 new ZoneList<CharacterRange>(Max(character_set->length(),
4946 body_set->length()));
4947 CharacterRange::Merge(character_set,
4948 body_set,
4949 union_set,
4950 union_set,
4951 union_set);
4952 character_set = union_set;
4953 }
4954 set_first_character_set(character_set);
4955 }
4956 }
4957 return budget;
4958}
4959
4960
4961int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
4962 budget--;
4963 if (budget >= 0) {
4964 GuardedAlternative successor = this->alternatives()->at(1);
4965 RegExpNode* successor_node = successor.node();
4966 budget = successor_node->ComputeFirstCharacterSet(budget);
4967 if (budget >= 0) {
4968 set_first_character_set(successor_node->first_character_set());
4969 }
4970 }
4971 return budget;
4972}
4973
4974
4975// The first character set of an EndNode is unknowable. Just use the
4976// default implementation that fails and returns all characters as possible.
4977
4978
4979int AssertionNode::ComputeFirstCharacterSet(int budget) {
4980 budget -= 1;
4981 if (budget >= 0) {
4982 switch (type_) {
4983 case AT_END: {
4984 set_first_character_set(new ZoneList<CharacterRange>(0));
4985 break;
4986 }
4987 case AT_START:
4988 case AT_BOUNDARY:
4989 case AT_NON_BOUNDARY:
4990 case AFTER_NEWLINE:
4991 case AFTER_NONWORD_CHARACTER:
4992 case AFTER_WORD_CHARACTER: {
4993 ASSERT_NOT_NULL(on_success());
4994 budget = on_success()->ComputeFirstCharacterSet(budget);
Steve Block6ded16b2010-05-10 14:33:55 +01004995 if (budget >= 0) {
4996 set_first_character_set(on_success()->first_character_set());
4997 }
Leon Clarkee46be812010-01-19 14:06:41 +00004998 break;
4999 }
5000 }
5001 }
5002 return budget;
5003}
5004
5005
5006int ActionNode::ComputeFirstCharacterSet(int budget) {
5007 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
5008 budget--;
5009 if (budget >= 0) {
5010 ASSERT_NOT_NULL(on_success());
5011 budget = on_success()->ComputeFirstCharacterSet(budget);
5012 if (budget >= 0) {
5013 set_first_character_set(on_success()->first_character_set());
5014 }
5015 }
5016 return budget;
5017}
5018
5019
5020int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5021 // We don't know anything about the first character of a backreference
5022 // at this point.
Steve Block6ded16b2010-05-10 14:33:55 +01005023 // The potential first characters are the first characters of the capture,
5024 // and the first characters of the on_success node, depending on whether the
5025 // capture can be empty and whether it is known to be participating or known
5026 // not to be.
Leon Clarkee46be812010-01-19 14:06:41 +00005027 return kComputeFirstCharacterSetFail;
5028}
5029
5030
5031int TextNode::ComputeFirstCharacterSet(int budget) {
5032 budget--;
5033 if (budget >= 0) {
5034 ASSERT_NE(0, elements()->length());
5035 TextElement text = elements()->at(0);
5036 if (text.type == TextElement::ATOM) {
5037 RegExpAtom* atom = text.data.u_atom;
5038 ASSERT_NE(0, atom->length());
5039 uc16 first_char = atom->data()[0];
5040 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5041 range->Add(CharacterRange(first_char, first_char));
5042 set_first_character_set(range);
5043 } else {
5044 ASSERT(text.type == TextElement::CHAR_CLASS);
5045 RegExpCharacterClass* char_class = text.data.u_char_class;
Steve Block6ded16b2010-05-10 14:33:55 +01005046 ZoneList<CharacterRange>* ranges = char_class->ranges();
5047 // TODO(lrn): Canonicalize ranges when they are created
5048 // instead of waiting until now.
5049 CharacterRange::Canonicalize(ranges);
Leon Clarkee46be812010-01-19 14:06:41 +00005050 if (char_class->is_negated()) {
Leon Clarkee46be812010-01-19 14:06:41 +00005051 int length = ranges->length();
5052 int new_length = length + 1;
5053 if (length > 0) {
5054 if (ranges->at(0).from() == 0) new_length--;
5055 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5056 new_length--;
5057 }
5058 }
5059 ZoneList<CharacterRange>* negated_ranges =
5060 new ZoneList<CharacterRange>(new_length);
5061 CharacterRange::Negate(ranges, negated_ranges);
5062 set_first_character_set(negated_ranges);
5063 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01005064 set_first_character_set(ranges);
Leon Clarkee46be812010-01-19 14:06:41 +00005065 }
5066 }
5067 }
5068 return budget;
5069}
5070
5071
5072
Steve Blocka7e24c12009-10-30 11:49:00 +00005073// -------------------------------------------------------------------
5074// Dispatch table construction
5075
5076
5077void DispatchTableConstructor::VisitEnd(EndNode* that) {
5078 AddRange(CharacterRange::Everything());
5079}
5080
5081
5082void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5083 node->set_being_calculated(true);
5084 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5085 for (int i = 0; i < alternatives->length(); i++) {
5086 set_choice_index(i);
5087 alternatives->at(i).node()->Accept(this);
5088 }
5089 node->set_being_calculated(false);
5090}
5091
5092
5093class AddDispatchRange {
5094 public:
5095 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5096 : constructor_(constructor) { }
5097 void Call(uc32 from, DispatchTable::Entry entry);
5098 private:
5099 DispatchTableConstructor* constructor_;
5100};
5101
5102
5103void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5104 CharacterRange range(from, entry.to());
5105 constructor_->AddRange(range);
5106}
5107
5108
5109void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5110 if (node->being_calculated())
5111 return;
5112 DispatchTable* table = node->GetTable(ignore_case_);
5113 AddDispatchRange adder(this);
5114 table->ForEach(&adder);
5115}
5116
5117
5118void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5119 // TODO(160): Find the node that we refer back to and propagate its start
5120 // set back to here. For now we just accept anything.
5121 AddRange(CharacterRange::Everything());
5122}
5123
5124
5125void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5126 RegExpNode* target = that->on_success();
5127 target->Accept(this);
5128}
5129
5130
Steve Blocka7e24c12009-10-30 11:49:00 +00005131static int CompareRangeByFrom(const CharacterRange* a,
5132 const CharacterRange* b) {
5133 return Compare<uc16>(a->from(), b->from());
5134}
5135
5136
5137void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5138 ranges->Sort(CompareRangeByFrom);
5139 uc16 last = 0;
5140 for (int i = 0; i < ranges->length(); i++) {
5141 CharacterRange range = ranges->at(i);
5142 if (last < range.from())
5143 AddRange(CharacterRange(last, range.from() - 1));
5144 if (range.to() >= last) {
5145 if (range.to() == String::kMaxUC16CharCode) {
5146 return;
5147 } else {
5148 last = range.to() + 1;
5149 }
5150 }
5151 }
5152 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
5153}
5154
5155
5156void DispatchTableConstructor::VisitText(TextNode* that) {
5157 TextElement elm = that->elements()->at(0);
5158 switch (elm.type) {
5159 case TextElement::ATOM: {
5160 uc16 c = elm.data.u_atom->data()[0];
5161 AddRange(CharacterRange(c, c));
5162 break;
5163 }
5164 case TextElement::CHAR_CLASS: {
5165 RegExpCharacterClass* tree = elm.data.u_char_class;
5166 ZoneList<CharacterRange>* ranges = tree->ranges();
5167 if (tree->is_negated()) {
5168 AddInverse(ranges);
5169 } else {
5170 for (int i = 0; i < ranges->length(); i++)
5171 AddRange(ranges->at(i));
5172 }
5173 break;
5174 }
5175 default: {
5176 UNIMPLEMENTED();
5177 }
5178 }
5179}
5180
5181
5182void DispatchTableConstructor::VisitAction(ActionNode* that) {
5183 RegExpNode* target = that->on_success();
5184 target->Accept(this);
5185}
5186
5187
5188RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5189 bool ignore_case,
5190 bool is_multiline,
5191 Handle<String> pattern,
5192 bool is_ascii) {
5193 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
5194 return IrregexpRegExpTooBig();
5195 }
5196 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
5197 // Wrap the body of the regexp in capture #0.
5198 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
5199 0,
5200 &compiler,
5201 compiler.accept());
5202 RegExpNode* node = captured_body;
5203 if (!data->tree->IsAnchored()) {
5204 // Add a .*? at the beginning, outside the body capture, unless
5205 // this expression is anchored at the beginning.
5206 RegExpNode* loop_node =
5207 RegExpQuantifier::ToNode(0,
5208 RegExpTree::kInfinity,
5209 false,
5210 new RegExpCharacterClass('*'),
5211 &compiler,
5212 captured_body,
5213 data->contains_anchor);
5214
5215 if (data->contains_anchor) {
5216 // Unroll loop once, to take care of the case that might start
5217 // at the start of input.
5218 ChoiceNode* first_step_node = new ChoiceNode(2);
5219 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5220 first_step_node->AddAlternative(GuardedAlternative(
5221 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5222 node = first_step_node;
5223 } else {
5224 node = loop_node;
5225 }
5226 }
5227 data->node = node;
Steve Blockd0582a62009-12-15 09:54:21 +00005228 Analysis analysis(ignore_case, is_ascii);
Steve Blocka7e24c12009-10-30 11:49:00 +00005229 analysis.EnsureAnalyzed(node);
5230 if (analysis.has_failed()) {
5231 const char* error_message = analysis.error_message();
5232 return CompilationResult(error_message);
5233 }
5234
5235 NodeInfo info = *node->info();
5236
5237 // Create the correct assembler for the architecture.
Steve Block6ded16b2010-05-10 14:33:55 +01005238#ifndef V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00005239 // Native regexp implementation.
5240
5241 NativeRegExpMacroAssembler::Mode mode =
5242 is_ascii ? NativeRegExpMacroAssembler::ASCII
5243 : NativeRegExpMacroAssembler::UC16;
5244
5245#if V8_TARGET_ARCH_IA32
5246 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5247#elif V8_TARGET_ARCH_X64
5248 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5249#elif V8_TARGET_ARCH_ARM
5250 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
5251#endif
5252
Steve Block6ded16b2010-05-10 14:33:55 +01005253#else // V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00005254 // Interpreted regexp implementation.
5255 EmbeddedVector<byte, 1024> codes;
5256 RegExpMacroAssemblerIrregexp macro_assembler(codes);
Steve Block6ded16b2010-05-10 14:33:55 +01005257#endif // V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00005258
5259 return compiler.Assemble(&macro_assembler,
5260 node,
5261 data->capture_count,
5262 pattern);
5263}
5264
Leon Clarkee46be812010-01-19 14:06:41 +00005265
5266int OffsetsVector::static_offsets_vector_[
5267 OffsetsVector::kStaticOffsetsVectorSize];
5268
Steve Blocka7e24c12009-10-30 11:49:00 +00005269}} // namespace v8::internal