blob: 9f98782bbc19a375fec4a903040711a7b19b3760 [file] [log] [blame]
ager@chromium.org381abbb2009-02-25 13:23:22 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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
ager@chromium.orga74f0da2008-12-03 16:05:52 +000030#include "ast.h"
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +000031#include "compiler.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032#include "execution.h"
33#include "factory.h"
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +000034#include "jsregexp.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "platform.h"
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000036#include "runtime.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "top.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000038#include "compilation-cache.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000039#include "string-stream.h"
40#include "parser.h"
41#include "regexp-macro-assembler.h"
42#include "regexp-macro-assembler-tracer.h"
43#include "regexp-macro-assembler-irregexp.h"
ager@chromium.org32912102009-01-16 10:38:43 +000044#include "regexp-stack.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000045
ricow@chromium.orgc9c80822010-04-21 08:22:37 +000046#ifndef V8_INTERPRETED_REGEXP
kasperl@chromium.org71affb52009-05-26 05:44:31 +000047#if V8_TARGET_ARCH_IA32
ager@chromium.org3a37e9b2009-04-27 09:26:21 +000048#include "ia32/regexp-macro-assembler-ia32.h"
ager@chromium.org9085a012009-05-11 19:22:57 +000049#elif V8_TARGET_ARCH_X64
ager@chromium.org9085a012009-05-11 19:22:57 +000050#include "x64/regexp-macro-assembler-x64.h"
51#elif V8_TARGET_ARCH_ARM
52#include "arm/regexp-macro-assembler-arm.h"
kasperl@chromium.org2abc4502009-07-02 07:00:29 +000053#else
54#error Unsupported target architecture.
ager@chromium.orga74f0da2008-12-03 16:05:52 +000055#endif
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000056#endif
ager@chromium.orga74f0da2008-12-03 16:05:52 +000057
58#include "interpreter-irregexp.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000059
ager@chromium.orga74f0da2008-12-03 16:05:52 +000060
kasperl@chromium.org71affb52009-05-26 05:44:31 +000061namespace v8 {
62namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063
64
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000065Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
66 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067 Handle<String> flags,
68 bool* has_pending_exception) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000069 // Call the construct code with 2 arguments.
70 Object** argv[2] = { Handle<Object>::cast(pattern).location(),
71 Handle<Object>::cast(flags).location() };
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000072 return Execution::New(constructor, 2, argv, has_pending_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073}
74
75
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000076static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
77 int flags = JSRegExp::NONE;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000078 for (int i = 0; i < str->length(); i++) {
79 switch (str->Get(i)) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000080 case 'i':
81 flags |= JSRegExp::IGNORE_CASE;
82 break;
83 case 'g':
84 flags |= JSRegExp::GLOBAL;
85 break;
86 case 'm':
87 flags |= JSRegExp::MULTILINE;
88 break;
89 }
90 }
91 return JSRegExp::Flags(flags);
92}
93
94
ager@chromium.orga74f0da2008-12-03 16:05:52 +000095static inline void ThrowRegExpException(Handle<JSRegExp> re,
96 Handle<String> pattern,
97 Handle<String> error_text,
98 const char* message) {
99 Handle<JSArray> array = Factory::NewJSArray(2);
100 SetElement(array, 0, pattern);
101 SetElement(array, 1, error_text);
102 Handle<Object> regexp_err = Factory::NewSyntaxError(message, array);
103 Top::Throw(*regexp_err);
104}
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000105
106
ager@chromium.org8bb60582008-12-11 12:02:20 +0000107// Generic RegExp methods. Dispatches to implementation specific methods.
108
109
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000110Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
111 Handle<String> pattern,
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000112 Handle<String> flag_str) {
113 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
114 Handle<FixedArray> cached = CompilationCache::LookupRegExp(pattern, flags);
115 bool in_cache = !cached.is_null();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000116 LOG(RegExpCompileEvent(re, in_cache));
117
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000118 Handle<Object> result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000119 if (in_cache) {
120 re->set_data(*cached);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000121 return re;
122 }
123 FlattenString(pattern);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000124 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000125 PostponeInterruptsScope postpone;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000126 RegExpCompileData parse_result;
127 FlatStringReader reader(pattern);
128 if (!ParseRegExp(&reader, flags.is_multiline(), &parse_result)) {
129 // Throw an exception if we fail to parse the pattern.
130 ThrowRegExpException(re,
131 pattern,
132 parse_result.error,
133 "malformed_regexp");
134 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000135 }
136
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000137 if (parse_result.simple && !flags.is_ignore_case()) {
138 // Parse-tree is a single atom that is equal to the pattern.
139 AtomCompile(re, pattern, flags, pattern);
140 } else if (parse_result.tree->IsAtom() &&
141 !flags.is_ignore_case() &&
142 parse_result.capture_count == 0) {
143 RegExpAtom* atom = parse_result.tree->AsAtom();
144 Vector<const uc16> atom_pattern = atom->data();
145 Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern);
146 AtomCompile(re, pattern, flags, atom_string);
147 } else {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000148 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000149 }
150 ASSERT(re->data()->IsFixedArray());
151 // Compilation succeeded so the data is set on the regexp
152 // and we can store it in the cache.
153 Handle<FixedArray> data(FixedArray::cast(re->data()));
154 CompilationCache::PutRegExp(pattern, flags, data);
155
156 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000157}
158
159
160Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
161 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000162 int index,
163 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000164 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000165 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000166 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000167 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000168 Handle<Object> result =
169 IrregexpExec(regexp, subject, index, last_match_info);
ager@chromium.org6f10e412009-02-13 10:11:16 +0000170 ASSERT(!result.is_null() || Top::has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000171 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000172 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000173 default:
174 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000175 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000176 }
177}
178
179
ager@chromium.org8bb60582008-12-11 12:02:20 +0000180// RegExp Atom implementation: Simple string search using indexOf.
181
182
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000183void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
184 Handle<String> pattern,
185 JSRegExp::Flags flags,
186 Handle<String> match_pattern) {
187 Factory::SetRegExpAtomData(re,
188 JSRegExp::ATOM,
189 pattern,
190 flags,
191 match_pattern);
192}
193
194
195static void SetAtomLastCapture(FixedArray* array,
196 String* subject,
197 int from,
198 int to) {
199 NoHandleAllocation no_handles;
200 RegExpImpl::SetLastCaptureCount(array, 2);
201 RegExpImpl::SetLastSubject(array, subject);
202 RegExpImpl::SetLastInput(array, subject);
203 RegExpImpl::SetCapture(array, 0, from);
204 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000205}
206
207
208Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
209 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000210 int index,
211 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000212 Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex)));
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000213
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000214 uint32_t start_index = index;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000215
ager@chromium.org7c537e22008-10-16 08:43:32 +0000216 int value = Runtime::StringMatch(subject, needle, start_index);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000217 if (value == -1) return Factory::null_value();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000218 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000219
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000220 {
221 NoHandleAllocation no_handles;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000222 FixedArray* array = FixedArray::cast(last_match_info->elements());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000223 SetAtomLastCapture(array, *subject, value, value + needle->length());
224 }
225 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000226}
227
228
ager@chromium.org8bb60582008-12-11 12:02:20 +0000229// Irregexp implementation.
230
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000231// Ensures that the regexp object contains a compiled version of the
232// source for either ASCII or non-ASCII strings.
233// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000234// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000235// If compilation fails, an exception is thrown and this function
236// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000237bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000238 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000239#ifdef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000240 if (compiled_code->IsByteArray()) return true;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000241#else // V8_INTERPRETED_REGEXP (RegExp native code)
242 if (compiled_code->IsCode()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000243#endif
244 return CompileIrregexp(re, is_ascii);
245}
ager@chromium.org8bb60582008-12-11 12:02:20 +0000246
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000247
248bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000249 // Compile the RegExp.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000250 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000251 PostponeInterruptsScope postpone;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000252 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
253 if (entry->IsJSObject()) {
254 // If it's a JSObject, a previous compilation failed and threw this object.
255 // Re-throw the object without trying again.
256 Top::Throw(entry);
257 return false;
258 }
259 ASSERT(entry->IsTheHole());
ager@chromium.org8bb60582008-12-11 12:02:20 +0000260
261 JSRegExp::Flags flags = re->GetFlags();
262
263 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000264 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000265 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000266 }
267
268 RegExpCompileData compile_data;
269 FlatStringReader reader(pattern);
270 if (!ParseRegExp(&reader, flags.is_multiline(), &compile_data)) {
271 // Throw an exception if we fail to parse the pattern.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000272 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000273 ThrowRegExpException(re,
274 pattern,
275 compile_data.error,
276 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000277 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000278 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000279 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000280 RegExpEngine::Compile(&compile_data,
281 flags.is_ignore_case(),
282 flags.is_multiline(),
283 pattern,
284 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000285 if (result.error_message != NULL) {
286 // Unable to compile regexp.
287 Handle<JSArray> array = Factory::NewJSArray(2);
288 SetElement(array, 0, pattern);
289 SetElement(array,
290 1,
291 Factory::NewStringFromUtf8(CStrVector(result.error_message)));
292 Handle<Object> regexp_err =
293 Factory::NewSyntaxError("malformed_regexp", array);
294 Top::Throw(*regexp_err);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000295 re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000296 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000297 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000298
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000299 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
300 data->set(JSRegExp::code_index(is_ascii), result.code);
301 int register_max = IrregexpMaxRegisterCount(*data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000302 if (result.num_registers > register_max) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000303 SetIrregexpMaxRegisterCount(*data, result.num_registers);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000304 }
305
306 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000307}
308
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000309
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000310int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
311 return Smi::cast(
312 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000313}
314
315
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000316void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
317 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000318}
319
320
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000321int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
322 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000323}
324
325
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000326int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
327 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000328}
329
330
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000331ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000332 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000333}
334
335
336Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000337 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000338}
339
340
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000341void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
342 Handle<String> pattern,
343 JSRegExp::Flags flags,
344 int capture_count) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000345 // Initialize compiled code entries to null.
346 Factory::SetRegExpIrregexpData(re,
347 JSRegExp::IRREGEXP,
348 pattern,
349 flags,
350 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000351}
352
353
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000354int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
355 Handle<String> subject) {
356 if (!subject->IsFlat()) {
357 FlattenString(subject);
358 }
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000359 // Check the asciiness of the underlying storage.
360 bool is_ascii;
361 {
362 AssertNoAllocation no_gc;
363 String* sequential_string = *subject;
364 if (subject->IsConsString()) {
365 sequential_string = ConsString::cast(*subject)->first();
366 }
367 is_ascii = sequential_string->IsAsciiRepresentation();
368 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000369 if (!EnsureCompiledIrregexp(regexp, is_ascii)) {
370 return -1;
371 }
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000372#ifdef V8_INTERPRETED_REGEXP
373 // Byte-code regexp needs space allocated for all its registers.
374 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
375#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000376 // Native regexp only needs room to output captures. Registers are handled
377 // internally.
378 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000379#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000380}
381
382
383RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(Handle<JSRegExp> regexp,
384 Handle<String> subject,
385 int index,
386 Vector<int> output) {
387 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()));
388
389 ASSERT(index >= 0);
390 ASSERT(index <= subject->length());
391 ASSERT(subject->IsFlat());
392
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000393 // A flat ASCII string might have a two-byte first part.
394 if (subject->IsConsString()) {
395 subject = Handle<String>(ConsString::cast(*subject)->first());
396 }
397
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000398#ifndef V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000399 ASSERT(output.length() >=
400 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
401 do {
402 bool is_ascii = subject->IsAsciiRepresentation();
403 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii));
404 NativeRegExpMacroAssembler::Result res =
405 NativeRegExpMacroAssembler::Match(code,
406 subject,
407 output.start(),
408 output.length(),
409 index);
410 if (res != NativeRegExpMacroAssembler::RETRY) {
411 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
412 Top::has_pending_exception());
413 STATIC_ASSERT(
414 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
415 STATIC_ASSERT(
416 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
417 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
418 == RE_EXCEPTION);
419 return static_cast<IrregexpResult>(res);
420 }
421 // If result is RETRY, the string has changed representation, and we
422 // must restart from scratch.
423 // In this case, it means we must make sure we are prepared to handle
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000424 // the, potentially, different subject (the string can switch between
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000425 // being internal and external, and even between being ASCII and UC16,
426 // but the characters are always the same).
427 IrregexpPrepare(regexp, subject);
428 } while (true);
429 UNREACHABLE();
430 return RE_EXCEPTION;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000431#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000432
433 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
434 bool is_ascii = subject->IsAsciiRepresentation();
435 // We must have done EnsureCompiledIrregexp, so we can get the number of
436 // registers.
437 int* register_vector = output.start();
438 int number_of_capture_registers =
439 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
440 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
441 register_vector[i] = -1;
442 }
443 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii));
444
445 if (IrregexpInterpreter::Match(byte_codes,
446 subject,
447 register_vector,
448 index)) {
449 return RE_SUCCESS;
450 }
451 return RE_FAILURE;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000452#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000453}
454
455
ager@chromium.org41826e72009-03-30 13:30:57 +0000456Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000457 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000458 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000459 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000460 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000461
ager@chromium.org8bb60582008-12-11 12:02:20 +0000462 // Prepare space for the return values.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000463#ifdef V8_INTERPRETED_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000464#ifdef DEBUG
465 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000466 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000467 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
468 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
469 }
470#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000471#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000472 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
473 if (required_registers < 0) {
474 // Compiling failed with an exception.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000475 ASSERT(Top::has_pending_exception());
476 return Handle<Object>::null();
477 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000478
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000479 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000480
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000481 IrregexpResult res = IrregexpExecOnce(jsregexp,
482 subject,
483 previous_index,
484 Vector<int>(registers.vector(),
485 registers.length()));
486 if (res == RE_SUCCESS) {
487 int capture_register_count =
488 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
489 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
490 AssertNoAllocation no_gc;
491 int* register_vector = registers.vector();
492 FixedArray* array = FixedArray::cast(last_match_info->elements());
493 for (int i = 0; i < capture_register_count; i += 2) {
494 SetCapture(array, i, register_vector[i]);
495 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000496 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000497 SetLastCaptureCount(array, capture_register_count);
498 SetLastSubject(array, *subject);
499 SetLastInput(array, *subject);
500 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000501 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000502 if (res == RE_EXCEPTION) {
503 ASSERT(Top::has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000504 return Handle<Object>::null();
505 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000506 ASSERT(res == RE_FAILURE);
507 return Factory::null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000508}
509
510
511// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000512// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000513//
514// The Irregexp regular expression engine is intended to be a complete
515// implementation of ECMAScript regular expressions. It generates either
516// bytecodes or native code.
517
518// The Irregexp regexp engine is structured in three steps.
519// 1) The parser generates an abstract syntax tree. See ast.cc.
520// 2) From the AST a node network is created. The nodes are all
521// subclasses of RegExpNode. The nodes represent states when
522// executing a regular expression. Several optimizations are
523// performed on the node network.
524// 3) From the nodes we generate either byte codes or native code
525// that can actually execute the regular expression (perform
526// the search). The code generation step is described in more
527// detail below.
528
529// Code generation.
530//
531// The nodes are divided into four main categories.
532// * Choice nodes
533// These represent places where the regular expression can
534// match in more than one way. For example on entry to an
535// alternation (foo|bar) or a repetition (*, +, ? or {}).
536// * Action nodes
537// These represent places where some action should be
538// performed. Examples include recording the current position
539// in the input string to a register (in order to implement
540// captures) or other actions on register for example in order
541// to implement the counters needed for {} repetitions.
542// * Matching nodes
543// These attempt to match some element part of the input string.
544// Examples of elements include character classes, plain strings
545// or back references.
546// * End nodes
547// These are used to implement the actions required on finding
548// a successful match or failing to find a match.
549//
550// The code generated (whether as byte codes or native code) maintains
551// some state as it runs. This consists of the following elements:
552//
553// * The capture registers. Used for string captures.
554// * Other registers. Used for counters etc.
555// * The current position.
556// * The stack of backtracking information. Used when a matching node
557// fails to find a match and needs to try an alternative.
558//
559// Conceptual regular expression execution model:
560//
561// There is a simple conceptual model of regular expression execution
562// which will be presented first. The actual code generated is a more
563// efficient simulation of the simple conceptual model:
564//
565// * Choice nodes are implemented as follows:
566// For each choice except the last {
567// push current position
568// push backtrack code location
569// <generate code to test for choice>
570// backtrack code location:
571// pop current position
572// }
573// <generate code to test for last choice>
574//
575// * Actions nodes are generated as follows
576// <push affected registers on backtrack stack>
577// <generate code to perform action>
578// push backtrack code location
579// <generate code to test for following nodes>
580// backtrack code location:
581// <pop affected registers to restore their state>
582// <pop backtrack location from stack and go to it>
583//
584// * Matching nodes are generated as follows:
585// if input string matches at current position
586// update current position
587// <generate code to test for following nodes>
588// else
589// <pop backtrack location from stack and go to it>
590//
591// Thus it can be seen that the current position is saved and restored
592// by the choice nodes, whereas the registers are saved and restored by
593// by the action nodes that manipulate them.
594//
595// The other interesting aspect of this model is that nodes are generated
596// at the point where they are needed by a recursive call to Emit(). If
597// the node has already been code generated then the Emit() call will
598// generate a jump to the previously generated code instead. In order to
599// limit recursion it is possible for the Emit() function to put the node
600// on a work list for later generation and instead generate a jump. The
601// destination of the jump is resolved later when the code is generated.
602//
603// Actual regular expression code generation.
604//
605// Code generation is actually more complicated than the above. In order
606// to improve the efficiency of the generated code some optimizations are
607// performed
608//
609// * Choice nodes have 1-character lookahead.
610// A choice node looks at the following character and eliminates some of
611// the choices immediately based on that character. This is not yet
612// implemented.
613// * Simple greedy loops store reduced backtracking information.
614// A quantifier like /.*foo/m will greedily match the whole input. It will
615// then need to backtrack to a point where it can match "foo". The naive
616// implementation of this would push each character position onto the
617// backtracking stack, then pop them off one by one. This would use space
618// proportional to the length of the input string. However since the "."
619// can only match in one way and always has a constant length (in this case
620// of 1) it suffices to store the current position on the top of the stack
621// once. Matching now becomes merely incrementing the current position and
622// backtracking becomes decrementing the current position and checking the
623// result against the stored current position. This is faster and saves
624// space.
625// * The current state is virtualized.
626// This is used to defer expensive operations until it is clear that they
627// are needed and to generate code for a node more than once, allowing
628// specialized an efficient versions of the code to be created. This is
629// explained in the section below.
630//
631// Execution state virtualization.
632//
633// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000634// manipulation in an object called the Trace. The Trace object can record a
635// current position offset, an optional backtrack code location on the top of
636// the virtualized backtrack stack and some register changes. When a node is
637// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000638// will emit code to bring the actual state into line with the virtual state.
639// Avoiding flushing the state can postpone some work (eg updates of capture
640// registers). Postponing work can save time when executing the regular
641// expression since it may be found that the work never has to be done as a
642// failure to match can occur. In addition it is much faster to jump to a
643// known backtrack code location than it is to pop an unknown backtrack
644// location from the stack and jump there.
645//
ager@chromium.org32912102009-01-16 10:38:43 +0000646// The virtual state found in the Trace affects code generation. For example
647// the virtual state contains the difference between the actual current
648// position and the virtual current position, and matching code needs to use
649// this offset to attempt a match in the correct location of the input
650// string. Therefore code generated for a non-trivial trace is specialized
651// to that trace. The code generator therefore has the ability to generate
652// code for each node several times. In order to limit the size of the
653// generated code there is an arbitrary limit on how many specialized sets of
654// code may be generated for a given node. If the limit is reached, the
655// trace is flushed and a generic version of the code for a node is emitted.
656// This is subsequently used for that node. The code emitted for non-generic
657// trace is not recorded in the node and so it cannot currently be reused in
658// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000659
660
661void RegExpTree::AppendToText(RegExpText* text) {
662 UNREACHABLE();
663}
664
665
666void RegExpAtom::AppendToText(RegExpText* text) {
667 text->AddElement(TextElement::Atom(this));
668}
669
670
671void RegExpCharacterClass::AppendToText(RegExpText* text) {
672 text->AddElement(TextElement::CharClass(this));
673}
674
675
676void RegExpText::AppendToText(RegExpText* text) {
677 for (int i = 0; i < elements()->length(); i++)
678 text->AddElement(elements()->at(i));
679}
680
681
682TextElement TextElement::Atom(RegExpAtom* atom) {
683 TextElement result = TextElement(ATOM);
684 result.data.u_atom = atom;
685 return result;
686}
687
688
689TextElement TextElement::CharClass(
690 RegExpCharacterClass* char_class) {
691 TextElement result = TextElement(CHAR_CLASS);
692 result.data.u_char_class = char_class;
693 return result;
694}
695
696
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000697int TextElement::length() {
698 if (type == ATOM) {
699 return data.u_atom->length();
700 } else {
701 ASSERT(type == CHAR_CLASS);
702 return 1;
703 }
704}
705
706
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000707DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
708 if (table_ == NULL) {
709 table_ = new DispatchTable();
710 DispatchTableConstructor cons(table_, ignore_case);
711 cons.BuildTable(this);
712 }
713 return table_;
714}
715
716
717class RegExpCompiler {
718 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000719 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000720
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000721 int AllocateRegister() {
722 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
723 reg_exp_too_big_ = true;
724 return next_register_;
725 }
726 return next_register_++;
727 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000728
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000729 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
730 RegExpNode* start,
731 int capture_count,
732 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000733
734 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
735
736 static const int kImplementationOffset = 0;
737 static const int kNumberOfRegistersOffset = 0;
738 static const int kCodeOffset = 1;
739
740 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
741 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000742
743 static const int kMaxRecursion = 100;
744 inline int recursion_depth() { return recursion_depth_; }
745 inline void IncrementRecursionDepth() { recursion_depth_++; }
746 inline void DecrementRecursionDepth() { recursion_depth_--; }
747
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000748 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
749
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000750 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000751 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000752
ager@chromium.org32912102009-01-16 10:38:43 +0000753 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000754 private:
755 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000756 int next_register_;
757 List<RegExpNode*>* work_list_;
758 int recursion_depth_;
759 RegExpMacroAssembler* macro_assembler_;
760 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000761 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000762 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000763};
764
765
766class RecursionCheck {
767 public:
768 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
769 compiler->IncrementRecursionDepth();
770 }
771 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
772 private:
773 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000774};
775
776
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000777static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
778 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000779}
780
781
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000782// Attempts to compile the regexp using an Irregexp code generator. Returns
783// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000784RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000785 : next_register_(2 * (capture_count + 1)),
786 work_list_(NULL),
787 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000788 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000789 ascii_(ascii),
790 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000791 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000792 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000793}
794
795
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000796RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000797 RegExpMacroAssembler* macro_assembler,
798 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000799 int capture_count,
800 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000801#ifdef DEBUG
802 if (FLAG_trace_regexp_assembler)
803 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
804 else
805#endif
806 macro_assembler_ = macro_assembler;
807 List <RegExpNode*> work_list(0);
808 work_list_ = &work_list;
809 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000810 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000811 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000812 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000813 macro_assembler_->Bind(&fail);
814 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000815 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000816 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000817 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000818 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
819
ager@chromium.org8bb60582008-12-11 12:02:20 +0000820 Handle<Object> code = macro_assembler_->GetCode(pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000821
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000822 work_list_ = NULL;
823#ifdef DEBUG
824 if (FLAG_trace_regexp_assembler) {
825 delete macro_assembler_;
826 }
827#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000828 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000829}
830
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000831
ager@chromium.org32912102009-01-16 10:38:43 +0000832bool Trace::DeferredAction::Mentions(int that) {
833 if (type() == ActionNode::CLEAR_CAPTURES) {
834 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
835 return range.Contains(that);
836 } else {
837 return reg() == that;
838 }
839}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000840
ager@chromium.org32912102009-01-16 10:38:43 +0000841
842bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000843 for (DeferredAction* action = actions_;
844 action != NULL;
845 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000846 if (action->Mentions(reg))
847 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000848 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000849 return false;
850}
851
852
ager@chromium.org32912102009-01-16 10:38:43 +0000853bool Trace::GetStoredPosition(int reg, int* cp_offset) {
854 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000855 for (DeferredAction* action = actions_;
856 action != NULL;
857 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000858 if (action->Mentions(reg)) {
859 if (action->type() == ActionNode::STORE_POSITION) {
860 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
861 return true;
862 } else {
863 return false;
864 }
865 }
866 }
867 return false;
868}
869
870
871int Trace::FindAffectedRegisters(OutSet* affected_registers) {
872 int max_register = RegExpCompiler::kNoRegister;
873 for (DeferredAction* action = actions_;
874 action != NULL;
875 action = action->next()) {
876 if (action->type() == ActionNode::CLEAR_CAPTURES) {
877 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
878 for (int i = range.from(); i <= range.to(); i++)
879 affected_registers->Set(i);
880 if (range.to() > max_register) max_register = range.to();
881 } else {
882 affected_registers->Set(action->reg());
883 if (action->reg() > max_register) max_register = action->reg();
884 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000885 }
886 return max_register;
887}
888
889
ager@chromium.org32912102009-01-16 10:38:43 +0000890void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
891 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000892 OutSet& registers_to_pop,
893 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000894 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000895 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
896 else if (registers_to_clear.Get(reg)) {
897 int clear_to = reg;
898 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
899 reg--;
900 }
901 assembler->ClearRegisters(reg, clear_to);
902 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000903 }
904}
905
906
ager@chromium.org32912102009-01-16 10:38:43 +0000907void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
908 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000909 OutSet& affected_registers,
910 OutSet* registers_to_pop,
911 OutSet* registers_to_clear) {
912 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
913 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
914
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000915 // Count pushes performed to force a stack limit check occasionally.
916 int pushes = 0;
917
ager@chromium.org8bb60582008-12-11 12:02:20 +0000918 for (int reg = 0; reg <= max_register; reg++) {
919 if (!affected_registers.Get(reg)) {
920 continue;
921 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000922
923 // The chronologically first deferred action in the trace
924 // is used to infer the action needed to restore a register
925 // to its previous state (or not, if it's safe to ignore it).
926 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
927 DeferredActionUndoType undo_action = IGNORE;
928
ager@chromium.org8bb60582008-12-11 12:02:20 +0000929 int value = 0;
930 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000931 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000932 int store_position = -1;
933 // This is a little tricky because we are scanning the actions in reverse
934 // historical order (newest first).
935 for (DeferredAction* action = actions_;
936 action != NULL;
937 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000938 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000939 switch (action->type()) {
940 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +0000941 Trace::DeferredSetRegister* psr =
942 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000943 if (!absolute) {
944 value += psr->value();
945 absolute = true;
946 }
947 // SET_REGISTER is currently only used for newly introduced loop
948 // counters. They can have a significant previous value if they
949 // occour in a loop. TODO(lrn): Propagate this information, so
950 // we can set undo_action to IGNORE if we know there is no value to
951 // restore.
952 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000953 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000954 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000955 break;
956 }
957 case ActionNode::INCREMENT_REGISTER:
958 if (!absolute) {
959 value++;
960 }
961 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000962 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000963 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000964 break;
965 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +0000966 Trace::DeferredCapture* pc =
967 static_cast<Trace::DeferredCapture*>(action);
968 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000969 store_position = pc->cp_offset();
970 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000971
972 // For captures we know that stores and clears alternate.
973 // Other register, are never cleared, and if the occur
974 // inside a loop, they might be assigned more than once.
975 if (reg <= 1) {
976 // Registers zero and one, aka "capture zero", is
977 // always set correctly if we succeed. There is no
978 // need to undo a setting on backtrack, because we
979 // will set it again or fail.
980 undo_action = IGNORE;
981 } else {
982 undo_action = pc->is_capture() ? CLEAR : RESTORE;
983 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000984 ASSERT(!absolute);
985 ASSERT_EQ(value, 0);
986 break;
987 }
ager@chromium.org32912102009-01-16 10:38:43 +0000988 case ActionNode::CLEAR_CAPTURES: {
989 // Since we're scanning in reverse order, if we've already
990 // set the position we have to ignore historically earlier
991 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000992 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +0000993 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000994 }
995 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +0000996 ASSERT(!absolute);
997 ASSERT_EQ(value, 0);
998 break;
999 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001000 default:
1001 UNREACHABLE();
1002 break;
1003 }
1004 }
1005 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001006 // Prepare for the undo-action (e.g., push if it's going to be popped).
1007 if (undo_action == RESTORE) {
1008 pushes++;
1009 RegExpMacroAssembler::StackCheckFlag stack_check =
1010 RegExpMacroAssembler::kNoStackLimitCheck;
1011 if (pushes == push_limit) {
1012 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1013 pushes = 0;
1014 }
1015
1016 assembler->PushRegister(reg, stack_check);
1017 registers_to_pop->Set(reg);
1018 } else if (undo_action == CLEAR) {
1019 registers_to_clear->Set(reg);
1020 }
1021 // Perform the chronologically last action (or accumulated increment)
1022 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001023 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001024 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001025 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001026 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001027 } else if (absolute) {
1028 assembler->SetRegister(reg, value);
1029 } else if (value != 0) {
1030 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001031 }
1032 }
1033}
1034
1035
ager@chromium.org8bb60582008-12-11 12:02:20 +00001036// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001037// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001038// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001039void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001040 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001041
iposva@chromium.org245aa852009-02-10 00:49:54 +00001042 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001043
1044 if (actions_ == NULL && backtrack() == NULL) {
1045 // Here we just have some deferred cp advances to fix and we are back to
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001046 // a normal situation. We may also have to forget some information gained
1047 // through a quick check that was already performed.
1048 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001049 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001050 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001051 successor->Emit(compiler, &new_state);
1052 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001053 }
1054
1055 // Generate deferred actions here along with code to undo them again.
1056 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001057
ager@chromium.org381abbb2009-02-25 13:23:22 +00001058 if (backtrack() != NULL) {
1059 // Here we have a concrete backtrack location. These are set up by choice
1060 // nodes and so they indicate that we have a deferred save of the current
1061 // position which we may need to emit here.
1062 assembler->PushCurrentPosition();
1063 }
1064
ager@chromium.org8bb60582008-12-11 12:02:20 +00001065 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001066 OutSet registers_to_pop;
1067 OutSet registers_to_clear;
1068 PerformDeferredActions(assembler,
1069 max_register,
1070 affected_registers,
1071 &registers_to_pop,
1072 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001073 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001074 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001075 }
1076
1077 // Create a new trivial state and generate the node with that.
1078 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001079 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001080 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001081 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001082
1083 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001084 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001085 RestoreAffectedRegisters(assembler,
1086 max_register,
1087 registers_to_pop,
1088 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001089 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001090 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001091 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001092 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001093 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001094 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001095}
1096
1097
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001098void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001099 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001100
1101 // Omit flushing the trace. We discard the entire stack frame anyway.
1102
ager@chromium.org8bb60582008-12-11 12:02:20 +00001103 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001104 // We are completely independent of the trace, since we ignore it,
1105 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001106 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001107 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001108
1109 // Throw away everything on the backtrack stack since the start
1110 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001111 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1112 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001113 if (clear_capture_count_ > 0) {
1114 // Clear any captures that might have been performed during the success
1115 // of the body of the negative look-ahead.
1116 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1117 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1118 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001119 // Now that we have unwound the stack we find at the top of the stack the
1120 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001121 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001122}
1123
1124
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001125void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001126 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001127 trace->Flush(compiler, this);
1128 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001129 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001130 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001131 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001132 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001133 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001134 switch (action_) {
1135 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001136 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001137 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001138 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001139 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001140 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001141 case NEGATIVE_SUBMATCH_SUCCESS:
1142 // This case is handled in a different virtual method.
1143 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001144 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001145 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001146}
1147
1148
1149void GuardedAlternative::AddGuard(Guard* guard) {
1150 if (guards_ == NULL)
1151 guards_ = new ZoneList<Guard*>(1);
1152 guards_->Add(guard);
1153}
1154
1155
ager@chromium.org8bb60582008-12-11 12:02:20 +00001156ActionNode* ActionNode::SetRegister(int reg,
1157 int val,
1158 RegExpNode* on_success) {
1159 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001160 result->data_.u_store_register.reg = reg;
1161 result->data_.u_store_register.value = val;
1162 return result;
1163}
1164
1165
1166ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1167 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1168 result->data_.u_increment_register.reg = reg;
1169 return result;
1170}
1171
1172
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001173ActionNode* ActionNode::StorePosition(int reg,
1174 bool is_capture,
1175 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001176 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1177 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001178 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001179 return result;
1180}
1181
1182
ager@chromium.org32912102009-01-16 10:38:43 +00001183ActionNode* ActionNode::ClearCaptures(Interval range,
1184 RegExpNode* on_success) {
1185 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1186 result->data_.u_clear_captures.range_from = range.from();
1187 result->data_.u_clear_captures.range_to = range.to();
1188 return result;
1189}
1190
1191
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001192ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1193 int position_reg,
1194 RegExpNode* on_success) {
1195 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1196 result->data_.u_submatch.stack_pointer_register = stack_reg;
1197 result->data_.u_submatch.current_position_register = position_reg;
1198 return result;
1199}
1200
1201
ager@chromium.org8bb60582008-12-11 12:02:20 +00001202ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1203 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001204 int clear_register_count,
1205 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001206 RegExpNode* on_success) {
1207 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001208 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001209 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001210 result->data_.u_submatch.clear_register_count = clear_register_count;
1211 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001212 return result;
1213}
1214
1215
ager@chromium.org32912102009-01-16 10:38:43 +00001216ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1217 int repetition_register,
1218 int repetition_limit,
1219 RegExpNode* on_success) {
1220 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1221 result->data_.u_empty_match_check.start_register = start_register;
1222 result->data_.u_empty_match_check.repetition_register = repetition_register;
1223 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1224 return result;
1225}
1226
1227
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001228#define DEFINE_ACCEPT(Type) \
1229 void Type##Node::Accept(NodeVisitor* visitor) { \
1230 visitor->Visit##Type(this); \
1231 }
1232FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1233#undef DEFINE_ACCEPT
1234
1235
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001236void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1237 visitor->VisitLoopChoice(this);
1238}
1239
1240
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001241// -------------------------------------------------------------------
1242// Emit code.
1243
1244
1245void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1246 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001247 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001248 switch (guard->op()) {
1249 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001250 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001251 macro_assembler->IfRegisterGE(guard->reg(),
1252 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001253 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001254 break;
1255 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001256 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001257 macro_assembler->IfRegisterLT(guard->reg(),
1258 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001259 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001260 break;
1261 }
1262}
1263
1264
1265static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1266static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1267
1268
ager@chromium.org381abbb2009-02-25 13:23:22 +00001269// Returns the number of characters in the equivalence class, omitting those
1270// that cannot occur in the source string because it is ASCII.
1271static int GetCaseIndependentLetters(uc16 character,
1272 bool ascii_subject,
1273 unibrow::uchar* letters) {
1274 int length = uncanonicalize.get(character, '\0', letters);
1275 // Unibrow returns 0 or 1 for characters where case independependence is
1276 // trivial.
1277 if (length == 0) {
1278 letters[0] = character;
1279 length = 1;
1280 }
1281 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1282 return length;
1283 }
1284 // The standard requires that non-ASCII characters cannot have ASCII
1285 // character codes in their equivalence class.
1286 return 0;
1287}
1288
1289
1290static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1291 uc16 c,
1292 Label* on_failure,
1293 int cp_offset,
1294 bool check,
1295 bool preloaded) {
1296 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1297 bool bound_checked = false;
1298 if (!preloaded) {
1299 assembler->LoadCurrentCharacter(
1300 cp_offset,
1301 on_failure,
1302 check);
1303 bound_checked = true;
1304 }
1305 assembler->CheckNotCharacter(c, on_failure);
1306 return bound_checked;
1307}
1308
1309
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001310// Only emits non-letters (things that don't have case). Only used for case
1311// independent matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001312static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1313 uc16 c,
1314 Label* on_failure,
1315 int cp_offset,
1316 bool check,
1317 bool preloaded) {
1318 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1319 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001320 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001321 int length = GetCaseIndependentLetters(c, ascii, chars);
1322 if (length < 1) {
1323 // This can't match. Must be an ASCII subject and a non-ASCII character.
1324 // We do not need to do anything since the ASCII pass already handled this.
1325 return false; // Bounds not checked.
1326 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001327 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001328 // We handle the length > 1 case in a later pass.
1329 if (length == 1) {
1330 if (ascii && c > String::kMaxAsciiCharCodeU) {
1331 // Can't match - see above.
1332 return false; // Bounds not checked.
1333 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001334 if (!preloaded) {
1335 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1336 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001337 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001338 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001339 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001340 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001341}
1342
1343
1344static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001345 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001346 uc16 c1,
1347 uc16 c2,
1348 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001349 uc16 char_mask;
1350 if (ascii) {
1351 char_mask = String::kMaxAsciiCharCode;
1352 } else {
1353 char_mask = String::kMaxUC16CharCode;
1354 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001355 uc16 exor = c1 ^ c2;
1356 // Check whether exor has only one bit set.
1357 if (((exor - 1) & exor) == 0) {
1358 // If c1 and c2 differ only by one bit.
1359 // Ecma262UnCanonicalize always gives the highest number last.
1360 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001361 uc16 mask = char_mask ^ exor;
1362 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001363 return true;
1364 }
1365 ASSERT(c2 > c1);
1366 uc16 diff = c2 - c1;
1367 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1368 // If the characters differ by 2^n but don't differ by one bit then
1369 // subtract the difference from the found character, then do the or
1370 // trick. We avoid the theoretical case where negative numbers are
1371 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001372 uc16 mask = char_mask ^ diff;
1373 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1374 diff,
1375 mask,
1376 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001377 return true;
1378 }
1379 return false;
1380}
1381
1382
ager@chromium.org381abbb2009-02-25 13:23:22 +00001383typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1384 uc16 c,
1385 Label* on_failure,
1386 int cp_offset,
1387 bool check,
1388 bool preloaded);
1389
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001390// Only emits letters (things that have case). Only used for case independent
1391// matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001392static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1393 uc16 c,
1394 Label* on_failure,
1395 int cp_offset,
1396 bool check,
1397 bool preloaded) {
1398 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1399 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001400 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001401 int length = GetCaseIndependentLetters(c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001402 if (length <= 1) return false;
1403 // We may not need to check against the end of the input string
1404 // if this character lies before a character that matched.
1405 if (!preloaded) {
1406 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001407 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001408 Label ok;
1409 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1410 switch (length) {
1411 case 2: {
1412 if (ShortCutEmitCharacterPair(macro_assembler,
1413 ascii,
1414 chars[0],
1415 chars[1],
1416 on_failure)) {
1417 } else {
1418 macro_assembler->CheckCharacter(chars[0], &ok);
1419 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1420 macro_assembler->Bind(&ok);
1421 }
1422 break;
1423 }
1424 case 4:
1425 macro_assembler->CheckCharacter(chars[3], &ok);
1426 // Fall through!
1427 case 3:
1428 macro_assembler->CheckCharacter(chars[0], &ok);
1429 macro_assembler->CheckCharacter(chars[1], &ok);
1430 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1431 macro_assembler->Bind(&ok);
1432 break;
1433 default:
1434 UNREACHABLE();
1435 break;
1436 }
1437 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001438}
1439
1440
1441static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1442 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001443 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001444 Label* on_failure,
1445 int cp_offset,
1446 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001447 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001448 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001449 int max_char;
1450 if (ascii) {
1451 max_char = String::kMaxAsciiCharCode;
1452 } else {
1453 max_char = String::kMaxUC16CharCode;
1454 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001455
1456 Label success;
1457
1458 Label* char_is_in_class =
1459 cc->is_negated() ? on_failure : &success;
1460
1461 int range_count = ranges->length();
1462
ager@chromium.org8bb60582008-12-11 12:02:20 +00001463 int last_valid_range = range_count - 1;
1464 while (last_valid_range >= 0) {
1465 CharacterRange& range = ranges->at(last_valid_range);
1466 if (range.from() <= max_char) {
1467 break;
1468 }
1469 last_valid_range--;
1470 }
1471
1472 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001473 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001474 // TODO(plesner): We can remove this when the node level does our
1475 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001476 macro_assembler->GoTo(on_failure);
1477 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001478 if (check_offset) {
1479 macro_assembler->CheckPosition(cp_offset, on_failure);
1480 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001481 return;
1482 }
1483
ager@chromium.org8bb60582008-12-11 12:02:20 +00001484 if (last_valid_range == 0 &&
1485 !cc->is_negated() &&
1486 ranges->at(0).IsEverything(max_char)) {
1487 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001488 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001489 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001490 }
1491 return;
1492 }
1493
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001494 if (!preloaded) {
1495 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001496 }
1497
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001498 if (cc->is_standard() &&
1499 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1500 on_failure)) {
1501 return;
1502 }
1503
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001504 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001505 CharacterRange& range = ranges->at(i);
1506 Label next_range;
1507 uc16 from = range.from();
1508 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001509 if (from > max_char) {
1510 continue;
1511 }
1512 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001513 if (to == from) {
1514 macro_assembler->CheckCharacter(to, char_is_in_class);
1515 } else {
1516 if (from != 0) {
1517 macro_assembler->CheckCharacterLT(from, &next_range);
1518 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001519 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001520 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1521 } else {
1522 macro_assembler->GoTo(char_is_in_class);
1523 }
1524 }
1525 macro_assembler->Bind(&next_range);
1526 }
1527
ager@chromium.org8bb60582008-12-11 12:02:20 +00001528 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001529 uc16 from = range.from();
1530 uc16 to = range.to();
1531
ager@chromium.org8bb60582008-12-11 12:02:20 +00001532 if (to > max_char) to = max_char;
1533 ASSERT(to >= from);
1534
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001535 if (to == from) {
1536 if (cc->is_negated()) {
1537 macro_assembler->CheckCharacter(to, on_failure);
1538 } else {
1539 macro_assembler->CheckNotCharacter(to, on_failure);
1540 }
1541 } else {
1542 if (from != 0) {
1543 if (cc->is_negated()) {
1544 macro_assembler->CheckCharacterLT(from, &success);
1545 } else {
1546 macro_assembler->CheckCharacterLT(from, on_failure);
1547 }
1548 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001549 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001550 if (cc->is_negated()) {
1551 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1552 } else {
1553 macro_assembler->CheckCharacterGT(to, on_failure);
1554 }
1555 } else {
1556 if (cc->is_negated()) {
1557 macro_assembler->GoTo(on_failure);
1558 }
1559 }
1560 }
1561 macro_assembler->Bind(&success);
1562}
1563
1564
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001565RegExpNode::~RegExpNode() {
1566}
1567
1568
ager@chromium.org8bb60582008-12-11 12:02:20 +00001569RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001570 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001571 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001572 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001573 return CONTINUE;
1574 }
1575
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001576 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001577 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001578 if (label_.is_bound()) {
1579 // We are being asked to generate a generic version, but that's already
1580 // been done so just go to it.
1581 macro_assembler->GoTo(&label_);
1582 return DONE;
1583 }
1584 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1585 // To avoid too deep recursion we push the node to the work queue and just
1586 // generate a goto here.
1587 compiler->AddWork(this);
1588 macro_assembler->GoTo(&label_);
1589 return DONE;
1590 }
1591 // Generate generic version of the node and bind the label for later use.
1592 macro_assembler->Bind(&label_);
1593 return CONTINUE;
1594 }
1595
1596 // We are being asked to make a non-generic version. Keep track of how many
1597 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001598 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001599 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001600 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001601 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1602 return CONTINUE;
1603 }
1604
ager@chromium.org32912102009-01-16 10:38:43 +00001605 // If we get here code has been generated for this node too many times or
1606 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001607 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001608 trace->Flush(compiler, this);
1609 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001610}
1611
1612
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001613int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001614 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1615 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001616 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001617}
1618
1619
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001620int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1621 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1622 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1623}
1624
1625
1626int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1627 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1628 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1629}
1630
1631
1632int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001633 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001634 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001635 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001636 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1637 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001638}
1639
1640
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001641int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
1642 int recursion_depth) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001643 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1644 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1645 // afterwards.
1646 RegExpNode* node = alternatives_->at(1).node();
1647 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1648}
1649
1650
1651void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1652 QuickCheckDetails* details,
1653 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001654 int filled_in,
1655 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001656 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1657 // afterwards.
1658 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001659 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001660}
1661
1662
1663int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1664 int recursion_depth,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001665 RegExpNode* ignore_this_node) {
1666 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1667 int min = 100;
1668 int choice_count = alternatives_->length();
1669 for (int i = 0; i < choice_count; i++) {
1670 RegExpNode* node = alternatives_->at(i).node();
1671 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001672 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1673 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001674 if (node_eats_at_least < min) min = node_eats_at_least;
1675 }
1676 return min;
1677}
1678
1679
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001680int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1681 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001682}
1683
1684
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001685int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1686 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001687}
1688
1689
1690// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1691static inline uint32_t SmearBitsRight(uint32_t v) {
1692 v |= v >> 1;
1693 v |= v >> 2;
1694 v |= v >> 4;
1695 v |= v >> 8;
1696 v |= v >> 16;
1697 return v;
1698}
1699
1700
1701bool QuickCheckDetails::Rationalize(bool asc) {
1702 bool found_useful_op = false;
1703 uint32_t char_mask;
1704 if (asc) {
1705 char_mask = String::kMaxAsciiCharCode;
1706 } else {
1707 char_mask = String::kMaxUC16CharCode;
1708 }
1709 mask_ = 0;
1710 value_ = 0;
1711 int char_shift = 0;
1712 for (int i = 0; i < characters_; i++) {
1713 Position* pos = &positions_[i];
1714 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1715 found_useful_op = true;
1716 }
1717 mask_ |= (pos->mask & char_mask) << char_shift;
1718 value_ |= (pos->value & char_mask) << char_shift;
1719 char_shift += asc ? 8 : 16;
1720 }
1721 return found_useful_op;
1722}
1723
1724
1725bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001726 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001727 bool preload_has_checked_bounds,
1728 Label* on_possible_success,
1729 QuickCheckDetails* details,
1730 bool fall_through_on_failure) {
1731 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001732 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1733 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001734 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001735 ASSERT(details->characters() == 1 ||
1736 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001737 uint32_t mask = details->mask();
1738 uint32_t value = details->value();
1739
1740 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1741
ager@chromium.org32912102009-01-16 10:38:43 +00001742 if (trace->characters_preloaded() != details->characters()) {
1743 assembler->LoadCurrentCharacter(trace->cp_offset(),
1744 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001745 !preload_has_checked_bounds,
1746 details->characters());
1747 }
1748
1749
1750 bool need_mask = true;
1751
1752 if (details->characters() == 1) {
1753 // If number of characters preloaded is 1 then we used a byte or 16 bit
1754 // load so the value is already masked down.
1755 uint32_t char_mask;
1756 if (compiler->ascii()) {
1757 char_mask = String::kMaxAsciiCharCode;
1758 } else {
1759 char_mask = String::kMaxUC16CharCode;
1760 }
1761 if ((mask & char_mask) == char_mask) need_mask = false;
1762 mask &= char_mask;
1763 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001764 // For 2-character preloads in ASCII mode or 1-character preloads in
1765 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001766 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001767 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1768 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001769 if ((mask & 0xffff) == 0xffff) need_mask = false;
1770 } else {
1771 if (mask == 0xffffffff) need_mask = false;
1772 }
1773 }
1774
1775 if (fall_through_on_failure) {
1776 if (need_mask) {
1777 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1778 } else {
1779 assembler->CheckCharacter(value, on_possible_success);
1780 }
1781 } else {
1782 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001783 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001784 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001785 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001786 }
1787 }
1788 return true;
1789}
1790
1791
1792// Here is the meat of GetQuickCheckDetails (see also the comment on the
1793// super-class in the .h file).
1794//
1795// We iterate along the text object, building up for each character a
1796// mask and value that can be used to test for a quick failure to match.
1797// The masks and values for the positions will be combined into a single
1798// machine word for the current character width in order to be used in
1799// generating a quick check.
1800void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1801 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001802 int characters_filled_in,
1803 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001804 ASSERT(characters_filled_in < details->characters());
1805 int characters = details->characters();
1806 int char_mask;
1807 int char_shift;
1808 if (compiler->ascii()) {
1809 char_mask = String::kMaxAsciiCharCode;
1810 char_shift = 8;
1811 } else {
1812 char_mask = String::kMaxUC16CharCode;
1813 char_shift = 16;
1814 }
1815 for (int k = 0; k < elms_->length(); k++) {
1816 TextElement elm = elms_->at(k);
1817 if (elm.type == TextElement::ATOM) {
1818 Vector<const uc16> quarks = elm.data.u_atom->data();
1819 for (int i = 0; i < characters && i < quarks.length(); i++) {
1820 QuickCheckDetails::Position* pos =
1821 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001822 uc16 c = quarks[i];
1823 if (c > char_mask) {
1824 // If we expect a non-ASCII character from an ASCII string,
1825 // there is no way we can match. Not even case independent
1826 // matching can turn an ASCII character into non-ASCII or
1827 // vice versa.
1828 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001829 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001830 return;
1831 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001832 if (compiler->ignore_case()) {
1833 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001834 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1835 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1836 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001837 // This letter has no case equivalents, so it's nice and simple
1838 // and the mask-compare will determine definitely whether we have
1839 // a match at this character position.
1840 pos->mask = char_mask;
1841 pos->value = c;
1842 pos->determines_perfectly = true;
1843 } else {
1844 uint32_t common_bits = char_mask;
1845 uint32_t bits = chars[0];
1846 for (int j = 1; j < length; j++) {
1847 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1848 common_bits ^= differing_bits;
1849 bits &= common_bits;
1850 }
1851 // If length is 2 and common bits has only one zero in it then
1852 // our mask and compare instruction will determine definitely
1853 // whether we have a match at this character position. Otherwise
1854 // it can only be an approximate check.
1855 uint32_t one_zero = (common_bits | ~char_mask);
1856 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1857 pos->determines_perfectly = true;
1858 }
1859 pos->mask = common_bits;
1860 pos->value = bits;
1861 }
1862 } else {
1863 // Don't ignore case. Nice simple case where the mask-compare will
1864 // determine definitely whether we have a match at this character
1865 // position.
1866 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001867 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001868 pos->determines_perfectly = true;
1869 }
1870 characters_filled_in++;
1871 ASSERT(characters_filled_in <= details->characters());
1872 if (characters_filled_in == details->characters()) {
1873 return;
1874 }
1875 }
1876 } else {
1877 QuickCheckDetails::Position* pos =
1878 details->positions(characters_filled_in);
1879 RegExpCharacterClass* tree = elm.data.u_char_class;
1880 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001881 if (tree->is_negated()) {
1882 // A quick check uses multi-character mask and compare. There is no
1883 // useful way to incorporate a negative char class into this scheme
1884 // so we just conservatively create a mask and value that will always
1885 // succeed.
1886 pos->mask = 0;
1887 pos->value = 0;
1888 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001889 int first_range = 0;
1890 while (ranges->at(first_range).from() > char_mask) {
1891 first_range++;
1892 if (first_range == ranges->length()) {
1893 details->set_cannot_match();
1894 pos->determines_perfectly = false;
1895 return;
1896 }
1897 }
1898 CharacterRange range = ranges->at(first_range);
1899 uc16 from = range.from();
1900 uc16 to = range.to();
1901 if (to > char_mask) {
1902 to = char_mask;
1903 }
1904 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001905 // A mask and compare is only perfect if the differing bits form a
1906 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001907 if ((differing_bits & (differing_bits + 1)) == 0 &&
1908 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001909 pos->determines_perfectly = true;
1910 }
1911 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001912 uint32_t bits = (from & common_bits);
1913 for (int i = first_range + 1; i < ranges->length(); i++) {
1914 CharacterRange range = ranges->at(i);
1915 uc16 from = range.from();
1916 uc16 to = range.to();
1917 if (from > char_mask) continue;
1918 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001919 // Here we are combining more ranges into the mask and compare
1920 // value. With each new range the mask becomes more sparse and
1921 // so the chances of a false positive rise. A character class
1922 // with multiple ranges is assumed never to be equivalent to a
1923 // mask and compare operation.
1924 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001925 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001926 new_common_bits = ~SmearBitsRight(new_common_bits);
1927 common_bits &= new_common_bits;
1928 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001929 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001930 common_bits ^= differing_bits;
1931 bits &= common_bits;
1932 }
1933 pos->mask = common_bits;
1934 pos->value = bits;
1935 }
1936 characters_filled_in++;
1937 ASSERT(characters_filled_in <= details->characters());
1938 if (characters_filled_in == details->characters()) {
1939 return;
1940 }
1941 }
1942 }
1943 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00001944 on_success()-> GetQuickCheckDetails(details,
1945 compiler,
1946 characters_filled_in,
1947 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001948}
1949
1950
1951void QuickCheckDetails::Clear() {
1952 for (int i = 0; i < characters_; i++) {
1953 positions_[i].mask = 0;
1954 positions_[i].value = 0;
1955 positions_[i].determines_perfectly = false;
1956 }
1957 characters_ = 0;
1958}
1959
1960
1961void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001962 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001963 if (by >= characters_) {
1964 Clear();
1965 return;
1966 }
1967 for (int i = 0; i < characters_ - by; i++) {
1968 positions_[i] = positions_[by + i];
1969 }
1970 for (int i = characters_ - by; i < characters_; i++) {
1971 positions_[i].mask = 0;
1972 positions_[i].value = 0;
1973 positions_[i].determines_perfectly = false;
1974 }
1975 characters_ -= by;
1976 // We could change mask_ and value_ here but we would never advance unless
1977 // they had already been used in a check and they won't be used again because
1978 // it would gain us nothing. So there's no point.
1979}
1980
1981
1982void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1983 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001984 if (other->cannot_match_) {
1985 return;
1986 }
1987 if (cannot_match_) {
1988 *this = *other;
1989 return;
1990 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001991 for (int i = from_index; i < characters_; i++) {
1992 QuickCheckDetails::Position* pos = positions(i);
1993 QuickCheckDetails::Position* other_pos = other->positions(i);
1994 if (pos->mask != other_pos->mask ||
1995 pos->value != other_pos->value ||
1996 !other_pos->determines_perfectly) {
1997 // Our mask-compare operation will be approximate unless we have the
1998 // exact same operation on both sides of the alternation.
1999 pos->determines_perfectly = false;
2000 }
2001 pos->mask &= other_pos->mask;
2002 pos->value &= pos->mask;
2003 other_pos->value &= pos->mask;
2004 uc16 differing_bits = (pos->value ^ other_pos->value);
2005 pos->mask &= ~differing_bits;
2006 pos->value &= pos->mask;
2007 }
2008}
2009
2010
ager@chromium.org32912102009-01-16 10:38:43 +00002011class VisitMarker {
2012 public:
2013 explicit VisitMarker(NodeInfo* info) : info_(info) {
2014 ASSERT(!info->visited);
2015 info->visited = true;
2016 }
2017 ~VisitMarker() {
2018 info_->visited = false;
2019 }
2020 private:
2021 NodeInfo* info_;
2022};
2023
2024
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002025void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2026 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002027 int characters_filled_in,
2028 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002029 if (body_can_be_zero_length_ || info()->visited) return;
2030 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002031 return ChoiceNode::GetQuickCheckDetails(details,
2032 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002033 characters_filled_in,
2034 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002035}
2036
2037
2038void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2039 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002040 int characters_filled_in,
2041 bool not_at_start) {
2042 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002043 int choice_count = alternatives_->length();
2044 ASSERT(choice_count > 0);
2045 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2046 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002047 characters_filled_in,
2048 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002049 for (int i = 1; i < choice_count; i++) {
2050 QuickCheckDetails new_details(details->characters());
2051 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002052 node->GetQuickCheckDetails(&new_details, compiler,
2053 characters_filled_in,
2054 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002055 // Here we merge the quick match details of the two branches.
2056 details->Merge(&new_details, characters_filled_in);
2057 }
2058}
2059
2060
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002061// Check for [0-9A-Z_a-z].
2062static void EmitWordCheck(RegExpMacroAssembler* assembler,
2063 Label* word,
2064 Label* non_word,
2065 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002066 if (assembler->CheckSpecialCharacterClass(
2067 fall_through_on_word ? 'w' : 'W',
2068 fall_through_on_word ? non_word : word)) {
2069 // Optimized implementation available.
2070 return;
2071 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002072 assembler->CheckCharacterGT('z', non_word);
2073 assembler->CheckCharacterLT('0', non_word);
2074 assembler->CheckCharacterGT('a' - 1, word);
2075 assembler->CheckCharacterLT('9' + 1, word);
2076 assembler->CheckCharacterLT('A', non_word);
2077 assembler->CheckCharacterLT('Z' + 1, word);
2078 if (fall_through_on_word) {
2079 assembler->CheckNotCharacter('_', non_word);
2080 } else {
2081 assembler->CheckCharacter('_', word);
2082 }
2083}
2084
2085
2086// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2087// that matches newline or the start of input).
2088static void EmitHat(RegExpCompiler* compiler,
2089 RegExpNode* on_success,
2090 Trace* trace) {
2091 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2092 // We will be loading the previous character into the current character
2093 // register.
2094 Trace new_trace(*trace);
2095 new_trace.InvalidateCurrentCharacter();
2096
2097 Label ok;
2098 if (new_trace.cp_offset() == 0) {
2099 // The start of input counts as a newline in this context, so skip to
2100 // ok if we are at the start.
2101 assembler->CheckAtStart(&ok);
2102 }
2103 // We already checked that we are not at the start of input so it must be
2104 // OK to load the previous character.
2105 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2106 new_trace.backtrack(),
2107 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002108 if (!assembler->CheckSpecialCharacterClass('n',
2109 new_trace.backtrack())) {
2110 // Newline means \n, \r, 0x2028 or 0x2029.
2111 if (!compiler->ascii()) {
2112 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2113 }
2114 assembler->CheckCharacter('\n', &ok);
2115 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002116 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002117 assembler->Bind(&ok);
2118 on_success->Emit(compiler, &new_trace);
2119}
2120
2121
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002122// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2123// when we know whether the next character must be a word character or not.
2124static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2125 RegExpCompiler* compiler,
2126 RegExpNode* on_success,
2127 Trace* trace) {
2128 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2129 Label done;
2130
2131 Trace new_trace(*trace);
2132
2133 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2134 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2135 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2136
2137 // Check whether previous character was a word character.
2138 switch (trace->at_start()) {
2139 case Trace::TRUE:
2140 if (expect_word_character) {
2141 assembler->GoTo(on_non_word);
2142 }
2143 break;
2144 case Trace::UNKNOWN:
2145 ASSERT_EQ(0, trace->cp_offset());
2146 assembler->CheckAtStart(on_non_word);
2147 // Fall through.
2148 case Trace::FALSE:
2149 int prev_char_offset = trace->cp_offset() - 1;
2150 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2151 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2152 // We may or may not have loaded the previous character.
2153 new_trace.InvalidateCurrentCharacter();
2154 }
2155
2156 assembler->Bind(&done);
2157
2158 on_success->Emit(compiler, &new_trace);
2159}
2160
2161
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002162// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2163static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2164 RegExpCompiler* compiler,
2165 RegExpNode* on_success,
2166 Trace* trace) {
2167 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2168 Label before_non_word;
2169 Label before_word;
2170 if (trace->characters_preloaded() != 1) {
2171 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2172 }
2173 // Fall through on non-word.
2174 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2175
2176 // We will be loading the previous character into the current character
2177 // register.
2178 Trace new_trace(*trace);
2179 new_trace.InvalidateCurrentCharacter();
2180
2181 Label ok;
2182 Label* boundary;
2183 Label* not_boundary;
2184 if (type == AssertionNode::AT_BOUNDARY) {
2185 boundary = &ok;
2186 not_boundary = new_trace.backtrack();
2187 } else {
2188 not_boundary = &ok;
2189 boundary = new_trace.backtrack();
2190 }
2191
2192 // Next character is not a word character.
2193 assembler->Bind(&before_non_word);
2194 if (new_trace.cp_offset() == 0) {
2195 // The start of input counts as a non-word character, so the question is
2196 // decided if we are at the start.
2197 assembler->CheckAtStart(not_boundary);
2198 }
2199 // We already checked that we are not at the start of input so it must be
2200 // OK to load the previous character.
2201 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2202 &ok, // Unused dummy label in this call.
2203 false);
2204 // Fall through on non-word.
2205 EmitWordCheck(assembler, boundary, not_boundary, false);
2206 assembler->GoTo(not_boundary);
2207
2208 // Next character is a word character.
2209 assembler->Bind(&before_word);
2210 if (new_trace.cp_offset() == 0) {
2211 // The start of input counts as a non-word character, so the question is
2212 // decided if we are at the start.
2213 assembler->CheckAtStart(boundary);
2214 }
2215 // We already checked that we are not at the start of input so it must be
2216 // OK to load the previous character.
2217 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2218 &ok, // Unused dummy label in this call.
2219 false);
2220 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2221 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2222
2223 assembler->Bind(&ok);
2224
2225 on_success->Emit(compiler, &new_trace);
2226}
2227
2228
iposva@chromium.org245aa852009-02-10 00:49:54 +00002229void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2230 RegExpCompiler* compiler,
2231 int filled_in,
2232 bool not_at_start) {
2233 if (type_ == AT_START && not_at_start) {
2234 details->set_cannot_match();
2235 return;
2236 }
2237 return on_success()->GetQuickCheckDetails(details,
2238 compiler,
2239 filled_in,
2240 not_at_start);
2241}
2242
2243
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002244void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2245 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2246 switch (type_) {
2247 case AT_END: {
2248 Label ok;
2249 assembler->CheckPosition(trace->cp_offset(), &ok);
2250 assembler->GoTo(trace->backtrack());
2251 assembler->Bind(&ok);
2252 break;
2253 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002254 case AT_START: {
2255 if (trace->at_start() == Trace::FALSE) {
2256 assembler->GoTo(trace->backtrack());
2257 return;
2258 }
2259 if (trace->at_start() == Trace::UNKNOWN) {
2260 assembler->CheckNotAtStart(trace->backtrack());
2261 Trace at_start_trace = *trace;
2262 at_start_trace.set_at_start(true);
2263 on_success()->Emit(compiler, &at_start_trace);
2264 return;
2265 }
2266 }
2267 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002268 case AFTER_NEWLINE:
2269 EmitHat(compiler, on_success(), trace);
2270 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002271 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002272 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002273 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2274 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002275 }
2276 case AFTER_WORD_CHARACTER:
2277 case AFTER_NONWORD_CHARACTER: {
2278 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2279 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002280 }
2281 on_success()->Emit(compiler, trace);
2282}
2283
2284
ager@chromium.org381abbb2009-02-25 13:23:22 +00002285static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2286 if (quick_check == NULL) return false;
2287 if (offset >= quick_check->characters()) return false;
2288 return quick_check->positions(offset)->determines_perfectly;
2289}
2290
2291
2292static void UpdateBoundsCheck(int index, int* checked_up_to) {
2293 if (index > *checked_up_to) {
2294 *checked_up_to = index;
2295 }
2296}
2297
2298
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002299// We call this repeatedly to generate code for each pass over the text node.
2300// The passes are in increasing order of difficulty because we hope one
2301// of the first passes will fail in which case we are saved the work of the
2302// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2303// we will check the '%' in the first pass, the case independent 'a' in the
2304// second pass and the character class in the last pass.
2305//
2306// The passes are done from right to left, so for example to test for /bar/
2307// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2308// and then a 'b' with offset 0. This means we can avoid the end-of-input
2309// bounds check most of the time. In the example we only need to check for
2310// end-of-input when loading the putative 'r'.
2311//
2312// A slight complication involves the fact that the first character may already
2313// be fetched into a register by the previous node. In this case we want to
2314// do the test for that character first. We do this in separate passes. The
2315// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2316// pass has been performed then subsequent passes will have true in
2317// first_element_checked to indicate that that character does not need to be
2318// checked again.
2319//
ager@chromium.org32912102009-01-16 10:38:43 +00002320// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002321// contain an AlternativeGeneration object. In this AlternativeGeneration
2322// object we can see details of any quick check that was already passed in
2323// order to get to the code we are now generating. The quick check can involve
2324// loading characters, which means we do not need to recheck the bounds
2325// up to the limit the quick check already checked. In addition the quick
2326// check can have involved a mask and compare operation which may simplify
2327// or obviate the need for further checks at some character positions.
2328void TextNode::TextEmitPass(RegExpCompiler* compiler,
2329 TextEmitPassType pass,
2330 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002331 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002332 bool first_element_checked,
2333 int* checked_up_to) {
2334 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2335 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002336 Label* backtrack = trace->backtrack();
2337 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002338 int element_count = elms_->length();
2339 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2340 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002341 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002342 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002343 Vector<const uc16> quarks = elm.data.u_atom->data();
2344 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2345 if (first_element_checked && i == 0 && j == 0) continue;
2346 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2347 EmitCharacterFunction* emit_function = NULL;
2348 switch (pass) {
2349 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002350 ASSERT(ascii);
2351 if (quarks[j] > String::kMaxAsciiCharCode) {
2352 assembler->GoTo(backtrack);
2353 return;
2354 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002355 break;
2356 case NON_LETTER_CHARACTER_MATCH:
2357 emit_function = &EmitAtomNonLetter;
2358 break;
2359 case SIMPLE_CHARACTER_MATCH:
2360 emit_function = &EmitSimpleCharacter;
2361 break;
2362 case CASE_CHARACTER_MATCH:
2363 emit_function = &EmitAtomLetter;
2364 break;
2365 default:
2366 break;
2367 }
2368 if (emit_function != NULL) {
2369 bool bound_checked = emit_function(compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002370 quarks[j],
2371 backtrack,
2372 cp_offset + j,
2373 *checked_up_to < cp_offset + j,
2374 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002375 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002376 }
2377 }
2378 } else {
2379 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002380 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002381 if (first_element_checked && i == 0) continue;
2382 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002383 RegExpCharacterClass* cc = elm.data.u_char_class;
2384 EmitCharClass(assembler,
2385 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002386 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002387 backtrack,
2388 cp_offset,
2389 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002390 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002391 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002392 }
2393 }
2394 }
2395}
2396
2397
2398int TextNode::Length() {
2399 TextElement elm = elms_->last();
2400 ASSERT(elm.cp_offset >= 0);
2401 if (elm.type == TextElement::ATOM) {
2402 return elm.cp_offset + elm.data.u_atom->data().length();
2403 } else {
2404 return elm.cp_offset + 1;
2405 }
2406}
2407
2408
ager@chromium.org381abbb2009-02-25 13:23:22 +00002409bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2410 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2411 if (ignore_case) {
2412 return pass == SIMPLE_CHARACTER_MATCH;
2413 } else {
2414 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2415 }
2416}
2417
2418
ager@chromium.org8bb60582008-12-11 12:02:20 +00002419// This generates the code to match a text node. A text node can contain
2420// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002421// way) and character classes. For efficiency we do not do this in a single
2422// pass from left to right. Instead we pass over the text node several times,
2423// emitting code for some character positions every time. See the comment on
2424// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002425void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002426 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002427 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002428 ASSERT(limit_result == CONTINUE);
2429
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002430 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2431 compiler->SetRegExpTooBig();
2432 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002433 }
2434
2435 if (compiler->ascii()) {
2436 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002437 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002438 }
2439
2440 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002441 int bound_checked_to = trace->cp_offset() - 1;
2442 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002443
2444 // If a character is preloaded into the current character register then
2445 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002446 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002447 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2448 if (!SkipPass(pass, compiler->ignore_case())) {
2449 TextEmitPass(compiler,
2450 static_cast<TextEmitPassType>(pass),
2451 true,
2452 trace,
2453 false,
2454 &bound_checked_to);
2455 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002456 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002457 first_elt_done = true;
2458 }
2459
ager@chromium.org381abbb2009-02-25 13:23:22 +00002460 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2461 if (!SkipPass(pass, compiler->ignore_case())) {
2462 TextEmitPass(compiler,
2463 static_cast<TextEmitPassType>(pass),
2464 false,
2465 trace,
2466 first_elt_done,
2467 &bound_checked_to);
2468 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002469 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002470
ager@chromium.org32912102009-01-16 10:38:43 +00002471 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002472 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002473 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002474 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002475 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002476}
2477
2478
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002479void Trace::InvalidateCurrentCharacter() {
2480 characters_preloaded_ = 0;
2481}
2482
2483
2484void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002485 ASSERT(by > 0);
2486 // We don't have an instruction for shifting the current character register
2487 // down or for using a shifted value for anything so lets just forget that
2488 // we preloaded any characters into it.
2489 characters_preloaded_ = 0;
2490 // Adjust the offsets of the quick check performed information. This
2491 // information is used to find out what we already determined about the
2492 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002493 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002494 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002495 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2496 compiler->SetRegExpTooBig();
2497 cp_offset_ = 0;
2498 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002499 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002500}
2501
2502
ager@chromium.org38e4c712009-11-11 09:11:58 +00002503void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002504 int element_count = elms_->length();
2505 for (int i = 0; i < element_count; i++) {
2506 TextElement elm = elms_->at(i);
2507 if (elm.type == TextElement::CHAR_CLASS) {
2508 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002509 // None of the standard character classses is different in the case
2510 // independent case and it slows us down if we don't know that.
2511 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002512 ZoneList<CharacterRange>* ranges = cc->ranges();
2513 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002514 for (int j = 0; j < range_count; j++) {
2515 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002516 }
2517 }
2518 }
2519}
2520
2521
ager@chromium.org8bb60582008-12-11 12:02:20 +00002522int TextNode::GreedyLoopTextLength() {
2523 TextElement elm = elms_->at(elms_->length() - 1);
2524 if (elm.type == TextElement::CHAR_CLASS) {
2525 return elm.cp_offset + 1;
2526 } else {
2527 return elm.cp_offset + elm.data.u_atom->data().length();
2528 }
2529}
2530
2531
2532// Finds the fixed match length of a sequence of nodes that goes from
2533// this alternative and back to this choice node. If there are variable
2534// length nodes or other complications in the way then return a sentinel
2535// value indicating that a greedy loop cannot be constructed.
2536int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2537 int length = 0;
2538 RegExpNode* node = alternative->node();
2539 // Later we will generate code for all these text nodes using recursion
2540 // so we have to limit the max number.
2541 int recursion_depth = 0;
2542 while (node != this) {
2543 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2544 return kNodeIsTooComplexForGreedyLoops;
2545 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002546 int node_length = node->GreedyLoopTextLength();
2547 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2548 return kNodeIsTooComplexForGreedyLoops;
2549 }
2550 length += node_length;
2551 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2552 node = seq_node->on_success();
2553 }
2554 return length;
2555}
2556
2557
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002558void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2559 ASSERT_EQ(loop_node_, NULL);
2560 AddAlternative(alt);
2561 loop_node_ = alt.node();
2562}
2563
2564
2565void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2566 ASSERT_EQ(continue_node_, NULL);
2567 AddAlternative(alt);
2568 continue_node_ = alt.node();
2569}
2570
2571
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002572void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002573 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002574 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002575 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2576 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2577 // Update the counter-based backtracking info on the stack. This is an
2578 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002579 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002580 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002581 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002582 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002583 }
ager@chromium.org32912102009-01-16 10:38:43 +00002584 ASSERT(trace->stop_node() == NULL);
2585 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002586 trace->Flush(compiler, this);
2587 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002588 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002589 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002590}
2591
2592
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002593int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002594 int preload_characters = EatsAtLeast(4, 0);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002595 if (compiler->macro_assembler()->CanReadUnaligned()) {
2596 bool ascii = compiler->ascii();
2597 if (ascii) {
2598 if (preload_characters > 4) preload_characters = 4;
2599 // We can't preload 3 characters because there is no machine instruction
2600 // to do that. We can't just load 4 because we could be reading
2601 // beyond the end of the string, which could cause a memory fault.
2602 if (preload_characters == 3) preload_characters = 2;
2603 } else {
2604 if (preload_characters > 2) preload_characters = 2;
2605 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002606 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002607 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002608 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002609 return preload_characters;
2610}
2611
2612
2613// This class is used when generating the alternatives in a choice node. It
2614// records the way the alternative is being code generated.
2615class AlternativeGeneration: public Malloced {
2616 public:
2617 AlternativeGeneration()
2618 : possible_success(),
2619 expects_preload(false),
2620 after(),
2621 quick_check_details() { }
2622 Label possible_success;
2623 bool expects_preload;
2624 Label after;
2625 QuickCheckDetails quick_check_details;
2626};
2627
2628
2629// Creates a list of AlternativeGenerations. If the list has a reasonable
2630// size then it is on the stack, otherwise the excess is on the heap.
2631class AlternativeGenerationList {
2632 public:
2633 explicit AlternativeGenerationList(int count)
2634 : alt_gens_(count) {
2635 for (int i = 0; i < count && i < kAFew; i++) {
2636 alt_gens_.Add(a_few_alt_gens_ + i);
2637 }
2638 for (int i = kAFew; i < count; i++) {
2639 alt_gens_.Add(new AlternativeGeneration());
2640 }
2641 }
2642 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002643 for (int i = kAFew; i < alt_gens_.length(); i++) {
2644 delete alt_gens_[i];
2645 alt_gens_[i] = NULL;
2646 }
2647 }
2648
2649 AlternativeGeneration* at(int i) {
2650 return alt_gens_[i];
2651 }
2652 private:
2653 static const int kAFew = 10;
2654 ZoneList<AlternativeGeneration*> alt_gens_;
2655 AlternativeGeneration a_few_alt_gens_[kAFew];
2656};
2657
2658
2659/* Code generation for choice nodes.
2660 *
2661 * We generate quick checks that do a mask and compare to eliminate a
2662 * choice. If the quick check succeeds then it jumps to the continuation to
2663 * do slow checks and check subsequent nodes. If it fails (the common case)
2664 * it falls through to the next choice.
2665 *
2666 * Here is the desired flow graph. Nodes directly below each other imply
2667 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2668 * 3 doesn't have a quick check so we have to call the slow check.
2669 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2670 * regexp continuation is generated directly after the Sn node, up to the
2671 * next GoTo if we decide to reuse some already generated code. Some
2672 * nodes expect preload_characters to be preloaded into the current
2673 * character register. R nodes do this preloading. Vertices are marked
2674 * F for failures and S for success (possible success in the case of quick
2675 * nodes). L, V, < and > are used as arrow heads.
2676 *
2677 * ----------> R
2678 * |
2679 * V
2680 * Q1 -----> S1
2681 * | S /
2682 * F| /
2683 * | F/
2684 * | /
2685 * | R
2686 * | /
2687 * V L
2688 * Q2 -----> S2
2689 * | S /
2690 * F| /
2691 * | F/
2692 * | /
2693 * | R
2694 * | /
2695 * V L
2696 * S3
2697 * |
2698 * F|
2699 * |
2700 * R
2701 * |
2702 * backtrack V
2703 * <----------Q4
2704 * \ F |
2705 * \ |S
2706 * \ F V
2707 * \-----S4
2708 *
2709 * For greedy loops we reverse our expectation and expect to match rather
2710 * than fail. Therefore we want the loop code to look like this (U is the
2711 * unwind code that steps back in the greedy loop). The following alternatives
2712 * look the same as above.
2713 * _____
2714 * / \
2715 * V |
2716 * ----------> S1 |
2717 * /| |
2718 * / |S |
2719 * F/ \_____/
2720 * /
2721 * |<-----------
2722 * | \
2723 * V \
2724 * Q2 ---> S2 \
2725 * | S / |
2726 * F| / |
2727 * | F/ |
2728 * | / |
2729 * | R |
2730 * | / |
2731 * F VL |
2732 * <------U |
2733 * back |S |
2734 * \______________/
2735 */
2736
2737
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002738void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002739 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2740 int choice_count = alternatives_->length();
2741#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002742 for (int i = 0; i < choice_count - 1; i++) {
2743 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002744 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002745 int guard_count = (guards == NULL) ? 0 : guards->length();
2746 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002747 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002748 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002749 }
2750#endif
2751
ager@chromium.org32912102009-01-16 10:38:43 +00002752 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002753 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002754 ASSERT(limit_result == CONTINUE);
2755
ager@chromium.org381abbb2009-02-25 13:23:22 +00002756 int new_flush_budget = trace->flush_budget() / choice_count;
2757 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2758 trace->Flush(compiler, this);
2759 return;
2760 }
2761
ager@chromium.org8bb60582008-12-11 12:02:20 +00002762 RecursionCheck rc(compiler);
2763
ager@chromium.org32912102009-01-16 10:38:43 +00002764 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002765
2766 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2767 bool greedy_loop = false;
2768 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002769 Trace counter_backtrack_trace;
2770 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002771 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2772
ager@chromium.org8bb60582008-12-11 12:02:20 +00002773 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2774 // Here we have special handling for greedy loops containing only text nodes
2775 // and other simple nodes. These are handled by pushing the current
2776 // position on the stack and then incrementing the current position each
2777 // time around the switch. On backtrack we decrement the current position
2778 // and check it against the pushed value. This avoids pushing backtrack
2779 // information for each iteration of the loop, which could take up a lot of
2780 // space.
2781 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002782 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002783 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002784 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002785 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002786 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002787 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002788 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002789 Label loop_label;
2790 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002791 greedy_match_trace.set_stop_node(this);
2792 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002793 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002794 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002795 }
2796
2797 Label second_choice; // For use in greedy matches.
2798 macro_assembler->Bind(&second_choice);
2799
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002800 int first_normal_choice = greedy_loop ? 1 : 0;
2801
2802 int preload_characters = CalculatePreloadCharacters(compiler);
2803 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002804 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002805 bool preload_has_checked_bounds = preload_is_current;
2806
2807 AlternativeGenerationList alt_gens(choice_count);
2808
ager@chromium.org8bb60582008-12-11 12:02:20 +00002809 // For now we just call all choices one after the other. The idea ultimately
2810 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002811 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002812 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002813 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002814 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002815 ZoneList<Guard*>* guards = alternative.guards();
2816 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002817 Trace new_trace(*current_trace);
2818 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002819 preload_characters :
2820 0);
2821 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002822 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002823 }
ager@chromium.org32912102009-01-16 10:38:43 +00002824 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002825 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002826 alt_gen->expects_preload = preload_is_current;
2827 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002828 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002829 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002830 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002831 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002832 preload_has_checked_bounds,
2833 &alt_gen->possible_success,
2834 &alt_gen->quick_check_details,
2835 i < choice_count - 1)) {
2836 // Quick check was generated for this choice.
2837 preload_is_current = true;
2838 preload_has_checked_bounds = true;
2839 // On the last choice in the ChoiceNode we generated the quick
2840 // check to fall through on possible success. So now we need to
2841 // generate the full check inline.
2842 if (i == choice_count - 1) {
2843 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002844 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2845 new_trace.set_characters_preloaded(preload_characters);
2846 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002847 generate_full_check_inline = true;
2848 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002849 } else if (alt_gen->quick_check_details.cannot_match()) {
2850 if (i == choice_count - 1 && !greedy_loop) {
2851 macro_assembler->GoTo(trace->backtrack());
2852 }
2853 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002854 } else {
2855 // No quick check was generated. Put the full code here.
2856 // If this is not the first choice then there could be slow checks from
2857 // previous cases that go here when they fail. There's no reason to
2858 // insist that they preload characters since the slow check we are about
2859 // to generate probably can't use it.
2860 if (i != first_normal_choice) {
2861 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002862 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002863 }
2864 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002865 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002866 }
2867 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002868 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002869 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002870 if (new_trace.actions() != NULL) {
2871 new_trace.set_flush_budget(new_flush_budget);
2872 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002873 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002874 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002875 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002876 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002877 preload_is_current = false;
2878 }
2879 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002880 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002881 if (greedy_loop) {
2882 macro_assembler->Bind(&greedy_loop_label);
2883 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002884 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002885 // Otherwise try the second priority at an earlier position.
2886 macro_assembler->AdvanceCurrentPosition(-text_length);
2887 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002888 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002889
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002890 // At this point we need to generate slow checks for the alternatives where
2891 // the quick check was inlined. We can recognize these because the associated
2892 // label was bound.
2893 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2894 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002895 Trace new_trace(*current_trace);
2896 // If there are actions to be flushed we have to limit how many times
2897 // they are flushed. Take the budget of the parent trace and distribute
2898 // it fairly amongst the children.
2899 if (new_trace.actions() != NULL) {
2900 new_trace.set_flush_budget(new_flush_budget);
2901 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002902 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002903 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002904 alternatives_->at(i),
2905 alt_gen,
2906 preload_characters,
2907 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002908 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002909}
2910
2911
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002912void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002913 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002914 GuardedAlternative alternative,
2915 AlternativeGeneration* alt_gen,
2916 int preload_characters,
2917 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002918 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002919
2920 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2921 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002922 Trace out_of_line_trace(*trace);
2923 out_of_line_trace.set_characters_preloaded(preload_characters);
2924 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002925 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002926 ZoneList<Guard*>* guards = alternative.guards();
2927 int guard_count = (guards == NULL) ? 0 : guards->length();
2928 if (next_expects_preload) {
2929 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00002930 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002931 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002932 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002933 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002934 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002935 macro_assembler->Bind(&reload_current_char);
2936 // Reload the current character, since the next quick check expects that.
2937 // We don't need to check bounds here because we only get into this
2938 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00002939 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002940 NULL,
2941 false,
2942 preload_characters);
2943 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002944 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00002945 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002946 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002947 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002948 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002949 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002950 }
2951}
2952
2953
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002954void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002955 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002956 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002957 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002958 ASSERT(limit_result == CONTINUE);
2959
2960 RecursionCheck rc(compiler);
2961
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002962 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002963 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00002964 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002965 new_capture(data_.u_position_register.reg,
2966 data_.u_position_register.is_capture,
2967 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002968 Trace new_trace = *trace;
2969 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002970 on_success()->Emit(compiler, &new_trace);
2971 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002972 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002973 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002974 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002975 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00002976 Trace new_trace = *trace;
2977 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002978 on_success()->Emit(compiler, &new_trace);
2979 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002980 }
2981 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002982 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002983 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00002984 Trace new_trace = *trace;
2985 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002986 on_success()->Emit(compiler, &new_trace);
2987 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002988 }
2989 case CLEAR_CAPTURES: {
2990 Trace::DeferredClearCaptures
2991 new_capture(Interval(data_.u_clear_captures.range_from,
2992 data_.u_clear_captures.range_to));
2993 Trace new_trace = *trace;
2994 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002995 on_success()->Emit(compiler, &new_trace);
2996 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002997 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002998 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002999 if (!trace->is_trivial()) {
3000 trace->Flush(compiler, this);
3001 } else {
3002 assembler->WriteCurrentPositionToRegister(
3003 data_.u_submatch.current_position_register, 0);
3004 assembler->WriteStackPointerToRegister(
3005 data_.u_submatch.stack_pointer_register);
3006 on_success()->Emit(compiler, trace);
3007 }
3008 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003009 case EMPTY_MATCH_CHECK: {
3010 int start_pos_reg = data_.u_empty_match_check.start_register;
3011 int stored_pos = 0;
3012 int rep_reg = data_.u_empty_match_check.repetition_register;
3013 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3014 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3015 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3016 // If we know we haven't advanced and there is no minimum we
3017 // can just backtrack immediately.
3018 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003019 } else if (know_dist && stored_pos < trace->cp_offset()) {
3020 // If we know we've advanced we can generate the continuation
3021 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003022 on_success()->Emit(compiler, trace);
3023 } else if (!trace->is_trivial()) {
3024 trace->Flush(compiler, this);
3025 } else {
3026 Label skip_empty_check;
3027 // If we have a minimum number of repetitions we check the current
3028 // number first and skip the empty check if it's not enough.
3029 if (has_minimum) {
3030 int limit = data_.u_empty_match_check.repetition_limit;
3031 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3032 }
3033 // If the match is empty we bail out, otherwise we fall through
3034 // to the on-success continuation.
3035 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3036 trace->backtrack());
3037 assembler->Bind(&skip_empty_check);
3038 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003039 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003040 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003041 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003042 case POSITIVE_SUBMATCH_SUCCESS: {
3043 if (!trace->is_trivial()) {
3044 trace->Flush(compiler, this);
3045 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003046 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003047 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003048 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003049 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003050 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003051 int clear_register_count = data_.u_submatch.clear_register_count;
3052 if (clear_register_count == 0) {
3053 on_success()->Emit(compiler, trace);
3054 return;
3055 }
3056 int clear_registers_from = data_.u_submatch.clear_register_from;
3057 Label clear_registers_backtrack;
3058 Trace new_trace = *trace;
3059 new_trace.set_backtrack(&clear_registers_backtrack);
3060 on_success()->Emit(compiler, &new_trace);
3061
3062 assembler->Bind(&clear_registers_backtrack);
3063 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3064 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3065
3066 ASSERT(trace->backtrack() == NULL);
3067 assembler->Backtrack();
3068 return;
3069 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003070 default:
3071 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003072 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003073}
3074
3075
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003076void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003077 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003078 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003079 trace->Flush(compiler, this);
3080 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003081 }
3082
ager@chromium.org32912102009-01-16 10:38:43 +00003083 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003084 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003085 ASSERT(limit_result == CONTINUE);
3086
3087 RecursionCheck rc(compiler);
3088
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003089 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003090 if (compiler->ignore_case()) {
3091 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3092 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003093 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003094 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003095 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003096 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003097}
3098
3099
3100// -------------------------------------------------------------------
3101// Dot/dotty output
3102
3103
3104#ifdef DEBUG
3105
3106
3107class DotPrinter: public NodeVisitor {
3108 public:
3109 explicit DotPrinter(bool ignore_case)
3110 : ignore_case_(ignore_case),
3111 stream_(&alloc_) { }
3112 void PrintNode(const char* label, RegExpNode* node);
3113 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003114 void PrintAttributes(RegExpNode* from);
3115 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003116 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003117#define DECLARE_VISIT(Type) \
3118 virtual void Visit##Type(Type##Node* that);
3119FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3120#undef DECLARE_VISIT
3121 private:
3122 bool ignore_case_;
3123 HeapStringAllocator alloc_;
3124 StringStream stream_;
3125};
3126
3127
3128void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3129 stream()->Add("digraph G {\n graph [label=\"");
3130 for (int i = 0; label[i]; i++) {
3131 switch (label[i]) {
3132 case '\\':
3133 stream()->Add("\\\\");
3134 break;
3135 case '"':
3136 stream()->Add("\"");
3137 break;
3138 default:
3139 stream()->Put(label[i]);
3140 break;
3141 }
3142 }
3143 stream()->Add("\"];\n");
3144 Visit(node);
3145 stream()->Add("}\n");
3146 printf("%s", *(stream()->ToCString()));
3147}
3148
3149
3150void DotPrinter::Visit(RegExpNode* node) {
3151 if (node->info()->visited) return;
3152 node->info()->visited = true;
3153 node->Accept(this);
3154}
3155
3156
3157void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003158 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3159 Visit(on_failure);
3160}
3161
3162
3163class TableEntryBodyPrinter {
3164 public:
3165 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3166 : stream_(stream), choice_(choice) { }
3167 void Call(uc16 from, DispatchTable::Entry entry) {
3168 OutSet* out_set = entry.out_set();
3169 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3170 if (out_set->Get(i)) {
3171 stream()->Add(" n%p:s%io%i -> n%p;\n",
3172 choice(),
3173 from,
3174 i,
3175 choice()->alternatives()->at(i).node());
3176 }
3177 }
3178 }
3179 private:
3180 StringStream* stream() { return stream_; }
3181 ChoiceNode* choice() { return choice_; }
3182 StringStream* stream_;
3183 ChoiceNode* choice_;
3184};
3185
3186
3187class TableEntryHeaderPrinter {
3188 public:
3189 explicit TableEntryHeaderPrinter(StringStream* stream)
3190 : first_(true), stream_(stream) { }
3191 void Call(uc16 from, DispatchTable::Entry entry) {
3192 if (first_) {
3193 first_ = false;
3194 } else {
3195 stream()->Add("|");
3196 }
3197 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3198 OutSet* out_set = entry.out_set();
3199 int priority = 0;
3200 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3201 if (out_set->Get(i)) {
3202 if (priority > 0) stream()->Add("|");
3203 stream()->Add("<s%io%i> %i", from, i, priority);
3204 priority++;
3205 }
3206 }
3207 stream()->Add("}}");
3208 }
3209 private:
3210 bool first_;
3211 StringStream* stream() { return stream_; }
3212 StringStream* stream_;
3213};
3214
3215
3216class AttributePrinter {
3217 public:
3218 explicit AttributePrinter(DotPrinter* out)
3219 : out_(out), first_(true) { }
3220 void PrintSeparator() {
3221 if (first_) {
3222 first_ = false;
3223 } else {
3224 out_->stream()->Add("|");
3225 }
3226 }
3227 void PrintBit(const char* name, bool value) {
3228 if (!value) return;
3229 PrintSeparator();
3230 out_->stream()->Add("{%s}", name);
3231 }
3232 void PrintPositive(const char* name, int value) {
3233 if (value < 0) return;
3234 PrintSeparator();
3235 out_->stream()->Add("{%s|%x}", name, value);
3236 }
3237 private:
3238 DotPrinter* out_;
3239 bool first_;
3240};
3241
3242
3243void DotPrinter::PrintAttributes(RegExpNode* that) {
3244 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3245 "margin=0.1, fontsize=10, label=\"{",
3246 that);
3247 AttributePrinter printer(this);
3248 NodeInfo* info = that->info();
3249 printer.PrintBit("NI", info->follows_newline_interest);
3250 printer.PrintBit("WI", info->follows_word_interest);
3251 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003252 Label* label = that->label();
3253 if (label->is_bound())
3254 printer.PrintPositive("@", label->pos());
3255 stream()->Add("}\"];\n");
3256 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3257 "arrowhead=none];\n", that, that);
3258}
3259
3260
3261static const bool kPrintDispatchTable = false;
3262void DotPrinter::VisitChoice(ChoiceNode* that) {
3263 if (kPrintDispatchTable) {
3264 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3265 TableEntryHeaderPrinter header_printer(stream());
3266 that->GetTable(ignore_case_)->ForEach(&header_printer);
3267 stream()->Add("\"]\n", that);
3268 PrintAttributes(that);
3269 TableEntryBodyPrinter body_printer(stream(), that);
3270 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003271 } else {
3272 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3273 for (int i = 0; i < that->alternatives()->length(); i++) {
3274 GuardedAlternative alt = that->alternatives()->at(i);
3275 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3276 }
3277 }
3278 for (int i = 0; i < that->alternatives()->length(); i++) {
3279 GuardedAlternative alt = that->alternatives()->at(i);
3280 alt.node()->Accept(this);
3281 }
3282}
3283
3284
3285void DotPrinter::VisitText(TextNode* that) {
3286 stream()->Add(" n%p [label=\"", that);
3287 for (int i = 0; i < that->elements()->length(); i++) {
3288 if (i > 0) stream()->Add(" ");
3289 TextElement elm = that->elements()->at(i);
3290 switch (elm.type) {
3291 case TextElement::ATOM: {
3292 stream()->Add("'%w'", elm.data.u_atom->data());
3293 break;
3294 }
3295 case TextElement::CHAR_CLASS: {
3296 RegExpCharacterClass* node = elm.data.u_char_class;
3297 stream()->Add("[");
3298 if (node->is_negated())
3299 stream()->Add("^");
3300 for (int j = 0; j < node->ranges()->length(); j++) {
3301 CharacterRange range = node->ranges()->at(j);
3302 stream()->Add("%k-%k", range.from(), range.to());
3303 }
3304 stream()->Add("]");
3305 break;
3306 }
3307 default:
3308 UNREACHABLE();
3309 }
3310 }
3311 stream()->Add("\", shape=box, peripheries=2];\n");
3312 PrintAttributes(that);
3313 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3314 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003315}
3316
3317
3318void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3319 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3320 that,
3321 that->start_register(),
3322 that->end_register());
3323 PrintAttributes(that);
3324 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3325 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003326}
3327
3328
3329void DotPrinter::VisitEnd(EndNode* that) {
3330 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3331 PrintAttributes(that);
3332}
3333
3334
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003335void DotPrinter::VisitAssertion(AssertionNode* that) {
3336 stream()->Add(" n%p [", that);
3337 switch (that->type()) {
3338 case AssertionNode::AT_END:
3339 stream()->Add("label=\"$\", shape=septagon");
3340 break;
3341 case AssertionNode::AT_START:
3342 stream()->Add("label=\"^\", shape=septagon");
3343 break;
3344 case AssertionNode::AT_BOUNDARY:
3345 stream()->Add("label=\"\\b\", shape=septagon");
3346 break;
3347 case AssertionNode::AT_NON_BOUNDARY:
3348 stream()->Add("label=\"\\B\", shape=septagon");
3349 break;
3350 case AssertionNode::AFTER_NEWLINE:
3351 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3352 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003353 case AssertionNode::AFTER_WORD_CHARACTER:
3354 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3355 break;
3356 case AssertionNode::AFTER_NONWORD_CHARACTER:
3357 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3358 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003359 }
3360 stream()->Add("];\n");
3361 PrintAttributes(that);
3362 RegExpNode* successor = that->on_success();
3363 stream()->Add(" n%p -> n%p;\n", that, successor);
3364 Visit(successor);
3365}
3366
3367
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003368void DotPrinter::VisitAction(ActionNode* that) {
3369 stream()->Add(" n%p [", that);
3370 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003371 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003372 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3373 that->data_.u_store_register.reg,
3374 that->data_.u_store_register.value);
3375 break;
3376 case ActionNode::INCREMENT_REGISTER:
3377 stream()->Add("label=\"$%i++\", shape=octagon",
3378 that->data_.u_increment_register.reg);
3379 break;
3380 case ActionNode::STORE_POSITION:
3381 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3382 that->data_.u_position_register.reg);
3383 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003384 case ActionNode::BEGIN_SUBMATCH:
3385 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3386 that->data_.u_submatch.current_position_register);
3387 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003388 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003389 stream()->Add("label=\"escape\", shape=septagon");
3390 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003391 case ActionNode::EMPTY_MATCH_CHECK:
3392 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3393 that->data_.u_empty_match_check.start_register,
3394 that->data_.u_empty_match_check.repetition_register,
3395 that->data_.u_empty_match_check.repetition_limit);
3396 break;
3397 case ActionNode::CLEAR_CAPTURES: {
3398 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3399 that->data_.u_clear_captures.range_from,
3400 that->data_.u_clear_captures.range_to);
3401 break;
3402 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003403 }
3404 stream()->Add("];\n");
3405 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003406 RegExpNode* successor = that->on_success();
3407 stream()->Add(" n%p -> n%p;\n", that, successor);
3408 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003409}
3410
3411
3412class DispatchTableDumper {
3413 public:
3414 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3415 void Call(uc16 key, DispatchTable::Entry entry);
3416 StringStream* stream() { return stream_; }
3417 private:
3418 StringStream* stream_;
3419};
3420
3421
3422void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3423 stream()->Add("[%k-%k]: {", key, entry.to());
3424 OutSet* set = entry.out_set();
3425 bool first = true;
3426 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3427 if (set->Get(i)) {
3428 if (first) {
3429 first = false;
3430 } else {
3431 stream()->Add(", ");
3432 }
3433 stream()->Add("%i", i);
3434 }
3435 }
3436 stream()->Add("}\n");
3437}
3438
3439
3440void DispatchTable::Dump() {
3441 HeapStringAllocator alloc;
3442 StringStream stream(&alloc);
3443 DispatchTableDumper dumper(&stream);
3444 tree()->ForEach(&dumper);
3445 OS::PrintError("%s", *stream.ToCString());
3446}
3447
3448
3449void RegExpEngine::DotPrint(const char* label,
3450 RegExpNode* node,
3451 bool ignore_case) {
3452 DotPrinter printer(ignore_case);
3453 printer.PrintNode(label, node);
3454}
3455
3456
3457#endif // DEBUG
3458
3459
3460// -------------------------------------------------------------------
3461// Tree to graph conversion
3462
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003463static const int kSpaceRangeCount = 20;
3464static const int kSpaceRangeAsciiCount = 4;
3465static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3466 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3467 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3468
3469static const int kWordRangeCount = 8;
3470static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3471 '_', 'a', 'z' };
3472
3473static const int kDigitRangeCount = 2;
3474static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3475
3476static const int kLineTerminatorRangeCount = 6;
3477static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3478 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003479
3480RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003481 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003482 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3483 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003484 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003485}
3486
3487
3488RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003489 RegExpNode* on_success) {
3490 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003491}
3492
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003493static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3494 const uc16* special_class,
3495 int length) {
3496 ASSERT(ranges->length() != 0);
3497 ASSERT(length != 0);
3498 ASSERT(special_class[0] != 0);
3499 if (ranges->length() != (length >> 1) + 1) {
3500 return false;
3501 }
3502 CharacterRange range = ranges->at(0);
3503 if (range.from() != 0) {
3504 return false;
3505 }
3506 for (int i = 0; i < length; i += 2) {
3507 if (special_class[i] != (range.to() + 1)) {
3508 return false;
3509 }
3510 range = ranges->at((i >> 1) + 1);
3511 if (special_class[i+1] != range.from() - 1) {
3512 return false;
3513 }
3514 }
3515 if (range.to() != 0xffff) {
3516 return false;
3517 }
3518 return true;
3519}
3520
3521
3522static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3523 const uc16* special_class,
3524 int length) {
3525 if (ranges->length() * 2 != length) {
3526 return false;
3527 }
3528 for (int i = 0; i < length; i += 2) {
3529 CharacterRange range = ranges->at(i >> 1);
3530 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3531 return false;
3532 }
3533 }
3534 return true;
3535}
3536
3537
3538bool RegExpCharacterClass::is_standard() {
3539 // TODO(lrn): Remove need for this function, by not throwing away information
3540 // along the way.
3541 if (is_negated_) {
3542 return false;
3543 }
3544 if (set_.is_standard()) {
3545 return true;
3546 }
3547 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3548 set_.set_standard_set_type('s');
3549 return true;
3550 }
3551 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3552 set_.set_standard_set_type('S');
3553 return true;
3554 }
3555 if (CompareInverseRanges(set_.ranges(),
3556 kLineTerminatorRanges,
3557 kLineTerminatorRangeCount)) {
3558 set_.set_standard_set_type('.');
3559 return true;
3560 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003561 if (CompareRanges(set_.ranges(),
3562 kLineTerminatorRanges,
3563 kLineTerminatorRangeCount)) {
3564 set_.set_standard_set_type('n');
3565 return true;
3566 }
3567 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3568 set_.set_standard_set_type('w');
3569 return true;
3570 }
3571 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3572 set_.set_standard_set_type('W');
3573 return true;
3574 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003575 return false;
3576}
3577
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003578
3579RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003580 RegExpNode* on_success) {
3581 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003582}
3583
3584
3585RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003586 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003587 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3588 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003589 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003590 for (int i = 0; i < length; i++) {
3591 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003592 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003593 result->AddAlternative(alternative);
3594 }
3595 return result;
3596}
3597
3598
3599RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003600 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003601 return ToNode(min(),
3602 max(),
3603 is_greedy(),
3604 body(),
3605 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003606 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003607}
3608
3609
3610RegExpNode* RegExpQuantifier::ToNode(int min,
3611 int max,
3612 bool is_greedy,
3613 RegExpTree* body,
3614 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003615 RegExpNode* on_success,
3616 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003617 // x{f, t} becomes this:
3618 //
3619 // (r++)<-.
3620 // | `
3621 // | (x)
3622 // v ^
3623 // (r=0)-->(?)---/ [if r < t]
3624 // |
3625 // [if r >= f] \----> ...
3626 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003627
3628 // 15.10.2.5 RepeatMatcher algorithm.
3629 // The parser has already eliminated the case where max is 0. In the case
3630 // where max_match is zero the parser has removed the quantifier if min was
3631 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3632
3633 // If we know that we cannot match zero length then things are a little
3634 // simpler since we don't need to make the special zero length match check
3635 // from step 2.1. If the min and max are small we can unroll a little in
3636 // this case.
3637 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3638 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3639 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003640 bool body_can_be_empty = (body->min_match() == 0);
3641 int body_start_reg = RegExpCompiler::kNoRegister;
3642 Interval capture_registers = body->CaptureRegisters();
3643 bool needs_capture_clearing = !capture_registers.is_empty();
3644 if (body_can_be_empty) {
3645 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003646 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003647 // Only unroll if there are no captures and the body can't be
3648 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003649 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3650 int new_max = (max == kInfinity) ? max : max - min;
3651 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003652 RegExpNode* answer = ToNode(
3653 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003654 // Unroll the forced matches from 0 to min. This can cause chains of
3655 // TextNodes (which the parser does not generate). These should be
3656 // combined if it turns out they hinder good code generation.
3657 for (int i = 0; i < min; i++) {
3658 answer = body->ToNode(compiler, answer);
3659 }
3660 return answer;
3661 }
3662 if (max <= kMaxUnrolledMaxMatches) {
3663 ASSERT(min == 0);
3664 // Unroll the optional matches up to max.
3665 RegExpNode* answer = on_success;
3666 for (int i = 0; i < max; i++) {
3667 ChoiceNode* alternation = new ChoiceNode(2);
3668 if (is_greedy) {
3669 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3670 answer)));
3671 alternation->AddAlternative(GuardedAlternative(on_success));
3672 } else {
3673 alternation->AddAlternative(GuardedAlternative(on_success));
3674 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3675 answer)));
3676 }
3677 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003678 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003679 }
3680 return answer;
3681 }
3682 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003683 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003684 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003685 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003686 int reg_ctr = needs_counter
3687 ? compiler->AllocateRegister()
3688 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003689 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003690 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003691 RegExpNode* loop_return = needs_counter
3692 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3693 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003694 if (body_can_be_empty) {
3695 // If the body can be empty we need to check if it was and then
3696 // backtrack.
3697 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3698 reg_ctr,
3699 min,
3700 loop_return);
3701 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003702 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003703 if (body_can_be_empty) {
3704 // If the body can be empty we need to store the start position
3705 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003706 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003707 }
3708 if (needs_capture_clearing) {
3709 // Before entering the body of this loop we need to clear captures.
3710 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3711 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003712 GuardedAlternative body_alt(body_node);
3713 if (has_max) {
3714 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3715 body_alt.AddGuard(body_guard);
3716 }
3717 GuardedAlternative rest_alt(on_success);
3718 if (has_min) {
3719 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3720 rest_alt.AddGuard(rest_guard);
3721 }
3722 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003723 center->AddLoopAlternative(body_alt);
3724 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003725 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003726 center->AddContinueAlternative(rest_alt);
3727 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003728 }
3729 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003730 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003731 } else {
3732 return center;
3733 }
3734}
3735
3736
3737RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003738 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003739 NodeInfo info;
3740 switch (type()) {
3741 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003742 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003743 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003744 return AssertionNode::AtStart(on_success);
3745 case BOUNDARY:
3746 return AssertionNode::AtBoundary(on_success);
3747 case NON_BOUNDARY:
3748 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003749 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003750 return AssertionNode::AtEnd(on_success);
3751 case END_OF_LINE: {
3752 // Compile $ in multiline regexps as an alternation with a positive
3753 // lookahead in one side and an end-of-input on the other side.
3754 // We need two registers for the lookahead.
3755 int stack_pointer_register = compiler->AllocateRegister();
3756 int position_register = compiler->AllocateRegister();
3757 // The ChoiceNode to distinguish between a newline and end-of-input.
3758 ChoiceNode* result = new ChoiceNode(2);
3759 // Create a newline atom.
3760 ZoneList<CharacterRange>* newline_ranges =
3761 new ZoneList<CharacterRange>(3);
3762 CharacterRange::AddClassEscape('n', newline_ranges);
3763 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3764 TextNode* newline_matcher = new TextNode(
3765 newline_atom,
3766 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3767 position_register,
3768 0, // No captures inside.
3769 -1, // Ignored if no captures.
3770 on_success));
3771 // Create an end-of-input matcher.
3772 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3773 stack_pointer_register,
3774 position_register,
3775 newline_matcher);
3776 // Add the two alternatives to the ChoiceNode.
3777 GuardedAlternative eol_alternative(end_of_line);
3778 result->AddAlternative(eol_alternative);
3779 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3780 result->AddAlternative(end_alternative);
3781 return result;
3782 }
3783 default:
3784 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003785 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003786 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003787}
3788
3789
3790RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003791 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003792 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3793 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003794 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003795}
3796
3797
3798RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003799 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003800 return on_success;
3801}
3802
3803
3804RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003805 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003806 int stack_pointer_register = compiler->AllocateRegister();
3807 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003808
3809 const int registers_per_capture = 2;
3810 const int register_of_first_capture = 2;
3811 int register_count = capture_count_ * registers_per_capture;
3812 int register_start =
3813 register_of_first_capture + capture_from_ * registers_per_capture;
3814
ager@chromium.org8bb60582008-12-11 12:02:20 +00003815 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003816 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003817 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003818 stack_pointer_register,
3819 position_register,
3820 body()->ToNode(
3821 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003822 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3823 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003824 register_count,
3825 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003826 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003827 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003828 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003829 // We use a ChoiceNode for a negative lookahead because it has most of
3830 // the characteristics we need. It has the body of the lookahead as its
3831 // first alternative and the expression after the lookahead of the second
3832 // alternative. If the first alternative succeeds then the
3833 // NegativeSubmatchSuccess will unwind the stack including everything the
3834 // choice node set up and backtrack. If the first alternative fails then
3835 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003836 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3837 // ChoiceNode that knows to ignore the first exit when calculating quick
3838 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003839 GuardedAlternative body_alt(
3840 body()->ToNode(
3841 compiler,
3842 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003843 position_register,
3844 register_count,
3845 register_start)));
3846 ChoiceNode* choice_node =
3847 new NegativeLookaheadChoiceNode(body_alt,
3848 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003849 return ActionNode::BeginSubmatch(stack_pointer_register,
3850 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003851 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003852 }
3853}
3854
3855
3856RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003857 RegExpNode* on_success) {
3858 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003859}
3860
3861
3862RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3863 int index,
3864 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003865 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003866 int start_reg = RegExpCapture::StartRegister(index);
3867 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003868 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003869 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003870 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003871}
3872
3873
3874RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003875 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003876 ZoneList<RegExpTree*>* children = nodes();
3877 RegExpNode* current = on_success;
3878 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003879 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003880 }
3881 return current;
3882}
3883
3884
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003885static void AddClass(const uc16* elmv,
3886 int elmc,
3887 ZoneList<CharacterRange>* ranges) {
3888 for (int i = 0; i < elmc; i += 2) {
3889 ASSERT(elmv[i] <= elmv[i + 1]);
3890 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3891 }
3892}
3893
3894
3895static void AddClassNegated(const uc16 *elmv,
3896 int elmc,
3897 ZoneList<CharacterRange>* ranges) {
3898 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003899 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003900 uc16 last = 0x0000;
3901 for (int i = 0; i < elmc; i += 2) {
3902 ASSERT(last <= elmv[i] - 1);
3903 ASSERT(elmv[i] <= elmv[i + 1]);
3904 ranges->Add(CharacterRange(last, elmv[i] - 1));
3905 last = elmv[i + 1] + 1;
3906 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003907 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003908}
3909
3910
3911void CharacterRange::AddClassEscape(uc16 type,
3912 ZoneList<CharacterRange>* ranges) {
3913 switch (type) {
3914 case 's':
3915 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3916 break;
3917 case 'S':
3918 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3919 break;
3920 case 'w':
3921 AddClass(kWordRanges, kWordRangeCount, ranges);
3922 break;
3923 case 'W':
3924 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3925 break;
3926 case 'd':
3927 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3928 break;
3929 case 'D':
3930 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3931 break;
3932 case '.':
3933 AddClassNegated(kLineTerminatorRanges,
3934 kLineTerminatorRangeCount,
3935 ranges);
3936 break;
3937 // This is not a character range as defined by the spec but a
3938 // convenient shorthand for a character class that matches any
3939 // character.
3940 case '*':
3941 ranges->Add(CharacterRange::Everything());
3942 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003943 // This is the set of characters matched by the $ and ^ symbols
3944 // in multiline mode.
3945 case 'n':
3946 AddClass(kLineTerminatorRanges,
3947 kLineTerminatorRangeCount,
3948 ranges);
3949 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003950 default:
3951 UNREACHABLE();
3952 }
3953}
3954
3955
3956Vector<const uc16> CharacterRange::GetWordBounds() {
3957 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3958}
3959
3960
3961class CharacterRangeSplitter {
3962 public:
3963 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3964 ZoneList<CharacterRange>** excluded)
3965 : included_(included),
3966 excluded_(excluded) { }
3967 void Call(uc16 from, DispatchTable::Entry entry);
3968
3969 static const int kInBase = 0;
3970 static const int kInOverlay = 1;
3971
3972 private:
3973 ZoneList<CharacterRange>** included_;
3974 ZoneList<CharacterRange>** excluded_;
3975};
3976
3977
3978void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3979 if (!entry.out_set()->Get(kInBase)) return;
3980 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3981 ? included_
3982 : excluded_;
3983 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3984 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3985}
3986
3987
3988void CharacterRange::Split(ZoneList<CharacterRange>* base,
3989 Vector<const uc16> overlay,
3990 ZoneList<CharacterRange>** included,
3991 ZoneList<CharacterRange>** excluded) {
3992 ASSERT_EQ(NULL, *included);
3993 ASSERT_EQ(NULL, *excluded);
3994 DispatchTable table;
3995 for (int i = 0; i < base->length(); i++)
3996 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3997 for (int i = 0; i < overlay.length(); i += 2) {
3998 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
3999 CharacterRangeSplitter::kInOverlay);
4000 }
4001 CharacterRangeSplitter callback(included, excluded);
4002 table.ForEach(&callback);
4003}
4004
4005
ager@chromium.org38e4c712009-11-11 09:11:58 +00004006static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4007 int bottom,
4008 int top);
4009
4010
4011void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4012 bool is_ascii) {
4013 uc16 bottom = from();
4014 uc16 top = to();
4015 if (is_ascii) {
4016 if (bottom > String::kMaxAsciiCharCode) return;
4017 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4018 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004019 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004020 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004021 // If this is a singleton we just expand the one character.
ager@chromium.org38e4c712009-11-11 09:11:58 +00004022 int length = uncanonicalize.get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004023 for (int i = 0; i < length; i++) {
4024 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004025 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004026 ranges->Add(CharacterRange::Singleton(chars[i]));
4027 }
4028 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004029 } else if (bottom <= kRangeCanonicalizeMax &&
4030 top <= kRangeCanonicalizeMax) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004031 // If this is a range we expand the characters block by block,
4032 // expanding contiguous subranges (blocks) one at a time.
4033 // The approach is as follows. For a given start character we
4034 // look up the block that contains it, for instance 'a' if the
4035 // start character is 'c'. A block is characterized by the property
4036 // that all characters uncanonicalize in the same way as the first
4037 // element, except that each entry in the result is incremented
4038 // by the distance from the first element. So a-z is a block
4039 // because 'a' uncanonicalizes to ['a', 'A'] and the k'th letter
4040 // uncanonicalizes to ['a' + k, 'A' + k].
4041 // Once we've found the start point we look up its uncanonicalization
4042 // and produce a range for each element. For instance for [c-f]
4043 // we look up ['a', 'A'] and produce [c-f] and [C-F]. We then only
4044 // add a range if it is not already contained in the input, so [c-f]
4045 // will be skipped but [C-F] will be added. If this range is not
4046 // completely contained in a block we do this for all the blocks
4047 // covered by the range.
4048 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004049 // First, look up the block that contains the 'bottom' character.
4050 int length = canonrange.get(bottom, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004051 if (length == 0) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004052 range[0] = bottom;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004053 } else {
4054 ASSERT_EQ(1, length);
4055 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004056 int pos = bottom;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004057 // The start of the current block. Note that except for the first
4058 // iteration 'start' is always equal to 'pos'.
4059 int start;
4060 // If it is not the start point of a block the entry contains the
4061 // offset of the character from the start point.
4062 if ((range[0] & kStartMarker) == 0) {
4063 start = pos - range[0];
4064 } else {
4065 start = pos;
4066 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004067 // Then we add the ranges one at a time, incrementing the current
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004068 // position to be after the last block each time. The position
4069 // always points to the start of a block.
ager@chromium.org38e4c712009-11-11 09:11:58 +00004070 while (pos < top) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004071 length = canonrange.get(start, '\0', range);
4072 if (length == 0) {
4073 range[0] = start;
4074 } else {
4075 ASSERT_EQ(1, length);
4076 }
4077 ASSERT((range[0] & kStartMarker) != 0);
4078 // The start point of a block contains the distance to the end
4079 // of the range.
4080 int block_end = start + (range[0] & kPayloadMask) - 1;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004081 int end = (block_end > top) ? top : block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004082 length = uncanonicalize.get(start, '\0', range);
4083 for (int i = 0; i < length; i++) {
4084 uc32 c = range[i];
4085 uc16 range_from = c + (pos - start);
4086 uc16 range_to = c + (end - start);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004087 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004088 ranges->Add(CharacterRange(range_from, range_to));
4089 }
4090 }
4091 start = pos = block_end + 1;
4092 }
4093 } else {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004094 // Unibrow ranges don't work for high characters due to the "2^11 bug".
4095 // Therefore we do something dumber for these ranges.
4096 AddUncanonicals(ranges, bottom, top);
4097 }
4098}
4099
4100
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004101bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4102 ASSERT_NOT_NULL(ranges);
4103 int n = ranges->length();
4104 if (n <= 1) return true;
4105 int max = ranges->at(0).to();
4106 for (int i = 1; i < n; i++) {
4107 CharacterRange next_range = ranges->at(i);
4108 if (next_range.from() <= max + 1) return false;
4109 max = next_range.to();
4110 }
4111 return true;
4112}
4113
4114SetRelation CharacterRange::WordCharacterRelation(
4115 ZoneList<CharacterRange>* range) {
4116 ASSERT(IsCanonical(range));
4117 int i = 0; // Word character range index.
4118 int j = 0; // Argument range index.
4119 ASSERT_NE(0, kWordRangeCount);
4120 SetRelation result;
4121 if (range->length() == 0) {
4122 result.SetElementsInSecondSet();
4123 return result;
4124 }
4125 CharacterRange argument_range = range->at(0);
4126 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4127 while (i < kWordRangeCount && j < range->length()) {
4128 // Check the two ranges for the five cases:
4129 // - no overlap.
4130 // - partial overlap (there are elements in both ranges that isn't
4131 // in the other, and there are also elements that are in both).
4132 // - argument range entirely inside word range.
4133 // - word range entirely inside argument range.
4134 // - ranges are completely equal.
4135
4136 // First check for no overlap. The earlier range is not in the other set.
4137 if (argument_range.from() > word_range.to()) {
4138 // Ranges are disjoint. The earlier word range contains elements that
4139 // cannot be in the argument set.
4140 result.SetElementsInSecondSet();
4141 } else if (word_range.from() > argument_range.to()) {
4142 // Ranges are disjoint. The earlier argument range contains elements that
4143 // cannot be in the word set.
4144 result.SetElementsInFirstSet();
4145 } else if (word_range.from() <= argument_range.from() &&
4146 word_range.to() >= argument_range.from()) {
4147 result.SetElementsInBothSets();
4148 // argument range completely inside word range.
4149 if (word_range.from() < argument_range.from() ||
4150 word_range.to() > argument_range.from()) {
4151 result.SetElementsInSecondSet();
4152 }
4153 } else if (word_range.from() >= argument_range.from() &&
4154 word_range.to() <= argument_range.from()) {
4155 result.SetElementsInBothSets();
4156 result.SetElementsInFirstSet();
4157 } else {
4158 // There is overlap, and neither is a subrange of the other
4159 result.SetElementsInFirstSet();
4160 result.SetElementsInSecondSet();
4161 result.SetElementsInBothSets();
4162 }
4163 if (result.NonTrivialIntersection()) {
4164 // The result is as (im)precise as we can possibly make it.
4165 return result;
4166 }
4167 // Progress the range(s) with minimal to-character.
4168 uc16 word_to = word_range.to();
4169 uc16 argument_to = argument_range.to();
4170 if (argument_to <= word_to) {
4171 j++;
4172 if (j < range->length()) {
4173 argument_range = range->at(j);
4174 }
4175 }
4176 if (word_to <= argument_to) {
4177 i += 2;
4178 if (i < kWordRangeCount) {
4179 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4180 }
4181 }
4182 }
4183 // Check if anything wasn't compared in the loop.
4184 if (i < kWordRangeCount) {
4185 // word range contains something not in argument range.
4186 result.SetElementsInSecondSet();
4187 } else if (j < range->length()) {
4188 // Argument range contains something not in word range.
4189 result.SetElementsInFirstSet();
4190 }
4191
4192 return result;
4193}
4194
4195
ager@chromium.org38e4c712009-11-11 09:11:58 +00004196static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4197 int bottom,
4198 int top) {
4199 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4200 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4201 // this table is correct.
4202 // 0x0600 - 0x0fff
4203 // 0x1100 - 0x1cff
4204 // 0x2000 - 0x20ff
4205 // 0x2200 - 0x23ff
4206 // 0x2500 - 0x2bff
4207 // 0x2e00 - 0xa5ff
4208 // 0xa800 - 0xfaff
4209 // 0xfc00 - 0xfeff
4210 const int boundary_count = 18;
4211 // The ASCII boundary and the kRangeCanonicalizeMax boundary are also in this
4212 // array. This is to split up big ranges and not because they actually denote
4213 // a case-mapping-free-zone.
4214 ASSERT(CharacterRange::kRangeCanonicalizeMax < 0x600);
4215 const int kFirstRealCaselessZoneIndex = 2;
4216 int boundaries[] = {0x80, CharacterRange::kRangeCanonicalizeMax,
4217 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4218 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4219
4220 // Special ASCII rule from spec can save us some work here.
4221 if (bottom == 0x80 && top == 0xffff) return;
4222
4223 // We have optimized support for this range.
4224 if (top <= CharacterRange::kRangeCanonicalizeMax) {
4225 CharacterRange range(bottom, top);
4226 range.AddCaseEquivalents(ranges, false);
4227 return;
4228 }
4229
4230 // Split up very large ranges. This helps remove ranges where there are no
4231 // case mappings.
4232 for (int i = 0; i < boundary_count; i++) {
4233 if (bottom < boundaries[i] && top >= boundaries[i]) {
4234 AddUncanonicals(ranges, bottom, boundaries[i] - 1);
4235 AddUncanonicals(ranges, boundaries[i], top);
4236 return;
4237 }
4238 }
4239
4240 // If we are completely in a zone with no case mappings then we are done.
4241 // We start at 2 so as not to except the ASCII range from mappings.
4242 for (int i = kFirstRealCaselessZoneIndex; i < boundary_count; i += 2) {
4243 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4244#ifdef DEBUG
4245 for (int j = bottom; j <= top; j++) {
4246 unsigned current_char = j;
4247 int length = uncanonicalize.get(current_char, '\0', chars);
4248 for (int k = 0; k < length; k++) {
4249 ASSERT(chars[k] == current_char);
4250 }
4251 }
4252#endif
4253 return;
4254 }
4255 }
4256
4257 // Step through the range finding equivalent characters.
4258 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4259 for (int i = bottom; i <= top; i++) {
4260 int length = uncanonicalize.get(i, '\0', chars);
4261 for (int j = 0; j < length; j++) {
4262 uc32 chr = chars[j];
4263 if (chr != i && (chr < bottom || chr > top)) {
4264 characters->Add(chr);
4265 }
4266 }
4267 }
4268
4269 // Step through the equivalent characters finding simple ranges and
4270 // adding ranges to the character class.
4271 if (characters->length() > 0) {
4272 int new_from = characters->at(0);
4273 int new_to = new_from;
4274 for (int i = 1; i < characters->length(); i++) {
4275 int chr = characters->at(i);
4276 if (chr == new_to + 1) {
4277 new_to++;
4278 } else {
4279 if (new_to == new_from) {
4280 ranges->Add(CharacterRange::Singleton(new_from));
4281 } else {
4282 ranges->Add(CharacterRange(new_from, new_to));
4283 }
4284 new_from = new_to = chr;
4285 }
4286 }
4287 if (new_to == new_from) {
4288 ranges->Add(CharacterRange::Singleton(new_from));
4289 } else {
4290 ranges->Add(CharacterRange(new_from, new_to));
4291 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004292 }
4293}
4294
4295
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004296ZoneList<CharacterRange>* CharacterSet::ranges() {
4297 if (ranges_ == NULL) {
4298 ranges_ = new ZoneList<CharacterRange>(2);
4299 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4300 }
4301 return ranges_;
4302}
4303
4304
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004305// Move a number of elements in a zonelist to another position
4306// in the same list. Handles overlapping source and target areas.
4307static void MoveRanges(ZoneList<CharacterRange>* list,
4308 int from,
4309 int to,
4310 int count) {
4311 // Ranges are potentially overlapping.
4312 if (from < to) {
4313 for (int i = count - 1; i >= 0; i--) {
4314 list->at(to + i) = list->at(from + i);
4315 }
4316 } else {
4317 for (int i = 0; i < count; i++) {
4318 list->at(to + i) = list->at(from + i);
4319 }
4320 }
4321}
4322
4323
4324static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4325 int count,
4326 CharacterRange insert) {
4327 // Inserts a range into list[0..count[, which must be sorted
4328 // by from value and non-overlapping and non-adjacent, using at most
4329 // list[0..count] for the result. Returns the number of resulting
4330 // canonicalized ranges. Inserting a range may collapse existing ranges into
4331 // fewer ranges, so the return value can be anything in the range 1..count+1.
4332 uc16 from = insert.from();
4333 uc16 to = insert.to();
4334 int start_pos = 0;
4335 int end_pos = count;
4336 for (int i = count - 1; i >= 0; i--) {
4337 CharacterRange current = list->at(i);
4338 if (current.from() > to + 1) {
4339 end_pos = i;
4340 } else if (current.to() + 1 < from) {
4341 start_pos = i + 1;
4342 break;
4343 }
4344 }
4345
4346 // Inserted range overlaps, or is adjacent to, ranges at positions
4347 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4348 // not affected by the insertion.
4349 // If start_pos == end_pos, the range must be inserted before start_pos.
4350 // if start_pos < end_pos, the entire range from start_pos to end_pos
4351 // must be merged with the insert range.
4352
4353 if (start_pos == end_pos) {
4354 // Insert between existing ranges at position start_pos.
4355 if (start_pos < count) {
4356 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4357 }
4358 list->at(start_pos) = insert;
4359 return count + 1;
4360 }
4361 if (start_pos + 1 == end_pos) {
4362 // Replace single existing range at position start_pos.
4363 CharacterRange to_replace = list->at(start_pos);
4364 int new_from = Min(to_replace.from(), from);
4365 int new_to = Max(to_replace.to(), to);
4366 list->at(start_pos) = CharacterRange(new_from, new_to);
4367 return count;
4368 }
4369 // Replace a number of existing ranges from start_pos to end_pos - 1.
4370 // Move the remaining ranges down.
4371
4372 int new_from = Min(list->at(start_pos).from(), from);
4373 int new_to = Max(list->at(end_pos - 1).to(), to);
4374 if (end_pos < count) {
4375 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4376 }
4377 list->at(start_pos) = CharacterRange(new_from, new_to);
4378 return count - (end_pos - start_pos) + 1;
4379}
4380
4381
4382void CharacterSet::Canonicalize() {
4383 // Special/default classes are always considered canonical. The result
4384 // of calling ranges() will be sorted.
4385 if (ranges_ == NULL) return;
4386 CharacterRange::Canonicalize(ranges_);
4387}
4388
4389
4390void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4391 if (character_ranges->length() <= 1) return;
4392 // Check whether ranges are already canonical (increasing, non-overlapping,
4393 // non-adjacent).
4394 int n = character_ranges->length();
4395 int max = character_ranges->at(0).to();
4396 int i = 1;
4397 while (i < n) {
4398 CharacterRange current = character_ranges->at(i);
4399 if (current.from() <= max + 1) {
4400 break;
4401 }
4402 max = current.to();
4403 i++;
4404 }
4405 // Canonical until the i'th range. If that's all of them, we are done.
4406 if (i == n) return;
4407
4408 // The ranges at index i and forward are not canonicalized. Make them so by
4409 // doing the equivalent of insertion sort (inserting each into the previous
4410 // list, in order).
4411 // Notice that inserting a range can reduce the number of ranges in the
4412 // result due to combining of adjacent and overlapping ranges.
4413 int read = i; // Range to insert.
4414 int num_canonical = i; // Length of canonicalized part of list.
4415 do {
4416 num_canonical = InsertRangeInCanonicalList(character_ranges,
4417 num_canonical,
4418 character_ranges->at(read));
4419 read++;
4420 } while (read < n);
4421 character_ranges->Rewind(num_canonical);
4422
4423 ASSERT(CharacterRange::IsCanonical(character_ranges));
4424}
4425
4426
4427// Utility function for CharacterRange::Merge. Adds a range at the end of
4428// a canonicalized range list, if necessary merging the range with the last
4429// range of the list.
4430static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4431 if (set == NULL) return;
4432 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4433 int n = set->length();
4434 if (n > 0) {
4435 CharacterRange lastRange = set->at(n - 1);
4436 if (lastRange.to() == range.from() - 1) {
4437 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4438 return;
4439 }
4440 }
4441 set->Add(range);
4442}
4443
4444
4445static void AddRangeToSelectedSet(int selector,
4446 ZoneList<CharacterRange>* first_set,
4447 ZoneList<CharacterRange>* second_set,
4448 ZoneList<CharacterRange>* intersection_set,
4449 CharacterRange range) {
4450 switch (selector) {
4451 case kInsideFirst:
4452 AddRangeToSet(first_set, range);
4453 break;
4454 case kInsideSecond:
4455 AddRangeToSet(second_set, range);
4456 break;
4457 case kInsideBoth:
4458 AddRangeToSet(intersection_set, range);
4459 break;
4460 }
4461}
4462
4463
4464
4465void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4466 ZoneList<CharacterRange>* second_set,
4467 ZoneList<CharacterRange>* first_set_only_out,
4468 ZoneList<CharacterRange>* second_set_only_out,
4469 ZoneList<CharacterRange>* both_sets_out) {
4470 // Inputs are canonicalized.
4471 ASSERT(CharacterRange::IsCanonical(first_set));
4472 ASSERT(CharacterRange::IsCanonical(second_set));
4473 // Outputs are empty, if applicable.
4474 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4475 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4476 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4477
4478 // Merge sets by iterating through the lists in order of lowest "from" value,
4479 // and putting intervals into one of three sets.
4480
4481 if (first_set->length() == 0) {
4482 second_set_only_out->AddAll(*second_set);
4483 return;
4484 }
4485 if (second_set->length() == 0) {
4486 first_set_only_out->AddAll(*first_set);
4487 return;
4488 }
4489 // Indices into input lists.
4490 int i1 = 0;
4491 int i2 = 0;
4492 // Cache length of input lists.
4493 int n1 = first_set->length();
4494 int n2 = second_set->length();
4495 // Current range. May be invalid if state is kInsideNone.
4496 int from = 0;
4497 int to = -1;
4498 // Where current range comes from.
4499 int state = kInsideNone;
4500
4501 while (i1 < n1 || i2 < n2) {
4502 CharacterRange next_range;
4503 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004504 if (i2 == n2 ||
4505 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4506 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004507 next_range = first_set->at(i1++);
4508 range_source = kInsideFirst;
4509 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004510 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004511 next_range = second_set->at(i2++);
4512 range_source = kInsideSecond;
4513 }
4514 if (to < next_range.from()) {
4515 // Ranges disjoint: |current| |next|
4516 AddRangeToSelectedSet(state,
4517 first_set_only_out,
4518 second_set_only_out,
4519 both_sets_out,
4520 CharacterRange(from, to));
4521 from = next_range.from();
4522 to = next_range.to();
4523 state = range_source;
4524 } else {
4525 if (from < next_range.from()) {
4526 AddRangeToSelectedSet(state,
4527 first_set_only_out,
4528 second_set_only_out,
4529 both_sets_out,
4530 CharacterRange(from, next_range.from()-1));
4531 }
4532 if (to < next_range.to()) {
4533 // Ranges overlap: |current|
4534 // |next|
4535 AddRangeToSelectedSet(state | range_source,
4536 first_set_only_out,
4537 second_set_only_out,
4538 both_sets_out,
4539 CharacterRange(next_range.from(), to));
4540 from = to + 1;
4541 to = next_range.to();
4542 state = range_source;
4543 } else {
4544 // Range included: |current| , possibly ending at same character.
4545 // |next|
4546 AddRangeToSelectedSet(
4547 state | range_source,
4548 first_set_only_out,
4549 second_set_only_out,
4550 both_sets_out,
4551 CharacterRange(next_range.from(), next_range.to()));
4552 from = next_range.to() + 1;
4553 // If ranges end at same character, both ranges are consumed completely.
4554 if (next_range.to() == to) state = kInsideNone;
4555 }
4556 }
4557 }
4558 AddRangeToSelectedSet(state,
4559 first_set_only_out,
4560 second_set_only_out,
4561 both_sets_out,
4562 CharacterRange(from, to));
4563}
4564
4565
4566void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4567 ZoneList<CharacterRange>* negated_ranges) {
4568 ASSERT(CharacterRange::IsCanonical(ranges));
4569 ASSERT_EQ(0, negated_ranges->length());
4570 int range_count = ranges->length();
4571 uc16 from = 0;
4572 int i = 0;
4573 if (range_count > 0 && ranges->at(0).from() == 0) {
4574 from = ranges->at(0).to();
4575 i = 1;
4576 }
4577 while (i < range_count) {
4578 CharacterRange range = ranges->at(i);
4579 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4580 from = range.to();
4581 i++;
4582 }
4583 if (from < String::kMaxUC16CharCode) {
4584 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4585 }
4586}
4587
4588
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004589
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004590// -------------------------------------------------------------------
4591// Interest propagation
4592
4593
4594RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4595 for (int i = 0; i < siblings_.length(); i++) {
4596 RegExpNode* sibling = siblings_.Get(i);
4597 if (sibling->info()->Matches(info))
4598 return sibling;
4599 }
4600 return NULL;
4601}
4602
4603
4604RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4605 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004606 siblings_.Ensure(this);
4607 RegExpNode* result = TryGetSibling(info);
4608 if (result != NULL) return result;
4609 result = this->Clone();
4610 NodeInfo* new_info = result->info();
4611 new_info->ResetCompilationState();
4612 new_info->AddFromPreceding(info);
4613 AddSibling(result);
4614 *cloned = true;
4615 return result;
4616}
4617
4618
4619template <class C>
4620static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4621 NodeInfo full_info(*node->info());
4622 full_info.AddFromPreceding(info);
4623 bool cloned = false;
4624 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4625}
4626
4627
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004628// -------------------------------------------------------------------
4629// Splay tree
4630
4631
4632OutSet* OutSet::Extend(unsigned value) {
4633 if (Get(value))
4634 return this;
4635 if (successors() != NULL) {
4636 for (int i = 0; i < successors()->length(); i++) {
4637 OutSet* successor = successors()->at(i);
4638 if (successor->Get(value))
4639 return successor;
4640 }
4641 } else {
4642 successors_ = new ZoneList<OutSet*>(2);
4643 }
4644 OutSet* result = new OutSet(first_, remaining_);
4645 result->Set(value);
4646 successors()->Add(result);
4647 return result;
4648}
4649
4650
4651void OutSet::Set(unsigned value) {
4652 if (value < kFirstLimit) {
4653 first_ |= (1 << value);
4654 } else {
4655 if (remaining_ == NULL)
4656 remaining_ = new ZoneList<unsigned>(1);
4657 if (remaining_->is_empty() || !remaining_->Contains(value))
4658 remaining_->Add(value);
4659 }
4660}
4661
4662
4663bool OutSet::Get(unsigned value) {
4664 if (value < kFirstLimit) {
4665 return (first_ & (1 << value)) != 0;
4666 } else if (remaining_ == NULL) {
4667 return false;
4668 } else {
4669 return remaining_->Contains(value);
4670 }
4671}
4672
4673
4674const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4675const DispatchTable::Entry DispatchTable::Config::kNoValue;
4676
4677
4678void DispatchTable::AddRange(CharacterRange full_range, int value) {
4679 CharacterRange current = full_range;
4680 if (tree()->is_empty()) {
4681 // If this is the first range we just insert into the table.
4682 ZoneSplayTree<Config>::Locator loc;
4683 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4684 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4685 return;
4686 }
4687 // First see if there is a range to the left of this one that
4688 // overlaps.
4689 ZoneSplayTree<Config>::Locator loc;
4690 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4691 Entry* entry = &loc.value();
4692 // If we've found a range that overlaps with this one, and it
4693 // starts strictly to the left of this one, we have to fix it
4694 // because the following code only handles ranges that start on
4695 // or after the start point of the range we're adding.
4696 if (entry->from() < current.from() && entry->to() >= current.from()) {
4697 // Snap the overlapping range in half around the start point of
4698 // the range we're adding.
4699 CharacterRange left(entry->from(), current.from() - 1);
4700 CharacterRange right(current.from(), entry->to());
4701 // The left part of the overlapping range doesn't overlap.
4702 // Truncate the whole entry to be just the left part.
4703 entry->set_to(left.to());
4704 // The right part is the one that overlaps. We add this part
4705 // to the map and let the next step deal with merging it with
4706 // the range we're adding.
4707 ZoneSplayTree<Config>::Locator loc;
4708 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4709 loc.set_value(Entry(right.from(),
4710 right.to(),
4711 entry->out_set()));
4712 }
4713 }
4714 while (current.is_valid()) {
4715 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4716 (loc.value().from() <= current.to()) &&
4717 (loc.value().to() >= current.from())) {
4718 Entry* entry = &loc.value();
4719 // We have overlap. If there is space between the start point of
4720 // the range we're adding and where the overlapping range starts
4721 // then we have to add a range covering just that space.
4722 if (current.from() < entry->from()) {
4723 ZoneSplayTree<Config>::Locator ins;
4724 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4725 ins.set_value(Entry(current.from(),
4726 entry->from() - 1,
4727 empty()->Extend(value)));
4728 current.set_from(entry->from());
4729 }
4730 ASSERT_EQ(current.from(), entry->from());
4731 // If the overlapping range extends beyond the one we want to add
4732 // we have to snap the right part off and add it separately.
4733 if (entry->to() > current.to()) {
4734 ZoneSplayTree<Config>::Locator ins;
4735 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4736 ins.set_value(Entry(current.to() + 1,
4737 entry->to(),
4738 entry->out_set()));
4739 entry->set_to(current.to());
4740 }
4741 ASSERT(entry->to() <= current.to());
4742 // The overlapping range is now completely contained by the range
4743 // we're adding so we can just update it and move the start point
4744 // of the range we're adding just past it.
4745 entry->AddValue(value);
4746 // Bail out if the last interval ended at 0xFFFF since otherwise
4747 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004748 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004749 break;
4750 ASSERT(entry->to() + 1 > current.from());
4751 current.set_from(entry->to() + 1);
4752 } else {
4753 // There is no overlap so we can just add the range
4754 ZoneSplayTree<Config>::Locator ins;
4755 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4756 ins.set_value(Entry(current.from(),
4757 current.to(),
4758 empty()->Extend(value)));
4759 break;
4760 }
4761 }
4762}
4763
4764
4765OutSet* DispatchTable::Get(uc16 value) {
4766 ZoneSplayTree<Config>::Locator loc;
4767 if (!tree()->FindGreatestLessThan(value, &loc))
4768 return empty();
4769 Entry* entry = &loc.value();
4770 if (value <= entry->to())
4771 return entry->out_set();
4772 else
4773 return empty();
4774}
4775
4776
4777// -------------------------------------------------------------------
4778// Analysis
4779
4780
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004781void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004782 StackLimitCheck check;
4783 if (check.HasOverflowed()) {
4784 fail("Stack overflow");
4785 return;
4786 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004787 if (that->info()->been_analyzed || that->info()->being_analyzed)
4788 return;
4789 that->info()->being_analyzed = true;
4790 that->Accept(this);
4791 that->info()->being_analyzed = false;
4792 that->info()->been_analyzed = true;
4793}
4794
4795
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004796void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004797 // nothing to do
4798}
4799
4800
ager@chromium.org8bb60582008-12-11 12:02:20 +00004801void TextNode::CalculateOffsets() {
4802 int element_count = elements()->length();
4803 // Set up the offsets of the elements relative to the start. This is a fixed
4804 // quantity since a TextNode can only contain fixed-width things.
4805 int cp_offset = 0;
4806 for (int i = 0; i < element_count; i++) {
4807 TextElement& elm = elements()->at(i);
4808 elm.cp_offset = cp_offset;
4809 if (elm.type == TextElement::ATOM) {
4810 cp_offset += elm.data.u_atom->data().length();
4811 } else {
4812 cp_offset++;
4813 Vector<const uc16> quarks = elm.data.u_atom->data();
4814 }
4815 }
4816}
4817
4818
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004819void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004820 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004821 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004822 }
4823 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004824 if (!has_failed()) {
4825 that->CalculateOffsets();
4826 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004827}
4828
4829
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004830void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004831 RegExpNode* target = that->on_success();
4832 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004833 if (!has_failed()) {
4834 // If the next node is interested in what it follows then this node
4835 // has to be interested too so it can pass the information on.
4836 that->info()->AddFromFollowing(target->info());
4837 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004838}
4839
4840
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004841void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004842 NodeInfo* info = that->info();
4843 for (int i = 0; i < that->alternatives()->length(); i++) {
4844 RegExpNode* node = that->alternatives()->at(i).node();
4845 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004846 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004847 // Anything the following nodes need to know has to be known by
4848 // this node also, so it can pass it on.
4849 info->AddFromFollowing(node->info());
4850 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004851}
4852
4853
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004854void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4855 NodeInfo* info = that->info();
4856 for (int i = 0; i < that->alternatives()->length(); i++) {
4857 RegExpNode* node = that->alternatives()->at(i).node();
4858 if (node != that->loop_node()) {
4859 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004860 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004861 info->AddFromFollowing(node->info());
4862 }
4863 }
4864 // Check the loop last since it may need the value of this node
4865 // to get a correct result.
4866 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004867 if (!has_failed()) {
4868 info->AddFromFollowing(that->loop_node()->info());
4869 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004870}
4871
4872
4873void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004874 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004875}
4876
4877
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004878void Analysis::VisitAssertion(AssertionNode* that) {
4879 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004880 AssertionNode::AssertionNodeType type = that->type();
4881 if (type == AssertionNode::AT_BOUNDARY ||
4882 type == AssertionNode::AT_NON_BOUNDARY) {
4883 // Check if the following character is known to be a word character
4884 // or known to not be a word character.
4885 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4886
4887 CharacterRange::Canonicalize(following_chars);
4888
4889 SetRelation word_relation =
4890 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004891 if (word_relation.Disjoint()) {
4892 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004893 // Following character is definitely *not* a word character.
4894 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004895 AssertionNode::AFTER_WORD_CHARACTER :
4896 AssertionNode::AFTER_NONWORD_CHARACTER;
4897 that->set_type(type);
4898 } else if (word_relation.ContainedIn()) {
4899 // Following character is definitely a word character.
4900 type = (type == AssertionNode::AT_BOUNDARY) ?
4901 AssertionNode::AFTER_NONWORD_CHARACTER :
4902 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004903 that->set_type(type);
4904 }
4905 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004906}
4907
4908
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004909ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4910 if (first_character_set_ == NULL) {
4911 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4912 // If we can't find an exact solution within the budget, we
4913 // set the value to the set of every character, i.e., all characters
4914 // are possible.
4915 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4916 all_set->Add(CharacterRange::Everything());
4917 first_character_set_ = all_set;
4918 }
4919 }
4920 return first_character_set_;
4921}
4922
4923
4924int RegExpNode::ComputeFirstCharacterSet(int budget) {
4925 // Default behavior is to not be able to determine the first character.
4926 return kComputeFirstCharacterSetFail;
4927}
4928
4929
4930int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
4931 budget--;
4932 if (budget >= 0) {
4933 // Find loop min-iteration. It's the value of the guarded choice node
4934 // with a GEQ guard, if any.
4935 int min_repetition = 0;
4936
4937 for (int i = 0; i <= 1; i++) {
4938 GuardedAlternative alternative = alternatives()->at(i);
4939 ZoneList<Guard*>* guards = alternative.guards();
4940 if (guards != NULL && guards->length() > 0) {
4941 Guard* guard = guards->at(0);
4942 if (guard->op() == Guard::GEQ) {
4943 min_repetition = guard->value();
4944 break;
4945 }
4946 }
4947 }
4948
4949 budget = loop_node()->ComputeFirstCharacterSet(budget);
4950 if (budget >= 0) {
4951 ZoneList<CharacterRange>* character_set =
4952 loop_node()->first_character_set();
4953 if (body_can_be_zero_length() || min_repetition == 0) {
4954 budget = continue_node()->ComputeFirstCharacterSet(budget);
4955 if (budget < 0) return budget;
4956 ZoneList<CharacterRange>* body_set =
4957 continue_node()->first_character_set();
4958 ZoneList<CharacterRange>* union_set =
4959 new ZoneList<CharacterRange>(Max(character_set->length(),
4960 body_set->length()));
4961 CharacterRange::Merge(character_set,
4962 body_set,
4963 union_set,
4964 union_set,
4965 union_set);
4966 character_set = union_set;
4967 }
4968 set_first_character_set(character_set);
4969 }
4970 }
4971 return budget;
4972}
4973
4974
4975int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
4976 budget--;
4977 if (budget >= 0) {
4978 GuardedAlternative successor = this->alternatives()->at(1);
4979 RegExpNode* successor_node = successor.node();
4980 budget = successor_node->ComputeFirstCharacterSet(budget);
4981 if (budget >= 0) {
4982 set_first_character_set(successor_node->first_character_set());
4983 }
4984 }
4985 return budget;
4986}
4987
4988
4989// The first character set of an EndNode is unknowable. Just use the
4990// default implementation that fails and returns all characters as possible.
4991
4992
4993int AssertionNode::ComputeFirstCharacterSet(int budget) {
4994 budget -= 1;
4995 if (budget >= 0) {
4996 switch (type_) {
4997 case AT_END: {
4998 set_first_character_set(new ZoneList<CharacterRange>(0));
4999 break;
5000 }
5001 case AT_START:
5002 case AT_BOUNDARY:
5003 case AT_NON_BOUNDARY:
5004 case AFTER_NEWLINE:
5005 case AFTER_NONWORD_CHARACTER:
5006 case AFTER_WORD_CHARACTER: {
5007 ASSERT_NOT_NULL(on_success());
5008 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005009 if (budget >= 0) {
5010 set_first_character_set(on_success()->first_character_set());
5011 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005012 break;
5013 }
5014 }
5015 }
5016 return budget;
5017}
5018
5019
5020int ActionNode::ComputeFirstCharacterSet(int budget) {
5021 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
5022 budget--;
5023 if (budget >= 0) {
5024 ASSERT_NOT_NULL(on_success());
5025 budget = on_success()->ComputeFirstCharacterSet(budget);
5026 if (budget >= 0) {
5027 set_first_character_set(on_success()->first_character_set());
5028 }
5029 }
5030 return budget;
5031}
5032
5033
5034int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5035 // We don't know anything about the first character of a backreference
5036 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005037 // The potential first characters are the first characters of the capture,
5038 // and the first characters of the on_success node, depending on whether the
5039 // capture can be empty and whether it is known to be participating or known
5040 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005041 return kComputeFirstCharacterSetFail;
5042}
5043
5044
5045int TextNode::ComputeFirstCharacterSet(int budget) {
5046 budget--;
5047 if (budget >= 0) {
5048 ASSERT_NE(0, elements()->length());
5049 TextElement text = elements()->at(0);
5050 if (text.type == TextElement::ATOM) {
5051 RegExpAtom* atom = text.data.u_atom;
5052 ASSERT_NE(0, atom->length());
5053 uc16 first_char = atom->data()[0];
5054 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5055 range->Add(CharacterRange(first_char, first_char));
5056 set_first_character_set(range);
5057 } else {
5058 ASSERT(text.type == TextElement::CHAR_CLASS);
5059 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005060 ZoneList<CharacterRange>* ranges = char_class->ranges();
5061 // TODO(lrn): Canonicalize ranges when they are created
5062 // instead of waiting until now.
5063 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005064 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005065 int length = ranges->length();
5066 int new_length = length + 1;
5067 if (length > 0) {
5068 if (ranges->at(0).from() == 0) new_length--;
5069 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5070 new_length--;
5071 }
5072 }
5073 ZoneList<CharacterRange>* negated_ranges =
5074 new ZoneList<CharacterRange>(new_length);
5075 CharacterRange::Negate(ranges, negated_ranges);
5076 set_first_character_set(negated_ranges);
5077 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005078 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005079 }
5080 }
5081 }
5082 return budget;
5083}
5084
5085
5086
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005087// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005088// Dispatch table construction
5089
5090
5091void DispatchTableConstructor::VisitEnd(EndNode* that) {
5092 AddRange(CharacterRange::Everything());
5093}
5094
5095
5096void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5097 node->set_being_calculated(true);
5098 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5099 for (int i = 0; i < alternatives->length(); i++) {
5100 set_choice_index(i);
5101 alternatives->at(i).node()->Accept(this);
5102 }
5103 node->set_being_calculated(false);
5104}
5105
5106
5107class AddDispatchRange {
5108 public:
5109 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5110 : constructor_(constructor) { }
5111 void Call(uc32 from, DispatchTable::Entry entry);
5112 private:
5113 DispatchTableConstructor* constructor_;
5114};
5115
5116
5117void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5118 CharacterRange range(from, entry.to());
5119 constructor_->AddRange(range);
5120}
5121
5122
5123void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5124 if (node->being_calculated())
5125 return;
5126 DispatchTable* table = node->GetTable(ignore_case_);
5127 AddDispatchRange adder(this);
5128 table->ForEach(&adder);
5129}
5130
5131
5132void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5133 // TODO(160): Find the node that we refer back to and propagate its start
5134 // set back to here. For now we just accept anything.
5135 AddRange(CharacterRange::Everything());
5136}
5137
5138
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005139void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5140 RegExpNode* target = that->on_success();
5141 target->Accept(this);
5142}
5143
5144
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005145static int CompareRangeByFrom(const CharacterRange* a,
5146 const CharacterRange* b) {
5147 return Compare<uc16>(a->from(), b->from());
5148}
5149
5150
5151void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5152 ranges->Sort(CompareRangeByFrom);
5153 uc16 last = 0;
5154 for (int i = 0; i < ranges->length(); i++) {
5155 CharacterRange range = ranges->at(i);
5156 if (last < range.from())
5157 AddRange(CharacterRange(last, range.from() - 1));
5158 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005159 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005160 return;
5161 } else {
5162 last = range.to() + 1;
5163 }
5164 }
5165 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005166 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005167}
5168
5169
5170void DispatchTableConstructor::VisitText(TextNode* that) {
5171 TextElement elm = that->elements()->at(0);
5172 switch (elm.type) {
5173 case TextElement::ATOM: {
5174 uc16 c = elm.data.u_atom->data()[0];
5175 AddRange(CharacterRange(c, c));
5176 break;
5177 }
5178 case TextElement::CHAR_CLASS: {
5179 RegExpCharacterClass* tree = elm.data.u_char_class;
5180 ZoneList<CharacterRange>* ranges = tree->ranges();
5181 if (tree->is_negated()) {
5182 AddInverse(ranges);
5183 } else {
5184 for (int i = 0; i < ranges->length(); i++)
5185 AddRange(ranges->at(i));
5186 }
5187 break;
5188 }
5189 default: {
5190 UNIMPLEMENTED();
5191 }
5192 }
5193}
5194
5195
5196void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005197 RegExpNode* target = that->on_success();
5198 target->Accept(this);
5199}
5200
5201
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005202RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5203 bool ignore_case,
5204 bool is_multiline,
5205 Handle<String> pattern,
5206 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005207 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005208 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005209 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005210 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005211 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005212 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005213 0,
5214 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005215 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005216 RegExpNode* node = captured_body;
5217 if (!data->tree->IsAnchored()) {
5218 // Add a .*? at the beginning, outside the body capture, unless
5219 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005220 RegExpNode* loop_node =
5221 RegExpQuantifier::ToNode(0,
5222 RegExpTree::kInfinity,
5223 false,
5224 new RegExpCharacterClass('*'),
5225 &compiler,
5226 captured_body,
5227 data->contains_anchor);
5228
5229 if (data->contains_anchor) {
5230 // Unroll loop once, to take care of the case that might start
5231 // at the start of input.
5232 ChoiceNode* first_step_node = new ChoiceNode(2);
5233 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5234 first_step_node->AddAlternative(GuardedAlternative(
5235 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5236 node = first_step_node;
5237 } else {
5238 node = loop_node;
5239 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005240 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005241 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005242 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005243 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005244 if (analysis.has_failed()) {
5245 const char* error_message = analysis.error_message();
5246 return CompilationResult(error_message);
5247 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005248
5249 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005250
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005251 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005252#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005253 // Native regexp implementation.
5254
5255 NativeRegExpMacroAssembler::Mode mode =
5256 is_ascii ? NativeRegExpMacroAssembler::ASCII
5257 : NativeRegExpMacroAssembler::UC16;
5258
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005259#if V8_TARGET_ARCH_IA32
5260 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5261#elif V8_TARGET_ARCH_X64
5262 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5263#elif V8_TARGET_ARCH_ARM
5264 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005265#endif
5266
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005267#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005268 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005269 EmbeddedVector<byte, 1024> codes;
5270 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005271#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005272
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005273 return compiler.Assemble(&macro_assembler,
5274 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005275 data->capture_count,
5276 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005277}
5278
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005279
5280int OffsetsVector::static_offsets_vector_[
5281 OffsetsVector::kStaticOffsetsVectorSize];
5282
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005283}} // namespace v8::internal