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