blob: dfd9ef64fd50413d1afb7eb0d341fc8a8493da5e [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
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000046#ifdef V8_NATIVE_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);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000125 RegExpCompileData parse_result;
126 FlatStringReader reader(pattern);
127 if (!ParseRegExp(&reader, flags.is_multiline(), &parse_result)) {
128 // Throw an exception if we fail to parse the pattern.
129 ThrowRegExpException(re,
130 pattern,
131 parse_result.error,
132 "malformed_regexp");
133 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000134 }
135
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000136 if (parse_result.simple && !flags.is_ignore_case()) {
137 // Parse-tree is a single atom that is equal to the pattern.
138 AtomCompile(re, pattern, flags, pattern);
139 } else if (parse_result.tree->IsAtom() &&
140 !flags.is_ignore_case() &&
141 parse_result.capture_count == 0) {
142 RegExpAtom* atom = parse_result.tree->AsAtom();
143 Vector<const uc16> atom_pattern = atom->data();
144 Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern);
145 AtomCompile(re, pattern, flags, atom_string);
146 } else {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000147 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000148 }
149 ASSERT(re->data()->IsFixedArray());
150 // Compilation succeeded so the data is set on the regexp
151 // and we can store it in the cache.
152 Handle<FixedArray> data(FixedArray::cast(re->data()));
153 CompilationCache::PutRegExp(pattern, flags, data);
154
155 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000156}
157
158
159Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
160 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000161 int index,
162 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000163 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000164 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000165 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000166 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000167 Handle<Object> result =
168 IrregexpExec(regexp, subject, index, last_match_info);
ager@chromium.org6f10e412009-02-13 10:11:16 +0000169 ASSERT(!result.is_null() || Top::has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000170 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000171 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000172 default:
173 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000174 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000175 }
176}
177
178
ager@chromium.org8bb60582008-12-11 12:02:20 +0000179// RegExp Atom implementation: Simple string search using indexOf.
180
181
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000182void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
183 Handle<String> pattern,
184 JSRegExp::Flags flags,
185 Handle<String> match_pattern) {
186 Factory::SetRegExpAtomData(re,
187 JSRegExp::ATOM,
188 pattern,
189 flags,
190 match_pattern);
191}
192
193
194static void SetAtomLastCapture(FixedArray* array,
195 String* subject,
196 int from,
197 int to) {
198 NoHandleAllocation no_handles;
199 RegExpImpl::SetLastCaptureCount(array, 2);
200 RegExpImpl::SetLastSubject(array, subject);
201 RegExpImpl::SetLastInput(array, subject);
202 RegExpImpl::SetCapture(array, 0, from);
203 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000204}
205
206
207Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
208 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000209 int index,
210 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000211 Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex)));
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000212
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000213 uint32_t start_index = index;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000214
ager@chromium.org7c537e22008-10-16 08:43:32 +0000215 int value = Runtime::StringMatch(subject, needle, start_index);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000216 if (value == -1) return Factory::null_value();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000217 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000218
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000219 {
220 NoHandleAllocation no_handles;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000221 FixedArray* array = FixedArray::cast(last_match_info->elements());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000222 SetAtomLastCapture(array, *subject, value, value + needle->length());
223 }
224 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000225}
226
227
ager@chromium.org8bb60582008-12-11 12:02:20 +0000228// Irregexp implementation.
229
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000230// Ensures that the regexp object contains a compiled version of the
231// source for either ASCII or non-ASCII strings.
232// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000233// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000234// If compilation fails, an exception is thrown and this function
235// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000236bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000237 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000238#ifdef V8_NATIVE_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000239 if (compiled_code->IsCode()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000240#else // ! V8_NATIVE_REGEXP (RegExp interpreter code)
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000241 if (compiled_code->IsByteArray()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000242#endif
243 return CompileIrregexp(re, is_ascii);
244}
ager@chromium.org8bb60582008-12-11 12:02:20 +0000245
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000246
247bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000248 // Compile the RegExp.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000249 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000250 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
251 if (entry->IsJSObject()) {
252 // If it's a JSObject, a previous compilation failed and threw this object.
253 // Re-throw the object without trying again.
254 Top::Throw(entry);
255 return false;
256 }
257 ASSERT(entry->IsTheHole());
ager@chromium.org8bb60582008-12-11 12:02:20 +0000258
259 JSRegExp::Flags flags = re->GetFlags();
260
261 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000262 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000263 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000264 }
265
266 RegExpCompileData compile_data;
267 FlatStringReader reader(pattern);
268 if (!ParseRegExp(&reader, flags.is_multiline(), &compile_data)) {
269 // Throw an exception if we fail to parse the pattern.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000270 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000271 ThrowRegExpException(re,
272 pattern,
273 compile_data.error,
274 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000275 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000276 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000277 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000278 RegExpEngine::Compile(&compile_data,
279 flags.is_ignore_case(),
280 flags.is_multiline(),
281 pattern,
282 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000283 if (result.error_message != NULL) {
284 // Unable to compile regexp.
285 Handle<JSArray> array = Factory::NewJSArray(2);
286 SetElement(array, 0, pattern);
287 SetElement(array,
288 1,
289 Factory::NewStringFromUtf8(CStrVector(result.error_message)));
290 Handle<Object> regexp_err =
291 Factory::NewSyntaxError("malformed_regexp", array);
292 Top::Throw(*regexp_err);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000293 re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000294 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000295 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000296
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000297 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
298 data->set(JSRegExp::code_index(is_ascii), result.code);
299 int register_max = IrregexpMaxRegisterCount(*data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000300 if (result.num_registers > register_max) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000301 SetIrregexpMaxRegisterCount(*data, result.num_registers);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000302 }
303
304 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000305}
306
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000307
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000308int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
309 return Smi::cast(
310 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000311}
312
313
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000314void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
315 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000316}
317
318
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000319int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
320 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000321}
322
323
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000324int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
325 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000326}
327
328
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000329ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000330 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000331}
332
333
334Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000335 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000336}
337
338
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000339void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
340 Handle<String> pattern,
341 JSRegExp::Flags flags,
342 int capture_count) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000343 // Initialize compiled code entries to null.
344 Factory::SetRegExpIrregexpData(re,
345 JSRegExp::IRREGEXP,
346 pattern,
347 flags,
348 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000349}
350
351
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000352int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
353 Handle<String> subject) {
354 if (!subject->IsFlat()) {
355 FlattenString(subject);
356 }
357 bool is_ascii = subject->IsAsciiRepresentation();
358 if (!EnsureCompiledIrregexp(regexp, is_ascii)) {
359 return -1;
360 }
361#ifdef V8_NATIVE_REGEXP
362 // Native regexp only needs room to output captures. Registers are handled
363 // internally.
364 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
365#else // !V8_NATIVE_REGEXP
366 // Byte-code regexp needs space allocated for all its registers.
367 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
368#endif // V8_NATIVE_REGEXP
369}
370
371
372RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(Handle<JSRegExp> regexp,
373 Handle<String> subject,
374 int index,
375 Vector<int> output) {
376 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()));
377
378 ASSERT(index >= 0);
379 ASSERT(index <= subject->length());
380 ASSERT(subject->IsFlat());
381
382#ifdef V8_NATIVE_REGEXP
383 ASSERT(output.length() >=
384 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
385 do {
386 bool is_ascii = subject->IsAsciiRepresentation();
387 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii));
388 NativeRegExpMacroAssembler::Result res =
389 NativeRegExpMacroAssembler::Match(code,
390 subject,
391 output.start(),
392 output.length(),
393 index);
394 if (res != NativeRegExpMacroAssembler::RETRY) {
395 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
396 Top::has_pending_exception());
397 STATIC_ASSERT(
398 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
399 STATIC_ASSERT(
400 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
401 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
402 == RE_EXCEPTION);
403 return static_cast<IrregexpResult>(res);
404 }
405 // If result is RETRY, the string has changed representation, and we
406 // must restart from scratch.
407 // In this case, it means we must make sure we are prepared to handle
408 // the, potentially, differen subject (the string can switch between
409 // being internal and external, and even between being ASCII and UC16,
410 // but the characters are always the same).
411 IrregexpPrepare(regexp, subject);
412 } while (true);
413 UNREACHABLE();
414 return RE_EXCEPTION;
415#else // ndef V8_NATIVE_REGEXP
416
417 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
418 bool is_ascii = subject->IsAsciiRepresentation();
419 // We must have done EnsureCompiledIrregexp, so we can get the number of
420 // registers.
421 int* register_vector = output.start();
422 int number_of_capture_registers =
423 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
424 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
425 register_vector[i] = -1;
426 }
427 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii));
428
429 if (IrregexpInterpreter::Match(byte_codes,
430 subject,
431 register_vector,
432 index)) {
433 return RE_SUCCESS;
434 }
435 return RE_FAILURE;
436#endif // ndef V8_NATIVE_REGEXP
437}
438
439
ager@chromium.org41826e72009-03-30 13:30:57 +0000440Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000441 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000442 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000443 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000444 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000445
ager@chromium.org8bb60582008-12-11 12:02:20 +0000446 // Prepare space for the return values.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000447#ifndef V8_NATIVE_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000448#ifdef DEBUG
449 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000450 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000451 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
452 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
453 }
454#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000455#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000456 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
457 if (required_registers < 0) {
458 // Compiling failed with an exception.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000459 ASSERT(Top::has_pending_exception());
460 return Handle<Object>::null();
461 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000462
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000463 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000464
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000465 IrregexpResult res = IrregexpExecOnce(jsregexp,
466 subject,
467 previous_index,
468 Vector<int>(registers.vector(),
469 registers.length()));
470 if (res == RE_SUCCESS) {
471 int capture_register_count =
472 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
473 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
474 AssertNoAllocation no_gc;
475 int* register_vector = registers.vector();
476 FixedArray* array = FixedArray::cast(last_match_info->elements());
477 for (int i = 0; i < capture_register_count; i += 2) {
478 SetCapture(array, i, register_vector[i]);
479 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000480 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000481 SetLastCaptureCount(array, capture_register_count);
482 SetLastSubject(array, *subject);
483 SetLastInput(array, *subject);
484 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000485 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000486 if (res == RE_EXCEPTION) {
487 ASSERT(Top::has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000488 return Handle<Object>::null();
489 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000490 ASSERT(res == RE_FAILURE);
491 return Factory::null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000492}
493
494
495// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000496// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000497//
498// The Irregexp regular expression engine is intended to be a complete
499// implementation of ECMAScript regular expressions. It generates either
500// bytecodes or native code.
501
502// The Irregexp regexp engine is structured in three steps.
503// 1) The parser generates an abstract syntax tree. See ast.cc.
504// 2) From the AST a node network is created. The nodes are all
505// subclasses of RegExpNode. The nodes represent states when
506// executing a regular expression. Several optimizations are
507// performed on the node network.
508// 3) From the nodes we generate either byte codes or native code
509// that can actually execute the regular expression (perform
510// the search). The code generation step is described in more
511// detail below.
512
513// Code generation.
514//
515// The nodes are divided into four main categories.
516// * Choice nodes
517// These represent places where the regular expression can
518// match in more than one way. For example on entry to an
519// alternation (foo|bar) or a repetition (*, +, ? or {}).
520// * Action nodes
521// These represent places where some action should be
522// performed. Examples include recording the current position
523// in the input string to a register (in order to implement
524// captures) or other actions on register for example in order
525// to implement the counters needed for {} repetitions.
526// * Matching nodes
527// These attempt to match some element part of the input string.
528// Examples of elements include character classes, plain strings
529// or back references.
530// * End nodes
531// These are used to implement the actions required on finding
532// a successful match or failing to find a match.
533//
534// The code generated (whether as byte codes or native code) maintains
535// some state as it runs. This consists of the following elements:
536//
537// * The capture registers. Used for string captures.
538// * Other registers. Used for counters etc.
539// * The current position.
540// * The stack of backtracking information. Used when a matching node
541// fails to find a match and needs to try an alternative.
542//
543// Conceptual regular expression execution model:
544//
545// There is a simple conceptual model of regular expression execution
546// which will be presented first. The actual code generated is a more
547// efficient simulation of the simple conceptual model:
548//
549// * Choice nodes are implemented as follows:
550// For each choice except the last {
551// push current position
552// push backtrack code location
553// <generate code to test for choice>
554// backtrack code location:
555// pop current position
556// }
557// <generate code to test for last choice>
558//
559// * Actions nodes are generated as follows
560// <push affected registers on backtrack stack>
561// <generate code to perform action>
562// push backtrack code location
563// <generate code to test for following nodes>
564// backtrack code location:
565// <pop affected registers to restore their state>
566// <pop backtrack location from stack and go to it>
567//
568// * Matching nodes are generated as follows:
569// if input string matches at current position
570// update current position
571// <generate code to test for following nodes>
572// else
573// <pop backtrack location from stack and go to it>
574//
575// Thus it can be seen that the current position is saved and restored
576// by the choice nodes, whereas the registers are saved and restored by
577// by the action nodes that manipulate them.
578//
579// The other interesting aspect of this model is that nodes are generated
580// at the point where they are needed by a recursive call to Emit(). If
581// the node has already been code generated then the Emit() call will
582// generate a jump to the previously generated code instead. In order to
583// limit recursion it is possible for the Emit() function to put the node
584// on a work list for later generation and instead generate a jump. The
585// destination of the jump is resolved later when the code is generated.
586//
587// Actual regular expression code generation.
588//
589// Code generation is actually more complicated than the above. In order
590// to improve the efficiency of the generated code some optimizations are
591// performed
592//
593// * Choice nodes have 1-character lookahead.
594// A choice node looks at the following character and eliminates some of
595// the choices immediately based on that character. This is not yet
596// implemented.
597// * Simple greedy loops store reduced backtracking information.
598// A quantifier like /.*foo/m will greedily match the whole input. It will
599// then need to backtrack to a point where it can match "foo". The naive
600// implementation of this would push each character position onto the
601// backtracking stack, then pop them off one by one. This would use space
602// proportional to the length of the input string. However since the "."
603// can only match in one way and always has a constant length (in this case
604// of 1) it suffices to store the current position on the top of the stack
605// once. Matching now becomes merely incrementing the current position and
606// backtracking becomes decrementing the current position and checking the
607// result against the stored current position. This is faster and saves
608// space.
609// * The current state is virtualized.
610// This is used to defer expensive operations until it is clear that they
611// are needed and to generate code for a node more than once, allowing
612// specialized an efficient versions of the code to be created. This is
613// explained in the section below.
614//
615// Execution state virtualization.
616//
617// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000618// manipulation in an object called the Trace. The Trace object can record a
619// current position offset, an optional backtrack code location on the top of
620// the virtualized backtrack stack and some register changes. When a node is
621// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000622// will emit code to bring the actual state into line with the virtual state.
623// Avoiding flushing the state can postpone some work (eg updates of capture
624// registers). Postponing work can save time when executing the regular
625// expression since it may be found that the work never has to be done as a
626// failure to match can occur. In addition it is much faster to jump to a
627// known backtrack code location than it is to pop an unknown backtrack
628// location from the stack and jump there.
629//
ager@chromium.org32912102009-01-16 10:38:43 +0000630// The virtual state found in the Trace affects code generation. For example
631// the virtual state contains the difference between the actual current
632// position and the virtual current position, and matching code needs to use
633// this offset to attempt a match in the correct location of the input
634// string. Therefore code generated for a non-trivial trace is specialized
635// to that trace. The code generator therefore has the ability to generate
636// code for each node several times. In order to limit the size of the
637// generated code there is an arbitrary limit on how many specialized sets of
638// code may be generated for a given node. If the limit is reached, the
639// trace is flushed and a generic version of the code for a node is emitted.
640// This is subsequently used for that node. The code emitted for non-generic
641// trace is not recorded in the node and so it cannot currently be reused in
642// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000643
644
645void RegExpTree::AppendToText(RegExpText* text) {
646 UNREACHABLE();
647}
648
649
650void RegExpAtom::AppendToText(RegExpText* text) {
651 text->AddElement(TextElement::Atom(this));
652}
653
654
655void RegExpCharacterClass::AppendToText(RegExpText* text) {
656 text->AddElement(TextElement::CharClass(this));
657}
658
659
660void RegExpText::AppendToText(RegExpText* text) {
661 for (int i = 0; i < elements()->length(); i++)
662 text->AddElement(elements()->at(i));
663}
664
665
666TextElement TextElement::Atom(RegExpAtom* atom) {
667 TextElement result = TextElement(ATOM);
668 result.data.u_atom = atom;
669 return result;
670}
671
672
673TextElement TextElement::CharClass(
674 RegExpCharacterClass* char_class) {
675 TextElement result = TextElement(CHAR_CLASS);
676 result.data.u_char_class = char_class;
677 return result;
678}
679
680
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000681int TextElement::length() {
682 if (type == ATOM) {
683 return data.u_atom->length();
684 } else {
685 ASSERT(type == CHAR_CLASS);
686 return 1;
687 }
688}
689
690
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000691DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
692 if (table_ == NULL) {
693 table_ = new DispatchTable();
694 DispatchTableConstructor cons(table_, ignore_case);
695 cons.BuildTable(this);
696 }
697 return table_;
698}
699
700
701class RegExpCompiler {
702 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000703 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000704
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000705 int AllocateRegister() {
706 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
707 reg_exp_too_big_ = true;
708 return next_register_;
709 }
710 return next_register_++;
711 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000712
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000713 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
714 RegExpNode* start,
715 int capture_count,
716 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000717
718 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
719
720 static const int kImplementationOffset = 0;
721 static const int kNumberOfRegistersOffset = 0;
722 static const int kCodeOffset = 1;
723
724 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
725 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000726
727 static const int kMaxRecursion = 100;
728 inline int recursion_depth() { return recursion_depth_; }
729 inline void IncrementRecursionDepth() { recursion_depth_++; }
730 inline void DecrementRecursionDepth() { recursion_depth_--; }
731
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000732 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
733
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000734 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000735 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000736
ager@chromium.org32912102009-01-16 10:38:43 +0000737 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000738 private:
739 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000740 int next_register_;
741 List<RegExpNode*>* work_list_;
742 int recursion_depth_;
743 RegExpMacroAssembler* macro_assembler_;
744 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000745 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000746 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000747};
748
749
750class RecursionCheck {
751 public:
752 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
753 compiler->IncrementRecursionDepth();
754 }
755 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
756 private:
757 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000758};
759
760
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000761static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
762 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000763}
764
765
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000766// Attempts to compile the regexp using an Irregexp code generator. Returns
767// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000768RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000769 : next_register_(2 * (capture_count + 1)),
770 work_list_(NULL),
771 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000772 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000773 ascii_(ascii),
774 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000775 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000776 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000777}
778
779
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000780RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000781 RegExpMacroAssembler* macro_assembler,
782 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000783 int capture_count,
784 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000785#ifdef DEBUG
786 if (FLAG_trace_regexp_assembler)
787 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
788 else
789#endif
790 macro_assembler_ = macro_assembler;
791 List <RegExpNode*> work_list(0);
792 work_list_ = &work_list;
793 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000794 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000795 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000796 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000797 macro_assembler_->Bind(&fail);
798 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000799 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000800 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000801 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000802 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
803
ager@chromium.org8bb60582008-12-11 12:02:20 +0000804 Handle<Object> code = macro_assembler_->GetCode(pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000805
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000806 work_list_ = NULL;
807#ifdef DEBUG
808 if (FLAG_trace_regexp_assembler) {
809 delete macro_assembler_;
810 }
811#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000812 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000813}
814
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000815
ager@chromium.org32912102009-01-16 10:38:43 +0000816bool Trace::DeferredAction::Mentions(int that) {
817 if (type() == ActionNode::CLEAR_CAPTURES) {
818 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
819 return range.Contains(that);
820 } else {
821 return reg() == that;
822 }
823}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000824
ager@chromium.org32912102009-01-16 10:38:43 +0000825
826bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000827 for (DeferredAction* action = actions_;
828 action != NULL;
829 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000830 if (action->Mentions(reg))
831 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000832 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000833 return false;
834}
835
836
ager@chromium.org32912102009-01-16 10:38:43 +0000837bool Trace::GetStoredPosition(int reg, int* cp_offset) {
838 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000839 for (DeferredAction* action = actions_;
840 action != NULL;
841 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000842 if (action->Mentions(reg)) {
843 if (action->type() == ActionNode::STORE_POSITION) {
844 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
845 return true;
846 } else {
847 return false;
848 }
849 }
850 }
851 return false;
852}
853
854
855int Trace::FindAffectedRegisters(OutSet* affected_registers) {
856 int max_register = RegExpCompiler::kNoRegister;
857 for (DeferredAction* action = actions_;
858 action != NULL;
859 action = action->next()) {
860 if (action->type() == ActionNode::CLEAR_CAPTURES) {
861 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
862 for (int i = range.from(); i <= range.to(); i++)
863 affected_registers->Set(i);
864 if (range.to() > max_register) max_register = range.to();
865 } else {
866 affected_registers->Set(action->reg());
867 if (action->reg() > max_register) max_register = action->reg();
868 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000869 }
870 return max_register;
871}
872
873
ager@chromium.org32912102009-01-16 10:38:43 +0000874void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
875 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000876 OutSet& registers_to_pop,
877 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000878 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000879 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
880 else if (registers_to_clear.Get(reg)) {
881 int clear_to = reg;
882 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
883 reg--;
884 }
885 assembler->ClearRegisters(reg, clear_to);
886 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000887 }
888}
889
890
ager@chromium.org32912102009-01-16 10:38:43 +0000891void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
892 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000893 OutSet& affected_registers,
894 OutSet* registers_to_pop,
895 OutSet* registers_to_clear) {
896 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
897 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
898
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000899 // Count pushes performed to force a stack limit check occasionally.
900 int pushes = 0;
901
ager@chromium.org8bb60582008-12-11 12:02:20 +0000902 for (int reg = 0; reg <= max_register; reg++) {
903 if (!affected_registers.Get(reg)) {
904 continue;
905 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000906
907 // The chronologically first deferred action in the trace
908 // is used to infer the action needed to restore a register
909 // to its previous state (or not, if it's safe to ignore it).
910 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
911 DeferredActionUndoType undo_action = IGNORE;
912
ager@chromium.org8bb60582008-12-11 12:02:20 +0000913 int value = 0;
914 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000915 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000916 int store_position = -1;
917 // This is a little tricky because we are scanning the actions in reverse
918 // historical order (newest first).
919 for (DeferredAction* action = actions_;
920 action != NULL;
921 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000922 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000923 switch (action->type()) {
924 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +0000925 Trace::DeferredSetRegister* psr =
926 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000927 if (!absolute) {
928 value += psr->value();
929 absolute = true;
930 }
931 // SET_REGISTER is currently only used for newly introduced loop
932 // counters. They can have a significant previous value if they
933 // occour in a loop. TODO(lrn): Propagate this information, so
934 // we can set undo_action to IGNORE if we know there is no value to
935 // restore.
936 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000937 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000938 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000939 break;
940 }
941 case ActionNode::INCREMENT_REGISTER:
942 if (!absolute) {
943 value++;
944 }
945 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000946 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000947 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000948 break;
949 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +0000950 Trace::DeferredCapture* pc =
951 static_cast<Trace::DeferredCapture*>(action);
952 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000953 store_position = pc->cp_offset();
954 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000955
956 // For captures we know that stores and clears alternate.
957 // Other register, are never cleared, and if the occur
958 // inside a loop, they might be assigned more than once.
959 if (reg <= 1) {
960 // Registers zero and one, aka "capture zero", is
961 // always set correctly if we succeed. There is no
962 // need to undo a setting on backtrack, because we
963 // will set it again or fail.
964 undo_action = IGNORE;
965 } else {
966 undo_action = pc->is_capture() ? CLEAR : RESTORE;
967 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000968 ASSERT(!absolute);
969 ASSERT_EQ(value, 0);
970 break;
971 }
ager@chromium.org32912102009-01-16 10:38:43 +0000972 case ActionNode::CLEAR_CAPTURES: {
973 // Since we're scanning in reverse order, if we've already
974 // set the position we have to ignore historically earlier
975 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000976 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +0000977 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000978 }
979 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +0000980 ASSERT(!absolute);
981 ASSERT_EQ(value, 0);
982 break;
983 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000984 default:
985 UNREACHABLE();
986 break;
987 }
988 }
989 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000990 // Prepare for the undo-action (e.g., push if it's going to be popped).
991 if (undo_action == RESTORE) {
992 pushes++;
993 RegExpMacroAssembler::StackCheckFlag stack_check =
994 RegExpMacroAssembler::kNoStackLimitCheck;
995 if (pushes == push_limit) {
996 stack_check = RegExpMacroAssembler::kCheckStackLimit;
997 pushes = 0;
998 }
999
1000 assembler->PushRegister(reg, stack_check);
1001 registers_to_pop->Set(reg);
1002 } else if (undo_action == CLEAR) {
1003 registers_to_clear->Set(reg);
1004 }
1005 // Perform the chronologically last action (or accumulated increment)
1006 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001007 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001008 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001009 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001010 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001011 } else if (absolute) {
1012 assembler->SetRegister(reg, value);
1013 } else if (value != 0) {
1014 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001015 }
1016 }
1017}
1018
1019
ager@chromium.org8bb60582008-12-11 12:02:20 +00001020// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001021// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001022// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001023void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001024 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001025
iposva@chromium.org245aa852009-02-10 00:49:54 +00001026 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001027
1028 if (actions_ == NULL && backtrack() == NULL) {
1029 // 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 +00001030 // a normal situation. We may also have to forget some information gained
1031 // through a quick check that was already performed.
1032 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001033 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001034 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001035 successor->Emit(compiler, &new_state);
1036 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001037 }
1038
1039 // Generate deferred actions here along with code to undo them again.
1040 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001041
ager@chromium.org381abbb2009-02-25 13:23:22 +00001042 if (backtrack() != NULL) {
1043 // Here we have a concrete backtrack location. These are set up by choice
1044 // nodes and so they indicate that we have a deferred save of the current
1045 // position which we may need to emit here.
1046 assembler->PushCurrentPosition();
1047 }
1048
ager@chromium.org8bb60582008-12-11 12:02:20 +00001049 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001050 OutSet registers_to_pop;
1051 OutSet registers_to_clear;
1052 PerformDeferredActions(assembler,
1053 max_register,
1054 affected_registers,
1055 &registers_to_pop,
1056 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001057 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001058 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001059 }
1060
1061 // Create a new trivial state and generate the node with that.
1062 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001063 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001064 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001065 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001066
1067 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001068 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001069 RestoreAffectedRegisters(assembler,
1070 max_register,
1071 registers_to_pop,
1072 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001073 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001074 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001075 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001076 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001077 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001078 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001079}
1080
1081
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001082void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001083 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001084
1085 // Omit flushing the trace. We discard the entire stack frame anyway.
1086
ager@chromium.org8bb60582008-12-11 12:02:20 +00001087 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001088 // We are completely independent of the trace, since we ignore it,
1089 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001090 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001091 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001092
1093 // Throw away everything on the backtrack stack since the start
1094 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001095 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1096 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001097 if (clear_capture_count_ > 0) {
1098 // Clear any captures that might have been performed during the success
1099 // of the body of the negative look-ahead.
1100 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1101 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1102 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001103 // Now that we have unwound the stack we find at the top of the stack the
1104 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001105 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001106}
1107
1108
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001109void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001110 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001111 trace->Flush(compiler, this);
1112 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001113 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001114 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001115 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001116 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001117 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001118 switch (action_) {
1119 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001120 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001121 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001122 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001123 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001124 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001125 case NEGATIVE_SUBMATCH_SUCCESS:
1126 // This case is handled in a different virtual method.
1127 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001128 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001129 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001130}
1131
1132
1133void GuardedAlternative::AddGuard(Guard* guard) {
1134 if (guards_ == NULL)
1135 guards_ = new ZoneList<Guard*>(1);
1136 guards_->Add(guard);
1137}
1138
1139
ager@chromium.org8bb60582008-12-11 12:02:20 +00001140ActionNode* ActionNode::SetRegister(int reg,
1141 int val,
1142 RegExpNode* on_success) {
1143 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001144 result->data_.u_store_register.reg = reg;
1145 result->data_.u_store_register.value = val;
1146 return result;
1147}
1148
1149
1150ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1151 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1152 result->data_.u_increment_register.reg = reg;
1153 return result;
1154}
1155
1156
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001157ActionNode* ActionNode::StorePosition(int reg,
1158 bool is_capture,
1159 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001160 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1161 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001162 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001163 return result;
1164}
1165
1166
ager@chromium.org32912102009-01-16 10:38:43 +00001167ActionNode* ActionNode::ClearCaptures(Interval range,
1168 RegExpNode* on_success) {
1169 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1170 result->data_.u_clear_captures.range_from = range.from();
1171 result->data_.u_clear_captures.range_to = range.to();
1172 return result;
1173}
1174
1175
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001176ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1177 int position_reg,
1178 RegExpNode* on_success) {
1179 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1180 result->data_.u_submatch.stack_pointer_register = stack_reg;
1181 result->data_.u_submatch.current_position_register = position_reg;
1182 return result;
1183}
1184
1185
ager@chromium.org8bb60582008-12-11 12:02:20 +00001186ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1187 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001188 int clear_register_count,
1189 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001190 RegExpNode* on_success) {
1191 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001192 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001193 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001194 result->data_.u_submatch.clear_register_count = clear_register_count;
1195 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001196 return result;
1197}
1198
1199
ager@chromium.org32912102009-01-16 10:38:43 +00001200ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1201 int repetition_register,
1202 int repetition_limit,
1203 RegExpNode* on_success) {
1204 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1205 result->data_.u_empty_match_check.start_register = start_register;
1206 result->data_.u_empty_match_check.repetition_register = repetition_register;
1207 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1208 return result;
1209}
1210
1211
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001212#define DEFINE_ACCEPT(Type) \
1213 void Type##Node::Accept(NodeVisitor* visitor) { \
1214 visitor->Visit##Type(this); \
1215 }
1216FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1217#undef DEFINE_ACCEPT
1218
1219
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001220void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1221 visitor->VisitLoopChoice(this);
1222}
1223
1224
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001225// -------------------------------------------------------------------
1226// Emit code.
1227
1228
1229void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1230 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001231 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001232 switch (guard->op()) {
1233 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001234 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001235 macro_assembler->IfRegisterGE(guard->reg(),
1236 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001237 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001238 break;
1239 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001240 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001241 macro_assembler->IfRegisterLT(guard->reg(),
1242 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001243 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001244 break;
1245 }
1246}
1247
1248
1249static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1250static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1251
1252
ager@chromium.org381abbb2009-02-25 13:23:22 +00001253// Returns the number of characters in the equivalence class, omitting those
1254// that cannot occur in the source string because it is ASCII.
1255static int GetCaseIndependentLetters(uc16 character,
1256 bool ascii_subject,
1257 unibrow::uchar* letters) {
1258 int length = uncanonicalize.get(character, '\0', letters);
1259 // Unibrow returns 0 or 1 for characters where case independependence is
1260 // trivial.
1261 if (length == 0) {
1262 letters[0] = character;
1263 length = 1;
1264 }
1265 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1266 return length;
1267 }
1268 // The standard requires that non-ASCII characters cannot have ASCII
1269 // character codes in their equivalence class.
1270 return 0;
1271}
1272
1273
1274static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1275 uc16 c,
1276 Label* on_failure,
1277 int cp_offset,
1278 bool check,
1279 bool preloaded) {
1280 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1281 bool bound_checked = false;
1282 if (!preloaded) {
1283 assembler->LoadCurrentCharacter(
1284 cp_offset,
1285 on_failure,
1286 check);
1287 bound_checked = true;
1288 }
1289 assembler->CheckNotCharacter(c, on_failure);
1290 return bound_checked;
1291}
1292
1293
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001294// Only emits non-letters (things that don't have case). Only used for case
1295// independent matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001296static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1297 uc16 c,
1298 Label* on_failure,
1299 int cp_offset,
1300 bool check,
1301 bool preloaded) {
1302 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1303 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001304 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001305 int length = GetCaseIndependentLetters(c, ascii, chars);
1306 if (length < 1) {
1307 // This can't match. Must be an ASCII subject and a non-ASCII character.
1308 // We do not need to do anything since the ASCII pass already handled this.
1309 return false; // Bounds not checked.
1310 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001311 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001312 // We handle the length > 1 case in a later pass.
1313 if (length == 1) {
1314 if (ascii && c > String::kMaxAsciiCharCodeU) {
1315 // Can't match - see above.
1316 return false; // Bounds not checked.
1317 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001318 if (!preloaded) {
1319 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1320 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001321 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001322 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001323 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001324 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001325}
1326
1327
1328static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001329 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001330 uc16 c1,
1331 uc16 c2,
1332 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001333 uc16 char_mask;
1334 if (ascii) {
1335 char_mask = String::kMaxAsciiCharCode;
1336 } else {
1337 char_mask = String::kMaxUC16CharCode;
1338 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001339 uc16 exor = c1 ^ c2;
1340 // Check whether exor has only one bit set.
1341 if (((exor - 1) & exor) == 0) {
1342 // If c1 and c2 differ only by one bit.
1343 // Ecma262UnCanonicalize always gives the highest number last.
1344 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001345 uc16 mask = char_mask ^ exor;
1346 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001347 return true;
1348 }
1349 ASSERT(c2 > c1);
1350 uc16 diff = c2 - c1;
1351 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1352 // If the characters differ by 2^n but don't differ by one bit then
1353 // subtract the difference from the found character, then do the or
1354 // trick. We avoid the theoretical case where negative numbers are
1355 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001356 uc16 mask = char_mask ^ diff;
1357 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1358 diff,
1359 mask,
1360 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001361 return true;
1362 }
1363 return false;
1364}
1365
1366
ager@chromium.org381abbb2009-02-25 13:23:22 +00001367typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1368 uc16 c,
1369 Label* on_failure,
1370 int cp_offset,
1371 bool check,
1372 bool preloaded);
1373
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001374// Only emits letters (things that have case). Only used for case independent
1375// matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001376static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1377 uc16 c,
1378 Label* on_failure,
1379 int cp_offset,
1380 bool check,
1381 bool preloaded) {
1382 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1383 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001384 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001385 int length = GetCaseIndependentLetters(c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001386 if (length <= 1) return false;
1387 // We may not need to check against the end of the input string
1388 // if this character lies before a character that matched.
1389 if (!preloaded) {
1390 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001391 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001392 Label ok;
1393 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1394 switch (length) {
1395 case 2: {
1396 if (ShortCutEmitCharacterPair(macro_assembler,
1397 ascii,
1398 chars[0],
1399 chars[1],
1400 on_failure)) {
1401 } else {
1402 macro_assembler->CheckCharacter(chars[0], &ok);
1403 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1404 macro_assembler->Bind(&ok);
1405 }
1406 break;
1407 }
1408 case 4:
1409 macro_assembler->CheckCharacter(chars[3], &ok);
1410 // Fall through!
1411 case 3:
1412 macro_assembler->CheckCharacter(chars[0], &ok);
1413 macro_assembler->CheckCharacter(chars[1], &ok);
1414 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1415 macro_assembler->Bind(&ok);
1416 break;
1417 default:
1418 UNREACHABLE();
1419 break;
1420 }
1421 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001422}
1423
1424
1425static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1426 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001427 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001428 Label* on_failure,
1429 int cp_offset,
1430 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001431 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001432 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001433 int max_char;
1434 if (ascii) {
1435 max_char = String::kMaxAsciiCharCode;
1436 } else {
1437 max_char = String::kMaxUC16CharCode;
1438 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001439
1440 Label success;
1441
1442 Label* char_is_in_class =
1443 cc->is_negated() ? on_failure : &success;
1444
1445 int range_count = ranges->length();
1446
ager@chromium.org8bb60582008-12-11 12:02:20 +00001447 int last_valid_range = range_count - 1;
1448 while (last_valid_range >= 0) {
1449 CharacterRange& range = ranges->at(last_valid_range);
1450 if (range.from() <= max_char) {
1451 break;
1452 }
1453 last_valid_range--;
1454 }
1455
1456 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001457 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001458 // TODO(plesner): We can remove this when the node level does our
1459 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001460 macro_assembler->GoTo(on_failure);
1461 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001462 if (check_offset) {
1463 macro_assembler->CheckPosition(cp_offset, on_failure);
1464 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001465 return;
1466 }
1467
ager@chromium.org8bb60582008-12-11 12:02:20 +00001468 if (last_valid_range == 0 &&
1469 !cc->is_negated() &&
1470 ranges->at(0).IsEverything(max_char)) {
1471 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001472 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001473 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001474 }
1475 return;
1476 }
1477
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001478 if (!preloaded) {
1479 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001480 }
1481
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001482 if (cc->is_standard() &&
1483 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1484 on_failure)) {
1485 return;
1486 }
1487
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001488 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001489 CharacterRange& range = ranges->at(i);
1490 Label next_range;
1491 uc16 from = range.from();
1492 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001493 if (from > max_char) {
1494 continue;
1495 }
1496 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001497 if (to == from) {
1498 macro_assembler->CheckCharacter(to, char_is_in_class);
1499 } else {
1500 if (from != 0) {
1501 macro_assembler->CheckCharacterLT(from, &next_range);
1502 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001503 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001504 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1505 } else {
1506 macro_assembler->GoTo(char_is_in_class);
1507 }
1508 }
1509 macro_assembler->Bind(&next_range);
1510 }
1511
ager@chromium.org8bb60582008-12-11 12:02:20 +00001512 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001513 uc16 from = range.from();
1514 uc16 to = range.to();
1515
ager@chromium.org8bb60582008-12-11 12:02:20 +00001516 if (to > max_char) to = max_char;
1517 ASSERT(to >= from);
1518
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001519 if (to == from) {
1520 if (cc->is_negated()) {
1521 macro_assembler->CheckCharacter(to, on_failure);
1522 } else {
1523 macro_assembler->CheckNotCharacter(to, on_failure);
1524 }
1525 } else {
1526 if (from != 0) {
1527 if (cc->is_negated()) {
1528 macro_assembler->CheckCharacterLT(from, &success);
1529 } else {
1530 macro_assembler->CheckCharacterLT(from, on_failure);
1531 }
1532 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001533 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001534 if (cc->is_negated()) {
1535 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1536 } else {
1537 macro_assembler->CheckCharacterGT(to, on_failure);
1538 }
1539 } else {
1540 if (cc->is_negated()) {
1541 macro_assembler->GoTo(on_failure);
1542 }
1543 }
1544 }
1545 macro_assembler->Bind(&success);
1546}
1547
1548
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001549RegExpNode::~RegExpNode() {
1550}
1551
1552
ager@chromium.org8bb60582008-12-11 12:02:20 +00001553RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001554 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001555 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001556 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001557 return CONTINUE;
1558 }
1559
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001560 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001561 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001562 if (label_.is_bound()) {
1563 // We are being asked to generate a generic version, but that's already
1564 // been done so just go to it.
1565 macro_assembler->GoTo(&label_);
1566 return DONE;
1567 }
1568 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1569 // To avoid too deep recursion we push the node to the work queue and just
1570 // generate a goto here.
1571 compiler->AddWork(this);
1572 macro_assembler->GoTo(&label_);
1573 return DONE;
1574 }
1575 // Generate generic version of the node and bind the label for later use.
1576 macro_assembler->Bind(&label_);
1577 return CONTINUE;
1578 }
1579
1580 // We are being asked to make a non-generic version. Keep track of how many
1581 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001582 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001583 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001584 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001585 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1586 return CONTINUE;
1587 }
1588
ager@chromium.org32912102009-01-16 10:38:43 +00001589 // If we get here code has been generated for this node too many times or
1590 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001591 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001592 trace->Flush(compiler, this);
1593 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001594}
1595
1596
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001597int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001598 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1599 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001600 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001601}
1602
1603
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001604int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1605 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1606 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1607}
1608
1609
1610int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1611 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1612 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1613}
1614
1615
1616int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001617 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001618 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001619 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001620 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1621 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001622}
1623
1624
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001625int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
1626 int recursion_depth) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001627 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1628 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1629 // afterwards.
1630 RegExpNode* node = alternatives_->at(1).node();
1631 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1632}
1633
1634
1635void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1636 QuickCheckDetails* details,
1637 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001638 int filled_in,
1639 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001640 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1641 // afterwards.
1642 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001643 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001644}
1645
1646
1647int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1648 int recursion_depth,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001649 RegExpNode* ignore_this_node) {
1650 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1651 int min = 100;
1652 int choice_count = alternatives_->length();
1653 for (int i = 0; i < choice_count; i++) {
1654 RegExpNode* node = alternatives_->at(i).node();
1655 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001656 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1657 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001658 if (node_eats_at_least < min) min = node_eats_at_least;
1659 }
1660 return min;
1661}
1662
1663
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001664int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1665 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001666}
1667
1668
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001669int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1670 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001671}
1672
1673
1674// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1675static inline uint32_t SmearBitsRight(uint32_t v) {
1676 v |= v >> 1;
1677 v |= v >> 2;
1678 v |= v >> 4;
1679 v |= v >> 8;
1680 v |= v >> 16;
1681 return v;
1682}
1683
1684
1685bool QuickCheckDetails::Rationalize(bool asc) {
1686 bool found_useful_op = false;
1687 uint32_t char_mask;
1688 if (asc) {
1689 char_mask = String::kMaxAsciiCharCode;
1690 } else {
1691 char_mask = String::kMaxUC16CharCode;
1692 }
1693 mask_ = 0;
1694 value_ = 0;
1695 int char_shift = 0;
1696 for (int i = 0; i < characters_; i++) {
1697 Position* pos = &positions_[i];
1698 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1699 found_useful_op = true;
1700 }
1701 mask_ |= (pos->mask & char_mask) << char_shift;
1702 value_ |= (pos->value & char_mask) << char_shift;
1703 char_shift += asc ? 8 : 16;
1704 }
1705 return found_useful_op;
1706}
1707
1708
1709bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001710 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001711 bool preload_has_checked_bounds,
1712 Label* on_possible_success,
1713 QuickCheckDetails* details,
1714 bool fall_through_on_failure) {
1715 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001716 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1717 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001718 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001719 ASSERT(details->characters() == 1 ||
1720 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001721 uint32_t mask = details->mask();
1722 uint32_t value = details->value();
1723
1724 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1725
ager@chromium.org32912102009-01-16 10:38:43 +00001726 if (trace->characters_preloaded() != details->characters()) {
1727 assembler->LoadCurrentCharacter(trace->cp_offset(),
1728 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001729 !preload_has_checked_bounds,
1730 details->characters());
1731 }
1732
1733
1734 bool need_mask = true;
1735
1736 if (details->characters() == 1) {
1737 // If number of characters preloaded is 1 then we used a byte or 16 bit
1738 // load so the value is already masked down.
1739 uint32_t char_mask;
1740 if (compiler->ascii()) {
1741 char_mask = String::kMaxAsciiCharCode;
1742 } else {
1743 char_mask = String::kMaxUC16CharCode;
1744 }
1745 if ((mask & char_mask) == char_mask) need_mask = false;
1746 mask &= char_mask;
1747 } else {
1748 // For 2-character preloads in ASCII mode we also use a 16 bit load with
1749 // zero extend.
1750 if (details->characters() == 2 && compiler->ascii()) {
1751 if ((mask & 0xffff) == 0xffff) need_mask = false;
1752 } else {
1753 if (mask == 0xffffffff) need_mask = false;
1754 }
1755 }
1756
1757 if (fall_through_on_failure) {
1758 if (need_mask) {
1759 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1760 } else {
1761 assembler->CheckCharacter(value, on_possible_success);
1762 }
1763 } else {
1764 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001765 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001766 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001767 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001768 }
1769 }
1770 return true;
1771}
1772
1773
1774// Here is the meat of GetQuickCheckDetails (see also the comment on the
1775// super-class in the .h file).
1776//
1777// We iterate along the text object, building up for each character a
1778// mask and value that can be used to test for a quick failure to match.
1779// The masks and values for the positions will be combined into a single
1780// machine word for the current character width in order to be used in
1781// generating a quick check.
1782void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1783 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001784 int characters_filled_in,
1785 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001786 ASSERT(characters_filled_in < details->characters());
1787 int characters = details->characters();
1788 int char_mask;
1789 int char_shift;
1790 if (compiler->ascii()) {
1791 char_mask = String::kMaxAsciiCharCode;
1792 char_shift = 8;
1793 } else {
1794 char_mask = String::kMaxUC16CharCode;
1795 char_shift = 16;
1796 }
1797 for (int k = 0; k < elms_->length(); k++) {
1798 TextElement elm = elms_->at(k);
1799 if (elm.type == TextElement::ATOM) {
1800 Vector<const uc16> quarks = elm.data.u_atom->data();
1801 for (int i = 0; i < characters && i < quarks.length(); i++) {
1802 QuickCheckDetails::Position* pos =
1803 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001804 uc16 c = quarks[i];
1805 if (c > char_mask) {
1806 // If we expect a non-ASCII character from an ASCII string,
1807 // there is no way we can match. Not even case independent
1808 // matching can turn an ASCII character into non-ASCII or
1809 // vice versa.
1810 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001811 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001812 return;
1813 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001814 if (compiler->ignore_case()) {
1815 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001816 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1817 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1818 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001819 // This letter has no case equivalents, so it's nice and simple
1820 // and the mask-compare will determine definitely whether we have
1821 // a match at this character position.
1822 pos->mask = char_mask;
1823 pos->value = c;
1824 pos->determines_perfectly = true;
1825 } else {
1826 uint32_t common_bits = char_mask;
1827 uint32_t bits = chars[0];
1828 for (int j = 1; j < length; j++) {
1829 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1830 common_bits ^= differing_bits;
1831 bits &= common_bits;
1832 }
1833 // If length is 2 and common bits has only one zero in it then
1834 // our mask and compare instruction will determine definitely
1835 // whether we have a match at this character position. Otherwise
1836 // it can only be an approximate check.
1837 uint32_t one_zero = (common_bits | ~char_mask);
1838 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1839 pos->determines_perfectly = true;
1840 }
1841 pos->mask = common_bits;
1842 pos->value = bits;
1843 }
1844 } else {
1845 // Don't ignore case. Nice simple case where the mask-compare will
1846 // determine definitely whether we have a match at this character
1847 // position.
1848 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001849 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001850 pos->determines_perfectly = true;
1851 }
1852 characters_filled_in++;
1853 ASSERT(characters_filled_in <= details->characters());
1854 if (characters_filled_in == details->characters()) {
1855 return;
1856 }
1857 }
1858 } else {
1859 QuickCheckDetails::Position* pos =
1860 details->positions(characters_filled_in);
1861 RegExpCharacterClass* tree = elm.data.u_char_class;
1862 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001863 if (tree->is_negated()) {
1864 // A quick check uses multi-character mask and compare. There is no
1865 // useful way to incorporate a negative char class into this scheme
1866 // so we just conservatively create a mask and value that will always
1867 // succeed.
1868 pos->mask = 0;
1869 pos->value = 0;
1870 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001871 int first_range = 0;
1872 while (ranges->at(first_range).from() > char_mask) {
1873 first_range++;
1874 if (first_range == ranges->length()) {
1875 details->set_cannot_match();
1876 pos->determines_perfectly = false;
1877 return;
1878 }
1879 }
1880 CharacterRange range = ranges->at(first_range);
1881 uc16 from = range.from();
1882 uc16 to = range.to();
1883 if (to > char_mask) {
1884 to = char_mask;
1885 }
1886 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001887 // A mask and compare is only perfect if the differing bits form a
1888 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001889 if ((differing_bits & (differing_bits + 1)) == 0 &&
1890 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001891 pos->determines_perfectly = true;
1892 }
1893 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001894 uint32_t bits = (from & common_bits);
1895 for (int i = first_range + 1; i < ranges->length(); i++) {
1896 CharacterRange range = ranges->at(i);
1897 uc16 from = range.from();
1898 uc16 to = range.to();
1899 if (from > char_mask) continue;
1900 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001901 // Here we are combining more ranges into the mask and compare
1902 // value. With each new range the mask becomes more sparse and
1903 // so the chances of a false positive rise. A character class
1904 // with multiple ranges is assumed never to be equivalent to a
1905 // mask and compare operation.
1906 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001907 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001908 new_common_bits = ~SmearBitsRight(new_common_bits);
1909 common_bits &= new_common_bits;
1910 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001911 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001912 common_bits ^= differing_bits;
1913 bits &= common_bits;
1914 }
1915 pos->mask = common_bits;
1916 pos->value = bits;
1917 }
1918 characters_filled_in++;
1919 ASSERT(characters_filled_in <= details->characters());
1920 if (characters_filled_in == details->characters()) {
1921 return;
1922 }
1923 }
1924 }
1925 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00001926 on_success()-> GetQuickCheckDetails(details,
1927 compiler,
1928 characters_filled_in,
1929 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001930}
1931
1932
1933void QuickCheckDetails::Clear() {
1934 for (int i = 0; i < characters_; i++) {
1935 positions_[i].mask = 0;
1936 positions_[i].value = 0;
1937 positions_[i].determines_perfectly = false;
1938 }
1939 characters_ = 0;
1940}
1941
1942
1943void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001944 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001945 if (by >= characters_) {
1946 Clear();
1947 return;
1948 }
1949 for (int i = 0; i < characters_ - by; i++) {
1950 positions_[i] = positions_[by + i];
1951 }
1952 for (int i = characters_ - by; i < characters_; i++) {
1953 positions_[i].mask = 0;
1954 positions_[i].value = 0;
1955 positions_[i].determines_perfectly = false;
1956 }
1957 characters_ -= by;
1958 // We could change mask_ and value_ here but we would never advance unless
1959 // they had already been used in a check and they won't be used again because
1960 // it would gain us nothing. So there's no point.
1961}
1962
1963
1964void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1965 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001966 if (other->cannot_match_) {
1967 return;
1968 }
1969 if (cannot_match_) {
1970 *this = *other;
1971 return;
1972 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001973 for (int i = from_index; i < characters_; i++) {
1974 QuickCheckDetails::Position* pos = positions(i);
1975 QuickCheckDetails::Position* other_pos = other->positions(i);
1976 if (pos->mask != other_pos->mask ||
1977 pos->value != other_pos->value ||
1978 !other_pos->determines_perfectly) {
1979 // Our mask-compare operation will be approximate unless we have the
1980 // exact same operation on both sides of the alternation.
1981 pos->determines_perfectly = false;
1982 }
1983 pos->mask &= other_pos->mask;
1984 pos->value &= pos->mask;
1985 other_pos->value &= pos->mask;
1986 uc16 differing_bits = (pos->value ^ other_pos->value);
1987 pos->mask &= ~differing_bits;
1988 pos->value &= pos->mask;
1989 }
1990}
1991
1992
ager@chromium.org32912102009-01-16 10:38:43 +00001993class VisitMarker {
1994 public:
1995 explicit VisitMarker(NodeInfo* info) : info_(info) {
1996 ASSERT(!info->visited);
1997 info->visited = true;
1998 }
1999 ~VisitMarker() {
2000 info_->visited = false;
2001 }
2002 private:
2003 NodeInfo* info_;
2004};
2005
2006
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002007void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2008 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002009 int characters_filled_in,
2010 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002011 if (body_can_be_zero_length_ || info()->visited) return;
2012 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002013 return ChoiceNode::GetQuickCheckDetails(details,
2014 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002015 characters_filled_in,
2016 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002017}
2018
2019
2020void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2021 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002022 int characters_filled_in,
2023 bool not_at_start) {
2024 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002025 int choice_count = alternatives_->length();
2026 ASSERT(choice_count > 0);
2027 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2028 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002029 characters_filled_in,
2030 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002031 for (int i = 1; i < choice_count; i++) {
2032 QuickCheckDetails new_details(details->characters());
2033 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002034 node->GetQuickCheckDetails(&new_details, compiler,
2035 characters_filled_in,
2036 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002037 // Here we merge the quick match details of the two branches.
2038 details->Merge(&new_details, characters_filled_in);
2039 }
2040}
2041
2042
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002043// Check for [0-9A-Z_a-z].
2044static void EmitWordCheck(RegExpMacroAssembler* assembler,
2045 Label* word,
2046 Label* non_word,
2047 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002048 if (assembler->CheckSpecialCharacterClass(
2049 fall_through_on_word ? 'w' : 'W',
2050 fall_through_on_word ? non_word : word)) {
2051 // Optimized implementation available.
2052 return;
2053 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002054 assembler->CheckCharacterGT('z', non_word);
2055 assembler->CheckCharacterLT('0', non_word);
2056 assembler->CheckCharacterGT('a' - 1, word);
2057 assembler->CheckCharacterLT('9' + 1, word);
2058 assembler->CheckCharacterLT('A', non_word);
2059 assembler->CheckCharacterLT('Z' + 1, word);
2060 if (fall_through_on_word) {
2061 assembler->CheckNotCharacter('_', non_word);
2062 } else {
2063 assembler->CheckCharacter('_', word);
2064 }
2065}
2066
2067
2068// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2069// that matches newline or the start of input).
2070static void EmitHat(RegExpCompiler* compiler,
2071 RegExpNode* on_success,
2072 Trace* trace) {
2073 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2074 // We will be loading the previous character into the current character
2075 // register.
2076 Trace new_trace(*trace);
2077 new_trace.InvalidateCurrentCharacter();
2078
2079 Label ok;
2080 if (new_trace.cp_offset() == 0) {
2081 // The start of input counts as a newline in this context, so skip to
2082 // ok if we are at the start.
2083 assembler->CheckAtStart(&ok);
2084 }
2085 // We already checked that we are not at the start of input so it must be
2086 // OK to load the previous character.
2087 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2088 new_trace.backtrack(),
2089 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002090 if (!assembler->CheckSpecialCharacterClass('n',
2091 new_trace.backtrack())) {
2092 // Newline means \n, \r, 0x2028 or 0x2029.
2093 if (!compiler->ascii()) {
2094 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2095 }
2096 assembler->CheckCharacter('\n', &ok);
2097 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002098 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002099 assembler->Bind(&ok);
2100 on_success->Emit(compiler, &new_trace);
2101}
2102
2103
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002104// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2105// when we know whether the next character must be a word character or not.
2106static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2107 RegExpCompiler* compiler,
2108 RegExpNode* on_success,
2109 Trace* trace) {
2110 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2111 Label done;
2112
2113 Trace new_trace(*trace);
2114
2115 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2116 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2117 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2118
2119 // Check whether previous character was a word character.
2120 switch (trace->at_start()) {
2121 case Trace::TRUE:
2122 if (expect_word_character) {
2123 assembler->GoTo(on_non_word);
2124 }
2125 break;
2126 case Trace::UNKNOWN:
2127 ASSERT_EQ(0, trace->cp_offset());
2128 assembler->CheckAtStart(on_non_word);
2129 // Fall through.
2130 case Trace::FALSE:
2131 int prev_char_offset = trace->cp_offset() - 1;
2132 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2133 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2134 // We may or may not have loaded the previous character.
2135 new_trace.InvalidateCurrentCharacter();
2136 }
2137
2138 assembler->Bind(&done);
2139
2140 on_success->Emit(compiler, &new_trace);
2141}
2142
2143
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002144// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2145static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2146 RegExpCompiler* compiler,
2147 RegExpNode* on_success,
2148 Trace* trace) {
2149 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2150 Label before_non_word;
2151 Label before_word;
2152 if (trace->characters_preloaded() != 1) {
2153 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2154 }
2155 // Fall through on non-word.
2156 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2157
2158 // We will be loading the previous character into the current character
2159 // register.
2160 Trace new_trace(*trace);
2161 new_trace.InvalidateCurrentCharacter();
2162
2163 Label ok;
2164 Label* boundary;
2165 Label* not_boundary;
2166 if (type == AssertionNode::AT_BOUNDARY) {
2167 boundary = &ok;
2168 not_boundary = new_trace.backtrack();
2169 } else {
2170 not_boundary = &ok;
2171 boundary = new_trace.backtrack();
2172 }
2173
2174 // Next character is not a word character.
2175 assembler->Bind(&before_non_word);
2176 if (new_trace.cp_offset() == 0) {
2177 // The start of input counts as a non-word character, so the question is
2178 // decided if we are at the start.
2179 assembler->CheckAtStart(not_boundary);
2180 }
2181 // We already checked that we are not at the start of input so it must be
2182 // OK to load the previous character.
2183 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2184 &ok, // Unused dummy label in this call.
2185 false);
2186 // Fall through on non-word.
2187 EmitWordCheck(assembler, boundary, not_boundary, false);
2188 assembler->GoTo(not_boundary);
2189
2190 // Next character is a word character.
2191 assembler->Bind(&before_word);
2192 if (new_trace.cp_offset() == 0) {
2193 // The start of input counts as a non-word character, so the question is
2194 // decided if we are at the start.
2195 assembler->CheckAtStart(boundary);
2196 }
2197 // We already checked that we are not at the start of input so it must be
2198 // OK to load the previous character.
2199 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2200 &ok, // Unused dummy label in this call.
2201 false);
2202 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2203 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2204
2205 assembler->Bind(&ok);
2206
2207 on_success->Emit(compiler, &new_trace);
2208}
2209
2210
iposva@chromium.org245aa852009-02-10 00:49:54 +00002211void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2212 RegExpCompiler* compiler,
2213 int filled_in,
2214 bool not_at_start) {
2215 if (type_ == AT_START && not_at_start) {
2216 details->set_cannot_match();
2217 return;
2218 }
2219 return on_success()->GetQuickCheckDetails(details,
2220 compiler,
2221 filled_in,
2222 not_at_start);
2223}
2224
2225
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002226void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2227 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2228 switch (type_) {
2229 case AT_END: {
2230 Label ok;
2231 assembler->CheckPosition(trace->cp_offset(), &ok);
2232 assembler->GoTo(trace->backtrack());
2233 assembler->Bind(&ok);
2234 break;
2235 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002236 case AT_START: {
2237 if (trace->at_start() == Trace::FALSE) {
2238 assembler->GoTo(trace->backtrack());
2239 return;
2240 }
2241 if (trace->at_start() == Trace::UNKNOWN) {
2242 assembler->CheckNotAtStart(trace->backtrack());
2243 Trace at_start_trace = *trace;
2244 at_start_trace.set_at_start(true);
2245 on_success()->Emit(compiler, &at_start_trace);
2246 return;
2247 }
2248 }
2249 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002250 case AFTER_NEWLINE:
2251 EmitHat(compiler, on_success(), trace);
2252 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002253 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002254 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002255 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2256 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002257 }
2258 case AFTER_WORD_CHARACTER:
2259 case AFTER_NONWORD_CHARACTER: {
2260 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2261 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002262 }
2263 on_success()->Emit(compiler, trace);
2264}
2265
2266
ager@chromium.org381abbb2009-02-25 13:23:22 +00002267static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2268 if (quick_check == NULL) return false;
2269 if (offset >= quick_check->characters()) return false;
2270 return quick_check->positions(offset)->determines_perfectly;
2271}
2272
2273
2274static void UpdateBoundsCheck(int index, int* checked_up_to) {
2275 if (index > *checked_up_to) {
2276 *checked_up_to = index;
2277 }
2278}
2279
2280
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002281// We call this repeatedly to generate code for each pass over the text node.
2282// The passes are in increasing order of difficulty because we hope one
2283// of the first passes will fail in which case we are saved the work of the
2284// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2285// we will check the '%' in the first pass, the case independent 'a' in the
2286// second pass and the character class in the last pass.
2287//
2288// The passes are done from right to left, so for example to test for /bar/
2289// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2290// and then a 'b' with offset 0. This means we can avoid the end-of-input
2291// bounds check most of the time. In the example we only need to check for
2292// end-of-input when loading the putative 'r'.
2293//
2294// A slight complication involves the fact that the first character may already
2295// be fetched into a register by the previous node. In this case we want to
2296// do the test for that character first. We do this in separate passes. The
2297// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2298// pass has been performed then subsequent passes will have true in
2299// first_element_checked to indicate that that character does not need to be
2300// checked again.
2301//
ager@chromium.org32912102009-01-16 10:38:43 +00002302// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002303// contain an AlternativeGeneration object. In this AlternativeGeneration
2304// object we can see details of any quick check that was already passed in
2305// order to get to the code we are now generating. The quick check can involve
2306// loading characters, which means we do not need to recheck the bounds
2307// up to the limit the quick check already checked. In addition the quick
2308// check can have involved a mask and compare operation which may simplify
2309// or obviate the need for further checks at some character positions.
2310void TextNode::TextEmitPass(RegExpCompiler* compiler,
2311 TextEmitPassType pass,
2312 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002313 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002314 bool first_element_checked,
2315 int* checked_up_to) {
2316 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2317 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002318 Label* backtrack = trace->backtrack();
2319 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002320 int element_count = elms_->length();
2321 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2322 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002323 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002324 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002325 Vector<const uc16> quarks = elm.data.u_atom->data();
2326 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2327 if (first_element_checked && i == 0 && j == 0) continue;
2328 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2329 EmitCharacterFunction* emit_function = NULL;
2330 switch (pass) {
2331 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002332 ASSERT(ascii);
2333 if (quarks[j] > String::kMaxAsciiCharCode) {
2334 assembler->GoTo(backtrack);
2335 return;
2336 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002337 break;
2338 case NON_LETTER_CHARACTER_MATCH:
2339 emit_function = &EmitAtomNonLetter;
2340 break;
2341 case SIMPLE_CHARACTER_MATCH:
2342 emit_function = &EmitSimpleCharacter;
2343 break;
2344 case CASE_CHARACTER_MATCH:
2345 emit_function = &EmitAtomLetter;
2346 break;
2347 default:
2348 break;
2349 }
2350 if (emit_function != NULL) {
2351 bool bound_checked = emit_function(compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002352 quarks[j],
2353 backtrack,
2354 cp_offset + j,
2355 *checked_up_to < cp_offset + j,
2356 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002357 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002358 }
2359 }
2360 } else {
2361 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002362 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002363 if (first_element_checked && i == 0) continue;
2364 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002365 RegExpCharacterClass* cc = elm.data.u_char_class;
2366 EmitCharClass(assembler,
2367 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002368 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002369 backtrack,
2370 cp_offset,
2371 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002372 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002373 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002374 }
2375 }
2376 }
2377}
2378
2379
2380int TextNode::Length() {
2381 TextElement elm = elms_->last();
2382 ASSERT(elm.cp_offset >= 0);
2383 if (elm.type == TextElement::ATOM) {
2384 return elm.cp_offset + elm.data.u_atom->data().length();
2385 } else {
2386 return elm.cp_offset + 1;
2387 }
2388}
2389
2390
ager@chromium.org381abbb2009-02-25 13:23:22 +00002391bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2392 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2393 if (ignore_case) {
2394 return pass == SIMPLE_CHARACTER_MATCH;
2395 } else {
2396 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2397 }
2398}
2399
2400
ager@chromium.org8bb60582008-12-11 12:02:20 +00002401// This generates the code to match a text node. A text node can contain
2402// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002403// way) and character classes. For efficiency we do not do this in a single
2404// pass from left to right. Instead we pass over the text node several times,
2405// emitting code for some character positions every time. See the comment on
2406// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002407void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002408 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002409 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002410 ASSERT(limit_result == CONTINUE);
2411
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002412 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2413 compiler->SetRegExpTooBig();
2414 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002415 }
2416
2417 if (compiler->ascii()) {
2418 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002419 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002420 }
2421
2422 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002423 int bound_checked_to = trace->cp_offset() - 1;
2424 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002425
2426 // If a character is preloaded into the current character register then
2427 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002428 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002429 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2430 if (!SkipPass(pass, compiler->ignore_case())) {
2431 TextEmitPass(compiler,
2432 static_cast<TextEmitPassType>(pass),
2433 true,
2434 trace,
2435 false,
2436 &bound_checked_to);
2437 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002438 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002439 first_elt_done = true;
2440 }
2441
ager@chromium.org381abbb2009-02-25 13:23:22 +00002442 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2443 if (!SkipPass(pass, compiler->ignore_case())) {
2444 TextEmitPass(compiler,
2445 static_cast<TextEmitPassType>(pass),
2446 false,
2447 trace,
2448 first_elt_done,
2449 &bound_checked_to);
2450 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002451 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002452
ager@chromium.org32912102009-01-16 10:38:43 +00002453 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002454 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002455 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002456 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002457 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002458}
2459
2460
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002461void Trace::InvalidateCurrentCharacter() {
2462 characters_preloaded_ = 0;
2463}
2464
2465
2466void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002467 ASSERT(by > 0);
2468 // We don't have an instruction for shifting the current character register
2469 // down or for using a shifted value for anything so lets just forget that
2470 // we preloaded any characters into it.
2471 characters_preloaded_ = 0;
2472 // Adjust the offsets of the quick check performed information. This
2473 // information is used to find out what we already determined about the
2474 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002475 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002476 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002477 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2478 compiler->SetRegExpTooBig();
2479 cp_offset_ = 0;
2480 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002481 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002482}
2483
2484
ager@chromium.org38e4c712009-11-11 09:11:58 +00002485void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002486 int element_count = elms_->length();
2487 for (int i = 0; i < element_count; i++) {
2488 TextElement elm = elms_->at(i);
2489 if (elm.type == TextElement::CHAR_CLASS) {
2490 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002491 // None of the standard character classses is different in the case
2492 // independent case and it slows us down if we don't know that.
2493 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002494 ZoneList<CharacterRange>* ranges = cc->ranges();
2495 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002496 for (int j = 0; j < range_count; j++) {
2497 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002498 }
2499 }
2500 }
2501}
2502
2503
ager@chromium.org8bb60582008-12-11 12:02:20 +00002504int TextNode::GreedyLoopTextLength() {
2505 TextElement elm = elms_->at(elms_->length() - 1);
2506 if (elm.type == TextElement::CHAR_CLASS) {
2507 return elm.cp_offset + 1;
2508 } else {
2509 return elm.cp_offset + elm.data.u_atom->data().length();
2510 }
2511}
2512
2513
2514// Finds the fixed match length of a sequence of nodes that goes from
2515// this alternative and back to this choice node. If there are variable
2516// length nodes or other complications in the way then return a sentinel
2517// value indicating that a greedy loop cannot be constructed.
2518int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2519 int length = 0;
2520 RegExpNode* node = alternative->node();
2521 // Later we will generate code for all these text nodes using recursion
2522 // so we have to limit the max number.
2523 int recursion_depth = 0;
2524 while (node != this) {
2525 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2526 return kNodeIsTooComplexForGreedyLoops;
2527 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002528 int node_length = node->GreedyLoopTextLength();
2529 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2530 return kNodeIsTooComplexForGreedyLoops;
2531 }
2532 length += node_length;
2533 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2534 node = seq_node->on_success();
2535 }
2536 return length;
2537}
2538
2539
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002540void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2541 ASSERT_EQ(loop_node_, NULL);
2542 AddAlternative(alt);
2543 loop_node_ = alt.node();
2544}
2545
2546
2547void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2548 ASSERT_EQ(continue_node_, NULL);
2549 AddAlternative(alt);
2550 continue_node_ = alt.node();
2551}
2552
2553
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002554void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002555 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002556 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002557 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2558 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2559 // Update the counter-based backtracking info on the stack. This is an
2560 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002561 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002562 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002563 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002564 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002565 }
ager@chromium.org32912102009-01-16 10:38:43 +00002566 ASSERT(trace->stop_node() == NULL);
2567 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002568 trace->Flush(compiler, this);
2569 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002570 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002571 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002572}
2573
2574
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002575int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002576 int preload_characters = EatsAtLeast(4, 0);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002577 if (compiler->macro_assembler()->CanReadUnaligned()) {
2578 bool ascii = compiler->ascii();
2579 if (ascii) {
2580 if (preload_characters > 4) preload_characters = 4;
2581 // We can't preload 3 characters because there is no machine instruction
2582 // to do that. We can't just load 4 because we could be reading
2583 // beyond the end of the string, which could cause a memory fault.
2584 if (preload_characters == 3) preload_characters = 2;
2585 } else {
2586 if (preload_characters > 2) preload_characters = 2;
2587 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002588 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002589 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002590 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002591 return preload_characters;
2592}
2593
2594
2595// This class is used when generating the alternatives in a choice node. It
2596// records the way the alternative is being code generated.
2597class AlternativeGeneration: public Malloced {
2598 public:
2599 AlternativeGeneration()
2600 : possible_success(),
2601 expects_preload(false),
2602 after(),
2603 quick_check_details() { }
2604 Label possible_success;
2605 bool expects_preload;
2606 Label after;
2607 QuickCheckDetails quick_check_details;
2608};
2609
2610
2611// Creates a list of AlternativeGenerations. If the list has a reasonable
2612// size then it is on the stack, otherwise the excess is on the heap.
2613class AlternativeGenerationList {
2614 public:
2615 explicit AlternativeGenerationList(int count)
2616 : alt_gens_(count) {
2617 for (int i = 0; i < count && i < kAFew; i++) {
2618 alt_gens_.Add(a_few_alt_gens_ + i);
2619 }
2620 for (int i = kAFew; i < count; i++) {
2621 alt_gens_.Add(new AlternativeGeneration());
2622 }
2623 }
2624 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002625 for (int i = kAFew; i < alt_gens_.length(); i++) {
2626 delete alt_gens_[i];
2627 alt_gens_[i] = NULL;
2628 }
2629 }
2630
2631 AlternativeGeneration* at(int i) {
2632 return alt_gens_[i];
2633 }
2634 private:
2635 static const int kAFew = 10;
2636 ZoneList<AlternativeGeneration*> alt_gens_;
2637 AlternativeGeneration a_few_alt_gens_[kAFew];
2638};
2639
2640
2641/* Code generation for choice nodes.
2642 *
2643 * We generate quick checks that do a mask and compare to eliminate a
2644 * choice. If the quick check succeeds then it jumps to the continuation to
2645 * do slow checks and check subsequent nodes. If it fails (the common case)
2646 * it falls through to the next choice.
2647 *
2648 * Here is the desired flow graph. Nodes directly below each other imply
2649 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2650 * 3 doesn't have a quick check so we have to call the slow check.
2651 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2652 * regexp continuation is generated directly after the Sn node, up to the
2653 * next GoTo if we decide to reuse some already generated code. Some
2654 * nodes expect preload_characters to be preloaded into the current
2655 * character register. R nodes do this preloading. Vertices are marked
2656 * F for failures and S for success (possible success in the case of quick
2657 * nodes). L, V, < and > are used as arrow heads.
2658 *
2659 * ----------> R
2660 * |
2661 * V
2662 * Q1 -----> S1
2663 * | S /
2664 * F| /
2665 * | F/
2666 * | /
2667 * | R
2668 * | /
2669 * V L
2670 * Q2 -----> S2
2671 * | S /
2672 * F| /
2673 * | F/
2674 * | /
2675 * | R
2676 * | /
2677 * V L
2678 * S3
2679 * |
2680 * F|
2681 * |
2682 * R
2683 * |
2684 * backtrack V
2685 * <----------Q4
2686 * \ F |
2687 * \ |S
2688 * \ F V
2689 * \-----S4
2690 *
2691 * For greedy loops we reverse our expectation and expect to match rather
2692 * than fail. Therefore we want the loop code to look like this (U is the
2693 * unwind code that steps back in the greedy loop). The following alternatives
2694 * look the same as above.
2695 * _____
2696 * / \
2697 * V |
2698 * ----------> S1 |
2699 * /| |
2700 * / |S |
2701 * F/ \_____/
2702 * /
2703 * |<-----------
2704 * | \
2705 * V \
2706 * Q2 ---> S2 \
2707 * | S / |
2708 * F| / |
2709 * | F/ |
2710 * | / |
2711 * | R |
2712 * | / |
2713 * F VL |
2714 * <------U |
2715 * back |S |
2716 * \______________/
2717 */
2718
2719
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002720void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002721 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2722 int choice_count = alternatives_->length();
2723#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002724 for (int i = 0; i < choice_count - 1; i++) {
2725 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002726 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002727 int guard_count = (guards == NULL) ? 0 : guards->length();
2728 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002729 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002730 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002731 }
2732#endif
2733
ager@chromium.org32912102009-01-16 10:38:43 +00002734 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002735 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002736 ASSERT(limit_result == CONTINUE);
2737
ager@chromium.org381abbb2009-02-25 13:23:22 +00002738 int new_flush_budget = trace->flush_budget() / choice_count;
2739 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2740 trace->Flush(compiler, this);
2741 return;
2742 }
2743
ager@chromium.org8bb60582008-12-11 12:02:20 +00002744 RecursionCheck rc(compiler);
2745
ager@chromium.org32912102009-01-16 10:38:43 +00002746 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002747
2748 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2749 bool greedy_loop = false;
2750 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002751 Trace counter_backtrack_trace;
2752 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002753 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2754
ager@chromium.org8bb60582008-12-11 12:02:20 +00002755 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2756 // Here we have special handling for greedy loops containing only text nodes
2757 // and other simple nodes. These are handled by pushing the current
2758 // position on the stack and then incrementing the current position each
2759 // time around the switch. On backtrack we decrement the current position
2760 // and check it against the pushed value. This avoids pushing backtrack
2761 // information for each iteration of the loop, which could take up a lot of
2762 // space.
2763 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002764 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002765 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002766 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002767 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002768 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002769 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002770 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002771 Label loop_label;
2772 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002773 greedy_match_trace.set_stop_node(this);
2774 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002775 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002776 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002777 }
2778
2779 Label second_choice; // For use in greedy matches.
2780 macro_assembler->Bind(&second_choice);
2781
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002782 int first_normal_choice = greedy_loop ? 1 : 0;
2783
2784 int preload_characters = CalculatePreloadCharacters(compiler);
2785 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002786 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002787 bool preload_has_checked_bounds = preload_is_current;
2788
2789 AlternativeGenerationList alt_gens(choice_count);
2790
ager@chromium.org8bb60582008-12-11 12:02:20 +00002791 // For now we just call all choices one after the other. The idea ultimately
2792 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002793 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002794 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002795 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002796 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002797 ZoneList<Guard*>* guards = alternative.guards();
2798 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002799 Trace new_trace(*current_trace);
2800 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002801 preload_characters :
2802 0);
2803 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002804 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002805 }
ager@chromium.org32912102009-01-16 10:38:43 +00002806 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002807 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002808 alt_gen->expects_preload = preload_is_current;
2809 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002810 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002811 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002812 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002813 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002814 preload_has_checked_bounds,
2815 &alt_gen->possible_success,
2816 &alt_gen->quick_check_details,
2817 i < choice_count - 1)) {
2818 // Quick check was generated for this choice.
2819 preload_is_current = true;
2820 preload_has_checked_bounds = true;
2821 // On the last choice in the ChoiceNode we generated the quick
2822 // check to fall through on possible success. So now we need to
2823 // generate the full check inline.
2824 if (i == choice_count - 1) {
2825 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002826 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2827 new_trace.set_characters_preloaded(preload_characters);
2828 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002829 generate_full_check_inline = true;
2830 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002831 } else if (alt_gen->quick_check_details.cannot_match()) {
2832 if (i == choice_count - 1 && !greedy_loop) {
2833 macro_assembler->GoTo(trace->backtrack());
2834 }
2835 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002836 } else {
2837 // No quick check was generated. Put the full code here.
2838 // If this is not the first choice then there could be slow checks from
2839 // previous cases that go here when they fail. There's no reason to
2840 // insist that they preload characters since the slow check we are about
2841 // to generate probably can't use it.
2842 if (i != first_normal_choice) {
2843 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002844 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002845 }
2846 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002847 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002848 }
2849 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002850 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002851 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002852 if (new_trace.actions() != NULL) {
2853 new_trace.set_flush_budget(new_flush_budget);
2854 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002855 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002856 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002857 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002858 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002859 preload_is_current = false;
2860 }
2861 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002862 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002863 if (greedy_loop) {
2864 macro_assembler->Bind(&greedy_loop_label);
2865 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002866 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002867 // Otherwise try the second priority at an earlier position.
2868 macro_assembler->AdvanceCurrentPosition(-text_length);
2869 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002870 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002871
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002872 // At this point we need to generate slow checks for the alternatives where
2873 // the quick check was inlined. We can recognize these because the associated
2874 // label was bound.
2875 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2876 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002877 Trace new_trace(*current_trace);
2878 // If there are actions to be flushed we have to limit how many times
2879 // they are flushed. Take the budget of the parent trace and distribute
2880 // it fairly amongst the children.
2881 if (new_trace.actions() != NULL) {
2882 new_trace.set_flush_budget(new_flush_budget);
2883 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002884 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002885 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002886 alternatives_->at(i),
2887 alt_gen,
2888 preload_characters,
2889 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002890 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002891}
2892
2893
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002894void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002895 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002896 GuardedAlternative alternative,
2897 AlternativeGeneration* alt_gen,
2898 int preload_characters,
2899 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002900 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002901
2902 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2903 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002904 Trace out_of_line_trace(*trace);
2905 out_of_line_trace.set_characters_preloaded(preload_characters);
2906 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002907 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002908 ZoneList<Guard*>* guards = alternative.guards();
2909 int guard_count = (guards == NULL) ? 0 : guards->length();
2910 if (next_expects_preload) {
2911 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00002912 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002913 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002914 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002915 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002916 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002917 macro_assembler->Bind(&reload_current_char);
2918 // Reload the current character, since the next quick check expects that.
2919 // We don't need to check bounds here because we only get into this
2920 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00002921 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002922 NULL,
2923 false,
2924 preload_characters);
2925 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002926 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00002927 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002928 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002929 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002930 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002931 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002932 }
2933}
2934
2935
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002936void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002937 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002938 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002939 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002940 ASSERT(limit_result == CONTINUE);
2941
2942 RecursionCheck rc(compiler);
2943
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002944 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002945 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00002946 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002947 new_capture(data_.u_position_register.reg,
2948 data_.u_position_register.is_capture,
2949 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002950 Trace new_trace = *trace;
2951 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002952 on_success()->Emit(compiler, &new_trace);
2953 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002954 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002955 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002956 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002957 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00002958 Trace new_trace = *trace;
2959 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002960 on_success()->Emit(compiler, &new_trace);
2961 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002962 }
2963 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002964 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002965 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00002966 Trace new_trace = *trace;
2967 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002968 on_success()->Emit(compiler, &new_trace);
2969 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002970 }
2971 case CLEAR_CAPTURES: {
2972 Trace::DeferredClearCaptures
2973 new_capture(Interval(data_.u_clear_captures.range_from,
2974 data_.u_clear_captures.range_to));
2975 Trace new_trace = *trace;
2976 new_trace.add_action(&new_capture);
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 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002980 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002981 if (!trace->is_trivial()) {
2982 trace->Flush(compiler, this);
2983 } else {
2984 assembler->WriteCurrentPositionToRegister(
2985 data_.u_submatch.current_position_register, 0);
2986 assembler->WriteStackPointerToRegister(
2987 data_.u_submatch.stack_pointer_register);
2988 on_success()->Emit(compiler, trace);
2989 }
2990 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002991 case EMPTY_MATCH_CHECK: {
2992 int start_pos_reg = data_.u_empty_match_check.start_register;
2993 int stored_pos = 0;
2994 int rep_reg = data_.u_empty_match_check.repetition_register;
2995 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
2996 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
2997 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
2998 // If we know we haven't advanced and there is no minimum we
2999 // can just backtrack immediately.
3000 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003001 } else if (know_dist && stored_pos < trace->cp_offset()) {
3002 // If we know we've advanced we can generate the continuation
3003 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003004 on_success()->Emit(compiler, trace);
3005 } else if (!trace->is_trivial()) {
3006 trace->Flush(compiler, this);
3007 } else {
3008 Label skip_empty_check;
3009 // If we have a minimum number of repetitions we check the current
3010 // number first and skip the empty check if it's not enough.
3011 if (has_minimum) {
3012 int limit = data_.u_empty_match_check.repetition_limit;
3013 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3014 }
3015 // If the match is empty we bail out, otherwise we fall through
3016 // to the on-success continuation.
3017 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3018 trace->backtrack());
3019 assembler->Bind(&skip_empty_check);
3020 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003021 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003022 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003023 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003024 case POSITIVE_SUBMATCH_SUCCESS: {
3025 if (!trace->is_trivial()) {
3026 trace->Flush(compiler, this);
3027 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003028 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003029 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003030 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003031 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003032 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003033 int clear_register_count = data_.u_submatch.clear_register_count;
3034 if (clear_register_count == 0) {
3035 on_success()->Emit(compiler, trace);
3036 return;
3037 }
3038 int clear_registers_from = data_.u_submatch.clear_register_from;
3039 Label clear_registers_backtrack;
3040 Trace new_trace = *trace;
3041 new_trace.set_backtrack(&clear_registers_backtrack);
3042 on_success()->Emit(compiler, &new_trace);
3043
3044 assembler->Bind(&clear_registers_backtrack);
3045 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3046 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3047
3048 ASSERT(trace->backtrack() == NULL);
3049 assembler->Backtrack();
3050 return;
3051 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003052 default:
3053 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003054 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003055}
3056
3057
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003058void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003059 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003060 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003061 trace->Flush(compiler, this);
3062 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003063 }
3064
ager@chromium.org32912102009-01-16 10:38:43 +00003065 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003066 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003067 ASSERT(limit_result == CONTINUE);
3068
3069 RecursionCheck rc(compiler);
3070
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003071 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003072 if (compiler->ignore_case()) {
3073 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3074 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003075 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003076 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003077 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003078 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003079}
3080
3081
3082// -------------------------------------------------------------------
3083// Dot/dotty output
3084
3085
3086#ifdef DEBUG
3087
3088
3089class DotPrinter: public NodeVisitor {
3090 public:
3091 explicit DotPrinter(bool ignore_case)
3092 : ignore_case_(ignore_case),
3093 stream_(&alloc_) { }
3094 void PrintNode(const char* label, RegExpNode* node);
3095 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003096 void PrintAttributes(RegExpNode* from);
3097 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003098 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003099#define DECLARE_VISIT(Type) \
3100 virtual void Visit##Type(Type##Node* that);
3101FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3102#undef DECLARE_VISIT
3103 private:
3104 bool ignore_case_;
3105 HeapStringAllocator alloc_;
3106 StringStream stream_;
3107};
3108
3109
3110void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3111 stream()->Add("digraph G {\n graph [label=\"");
3112 for (int i = 0; label[i]; i++) {
3113 switch (label[i]) {
3114 case '\\':
3115 stream()->Add("\\\\");
3116 break;
3117 case '"':
3118 stream()->Add("\"");
3119 break;
3120 default:
3121 stream()->Put(label[i]);
3122 break;
3123 }
3124 }
3125 stream()->Add("\"];\n");
3126 Visit(node);
3127 stream()->Add("}\n");
3128 printf("%s", *(stream()->ToCString()));
3129}
3130
3131
3132void DotPrinter::Visit(RegExpNode* node) {
3133 if (node->info()->visited) return;
3134 node->info()->visited = true;
3135 node->Accept(this);
3136}
3137
3138
3139void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003140 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3141 Visit(on_failure);
3142}
3143
3144
3145class TableEntryBodyPrinter {
3146 public:
3147 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3148 : stream_(stream), choice_(choice) { }
3149 void Call(uc16 from, DispatchTable::Entry entry) {
3150 OutSet* out_set = entry.out_set();
3151 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3152 if (out_set->Get(i)) {
3153 stream()->Add(" n%p:s%io%i -> n%p;\n",
3154 choice(),
3155 from,
3156 i,
3157 choice()->alternatives()->at(i).node());
3158 }
3159 }
3160 }
3161 private:
3162 StringStream* stream() { return stream_; }
3163 ChoiceNode* choice() { return choice_; }
3164 StringStream* stream_;
3165 ChoiceNode* choice_;
3166};
3167
3168
3169class TableEntryHeaderPrinter {
3170 public:
3171 explicit TableEntryHeaderPrinter(StringStream* stream)
3172 : first_(true), stream_(stream) { }
3173 void Call(uc16 from, DispatchTable::Entry entry) {
3174 if (first_) {
3175 first_ = false;
3176 } else {
3177 stream()->Add("|");
3178 }
3179 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3180 OutSet* out_set = entry.out_set();
3181 int priority = 0;
3182 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3183 if (out_set->Get(i)) {
3184 if (priority > 0) stream()->Add("|");
3185 stream()->Add("<s%io%i> %i", from, i, priority);
3186 priority++;
3187 }
3188 }
3189 stream()->Add("}}");
3190 }
3191 private:
3192 bool first_;
3193 StringStream* stream() { return stream_; }
3194 StringStream* stream_;
3195};
3196
3197
3198class AttributePrinter {
3199 public:
3200 explicit AttributePrinter(DotPrinter* out)
3201 : out_(out), first_(true) { }
3202 void PrintSeparator() {
3203 if (first_) {
3204 first_ = false;
3205 } else {
3206 out_->stream()->Add("|");
3207 }
3208 }
3209 void PrintBit(const char* name, bool value) {
3210 if (!value) return;
3211 PrintSeparator();
3212 out_->stream()->Add("{%s}", name);
3213 }
3214 void PrintPositive(const char* name, int value) {
3215 if (value < 0) return;
3216 PrintSeparator();
3217 out_->stream()->Add("{%s|%x}", name, value);
3218 }
3219 private:
3220 DotPrinter* out_;
3221 bool first_;
3222};
3223
3224
3225void DotPrinter::PrintAttributes(RegExpNode* that) {
3226 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3227 "margin=0.1, fontsize=10, label=\"{",
3228 that);
3229 AttributePrinter printer(this);
3230 NodeInfo* info = that->info();
3231 printer.PrintBit("NI", info->follows_newline_interest);
3232 printer.PrintBit("WI", info->follows_word_interest);
3233 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003234 Label* label = that->label();
3235 if (label->is_bound())
3236 printer.PrintPositive("@", label->pos());
3237 stream()->Add("}\"];\n");
3238 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3239 "arrowhead=none];\n", that, that);
3240}
3241
3242
3243static const bool kPrintDispatchTable = false;
3244void DotPrinter::VisitChoice(ChoiceNode* that) {
3245 if (kPrintDispatchTable) {
3246 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3247 TableEntryHeaderPrinter header_printer(stream());
3248 that->GetTable(ignore_case_)->ForEach(&header_printer);
3249 stream()->Add("\"]\n", that);
3250 PrintAttributes(that);
3251 TableEntryBodyPrinter body_printer(stream(), that);
3252 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003253 } else {
3254 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3255 for (int i = 0; i < that->alternatives()->length(); i++) {
3256 GuardedAlternative alt = that->alternatives()->at(i);
3257 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3258 }
3259 }
3260 for (int i = 0; i < that->alternatives()->length(); i++) {
3261 GuardedAlternative alt = that->alternatives()->at(i);
3262 alt.node()->Accept(this);
3263 }
3264}
3265
3266
3267void DotPrinter::VisitText(TextNode* that) {
3268 stream()->Add(" n%p [label=\"", that);
3269 for (int i = 0; i < that->elements()->length(); i++) {
3270 if (i > 0) stream()->Add(" ");
3271 TextElement elm = that->elements()->at(i);
3272 switch (elm.type) {
3273 case TextElement::ATOM: {
3274 stream()->Add("'%w'", elm.data.u_atom->data());
3275 break;
3276 }
3277 case TextElement::CHAR_CLASS: {
3278 RegExpCharacterClass* node = elm.data.u_char_class;
3279 stream()->Add("[");
3280 if (node->is_negated())
3281 stream()->Add("^");
3282 for (int j = 0; j < node->ranges()->length(); j++) {
3283 CharacterRange range = node->ranges()->at(j);
3284 stream()->Add("%k-%k", range.from(), range.to());
3285 }
3286 stream()->Add("]");
3287 break;
3288 }
3289 default:
3290 UNREACHABLE();
3291 }
3292 }
3293 stream()->Add("\", shape=box, peripheries=2];\n");
3294 PrintAttributes(that);
3295 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3296 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003297}
3298
3299
3300void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3301 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3302 that,
3303 that->start_register(),
3304 that->end_register());
3305 PrintAttributes(that);
3306 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3307 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003308}
3309
3310
3311void DotPrinter::VisitEnd(EndNode* that) {
3312 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3313 PrintAttributes(that);
3314}
3315
3316
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003317void DotPrinter::VisitAssertion(AssertionNode* that) {
3318 stream()->Add(" n%p [", that);
3319 switch (that->type()) {
3320 case AssertionNode::AT_END:
3321 stream()->Add("label=\"$\", shape=septagon");
3322 break;
3323 case AssertionNode::AT_START:
3324 stream()->Add("label=\"^\", shape=septagon");
3325 break;
3326 case AssertionNode::AT_BOUNDARY:
3327 stream()->Add("label=\"\\b\", shape=septagon");
3328 break;
3329 case AssertionNode::AT_NON_BOUNDARY:
3330 stream()->Add("label=\"\\B\", shape=septagon");
3331 break;
3332 case AssertionNode::AFTER_NEWLINE:
3333 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3334 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003335 case AssertionNode::AFTER_WORD_CHARACTER:
3336 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3337 break;
3338 case AssertionNode::AFTER_NONWORD_CHARACTER:
3339 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3340 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003341 }
3342 stream()->Add("];\n");
3343 PrintAttributes(that);
3344 RegExpNode* successor = that->on_success();
3345 stream()->Add(" n%p -> n%p;\n", that, successor);
3346 Visit(successor);
3347}
3348
3349
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003350void DotPrinter::VisitAction(ActionNode* that) {
3351 stream()->Add(" n%p [", that);
3352 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003353 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003354 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3355 that->data_.u_store_register.reg,
3356 that->data_.u_store_register.value);
3357 break;
3358 case ActionNode::INCREMENT_REGISTER:
3359 stream()->Add("label=\"$%i++\", shape=octagon",
3360 that->data_.u_increment_register.reg);
3361 break;
3362 case ActionNode::STORE_POSITION:
3363 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3364 that->data_.u_position_register.reg);
3365 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003366 case ActionNode::BEGIN_SUBMATCH:
3367 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3368 that->data_.u_submatch.current_position_register);
3369 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003370 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003371 stream()->Add("label=\"escape\", shape=septagon");
3372 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003373 case ActionNode::EMPTY_MATCH_CHECK:
3374 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3375 that->data_.u_empty_match_check.start_register,
3376 that->data_.u_empty_match_check.repetition_register,
3377 that->data_.u_empty_match_check.repetition_limit);
3378 break;
3379 case ActionNode::CLEAR_CAPTURES: {
3380 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3381 that->data_.u_clear_captures.range_from,
3382 that->data_.u_clear_captures.range_to);
3383 break;
3384 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003385 }
3386 stream()->Add("];\n");
3387 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003388 RegExpNode* successor = that->on_success();
3389 stream()->Add(" n%p -> n%p;\n", that, successor);
3390 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003391}
3392
3393
3394class DispatchTableDumper {
3395 public:
3396 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3397 void Call(uc16 key, DispatchTable::Entry entry);
3398 StringStream* stream() { return stream_; }
3399 private:
3400 StringStream* stream_;
3401};
3402
3403
3404void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3405 stream()->Add("[%k-%k]: {", key, entry.to());
3406 OutSet* set = entry.out_set();
3407 bool first = true;
3408 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3409 if (set->Get(i)) {
3410 if (first) {
3411 first = false;
3412 } else {
3413 stream()->Add(", ");
3414 }
3415 stream()->Add("%i", i);
3416 }
3417 }
3418 stream()->Add("}\n");
3419}
3420
3421
3422void DispatchTable::Dump() {
3423 HeapStringAllocator alloc;
3424 StringStream stream(&alloc);
3425 DispatchTableDumper dumper(&stream);
3426 tree()->ForEach(&dumper);
3427 OS::PrintError("%s", *stream.ToCString());
3428}
3429
3430
3431void RegExpEngine::DotPrint(const char* label,
3432 RegExpNode* node,
3433 bool ignore_case) {
3434 DotPrinter printer(ignore_case);
3435 printer.PrintNode(label, node);
3436}
3437
3438
3439#endif // DEBUG
3440
3441
3442// -------------------------------------------------------------------
3443// Tree to graph conversion
3444
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003445static const int kSpaceRangeCount = 20;
3446static const int kSpaceRangeAsciiCount = 4;
3447static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3448 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3449 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3450
3451static const int kWordRangeCount = 8;
3452static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3453 '_', 'a', 'z' };
3454
3455static const int kDigitRangeCount = 2;
3456static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3457
3458static const int kLineTerminatorRangeCount = 6;
3459static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3460 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003461
3462RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003463 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003464 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3465 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003466 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003467}
3468
3469
3470RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003471 RegExpNode* on_success) {
3472 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003473}
3474
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003475static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3476 const uc16* special_class,
3477 int length) {
3478 ASSERT(ranges->length() != 0);
3479 ASSERT(length != 0);
3480 ASSERT(special_class[0] != 0);
3481 if (ranges->length() != (length >> 1) + 1) {
3482 return false;
3483 }
3484 CharacterRange range = ranges->at(0);
3485 if (range.from() != 0) {
3486 return false;
3487 }
3488 for (int i = 0; i < length; i += 2) {
3489 if (special_class[i] != (range.to() + 1)) {
3490 return false;
3491 }
3492 range = ranges->at((i >> 1) + 1);
3493 if (special_class[i+1] != range.from() - 1) {
3494 return false;
3495 }
3496 }
3497 if (range.to() != 0xffff) {
3498 return false;
3499 }
3500 return true;
3501}
3502
3503
3504static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3505 const uc16* special_class,
3506 int length) {
3507 if (ranges->length() * 2 != length) {
3508 return false;
3509 }
3510 for (int i = 0; i < length; i += 2) {
3511 CharacterRange range = ranges->at(i >> 1);
3512 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3513 return false;
3514 }
3515 }
3516 return true;
3517}
3518
3519
3520bool RegExpCharacterClass::is_standard() {
3521 // TODO(lrn): Remove need for this function, by not throwing away information
3522 // along the way.
3523 if (is_negated_) {
3524 return false;
3525 }
3526 if (set_.is_standard()) {
3527 return true;
3528 }
3529 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3530 set_.set_standard_set_type('s');
3531 return true;
3532 }
3533 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3534 set_.set_standard_set_type('S');
3535 return true;
3536 }
3537 if (CompareInverseRanges(set_.ranges(),
3538 kLineTerminatorRanges,
3539 kLineTerminatorRangeCount)) {
3540 set_.set_standard_set_type('.');
3541 return true;
3542 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003543 if (CompareRanges(set_.ranges(),
3544 kLineTerminatorRanges,
3545 kLineTerminatorRangeCount)) {
3546 set_.set_standard_set_type('n');
3547 return true;
3548 }
3549 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3550 set_.set_standard_set_type('w');
3551 return true;
3552 }
3553 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3554 set_.set_standard_set_type('W');
3555 return true;
3556 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003557 return false;
3558}
3559
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003560
3561RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003562 RegExpNode* on_success) {
3563 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003564}
3565
3566
3567RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003568 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003569 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3570 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003571 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003572 for (int i = 0; i < length; i++) {
3573 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003574 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003575 result->AddAlternative(alternative);
3576 }
3577 return result;
3578}
3579
3580
3581RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003582 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003583 return ToNode(min(),
3584 max(),
3585 is_greedy(),
3586 body(),
3587 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003588 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003589}
3590
3591
3592RegExpNode* RegExpQuantifier::ToNode(int min,
3593 int max,
3594 bool is_greedy,
3595 RegExpTree* body,
3596 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003597 RegExpNode* on_success,
3598 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003599 // x{f, t} becomes this:
3600 //
3601 // (r++)<-.
3602 // | `
3603 // | (x)
3604 // v ^
3605 // (r=0)-->(?)---/ [if r < t]
3606 // |
3607 // [if r >= f] \----> ...
3608 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003609
3610 // 15.10.2.5 RepeatMatcher algorithm.
3611 // The parser has already eliminated the case where max is 0. In the case
3612 // where max_match is zero the parser has removed the quantifier if min was
3613 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3614
3615 // If we know that we cannot match zero length then things are a little
3616 // simpler since we don't need to make the special zero length match check
3617 // from step 2.1. If the min and max are small we can unroll a little in
3618 // this case.
3619 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3620 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3621 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003622 bool body_can_be_empty = (body->min_match() == 0);
3623 int body_start_reg = RegExpCompiler::kNoRegister;
3624 Interval capture_registers = body->CaptureRegisters();
3625 bool needs_capture_clearing = !capture_registers.is_empty();
3626 if (body_can_be_empty) {
3627 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003628 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003629 // Only unroll if there are no captures and the body can't be
3630 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003631 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3632 int new_max = (max == kInfinity) ? max : max - min;
3633 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003634 RegExpNode* answer = ToNode(
3635 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003636 // Unroll the forced matches from 0 to min. This can cause chains of
3637 // TextNodes (which the parser does not generate). These should be
3638 // combined if it turns out they hinder good code generation.
3639 for (int i = 0; i < min; i++) {
3640 answer = body->ToNode(compiler, answer);
3641 }
3642 return answer;
3643 }
3644 if (max <= kMaxUnrolledMaxMatches) {
3645 ASSERT(min == 0);
3646 // Unroll the optional matches up to max.
3647 RegExpNode* answer = on_success;
3648 for (int i = 0; i < max; i++) {
3649 ChoiceNode* alternation = new ChoiceNode(2);
3650 if (is_greedy) {
3651 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3652 answer)));
3653 alternation->AddAlternative(GuardedAlternative(on_success));
3654 } else {
3655 alternation->AddAlternative(GuardedAlternative(on_success));
3656 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3657 answer)));
3658 }
3659 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003660 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003661 }
3662 return answer;
3663 }
3664 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003665 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003666 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003667 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003668 int reg_ctr = needs_counter
3669 ? compiler->AllocateRegister()
3670 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003671 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003672 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003673 RegExpNode* loop_return = needs_counter
3674 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3675 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003676 if (body_can_be_empty) {
3677 // If the body can be empty we need to check if it was and then
3678 // backtrack.
3679 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3680 reg_ctr,
3681 min,
3682 loop_return);
3683 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003684 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003685 if (body_can_be_empty) {
3686 // If the body can be empty we need to store the start position
3687 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003688 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003689 }
3690 if (needs_capture_clearing) {
3691 // Before entering the body of this loop we need to clear captures.
3692 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3693 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003694 GuardedAlternative body_alt(body_node);
3695 if (has_max) {
3696 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3697 body_alt.AddGuard(body_guard);
3698 }
3699 GuardedAlternative rest_alt(on_success);
3700 if (has_min) {
3701 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3702 rest_alt.AddGuard(rest_guard);
3703 }
3704 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003705 center->AddLoopAlternative(body_alt);
3706 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003707 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003708 center->AddContinueAlternative(rest_alt);
3709 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003710 }
3711 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003712 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003713 } else {
3714 return center;
3715 }
3716}
3717
3718
3719RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003720 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003721 NodeInfo info;
3722 switch (type()) {
3723 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003724 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003725 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003726 return AssertionNode::AtStart(on_success);
3727 case BOUNDARY:
3728 return AssertionNode::AtBoundary(on_success);
3729 case NON_BOUNDARY:
3730 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003731 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003732 return AssertionNode::AtEnd(on_success);
3733 case END_OF_LINE: {
3734 // Compile $ in multiline regexps as an alternation with a positive
3735 // lookahead in one side and an end-of-input on the other side.
3736 // We need two registers for the lookahead.
3737 int stack_pointer_register = compiler->AllocateRegister();
3738 int position_register = compiler->AllocateRegister();
3739 // The ChoiceNode to distinguish between a newline and end-of-input.
3740 ChoiceNode* result = new ChoiceNode(2);
3741 // Create a newline atom.
3742 ZoneList<CharacterRange>* newline_ranges =
3743 new ZoneList<CharacterRange>(3);
3744 CharacterRange::AddClassEscape('n', newline_ranges);
3745 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3746 TextNode* newline_matcher = new TextNode(
3747 newline_atom,
3748 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3749 position_register,
3750 0, // No captures inside.
3751 -1, // Ignored if no captures.
3752 on_success));
3753 // Create an end-of-input matcher.
3754 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3755 stack_pointer_register,
3756 position_register,
3757 newline_matcher);
3758 // Add the two alternatives to the ChoiceNode.
3759 GuardedAlternative eol_alternative(end_of_line);
3760 result->AddAlternative(eol_alternative);
3761 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3762 result->AddAlternative(end_alternative);
3763 return result;
3764 }
3765 default:
3766 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003767 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003768 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003769}
3770
3771
3772RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003773 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003774 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3775 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003776 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003777}
3778
3779
3780RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003781 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003782 return on_success;
3783}
3784
3785
3786RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003787 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003788 int stack_pointer_register = compiler->AllocateRegister();
3789 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003790
3791 const int registers_per_capture = 2;
3792 const int register_of_first_capture = 2;
3793 int register_count = capture_count_ * registers_per_capture;
3794 int register_start =
3795 register_of_first_capture + capture_from_ * registers_per_capture;
3796
ager@chromium.org8bb60582008-12-11 12:02:20 +00003797 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003798 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003799 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003800 stack_pointer_register,
3801 position_register,
3802 body()->ToNode(
3803 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003804 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3805 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003806 register_count,
3807 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003808 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003809 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003810 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003811 // We use a ChoiceNode for a negative lookahead because it has most of
3812 // the characteristics we need. It has the body of the lookahead as its
3813 // first alternative and the expression after the lookahead of the second
3814 // alternative. If the first alternative succeeds then the
3815 // NegativeSubmatchSuccess will unwind the stack including everything the
3816 // choice node set up and backtrack. If the first alternative fails then
3817 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003818 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3819 // ChoiceNode that knows to ignore the first exit when calculating quick
3820 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003821 GuardedAlternative body_alt(
3822 body()->ToNode(
3823 compiler,
3824 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003825 position_register,
3826 register_count,
3827 register_start)));
3828 ChoiceNode* choice_node =
3829 new NegativeLookaheadChoiceNode(body_alt,
3830 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003831 return ActionNode::BeginSubmatch(stack_pointer_register,
3832 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003833 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003834 }
3835}
3836
3837
3838RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003839 RegExpNode* on_success) {
3840 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003841}
3842
3843
3844RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3845 int index,
3846 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003847 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003848 int start_reg = RegExpCapture::StartRegister(index);
3849 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003850 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003851 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003852 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003853}
3854
3855
3856RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003857 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003858 ZoneList<RegExpTree*>* children = nodes();
3859 RegExpNode* current = on_success;
3860 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003861 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003862 }
3863 return current;
3864}
3865
3866
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003867static void AddClass(const uc16* elmv,
3868 int elmc,
3869 ZoneList<CharacterRange>* ranges) {
3870 for (int i = 0; i < elmc; i += 2) {
3871 ASSERT(elmv[i] <= elmv[i + 1]);
3872 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3873 }
3874}
3875
3876
3877static void AddClassNegated(const uc16 *elmv,
3878 int elmc,
3879 ZoneList<CharacterRange>* ranges) {
3880 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003881 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003882 uc16 last = 0x0000;
3883 for (int i = 0; i < elmc; i += 2) {
3884 ASSERT(last <= elmv[i] - 1);
3885 ASSERT(elmv[i] <= elmv[i + 1]);
3886 ranges->Add(CharacterRange(last, elmv[i] - 1));
3887 last = elmv[i + 1] + 1;
3888 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003889 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003890}
3891
3892
3893void CharacterRange::AddClassEscape(uc16 type,
3894 ZoneList<CharacterRange>* ranges) {
3895 switch (type) {
3896 case 's':
3897 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3898 break;
3899 case 'S':
3900 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3901 break;
3902 case 'w':
3903 AddClass(kWordRanges, kWordRangeCount, ranges);
3904 break;
3905 case 'W':
3906 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3907 break;
3908 case 'd':
3909 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3910 break;
3911 case 'D':
3912 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3913 break;
3914 case '.':
3915 AddClassNegated(kLineTerminatorRanges,
3916 kLineTerminatorRangeCount,
3917 ranges);
3918 break;
3919 // This is not a character range as defined by the spec but a
3920 // convenient shorthand for a character class that matches any
3921 // character.
3922 case '*':
3923 ranges->Add(CharacterRange::Everything());
3924 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003925 // This is the set of characters matched by the $ and ^ symbols
3926 // in multiline mode.
3927 case 'n':
3928 AddClass(kLineTerminatorRanges,
3929 kLineTerminatorRangeCount,
3930 ranges);
3931 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003932 default:
3933 UNREACHABLE();
3934 }
3935}
3936
3937
3938Vector<const uc16> CharacterRange::GetWordBounds() {
3939 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3940}
3941
3942
3943class CharacterRangeSplitter {
3944 public:
3945 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3946 ZoneList<CharacterRange>** excluded)
3947 : included_(included),
3948 excluded_(excluded) { }
3949 void Call(uc16 from, DispatchTable::Entry entry);
3950
3951 static const int kInBase = 0;
3952 static const int kInOverlay = 1;
3953
3954 private:
3955 ZoneList<CharacterRange>** included_;
3956 ZoneList<CharacterRange>** excluded_;
3957};
3958
3959
3960void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3961 if (!entry.out_set()->Get(kInBase)) return;
3962 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3963 ? included_
3964 : excluded_;
3965 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3966 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3967}
3968
3969
3970void CharacterRange::Split(ZoneList<CharacterRange>* base,
3971 Vector<const uc16> overlay,
3972 ZoneList<CharacterRange>** included,
3973 ZoneList<CharacterRange>** excluded) {
3974 ASSERT_EQ(NULL, *included);
3975 ASSERT_EQ(NULL, *excluded);
3976 DispatchTable table;
3977 for (int i = 0; i < base->length(); i++)
3978 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3979 for (int i = 0; i < overlay.length(); i += 2) {
3980 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
3981 CharacterRangeSplitter::kInOverlay);
3982 }
3983 CharacterRangeSplitter callback(included, excluded);
3984 table.ForEach(&callback);
3985}
3986
3987
ager@chromium.org38e4c712009-11-11 09:11:58 +00003988static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
3989 int bottom,
3990 int top);
3991
3992
3993void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
3994 bool is_ascii) {
3995 uc16 bottom = from();
3996 uc16 top = to();
3997 if (is_ascii) {
3998 if (bottom > String::kMaxAsciiCharCode) return;
3999 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4000 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004001 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004002 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004003 // If this is a singleton we just expand the one character.
ager@chromium.org38e4c712009-11-11 09:11:58 +00004004 int length = uncanonicalize.get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004005 for (int i = 0; i < length; i++) {
4006 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004007 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004008 ranges->Add(CharacterRange::Singleton(chars[i]));
4009 }
4010 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004011 } else if (bottom <= kRangeCanonicalizeMax &&
4012 top <= kRangeCanonicalizeMax) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004013 // If this is a range we expand the characters block by block,
4014 // expanding contiguous subranges (blocks) one at a time.
4015 // The approach is as follows. For a given start character we
4016 // look up the block that contains it, for instance 'a' if the
4017 // start character is 'c'. A block is characterized by the property
4018 // that all characters uncanonicalize in the same way as the first
4019 // element, except that each entry in the result is incremented
4020 // by the distance from the first element. So a-z is a block
4021 // because 'a' uncanonicalizes to ['a', 'A'] and the k'th letter
4022 // uncanonicalizes to ['a' + k, 'A' + k].
4023 // Once we've found the start point we look up its uncanonicalization
4024 // and produce a range for each element. For instance for [c-f]
4025 // we look up ['a', 'A'] and produce [c-f] and [C-F]. We then only
4026 // add a range if it is not already contained in the input, so [c-f]
4027 // will be skipped but [C-F] will be added. If this range is not
4028 // completely contained in a block we do this for all the blocks
4029 // covered by the range.
4030 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004031 // First, look up the block that contains the 'bottom' character.
4032 int length = canonrange.get(bottom, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004033 if (length == 0) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004034 range[0] = bottom;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004035 } else {
4036 ASSERT_EQ(1, length);
4037 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004038 int pos = bottom;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004039 // The start of the current block. Note that except for the first
4040 // iteration 'start' is always equal to 'pos'.
4041 int start;
4042 // If it is not the start point of a block the entry contains the
4043 // offset of the character from the start point.
4044 if ((range[0] & kStartMarker) == 0) {
4045 start = pos - range[0];
4046 } else {
4047 start = pos;
4048 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004049 // Then we add the ranges one at a time, incrementing the current
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004050 // position to be after the last block each time. The position
4051 // always points to the start of a block.
ager@chromium.org38e4c712009-11-11 09:11:58 +00004052 while (pos < top) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004053 length = canonrange.get(start, '\0', range);
4054 if (length == 0) {
4055 range[0] = start;
4056 } else {
4057 ASSERT_EQ(1, length);
4058 }
4059 ASSERT((range[0] & kStartMarker) != 0);
4060 // The start point of a block contains the distance to the end
4061 // of the range.
4062 int block_end = start + (range[0] & kPayloadMask) - 1;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004063 int end = (block_end > top) ? top : block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004064 length = uncanonicalize.get(start, '\0', range);
4065 for (int i = 0; i < length; i++) {
4066 uc32 c = range[i];
4067 uc16 range_from = c + (pos - start);
4068 uc16 range_to = c + (end - start);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004069 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004070 ranges->Add(CharacterRange(range_from, range_to));
4071 }
4072 }
4073 start = pos = block_end + 1;
4074 }
4075 } else {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004076 // Unibrow ranges don't work for high characters due to the "2^11 bug".
4077 // Therefore we do something dumber for these ranges.
4078 AddUncanonicals(ranges, bottom, top);
4079 }
4080}
4081
4082
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004083bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4084 ASSERT_NOT_NULL(ranges);
4085 int n = ranges->length();
4086 if (n <= 1) return true;
4087 int max = ranges->at(0).to();
4088 for (int i = 1; i < n; i++) {
4089 CharacterRange next_range = ranges->at(i);
4090 if (next_range.from() <= max + 1) return false;
4091 max = next_range.to();
4092 }
4093 return true;
4094}
4095
4096SetRelation CharacterRange::WordCharacterRelation(
4097 ZoneList<CharacterRange>* range) {
4098 ASSERT(IsCanonical(range));
4099 int i = 0; // Word character range index.
4100 int j = 0; // Argument range index.
4101 ASSERT_NE(0, kWordRangeCount);
4102 SetRelation result;
4103 if (range->length() == 0) {
4104 result.SetElementsInSecondSet();
4105 return result;
4106 }
4107 CharacterRange argument_range = range->at(0);
4108 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4109 while (i < kWordRangeCount && j < range->length()) {
4110 // Check the two ranges for the five cases:
4111 // - no overlap.
4112 // - partial overlap (there are elements in both ranges that isn't
4113 // in the other, and there are also elements that are in both).
4114 // - argument range entirely inside word range.
4115 // - word range entirely inside argument range.
4116 // - ranges are completely equal.
4117
4118 // First check for no overlap. The earlier range is not in the other set.
4119 if (argument_range.from() > word_range.to()) {
4120 // Ranges are disjoint. The earlier word range contains elements that
4121 // cannot be in the argument set.
4122 result.SetElementsInSecondSet();
4123 } else if (word_range.from() > argument_range.to()) {
4124 // Ranges are disjoint. The earlier argument range contains elements that
4125 // cannot be in the word set.
4126 result.SetElementsInFirstSet();
4127 } else if (word_range.from() <= argument_range.from() &&
4128 word_range.to() >= argument_range.from()) {
4129 result.SetElementsInBothSets();
4130 // argument range completely inside word range.
4131 if (word_range.from() < argument_range.from() ||
4132 word_range.to() > argument_range.from()) {
4133 result.SetElementsInSecondSet();
4134 }
4135 } else if (word_range.from() >= argument_range.from() &&
4136 word_range.to() <= argument_range.from()) {
4137 result.SetElementsInBothSets();
4138 result.SetElementsInFirstSet();
4139 } else {
4140 // There is overlap, and neither is a subrange of the other
4141 result.SetElementsInFirstSet();
4142 result.SetElementsInSecondSet();
4143 result.SetElementsInBothSets();
4144 }
4145 if (result.NonTrivialIntersection()) {
4146 // The result is as (im)precise as we can possibly make it.
4147 return result;
4148 }
4149 // Progress the range(s) with minimal to-character.
4150 uc16 word_to = word_range.to();
4151 uc16 argument_to = argument_range.to();
4152 if (argument_to <= word_to) {
4153 j++;
4154 if (j < range->length()) {
4155 argument_range = range->at(j);
4156 }
4157 }
4158 if (word_to <= argument_to) {
4159 i += 2;
4160 if (i < kWordRangeCount) {
4161 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4162 }
4163 }
4164 }
4165 // Check if anything wasn't compared in the loop.
4166 if (i < kWordRangeCount) {
4167 // word range contains something not in argument range.
4168 result.SetElementsInSecondSet();
4169 } else if (j < range->length()) {
4170 // Argument range contains something not in word range.
4171 result.SetElementsInFirstSet();
4172 }
4173
4174 return result;
4175}
4176
4177
ager@chromium.org38e4c712009-11-11 09:11:58 +00004178static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4179 int bottom,
4180 int top) {
4181 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4182 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4183 // this table is correct.
4184 // 0x0600 - 0x0fff
4185 // 0x1100 - 0x1cff
4186 // 0x2000 - 0x20ff
4187 // 0x2200 - 0x23ff
4188 // 0x2500 - 0x2bff
4189 // 0x2e00 - 0xa5ff
4190 // 0xa800 - 0xfaff
4191 // 0xfc00 - 0xfeff
4192 const int boundary_count = 18;
4193 // The ASCII boundary and the kRangeCanonicalizeMax boundary are also in this
4194 // array. This is to split up big ranges and not because they actually denote
4195 // a case-mapping-free-zone.
4196 ASSERT(CharacterRange::kRangeCanonicalizeMax < 0x600);
4197 const int kFirstRealCaselessZoneIndex = 2;
4198 int boundaries[] = {0x80, CharacterRange::kRangeCanonicalizeMax,
4199 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4200 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4201
4202 // Special ASCII rule from spec can save us some work here.
4203 if (bottom == 0x80 && top == 0xffff) return;
4204
4205 // We have optimized support for this range.
4206 if (top <= CharacterRange::kRangeCanonicalizeMax) {
4207 CharacterRange range(bottom, top);
4208 range.AddCaseEquivalents(ranges, false);
4209 return;
4210 }
4211
4212 // Split up very large ranges. This helps remove ranges where there are no
4213 // case mappings.
4214 for (int i = 0; i < boundary_count; i++) {
4215 if (bottom < boundaries[i] && top >= boundaries[i]) {
4216 AddUncanonicals(ranges, bottom, boundaries[i] - 1);
4217 AddUncanonicals(ranges, boundaries[i], top);
4218 return;
4219 }
4220 }
4221
4222 // If we are completely in a zone with no case mappings then we are done.
4223 // We start at 2 so as not to except the ASCII range from mappings.
4224 for (int i = kFirstRealCaselessZoneIndex; i < boundary_count; i += 2) {
4225 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4226#ifdef DEBUG
4227 for (int j = bottom; j <= top; j++) {
4228 unsigned current_char = j;
4229 int length = uncanonicalize.get(current_char, '\0', chars);
4230 for (int k = 0; k < length; k++) {
4231 ASSERT(chars[k] == current_char);
4232 }
4233 }
4234#endif
4235 return;
4236 }
4237 }
4238
4239 // Step through the range finding equivalent characters.
4240 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4241 for (int i = bottom; i <= top; i++) {
4242 int length = uncanonicalize.get(i, '\0', chars);
4243 for (int j = 0; j < length; j++) {
4244 uc32 chr = chars[j];
4245 if (chr != i && (chr < bottom || chr > top)) {
4246 characters->Add(chr);
4247 }
4248 }
4249 }
4250
4251 // Step through the equivalent characters finding simple ranges and
4252 // adding ranges to the character class.
4253 if (characters->length() > 0) {
4254 int new_from = characters->at(0);
4255 int new_to = new_from;
4256 for (int i = 1; i < characters->length(); i++) {
4257 int chr = characters->at(i);
4258 if (chr == new_to + 1) {
4259 new_to++;
4260 } else {
4261 if (new_to == new_from) {
4262 ranges->Add(CharacterRange::Singleton(new_from));
4263 } else {
4264 ranges->Add(CharacterRange(new_from, new_to));
4265 }
4266 new_from = new_to = chr;
4267 }
4268 }
4269 if (new_to == new_from) {
4270 ranges->Add(CharacterRange::Singleton(new_from));
4271 } else {
4272 ranges->Add(CharacterRange(new_from, new_to));
4273 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004274 }
4275}
4276
4277
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004278ZoneList<CharacterRange>* CharacterSet::ranges() {
4279 if (ranges_ == NULL) {
4280 ranges_ = new ZoneList<CharacterRange>(2);
4281 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4282 }
4283 return ranges_;
4284}
4285
4286
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004287// Move a number of elements in a zonelist to another position
4288// in the same list. Handles overlapping source and target areas.
4289static void MoveRanges(ZoneList<CharacterRange>* list,
4290 int from,
4291 int to,
4292 int count) {
4293 // Ranges are potentially overlapping.
4294 if (from < to) {
4295 for (int i = count - 1; i >= 0; i--) {
4296 list->at(to + i) = list->at(from + i);
4297 }
4298 } else {
4299 for (int i = 0; i < count; i++) {
4300 list->at(to + i) = list->at(from + i);
4301 }
4302 }
4303}
4304
4305
4306static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4307 int count,
4308 CharacterRange insert) {
4309 // Inserts a range into list[0..count[, which must be sorted
4310 // by from value and non-overlapping and non-adjacent, using at most
4311 // list[0..count] for the result. Returns the number of resulting
4312 // canonicalized ranges. Inserting a range may collapse existing ranges into
4313 // fewer ranges, so the return value can be anything in the range 1..count+1.
4314 uc16 from = insert.from();
4315 uc16 to = insert.to();
4316 int start_pos = 0;
4317 int end_pos = count;
4318 for (int i = count - 1; i >= 0; i--) {
4319 CharacterRange current = list->at(i);
4320 if (current.from() > to + 1) {
4321 end_pos = i;
4322 } else if (current.to() + 1 < from) {
4323 start_pos = i + 1;
4324 break;
4325 }
4326 }
4327
4328 // Inserted range overlaps, or is adjacent to, ranges at positions
4329 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4330 // not affected by the insertion.
4331 // If start_pos == end_pos, the range must be inserted before start_pos.
4332 // if start_pos < end_pos, the entire range from start_pos to end_pos
4333 // must be merged with the insert range.
4334
4335 if (start_pos == end_pos) {
4336 // Insert between existing ranges at position start_pos.
4337 if (start_pos < count) {
4338 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4339 }
4340 list->at(start_pos) = insert;
4341 return count + 1;
4342 }
4343 if (start_pos + 1 == end_pos) {
4344 // Replace single existing range at position start_pos.
4345 CharacterRange to_replace = list->at(start_pos);
4346 int new_from = Min(to_replace.from(), from);
4347 int new_to = Max(to_replace.to(), to);
4348 list->at(start_pos) = CharacterRange(new_from, new_to);
4349 return count;
4350 }
4351 // Replace a number of existing ranges from start_pos to end_pos - 1.
4352 // Move the remaining ranges down.
4353
4354 int new_from = Min(list->at(start_pos).from(), from);
4355 int new_to = Max(list->at(end_pos - 1).to(), to);
4356 if (end_pos < count) {
4357 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4358 }
4359 list->at(start_pos) = CharacterRange(new_from, new_to);
4360 return count - (end_pos - start_pos) + 1;
4361}
4362
4363
4364void CharacterSet::Canonicalize() {
4365 // Special/default classes are always considered canonical. The result
4366 // of calling ranges() will be sorted.
4367 if (ranges_ == NULL) return;
4368 CharacterRange::Canonicalize(ranges_);
4369}
4370
4371
4372void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4373 if (character_ranges->length() <= 1) return;
4374 // Check whether ranges are already canonical (increasing, non-overlapping,
4375 // non-adjacent).
4376 int n = character_ranges->length();
4377 int max = character_ranges->at(0).to();
4378 int i = 1;
4379 while (i < n) {
4380 CharacterRange current = character_ranges->at(i);
4381 if (current.from() <= max + 1) {
4382 break;
4383 }
4384 max = current.to();
4385 i++;
4386 }
4387 // Canonical until the i'th range. If that's all of them, we are done.
4388 if (i == n) return;
4389
4390 // The ranges at index i and forward are not canonicalized. Make them so by
4391 // doing the equivalent of insertion sort (inserting each into the previous
4392 // list, in order).
4393 // Notice that inserting a range can reduce the number of ranges in the
4394 // result due to combining of adjacent and overlapping ranges.
4395 int read = i; // Range to insert.
4396 int num_canonical = i; // Length of canonicalized part of list.
4397 do {
4398 num_canonical = InsertRangeInCanonicalList(character_ranges,
4399 num_canonical,
4400 character_ranges->at(read));
4401 read++;
4402 } while (read < n);
4403 character_ranges->Rewind(num_canonical);
4404
4405 ASSERT(CharacterRange::IsCanonical(character_ranges));
4406}
4407
4408
4409// Utility function for CharacterRange::Merge. Adds a range at the end of
4410// a canonicalized range list, if necessary merging the range with the last
4411// range of the list.
4412static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4413 if (set == NULL) return;
4414 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4415 int n = set->length();
4416 if (n > 0) {
4417 CharacterRange lastRange = set->at(n - 1);
4418 if (lastRange.to() == range.from() - 1) {
4419 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4420 return;
4421 }
4422 }
4423 set->Add(range);
4424}
4425
4426
4427static void AddRangeToSelectedSet(int selector,
4428 ZoneList<CharacterRange>* first_set,
4429 ZoneList<CharacterRange>* second_set,
4430 ZoneList<CharacterRange>* intersection_set,
4431 CharacterRange range) {
4432 switch (selector) {
4433 case kInsideFirst:
4434 AddRangeToSet(first_set, range);
4435 break;
4436 case kInsideSecond:
4437 AddRangeToSet(second_set, range);
4438 break;
4439 case kInsideBoth:
4440 AddRangeToSet(intersection_set, range);
4441 break;
4442 }
4443}
4444
4445
4446
4447void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4448 ZoneList<CharacterRange>* second_set,
4449 ZoneList<CharacterRange>* first_set_only_out,
4450 ZoneList<CharacterRange>* second_set_only_out,
4451 ZoneList<CharacterRange>* both_sets_out) {
4452 // Inputs are canonicalized.
4453 ASSERT(CharacterRange::IsCanonical(first_set));
4454 ASSERT(CharacterRange::IsCanonical(second_set));
4455 // Outputs are empty, if applicable.
4456 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4457 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4458 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4459
4460 // Merge sets by iterating through the lists in order of lowest "from" value,
4461 // and putting intervals into one of three sets.
4462
4463 if (first_set->length() == 0) {
4464 second_set_only_out->AddAll(*second_set);
4465 return;
4466 }
4467 if (second_set->length() == 0) {
4468 first_set_only_out->AddAll(*first_set);
4469 return;
4470 }
4471 // Indices into input lists.
4472 int i1 = 0;
4473 int i2 = 0;
4474 // Cache length of input lists.
4475 int n1 = first_set->length();
4476 int n2 = second_set->length();
4477 // Current range. May be invalid if state is kInsideNone.
4478 int from = 0;
4479 int to = -1;
4480 // Where current range comes from.
4481 int state = kInsideNone;
4482
4483 while (i1 < n1 || i2 < n2) {
4484 CharacterRange next_range;
4485 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004486 if (i2 == n2 ||
4487 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4488 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004489 next_range = first_set->at(i1++);
4490 range_source = kInsideFirst;
4491 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004492 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004493 next_range = second_set->at(i2++);
4494 range_source = kInsideSecond;
4495 }
4496 if (to < next_range.from()) {
4497 // Ranges disjoint: |current| |next|
4498 AddRangeToSelectedSet(state,
4499 first_set_only_out,
4500 second_set_only_out,
4501 both_sets_out,
4502 CharacterRange(from, to));
4503 from = next_range.from();
4504 to = next_range.to();
4505 state = range_source;
4506 } else {
4507 if (from < next_range.from()) {
4508 AddRangeToSelectedSet(state,
4509 first_set_only_out,
4510 second_set_only_out,
4511 both_sets_out,
4512 CharacterRange(from, next_range.from()-1));
4513 }
4514 if (to < next_range.to()) {
4515 // Ranges overlap: |current|
4516 // |next|
4517 AddRangeToSelectedSet(state | range_source,
4518 first_set_only_out,
4519 second_set_only_out,
4520 both_sets_out,
4521 CharacterRange(next_range.from(), to));
4522 from = to + 1;
4523 to = next_range.to();
4524 state = range_source;
4525 } else {
4526 // Range included: |current| , possibly ending at same character.
4527 // |next|
4528 AddRangeToSelectedSet(
4529 state | range_source,
4530 first_set_only_out,
4531 second_set_only_out,
4532 both_sets_out,
4533 CharacterRange(next_range.from(), next_range.to()));
4534 from = next_range.to() + 1;
4535 // If ranges end at same character, both ranges are consumed completely.
4536 if (next_range.to() == to) state = kInsideNone;
4537 }
4538 }
4539 }
4540 AddRangeToSelectedSet(state,
4541 first_set_only_out,
4542 second_set_only_out,
4543 both_sets_out,
4544 CharacterRange(from, to));
4545}
4546
4547
4548void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4549 ZoneList<CharacterRange>* negated_ranges) {
4550 ASSERT(CharacterRange::IsCanonical(ranges));
4551 ASSERT_EQ(0, negated_ranges->length());
4552 int range_count = ranges->length();
4553 uc16 from = 0;
4554 int i = 0;
4555 if (range_count > 0 && ranges->at(0).from() == 0) {
4556 from = ranges->at(0).to();
4557 i = 1;
4558 }
4559 while (i < range_count) {
4560 CharacterRange range = ranges->at(i);
4561 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4562 from = range.to();
4563 i++;
4564 }
4565 if (from < String::kMaxUC16CharCode) {
4566 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4567 }
4568}
4569
4570
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004571
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004572// -------------------------------------------------------------------
4573// Interest propagation
4574
4575
4576RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4577 for (int i = 0; i < siblings_.length(); i++) {
4578 RegExpNode* sibling = siblings_.Get(i);
4579 if (sibling->info()->Matches(info))
4580 return sibling;
4581 }
4582 return NULL;
4583}
4584
4585
4586RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4587 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004588 siblings_.Ensure(this);
4589 RegExpNode* result = TryGetSibling(info);
4590 if (result != NULL) return result;
4591 result = this->Clone();
4592 NodeInfo* new_info = result->info();
4593 new_info->ResetCompilationState();
4594 new_info->AddFromPreceding(info);
4595 AddSibling(result);
4596 *cloned = true;
4597 return result;
4598}
4599
4600
4601template <class C>
4602static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4603 NodeInfo full_info(*node->info());
4604 full_info.AddFromPreceding(info);
4605 bool cloned = false;
4606 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4607}
4608
4609
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004610// -------------------------------------------------------------------
4611// Splay tree
4612
4613
4614OutSet* OutSet::Extend(unsigned value) {
4615 if (Get(value))
4616 return this;
4617 if (successors() != NULL) {
4618 for (int i = 0; i < successors()->length(); i++) {
4619 OutSet* successor = successors()->at(i);
4620 if (successor->Get(value))
4621 return successor;
4622 }
4623 } else {
4624 successors_ = new ZoneList<OutSet*>(2);
4625 }
4626 OutSet* result = new OutSet(first_, remaining_);
4627 result->Set(value);
4628 successors()->Add(result);
4629 return result;
4630}
4631
4632
4633void OutSet::Set(unsigned value) {
4634 if (value < kFirstLimit) {
4635 first_ |= (1 << value);
4636 } else {
4637 if (remaining_ == NULL)
4638 remaining_ = new ZoneList<unsigned>(1);
4639 if (remaining_->is_empty() || !remaining_->Contains(value))
4640 remaining_->Add(value);
4641 }
4642}
4643
4644
4645bool OutSet::Get(unsigned value) {
4646 if (value < kFirstLimit) {
4647 return (first_ & (1 << value)) != 0;
4648 } else if (remaining_ == NULL) {
4649 return false;
4650 } else {
4651 return remaining_->Contains(value);
4652 }
4653}
4654
4655
4656const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4657const DispatchTable::Entry DispatchTable::Config::kNoValue;
4658
4659
4660void DispatchTable::AddRange(CharacterRange full_range, int value) {
4661 CharacterRange current = full_range;
4662 if (tree()->is_empty()) {
4663 // If this is the first range we just insert into the table.
4664 ZoneSplayTree<Config>::Locator loc;
4665 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4666 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4667 return;
4668 }
4669 // First see if there is a range to the left of this one that
4670 // overlaps.
4671 ZoneSplayTree<Config>::Locator loc;
4672 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4673 Entry* entry = &loc.value();
4674 // If we've found a range that overlaps with this one, and it
4675 // starts strictly to the left of this one, we have to fix it
4676 // because the following code only handles ranges that start on
4677 // or after the start point of the range we're adding.
4678 if (entry->from() < current.from() && entry->to() >= current.from()) {
4679 // Snap the overlapping range in half around the start point of
4680 // the range we're adding.
4681 CharacterRange left(entry->from(), current.from() - 1);
4682 CharacterRange right(current.from(), entry->to());
4683 // The left part of the overlapping range doesn't overlap.
4684 // Truncate the whole entry to be just the left part.
4685 entry->set_to(left.to());
4686 // The right part is the one that overlaps. We add this part
4687 // to the map and let the next step deal with merging it with
4688 // the range we're adding.
4689 ZoneSplayTree<Config>::Locator loc;
4690 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4691 loc.set_value(Entry(right.from(),
4692 right.to(),
4693 entry->out_set()));
4694 }
4695 }
4696 while (current.is_valid()) {
4697 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4698 (loc.value().from() <= current.to()) &&
4699 (loc.value().to() >= current.from())) {
4700 Entry* entry = &loc.value();
4701 // We have overlap. If there is space between the start point of
4702 // the range we're adding and where the overlapping range starts
4703 // then we have to add a range covering just that space.
4704 if (current.from() < entry->from()) {
4705 ZoneSplayTree<Config>::Locator ins;
4706 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4707 ins.set_value(Entry(current.from(),
4708 entry->from() - 1,
4709 empty()->Extend(value)));
4710 current.set_from(entry->from());
4711 }
4712 ASSERT_EQ(current.from(), entry->from());
4713 // If the overlapping range extends beyond the one we want to add
4714 // we have to snap the right part off and add it separately.
4715 if (entry->to() > current.to()) {
4716 ZoneSplayTree<Config>::Locator ins;
4717 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4718 ins.set_value(Entry(current.to() + 1,
4719 entry->to(),
4720 entry->out_set()));
4721 entry->set_to(current.to());
4722 }
4723 ASSERT(entry->to() <= current.to());
4724 // The overlapping range is now completely contained by the range
4725 // we're adding so we can just update it and move the start point
4726 // of the range we're adding just past it.
4727 entry->AddValue(value);
4728 // Bail out if the last interval ended at 0xFFFF since otherwise
4729 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004730 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004731 break;
4732 ASSERT(entry->to() + 1 > current.from());
4733 current.set_from(entry->to() + 1);
4734 } else {
4735 // There is no overlap so we can just add the range
4736 ZoneSplayTree<Config>::Locator ins;
4737 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4738 ins.set_value(Entry(current.from(),
4739 current.to(),
4740 empty()->Extend(value)));
4741 break;
4742 }
4743 }
4744}
4745
4746
4747OutSet* DispatchTable::Get(uc16 value) {
4748 ZoneSplayTree<Config>::Locator loc;
4749 if (!tree()->FindGreatestLessThan(value, &loc))
4750 return empty();
4751 Entry* entry = &loc.value();
4752 if (value <= entry->to())
4753 return entry->out_set();
4754 else
4755 return empty();
4756}
4757
4758
4759// -------------------------------------------------------------------
4760// Analysis
4761
4762
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004763void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004764 StackLimitCheck check;
4765 if (check.HasOverflowed()) {
4766 fail("Stack overflow");
4767 return;
4768 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004769 if (that->info()->been_analyzed || that->info()->being_analyzed)
4770 return;
4771 that->info()->being_analyzed = true;
4772 that->Accept(this);
4773 that->info()->being_analyzed = false;
4774 that->info()->been_analyzed = true;
4775}
4776
4777
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004778void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004779 // nothing to do
4780}
4781
4782
ager@chromium.org8bb60582008-12-11 12:02:20 +00004783void TextNode::CalculateOffsets() {
4784 int element_count = elements()->length();
4785 // Set up the offsets of the elements relative to the start. This is a fixed
4786 // quantity since a TextNode can only contain fixed-width things.
4787 int cp_offset = 0;
4788 for (int i = 0; i < element_count; i++) {
4789 TextElement& elm = elements()->at(i);
4790 elm.cp_offset = cp_offset;
4791 if (elm.type == TextElement::ATOM) {
4792 cp_offset += elm.data.u_atom->data().length();
4793 } else {
4794 cp_offset++;
4795 Vector<const uc16> quarks = elm.data.u_atom->data();
4796 }
4797 }
4798}
4799
4800
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004801void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004802 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004803 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004804 }
4805 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004806 if (!has_failed()) {
4807 that->CalculateOffsets();
4808 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004809}
4810
4811
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004812void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004813 RegExpNode* target = that->on_success();
4814 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004815 if (!has_failed()) {
4816 // If the next node is interested in what it follows then this node
4817 // has to be interested too so it can pass the information on.
4818 that->info()->AddFromFollowing(target->info());
4819 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004820}
4821
4822
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004823void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004824 NodeInfo* info = that->info();
4825 for (int i = 0; i < that->alternatives()->length(); i++) {
4826 RegExpNode* node = that->alternatives()->at(i).node();
4827 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004828 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004829 // Anything the following nodes need to know has to be known by
4830 // this node also, so it can pass it on.
4831 info->AddFromFollowing(node->info());
4832 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004833}
4834
4835
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004836void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4837 NodeInfo* info = that->info();
4838 for (int i = 0; i < that->alternatives()->length(); i++) {
4839 RegExpNode* node = that->alternatives()->at(i).node();
4840 if (node != that->loop_node()) {
4841 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004842 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004843 info->AddFromFollowing(node->info());
4844 }
4845 }
4846 // Check the loop last since it may need the value of this node
4847 // to get a correct result.
4848 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004849 if (!has_failed()) {
4850 info->AddFromFollowing(that->loop_node()->info());
4851 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004852}
4853
4854
4855void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004856 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004857}
4858
4859
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004860void Analysis::VisitAssertion(AssertionNode* that) {
4861 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004862 AssertionNode::AssertionNodeType type = that->type();
4863 if (type == AssertionNode::AT_BOUNDARY ||
4864 type == AssertionNode::AT_NON_BOUNDARY) {
4865 // Check if the following character is known to be a word character
4866 // or known to not be a word character.
4867 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4868
4869 CharacterRange::Canonicalize(following_chars);
4870
4871 SetRelation word_relation =
4872 CharacterRange::WordCharacterRelation(following_chars);
4873 if (word_relation.ContainedIn()) {
4874 // Following character is definitely a word character.
4875 type = (type == AssertionNode::AT_BOUNDARY) ?
4876 AssertionNode::AFTER_NONWORD_CHARACTER :
4877 AssertionNode::AFTER_WORD_CHARACTER;
4878 that->set_type(type);
4879 } else if (word_relation.Disjoint()) {
4880 // Following character is definitely *not* a word character.
4881 type = (type == AssertionNode::AT_BOUNDARY) ?
4882 AssertionNode::AFTER_WORD_CHARACTER :
4883 AssertionNode::AFTER_NONWORD_CHARACTER;
4884 that->set_type(type);
4885 }
4886 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004887}
4888
4889
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004890ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4891 if (first_character_set_ == NULL) {
4892 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4893 // If we can't find an exact solution within the budget, we
4894 // set the value to the set of every character, i.e., all characters
4895 // are possible.
4896 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4897 all_set->Add(CharacterRange::Everything());
4898 first_character_set_ = all_set;
4899 }
4900 }
4901 return first_character_set_;
4902}
4903
4904
4905int RegExpNode::ComputeFirstCharacterSet(int budget) {
4906 // Default behavior is to not be able to determine the first character.
4907 return kComputeFirstCharacterSetFail;
4908}
4909
4910
4911int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
4912 budget--;
4913 if (budget >= 0) {
4914 // Find loop min-iteration. It's the value of the guarded choice node
4915 // with a GEQ guard, if any.
4916 int min_repetition = 0;
4917
4918 for (int i = 0; i <= 1; i++) {
4919 GuardedAlternative alternative = alternatives()->at(i);
4920 ZoneList<Guard*>* guards = alternative.guards();
4921 if (guards != NULL && guards->length() > 0) {
4922 Guard* guard = guards->at(0);
4923 if (guard->op() == Guard::GEQ) {
4924 min_repetition = guard->value();
4925 break;
4926 }
4927 }
4928 }
4929
4930 budget = loop_node()->ComputeFirstCharacterSet(budget);
4931 if (budget >= 0) {
4932 ZoneList<CharacterRange>* character_set =
4933 loop_node()->first_character_set();
4934 if (body_can_be_zero_length() || min_repetition == 0) {
4935 budget = continue_node()->ComputeFirstCharacterSet(budget);
4936 if (budget < 0) return budget;
4937 ZoneList<CharacterRange>* body_set =
4938 continue_node()->first_character_set();
4939 ZoneList<CharacterRange>* union_set =
4940 new ZoneList<CharacterRange>(Max(character_set->length(),
4941 body_set->length()));
4942 CharacterRange::Merge(character_set,
4943 body_set,
4944 union_set,
4945 union_set,
4946 union_set);
4947 character_set = union_set;
4948 }
4949 set_first_character_set(character_set);
4950 }
4951 }
4952 return budget;
4953}
4954
4955
4956int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
4957 budget--;
4958 if (budget >= 0) {
4959 GuardedAlternative successor = this->alternatives()->at(1);
4960 RegExpNode* successor_node = successor.node();
4961 budget = successor_node->ComputeFirstCharacterSet(budget);
4962 if (budget >= 0) {
4963 set_first_character_set(successor_node->first_character_set());
4964 }
4965 }
4966 return budget;
4967}
4968
4969
4970// The first character set of an EndNode is unknowable. Just use the
4971// default implementation that fails and returns all characters as possible.
4972
4973
4974int AssertionNode::ComputeFirstCharacterSet(int budget) {
4975 budget -= 1;
4976 if (budget >= 0) {
4977 switch (type_) {
4978 case AT_END: {
4979 set_first_character_set(new ZoneList<CharacterRange>(0));
4980 break;
4981 }
4982 case AT_START:
4983 case AT_BOUNDARY:
4984 case AT_NON_BOUNDARY:
4985 case AFTER_NEWLINE:
4986 case AFTER_NONWORD_CHARACTER:
4987 case AFTER_WORD_CHARACTER: {
4988 ASSERT_NOT_NULL(on_success());
4989 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00004990 if (budget >= 0) {
4991 set_first_character_set(on_success()->first_character_set());
4992 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004993 break;
4994 }
4995 }
4996 }
4997 return budget;
4998}
4999
5000
5001int ActionNode::ComputeFirstCharacterSet(int budget) {
5002 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
5003 budget--;
5004 if (budget >= 0) {
5005 ASSERT_NOT_NULL(on_success());
5006 budget = on_success()->ComputeFirstCharacterSet(budget);
5007 if (budget >= 0) {
5008 set_first_character_set(on_success()->first_character_set());
5009 }
5010 }
5011 return budget;
5012}
5013
5014
5015int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5016 // We don't know anything about the first character of a backreference
5017 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005018 // The potential first characters are the first characters of the capture,
5019 // and the first characters of the on_success node, depending on whether the
5020 // capture can be empty and whether it is known to be participating or known
5021 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005022 return kComputeFirstCharacterSetFail;
5023}
5024
5025
5026int TextNode::ComputeFirstCharacterSet(int budget) {
5027 budget--;
5028 if (budget >= 0) {
5029 ASSERT_NE(0, elements()->length());
5030 TextElement text = elements()->at(0);
5031 if (text.type == TextElement::ATOM) {
5032 RegExpAtom* atom = text.data.u_atom;
5033 ASSERT_NE(0, atom->length());
5034 uc16 first_char = atom->data()[0];
5035 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5036 range->Add(CharacterRange(first_char, first_char));
5037 set_first_character_set(range);
5038 } else {
5039 ASSERT(text.type == TextElement::CHAR_CLASS);
5040 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005041 ZoneList<CharacterRange>* ranges = char_class->ranges();
5042 // TODO(lrn): Canonicalize ranges when they are created
5043 // instead of waiting until now.
5044 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005045 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005046 int length = ranges->length();
5047 int new_length = length + 1;
5048 if (length > 0) {
5049 if (ranges->at(0).from() == 0) new_length--;
5050 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5051 new_length--;
5052 }
5053 }
5054 ZoneList<CharacterRange>* negated_ranges =
5055 new ZoneList<CharacterRange>(new_length);
5056 CharacterRange::Negate(ranges, negated_ranges);
5057 set_first_character_set(negated_ranges);
5058 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005059 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005060 }
5061 }
5062 }
5063 return budget;
5064}
5065
5066
5067
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005068// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005069// Dispatch table construction
5070
5071
5072void DispatchTableConstructor::VisitEnd(EndNode* that) {
5073 AddRange(CharacterRange::Everything());
5074}
5075
5076
5077void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5078 node->set_being_calculated(true);
5079 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5080 for (int i = 0; i < alternatives->length(); i++) {
5081 set_choice_index(i);
5082 alternatives->at(i).node()->Accept(this);
5083 }
5084 node->set_being_calculated(false);
5085}
5086
5087
5088class AddDispatchRange {
5089 public:
5090 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5091 : constructor_(constructor) { }
5092 void Call(uc32 from, DispatchTable::Entry entry);
5093 private:
5094 DispatchTableConstructor* constructor_;
5095};
5096
5097
5098void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5099 CharacterRange range(from, entry.to());
5100 constructor_->AddRange(range);
5101}
5102
5103
5104void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5105 if (node->being_calculated())
5106 return;
5107 DispatchTable* table = node->GetTable(ignore_case_);
5108 AddDispatchRange adder(this);
5109 table->ForEach(&adder);
5110}
5111
5112
5113void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5114 // TODO(160): Find the node that we refer back to and propagate its start
5115 // set back to here. For now we just accept anything.
5116 AddRange(CharacterRange::Everything());
5117}
5118
5119
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005120void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5121 RegExpNode* target = that->on_success();
5122 target->Accept(this);
5123}
5124
5125
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005126static int CompareRangeByFrom(const CharacterRange* a,
5127 const CharacterRange* b) {
5128 return Compare<uc16>(a->from(), b->from());
5129}
5130
5131
5132void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5133 ranges->Sort(CompareRangeByFrom);
5134 uc16 last = 0;
5135 for (int i = 0; i < ranges->length(); i++) {
5136 CharacterRange range = ranges->at(i);
5137 if (last < range.from())
5138 AddRange(CharacterRange(last, range.from() - 1));
5139 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005140 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005141 return;
5142 } else {
5143 last = range.to() + 1;
5144 }
5145 }
5146 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005147 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005148}
5149
5150
5151void DispatchTableConstructor::VisitText(TextNode* that) {
5152 TextElement elm = that->elements()->at(0);
5153 switch (elm.type) {
5154 case TextElement::ATOM: {
5155 uc16 c = elm.data.u_atom->data()[0];
5156 AddRange(CharacterRange(c, c));
5157 break;
5158 }
5159 case TextElement::CHAR_CLASS: {
5160 RegExpCharacterClass* tree = elm.data.u_char_class;
5161 ZoneList<CharacterRange>* ranges = tree->ranges();
5162 if (tree->is_negated()) {
5163 AddInverse(ranges);
5164 } else {
5165 for (int i = 0; i < ranges->length(); i++)
5166 AddRange(ranges->at(i));
5167 }
5168 break;
5169 }
5170 default: {
5171 UNIMPLEMENTED();
5172 }
5173 }
5174}
5175
5176
5177void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005178 RegExpNode* target = that->on_success();
5179 target->Accept(this);
5180}
5181
5182
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005183RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5184 bool ignore_case,
5185 bool is_multiline,
5186 Handle<String> pattern,
5187 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005188 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005189 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005190 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005191 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005192 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005193 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005194 0,
5195 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005196 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005197 RegExpNode* node = captured_body;
5198 if (!data->tree->IsAnchored()) {
5199 // Add a .*? at the beginning, outside the body capture, unless
5200 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005201 RegExpNode* loop_node =
5202 RegExpQuantifier::ToNode(0,
5203 RegExpTree::kInfinity,
5204 false,
5205 new RegExpCharacterClass('*'),
5206 &compiler,
5207 captured_body,
5208 data->contains_anchor);
5209
5210 if (data->contains_anchor) {
5211 // Unroll loop once, to take care of the case that might start
5212 // at the start of input.
5213 ChoiceNode* first_step_node = new ChoiceNode(2);
5214 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5215 first_step_node->AddAlternative(GuardedAlternative(
5216 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5217 node = first_step_node;
5218 } else {
5219 node = loop_node;
5220 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005221 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005222 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005223 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005224 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005225 if (analysis.has_failed()) {
5226 const char* error_message = analysis.error_message();
5227 return CompilationResult(error_message);
5228 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005229
5230 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005231
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005232 // Create the correct assembler for the architecture.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00005233#ifdef V8_NATIVE_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005234 // Native regexp implementation.
5235
5236 NativeRegExpMacroAssembler::Mode mode =
5237 is_ascii ? NativeRegExpMacroAssembler::ASCII
5238 : NativeRegExpMacroAssembler::UC16;
5239
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005240#if V8_TARGET_ARCH_IA32
5241 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5242#elif V8_TARGET_ARCH_X64
5243 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5244#elif V8_TARGET_ARCH_ARM
5245 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005246#endif
5247
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00005248#else // ! V8_NATIVE_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005249 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005250 EmbeddedVector<byte, 1024> codes;
5251 RegExpMacroAssemblerIrregexp macro_assembler(codes);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005252#endif
5253
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005254 return compiler.Assemble(&macro_assembler,
5255 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005256 data->capture_count,
5257 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005258}
5259
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005260
5261int OffsetsVector::static_offsets_vector_[
5262 OffsetsVector::kStaticOffsetsVectorSize];
5263
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005264}} // namespace v8::internal