blob: 30d4dcbf23b43a8a3ab360f03a767556a59e0319 [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
erik.corry@gmail.com145eff52010-08-23 11:36:18 +0000383RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(
384 Handle<JSRegExp> regexp,
385 Handle<String> subject,
386 int index,
387 Vector<int32_t> output) {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000388 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()));
389
390 ASSERT(index >= 0);
391 ASSERT(index <= subject->length());
392 ASSERT(subject->IsFlat());
393
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000394 // A flat ASCII string might have a two-byte first part.
395 if (subject->IsConsString()) {
396 subject = Handle<String>(ConsString::cast(*subject)->first());
397 }
398
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000399#ifndef V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000400 ASSERT(output.length() >=
401 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
402 do {
403 bool is_ascii = subject->IsAsciiRepresentation();
404 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii));
405 NativeRegExpMacroAssembler::Result res =
406 NativeRegExpMacroAssembler::Match(code,
407 subject,
408 output.start(),
409 output.length(),
410 index);
411 if (res != NativeRegExpMacroAssembler::RETRY) {
412 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
413 Top::has_pending_exception());
414 STATIC_ASSERT(
415 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
416 STATIC_ASSERT(
417 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
418 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
419 == RE_EXCEPTION);
420 return static_cast<IrregexpResult>(res);
421 }
422 // If result is RETRY, the string has changed representation, and we
423 // must restart from scratch.
424 // In this case, it means we must make sure we are prepared to handle
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000425 // the, potentially, different subject (the string can switch between
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000426 // being internal and external, and even between being ASCII and UC16,
427 // but the characters are always the same).
428 IrregexpPrepare(regexp, subject);
429 } while (true);
430 UNREACHABLE();
431 return RE_EXCEPTION;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000432#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000433
434 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
435 bool is_ascii = subject->IsAsciiRepresentation();
436 // We must have done EnsureCompiledIrregexp, so we can get the number of
437 // registers.
438 int* register_vector = output.start();
439 int number_of_capture_registers =
440 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
441 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
442 register_vector[i] = -1;
443 }
444 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii));
445
446 if (IrregexpInterpreter::Match(byte_codes,
447 subject,
448 register_vector,
449 index)) {
450 return RE_SUCCESS;
451 }
452 return RE_FAILURE;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000453#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000454}
455
456
ager@chromium.org41826e72009-03-30 13:30:57 +0000457Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000458 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000459 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000460 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000461 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000462
ager@chromium.org8bb60582008-12-11 12:02:20 +0000463 // Prepare space for the return values.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000464#ifdef V8_INTERPRETED_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000465#ifdef DEBUG
466 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000467 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000468 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
469 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
470 }
471#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000472#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000473 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
474 if (required_registers < 0) {
475 // Compiling failed with an exception.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000476 ASSERT(Top::has_pending_exception());
477 return Handle<Object>::null();
478 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000479
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000480 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000481
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000482 IrregexpResult res = RegExpImpl::IrregexpExecOnce(
erik.corry@gmail.com145eff52010-08-23 11:36:18 +0000483 jsregexp, subject, previous_index, Vector<int32_t>(registers.vector(),
484 registers.length()));
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000485 if (res == RE_SUCCESS) {
486 int capture_register_count =
487 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
488 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
489 AssertNoAllocation no_gc;
490 int* register_vector = registers.vector();
491 FixedArray* array = FixedArray::cast(last_match_info->elements());
492 for (int i = 0; i < capture_register_count; i += 2) {
493 SetCapture(array, i, register_vector[i]);
494 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000495 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000496 SetLastCaptureCount(array, capture_register_count);
497 SetLastSubject(array, *subject);
498 SetLastInput(array, *subject);
499 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000500 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000501 if (res == RE_EXCEPTION) {
502 ASSERT(Top::has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000503 return Handle<Object>::null();
504 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000505 ASSERT(res == RE_FAILURE);
506 return Factory::null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000507}
508
509
510// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000511// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000512//
513// The Irregexp regular expression engine is intended to be a complete
514// implementation of ECMAScript regular expressions. It generates either
515// bytecodes or native code.
516
517// The Irregexp regexp engine is structured in three steps.
518// 1) The parser generates an abstract syntax tree. See ast.cc.
519// 2) From the AST a node network is created. The nodes are all
520// subclasses of RegExpNode. The nodes represent states when
521// executing a regular expression. Several optimizations are
522// performed on the node network.
523// 3) From the nodes we generate either byte codes or native code
524// that can actually execute the regular expression (perform
525// the search). The code generation step is described in more
526// detail below.
527
528// Code generation.
529//
530// The nodes are divided into four main categories.
531// * Choice nodes
532// These represent places where the regular expression can
533// match in more than one way. For example on entry to an
534// alternation (foo|bar) or a repetition (*, +, ? or {}).
535// * Action nodes
536// These represent places where some action should be
537// performed. Examples include recording the current position
538// in the input string to a register (in order to implement
539// captures) or other actions on register for example in order
540// to implement the counters needed for {} repetitions.
541// * Matching nodes
542// These attempt to match some element part of the input string.
543// Examples of elements include character classes, plain strings
544// or back references.
545// * End nodes
546// These are used to implement the actions required on finding
547// a successful match or failing to find a match.
548//
549// The code generated (whether as byte codes or native code) maintains
550// some state as it runs. This consists of the following elements:
551//
552// * The capture registers. Used for string captures.
553// * Other registers. Used for counters etc.
554// * The current position.
555// * The stack of backtracking information. Used when a matching node
556// fails to find a match and needs to try an alternative.
557//
558// Conceptual regular expression execution model:
559//
560// There is a simple conceptual model of regular expression execution
561// which will be presented first. The actual code generated is a more
562// efficient simulation of the simple conceptual model:
563//
564// * Choice nodes are implemented as follows:
565// For each choice except the last {
566// push current position
567// push backtrack code location
568// <generate code to test for choice>
569// backtrack code location:
570// pop current position
571// }
572// <generate code to test for last choice>
573//
574// * Actions nodes are generated as follows
575// <push affected registers on backtrack stack>
576// <generate code to perform action>
577// push backtrack code location
578// <generate code to test for following nodes>
579// backtrack code location:
580// <pop affected registers to restore their state>
581// <pop backtrack location from stack and go to it>
582//
583// * Matching nodes are generated as follows:
584// if input string matches at current position
585// update current position
586// <generate code to test for following nodes>
587// else
588// <pop backtrack location from stack and go to it>
589//
590// Thus it can be seen that the current position is saved and restored
591// by the choice nodes, whereas the registers are saved and restored by
592// by the action nodes that manipulate them.
593//
594// The other interesting aspect of this model is that nodes are generated
595// at the point where they are needed by a recursive call to Emit(). If
596// the node has already been code generated then the Emit() call will
597// generate a jump to the previously generated code instead. In order to
598// limit recursion it is possible for the Emit() function to put the node
599// on a work list for later generation and instead generate a jump. The
600// destination of the jump is resolved later when the code is generated.
601//
602// Actual regular expression code generation.
603//
604// Code generation is actually more complicated than the above. In order
605// to improve the efficiency of the generated code some optimizations are
606// performed
607//
608// * Choice nodes have 1-character lookahead.
609// A choice node looks at the following character and eliminates some of
610// the choices immediately based on that character. This is not yet
611// implemented.
612// * Simple greedy loops store reduced backtracking information.
613// A quantifier like /.*foo/m will greedily match the whole input. It will
614// then need to backtrack to a point where it can match "foo". The naive
615// implementation of this would push each character position onto the
616// backtracking stack, then pop them off one by one. This would use space
617// proportional to the length of the input string. However since the "."
618// can only match in one way and always has a constant length (in this case
619// of 1) it suffices to store the current position on the top of the stack
620// once. Matching now becomes merely incrementing the current position and
621// backtracking becomes decrementing the current position and checking the
622// result against the stored current position. This is faster and saves
623// space.
624// * The current state is virtualized.
625// This is used to defer expensive operations until it is clear that they
626// are needed and to generate code for a node more than once, allowing
627// specialized an efficient versions of the code to be created. This is
628// explained in the section below.
629//
630// Execution state virtualization.
631//
632// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000633// manipulation in an object called the Trace. The Trace object can record a
634// current position offset, an optional backtrack code location on the top of
635// the virtualized backtrack stack and some register changes. When a node is
636// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000637// will emit code to bring the actual state into line with the virtual state.
638// Avoiding flushing the state can postpone some work (eg updates of capture
639// registers). Postponing work can save time when executing the regular
640// expression since it may be found that the work never has to be done as a
641// failure to match can occur. In addition it is much faster to jump to a
642// known backtrack code location than it is to pop an unknown backtrack
643// location from the stack and jump there.
644//
ager@chromium.org32912102009-01-16 10:38:43 +0000645// The virtual state found in the Trace affects code generation. For example
646// the virtual state contains the difference between the actual current
647// position and the virtual current position, and matching code needs to use
648// this offset to attempt a match in the correct location of the input
649// string. Therefore code generated for a non-trivial trace is specialized
650// to that trace. The code generator therefore has the ability to generate
651// code for each node several times. In order to limit the size of the
652// generated code there is an arbitrary limit on how many specialized sets of
653// code may be generated for a given node. If the limit is reached, the
654// trace is flushed and a generic version of the code for a node is emitted.
655// This is subsequently used for that node. The code emitted for non-generic
656// trace is not recorded in the node and so it cannot currently be reused in
657// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000658
659
660void RegExpTree::AppendToText(RegExpText* text) {
661 UNREACHABLE();
662}
663
664
665void RegExpAtom::AppendToText(RegExpText* text) {
666 text->AddElement(TextElement::Atom(this));
667}
668
669
670void RegExpCharacterClass::AppendToText(RegExpText* text) {
671 text->AddElement(TextElement::CharClass(this));
672}
673
674
675void RegExpText::AppendToText(RegExpText* text) {
676 for (int i = 0; i < elements()->length(); i++)
677 text->AddElement(elements()->at(i));
678}
679
680
681TextElement TextElement::Atom(RegExpAtom* atom) {
682 TextElement result = TextElement(ATOM);
683 result.data.u_atom = atom;
684 return result;
685}
686
687
688TextElement TextElement::CharClass(
689 RegExpCharacterClass* char_class) {
690 TextElement result = TextElement(CHAR_CLASS);
691 result.data.u_char_class = char_class;
692 return result;
693}
694
695
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000696int TextElement::length() {
697 if (type == ATOM) {
698 return data.u_atom->length();
699 } else {
700 ASSERT(type == CHAR_CLASS);
701 return 1;
702 }
703}
704
705
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000706DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
707 if (table_ == NULL) {
708 table_ = new DispatchTable();
709 DispatchTableConstructor cons(table_, ignore_case);
710 cons.BuildTable(this);
711 }
712 return table_;
713}
714
715
716class RegExpCompiler {
717 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000718 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000719
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000720 int AllocateRegister() {
721 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
722 reg_exp_too_big_ = true;
723 return next_register_;
724 }
725 return next_register_++;
726 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000727
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000728 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
729 RegExpNode* start,
730 int capture_count,
731 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000732
733 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
734
735 static const int kImplementationOffset = 0;
736 static const int kNumberOfRegistersOffset = 0;
737 static const int kCodeOffset = 1;
738
739 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
740 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000741
742 static const int kMaxRecursion = 100;
743 inline int recursion_depth() { return recursion_depth_; }
744 inline void IncrementRecursionDepth() { recursion_depth_++; }
745 inline void DecrementRecursionDepth() { recursion_depth_--; }
746
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000747 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
748
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000749 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000750 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000751
ager@chromium.org32912102009-01-16 10:38:43 +0000752 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000753 private:
754 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000755 int next_register_;
756 List<RegExpNode*>* work_list_;
757 int recursion_depth_;
758 RegExpMacroAssembler* macro_assembler_;
759 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000760 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000761 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000762};
763
764
765class RecursionCheck {
766 public:
767 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
768 compiler->IncrementRecursionDepth();
769 }
770 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
771 private:
772 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000773};
774
775
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000776static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
777 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000778}
779
780
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000781// Attempts to compile the regexp using an Irregexp code generator. Returns
782// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000783RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000784 : next_register_(2 * (capture_count + 1)),
785 work_list_(NULL),
786 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000787 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000788 ascii_(ascii),
789 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000790 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000791 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000792}
793
794
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000795RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000796 RegExpMacroAssembler* macro_assembler,
797 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000798 int capture_count,
799 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000800#ifdef DEBUG
801 if (FLAG_trace_regexp_assembler)
802 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
803 else
804#endif
805 macro_assembler_ = macro_assembler;
806 List <RegExpNode*> work_list(0);
807 work_list_ = &work_list;
808 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000809 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000810 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000811 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000812 macro_assembler_->Bind(&fail);
813 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000814 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000815 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000816 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000817 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
818
ager@chromium.org8bb60582008-12-11 12:02:20 +0000819 Handle<Object> code = macro_assembler_->GetCode(pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000820
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000821 work_list_ = NULL;
822#ifdef DEBUG
823 if (FLAG_trace_regexp_assembler) {
824 delete macro_assembler_;
825 }
826#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000827 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000828}
829
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000830
ager@chromium.org32912102009-01-16 10:38:43 +0000831bool Trace::DeferredAction::Mentions(int that) {
832 if (type() == ActionNode::CLEAR_CAPTURES) {
833 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
834 return range.Contains(that);
835 } else {
836 return reg() == that;
837 }
838}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000839
ager@chromium.org32912102009-01-16 10:38:43 +0000840
841bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000842 for (DeferredAction* action = actions_;
843 action != NULL;
844 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000845 if (action->Mentions(reg))
846 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000847 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000848 return false;
849}
850
851
ager@chromium.org32912102009-01-16 10:38:43 +0000852bool Trace::GetStoredPosition(int reg, int* cp_offset) {
853 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000854 for (DeferredAction* action = actions_;
855 action != NULL;
856 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000857 if (action->Mentions(reg)) {
858 if (action->type() == ActionNode::STORE_POSITION) {
859 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
860 return true;
861 } else {
862 return false;
863 }
864 }
865 }
866 return false;
867}
868
869
870int Trace::FindAffectedRegisters(OutSet* affected_registers) {
871 int max_register = RegExpCompiler::kNoRegister;
872 for (DeferredAction* action = actions_;
873 action != NULL;
874 action = action->next()) {
875 if (action->type() == ActionNode::CLEAR_CAPTURES) {
876 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
877 for (int i = range.from(); i <= range.to(); i++)
878 affected_registers->Set(i);
879 if (range.to() > max_register) max_register = range.to();
880 } else {
881 affected_registers->Set(action->reg());
882 if (action->reg() > max_register) max_register = action->reg();
883 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000884 }
885 return max_register;
886}
887
888
ager@chromium.org32912102009-01-16 10:38:43 +0000889void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
890 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000891 OutSet& registers_to_pop,
892 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000893 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000894 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
895 else if (registers_to_clear.Get(reg)) {
896 int clear_to = reg;
897 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
898 reg--;
899 }
900 assembler->ClearRegisters(reg, clear_to);
901 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000902 }
903}
904
905
ager@chromium.org32912102009-01-16 10:38:43 +0000906void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
907 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000908 OutSet& affected_registers,
909 OutSet* registers_to_pop,
910 OutSet* registers_to_clear) {
911 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
912 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
913
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000914 // Count pushes performed to force a stack limit check occasionally.
915 int pushes = 0;
916
ager@chromium.org8bb60582008-12-11 12:02:20 +0000917 for (int reg = 0; reg <= max_register; reg++) {
918 if (!affected_registers.Get(reg)) {
919 continue;
920 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000921
922 // The chronologically first deferred action in the trace
923 // is used to infer the action needed to restore a register
924 // to its previous state (or not, if it's safe to ignore it).
925 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
926 DeferredActionUndoType undo_action = IGNORE;
927
ager@chromium.org8bb60582008-12-11 12:02:20 +0000928 int value = 0;
929 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000930 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000931 int store_position = -1;
932 // This is a little tricky because we are scanning the actions in reverse
933 // historical order (newest first).
934 for (DeferredAction* action = actions_;
935 action != NULL;
936 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000937 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000938 switch (action->type()) {
939 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +0000940 Trace::DeferredSetRegister* psr =
941 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000942 if (!absolute) {
943 value += psr->value();
944 absolute = true;
945 }
946 // SET_REGISTER is currently only used for newly introduced loop
947 // counters. They can have a significant previous value if they
948 // occour in a loop. TODO(lrn): Propagate this information, so
949 // we can set undo_action to IGNORE if we know there is no value to
950 // restore.
951 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000952 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000953 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000954 break;
955 }
956 case ActionNode::INCREMENT_REGISTER:
957 if (!absolute) {
958 value++;
959 }
960 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000961 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000962 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000963 break;
964 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +0000965 Trace::DeferredCapture* pc =
966 static_cast<Trace::DeferredCapture*>(action);
967 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000968 store_position = pc->cp_offset();
969 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000970
971 // For captures we know that stores and clears alternate.
972 // Other register, are never cleared, and if the occur
973 // inside a loop, they might be assigned more than once.
974 if (reg <= 1) {
975 // Registers zero and one, aka "capture zero", is
976 // always set correctly if we succeed. There is no
977 // need to undo a setting on backtrack, because we
978 // will set it again or fail.
979 undo_action = IGNORE;
980 } else {
981 undo_action = pc->is_capture() ? CLEAR : RESTORE;
982 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000983 ASSERT(!absolute);
984 ASSERT_EQ(value, 0);
985 break;
986 }
ager@chromium.org32912102009-01-16 10:38:43 +0000987 case ActionNode::CLEAR_CAPTURES: {
988 // Since we're scanning in reverse order, if we've already
989 // set the position we have to ignore historically earlier
990 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000991 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +0000992 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000993 }
994 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +0000995 ASSERT(!absolute);
996 ASSERT_EQ(value, 0);
997 break;
998 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000999 default:
1000 UNREACHABLE();
1001 break;
1002 }
1003 }
1004 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001005 // Prepare for the undo-action (e.g., push if it's going to be popped).
1006 if (undo_action == RESTORE) {
1007 pushes++;
1008 RegExpMacroAssembler::StackCheckFlag stack_check =
1009 RegExpMacroAssembler::kNoStackLimitCheck;
1010 if (pushes == push_limit) {
1011 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1012 pushes = 0;
1013 }
1014
1015 assembler->PushRegister(reg, stack_check);
1016 registers_to_pop->Set(reg);
1017 } else if (undo_action == CLEAR) {
1018 registers_to_clear->Set(reg);
1019 }
1020 // Perform the chronologically last action (or accumulated increment)
1021 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001022 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001023 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001024 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001025 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001026 } else if (absolute) {
1027 assembler->SetRegister(reg, value);
1028 } else if (value != 0) {
1029 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001030 }
1031 }
1032}
1033
1034
ager@chromium.org8bb60582008-12-11 12:02:20 +00001035// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001036// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001037// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001038void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001039 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001040
iposva@chromium.org245aa852009-02-10 00:49:54 +00001041 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001042
1043 if (actions_ == NULL && backtrack() == NULL) {
1044 // 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 +00001045 // a normal situation. We may also have to forget some information gained
1046 // through a quick check that was already performed.
1047 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001048 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001049 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001050 successor->Emit(compiler, &new_state);
1051 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001052 }
1053
1054 // Generate deferred actions here along with code to undo them again.
1055 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001056
ager@chromium.org381abbb2009-02-25 13:23:22 +00001057 if (backtrack() != NULL) {
1058 // Here we have a concrete backtrack location. These are set up by choice
1059 // nodes and so they indicate that we have a deferred save of the current
1060 // position which we may need to emit here.
1061 assembler->PushCurrentPosition();
1062 }
1063
ager@chromium.org8bb60582008-12-11 12:02:20 +00001064 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001065 OutSet registers_to_pop;
1066 OutSet registers_to_clear;
1067 PerformDeferredActions(assembler,
1068 max_register,
1069 affected_registers,
1070 &registers_to_pop,
1071 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001072 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001073 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001074 }
1075
1076 // Create a new trivial state and generate the node with that.
1077 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001078 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001079 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001080 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001081
1082 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001083 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001084 RestoreAffectedRegisters(assembler,
1085 max_register,
1086 registers_to_pop,
1087 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001088 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001089 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001090 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001091 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001092 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001093 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001094}
1095
1096
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001097void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001098 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001099
1100 // Omit flushing the trace. We discard the entire stack frame anyway.
1101
ager@chromium.org8bb60582008-12-11 12:02:20 +00001102 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001103 // We are completely independent of the trace, since we ignore it,
1104 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001105 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001106 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001107
1108 // Throw away everything on the backtrack stack since the start
1109 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001110 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1111 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001112 if (clear_capture_count_ > 0) {
1113 // Clear any captures that might have been performed during the success
1114 // of the body of the negative look-ahead.
1115 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1116 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1117 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001118 // Now that we have unwound the stack we find at the top of the stack the
1119 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001120 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001121}
1122
1123
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001124void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001125 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001126 trace->Flush(compiler, this);
1127 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001128 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001129 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001130 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001131 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001132 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001133 switch (action_) {
1134 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001135 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001136 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001137 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001138 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001139 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001140 case NEGATIVE_SUBMATCH_SUCCESS:
1141 // This case is handled in a different virtual method.
1142 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001143 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001144 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001145}
1146
1147
1148void GuardedAlternative::AddGuard(Guard* guard) {
1149 if (guards_ == NULL)
1150 guards_ = new ZoneList<Guard*>(1);
1151 guards_->Add(guard);
1152}
1153
1154
ager@chromium.org8bb60582008-12-11 12:02:20 +00001155ActionNode* ActionNode::SetRegister(int reg,
1156 int val,
1157 RegExpNode* on_success) {
1158 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001159 result->data_.u_store_register.reg = reg;
1160 result->data_.u_store_register.value = val;
1161 return result;
1162}
1163
1164
1165ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1166 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1167 result->data_.u_increment_register.reg = reg;
1168 return result;
1169}
1170
1171
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001172ActionNode* ActionNode::StorePosition(int reg,
1173 bool is_capture,
1174 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001175 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1176 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001177 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001178 return result;
1179}
1180
1181
ager@chromium.org32912102009-01-16 10:38:43 +00001182ActionNode* ActionNode::ClearCaptures(Interval range,
1183 RegExpNode* on_success) {
1184 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1185 result->data_.u_clear_captures.range_from = range.from();
1186 result->data_.u_clear_captures.range_to = range.to();
1187 return result;
1188}
1189
1190
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001191ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1192 int position_reg,
1193 RegExpNode* on_success) {
1194 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1195 result->data_.u_submatch.stack_pointer_register = stack_reg;
1196 result->data_.u_submatch.current_position_register = position_reg;
1197 return result;
1198}
1199
1200
ager@chromium.org8bb60582008-12-11 12:02:20 +00001201ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1202 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001203 int clear_register_count,
1204 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001205 RegExpNode* on_success) {
1206 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001207 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001208 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001209 result->data_.u_submatch.clear_register_count = clear_register_count;
1210 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001211 return result;
1212}
1213
1214
ager@chromium.org32912102009-01-16 10:38:43 +00001215ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1216 int repetition_register,
1217 int repetition_limit,
1218 RegExpNode* on_success) {
1219 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1220 result->data_.u_empty_match_check.start_register = start_register;
1221 result->data_.u_empty_match_check.repetition_register = repetition_register;
1222 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1223 return result;
1224}
1225
1226
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001227#define DEFINE_ACCEPT(Type) \
1228 void Type##Node::Accept(NodeVisitor* visitor) { \
1229 visitor->Visit##Type(this); \
1230 }
1231FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1232#undef DEFINE_ACCEPT
1233
1234
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001235void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1236 visitor->VisitLoopChoice(this);
1237}
1238
1239
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001240// -------------------------------------------------------------------
1241// Emit code.
1242
1243
1244void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1245 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001246 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001247 switch (guard->op()) {
1248 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001249 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001250 macro_assembler->IfRegisterGE(guard->reg(),
1251 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001252 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001253 break;
1254 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001255 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001256 macro_assembler->IfRegisterLT(guard->reg(),
1257 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001258 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001259 break;
1260 }
1261}
1262
1263
1264static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1265static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1266
1267
ager@chromium.org381abbb2009-02-25 13:23:22 +00001268// Returns the number of characters in the equivalence class, omitting those
1269// that cannot occur in the source string because it is ASCII.
1270static int GetCaseIndependentLetters(uc16 character,
1271 bool ascii_subject,
1272 unibrow::uchar* letters) {
1273 int length = uncanonicalize.get(character, '\0', letters);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00001274 // Unibrow returns 0 or 1 for characters where case independence is
ager@chromium.org381abbb2009-02-25 13:23:22 +00001275 // trivial.
1276 if (length == 0) {
1277 letters[0] = character;
1278 length = 1;
1279 }
1280 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1281 return length;
1282 }
1283 // The standard requires that non-ASCII characters cannot have ASCII
1284 // character codes in their equivalence class.
1285 return 0;
1286}
1287
1288
1289static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1290 uc16 c,
1291 Label* on_failure,
1292 int cp_offset,
1293 bool check,
1294 bool preloaded) {
1295 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1296 bool bound_checked = false;
1297 if (!preloaded) {
1298 assembler->LoadCurrentCharacter(
1299 cp_offset,
1300 on_failure,
1301 check);
1302 bound_checked = true;
1303 }
1304 assembler->CheckNotCharacter(c, on_failure);
1305 return bound_checked;
1306}
1307
1308
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001309// Only emits non-letters (things that don't have case). Only used for case
1310// independent matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001311static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1312 uc16 c,
1313 Label* on_failure,
1314 int cp_offset,
1315 bool check,
1316 bool preloaded) {
1317 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1318 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001319 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001320 int length = GetCaseIndependentLetters(c, ascii, chars);
1321 if (length < 1) {
1322 // This can't match. Must be an ASCII subject and a non-ASCII character.
1323 // We do not need to do anything since the ASCII pass already handled this.
1324 return false; // Bounds not checked.
1325 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001326 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001327 // We handle the length > 1 case in a later pass.
1328 if (length == 1) {
1329 if (ascii && c > String::kMaxAsciiCharCodeU) {
1330 // Can't match - see above.
1331 return false; // Bounds not checked.
1332 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001333 if (!preloaded) {
1334 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1335 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001336 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001337 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001338 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001339 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001340}
1341
1342
1343static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001344 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001345 uc16 c1,
1346 uc16 c2,
1347 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001348 uc16 char_mask;
1349 if (ascii) {
1350 char_mask = String::kMaxAsciiCharCode;
1351 } else {
1352 char_mask = String::kMaxUC16CharCode;
1353 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001354 uc16 exor = c1 ^ c2;
1355 // Check whether exor has only one bit set.
1356 if (((exor - 1) & exor) == 0) {
1357 // If c1 and c2 differ only by one bit.
1358 // Ecma262UnCanonicalize always gives the highest number last.
1359 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001360 uc16 mask = char_mask ^ exor;
1361 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001362 return true;
1363 }
1364 ASSERT(c2 > c1);
1365 uc16 diff = c2 - c1;
1366 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1367 // If the characters differ by 2^n but don't differ by one bit then
1368 // subtract the difference from the found character, then do the or
1369 // trick. We avoid the theoretical case where negative numbers are
1370 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001371 uc16 mask = char_mask ^ diff;
1372 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1373 diff,
1374 mask,
1375 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001376 return true;
1377 }
1378 return false;
1379}
1380
1381
ager@chromium.org381abbb2009-02-25 13:23:22 +00001382typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1383 uc16 c,
1384 Label* on_failure,
1385 int cp_offset,
1386 bool check,
1387 bool preloaded);
1388
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001389// Only emits letters (things that have case). Only used for case independent
1390// matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001391static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1392 uc16 c,
1393 Label* on_failure,
1394 int cp_offset,
1395 bool check,
1396 bool preloaded) {
1397 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1398 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001399 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001400 int length = GetCaseIndependentLetters(c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001401 if (length <= 1) return false;
1402 // We may not need to check against the end of the input string
1403 // if this character lies before a character that matched.
1404 if (!preloaded) {
1405 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001406 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001407 Label ok;
1408 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1409 switch (length) {
1410 case 2: {
1411 if (ShortCutEmitCharacterPair(macro_assembler,
1412 ascii,
1413 chars[0],
1414 chars[1],
1415 on_failure)) {
1416 } else {
1417 macro_assembler->CheckCharacter(chars[0], &ok);
1418 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1419 macro_assembler->Bind(&ok);
1420 }
1421 break;
1422 }
1423 case 4:
1424 macro_assembler->CheckCharacter(chars[3], &ok);
1425 // Fall through!
1426 case 3:
1427 macro_assembler->CheckCharacter(chars[0], &ok);
1428 macro_assembler->CheckCharacter(chars[1], &ok);
1429 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1430 macro_assembler->Bind(&ok);
1431 break;
1432 default:
1433 UNREACHABLE();
1434 break;
1435 }
1436 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001437}
1438
1439
1440static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1441 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001442 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001443 Label* on_failure,
1444 int cp_offset,
1445 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001446 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001447 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001448 int max_char;
1449 if (ascii) {
1450 max_char = String::kMaxAsciiCharCode;
1451 } else {
1452 max_char = String::kMaxUC16CharCode;
1453 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001454
1455 Label success;
1456
1457 Label* char_is_in_class =
1458 cc->is_negated() ? on_failure : &success;
1459
1460 int range_count = ranges->length();
1461
ager@chromium.org8bb60582008-12-11 12:02:20 +00001462 int last_valid_range = range_count - 1;
1463 while (last_valid_range >= 0) {
1464 CharacterRange& range = ranges->at(last_valid_range);
1465 if (range.from() <= max_char) {
1466 break;
1467 }
1468 last_valid_range--;
1469 }
1470
1471 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001472 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001473 // TODO(plesner): We can remove this when the node level does our
1474 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001475 macro_assembler->GoTo(on_failure);
1476 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001477 if (check_offset) {
1478 macro_assembler->CheckPosition(cp_offset, on_failure);
1479 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001480 return;
1481 }
1482
ager@chromium.org8bb60582008-12-11 12:02:20 +00001483 if (last_valid_range == 0 &&
1484 !cc->is_negated() &&
1485 ranges->at(0).IsEverything(max_char)) {
1486 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001487 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001488 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001489 }
1490 return;
1491 }
1492
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001493 if (!preloaded) {
1494 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001495 }
1496
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001497 if (cc->is_standard() &&
1498 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1499 on_failure)) {
1500 return;
1501 }
1502
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001503 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001504 CharacterRange& range = ranges->at(i);
1505 Label next_range;
1506 uc16 from = range.from();
1507 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001508 if (from > max_char) {
1509 continue;
1510 }
1511 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001512 if (to == from) {
1513 macro_assembler->CheckCharacter(to, char_is_in_class);
1514 } else {
1515 if (from != 0) {
1516 macro_assembler->CheckCharacterLT(from, &next_range);
1517 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001518 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001519 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1520 } else {
1521 macro_assembler->GoTo(char_is_in_class);
1522 }
1523 }
1524 macro_assembler->Bind(&next_range);
1525 }
1526
ager@chromium.org8bb60582008-12-11 12:02:20 +00001527 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001528 uc16 from = range.from();
1529 uc16 to = range.to();
1530
ager@chromium.org8bb60582008-12-11 12:02:20 +00001531 if (to > max_char) to = max_char;
1532 ASSERT(to >= from);
1533
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001534 if (to == from) {
1535 if (cc->is_negated()) {
1536 macro_assembler->CheckCharacter(to, on_failure);
1537 } else {
1538 macro_assembler->CheckNotCharacter(to, on_failure);
1539 }
1540 } else {
1541 if (from != 0) {
1542 if (cc->is_negated()) {
1543 macro_assembler->CheckCharacterLT(from, &success);
1544 } else {
1545 macro_assembler->CheckCharacterLT(from, on_failure);
1546 }
1547 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001548 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001549 if (cc->is_negated()) {
1550 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1551 } else {
1552 macro_assembler->CheckCharacterGT(to, on_failure);
1553 }
1554 } else {
1555 if (cc->is_negated()) {
1556 macro_assembler->GoTo(on_failure);
1557 }
1558 }
1559 }
1560 macro_assembler->Bind(&success);
1561}
1562
1563
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001564RegExpNode::~RegExpNode() {
1565}
1566
1567
ager@chromium.org8bb60582008-12-11 12:02:20 +00001568RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001569 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001570 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001571 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001572 return CONTINUE;
1573 }
1574
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001575 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001576 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001577 if (label_.is_bound()) {
1578 // We are being asked to generate a generic version, but that's already
1579 // been done so just go to it.
1580 macro_assembler->GoTo(&label_);
1581 return DONE;
1582 }
1583 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1584 // To avoid too deep recursion we push the node to the work queue and just
1585 // generate a goto here.
1586 compiler->AddWork(this);
1587 macro_assembler->GoTo(&label_);
1588 return DONE;
1589 }
1590 // Generate generic version of the node and bind the label for later use.
1591 macro_assembler->Bind(&label_);
1592 return CONTINUE;
1593 }
1594
1595 // We are being asked to make a non-generic version. Keep track of how many
1596 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001597 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001598 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001599 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001600 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1601 return CONTINUE;
1602 }
1603
ager@chromium.org32912102009-01-16 10:38:43 +00001604 // If we get here code has been generated for this node too many times or
1605 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001606 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001607 trace->Flush(compiler, this);
1608 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001609}
1610
1611
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001612int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001613 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1614 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001615 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001616}
1617
1618
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001619int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1620 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1621 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1622}
1623
1624
1625int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1626 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1627 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1628}
1629
1630
1631int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001632 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001633 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001634 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001635 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1636 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001637}
1638
1639
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001640int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
1641 int recursion_depth) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001642 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1643 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1644 // afterwards.
1645 RegExpNode* node = alternatives_->at(1).node();
1646 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1647}
1648
1649
1650void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1651 QuickCheckDetails* details,
1652 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001653 int filled_in,
1654 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001655 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1656 // afterwards.
1657 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001658 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001659}
1660
1661
1662int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1663 int recursion_depth,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001664 RegExpNode* ignore_this_node) {
1665 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1666 int min = 100;
1667 int choice_count = alternatives_->length();
1668 for (int i = 0; i < choice_count; i++) {
1669 RegExpNode* node = alternatives_->at(i).node();
1670 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001671 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1672 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001673 if (node_eats_at_least < min) min = node_eats_at_least;
1674 }
1675 return min;
1676}
1677
1678
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001679int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1680 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001681}
1682
1683
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001684int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1685 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001686}
1687
1688
1689// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1690static inline uint32_t SmearBitsRight(uint32_t v) {
1691 v |= v >> 1;
1692 v |= v >> 2;
1693 v |= v >> 4;
1694 v |= v >> 8;
1695 v |= v >> 16;
1696 return v;
1697}
1698
1699
1700bool QuickCheckDetails::Rationalize(bool asc) {
1701 bool found_useful_op = false;
1702 uint32_t char_mask;
1703 if (asc) {
1704 char_mask = String::kMaxAsciiCharCode;
1705 } else {
1706 char_mask = String::kMaxUC16CharCode;
1707 }
1708 mask_ = 0;
1709 value_ = 0;
1710 int char_shift = 0;
1711 for (int i = 0; i < characters_; i++) {
1712 Position* pos = &positions_[i];
1713 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1714 found_useful_op = true;
1715 }
1716 mask_ |= (pos->mask & char_mask) << char_shift;
1717 value_ |= (pos->value & char_mask) << char_shift;
1718 char_shift += asc ? 8 : 16;
1719 }
1720 return found_useful_op;
1721}
1722
1723
1724bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001725 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001726 bool preload_has_checked_bounds,
1727 Label* on_possible_success,
1728 QuickCheckDetails* details,
1729 bool fall_through_on_failure) {
1730 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001731 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1732 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001733 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001734 ASSERT(details->characters() == 1 ||
1735 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001736 uint32_t mask = details->mask();
1737 uint32_t value = details->value();
1738
1739 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1740
ager@chromium.org32912102009-01-16 10:38:43 +00001741 if (trace->characters_preloaded() != details->characters()) {
1742 assembler->LoadCurrentCharacter(trace->cp_offset(),
1743 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001744 !preload_has_checked_bounds,
1745 details->characters());
1746 }
1747
1748
1749 bool need_mask = true;
1750
1751 if (details->characters() == 1) {
1752 // If number of characters preloaded is 1 then we used a byte or 16 bit
1753 // load so the value is already masked down.
1754 uint32_t char_mask;
1755 if (compiler->ascii()) {
1756 char_mask = String::kMaxAsciiCharCode;
1757 } else {
1758 char_mask = String::kMaxUC16CharCode;
1759 }
1760 if ((mask & char_mask) == char_mask) need_mask = false;
1761 mask &= char_mask;
1762 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001763 // For 2-character preloads in ASCII mode or 1-character preloads in
1764 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001765 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001766 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1767 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001768 if ((mask & 0xffff) == 0xffff) need_mask = false;
1769 } else {
1770 if (mask == 0xffffffff) need_mask = false;
1771 }
1772 }
1773
1774 if (fall_through_on_failure) {
1775 if (need_mask) {
1776 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1777 } else {
1778 assembler->CheckCharacter(value, on_possible_success);
1779 }
1780 } else {
1781 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001782 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001783 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001784 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001785 }
1786 }
1787 return true;
1788}
1789
1790
1791// Here is the meat of GetQuickCheckDetails (see also the comment on the
1792// super-class in the .h file).
1793//
1794// We iterate along the text object, building up for each character a
1795// mask and value that can be used to test for a quick failure to match.
1796// The masks and values for the positions will be combined into a single
1797// machine word for the current character width in order to be used in
1798// generating a quick check.
1799void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1800 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001801 int characters_filled_in,
1802 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001803 ASSERT(characters_filled_in < details->characters());
1804 int characters = details->characters();
1805 int char_mask;
1806 int char_shift;
1807 if (compiler->ascii()) {
1808 char_mask = String::kMaxAsciiCharCode;
1809 char_shift = 8;
1810 } else {
1811 char_mask = String::kMaxUC16CharCode;
1812 char_shift = 16;
1813 }
1814 for (int k = 0; k < elms_->length(); k++) {
1815 TextElement elm = elms_->at(k);
1816 if (elm.type == TextElement::ATOM) {
1817 Vector<const uc16> quarks = elm.data.u_atom->data();
1818 for (int i = 0; i < characters && i < quarks.length(); i++) {
1819 QuickCheckDetails::Position* pos =
1820 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001821 uc16 c = quarks[i];
1822 if (c > char_mask) {
1823 // If we expect a non-ASCII character from an ASCII string,
1824 // there is no way we can match. Not even case independent
1825 // matching can turn an ASCII character into non-ASCII or
1826 // vice versa.
1827 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001828 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001829 return;
1830 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001831 if (compiler->ignore_case()) {
1832 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001833 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1834 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1835 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001836 // This letter has no case equivalents, so it's nice and simple
1837 // and the mask-compare will determine definitely whether we have
1838 // a match at this character position.
1839 pos->mask = char_mask;
1840 pos->value = c;
1841 pos->determines_perfectly = true;
1842 } else {
1843 uint32_t common_bits = char_mask;
1844 uint32_t bits = chars[0];
1845 for (int j = 1; j < length; j++) {
1846 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1847 common_bits ^= differing_bits;
1848 bits &= common_bits;
1849 }
1850 // If length is 2 and common bits has only one zero in it then
1851 // our mask and compare instruction will determine definitely
1852 // whether we have a match at this character position. Otherwise
1853 // it can only be an approximate check.
1854 uint32_t one_zero = (common_bits | ~char_mask);
1855 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1856 pos->determines_perfectly = true;
1857 }
1858 pos->mask = common_bits;
1859 pos->value = bits;
1860 }
1861 } else {
1862 // Don't ignore case. Nice simple case where the mask-compare will
1863 // determine definitely whether we have a match at this character
1864 // position.
1865 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001866 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001867 pos->determines_perfectly = true;
1868 }
1869 characters_filled_in++;
1870 ASSERT(characters_filled_in <= details->characters());
1871 if (characters_filled_in == details->characters()) {
1872 return;
1873 }
1874 }
1875 } else {
1876 QuickCheckDetails::Position* pos =
1877 details->positions(characters_filled_in);
1878 RegExpCharacterClass* tree = elm.data.u_char_class;
1879 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001880 if (tree->is_negated()) {
1881 // A quick check uses multi-character mask and compare. There is no
1882 // useful way to incorporate a negative char class into this scheme
1883 // so we just conservatively create a mask and value that will always
1884 // succeed.
1885 pos->mask = 0;
1886 pos->value = 0;
1887 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001888 int first_range = 0;
1889 while (ranges->at(first_range).from() > char_mask) {
1890 first_range++;
1891 if (first_range == ranges->length()) {
1892 details->set_cannot_match();
1893 pos->determines_perfectly = false;
1894 return;
1895 }
1896 }
1897 CharacterRange range = ranges->at(first_range);
1898 uc16 from = range.from();
1899 uc16 to = range.to();
1900 if (to > char_mask) {
1901 to = char_mask;
1902 }
1903 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001904 // A mask and compare is only perfect if the differing bits form a
1905 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001906 if ((differing_bits & (differing_bits + 1)) == 0 &&
1907 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001908 pos->determines_perfectly = true;
1909 }
1910 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001911 uint32_t bits = (from & common_bits);
1912 for (int i = first_range + 1; i < ranges->length(); i++) {
1913 CharacterRange range = ranges->at(i);
1914 uc16 from = range.from();
1915 uc16 to = range.to();
1916 if (from > char_mask) continue;
1917 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001918 // Here we are combining more ranges into the mask and compare
1919 // value. With each new range the mask becomes more sparse and
1920 // so the chances of a false positive rise. A character class
1921 // with multiple ranges is assumed never to be equivalent to a
1922 // mask and compare operation.
1923 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001924 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001925 new_common_bits = ~SmearBitsRight(new_common_bits);
1926 common_bits &= new_common_bits;
1927 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001928 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001929 common_bits ^= differing_bits;
1930 bits &= common_bits;
1931 }
1932 pos->mask = common_bits;
1933 pos->value = bits;
1934 }
1935 characters_filled_in++;
1936 ASSERT(characters_filled_in <= details->characters());
1937 if (characters_filled_in == details->characters()) {
1938 return;
1939 }
1940 }
1941 }
1942 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00001943 on_success()-> GetQuickCheckDetails(details,
1944 compiler,
1945 characters_filled_in,
1946 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001947}
1948
1949
1950void QuickCheckDetails::Clear() {
1951 for (int i = 0; i < characters_; i++) {
1952 positions_[i].mask = 0;
1953 positions_[i].value = 0;
1954 positions_[i].determines_perfectly = false;
1955 }
1956 characters_ = 0;
1957}
1958
1959
1960void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001961 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001962 if (by >= characters_) {
1963 Clear();
1964 return;
1965 }
1966 for (int i = 0; i < characters_ - by; i++) {
1967 positions_[i] = positions_[by + i];
1968 }
1969 for (int i = characters_ - by; i < characters_; i++) {
1970 positions_[i].mask = 0;
1971 positions_[i].value = 0;
1972 positions_[i].determines_perfectly = false;
1973 }
1974 characters_ -= by;
1975 // We could change mask_ and value_ here but we would never advance unless
1976 // they had already been used in a check and they won't be used again because
1977 // it would gain us nothing. So there's no point.
1978}
1979
1980
1981void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1982 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001983 if (other->cannot_match_) {
1984 return;
1985 }
1986 if (cannot_match_) {
1987 *this = *other;
1988 return;
1989 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001990 for (int i = from_index; i < characters_; i++) {
1991 QuickCheckDetails::Position* pos = positions(i);
1992 QuickCheckDetails::Position* other_pos = other->positions(i);
1993 if (pos->mask != other_pos->mask ||
1994 pos->value != other_pos->value ||
1995 !other_pos->determines_perfectly) {
1996 // Our mask-compare operation will be approximate unless we have the
1997 // exact same operation on both sides of the alternation.
1998 pos->determines_perfectly = false;
1999 }
2000 pos->mask &= other_pos->mask;
2001 pos->value &= pos->mask;
2002 other_pos->value &= pos->mask;
2003 uc16 differing_bits = (pos->value ^ other_pos->value);
2004 pos->mask &= ~differing_bits;
2005 pos->value &= pos->mask;
2006 }
2007}
2008
2009
ager@chromium.org32912102009-01-16 10:38:43 +00002010class VisitMarker {
2011 public:
2012 explicit VisitMarker(NodeInfo* info) : info_(info) {
2013 ASSERT(!info->visited);
2014 info->visited = true;
2015 }
2016 ~VisitMarker() {
2017 info_->visited = false;
2018 }
2019 private:
2020 NodeInfo* info_;
2021};
2022
2023
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002024void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2025 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002026 int characters_filled_in,
2027 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002028 if (body_can_be_zero_length_ || info()->visited) return;
2029 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002030 return ChoiceNode::GetQuickCheckDetails(details,
2031 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002032 characters_filled_in,
2033 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002034}
2035
2036
2037void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2038 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002039 int characters_filled_in,
2040 bool not_at_start) {
2041 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002042 int choice_count = alternatives_->length();
2043 ASSERT(choice_count > 0);
2044 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2045 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002046 characters_filled_in,
2047 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002048 for (int i = 1; i < choice_count; i++) {
2049 QuickCheckDetails new_details(details->characters());
2050 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002051 node->GetQuickCheckDetails(&new_details, compiler,
2052 characters_filled_in,
2053 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002054 // Here we merge the quick match details of the two branches.
2055 details->Merge(&new_details, characters_filled_in);
2056 }
2057}
2058
2059
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002060// Check for [0-9A-Z_a-z].
2061static void EmitWordCheck(RegExpMacroAssembler* assembler,
2062 Label* word,
2063 Label* non_word,
2064 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002065 if (assembler->CheckSpecialCharacterClass(
2066 fall_through_on_word ? 'w' : 'W',
2067 fall_through_on_word ? non_word : word)) {
2068 // Optimized implementation available.
2069 return;
2070 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002071 assembler->CheckCharacterGT('z', non_word);
2072 assembler->CheckCharacterLT('0', non_word);
2073 assembler->CheckCharacterGT('a' - 1, word);
2074 assembler->CheckCharacterLT('9' + 1, word);
2075 assembler->CheckCharacterLT('A', non_word);
2076 assembler->CheckCharacterLT('Z' + 1, word);
2077 if (fall_through_on_word) {
2078 assembler->CheckNotCharacter('_', non_word);
2079 } else {
2080 assembler->CheckCharacter('_', word);
2081 }
2082}
2083
2084
2085// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2086// that matches newline or the start of input).
2087static void EmitHat(RegExpCompiler* compiler,
2088 RegExpNode* on_success,
2089 Trace* trace) {
2090 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2091 // We will be loading the previous character into the current character
2092 // register.
2093 Trace new_trace(*trace);
2094 new_trace.InvalidateCurrentCharacter();
2095
2096 Label ok;
2097 if (new_trace.cp_offset() == 0) {
2098 // The start of input counts as a newline in this context, so skip to
2099 // ok if we are at the start.
2100 assembler->CheckAtStart(&ok);
2101 }
2102 // We already checked that we are not at the start of input so it must be
2103 // OK to load the previous character.
2104 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2105 new_trace.backtrack(),
2106 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002107 if (!assembler->CheckSpecialCharacterClass('n',
2108 new_trace.backtrack())) {
2109 // Newline means \n, \r, 0x2028 or 0x2029.
2110 if (!compiler->ascii()) {
2111 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2112 }
2113 assembler->CheckCharacter('\n', &ok);
2114 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002115 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002116 assembler->Bind(&ok);
2117 on_success->Emit(compiler, &new_trace);
2118}
2119
2120
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002121// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2122// when we know whether the next character must be a word character or not.
2123static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2124 RegExpCompiler* compiler,
2125 RegExpNode* on_success,
2126 Trace* trace) {
2127 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2128 Label done;
2129
2130 Trace new_trace(*trace);
2131
2132 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2133 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2134 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2135
2136 // Check whether previous character was a word character.
2137 switch (trace->at_start()) {
2138 case Trace::TRUE:
2139 if (expect_word_character) {
2140 assembler->GoTo(on_non_word);
2141 }
2142 break;
2143 case Trace::UNKNOWN:
2144 ASSERT_EQ(0, trace->cp_offset());
2145 assembler->CheckAtStart(on_non_word);
2146 // Fall through.
2147 case Trace::FALSE:
2148 int prev_char_offset = trace->cp_offset() - 1;
2149 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2150 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2151 // We may or may not have loaded the previous character.
2152 new_trace.InvalidateCurrentCharacter();
2153 }
2154
2155 assembler->Bind(&done);
2156
2157 on_success->Emit(compiler, &new_trace);
2158}
2159
2160
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002161// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2162static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2163 RegExpCompiler* compiler,
2164 RegExpNode* on_success,
2165 Trace* trace) {
2166 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2167 Label before_non_word;
2168 Label before_word;
2169 if (trace->characters_preloaded() != 1) {
2170 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2171 }
2172 // Fall through on non-word.
2173 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2174
2175 // We will be loading the previous character into the current character
2176 // register.
2177 Trace new_trace(*trace);
2178 new_trace.InvalidateCurrentCharacter();
2179
2180 Label ok;
2181 Label* boundary;
2182 Label* not_boundary;
2183 if (type == AssertionNode::AT_BOUNDARY) {
2184 boundary = &ok;
2185 not_boundary = new_trace.backtrack();
2186 } else {
2187 not_boundary = &ok;
2188 boundary = new_trace.backtrack();
2189 }
2190
2191 // Next character is not a word character.
2192 assembler->Bind(&before_non_word);
2193 if (new_trace.cp_offset() == 0) {
2194 // The start of input counts as a non-word character, so the question is
2195 // decided if we are at the start.
2196 assembler->CheckAtStart(not_boundary);
2197 }
2198 // We already checked that we are not at the start of input so it must be
2199 // OK to load the previous character.
2200 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2201 &ok, // Unused dummy label in this call.
2202 false);
2203 // Fall through on non-word.
2204 EmitWordCheck(assembler, boundary, not_boundary, false);
2205 assembler->GoTo(not_boundary);
2206
2207 // Next character is a word character.
2208 assembler->Bind(&before_word);
2209 if (new_trace.cp_offset() == 0) {
2210 // The start of input counts as a non-word character, so the question is
2211 // decided if we are at the start.
2212 assembler->CheckAtStart(boundary);
2213 }
2214 // We already checked that we are not at the start of input so it must be
2215 // OK to load the previous character.
2216 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2217 &ok, // Unused dummy label in this call.
2218 false);
2219 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2220 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2221
2222 assembler->Bind(&ok);
2223
2224 on_success->Emit(compiler, &new_trace);
2225}
2226
2227
iposva@chromium.org245aa852009-02-10 00:49:54 +00002228void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2229 RegExpCompiler* compiler,
2230 int filled_in,
2231 bool not_at_start) {
2232 if (type_ == AT_START && not_at_start) {
2233 details->set_cannot_match();
2234 return;
2235 }
2236 return on_success()->GetQuickCheckDetails(details,
2237 compiler,
2238 filled_in,
2239 not_at_start);
2240}
2241
2242
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002243void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2244 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2245 switch (type_) {
2246 case AT_END: {
2247 Label ok;
2248 assembler->CheckPosition(trace->cp_offset(), &ok);
2249 assembler->GoTo(trace->backtrack());
2250 assembler->Bind(&ok);
2251 break;
2252 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002253 case AT_START: {
2254 if (trace->at_start() == Trace::FALSE) {
2255 assembler->GoTo(trace->backtrack());
2256 return;
2257 }
2258 if (trace->at_start() == Trace::UNKNOWN) {
2259 assembler->CheckNotAtStart(trace->backtrack());
2260 Trace at_start_trace = *trace;
2261 at_start_trace.set_at_start(true);
2262 on_success()->Emit(compiler, &at_start_trace);
2263 return;
2264 }
2265 }
2266 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002267 case AFTER_NEWLINE:
2268 EmitHat(compiler, on_success(), trace);
2269 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002270 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002271 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002272 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2273 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002274 }
2275 case AFTER_WORD_CHARACTER:
2276 case AFTER_NONWORD_CHARACTER: {
2277 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2278 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002279 }
2280 on_success()->Emit(compiler, trace);
2281}
2282
2283
ager@chromium.org381abbb2009-02-25 13:23:22 +00002284static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2285 if (quick_check == NULL) return false;
2286 if (offset >= quick_check->characters()) return false;
2287 return quick_check->positions(offset)->determines_perfectly;
2288}
2289
2290
2291static void UpdateBoundsCheck(int index, int* checked_up_to) {
2292 if (index > *checked_up_to) {
2293 *checked_up_to = index;
2294 }
2295}
2296
2297
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002298// We call this repeatedly to generate code for each pass over the text node.
2299// The passes are in increasing order of difficulty because we hope one
2300// of the first passes will fail in which case we are saved the work of the
2301// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2302// we will check the '%' in the first pass, the case independent 'a' in the
2303// second pass and the character class in the last pass.
2304//
2305// The passes are done from right to left, so for example to test for /bar/
2306// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2307// and then a 'b' with offset 0. This means we can avoid the end-of-input
2308// bounds check most of the time. In the example we only need to check for
2309// end-of-input when loading the putative 'r'.
2310//
2311// A slight complication involves the fact that the first character may already
2312// be fetched into a register by the previous node. In this case we want to
2313// do the test for that character first. We do this in separate passes. The
2314// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2315// pass has been performed then subsequent passes will have true in
2316// first_element_checked to indicate that that character does not need to be
2317// checked again.
2318//
ager@chromium.org32912102009-01-16 10:38:43 +00002319// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002320// contain an AlternativeGeneration object. In this AlternativeGeneration
2321// object we can see details of any quick check that was already passed in
2322// order to get to the code we are now generating. The quick check can involve
2323// loading characters, which means we do not need to recheck the bounds
2324// up to the limit the quick check already checked. In addition the quick
2325// check can have involved a mask and compare operation which may simplify
2326// or obviate the need for further checks at some character positions.
2327void TextNode::TextEmitPass(RegExpCompiler* compiler,
2328 TextEmitPassType pass,
2329 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002330 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002331 bool first_element_checked,
2332 int* checked_up_to) {
2333 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2334 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002335 Label* backtrack = trace->backtrack();
2336 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002337 int element_count = elms_->length();
2338 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2339 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002340 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002341 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002342 Vector<const uc16> quarks = elm.data.u_atom->data();
2343 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2344 if (first_element_checked && i == 0 && j == 0) continue;
2345 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2346 EmitCharacterFunction* emit_function = NULL;
2347 switch (pass) {
2348 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002349 ASSERT(ascii);
2350 if (quarks[j] > String::kMaxAsciiCharCode) {
2351 assembler->GoTo(backtrack);
2352 return;
2353 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002354 break;
2355 case NON_LETTER_CHARACTER_MATCH:
2356 emit_function = &EmitAtomNonLetter;
2357 break;
2358 case SIMPLE_CHARACTER_MATCH:
2359 emit_function = &EmitSimpleCharacter;
2360 break;
2361 case CASE_CHARACTER_MATCH:
2362 emit_function = &EmitAtomLetter;
2363 break;
2364 default:
2365 break;
2366 }
2367 if (emit_function != NULL) {
2368 bool bound_checked = emit_function(compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002369 quarks[j],
2370 backtrack,
2371 cp_offset + j,
2372 *checked_up_to < cp_offset + j,
2373 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002374 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002375 }
2376 }
2377 } else {
2378 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002379 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002380 if (first_element_checked && i == 0) continue;
2381 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002382 RegExpCharacterClass* cc = elm.data.u_char_class;
2383 EmitCharClass(assembler,
2384 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002385 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002386 backtrack,
2387 cp_offset,
2388 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002389 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002390 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002391 }
2392 }
2393 }
2394}
2395
2396
2397int TextNode::Length() {
2398 TextElement elm = elms_->last();
2399 ASSERT(elm.cp_offset >= 0);
2400 if (elm.type == TextElement::ATOM) {
2401 return elm.cp_offset + elm.data.u_atom->data().length();
2402 } else {
2403 return elm.cp_offset + 1;
2404 }
2405}
2406
2407
ager@chromium.org381abbb2009-02-25 13:23:22 +00002408bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2409 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2410 if (ignore_case) {
2411 return pass == SIMPLE_CHARACTER_MATCH;
2412 } else {
2413 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2414 }
2415}
2416
2417
ager@chromium.org8bb60582008-12-11 12:02:20 +00002418// This generates the code to match a text node. A text node can contain
2419// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002420// way) and character classes. For efficiency we do not do this in a single
2421// pass from left to right. Instead we pass over the text node several times,
2422// emitting code for some character positions every time. See the comment on
2423// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002424void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002425 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002426 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002427 ASSERT(limit_result == CONTINUE);
2428
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002429 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2430 compiler->SetRegExpTooBig();
2431 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002432 }
2433
2434 if (compiler->ascii()) {
2435 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002436 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002437 }
2438
2439 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002440 int bound_checked_to = trace->cp_offset() - 1;
2441 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002442
2443 // If a character is preloaded into the current character register then
2444 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002445 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002446 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2447 if (!SkipPass(pass, compiler->ignore_case())) {
2448 TextEmitPass(compiler,
2449 static_cast<TextEmitPassType>(pass),
2450 true,
2451 trace,
2452 false,
2453 &bound_checked_to);
2454 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002455 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002456 first_elt_done = true;
2457 }
2458
ager@chromium.org381abbb2009-02-25 13:23:22 +00002459 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2460 if (!SkipPass(pass, compiler->ignore_case())) {
2461 TextEmitPass(compiler,
2462 static_cast<TextEmitPassType>(pass),
2463 false,
2464 trace,
2465 first_elt_done,
2466 &bound_checked_to);
2467 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002468 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002469
ager@chromium.org32912102009-01-16 10:38:43 +00002470 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002471 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002472 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002473 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002474 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002475}
2476
2477
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002478void Trace::InvalidateCurrentCharacter() {
2479 characters_preloaded_ = 0;
2480}
2481
2482
2483void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002484 ASSERT(by > 0);
2485 // We don't have an instruction for shifting the current character register
2486 // down or for using a shifted value for anything so lets just forget that
2487 // we preloaded any characters into it.
2488 characters_preloaded_ = 0;
2489 // Adjust the offsets of the quick check performed information. This
2490 // information is used to find out what we already determined about the
2491 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002492 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002493 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002494 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2495 compiler->SetRegExpTooBig();
2496 cp_offset_ = 0;
2497 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002498 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002499}
2500
2501
ager@chromium.org38e4c712009-11-11 09:11:58 +00002502void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002503 int element_count = elms_->length();
2504 for (int i = 0; i < element_count; i++) {
2505 TextElement elm = elms_->at(i);
2506 if (elm.type == TextElement::CHAR_CLASS) {
2507 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002508 // None of the standard character classses is different in the case
2509 // independent case and it slows us down if we don't know that.
2510 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002511 ZoneList<CharacterRange>* ranges = cc->ranges();
2512 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002513 for (int j = 0; j < range_count; j++) {
2514 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002515 }
2516 }
2517 }
2518}
2519
2520
ager@chromium.org8bb60582008-12-11 12:02:20 +00002521int TextNode::GreedyLoopTextLength() {
2522 TextElement elm = elms_->at(elms_->length() - 1);
2523 if (elm.type == TextElement::CHAR_CLASS) {
2524 return elm.cp_offset + 1;
2525 } else {
2526 return elm.cp_offset + elm.data.u_atom->data().length();
2527 }
2528}
2529
2530
2531// Finds the fixed match length of a sequence of nodes that goes from
2532// this alternative and back to this choice node. If there are variable
2533// length nodes or other complications in the way then return a sentinel
2534// value indicating that a greedy loop cannot be constructed.
2535int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2536 int length = 0;
2537 RegExpNode* node = alternative->node();
2538 // Later we will generate code for all these text nodes using recursion
2539 // so we have to limit the max number.
2540 int recursion_depth = 0;
2541 while (node != this) {
2542 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2543 return kNodeIsTooComplexForGreedyLoops;
2544 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002545 int node_length = node->GreedyLoopTextLength();
2546 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2547 return kNodeIsTooComplexForGreedyLoops;
2548 }
2549 length += node_length;
2550 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2551 node = seq_node->on_success();
2552 }
2553 return length;
2554}
2555
2556
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002557void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2558 ASSERT_EQ(loop_node_, NULL);
2559 AddAlternative(alt);
2560 loop_node_ = alt.node();
2561}
2562
2563
2564void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2565 ASSERT_EQ(continue_node_, NULL);
2566 AddAlternative(alt);
2567 continue_node_ = alt.node();
2568}
2569
2570
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002571void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002572 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002573 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002574 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2575 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2576 // Update the counter-based backtracking info on the stack. This is an
2577 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002578 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002579 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002580 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002581 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002582 }
ager@chromium.org32912102009-01-16 10:38:43 +00002583 ASSERT(trace->stop_node() == NULL);
2584 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002585 trace->Flush(compiler, this);
2586 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002587 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002588 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002589}
2590
2591
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002592int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002593 int preload_characters = EatsAtLeast(4, 0);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002594 if (compiler->macro_assembler()->CanReadUnaligned()) {
2595 bool ascii = compiler->ascii();
2596 if (ascii) {
2597 if (preload_characters > 4) preload_characters = 4;
2598 // We can't preload 3 characters because there is no machine instruction
2599 // to do that. We can't just load 4 because we could be reading
2600 // beyond the end of the string, which could cause a memory fault.
2601 if (preload_characters == 3) preload_characters = 2;
2602 } else {
2603 if (preload_characters > 2) preload_characters = 2;
2604 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002605 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002606 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002607 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002608 return preload_characters;
2609}
2610
2611
2612// This class is used when generating the alternatives in a choice node. It
2613// records the way the alternative is being code generated.
2614class AlternativeGeneration: public Malloced {
2615 public:
2616 AlternativeGeneration()
2617 : possible_success(),
2618 expects_preload(false),
2619 after(),
2620 quick_check_details() { }
2621 Label possible_success;
2622 bool expects_preload;
2623 Label after;
2624 QuickCheckDetails quick_check_details;
2625};
2626
2627
2628// Creates a list of AlternativeGenerations. If the list has a reasonable
2629// size then it is on the stack, otherwise the excess is on the heap.
2630class AlternativeGenerationList {
2631 public:
2632 explicit AlternativeGenerationList(int count)
2633 : alt_gens_(count) {
2634 for (int i = 0; i < count && i < kAFew; i++) {
2635 alt_gens_.Add(a_few_alt_gens_ + i);
2636 }
2637 for (int i = kAFew; i < count; i++) {
2638 alt_gens_.Add(new AlternativeGeneration());
2639 }
2640 }
2641 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002642 for (int i = kAFew; i < alt_gens_.length(); i++) {
2643 delete alt_gens_[i];
2644 alt_gens_[i] = NULL;
2645 }
2646 }
2647
2648 AlternativeGeneration* at(int i) {
2649 return alt_gens_[i];
2650 }
2651 private:
2652 static const int kAFew = 10;
2653 ZoneList<AlternativeGeneration*> alt_gens_;
2654 AlternativeGeneration a_few_alt_gens_[kAFew];
2655};
2656
2657
2658/* Code generation for choice nodes.
2659 *
2660 * We generate quick checks that do a mask and compare to eliminate a
2661 * choice. If the quick check succeeds then it jumps to the continuation to
2662 * do slow checks and check subsequent nodes. If it fails (the common case)
2663 * it falls through to the next choice.
2664 *
2665 * Here is the desired flow graph. Nodes directly below each other imply
2666 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2667 * 3 doesn't have a quick check so we have to call the slow check.
2668 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2669 * regexp continuation is generated directly after the Sn node, up to the
2670 * next GoTo if we decide to reuse some already generated code. Some
2671 * nodes expect preload_characters to be preloaded into the current
2672 * character register. R nodes do this preloading. Vertices are marked
2673 * F for failures and S for success (possible success in the case of quick
2674 * nodes). L, V, < and > are used as arrow heads.
2675 *
2676 * ----------> R
2677 * |
2678 * V
2679 * Q1 -----> S1
2680 * | S /
2681 * F| /
2682 * | F/
2683 * | /
2684 * | R
2685 * | /
2686 * V L
2687 * Q2 -----> S2
2688 * | S /
2689 * F| /
2690 * | F/
2691 * | /
2692 * | R
2693 * | /
2694 * V L
2695 * S3
2696 * |
2697 * F|
2698 * |
2699 * R
2700 * |
2701 * backtrack V
2702 * <----------Q4
2703 * \ F |
2704 * \ |S
2705 * \ F V
2706 * \-----S4
2707 *
2708 * For greedy loops we reverse our expectation and expect to match rather
2709 * than fail. Therefore we want the loop code to look like this (U is the
2710 * unwind code that steps back in the greedy loop). The following alternatives
2711 * look the same as above.
2712 * _____
2713 * / \
2714 * V |
2715 * ----------> S1 |
2716 * /| |
2717 * / |S |
2718 * F/ \_____/
2719 * /
2720 * |<-----------
2721 * | \
2722 * V \
2723 * Q2 ---> S2 \
2724 * | S / |
2725 * F| / |
2726 * | F/ |
2727 * | / |
2728 * | R |
2729 * | / |
2730 * F VL |
2731 * <------U |
2732 * back |S |
2733 * \______________/
2734 */
2735
2736
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002737void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002738 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2739 int choice_count = alternatives_->length();
2740#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002741 for (int i = 0; i < choice_count - 1; i++) {
2742 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002743 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002744 int guard_count = (guards == NULL) ? 0 : guards->length();
2745 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002746 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002747 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002748 }
2749#endif
2750
ager@chromium.org32912102009-01-16 10:38:43 +00002751 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002752 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002753 ASSERT(limit_result == CONTINUE);
2754
ager@chromium.org381abbb2009-02-25 13:23:22 +00002755 int new_flush_budget = trace->flush_budget() / choice_count;
2756 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2757 trace->Flush(compiler, this);
2758 return;
2759 }
2760
ager@chromium.org8bb60582008-12-11 12:02:20 +00002761 RecursionCheck rc(compiler);
2762
ager@chromium.org32912102009-01-16 10:38:43 +00002763 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002764
2765 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2766 bool greedy_loop = false;
2767 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002768 Trace counter_backtrack_trace;
2769 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002770 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2771
ager@chromium.org8bb60582008-12-11 12:02:20 +00002772 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2773 // Here we have special handling for greedy loops containing only text nodes
2774 // and other simple nodes. These are handled by pushing the current
2775 // position on the stack and then incrementing the current position each
2776 // time around the switch. On backtrack we decrement the current position
2777 // and check it against the pushed value. This avoids pushing backtrack
2778 // information for each iteration of the loop, which could take up a lot of
2779 // space.
2780 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002781 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002782 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002783 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002784 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002785 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002786 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002787 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002788 Label loop_label;
2789 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002790 greedy_match_trace.set_stop_node(this);
2791 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002792 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002793 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002794 }
2795
2796 Label second_choice; // For use in greedy matches.
2797 macro_assembler->Bind(&second_choice);
2798
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002799 int first_normal_choice = greedy_loop ? 1 : 0;
2800
2801 int preload_characters = CalculatePreloadCharacters(compiler);
2802 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002803 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002804 bool preload_has_checked_bounds = preload_is_current;
2805
2806 AlternativeGenerationList alt_gens(choice_count);
2807
ager@chromium.org8bb60582008-12-11 12:02:20 +00002808 // For now we just call all choices one after the other. The idea ultimately
2809 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002810 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002811 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002812 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002813 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002814 ZoneList<Guard*>* guards = alternative.guards();
2815 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002816 Trace new_trace(*current_trace);
2817 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002818 preload_characters :
2819 0);
2820 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002821 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002822 }
ager@chromium.org32912102009-01-16 10:38:43 +00002823 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002824 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002825 alt_gen->expects_preload = preload_is_current;
2826 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002827 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002828 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002829 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002830 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002831 preload_has_checked_bounds,
2832 &alt_gen->possible_success,
2833 &alt_gen->quick_check_details,
2834 i < choice_count - 1)) {
2835 // Quick check was generated for this choice.
2836 preload_is_current = true;
2837 preload_has_checked_bounds = true;
2838 // On the last choice in the ChoiceNode we generated the quick
2839 // check to fall through on possible success. So now we need to
2840 // generate the full check inline.
2841 if (i == choice_count - 1) {
2842 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002843 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2844 new_trace.set_characters_preloaded(preload_characters);
2845 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002846 generate_full_check_inline = true;
2847 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002848 } else if (alt_gen->quick_check_details.cannot_match()) {
2849 if (i == choice_count - 1 && !greedy_loop) {
2850 macro_assembler->GoTo(trace->backtrack());
2851 }
2852 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002853 } else {
2854 // No quick check was generated. Put the full code here.
2855 // If this is not the first choice then there could be slow checks from
2856 // previous cases that go here when they fail. There's no reason to
2857 // insist that they preload characters since the slow check we are about
2858 // to generate probably can't use it.
2859 if (i != first_normal_choice) {
2860 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002861 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002862 }
2863 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002864 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002865 }
2866 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002867 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002868 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002869 if (new_trace.actions() != NULL) {
2870 new_trace.set_flush_budget(new_flush_budget);
2871 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002872 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002873 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002874 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002875 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002876 preload_is_current = false;
2877 }
2878 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002879 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002880 if (greedy_loop) {
2881 macro_assembler->Bind(&greedy_loop_label);
2882 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002883 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002884 // Otherwise try the second priority at an earlier position.
2885 macro_assembler->AdvanceCurrentPosition(-text_length);
2886 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002887 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002888
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002889 // At this point we need to generate slow checks for the alternatives where
2890 // the quick check was inlined. We can recognize these because the associated
2891 // label was bound.
2892 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2893 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002894 Trace new_trace(*current_trace);
2895 // If there are actions to be flushed we have to limit how many times
2896 // they are flushed. Take the budget of the parent trace and distribute
2897 // it fairly amongst the children.
2898 if (new_trace.actions() != NULL) {
2899 new_trace.set_flush_budget(new_flush_budget);
2900 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002901 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002902 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002903 alternatives_->at(i),
2904 alt_gen,
2905 preload_characters,
2906 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002907 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002908}
2909
2910
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002911void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002912 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002913 GuardedAlternative alternative,
2914 AlternativeGeneration* alt_gen,
2915 int preload_characters,
2916 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002917 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002918
2919 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2920 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002921 Trace out_of_line_trace(*trace);
2922 out_of_line_trace.set_characters_preloaded(preload_characters);
2923 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002924 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002925 ZoneList<Guard*>* guards = alternative.guards();
2926 int guard_count = (guards == NULL) ? 0 : guards->length();
2927 if (next_expects_preload) {
2928 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00002929 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002930 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002931 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002932 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002933 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002934 macro_assembler->Bind(&reload_current_char);
2935 // Reload the current character, since the next quick check expects that.
2936 // We don't need to check bounds here because we only get into this
2937 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00002938 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002939 NULL,
2940 false,
2941 preload_characters);
2942 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002943 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00002944 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002945 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002946 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002947 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002948 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002949 }
2950}
2951
2952
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002953void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002954 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002955 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002956 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002957 ASSERT(limit_result == CONTINUE);
2958
2959 RecursionCheck rc(compiler);
2960
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002961 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002962 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00002963 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002964 new_capture(data_.u_position_register.reg,
2965 data_.u_position_register.is_capture,
2966 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002967 Trace new_trace = *trace;
2968 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002969 on_success()->Emit(compiler, &new_trace);
2970 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002971 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002972 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002973 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002974 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00002975 Trace new_trace = *trace;
2976 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002977 on_success()->Emit(compiler, &new_trace);
2978 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002979 }
2980 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002981 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002982 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00002983 Trace new_trace = *trace;
2984 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002985 on_success()->Emit(compiler, &new_trace);
2986 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002987 }
2988 case CLEAR_CAPTURES: {
2989 Trace::DeferredClearCaptures
2990 new_capture(Interval(data_.u_clear_captures.range_from,
2991 data_.u_clear_captures.range_to));
2992 Trace new_trace = *trace;
2993 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002994 on_success()->Emit(compiler, &new_trace);
2995 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002996 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002997 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002998 if (!trace->is_trivial()) {
2999 trace->Flush(compiler, this);
3000 } else {
3001 assembler->WriteCurrentPositionToRegister(
3002 data_.u_submatch.current_position_register, 0);
3003 assembler->WriteStackPointerToRegister(
3004 data_.u_submatch.stack_pointer_register);
3005 on_success()->Emit(compiler, trace);
3006 }
3007 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003008 case EMPTY_MATCH_CHECK: {
3009 int start_pos_reg = data_.u_empty_match_check.start_register;
3010 int stored_pos = 0;
3011 int rep_reg = data_.u_empty_match_check.repetition_register;
3012 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3013 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3014 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3015 // If we know we haven't advanced and there is no minimum we
3016 // can just backtrack immediately.
3017 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003018 } else if (know_dist && stored_pos < trace->cp_offset()) {
3019 // If we know we've advanced we can generate the continuation
3020 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003021 on_success()->Emit(compiler, trace);
3022 } else if (!trace->is_trivial()) {
3023 trace->Flush(compiler, this);
3024 } else {
3025 Label skip_empty_check;
3026 // If we have a minimum number of repetitions we check the current
3027 // number first and skip the empty check if it's not enough.
3028 if (has_minimum) {
3029 int limit = data_.u_empty_match_check.repetition_limit;
3030 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3031 }
3032 // If the match is empty we bail out, otherwise we fall through
3033 // to the on-success continuation.
3034 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3035 trace->backtrack());
3036 assembler->Bind(&skip_empty_check);
3037 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003038 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003039 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003040 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003041 case POSITIVE_SUBMATCH_SUCCESS: {
3042 if (!trace->is_trivial()) {
3043 trace->Flush(compiler, this);
3044 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003045 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003046 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003047 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003048 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003049 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003050 int clear_register_count = data_.u_submatch.clear_register_count;
3051 if (clear_register_count == 0) {
3052 on_success()->Emit(compiler, trace);
3053 return;
3054 }
3055 int clear_registers_from = data_.u_submatch.clear_register_from;
3056 Label clear_registers_backtrack;
3057 Trace new_trace = *trace;
3058 new_trace.set_backtrack(&clear_registers_backtrack);
3059 on_success()->Emit(compiler, &new_trace);
3060
3061 assembler->Bind(&clear_registers_backtrack);
3062 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3063 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3064
3065 ASSERT(trace->backtrack() == NULL);
3066 assembler->Backtrack();
3067 return;
3068 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003069 default:
3070 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003071 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003072}
3073
3074
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003075void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003076 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003077 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003078 trace->Flush(compiler, this);
3079 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003080 }
3081
ager@chromium.org32912102009-01-16 10:38:43 +00003082 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003083 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003084 ASSERT(limit_result == CONTINUE);
3085
3086 RecursionCheck rc(compiler);
3087
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003088 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003089 if (compiler->ignore_case()) {
3090 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3091 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003092 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003093 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003094 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003095 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003096}
3097
3098
3099// -------------------------------------------------------------------
3100// Dot/dotty output
3101
3102
3103#ifdef DEBUG
3104
3105
3106class DotPrinter: public NodeVisitor {
3107 public:
3108 explicit DotPrinter(bool ignore_case)
3109 : ignore_case_(ignore_case),
3110 stream_(&alloc_) { }
3111 void PrintNode(const char* label, RegExpNode* node);
3112 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003113 void PrintAttributes(RegExpNode* from);
3114 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003115 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003116#define DECLARE_VISIT(Type) \
3117 virtual void Visit##Type(Type##Node* that);
3118FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3119#undef DECLARE_VISIT
3120 private:
3121 bool ignore_case_;
3122 HeapStringAllocator alloc_;
3123 StringStream stream_;
3124};
3125
3126
3127void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3128 stream()->Add("digraph G {\n graph [label=\"");
3129 for (int i = 0; label[i]; i++) {
3130 switch (label[i]) {
3131 case '\\':
3132 stream()->Add("\\\\");
3133 break;
3134 case '"':
3135 stream()->Add("\"");
3136 break;
3137 default:
3138 stream()->Put(label[i]);
3139 break;
3140 }
3141 }
3142 stream()->Add("\"];\n");
3143 Visit(node);
3144 stream()->Add("}\n");
3145 printf("%s", *(stream()->ToCString()));
3146}
3147
3148
3149void DotPrinter::Visit(RegExpNode* node) {
3150 if (node->info()->visited) return;
3151 node->info()->visited = true;
3152 node->Accept(this);
3153}
3154
3155
3156void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003157 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3158 Visit(on_failure);
3159}
3160
3161
3162class TableEntryBodyPrinter {
3163 public:
3164 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3165 : stream_(stream), choice_(choice) { }
3166 void Call(uc16 from, DispatchTable::Entry entry) {
3167 OutSet* out_set = entry.out_set();
3168 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3169 if (out_set->Get(i)) {
3170 stream()->Add(" n%p:s%io%i -> n%p;\n",
3171 choice(),
3172 from,
3173 i,
3174 choice()->alternatives()->at(i).node());
3175 }
3176 }
3177 }
3178 private:
3179 StringStream* stream() { return stream_; }
3180 ChoiceNode* choice() { return choice_; }
3181 StringStream* stream_;
3182 ChoiceNode* choice_;
3183};
3184
3185
3186class TableEntryHeaderPrinter {
3187 public:
3188 explicit TableEntryHeaderPrinter(StringStream* stream)
3189 : first_(true), stream_(stream) { }
3190 void Call(uc16 from, DispatchTable::Entry entry) {
3191 if (first_) {
3192 first_ = false;
3193 } else {
3194 stream()->Add("|");
3195 }
3196 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3197 OutSet* out_set = entry.out_set();
3198 int priority = 0;
3199 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3200 if (out_set->Get(i)) {
3201 if (priority > 0) stream()->Add("|");
3202 stream()->Add("<s%io%i> %i", from, i, priority);
3203 priority++;
3204 }
3205 }
3206 stream()->Add("}}");
3207 }
3208 private:
3209 bool first_;
3210 StringStream* stream() { return stream_; }
3211 StringStream* stream_;
3212};
3213
3214
3215class AttributePrinter {
3216 public:
3217 explicit AttributePrinter(DotPrinter* out)
3218 : out_(out), first_(true) { }
3219 void PrintSeparator() {
3220 if (first_) {
3221 first_ = false;
3222 } else {
3223 out_->stream()->Add("|");
3224 }
3225 }
3226 void PrintBit(const char* name, bool value) {
3227 if (!value) return;
3228 PrintSeparator();
3229 out_->stream()->Add("{%s}", name);
3230 }
3231 void PrintPositive(const char* name, int value) {
3232 if (value < 0) return;
3233 PrintSeparator();
3234 out_->stream()->Add("{%s|%x}", name, value);
3235 }
3236 private:
3237 DotPrinter* out_;
3238 bool first_;
3239};
3240
3241
3242void DotPrinter::PrintAttributes(RegExpNode* that) {
3243 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3244 "margin=0.1, fontsize=10, label=\"{",
3245 that);
3246 AttributePrinter printer(this);
3247 NodeInfo* info = that->info();
3248 printer.PrintBit("NI", info->follows_newline_interest);
3249 printer.PrintBit("WI", info->follows_word_interest);
3250 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003251 Label* label = that->label();
3252 if (label->is_bound())
3253 printer.PrintPositive("@", label->pos());
3254 stream()->Add("}\"];\n");
3255 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3256 "arrowhead=none];\n", that, that);
3257}
3258
3259
3260static const bool kPrintDispatchTable = false;
3261void DotPrinter::VisitChoice(ChoiceNode* that) {
3262 if (kPrintDispatchTable) {
3263 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3264 TableEntryHeaderPrinter header_printer(stream());
3265 that->GetTable(ignore_case_)->ForEach(&header_printer);
3266 stream()->Add("\"]\n", that);
3267 PrintAttributes(that);
3268 TableEntryBodyPrinter body_printer(stream(), that);
3269 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003270 } else {
3271 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3272 for (int i = 0; i < that->alternatives()->length(); i++) {
3273 GuardedAlternative alt = that->alternatives()->at(i);
3274 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3275 }
3276 }
3277 for (int i = 0; i < that->alternatives()->length(); i++) {
3278 GuardedAlternative alt = that->alternatives()->at(i);
3279 alt.node()->Accept(this);
3280 }
3281}
3282
3283
3284void DotPrinter::VisitText(TextNode* that) {
3285 stream()->Add(" n%p [label=\"", that);
3286 for (int i = 0; i < that->elements()->length(); i++) {
3287 if (i > 0) stream()->Add(" ");
3288 TextElement elm = that->elements()->at(i);
3289 switch (elm.type) {
3290 case TextElement::ATOM: {
3291 stream()->Add("'%w'", elm.data.u_atom->data());
3292 break;
3293 }
3294 case TextElement::CHAR_CLASS: {
3295 RegExpCharacterClass* node = elm.data.u_char_class;
3296 stream()->Add("[");
3297 if (node->is_negated())
3298 stream()->Add("^");
3299 for (int j = 0; j < node->ranges()->length(); j++) {
3300 CharacterRange range = node->ranges()->at(j);
3301 stream()->Add("%k-%k", range.from(), range.to());
3302 }
3303 stream()->Add("]");
3304 break;
3305 }
3306 default:
3307 UNREACHABLE();
3308 }
3309 }
3310 stream()->Add("\", shape=box, peripheries=2];\n");
3311 PrintAttributes(that);
3312 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3313 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003314}
3315
3316
3317void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3318 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3319 that,
3320 that->start_register(),
3321 that->end_register());
3322 PrintAttributes(that);
3323 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3324 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003325}
3326
3327
3328void DotPrinter::VisitEnd(EndNode* that) {
3329 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3330 PrintAttributes(that);
3331}
3332
3333
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003334void DotPrinter::VisitAssertion(AssertionNode* that) {
3335 stream()->Add(" n%p [", that);
3336 switch (that->type()) {
3337 case AssertionNode::AT_END:
3338 stream()->Add("label=\"$\", shape=septagon");
3339 break;
3340 case AssertionNode::AT_START:
3341 stream()->Add("label=\"^\", shape=septagon");
3342 break;
3343 case AssertionNode::AT_BOUNDARY:
3344 stream()->Add("label=\"\\b\", shape=septagon");
3345 break;
3346 case AssertionNode::AT_NON_BOUNDARY:
3347 stream()->Add("label=\"\\B\", shape=septagon");
3348 break;
3349 case AssertionNode::AFTER_NEWLINE:
3350 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3351 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003352 case AssertionNode::AFTER_WORD_CHARACTER:
3353 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3354 break;
3355 case AssertionNode::AFTER_NONWORD_CHARACTER:
3356 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3357 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003358 }
3359 stream()->Add("];\n");
3360 PrintAttributes(that);
3361 RegExpNode* successor = that->on_success();
3362 stream()->Add(" n%p -> n%p;\n", that, successor);
3363 Visit(successor);
3364}
3365
3366
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003367void DotPrinter::VisitAction(ActionNode* that) {
3368 stream()->Add(" n%p [", that);
3369 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003370 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003371 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3372 that->data_.u_store_register.reg,
3373 that->data_.u_store_register.value);
3374 break;
3375 case ActionNode::INCREMENT_REGISTER:
3376 stream()->Add("label=\"$%i++\", shape=octagon",
3377 that->data_.u_increment_register.reg);
3378 break;
3379 case ActionNode::STORE_POSITION:
3380 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3381 that->data_.u_position_register.reg);
3382 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003383 case ActionNode::BEGIN_SUBMATCH:
3384 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3385 that->data_.u_submatch.current_position_register);
3386 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003387 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003388 stream()->Add("label=\"escape\", shape=septagon");
3389 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003390 case ActionNode::EMPTY_MATCH_CHECK:
3391 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3392 that->data_.u_empty_match_check.start_register,
3393 that->data_.u_empty_match_check.repetition_register,
3394 that->data_.u_empty_match_check.repetition_limit);
3395 break;
3396 case ActionNode::CLEAR_CAPTURES: {
3397 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3398 that->data_.u_clear_captures.range_from,
3399 that->data_.u_clear_captures.range_to);
3400 break;
3401 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003402 }
3403 stream()->Add("];\n");
3404 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003405 RegExpNode* successor = that->on_success();
3406 stream()->Add(" n%p -> n%p;\n", that, successor);
3407 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003408}
3409
3410
3411class DispatchTableDumper {
3412 public:
3413 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3414 void Call(uc16 key, DispatchTable::Entry entry);
3415 StringStream* stream() { return stream_; }
3416 private:
3417 StringStream* stream_;
3418};
3419
3420
3421void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3422 stream()->Add("[%k-%k]: {", key, entry.to());
3423 OutSet* set = entry.out_set();
3424 bool first = true;
3425 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3426 if (set->Get(i)) {
3427 if (first) {
3428 first = false;
3429 } else {
3430 stream()->Add(", ");
3431 }
3432 stream()->Add("%i", i);
3433 }
3434 }
3435 stream()->Add("}\n");
3436}
3437
3438
3439void DispatchTable::Dump() {
3440 HeapStringAllocator alloc;
3441 StringStream stream(&alloc);
3442 DispatchTableDumper dumper(&stream);
3443 tree()->ForEach(&dumper);
3444 OS::PrintError("%s", *stream.ToCString());
3445}
3446
3447
3448void RegExpEngine::DotPrint(const char* label,
3449 RegExpNode* node,
3450 bool ignore_case) {
3451 DotPrinter printer(ignore_case);
3452 printer.PrintNode(label, node);
3453}
3454
3455
3456#endif // DEBUG
3457
3458
3459// -------------------------------------------------------------------
3460// Tree to graph conversion
3461
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003462static const int kSpaceRangeCount = 20;
3463static const int kSpaceRangeAsciiCount = 4;
3464static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3465 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3466 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3467
3468static const int kWordRangeCount = 8;
3469static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3470 '_', 'a', 'z' };
3471
3472static const int kDigitRangeCount = 2;
3473static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3474
3475static const int kLineTerminatorRangeCount = 6;
3476static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3477 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003478
3479RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003480 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003481 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3482 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003483 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003484}
3485
3486
3487RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003488 RegExpNode* on_success) {
3489 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003490}
3491
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003492static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3493 const uc16* special_class,
3494 int length) {
3495 ASSERT(ranges->length() != 0);
3496 ASSERT(length != 0);
3497 ASSERT(special_class[0] != 0);
3498 if (ranges->length() != (length >> 1) + 1) {
3499 return false;
3500 }
3501 CharacterRange range = ranges->at(0);
3502 if (range.from() != 0) {
3503 return false;
3504 }
3505 for (int i = 0; i < length; i += 2) {
3506 if (special_class[i] != (range.to() + 1)) {
3507 return false;
3508 }
3509 range = ranges->at((i >> 1) + 1);
3510 if (special_class[i+1] != range.from() - 1) {
3511 return false;
3512 }
3513 }
3514 if (range.to() != 0xffff) {
3515 return false;
3516 }
3517 return true;
3518}
3519
3520
3521static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3522 const uc16* special_class,
3523 int length) {
3524 if (ranges->length() * 2 != length) {
3525 return false;
3526 }
3527 for (int i = 0; i < length; i += 2) {
3528 CharacterRange range = ranges->at(i >> 1);
3529 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3530 return false;
3531 }
3532 }
3533 return true;
3534}
3535
3536
3537bool RegExpCharacterClass::is_standard() {
3538 // TODO(lrn): Remove need for this function, by not throwing away information
3539 // along the way.
3540 if (is_negated_) {
3541 return false;
3542 }
3543 if (set_.is_standard()) {
3544 return true;
3545 }
3546 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3547 set_.set_standard_set_type('s');
3548 return true;
3549 }
3550 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3551 set_.set_standard_set_type('S');
3552 return true;
3553 }
3554 if (CompareInverseRanges(set_.ranges(),
3555 kLineTerminatorRanges,
3556 kLineTerminatorRangeCount)) {
3557 set_.set_standard_set_type('.');
3558 return true;
3559 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003560 if (CompareRanges(set_.ranges(),
3561 kLineTerminatorRanges,
3562 kLineTerminatorRangeCount)) {
3563 set_.set_standard_set_type('n');
3564 return true;
3565 }
3566 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3567 set_.set_standard_set_type('w');
3568 return true;
3569 }
3570 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3571 set_.set_standard_set_type('W');
3572 return true;
3573 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003574 return false;
3575}
3576
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003577
3578RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003579 RegExpNode* on_success) {
3580 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003581}
3582
3583
3584RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003585 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003586 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3587 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003588 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003589 for (int i = 0; i < length; i++) {
3590 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003591 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003592 result->AddAlternative(alternative);
3593 }
3594 return result;
3595}
3596
3597
3598RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003599 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003600 return ToNode(min(),
3601 max(),
3602 is_greedy(),
3603 body(),
3604 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003605 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003606}
3607
3608
3609RegExpNode* RegExpQuantifier::ToNode(int min,
3610 int max,
3611 bool is_greedy,
3612 RegExpTree* body,
3613 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003614 RegExpNode* on_success,
3615 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003616 // x{f, t} becomes this:
3617 //
3618 // (r++)<-.
3619 // | `
3620 // | (x)
3621 // v ^
3622 // (r=0)-->(?)---/ [if r < t]
3623 // |
3624 // [if r >= f] \----> ...
3625 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003626
3627 // 15.10.2.5 RepeatMatcher algorithm.
3628 // The parser has already eliminated the case where max is 0. In the case
3629 // where max_match is zero the parser has removed the quantifier if min was
3630 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3631
3632 // If we know that we cannot match zero length then things are a little
3633 // simpler since we don't need to make the special zero length match check
3634 // from step 2.1. If the min and max are small we can unroll a little in
3635 // this case.
3636 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3637 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3638 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003639 bool body_can_be_empty = (body->min_match() == 0);
3640 int body_start_reg = RegExpCompiler::kNoRegister;
3641 Interval capture_registers = body->CaptureRegisters();
3642 bool needs_capture_clearing = !capture_registers.is_empty();
3643 if (body_can_be_empty) {
3644 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003645 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003646 // Only unroll if there are no captures and the body can't be
3647 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003648 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3649 int new_max = (max == kInfinity) ? max : max - min;
3650 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003651 RegExpNode* answer = ToNode(
3652 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003653 // Unroll the forced matches from 0 to min. This can cause chains of
3654 // TextNodes (which the parser does not generate). These should be
3655 // combined if it turns out they hinder good code generation.
3656 for (int i = 0; i < min; i++) {
3657 answer = body->ToNode(compiler, answer);
3658 }
3659 return answer;
3660 }
3661 if (max <= kMaxUnrolledMaxMatches) {
3662 ASSERT(min == 0);
3663 // Unroll the optional matches up to max.
3664 RegExpNode* answer = on_success;
3665 for (int i = 0; i < max; i++) {
3666 ChoiceNode* alternation = new ChoiceNode(2);
3667 if (is_greedy) {
3668 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3669 answer)));
3670 alternation->AddAlternative(GuardedAlternative(on_success));
3671 } else {
3672 alternation->AddAlternative(GuardedAlternative(on_success));
3673 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3674 answer)));
3675 }
3676 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003677 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003678 }
3679 return answer;
3680 }
3681 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003682 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003683 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003684 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003685 int reg_ctr = needs_counter
3686 ? compiler->AllocateRegister()
3687 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003688 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003689 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003690 RegExpNode* loop_return = needs_counter
3691 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3692 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003693 if (body_can_be_empty) {
3694 // If the body can be empty we need to check if it was and then
3695 // backtrack.
3696 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3697 reg_ctr,
3698 min,
3699 loop_return);
3700 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003701 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003702 if (body_can_be_empty) {
3703 // If the body can be empty we need to store the start position
3704 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003705 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003706 }
3707 if (needs_capture_clearing) {
3708 // Before entering the body of this loop we need to clear captures.
3709 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3710 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003711 GuardedAlternative body_alt(body_node);
3712 if (has_max) {
3713 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3714 body_alt.AddGuard(body_guard);
3715 }
3716 GuardedAlternative rest_alt(on_success);
3717 if (has_min) {
3718 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3719 rest_alt.AddGuard(rest_guard);
3720 }
3721 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003722 center->AddLoopAlternative(body_alt);
3723 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003724 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003725 center->AddContinueAlternative(rest_alt);
3726 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003727 }
3728 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003729 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003730 } else {
3731 return center;
3732 }
3733}
3734
3735
3736RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003737 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003738 NodeInfo info;
3739 switch (type()) {
3740 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003741 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003742 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003743 return AssertionNode::AtStart(on_success);
3744 case BOUNDARY:
3745 return AssertionNode::AtBoundary(on_success);
3746 case NON_BOUNDARY:
3747 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003748 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003749 return AssertionNode::AtEnd(on_success);
3750 case END_OF_LINE: {
3751 // Compile $ in multiline regexps as an alternation with a positive
3752 // lookahead in one side and an end-of-input on the other side.
3753 // We need two registers for the lookahead.
3754 int stack_pointer_register = compiler->AllocateRegister();
3755 int position_register = compiler->AllocateRegister();
3756 // The ChoiceNode to distinguish between a newline and end-of-input.
3757 ChoiceNode* result = new ChoiceNode(2);
3758 // Create a newline atom.
3759 ZoneList<CharacterRange>* newline_ranges =
3760 new ZoneList<CharacterRange>(3);
3761 CharacterRange::AddClassEscape('n', newline_ranges);
3762 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3763 TextNode* newline_matcher = new TextNode(
3764 newline_atom,
3765 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3766 position_register,
3767 0, // No captures inside.
3768 -1, // Ignored if no captures.
3769 on_success));
3770 // Create an end-of-input matcher.
3771 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3772 stack_pointer_register,
3773 position_register,
3774 newline_matcher);
3775 // Add the two alternatives to the ChoiceNode.
3776 GuardedAlternative eol_alternative(end_of_line);
3777 result->AddAlternative(eol_alternative);
3778 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3779 result->AddAlternative(end_alternative);
3780 return result;
3781 }
3782 default:
3783 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003784 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003785 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003786}
3787
3788
3789RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003790 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003791 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3792 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003793 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003794}
3795
3796
3797RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003798 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003799 return on_success;
3800}
3801
3802
3803RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003804 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003805 int stack_pointer_register = compiler->AllocateRegister();
3806 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003807
3808 const int registers_per_capture = 2;
3809 const int register_of_first_capture = 2;
3810 int register_count = capture_count_ * registers_per_capture;
3811 int register_start =
3812 register_of_first_capture + capture_from_ * registers_per_capture;
3813
ager@chromium.org8bb60582008-12-11 12:02:20 +00003814 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003815 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003816 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003817 stack_pointer_register,
3818 position_register,
3819 body()->ToNode(
3820 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003821 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3822 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003823 register_count,
3824 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003825 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003826 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003827 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003828 // We use a ChoiceNode for a negative lookahead because it has most of
3829 // the characteristics we need. It has the body of the lookahead as its
3830 // first alternative and the expression after the lookahead of the second
3831 // alternative. If the first alternative succeeds then the
3832 // NegativeSubmatchSuccess will unwind the stack including everything the
3833 // choice node set up and backtrack. If the first alternative fails then
3834 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003835 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3836 // ChoiceNode that knows to ignore the first exit when calculating quick
3837 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003838 GuardedAlternative body_alt(
3839 body()->ToNode(
3840 compiler,
3841 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003842 position_register,
3843 register_count,
3844 register_start)));
3845 ChoiceNode* choice_node =
3846 new NegativeLookaheadChoiceNode(body_alt,
3847 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003848 return ActionNode::BeginSubmatch(stack_pointer_register,
3849 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003850 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003851 }
3852}
3853
3854
3855RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003856 RegExpNode* on_success) {
3857 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003858}
3859
3860
3861RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3862 int index,
3863 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003864 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003865 int start_reg = RegExpCapture::StartRegister(index);
3866 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003867 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003868 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003869 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003870}
3871
3872
3873RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003874 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003875 ZoneList<RegExpTree*>* children = nodes();
3876 RegExpNode* current = on_success;
3877 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003878 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003879 }
3880 return current;
3881}
3882
3883
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003884static void AddClass(const uc16* elmv,
3885 int elmc,
3886 ZoneList<CharacterRange>* ranges) {
3887 for (int i = 0; i < elmc; i += 2) {
3888 ASSERT(elmv[i] <= elmv[i + 1]);
3889 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3890 }
3891}
3892
3893
3894static void AddClassNegated(const uc16 *elmv,
3895 int elmc,
3896 ZoneList<CharacterRange>* ranges) {
3897 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003898 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003899 uc16 last = 0x0000;
3900 for (int i = 0; i < elmc; i += 2) {
3901 ASSERT(last <= elmv[i] - 1);
3902 ASSERT(elmv[i] <= elmv[i + 1]);
3903 ranges->Add(CharacterRange(last, elmv[i] - 1));
3904 last = elmv[i + 1] + 1;
3905 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003906 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003907}
3908
3909
3910void CharacterRange::AddClassEscape(uc16 type,
3911 ZoneList<CharacterRange>* ranges) {
3912 switch (type) {
3913 case 's':
3914 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3915 break;
3916 case 'S':
3917 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3918 break;
3919 case 'w':
3920 AddClass(kWordRanges, kWordRangeCount, ranges);
3921 break;
3922 case 'W':
3923 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3924 break;
3925 case 'd':
3926 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3927 break;
3928 case 'D':
3929 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3930 break;
3931 case '.':
3932 AddClassNegated(kLineTerminatorRanges,
3933 kLineTerminatorRangeCount,
3934 ranges);
3935 break;
3936 // This is not a character range as defined by the spec but a
3937 // convenient shorthand for a character class that matches any
3938 // character.
3939 case '*':
3940 ranges->Add(CharacterRange::Everything());
3941 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003942 // This is the set of characters matched by the $ and ^ symbols
3943 // in multiline mode.
3944 case 'n':
3945 AddClass(kLineTerminatorRanges,
3946 kLineTerminatorRangeCount,
3947 ranges);
3948 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003949 default:
3950 UNREACHABLE();
3951 }
3952}
3953
3954
3955Vector<const uc16> CharacterRange::GetWordBounds() {
3956 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3957}
3958
3959
3960class CharacterRangeSplitter {
3961 public:
3962 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3963 ZoneList<CharacterRange>** excluded)
3964 : included_(included),
3965 excluded_(excluded) { }
3966 void Call(uc16 from, DispatchTable::Entry entry);
3967
3968 static const int kInBase = 0;
3969 static const int kInOverlay = 1;
3970
3971 private:
3972 ZoneList<CharacterRange>** included_;
3973 ZoneList<CharacterRange>** excluded_;
3974};
3975
3976
3977void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3978 if (!entry.out_set()->Get(kInBase)) return;
3979 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3980 ? included_
3981 : excluded_;
3982 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3983 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3984}
3985
3986
3987void CharacterRange::Split(ZoneList<CharacterRange>* base,
3988 Vector<const uc16> overlay,
3989 ZoneList<CharacterRange>** included,
3990 ZoneList<CharacterRange>** excluded) {
3991 ASSERT_EQ(NULL, *included);
3992 ASSERT_EQ(NULL, *excluded);
3993 DispatchTable table;
3994 for (int i = 0; i < base->length(); i++)
3995 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3996 for (int i = 0; i < overlay.length(); i += 2) {
3997 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
3998 CharacterRangeSplitter::kInOverlay);
3999 }
4000 CharacterRangeSplitter callback(included, excluded);
4001 table.ForEach(&callback);
4002}
4003
4004
ager@chromium.org38e4c712009-11-11 09:11:58 +00004005static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4006 int bottom,
4007 int top);
4008
4009
4010void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4011 bool is_ascii) {
4012 uc16 bottom = from();
4013 uc16 top = to();
4014 if (is_ascii) {
4015 if (bottom > String::kMaxAsciiCharCode) return;
4016 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4017 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004018 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004019 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004020 // If this is a singleton we just expand the one character.
ager@chromium.org38e4c712009-11-11 09:11:58 +00004021 int length = uncanonicalize.get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004022 for (int i = 0; i < length; i++) {
4023 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004024 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004025 ranges->Add(CharacterRange::Singleton(chars[i]));
4026 }
4027 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004028 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004029 // If this is a range we expand the characters block by block,
4030 // expanding contiguous subranges (blocks) one at a time.
4031 // The approach is as follows. For a given start character we
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004032 // look up the remainder of the block that contains it (represented
4033 // by the end point), for instance we find 'z' if the character
4034 // is 'c'. A block is characterized by the property
4035 // that all characters uncanonicalize in the same way, except that
4036 // each entry in the result is incremented by the distance from the first
4037 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
4038 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
4039 // Once we've found the end point we look up its uncanonicalization
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004040 // and produce a range for each element. For instance for [c-f]
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004041 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004042 // add a range if it is not already contained in the input, so [c-f]
4043 // will be skipped but [C-F] will be added. If this range is not
4044 // completely contained in a block we do this for all the blocks
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004045 // covered by the range (handling characters that is not in a block
4046 // as a "singleton block").
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004047 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004048 int pos = bottom;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004049 while (pos < top) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004050 int length = canonrange.get(pos, '\0', range);
4051 uc16 block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004052 if (length == 0) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004053 block_end = pos;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004054 } else {
4055 ASSERT_EQ(1, length);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004056 block_end = range[0];
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004057 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004058 int end = (block_end > top) ? top : block_end;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004059 length = uncanonicalize.get(block_end, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004060 for (int i = 0; i < length; i++) {
4061 uc32 c = range[i];
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004062 uc16 range_from = c - (block_end - pos);
4063 uc16 range_to = c - (block_end - end);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004064 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004065 ranges->Add(CharacterRange(range_from, range_to));
4066 }
4067 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004068 pos = end + 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004069 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004070 }
4071}
4072
4073
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004074bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4075 ASSERT_NOT_NULL(ranges);
4076 int n = ranges->length();
4077 if (n <= 1) return true;
4078 int max = ranges->at(0).to();
4079 for (int i = 1; i < n; i++) {
4080 CharacterRange next_range = ranges->at(i);
4081 if (next_range.from() <= max + 1) return false;
4082 max = next_range.to();
4083 }
4084 return true;
4085}
4086
4087SetRelation CharacterRange::WordCharacterRelation(
4088 ZoneList<CharacterRange>* range) {
4089 ASSERT(IsCanonical(range));
4090 int i = 0; // Word character range index.
4091 int j = 0; // Argument range index.
4092 ASSERT_NE(0, kWordRangeCount);
4093 SetRelation result;
4094 if (range->length() == 0) {
4095 result.SetElementsInSecondSet();
4096 return result;
4097 }
4098 CharacterRange argument_range = range->at(0);
4099 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4100 while (i < kWordRangeCount && j < range->length()) {
4101 // Check the two ranges for the five cases:
4102 // - no overlap.
4103 // - partial overlap (there are elements in both ranges that isn't
4104 // in the other, and there are also elements that are in both).
4105 // - argument range entirely inside word range.
4106 // - word range entirely inside argument range.
4107 // - ranges are completely equal.
4108
4109 // First check for no overlap. The earlier range is not in the other set.
4110 if (argument_range.from() > word_range.to()) {
4111 // Ranges are disjoint. The earlier word range contains elements that
4112 // cannot be in the argument set.
4113 result.SetElementsInSecondSet();
4114 } else if (word_range.from() > argument_range.to()) {
4115 // Ranges are disjoint. The earlier argument range contains elements that
4116 // cannot be in the word set.
4117 result.SetElementsInFirstSet();
4118 } else if (word_range.from() <= argument_range.from() &&
4119 word_range.to() >= argument_range.from()) {
4120 result.SetElementsInBothSets();
4121 // argument range completely inside word range.
4122 if (word_range.from() < argument_range.from() ||
4123 word_range.to() > argument_range.from()) {
4124 result.SetElementsInSecondSet();
4125 }
4126 } else if (word_range.from() >= argument_range.from() &&
4127 word_range.to() <= argument_range.from()) {
4128 result.SetElementsInBothSets();
4129 result.SetElementsInFirstSet();
4130 } else {
4131 // There is overlap, and neither is a subrange of the other
4132 result.SetElementsInFirstSet();
4133 result.SetElementsInSecondSet();
4134 result.SetElementsInBothSets();
4135 }
4136 if (result.NonTrivialIntersection()) {
4137 // The result is as (im)precise as we can possibly make it.
4138 return result;
4139 }
4140 // Progress the range(s) with minimal to-character.
4141 uc16 word_to = word_range.to();
4142 uc16 argument_to = argument_range.to();
4143 if (argument_to <= word_to) {
4144 j++;
4145 if (j < range->length()) {
4146 argument_range = range->at(j);
4147 }
4148 }
4149 if (word_to <= argument_to) {
4150 i += 2;
4151 if (i < kWordRangeCount) {
4152 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4153 }
4154 }
4155 }
4156 // Check if anything wasn't compared in the loop.
4157 if (i < kWordRangeCount) {
4158 // word range contains something not in argument range.
4159 result.SetElementsInSecondSet();
4160 } else if (j < range->length()) {
4161 // Argument range contains something not in word range.
4162 result.SetElementsInFirstSet();
4163 }
4164
4165 return result;
4166}
4167
4168
ager@chromium.org38e4c712009-11-11 09:11:58 +00004169static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4170 int bottom,
4171 int top) {
4172 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4173 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4174 // this table is correct.
4175 // 0x0600 - 0x0fff
4176 // 0x1100 - 0x1cff
4177 // 0x2000 - 0x20ff
4178 // 0x2200 - 0x23ff
4179 // 0x2500 - 0x2bff
4180 // 0x2e00 - 0xa5ff
4181 // 0xa800 - 0xfaff
4182 // 0xfc00 - 0xfeff
4183 const int boundary_count = 18;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004184 int boundaries[] = {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004185 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4186 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4187
4188 // Special ASCII rule from spec can save us some work here.
4189 if (bottom == 0x80 && top == 0xffff) return;
4190
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004191 if (top <= boundaries[0]) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004192 CharacterRange range(bottom, top);
4193 range.AddCaseEquivalents(ranges, false);
4194 return;
4195 }
4196
4197 // Split up very large ranges. This helps remove ranges where there are no
4198 // case mappings.
4199 for (int i = 0; i < boundary_count; i++) {
4200 if (bottom < boundaries[i] && top >= boundaries[i]) {
4201 AddUncanonicals(ranges, bottom, boundaries[i] - 1);
4202 AddUncanonicals(ranges, boundaries[i], top);
4203 return;
4204 }
4205 }
4206
4207 // If we are completely in a zone with no case mappings then we are done.
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004208 for (int i = 0; i < boundary_count; i += 2) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004209 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4210#ifdef DEBUG
4211 for (int j = bottom; j <= top; j++) {
4212 unsigned current_char = j;
4213 int length = uncanonicalize.get(current_char, '\0', chars);
4214 for (int k = 0; k < length; k++) {
4215 ASSERT(chars[k] == current_char);
4216 }
4217 }
4218#endif
4219 return;
4220 }
4221 }
4222
4223 // Step through the range finding equivalent characters.
4224 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4225 for (int i = bottom; i <= top; i++) {
4226 int length = uncanonicalize.get(i, '\0', chars);
4227 for (int j = 0; j < length; j++) {
4228 uc32 chr = chars[j];
4229 if (chr != i && (chr < bottom || chr > top)) {
4230 characters->Add(chr);
4231 }
4232 }
4233 }
4234
4235 // Step through the equivalent characters finding simple ranges and
4236 // adding ranges to the character class.
4237 if (characters->length() > 0) {
4238 int new_from = characters->at(0);
4239 int new_to = new_from;
4240 for (int i = 1; i < characters->length(); i++) {
4241 int chr = characters->at(i);
4242 if (chr == new_to + 1) {
4243 new_to++;
4244 } else {
4245 if (new_to == new_from) {
4246 ranges->Add(CharacterRange::Singleton(new_from));
4247 } else {
4248 ranges->Add(CharacterRange(new_from, new_to));
4249 }
4250 new_from = new_to = chr;
4251 }
4252 }
4253 if (new_to == new_from) {
4254 ranges->Add(CharacterRange::Singleton(new_from));
4255 } else {
4256 ranges->Add(CharacterRange(new_from, new_to));
4257 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004258 }
4259}
4260
4261
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004262ZoneList<CharacterRange>* CharacterSet::ranges() {
4263 if (ranges_ == NULL) {
4264 ranges_ = new ZoneList<CharacterRange>(2);
4265 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4266 }
4267 return ranges_;
4268}
4269
4270
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004271// Move a number of elements in a zonelist to another position
4272// in the same list. Handles overlapping source and target areas.
4273static void MoveRanges(ZoneList<CharacterRange>* list,
4274 int from,
4275 int to,
4276 int count) {
4277 // Ranges are potentially overlapping.
4278 if (from < to) {
4279 for (int i = count - 1; i >= 0; i--) {
4280 list->at(to + i) = list->at(from + i);
4281 }
4282 } else {
4283 for (int i = 0; i < count; i++) {
4284 list->at(to + i) = list->at(from + i);
4285 }
4286 }
4287}
4288
4289
4290static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4291 int count,
4292 CharacterRange insert) {
4293 // Inserts a range into list[0..count[, which must be sorted
4294 // by from value and non-overlapping and non-adjacent, using at most
4295 // list[0..count] for the result. Returns the number of resulting
4296 // canonicalized ranges. Inserting a range may collapse existing ranges into
4297 // fewer ranges, so the return value can be anything in the range 1..count+1.
4298 uc16 from = insert.from();
4299 uc16 to = insert.to();
4300 int start_pos = 0;
4301 int end_pos = count;
4302 for (int i = count - 1; i >= 0; i--) {
4303 CharacterRange current = list->at(i);
4304 if (current.from() > to + 1) {
4305 end_pos = i;
4306 } else if (current.to() + 1 < from) {
4307 start_pos = i + 1;
4308 break;
4309 }
4310 }
4311
4312 // Inserted range overlaps, or is adjacent to, ranges at positions
4313 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4314 // not affected by the insertion.
4315 // If start_pos == end_pos, the range must be inserted before start_pos.
4316 // if start_pos < end_pos, the entire range from start_pos to end_pos
4317 // must be merged with the insert range.
4318
4319 if (start_pos == end_pos) {
4320 // Insert between existing ranges at position start_pos.
4321 if (start_pos < count) {
4322 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4323 }
4324 list->at(start_pos) = insert;
4325 return count + 1;
4326 }
4327 if (start_pos + 1 == end_pos) {
4328 // Replace single existing range at position start_pos.
4329 CharacterRange to_replace = list->at(start_pos);
4330 int new_from = Min(to_replace.from(), from);
4331 int new_to = Max(to_replace.to(), to);
4332 list->at(start_pos) = CharacterRange(new_from, new_to);
4333 return count;
4334 }
4335 // Replace a number of existing ranges from start_pos to end_pos - 1.
4336 // Move the remaining ranges down.
4337
4338 int new_from = Min(list->at(start_pos).from(), from);
4339 int new_to = Max(list->at(end_pos - 1).to(), to);
4340 if (end_pos < count) {
4341 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4342 }
4343 list->at(start_pos) = CharacterRange(new_from, new_to);
4344 return count - (end_pos - start_pos) + 1;
4345}
4346
4347
4348void CharacterSet::Canonicalize() {
4349 // Special/default classes are always considered canonical. The result
4350 // of calling ranges() will be sorted.
4351 if (ranges_ == NULL) return;
4352 CharacterRange::Canonicalize(ranges_);
4353}
4354
4355
4356void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4357 if (character_ranges->length() <= 1) return;
4358 // Check whether ranges are already canonical (increasing, non-overlapping,
4359 // non-adjacent).
4360 int n = character_ranges->length();
4361 int max = character_ranges->at(0).to();
4362 int i = 1;
4363 while (i < n) {
4364 CharacterRange current = character_ranges->at(i);
4365 if (current.from() <= max + 1) {
4366 break;
4367 }
4368 max = current.to();
4369 i++;
4370 }
4371 // Canonical until the i'th range. If that's all of them, we are done.
4372 if (i == n) return;
4373
4374 // The ranges at index i and forward are not canonicalized. Make them so by
4375 // doing the equivalent of insertion sort (inserting each into the previous
4376 // list, in order).
4377 // Notice that inserting a range can reduce the number of ranges in the
4378 // result due to combining of adjacent and overlapping ranges.
4379 int read = i; // Range to insert.
4380 int num_canonical = i; // Length of canonicalized part of list.
4381 do {
4382 num_canonical = InsertRangeInCanonicalList(character_ranges,
4383 num_canonical,
4384 character_ranges->at(read));
4385 read++;
4386 } while (read < n);
4387 character_ranges->Rewind(num_canonical);
4388
4389 ASSERT(CharacterRange::IsCanonical(character_ranges));
4390}
4391
4392
4393// Utility function for CharacterRange::Merge. Adds a range at the end of
4394// a canonicalized range list, if necessary merging the range with the last
4395// range of the list.
4396static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4397 if (set == NULL) return;
4398 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4399 int n = set->length();
4400 if (n > 0) {
4401 CharacterRange lastRange = set->at(n - 1);
4402 if (lastRange.to() == range.from() - 1) {
4403 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4404 return;
4405 }
4406 }
4407 set->Add(range);
4408}
4409
4410
4411static void AddRangeToSelectedSet(int selector,
4412 ZoneList<CharacterRange>* first_set,
4413 ZoneList<CharacterRange>* second_set,
4414 ZoneList<CharacterRange>* intersection_set,
4415 CharacterRange range) {
4416 switch (selector) {
4417 case kInsideFirst:
4418 AddRangeToSet(first_set, range);
4419 break;
4420 case kInsideSecond:
4421 AddRangeToSet(second_set, range);
4422 break;
4423 case kInsideBoth:
4424 AddRangeToSet(intersection_set, range);
4425 break;
4426 }
4427}
4428
4429
4430
4431void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4432 ZoneList<CharacterRange>* second_set,
4433 ZoneList<CharacterRange>* first_set_only_out,
4434 ZoneList<CharacterRange>* second_set_only_out,
4435 ZoneList<CharacterRange>* both_sets_out) {
4436 // Inputs are canonicalized.
4437 ASSERT(CharacterRange::IsCanonical(first_set));
4438 ASSERT(CharacterRange::IsCanonical(second_set));
4439 // Outputs are empty, if applicable.
4440 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4441 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4442 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4443
4444 // Merge sets by iterating through the lists in order of lowest "from" value,
4445 // and putting intervals into one of three sets.
4446
4447 if (first_set->length() == 0) {
4448 second_set_only_out->AddAll(*second_set);
4449 return;
4450 }
4451 if (second_set->length() == 0) {
4452 first_set_only_out->AddAll(*first_set);
4453 return;
4454 }
4455 // Indices into input lists.
4456 int i1 = 0;
4457 int i2 = 0;
4458 // Cache length of input lists.
4459 int n1 = first_set->length();
4460 int n2 = second_set->length();
4461 // Current range. May be invalid if state is kInsideNone.
4462 int from = 0;
4463 int to = -1;
4464 // Where current range comes from.
4465 int state = kInsideNone;
4466
4467 while (i1 < n1 || i2 < n2) {
4468 CharacterRange next_range;
4469 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004470 if (i2 == n2 ||
4471 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4472 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004473 next_range = first_set->at(i1++);
4474 range_source = kInsideFirst;
4475 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004476 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004477 next_range = second_set->at(i2++);
4478 range_source = kInsideSecond;
4479 }
4480 if (to < next_range.from()) {
4481 // Ranges disjoint: |current| |next|
4482 AddRangeToSelectedSet(state,
4483 first_set_only_out,
4484 second_set_only_out,
4485 both_sets_out,
4486 CharacterRange(from, to));
4487 from = next_range.from();
4488 to = next_range.to();
4489 state = range_source;
4490 } else {
4491 if (from < next_range.from()) {
4492 AddRangeToSelectedSet(state,
4493 first_set_only_out,
4494 second_set_only_out,
4495 both_sets_out,
4496 CharacterRange(from, next_range.from()-1));
4497 }
4498 if (to < next_range.to()) {
4499 // Ranges overlap: |current|
4500 // |next|
4501 AddRangeToSelectedSet(state | range_source,
4502 first_set_only_out,
4503 second_set_only_out,
4504 both_sets_out,
4505 CharacterRange(next_range.from(), to));
4506 from = to + 1;
4507 to = next_range.to();
4508 state = range_source;
4509 } else {
4510 // Range included: |current| , possibly ending at same character.
4511 // |next|
4512 AddRangeToSelectedSet(
4513 state | range_source,
4514 first_set_only_out,
4515 second_set_only_out,
4516 both_sets_out,
4517 CharacterRange(next_range.from(), next_range.to()));
4518 from = next_range.to() + 1;
4519 // If ranges end at same character, both ranges are consumed completely.
4520 if (next_range.to() == to) state = kInsideNone;
4521 }
4522 }
4523 }
4524 AddRangeToSelectedSet(state,
4525 first_set_only_out,
4526 second_set_only_out,
4527 both_sets_out,
4528 CharacterRange(from, to));
4529}
4530
4531
4532void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4533 ZoneList<CharacterRange>* negated_ranges) {
4534 ASSERT(CharacterRange::IsCanonical(ranges));
4535 ASSERT_EQ(0, negated_ranges->length());
4536 int range_count = ranges->length();
4537 uc16 from = 0;
4538 int i = 0;
4539 if (range_count > 0 && ranges->at(0).from() == 0) {
4540 from = ranges->at(0).to();
4541 i = 1;
4542 }
4543 while (i < range_count) {
4544 CharacterRange range = ranges->at(i);
4545 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4546 from = range.to();
4547 i++;
4548 }
4549 if (from < String::kMaxUC16CharCode) {
4550 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4551 }
4552}
4553
4554
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004555
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004556// -------------------------------------------------------------------
4557// Interest propagation
4558
4559
4560RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4561 for (int i = 0; i < siblings_.length(); i++) {
4562 RegExpNode* sibling = siblings_.Get(i);
4563 if (sibling->info()->Matches(info))
4564 return sibling;
4565 }
4566 return NULL;
4567}
4568
4569
4570RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4571 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004572 siblings_.Ensure(this);
4573 RegExpNode* result = TryGetSibling(info);
4574 if (result != NULL) return result;
4575 result = this->Clone();
4576 NodeInfo* new_info = result->info();
4577 new_info->ResetCompilationState();
4578 new_info->AddFromPreceding(info);
4579 AddSibling(result);
4580 *cloned = true;
4581 return result;
4582}
4583
4584
4585template <class C>
4586static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4587 NodeInfo full_info(*node->info());
4588 full_info.AddFromPreceding(info);
4589 bool cloned = false;
4590 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4591}
4592
4593
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004594// -------------------------------------------------------------------
4595// Splay tree
4596
4597
4598OutSet* OutSet::Extend(unsigned value) {
4599 if (Get(value))
4600 return this;
4601 if (successors() != NULL) {
4602 for (int i = 0; i < successors()->length(); i++) {
4603 OutSet* successor = successors()->at(i);
4604 if (successor->Get(value))
4605 return successor;
4606 }
4607 } else {
4608 successors_ = new ZoneList<OutSet*>(2);
4609 }
4610 OutSet* result = new OutSet(first_, remaining_);
4611 result->Set(value);
4612 successors()->Add(result);
4613 return result;
4614}
4615
4616
4617void OutSet::Set(unsigned value) {
4618 if (value < kFirstLimit) {
4619 first_ |= (1 << value);
4620 } else {
4621 if (remaining_ == NULL)
4622 remaining_ = new ZoneList<unsigned>(1);
4623 if (remaining_->is_empty() || !remaining_->Contains(value))
4624 remaining_->Add(value);
4625 }
4626}
4627
4628
4629bool OutSet::Get(unsigned value) {
4630 if (value < kFirstLimit) {
4631 return (first_ & (1 << value)) != 0;
4632 } else if (remaining_ == NULL) {
4633 return false;
4634 } else {
4635 return remaining_->Contains(value);
4636 }
4637}
4638
4639
4640const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4641const DispatchTable::Entry DispatchTable::Config::kNoValue;
4642
4643
4644void DispatchTable::AddRange(CharacterRange full_range, int value) {
4645 CharacterRange current = full_range;
4646 if (tree()->is_empty()) {
4647 // If this is the first range we just insert into the table.
4648 ZoneSplayTree<Config>::Locator loc;
4649 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4650 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4651 return;
4652 }
4653 // First see if there is a range to the left of this one that
4654 // overlaps.
4655 ZoneSplayTree<Config>::Locator loc;
4656 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4657 Entry* entry = &loc.value();
4658 // If we've found a range that overlaps with this one, and it
4659 // starts strictly to the left of this one, we have to fix it
4660 // because the following code only handles ranges that start on
4661 // or after the start point of the range we're adding.
4662 if (entry->from() < current.from() && entry->to() >= current.from()) {
4663 // Snap the overlapping range in half around the start point of
4664 // the range we're adding.
4665 CharacterRange left(entry->from(), current.from() - 1);
4666 CharacterRange right(current.from(), entry->to());
4667 // The left part of the overlapping range doesn't overlap.
4668 // Truncate the whole entry to be just the left part.
4669 entry->set_to(left.to());
4670 // The right part is the one that overlaps. We add this part
4671 // to the map and let the next step deal with merging it with
4672 // the range we're adding.
4673 ZoneSplayTree<Config>::Locator loc;
4674 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4675 loc.set_value(Entry(right.from(),
4676 right.to(),
4677 entry->out_set()));
4678 }
4679 }
4680 while (current.is_valid()) {
4681 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4682 (loc.value().from() <= current.to()) &&
4683 (loc.value().to() >= current.from())) {
4684 Entry* entry = &loc.value();
4685 // We have overlap. If there is space between the start point of
4686 // the range we're adding and where the overlapping range starts
4687 // then we have to add a range covering just that space.
4688 if (current.from() < entry->from()) {
4689 ZoneSplayTree<Config>::Locator ins;
4690 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4691 ins.set_value(Entry(current.from(),
4692 entry->from() - 1,
4693 empty()->Extend(value)));
4694 current.set_from(entry->from());
4695 }
4696 ASSERT_EQ(current.from(), entry->from());
4697 // If the overlapping range extends beyond the one we want to add
4698 // we have to snap the right part off and add it separately.
4699 if (entry->to() > current.to()) {
4700 ZoneSplayTree<Config>::Locator ins;
4701 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4702 ins.set_value(Entry(current.to() + 1,
4703 entry->to(),
4704 entry->out_set()));
4705 entry->set_to(current.to());
4706 }
4707 ASSERT(entry->to() <= current.to());
4708 // The overlapping range is now completely contained by the range
4709 // we're adding so we can just update it and move the start point
4710 // of the range we're adding just past it.
4711 entry->AddValue(value);
4712 // Bail out if the last interval ended at 0xFFFF since otherwise
4713 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004714 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004715 break;
4716 ASSERT(entry->to() + 1 > current.from());
4717 current.set_from(entry->to() + 1);
4718 } else {
4719 // There is no overlap so we can just add the range
4720 ZoneSplayTree<Config>::Locator ins;
4721 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4722 ins.set_value(Entry(current.from(),
4723 current.to(),
4724 empty()->Extend(value)));
4725 break;
4726 }
4727 }
4728}
4729
4730
4731OutSet* DispatchTable::Get(uc16 value) {
4732 ZoneSplayTree<Config>::Locator loc;
4733 if (!tree()->FindGreatestLessThan(value, &loc))
4734 return empty();
4735 Entry* entry = &loc.value();
4736 if (value <= entry->to())
4737 return entry->out_set();
4738 else
4739 return empty();
4740}
4741
4742
4743// -------------------------------------------------------------------
4744// Analysis
4745
4746
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004747void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004748 StackLimitCheck check;
4749 if (check.HasOverflowed()) {
4750 fail("Stack overflow");
4751 return;
4752 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004753 if (that->info()->been_analyzed || that->info()->being_analyzed)
4754 return;
4755 that->info()->being_analyzed = true;
4756 that->Accept(this);
4757 that->info()->being_analyzed = false;
4758 that->info()->been_analyzed = true;
4759}
4760
4761
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004762void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004763 // nothing to do
4764}
4765
4766
ager@chromium.org8bb60582008-12-11 12:02:20 +00004767void TextNode::CalculateOffsets() {
4768 int element_count = elements()->length();
4769 // Set up the offsets of the elements relative to the start. This is a fixed
4770 // quantity since a TextNode can only contain fixed-width things.
4771 int cp_offset = 0;
4772 for (int i = 0; i < element_count; i++) {
4773 TextElement& elm = elements()->at(i);
4774 elm.cp_offset = cp_offset;
4775 if (elm.type == TextElement::ATOM) {
4776 cp_offset += elm.data.u_atom->data().length();
4777 } else {
4778 cp_offset++;
4779 Vector<const uc16> quarks = elm.data.u_atom->data();
4780 }
4781 }
4782}
4783
4784
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004785void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004786 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004787 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004788 }
4789 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004790 if (!has_failed()) {
4791 that->CalculateOffsets();
4792 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004793}
4794
4795
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004796void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004797 RegExpNode* target = that->on_success();
4798 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004799 if (!has_failed()) {
4800 // If the next node is interested in what it follows then this node
4801 // has to be interested too so it can pass the information on.
4802 that->info()->AddFromFollowing(target->info());
4803 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004804}
4805
4806
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004807void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004808 NodeInfo* info = that->info();
4809 for (int i = 0; i < that->alternatives()->length(); i++) {
4810 RegExpNode* node = that->alternatives()->at(i).node();
4811 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004812 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004813 // Anything the following nodes need to know has to be known by
4814 // this node also, so it can pass it on.
4815 info->AddFromFollowing(node->info());
4816 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004817}
4818
4819
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004820void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4821 NodeInfo* info = that->info();
4822 for (int i = 0; i < that->alternatives()->length(); i++) {
4823 RegExpNode* node = that->alternatives()->at(i).node();
4824 if (node != that->loop_node()) {
4825 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004826 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004827 info->AddFromFollowing(node->info());
4828 }
4829 }
4830 // Check the loop last since it may need the value of this node
4831 // to get a correct result.
4832 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004833 if (!has_failed()) {
4834 info->AddFromFollowing(that->loop_node()->info());
4835 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004836}
4837
4838
4839void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004840 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004841}
4842
4843
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004844void Analysis::VisitAssertion(AssertionNode* that) {
4845 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004846 AssertionNode::AssertionNodeType type = that->type();
4847 if (type == AssertionNode::AT_BOUNDARY ||
4848 type == AssertionNode::AT_NON_BOUNDARY) {
4849 // Check if the following character is known to be a word character
4850 // or known to not be a word character.
4851 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4852
4853 CharacterRange::Canonicalize(following_chars);
4854
4855 SetRelation word_relation =
4856 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004857 if (word_relation.Disjoint()) {
4858 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004859 // Following character is definitely *not* a word character.
4860 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004861 AssertionNode::AFTER_WORD_CHARACTER :
4862 AssertionNode::AFTER_NONWORD_CHARACTER;
4863 that->set_type(type);
4864 } else if (word_relation.ContainedIn()) {
4865 // Following character is definitely a word character.
4866 type = (type == AssertionNode::AT_BOUNDARY) ?
4867 AssertionNode::AFTER_NONWORD_CHARACTER :
4868 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004869 that->set_type(type);
4870 }
4871 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004872}
4873
4874
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004875ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4876 if (first_character_set_ == NULL) {
4877 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4878 // If we can't find an exact solution within the budget, we
4879 // set the value to the set of every character, i.e., all characters
4880 // are possible.
4881 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4882 all_set->Add(CharacterRange::Everything());
4883 first_character_set_ = all_set;
4884 }
4885 }
4886 return first_character_set_;
4887}
4888
4889
4890int RegExpNode::ComputeFirstCharacterSet(int budget) {
4891 // Default behavior is to not be able to determine the first character.
4892 return kComputeFirstCharacterSetFail;
4893}
4894
4895
4896int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
4897 budget--;
4898 if (budget >= 0) {
4899 // Find loop min-iteration. It's the value of the guarded choice node
4900 // with a GEQ guard, if any.
4901 int min_repetition = 0;
4902
4903 for (int i = 0; i <= 1; i++) {
4904 GuardedAlternative alternative = alternatives()->at(i);
4905 ZoneList<Guard*>* guards = alternative.guards();
4906 if (guards != NULL && guards->length() > 0) {
4907 Guard* guard = guards->at(0);
4908 if (guard->op() == Guard::GEQ) {
4909 min_repetition = guard->value();
4910 break;
4911 }
4912 }
4913 }
4914
4915 budget = loop_node()->ComputeFirstCharacterSet(budget);
4916 if (budget >= 0) {
4917 ZoneList<CharacterRange>* character_set =
4918 loop_node()->first_character_set();
4919 if (body_can_be_zero_length() || min_repetition == 0) {
4920 budget = continue_node()->ComputeFirstCharacterSet(budget);
4921 if (budget < 0) return budget;
4922 ZoneList<CharacterRange>* body_set =
4923 continue_node()->first_character_set();
4924 ZoneList<CharacterRange>* union_set =
4925 new ZoneList<CharacterRange>(Max(character_set->length(),
4926 body_set->length()));
4927 CharacterRange::Merge(character_set,
4928 body_set,
4929 union_set,
4930 union_set,
4931 union_set);
4932 character_set = union_set;
4933 }
4934 set_first_character_set(character_set);
4935 }
4936 }
4937 return budget;
4938}
4939
4940
4941int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
4942 budget--;
4943 if (budget >= 0) {
4944 GuardedAlternative successor = this->alternatives()->at(1);
4945 RegExpNode* successor_node = successor.node();
4946 budget = successor_node->ComputeFirstCharacterSet(budget);
4947 if (budget >= 0) {
4948 set_first_character_set(successor_node->first_character_set());
4949 }
4950 }
4951 return budget;
4952}
4953
4954
4955// The first character set of an EndNode is unknowable. Just use the
4956// default implementation that fails and returns all characters as possible.
4957
4958
4959int AssertionNode::ComputeFirstCharacterSet(int budget) {
4960 budget -= 1;
4961 if (budget >= 0) {
4962 switch (type_) {
4963 case AT_END: {
4964 set_first_character_set(new ZoneList<CharacterRange>(0));
4965 break;
4966 }
4967 case AT_START:
4968 case AT_BOUNDARY:
4969 case AT_NON_BOUNDARY:
4970 case AFTER_NEWLINE:
4971 case AFTER_NONWORD_CHARACTER:
4972 case AFTER_WORD_CHARACTER: {
4973 ASSERT_NOT_NULL(on_success());
4974 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00004975 if (budget >= 0) {
4976 set_first_character_set(on_success()->first_character_set());
4977 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004978 break;
4979 }
4980 }
4981 }
4982 return budget;
4983}
4984
4985
4986int ActionNode::ComputeFirstCharacterSet(int budget) {
4987 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
4988 budget--;
4989 if (budget >= 0) {
4990 ASSERT_NOT_NULL(on_success());
4991 budget = on_success()->ComputeFirstCharacterSet(budget);
4992 if (budget >= 0) {
4993 set_first_character_set(on_success()->first_character_set());
4994 }
4995 }
4996 return budget;
4997}
4998
4999
5000int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5001 // We don't know anything about the first character of a backreference
5002 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005003 // The potential first characters are the first characters of the capture,
5004 // and the first characters of the on_success node, depending on whether the
5005 // capture can be empty and whether it is known to be participating or known
5006 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005007 return kComputeFirstCharacterSetFail;
5008}
5009
5010
5011int TextNode::ComputeFirstCharacterSet(int budget) {
5012 budget--;
5013 if (budget >= 0) {
5014 ASSERT_NE(0, elements()->length());
5015 TextElement text = elements()->at(0);
5016 if (text.type == TextElement::ATOM) {
5017 RegExpAtom* atom = text.data.u_atom;
5018 ASSERT_NE(0, atom->length());
5019 uc16 first_char = atom->data()[0];
5020 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5021 range->Add(CharacterRange(first_char, first_char));
5022 set_first_character_set(range);
5023 } else {
5024 ASSERT(text.type == TextElement::CHAR_CLASS);
5025 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005026 ZoneList<CharacterRange>* ranges = char_class->ranges();
5027 // TODO(lrn): Canonicalize ranges when they are created
5028 // instead of waiting until now.
5029 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005030 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005031 int length = ranges->length();
5032 int new_length = length + 1;
5033 if (length > 0) {
5034 if (ranges->at(0).from() == 0) new_length--;
5035 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5036 new_length--;
5037 }
5038 }
5039 ZoneList<CharacterRange>* negated_ranges =
5040 new ZoneList<CharacterRange>(new_length);
5041 CharacterRange::Negate(ranges, negated_ranges);
5042 set_first_character_set(negated_ranges);
5043 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005044 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005045 }
5046 }
5047 }
5048 return budget;
5049}
5050
5051
5052
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005053// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005054// Dispatch table construction
5055
5056
5057void DispatchTableConstructor::VisitEnd(EndNode* that) {
5058 AddRange(CharacterRange::Everything());
5059}
5060
5061
5062void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5063 node->set_being_calculated(true);
5064 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5065 for (int i = 0; i < alternatives->length(); i++) {
5066 set_choice_index(i);
5067 alternatives->at(i).node()->Accept(this);
5068 }
5069 node->set_being_calculated(false);
5070}
5071
5072
5073class AddDispatchRange {
5074 public:
5075 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5076 : constructor_(constructor) { }
5077 void Call(uc32 from, DispatchTable::Entry entry);
5078 private:
5079 DispatchTableConstructor* constructor_;
5080};
5081
5082
5083void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5084 CharacterRange range(from, entry.to());
5085 constructor_->AddRange(range);
5086}
5087
5088
5089void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5090 if (node->being_calculated())
5091 return;
5092 DispatchTable* table = node->GetTable(ignore_case_);
5093 AddDispatchRange adder(this);
5094 table->ForEach(&adder);
5095}
5096
5097
5098void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5099 // TODO(160): Find the node that we refer back to and propagate its start
5100 // set back to here. For now we just accept anything.
5101 AddRange(CharacterRange::Everything());
5102}
5103
5104
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005105void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5106 RegExpNode* target = that->on_success();
5107 target->Accept(this);
5108}
5109
5110
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005111static int CompareRangeByFrom(const CharacterRange* a,
5112 const CharacterRange* b) {
5113 return Compare<uc16>(a->from(), b->from());
5114}
5115
5116
5117void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5118 ranges->Sort(CompareRangeByFrom);
5119 uc16 last = 0;
5120 for (int i = 0; i < ranges->length(); i++) {
5121 CharacterRange range = ranges->at(i);
5122 if (last < range.from())
5123 AddRange(CharacterRange(last, range.from() - 1));
5124 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005125 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005126 return;
5127 } else {
5128 last = range.to() + 1;
5129 }
5130 }
5131 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005132 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005133}
5134
5135
5136void DispatchTableConstructor::VisitText(TextNode* that) {
5137 TextElement elm = that->elements()->at(0);
5138 switch (elm.type) {
5139 case TextElement::ATOM: {
5140 uc16 c = elm.data.u_atom->data()[0];
5141 AddRange(CharacterRange(c, c));
5142 break;
5143 }
5144 case TextElement::CHAR_CLASS: {
5145 RegExpCharacterClass* tree = elm.data.u_char_class;
5146 ZoneList<CharacterRange>* ranges = tree->ranges();
5147 if (tree->is_negated()) {
5148 AddInverse(ranges);
5149 } else {
5150 for (int i = 0; i < ranges->length(); i++)
5151 AddRange(ranges->at(i));
5152 }
5153 break;
5154 }
5155 default: {
5156 UNIMPLEMENTED();
5157 }
5158 }
5159}
5160
5161
5162void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005163 RegExpNode* target = that->on_success();
5164 target->Accept(this);
5165}
5166
5167
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005168RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5169 bool ignore_case,
5170 bool is_multiline,
5171 Handle<String> pattern,
5172 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005173 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005174 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005175 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005176 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005177 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005178 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005179 0,
5180 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005181 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005182 RegExpNode* node = captured_body;
5183 if (!data->tree->IsAnchored()) {
5184 // Add a .*? at the beginning, outside the body capture, unless
5185 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005186 RegExpNode* loop_node =
5187 RegExpQuantifier::ToNode(0,
5188 RegExpTree::kInfinity,
5189 false,
5190 new RegExpCharacterClass('*'),
5191 &compiler,
5192 captured_body,
5193 data->contains_anchor);
5194
5195 if (data->contains_anchor) {
5196 // Unroll loop once, to take care of the case that might start
5197 // at the start of input.
5198 ChoiceNode* first_step_node = new ChoiceNode(2);
5199 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5200 first_step_node->AddAlternative(GuardedAlternative(
5201 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5202 node = first_step_node;
5203 } else {
5204 node = loop_node;
5205 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005206 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005207 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005208 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005209 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005210 if (analysis.has_failed()) {
5211 const char* error_message = analysis.error_message();
5212 return CompilationResult(error_message);
5213 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005214
5215 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005216
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005217 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005218#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005219 // Native regexp implementation.
5220
5221 NativeRegExpMacroAssembler::Mode mode =
5222 is_ascii ? NativeRegExpMacroAssembler::ASCII
5223 : NativeRegExpMacroAssembler::UC16;
5224
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005225#if V8_TARGET_ARCH_IA32
5226 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5227#elif V8_TARGET_ARCH_X64
5228 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5229#elif V8_TARGET_ARCH_ARM
5230 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005231#endif
5232
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005233#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005234 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005235 EmbeddedVector<byte, 1024> codes;
5236 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005237#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005238
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005239 return compiler.Assemble(&macro_assembler,
5240 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005241 data->capture_count,
5242 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005243}
5244
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005245
5246int OffsetsVector::static_offsets_vector_[
5247 OffsetsVector::kStaticOffsetsVectorSize];
5248
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005249}} // namespace v8::internal