blob: 5dfde945001788c0d99413723e2acb7ad9294e71 [file] [log] [blame]
ager@chromium.org381abbb2009-02-25 13:23:22 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
ager@chromium.orga74f0da2008-12-03 16:05:52 +000030#include "ast.h"
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +000031#include "compiler.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032#include "execution.h"
33#include "factory.h"
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +000034#include "jsregexp.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "platform.h"
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000036#include "runtime.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "top.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000038#include "compilation-cache.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000039#include "string-stream.h"
40#include "parser.h"
41#include "regexp-macro-assembler.h"
42#include "regexp-macro-assembler-tracer.h"
43#include "regexp-macro-assembler-irregexp.h"
ager@chromium.org32912102009-01-16 10:38:43 +000044#include "regexp-stack.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000045
ricow@chromium.orgc9c80822010-04-21 08:22:37 +000046#ifndef V8_INTERPRETED_REGEXP
kasperl@chromium.org71affb52009-05-26 05:44:31 +000047#if V8_TARGET_ARCH_IA32
ager@chromium.org3a37e9b2009-04-27 09:26:21 +000048#include "ia32/regexp-macro-assembler-ia32.h"
ager@chromium.org9085a012009-05-11 19:22:57 +000049#elif V8_TARGET_ARCH_X64
ager@chromium.org9085a012009-05-11 19:22:57 +000050#include "x64/regexp-macro-assembler-x64.h"
51#elif V8_TARGET_ARCH_ARM
52#include "arm/regexp-macro-assembler-arm.h"
kasperl@chromium.org2abc4502009-07-02 07:00:29 +000053#else
54#error Unsupported target architecture.
ager@chromium.orga74f0da2008-12-03 16:05:52 +000055#endif
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000056#endif
ager@chromium.orga74f0da2008-12-03 16:05:52 +000057
58#include "interpreter-irregexp.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000059
ager@chromium.orga74f0da2008-12-03 16:05:52 +000060
kasperl@chromium.org71affb52009-05-26 05:44:31 +000061namespace v8 {
62namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063
64
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000065Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
66 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067 Handle<String> flags,
68 bool* has_pending_exception) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000069 // Call the construct code with 2 arguments.
70 Object** argv[2] = { Handle<Object>::cast(pattern).location(),
71 Handle<Object>::cast(flags).location() };
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000072 return Execution::New(constructor, 2, argv, has_pending_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073}
74
75
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000076static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
77 int flags = JSRegExp::NONE;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000078 for (int i = 0; i < str->length(); i++) {
79 switch (str->Get(i)) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000080 case 'i':
81 flags |= JSRegExp::IGNORE_CASE;
82 break;
83 case 'g':
84 flags |= JSRegExp::GLOBAL;
85 break;
86 case 'm':
87 flags |= JSRegExp::MULTILINE;
88 break;
89 }
90 }
91 return JSRegExp::Flags(flags);
92}
93
94
ager@chromium.orga74f0da2008-12-03 16:05:52 +000095static inline void ThrowRegExpException(Handle<JSRegExp> re,
96 Handle<String> pattern,
97 Handle<String> error_text,
98 const char* message) {
99 Handle<JSArray> array = Factory::NewJSArray(2);
100 SetElement(array, 0, pattern);
101 SetElement(array, 1, error_text);
102 Handle<Object> regexp_err = Factory::NewSyntaxError(message, array);
103 Top::Throw(*regexp_err);
104}
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000105
106
ager@chromium.org8bb60582008-12-11 12:02:20 +0000107// Generic RegExp methods. Dispatches to implementation specific methods.
108
109
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000110Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
111 Handle<String> pattern,
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000112 Handle<String> flag_str) {
113 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
114 Handle<FixedArray> cached = CompilationCache::LookupRegExp(pattern, flags);
115 bool in_cache = !cached.is_null();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000116 LOG(RegExpCompileEvent(re, in_cache));
117
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000118 Handle<Object> result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000119 if (in_cache) {
120 re->set_data(*cached);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000121 return re;
122 }
123 FlattenString(pattern);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000124 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000125 PostponeInterruptsScope postpone;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000126 RegExpCompileData parse_result;
127 FlatStringReader reader(pattern);
128 if (!ParseRegExp(&reader, flags.is_multiline(), &parse_result)) {
129 // Throw an exception if we fail to parse the pattern.
130 ThrowRegExpException(re,
131 pattern,
132 parse_result.error,
133 "malformed_regexp");
134 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000135 }
136
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000137 if (parse_result.simple && !flags.is_ignore_case()) {
138 // Parse-tree is a single atom that is equal to the pattern.
139 AtomCompile(re, pattern, flags, pattern);
140 } else if (parse_result.tree->IsAtom() &&
141 !flags.is_ignore_case() &&
142 parse_result.capture_count == 0) {
143 RegExpAtom* atom = parse_result.tree->AsAtom();
144 Vector<const uc16> atom_pattern = atom->data();
145 Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern);
146 AtomCompile(re, pattern, flags, atom_string);
147 } else {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000148 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000149 }
150 ASSERT(re->data()->IsFixedArray());
151 // Compilation succeeded so the data is set on the regexp
152 // and we can store it in the cache.
153 Handle<FixedArray> data(FixedArray::cast(re->data()));
154 CompilationCache::PutRegExp(pattern, flags, data);
155
156 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000157}
158
159
160Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
161 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000162 int index,
163 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000164 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000165 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000166 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000167 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000168 Handle<Object> result =
169 IrregexpExec(regexp, subject, index, last_match_info);
ager@chromium.org6f10e412009-02-13 10:11:16 +0000170 ASSERT(!result.is_null() || Top::has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000171 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000172 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000173 default:
174 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000175 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000176 }
177}
178
179
ager@chromium.org8bb60582008-12-11 12:02:20 +0000180// RegExp Atom implementation: Simple string search using indexOf.
181
182
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000183void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
184 Handle<String> pattern,
185 JSRegExp::Flags flags,
186 Handle<String> match_pattern) {
187 Factory::SetRegExpAtomData(re,
188 JSRegExp::ATOM,
189 pattern,
190 flags,
191 match_pattern);
192}
193
194
195static void SetAtomLastCapture(FixedArray* array,
196 String* subject,
197 int from,
198 int to) {
199 NoHandleAllocation no_handles;
200 RegExpImpl::SetLastCaptureCount(array, 2);
201 RegExpImpl::SetLastSubject(array, subject);
202 RegExpImpl::SetLastInput(array, subject);
203 RegExpImpl::SetCapture(array, 0, from);
204 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000205}
206
207
208Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
209 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000210 int index,
211 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000212 Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex)));
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000213
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000214 uint32_t start_index = index;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000215
ager@chromium.org7c537e22008-10-16 08:43:32 +0000216 int value = Runtime::StringMatch(subject, needle, start_index);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000217 if (value == -1) return Factory::null_value();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000218 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000219
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000220 {
221 NoHandleAllocation no_handles;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000222 FixedArray* array = FixedArray::cast(last_match_info->elements());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000223 SetAtomLastCapture(array, *subject, value, value + needle->length());
224 }
225 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000226}
227
228
ager@chromium.org8bb60582008-12-11 12:02:20 +0000229// Irregexp implementation.
230
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000231// Ensures that the regexp object contains a compiled version of the
232// source for either ASCII or non-ASCII strings.
233// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000234// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000235// If compilation fails, an exception is thrown and this function
236// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000237bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000238 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000239#ifdef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000240 if (compiled_code->IsByteArray()) return true;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000241#else // V8_INTERPRETED_REGEXP (RegExp native code)
242 if (compiled_code->IsCode()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000243#endif
244 return CompileIrregexp(re, is_ascii);
245}
ager@chromium.org8bb60582008-12-11 12:02:20 +0000246
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000247
248bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000249 // Compile the RegExp.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000250 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000251 PostponeInterruptsScope postpone;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000252 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
253 if (entry->IsJSObject()) {
254 // If it's a JSObject, a previous compilation failed and threw this object.
255 // Re-throw the object without trying again.
256 Top::Throw(entry);
257 return false;
258 }
259 ASSERT(entry->IsTheHole());
ager@chromium.org8bb60582008-12-11 12:02:20 +0000260
261 JSRegExp::Flags flags = re->GetFlags();
262
263 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000264 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000265 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000266 }
267
268 RegExpCompileData compile_data;
269 FlatStringReader reader(pattern);
270 if (!ParseRegExp(&reader, flags.is_multiline(), &compile_data)) {
271 // Throw an exception if we fail to parse the pattern.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000272 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000273 ThrowRegExpException(re,
274 pattern,
275 compile_data.error,
276 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000277 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000278 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000279 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000280 RegExpEngine::Compile(&compile_data,
281 flags.is_ignore_case(),
282 flags.is_multiline(),
283 pattern,
284 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000285 if (result.error_message != NULL) {
286 // Unable to compile regexp.
287 Handle<JSArray> array = Factory::NewJSArray(2);
288 SetElement(array, 0, pattern);
289 SetElement(array,
290 1,
291 Factory::NewStringFromUtf8(CStrVector(result.error_message)));
292 Handle<Object> regexp_err =
293 Factory::NewSyntaxError("malformed_regexp", array);
294 Top::Throw(*regexp_err);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000295 re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000296 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000297 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000298
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000299 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
300 data->set(JSRegExp::code_index(is_ascii), result.code);
301 int register_max = IrregexpMaxRegisterCount(*data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000302 if (result.num_registers > register_max) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000303 SetIrregexpMaxRegisterCount(*data, result.num_registers);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000304 }
305
306 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000307}
308
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000309
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000310int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
311 return Smi::cast(
312 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000313}
314
315
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000316void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
317 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000318}
319
320
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000321int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
322 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000323}
324
325
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000326int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
327 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000328}
329
330
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000331ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000332 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000333}
334
335
336Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000337 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000338}
339
340
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000341void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
342 Handle<String> pattern,
343 JSRegExp::Flags flags,
344 int capture_count) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000345 // Initialize compiled code entries to null.
346 Factory::SetRegExpIrregexpData(re,
347 JSRegExp::IRREGEXP,
348 pattern,
349 flags,
350 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000351}
352
353
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000354int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
355 Handle<String> subject) {
356 if (!subject->IsFlat()) {
357 FlattenString(subject);
358 }
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000359 // Check the asciiness of the underlying storage.
360 bool is_ascii;
361 {
362 AssertNoAllocation no_gc;
363 String* sequential_string = *subject;
364 if (subject->IsConsString()) {
365 sequential_string = ConsString::cast(*subject)->first();
366 }
367 is_ascii = sequential_string->IsAsciiRepresentation();
368 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000369 if (!EnsureCompiledIrregexp(regexp, is_ascii)) {
370 return -1;
371 }
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000372#ifdef V8_INTERPRETED_REGEXP
373 // Byte-code regexp needs space allocated for all its registers.
374 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
375#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000376 // Native regexp only needs room to output captures. Registers are handled
377 // internally.
378 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000379#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000380}
381
382
383RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(Handle<JSRegExp> regexp,
384 Handle<String> subject,
385 int index,
386 Vector<int> output) {
387 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()));
388
389 ASSERT(index >= 0);
390 ASSERT(index <= subject->length());
391 ASSERT(subject->IsFlat());
392
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000393 // A flat ASCII string might have a two-byte first part.
394 if (subject->IsConsString()) {
395 subject = Handle<String>(ConsString::cast(*subject)->first());
396 }
397
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000398#ifndef V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000399 ASSERT(output.length() >=
400 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
401 do {
402 bool is_ascii = subject->IsAsciiRepresentation();
403 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii));
404 NativeRegExpMacroAssembler::Result res =
405 NativeRegExpMacroAssembler::Match(code,
406 subject,
407 output.start(),
408 output.length(),
409 index);
410 if (res != NativeRegExpMacroAssembler::RETRY) {
411 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
412 Top::has_pending_exception());
413 STATIC_ASSERT(
414 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
415 STATIC_ASSERT(
416 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
417 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
418 == RE_EXCEPTION);
419 return static_cast<IrregexpResult>(res);
420 }
421 // If result is RETRY, the string has changed representation, and we
422 // must restart from scratch.
423 // In this case, it means we must make sure we are prepared to handle
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000424 // the, potentially, different subject (the string can switch between
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000425 // being internal and external, and even between being ASCII and UC16,
426 // but the characters are always the same).
427 IrregexpPrepare(regexp, subject);
428 } while (true);
429 UNREACHABLE();
430 return RE_EXCEPTION;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000431#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000432
433 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
434 bool is_ascii = subject->IsAsciiRepresentation();
435 // We must have done EnsureCompiledIrregexp, so we can get the number of
436 // registers.
437 int* register_vector = output.start();
438 int number_of_capture_registers =
439 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
440 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
441 register_vector[i] = -1;
442 }
443 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii));
444
445 if (IrregexpInterpreter::Match(byte_codes,
446 subject,
447 register_vector,
448 index)) {
449 return RE_SUCCESS;
450 }
451 return RE_FAILURE;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000452#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000453}
454
455
ager@chromium.org41826e72009-03-30 13:30:57 +0000456Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000457 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000458 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000459 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000460 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000461
ager@chromium.org8bb60582008-12-11 12:02:20 +0000462 // Prepare space for the return values.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000463#ifdef V8_INTERPRETED_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000464#ifdef DEBUG
465 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000466 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000467 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
468 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
469 }
470#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000471#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000472 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
473 if (required_registers < 0) {
474 // Compiling failed with an exception.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000475 ASSERT(Top::has_pending_exception());
476 return Handle<Object>::null();
477 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000478
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000479 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000480
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000481 IrregexpResult res = RegExpImpl::IrregexpExecOnce(
482 jsregexp, subject, previous_index, Vector<int>(registers.vector(),
483 registers.length()));
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000484 if (res == RE_SUCCESS) {
485 int capture_register_count =
486 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
487 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
488 AssertNoAllocation no_gc;
489 int* register_vector = registers.vector();
490 FixedArray* array = FixedArray::cast(last_match_info->elements());
491 for (int i = 0; i < capture_register_count; i += 2) {
492 SetCapture(array, i, register_vector[i]);
493 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000494 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000495 SetLastCaptureCount(array, capture_register_count);
496 SetLastSubject(array, *subject);
497 SetLastInput(array, *subject);
498 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000499 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000500 if (res == RE_EXCEPTION) {
501 ASSERT(Top::has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000502 return Handle<Object>::null();
503 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000504 ASSERT(res == RE_FAILURE);
505 return Factory::null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000506}
507
508
509// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000510// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000511//
512// The Irregexp regular expression engine is intended to be a complete
513// implementation of ECMAScript regular expressions. It generates either
514// bytecodes or native code.
515
516// The Irregexp regexp engine is structured in three steps.
517// 1) The parser generates an abstract syntax tree. See ast.cc.
518// 2) From the AST a node network is created. The nodes are all
519// subclasses of RegExpNode. The nodes represent states when
520// executing a regular expression. Several optimizations are
521// performed on the node network.
522// 3) From the nodes we generate either byte codes or native code
523// that can actually execute the regular expression (perform
524// the search). The code generation step is described in more
525// detail below.
526
527// Code generation.
528//
529// The nodes are divided into four main categories.
530// * Choice nodes
531// These represent places where the regular expression can
532// match in more than one way. For example on entry to an
533// alternation (foo|bar) or a repetition (*, +, ? or {}).
534// * Action nodes
535// These represent places where some action should be
536// performed. Examples include recording the current position
537// in the input string to a register (in order to implement
538// captures) or other actions on register for example in order
539// to implement the counters needed for {} repetitions.
540// * Matching nodes
541// These attempt to match some element part of the input string.
542// Examples of elements include character classes, plain strings
543// or back references.
544// * End nodes
545// These are used to implement the actions required on finding
546// a successful match or failing to find a match.
547//
548// The code generated (whether as byte codes or native code) maintains
549// some state as it runs. This consists of the following elements:
550//
551// * The capture registers. Used for string captures.
552// * Other registers. Used for counters etc.
553// * The current position.
554// * The stack of backtracking information. Used when a matching node
555// fails to find a match and needs to try an alternative.
556//
557// Conceptual regular expression execution model:
558//
559// There is a simple conceptual model of regular expression execution
560// which will be presented first. The actual code generated is a more
561// efficient simulation of the simple conceptual model:
562//
563// * Choice nodes are implemented as follows:
564// For each choice except the last {
565// push current position
566// push backtrack code location
567// <generate code to test for choice>
568// backtrack code location:
569// pop current position
570// }
571// <generate code to test for last choice>
572//
573// * Actions nodes are generated as follows
574// <push affected registers on backtrack stack>
575// <generate code to perform action>
576// push backtrack code location
577// <generate code to test for following nodes>
578// backtrack code location:
579// <pop affected registers to restore their state>
580// <pop backtrack location from stack and go to it>
581//
582// * Matching nodes are generated as follows:
583// if input string matches at current position
584// update current position
585// <generate code to test for following nodes>
586// else
587// <pop backtrack location from stack and go to it>
588//
589// Thus it can be seen that the current position is saved and restored
590// by the choice nodes, whereas the registers are saved and restored by
591// by the action nodes that manipulate them.
592//
593// The other interesting aspect of this model is that nodes are generated
594// at the point where they are needed by a recursive call to Emit(). If
595// the node has already been code generated then the Emit() call will
596// generate a jump to the previously generated code instead. In order to
597// limit recursion it is possible for the Emit() function to put the node
598// on a work list for later generation and instead generate a jump. The
599// destination of the jump is resolved later when the code is generated.
600//
601// Actual regular expression code generation.
602//
603// Code generation is actually more complicated than the above. In order
604// to improve the efficiency of the generated code some optimizations are
605// performed
606//
607// * Choice nodes have 1-character lookahead.
608// A choice node looks at the following character and eliminates some of
609// the choices immediately based on that character. This is not yet
610// implemented.
611// * Simple greedy loops store reduced backtracking information.
612// A quantifier like /.*foo/m will greedily match the whole input. It will
613// then need to backtrack to a point where it can match "foo". The naive
614// implementation of this would push each character position onto the
615// backtracking stack, then pop them off one by one. This would use space
616// proportional to the length of the input string. However since the "."
617// can only match in one way and always has a constant length (in this case
618// of 1) it suffices to store the current position on the top of the stack
619// once. Matching now becomes merely incrementing the current position and
620// backtracking becomes decrementing the current position and checking the
621// result against the stored current position. This is faster and saves
622// space.
623// * The current state is virtualized.
624// This is used to defer expensive operations until it is clear that they
625// are needed and to generate code for a node more than once, allowing
626// specialized an efficient versions of the code to be created. This is
627// explained in the section below.
628//
629// Execution state virtualization.
630//
631// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000632// manipulation in an object called the Trace. The Trace object can record a
633// current position offset, an optional backtrack code location on the top of
634// the virtualized backtrack stack and some register changes. When a node is
635// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000636// will emit code to bring the actual state into line with the virtual state.
637// Avoiding flushing the state can postpone some work (eg updates of capture
638// registers). Postponing work can save time when executing the regular
639// expression since it may be found that the work never has to be done as a
640// failure to match can occur. In addition it is much faster to jump to a
641// known backtrack code location than it is to pop an unknown backtrack
642// location from the stack and jump there.
643//
ager@chromium.org32912102009-01-16 10:38:43 +0000644// The virtual state found in the Trace affects code generation. For example
645// the virtual state contains the difference between the actual current
646// position and the virtual current position, and matching code needs to use
647// this offset to attempt a match in the correct location of the input
648// string. Therefore code generated for a non-trivial trace is specialized
649// to that trace. The code generator therefore has the ability to generate
650// code for each node several times. In order to limit the size of the
651// generated code there is an arbitrary limit on how many specialized sets of
652// code may be generated for a given node. If the limit is reached, the
653// trace is flushed and a generic version of the code for a node is emitted.
654// This is subsequently used for that node. The code emitted for non-generic
655// trace is not recorded in the node and so it cannot currently be reused in
656// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000657
658
659void RegExpTree::AppendToText(RegExpText* text) {
660 UNREACHABLE();
661}
662
663
664void RegExpAtom::AppendToText(RegExpText* text) {
665 text->AddElement(TextElement::Atom(this));
666}
667
668
669void RegExpCharacterClass::AppendToText(RegExpText* text) {
670 text->AddElement(TextElement::CharClass(this));
671}
672
673
674void RegExpText::AppendToText(RegExpText* text) {
675 for (int i = 0; i < elements()->length(); i++)
676 text->AddElement(elements()->at(i));
677}
678
679
680TextElement TextElement::Atom(RegExpAtom* atom) {
681 TextElement result = TextElement(ATOM);
682 result.data.u_atom = atom;
683 return result;
684}
685
686
687TextElement TextElement::CharClass(
688 RegExpCharacterClass* char_class) {
689 TextElement result = TextElement(CHAR_CLASS);
690 result.data.u_char_class = char_class;
691 return result;
692}
693
694
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000695int TextElement::length() {
696 if (type == ATOM) {
697 return data.u_atom->length();
698 } else {
699 ASSERT(type == CHAR_CLASS);
700 return 1;
701 }
702}
703
704
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000705DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
706 if (table_ == NULL) {
707 table_ = new DispatchTable();
708 DispatchTableConstructor cons(table_, ignore_case);
709 cons.BuildTable(this);
710 }
711 return table_;
712}
713
714
715class RegExpCompiler {
716 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000717 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000718
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000719 int AllocateRegister() {
720 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
721 reg_exp_too_big_ = true;
722 return next_register_;
723 }
724 return next_register_++;
725 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000726
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000727 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
728 RegExpNode* start,
729 int capture_count,
730 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000731
732 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
733
734 static const int kImplementationOffset = 0;
735 static const int kNumberOfRegistersOffset = 0;
736 static const int kCodeOffset = 1;
737
738 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
739 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000740
741 static const int kMaxRecursion = 100;
742 inline int recursion_depth() { return recursion_depth_; }
743 inline void IncrementRecursionDepth() { recursion_depth_++; }
744 inline void DecrementRecursionDepth() { recursion_depth_--; }
745
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000746 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
747
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000748 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000749 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000750
ager@chromium.org32912102009-01-16 10:38:43 +0000751 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000752 private:
753 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000754 int next_register_;
755 List<RegExpNode*>* work_list_;
756 int recursion_depth_;
757 RegExpMacroAssembler* macro_assembler_;
758 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000759 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000760 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000761};
762
763
764class RecursionCheck {
765 public:
766 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
767 compiler->IncrementRecursionDepth();
768 }
769 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
770 private:
771 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000772};
773
774
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000775static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
776 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000777}
778
779
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000780// Attempts to compile the regexp using an Irregexp code generator. Returns
781// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000782RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000783 : next_register_(2 * (capture_count + 1)),
784 work_list_(NULL),
785 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000786 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000787 ascii_(ascii),
788 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000789 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000790 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000791}
792
793
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000794RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000795 RegExpMacroAssembler* macro_assembler,
796 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000797 int capture_count,
798 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000799#ifdef DEBUG
800 if (FLAG_trace_regexp_assembler)
801 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
802 else
803#endif
804 macro_assembler_ = macro_assembler;
805 List <RegExpNode*> work_list(0);
806 work_list_ = &work_list;
807 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000808 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000809 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000810 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000811 macro_assembler_->Bind(&fail);
812 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000813 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000814 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000815 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000816 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
817
ager@chromium.org8bb60582008-12-11 12:02:20 +0000818 Handle<Object> code = macro_assembler_->GetCode(pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000819
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000820 work_list_ = NULL;
821#ifdef DEBUG
822 if (FLAG_trace_regexp_assembler) {
823 delete macro_assembler_;
824 }
825#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000826 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000827}
828
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000829
ager@chromium.org32912102009-01-16 10:38:43 +0000830bool Trace::DeferredAction::Mentions(int that) {
831 if (type() == ActionNode::CLEAR_CAPTURES) {
832 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
833 return range.Contains(that);
834 } else {
835 return reg() == that;
836 }
837}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000838
ager@chromium.org32912102009-01-16 10:38:43 +0000839
840bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000841 for (DeferredAction* action = actions_;
842 action != NULL;
843 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000844 if (action->Mentions(reg))
845 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000846 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000847 return false;
848}
849
850
ager@chromium.org32912102009-01-16 10:38:43 +0000851bool Trace::GetStoredPosition(int reg, int* cp_offset) {
852 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000853 for (DeferredAction* action = actions_;
854 action != NULL;
855 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000856 if (action->Mentions(reg)) {
857 if (action->type() == ActionNode::STORE_POSITION) {
858 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
859 return true;
860 } else {
861 return false;
862 }
863 }
864 }
865 return false;
866}
867
868
869int Trace::FindAffectedRegisters(OutSet* affected_registers) {
870 int max_register = RegExpCompiler::kNoRegister;
871 for (DeferredAction* action = actions_;
872 action != NULL;
873 action = action->next()) {
874 if (action->type() == ActionNode::CLEAR_CAPTURES) {
875 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
876 for (int i = range.from(); i <= range.to(); i++)
877 affected_registers->Set(i);
878 if (range.to() > max_register) max_register = range.to();
879 } else {
880 affected_registers->Set(action->reg());
881 if (action->reg() > max_register) max_register = action->reg();
882 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000883 }
884 return max_register;
885}
886
887
ager@chromium.org32912102009-01-16 10:38:43 +0000888void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
889 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000890 OutSet& registers_to_pop,
891 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000892 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000893 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
894 else if (registers_to_clear.Get(reg)) {
895 int clear_to = reg;
896 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
897 reg--;
898 }
899 assembler->ClearRegisters(reg, clear_to);
900 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000901 }
902}
903
904
ager@chromium.org32912102009-01-16 10:38:43 +0000905void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
906 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000907 OutSet& affected_registers,
908 OutSet* registers_to_pop,
909 OutSet* registers_to_clear) {
910 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
911 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
912
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000913 // Count pushes performed to force a stack limit check occasionally.
914 int pushes = 0;
915
ager@chromium.org8bb60582008-12-11 12:02:20 +0000916 for (int reg = 0; reg <= max_register; reg++) {
917 if (!affected_registers.Get(reg)) {
918 continue;
919 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000920
921 // The chronologically first deferred action in the trace
922 // is used to infer the action needed to restore a register
923 // to its previous state (or not, if it's safe to ignore it).
924 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
925 DeferredActionUndoType undo_action = IGNORE;
926
ager@chromium.org8bb60582008-12-11 12:02:20 +0000927 int value = 0;
928 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000929 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000930 int store_position = -1;
931 // This is a little tricky because we are scanning the actions in reverse
932 // historical order (newest first).
933 for (DeferredAction* action = actions_;
934 action != NULL;
935 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000936 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000937 switch (action->type()) {
938 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +0000939 Trace::DeferredSetRegister* psr =
940 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000941 if (!absolute) {
942 value += psr->value();
943 absolute = true;
944 }
945 // SET_REGISTER is currently only used for newly introduced loop
946 // counters. They can have a significant previous value if they
947 // occour in a loop. TODO(lrn): Propagate this information, so
948 // we can set undo_action to IGNORE if we know there is no value to
949 // restore.
950 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000951 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000952 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000953 break;
954 }
955 case ActionNode::INCREMENT_REGISTER:
956 if (!absolute) {
957 value++;
958 }
959 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000960 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000961 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000962 break;
963 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +0000964 Trace::DeferredCapture* pc =
965 static_cast<Trace::DeferredCapture*>(action);
966 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000967 store_position = pc->cp_offset();
968 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000969
970 // For captures we know that stores and clears alternate.
971 // Other register, are never cleared, and if the occur
972 // inside a loop, they might be assigned more than once.
973 if (reg <= 1) {
974 // Registers zero and one, aka "capture zero", is
975 // always set correctly if we succeed. There is no
976 // need to undo a setting on backtrack, because we
977 // will set it again or fail.
978 undo_action = IGNORE;
979 } else {
980 undo_action = pc->is_capture() ? CLEAR : RESTORE;
981 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000982 ASSERT(!absolute);
983 ASSERT_EQ(value, 0);
984 break;
985 }
ager@chromium.org32912102009-01-16 10:38:43 +0000986 case ActionNode::CLEAR_CAPTURES: {
987 // Since we're scanning in reverse order, if we've already
988 // set the position we have to ignore historically earlier
989 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000990 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +0000991 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000992 }
993 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +0000994 ASSERT(!absolute);
995 ASSERT_EQ(value, 0);
996 break;
997 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000998 default:
999 UNREACHABLE();
1000 break;
1001 }
1002 }
1003 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001004 // Prepare for the undo-action (e.g., push if it's going to be popped).
1005 if (undo_action == RESTORE) {
1006 pushes++;
1007 RegExpMacroAssembler::StackCheckFlag stack_check =
1008 RegExpMacroAssembler::kNoStackLimitCheck;
1009 if (pushes == push_limit) {
1010 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1011 pushes = 0;
1012 }
1013
1014 assembler->PushRegister(reg, stack_check);
1015 registers_to_pop->Set(reg);
1016 } else if (undo_action == CLEAR) {
1017 registers_to_clear->Set(reg);
1018 }
1019 // Perform the chronologically last action (or accumulated increment)
1020 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001021 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001022 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001023 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001024 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001025 } else if (absolute) {
1026 assembler->SetRegister(reg, value);
1027 } else if (value != 0) {
1028 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001029 }
1030 }
1031}
1032
1033
ager@chromium.org8bb60582008-12-11 12:02:20 +00001034// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001035// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001036// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001037void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001038 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001039
iposva@chromium.org245aa852009-02-10 00:49:54 +00001040 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001041
1042 if (actions_ == NULL && backtrack() == NULL) {
1043 // 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 +00001044 // a normal situation. We may also have to forget some information gained
1045 // through a quick check that was already performed.
1046 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001047 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001048 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001049 successor->Emit(compiler, &new_state);
1050 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001051 }
1052
1053 // Generate deferred actions here along with code to undo them again.
1054 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001055
ager@chromium.org381abbb2009-02-25 13:23:22 +00001056 if (backtrack() != NULL) {
1057 // Here we have a concrete backtrack location. These are set up by choice
1058 // nodes and so they indicate that we have a deferred save of the current
1059 // position which we may need to emit here.
1060 assembler->PushCurrentPosition();
1061 }
1062
ager@chromium.org8bb60582008-12-11 12:02:20 +00001063 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001064 OutSet registers_to_pop;
1065 OutSet registers_to_clear;
1066 PerformDeferredActions(assembler,
1067 max_register,
1068 affected_registers,
1069 &registers_to_pop,
1070 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001071 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001072 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001073 }
1074
1075 // Create a new trivial state and generate the node with that.
1076 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001077 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001078 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001079 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001080
1081 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001082 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001083 RestoreAffectedRegisters(assembler,
1084 max_register,
1085 registers_to_pop,
1086 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001087 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001088 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001089 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001090 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001091 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001092 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001093}
1094
1095
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001096void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001097 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001098
1099 // Omit flushing the trace. We discard the entire stack frame anyway.
1100
ager@chromium.org8bb60582008-12-11 12:02:20 +00001101 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001102 // We are completely independent of the trace, since we ignore it,
1103 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001104 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001105 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001106
1107 // Throw away everything on the backtrack stack since the start
1108 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001109 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1110 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001111 if (clear_capture_count_ > 0) {
1112 // Clear any captures that might have been performed during the success
1113 // of the body of the negative look-ahead.
1114 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1115 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1116 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001117 // Now that we have unwound the stack we find at the top of the stack the
1118 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001119 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001120}
1121
1122
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001123void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001124 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001125 trace->Flush(compiler, this);
1126 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001127 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001128 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001129 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001130 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001131 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001132 switch (action_) {
1133 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001134 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001135 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001136 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001137 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001138 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001139 case NEGATIVE_SUBMATCH_SUCCESS:
1140 // This case is handled in a different virtual method.
1141 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001142 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001143 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001144}
1145
1146
1147void GuardedAlternative::AddGuard(Guard* guard) {
1148 if (guards_ == NULL)
1149 guards_ = new ZoneList<Guard*>(1);
1150 guards_->Add(guard);
1151}
1152
1153
ager@chromium.org8bb60582008-12-11 12:02:20 +00001154ActionNode* ActionNode::SetRegister(int reg,
1155 int val,
1156 RegExpNode* on_success) {
1157 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001158 result->data_.u_store_register.reg = reg;
1159 result->data_.u_store_register.value = val;
1160 return result;
1161}
1162
1163
1164ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1165 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1166 result->data_.u_increment_register.reg = reg;
1167 return result;
1168}
1169
1170
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001171ActionNode* ActionNode::StorePosition(int reg,
1172 bool is_capture,
1173 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001174 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1175 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001176 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001177 return result;
1178}
1179
1180
ager@chromium.org32912102009-01-16 10:38:43 +00001181ActionNode* ActionNode::ClearCaptures(Interval range,
1182 RegExpNode* on_success) {
1183 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1184 result->data_.u_clear_captures.range_from = range.from();
1185 result->data_.u_clear_captures.range_to = range.to();
1186 return result;
1187}
1188
1189
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001190ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1191 int position_reg,
1192 RegExpNode* on_success) {
1193 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1194 result->data_.u_submatch.stack_pointer_register = stack_reg;
1195 result->data_.u_submatch.current_position_register = position_reg;
1196 return result;
1197}
1198
1199
ager@chromium.org8bb60582008-12-11 12:02:20 +00001200ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1201 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001202 int clear_register_count,
1203 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001204 RegExpNode* on_success) {
1205 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001206 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001207 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001208 result->data_.u_submatch.clear_register_count = clear_register_count;
1209 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001210 return result;
1211}
1212
1213
ager@chromium.org32912102009-01-16 10:38:43 +00001214ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1215 int repetition_register,
1216 int repetition_limit,
1217 RegExpNode* on_success) {
1218 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1219 result->data_.u_empty_match_check.start_register = start_register;
1220 result->data_.u_empty_match_check.repetition_register = repetition_register;
1221 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1222 return result;
1223}
1224
1225
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001226#define DEFINE_ACCEPT(Type) \
1227 void Type##Node::Accept(NodeVisitor* visitor) { \
1228 visitor->Visit##Type(this); \
1229 }
1230FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1231#undef DEFINE_ACCEPT
1232
1233
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001234void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1235 visitor->VisitLoopChoice(this);
1236}
1237
1238
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001239// -------------------------------------------------------------------
1240// Emit code.
1241
1242
1243void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1244 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001245 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001246 switch (guard->op()) {
1247 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001248 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001249 macro_assembler->IfRegisterGE(guard->reg(),
1250 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001251 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001252 break;
1253 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001254 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001255 macro_assembler->IfRegisterLT(guard->reg(),
1256 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001257 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001258 break;
1259 }
1260}
1261
1262
1263static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1264static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1265
1266
ager@chromium.org381abbb2009-02-25 13:23:22 +00001267// Returns the number of characters in the equivalence class, omitting those
1268// that cannot occur in the source string because it is ASCII.
1269static int GetCaseIndependentLetters(uc16 character,
1270 bool ascii_subject,
1271 unibrow::uchar* letters) {
1272 int length = uncanonicalize.get(character, '\0', letters);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00001273 // Unibrow returns 0 or 1 for characters where case independence is
ager@chromium.org381abbb2009-02-25 13:23:22 +00001274 // trivial.
1275 if (length == 0) {
1276 letters[0] = character;
1277 length = 1;
1278 }
1279 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1280 return length;
1281 }
1282 // The standard requires that non-ASCII characters cannot have ASCII
1283 // character codes in their equivalence class.
1284 return 0;
1285}
1286
1287
1288static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1289 uc16 c,
1290 Label* on_failure,
1291 int cp_offset,
1292 bool check,
1293 bool preloaded) {
1294 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1295 bool bound_checked = false;
1296 if (!preloaded) {
1297 assembler->LoadCurrentCharacter(
1298 cp_offset,
1299 on_failure,
1300 check);
1301 bound_checked = true;
1302 }
1303 assembler->CheckNotCharacter(c, on_failure);
1304 return bound_checked;
1305}
1306
1307
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001308// Only emits non-letters (things that don't have case). Only used for case
1309// independent matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001310static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1311 uc16 c,
1312 Label* on_failure,
1313 int cp_offset,
1314 bool check,
1315 bool preloaded) {
1316 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1317 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001318 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001319 int length = GetCaseIndependentLetters(c, ascii, chars);
1320 if (length < 1) {
1321 // This can't match. Must be an ASCII subject and a non-ASCII character.
1322 // We do not need to do anything since the ASCII pass already handled this.
1323 return false; // Bounds not checked.
1324 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001325 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001326 // We handle the length > 1 case in a later pass.
1327 if (length == 1) {
1328 if (ascii && c > String::kMaxAsciiCharCodeU) {
1329 // Can't match - see above.
1330 return false; // Bounds not checked.
1331 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001332 if (!preloaded) {
1333 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1334 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001335 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001336 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001337 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001338 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001339}
1340
1341
1342static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001343 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001344 uc16 c1,
1345 uc16 c2,
1346 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001347 uc16 char_mask;
1348 if (ascii) {
1349 char_mask = String::kMaxAsciiCharCode;
1350 } else {
1351 char_mask = String::kMaxUC16CharCode;
1352 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001353 uc16 exor = c1 ^ c2;
1354 // Check whether exor has only one bit set.
1355 if (((exor - 1) & exor) == 0) {
1356 // If c1 and c2 differ only by one bit.
1357 // Ecma262UnCanonicalize always gives the highest number last.
1358 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001359 uc16 mask = char_mask ^ exor;
1360 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001361 return true;
1362 }
1363 ASSERT(c2 > c1);
1364 uc16 diff = c2 - c1;
1365 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1366 // If the characters differ by 2^n but don't differ by one bit then
1367 // subtract the difference from the found character, then do the or
1368 // trick. We avoid the theoretical case where negative numbers are
1369 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001370 uc16 mask = char_mask ^ diff;
1371 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1372 diff,
1373 mask,
1374 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001375 return true;
1376 }
1377 return false;
1378}
1379
1380
ager@chromium.org381abbb2009-02-25 13:23:22 +00001381typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1382 uc16 c,
1383 Label* on_failure,
1384 int cp_offset,
1385 bool check,
1386 bool preloaded);
1387
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001388// Only emits letters (things that have case). Only used for case independent
1389// matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001390static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1391 uc16 c,
1392 Label* on_failure,
1393 int cp_offset,
1394 bool check,
1395 bool preloaded) {
1396 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1397 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001398 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001399 int length = GetCaseIndependentLetters(c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001400 if (length <= 1) return false;
1401 // We may not need to check against the end of the input string
1402 // if this character lies before a character that matched.
1403 if (!preloaded) {
1404 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001405 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001406 Label ok;
1407 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1408 switch (length) {
1409 case 2: {
1410 if (ShortCutEmitCharacterPair(macro_assembler,
1411 ascii,
1412 chars[0],
1413 chars[1],
1414 on_failure)) {
1415 } else {
1416 macro_assembler->CheckCharacter(chars[0], &ok);
1417 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1418 macro_assembler->Bind(&ok);
1419 }
1420 break;
1421 }
1422 case 4:
1423 macro_assembler->CheckCharacter(chars[3], &ok);
1424 // Fall through!
1425 case 3:
1426 macro_assembler->CheckCharacter(chars[0], &ok);
1427 macro_assembler->CheckCharacter(chars[1], &ok);
1428 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1429 macro_assembler->Bind(&ok);
1430 break;
1431 default:
1432 UNREACHABLE();
1433 break;
1434 }
1435 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001436}
1437
1438
1439static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1440 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001441 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001442 Label* on_failure,
1443 int cp_offset,
1444 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001445 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001446 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001447 int max_char;
1448 if (ascii) {
1449 max_char = String::kMaxAsciiCharCode;
1450 } else {
1451 max_char = String::kMaxUC16CharCode;
1452 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001453
1454 Label success;
1455
1456 Label* char_is_in_class =
1457 cc->is_negated() ? on_failure : &success;
1458
1459 int range_count = ranges->length();
1460
ager@chromium.org8bb60582008-12-11 12:02:20 +00001461 int last_valid_range = range_count - 1;
1462 while (last_valid_range >= 0) {
1463 CharacterRange& range = ranges->at(last_valid_range);
1464 if (range.from() <= max_char) {
1465 break;
1466 }
1467 last_valid_range--;
1468 }
1469
1470 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001471 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001472 // TODO(plesner): We can remove this when the node level does our
1473 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001474 macro_assembler->GoTo(on_failure);
1475 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001476 if (check_offset) {
1477 macro_assembler->CheckPosition(cp_offset, on_failure);
1478 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001479 return;
1480 }
1481
ager@chromium.org8bb60582008-12-11 12:02:20 +00001482 if (last_valid_range == 0 &&
1483 !cc->is_negated() &&
1484 ranges->at(0).IsEverything(max_char)) {
1485 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001486 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001487 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001488 }
1489 return;
1490 }
1491
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001492 if (!preloaded) {
1493 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001494 }
1495
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001496 if (cc->is_standard() &&
1497 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1498 on_failure)) {
1499 return;
1500 }
1501
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001502 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001503 CharacterRange& range = ranges->at(i);
1504 Label next_range;
1505 uc16 from = range.from();
1506 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001507 if (from > max_char) {
1508 continue;
1509 }
1510 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001511 if (to == from) {
1512 macro_assembler->CheckCharacter(to, char_is_in_class);
1513 } else {
1514 if (from != 0) {
1515 macro_assembler->CheckCharacterLT(from, &next_range);
1516 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001517 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001518 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1519 } else {
1520 macro_assembler->GoTo(char_is_in_class);
1521 }
1522 }
1523 macro_assembler->Bind(&next_range);
1524 }
1525
ager@chromium.org8bb60582008-12-11 12:02:20 +00001526 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001527 uc16 from = range.from();
1528 uc16 to = range.to();
1529
ager@chromium.org8bb60582008-12-11 12:02:20 +00001530 if (to > max_char) to = max_char;
1531 ASSERT(to >= from);
1532
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001533 if (to == from) {
1534 if (cc->is_negated()) {
1535 macro_assembler->CheckCharacter(to, on_failure);
1536 } else {
1537 macro_assembler->CheckNotCharacter(to, on_failure);
1538 }
1539 } else {
1540 if (from != 0) {
1541 if (cc->is_negated()) {
1542 macro_assembler->CheckCharacterLT(from, &success);
1543 } else {
1544 macro_assembler->CheckCharacterLT(from, on_failure);
1545 }
1546 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001547 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001548 if (cc->is_negated()) {
1549 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1550 } else {
1551 macro_assembler->CheckCharacterGT(to, on_failure);
1552 }
1553 } else {
1554 if (cc->is_negated()) {
1555 macro_assembler->GoTo(on_failure);
1556 }
1557 }
1558 }
1559 macro_assembler->Bind(&success);
1560}
1561
1562
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001563RegExpNode::~RegExpNode() {
1564}
1565
1566
ager@chromium.org8bb60582008-12-11 12:02:20 +00001567RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001568 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001569 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001570 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001571 return CONTINUE;
1572 }
1573
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001574 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001575 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001576 if (label_.is_bound()) {
1577 // We are being asked to generate a generic version, but that's already
1578 // been done so just go to it.
1579 macro_assembler->GoTo(&label_);
1580 return DONE;
1581 }
1582 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1583 // To avoid too deep recursion we push the node to the work queue and just
1584 // generate a goto here.
1585 compiler->AddWork(this);
1586 macro_assembler->GoTo(&label_);
1587 return DONE;
1588 }
1589 // Generate generic version of the node and bind the label for later use.
1590 macro_assembler->Bind(&label_);
1591 return CONTINUE;
1592 }
1593
1594 // We are being asked to make a non-generic version. Keep track of how many
1595 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001596 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001597 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001598 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001599 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1600 return CONTINUE;
1601 }
1602
ager@chromium.org32912102009-01-16 10:38:43 +00001603 // If we get here code has been generated for this node too many times or
1604 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001605 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001606 trace->Flush(compiler, this);
1607 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001608}
1609
1610
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001611int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001612 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1613 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001614 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001615}
1616
1617
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001618int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1619 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1620 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1621}
1622
1623
1624int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1625 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1626 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1627}
1628
1629
1630int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001631 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001632 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001633 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001634 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1635 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001636}
1637
1638
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001639int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
1640 int recursion_depth) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001641 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1642 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1643 // afterwards.
1644 RegExpNode* node = alternatives_->at(1).node();
1645 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1646}
1647
1648
1649void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1650 QuickCheckDetails* details,
1651 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001652 int filled_in,
1653 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001654 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1655 // afterwards.
1656 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001657 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001658}
1659
1660
1661int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1662 int recursion_depth,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001663 RegExpNode* ignore_this_node) {
1664 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1665 int min = 100;
1666 int choice_count = alternatives_->length();
1667 for (int i = 0; i < choice_count; i++) {
1668 RegExpNode* node = alternatives_->at(i).node();
1669 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001670 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1671 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001672 if (node_eats_at_least < min) min = node_eats_at_least;
1673 }
1674 return min;
1675}
1676
1677
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001678int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1679 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001680}
1681
1682
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001683int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1684 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001685}
1686
1687
1688// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1689static inline uint32_t SmearBitsRight(uint32_t v) {
1690 v |= v >> 1;
1691 v |= v >> 2;
1692 v |= v >> 4;
1693 v |= v >> 8;
1694 v |= v >> 16;
1695 return v;
1696}
1697
1698
1699bool QuickCheckDetails::Rationalize(bool asc) {
1700 bool found_useful_op = false;
1701 uint32_t char_mask;
1702 if (asc) {
1703 char_mask = String::kMaxAsciiCharCode;
1704 } else {
1705 char_mask = String::kMaxUC16CharCode;
1706 }
1707 mask_ = 0;
1708 value_ = 0;
1709 int char_shift = 0;
1710 for (int i = 0; i < characters_; i++) {
1711 Position* pos = &positions_[i];
1712 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1713 found_useful_op = true;
1714 }
1715 mask_ |= (pos->mask & char_mask) << char_shift;
1716 value_ |= (pos->value & char_mask) << char_shift;
1717 char_shift += asc ? 8 : 16;
1718 }
1719 return found_useful_op;
1720}
1721
1722
1723bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001724 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001725 bool preload_has_checked_bounds,
1726 Label* on_possible_success,
1727 QuickCheckDetails* details,
1728 bool fall_through_on_failure) {
1729 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001730 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1731 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001732 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001733 ASSERT(details->characters() == 1 ||
1734 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001735 uint32_t mask = details->mask();
1736 uint32_t value = details->value();
1737
1738 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1739
ager@chromium.org32912102009-01-16 10:38:43 +00001740 if (trace->characters_preloaded() != details->characters()) {
1741 assembler->LoadCurrentCharacter(trace->cp_offset(),
1742 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001743 !preload_has_checked_bounds,
1744 details->characters());
1745 }
1746
1747
1748 bool need_mask = true;
1749
1750 if (details->characters() == 1) {
1751 // If number of characters preloaded is 1 then we used a byte or 16 bit
1752 // load so the value is already masked down.
1753 uint32_t char_mask;
1754 if (compiler->ascii()) {
1755 char_mask = String::kMaxAsciiCharCode;
1756 } else {
1757 char_mask = String::kMaxUC16CharCode;
1758 }
1759 if ((mask & char_mask) == char_mask) need_mask = false;
1760 mask &= char_mask;
1761 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001762 // For 2-character preloads in ASCII mode or 1-character preloads in
1763 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001764 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001765 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1766 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001767 if ((mask & 0xffff) == 0xffff) need_mask = false;
1768 } else {
1769 if (mask == 0xffffffff) need_mask = false;
1770 }
1771 }
1772
1773 if (fall_through_on_failure) {
1774 if (need_mask) {
1775 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1776 } else {
1777 assembler->CheckCharacter(value, on_possible_success);
1778 }
1779 } else {
1780 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001781 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001782 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001783 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001784 }
1785 }
1786 return true;
1787}
1788
1789
1790// Here is the meat of GetQuickCheckDetails (see also the comment on the
1791// super-class in the .h file).
1792//
1793// We iterate along the text object, building up for each character a
1794// mask and value that can be used to test for a quick failure to match.
1795// The masks and values for the positions will be combined into a single
1796// machine word for the current character width in order to be used in
1797// generating a quick check.
1798void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1799 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001800 int characters_filled_in,
1801 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001802 ASSERT(characters_filled_in < details->characters());
1803 int characters = details->characters();
1804 int char_mask;
1805 int char_shift;
1806 if (compiler->ascii()) {
1807 char_mask = String::kMaxAsciiCharCode;
1808 char_shift = 8;
1809 } else {
1810 char_mask = String::kMaxUC16CharCode;
1811 char_shift = 16;
1812 }
1813 for (int k = 0; k < elms_->length(); k++) {
1814 TextElement elm = elms_->at(k);
1815 if (elm.type == TextElement::ATOM) {
1816 Vector<const uc16> quarks = elm.data.u_atom->data();
1817 for (int i = 0; i < characters && i < quarks.length(); i++) {
1818 QuickCheckDetails::Position* pos =
1819 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001820 uc16 c = quarks[i];
1821 if (c > char_mask) {
1822 // If we expect a non-ASCII character from an ASCII string,
1823 // there is no way we can match. Not even case independent
1824 // matching can turn an ASCII character into non-ASCII or
1825 // vice versa.
1826 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001827 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001828 return;
1829 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001830 if (compiler->ignore_case()) {
1831 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001832 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1833 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1834 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001835 // This letter has no case equivalents, so it's nice and simple
1836 // and the mask-compare will determine definitely whether we have
1837 // a match at this character position.
1838 pos->mask = char_mask;
1839 pos->value = c;
1840 pos->determines_perfectly = true;
1841 } else {
1842 uint32_t common_bits = char_mask;
1843 uint32_t bits = chars[0];
1844 for (int j = 1; j < length; j++) {
1845 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1846 common_bits ^= differing_bits;
1847 bits &= common_bits;
1848 }
1849 // If length is 2 and common bits has only one zero in it then
1850 // our mask and compare instruction will determine definitely
1851 // whether we have a match at this character position. Otherwise
1852 // it can only be an approximate check.
1853 uint32_t one_zero = (common_bits | ~char_mask);
1854 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1855 pos->determines_perfectly = true;
1856 }
1857 pos->mask = common_bits;
1858 pos->value = bits;
1859 }
1860 } else {
1861 // Don't ignore case. Nice simple case where the mask-compare will
1862 // determine definitely whether we have a match at this character
1863 // position.
1864 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001865 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001866 pos->determines_perfectly = true;
1867 }
1868 characters_filled_in++;
1869 ASSERT(characters_filled_in <= details->characters());
1870 if (characters_filled_in == details->characters()) {
1871 return;
1872 }
1873 }
1874 } else {
1875 QuickCheckDetails::Position* pos =
1876 details->positions(characters_filled_in);
1877 RegExpCharacterClass* tree = elm.data.u_char_class;
1878 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001879 if (tree->is_negated()) {
1880 // A quick check uses multi-character mask and compare. There is no
1881 // useful way to incorporate a negative char class into this scheme
1882 // so we just conservatively create a mask and value that will always
1883 // succeed.
1884 pos->mask = 0;
1885 pos->value = 0;
1886 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001887 int first_range = 0;
1888 while (ranges->at(first_range).from() > char_mask) {
1889 first_range++;
1890 if (first_range == ranges->length()) {
1891 details->set_cannot_match();
1892 pos->determines_perfectly = false;
1893 return;
1894 }
1895 }
1896 CharacterRange range = ranges->at(first_range);
1897 uc16 from = range.from();
1898 uc16 to = range.to();
1899 if (to > char_mask) {
1900 to = char_mask;
1901 }
1902 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001903 // A mask and compare is only perfect if the differing bits form a
1904 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001905 if ((differing_bits & (differing_bits + 1)) == 0 &&
1906 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001907 pos->determines_perfectly = true;
1908 }
1909 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001910 uint32_t bits = (from & common_bits);
1911 for (int i = first_range + 1; i < ranges->length(); i++) {
1912 CharacterRange range = ranges->at(i);
1913 uc16 from = range.from();
1914 uc16 to = range.to();
1915 if (from > char_mask) continue;
1916 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001917 // Here we are combining more ranges into the mask and compare
1918 // value. With each new range the mask becomes more sparse and
1919 // so the chances of a false positive rise. A character class
1920 // with multiple ranges is assumed never to be equivalent to a
1921 // mask and compare operation.
1922 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001923 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001924 new_common_bits = ~SmearBitsRight(new_common_bits);
1925 common_bits &= new_common_bits;
1926 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001927 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001928 common_bits ^= differing_bits;
1929 bits &= common_bits;
1930 }
1931 pos->mask = common_bits;
1932 pos->value = bits;
1933 }
1934 characters_filled_in++;
1935 ASSERT(characters_filled_in <= details->characters());
1936 if (characters_filled_in == details->characters()) {
1937 return;
1938 }
1939 }
1940 }
1941 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00001942 on_success()-> GetQuickCheckDetails(details,
1943 compiler,
1944 characters_filled_in,
1945 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001946}
1947
1948
1949void QuickCheckDetails::Clear() {
1950 for (int i = 0; i < characters_; i++) {
1951 positions_[i].mask = 0;
1952 positions_[i].value = 0;
1953 positions_[i].determines_perfectly = false;
1954 }
1955 characters_ = 0;
1956}
1957
1958
1959void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001960 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001961 if (by >= characters_) {
1962 Clear();
1963 return;
1964 }
1965 for (int i = 0; i < characters_ - by; i++) {
1966 positions_[i] = positions_[by + i];
1967 }
1968 for (int i = characters_ - by; i < characters_; i++) {
1969 positions_[i].mask = 0;
1970 positions_[i].value = 0;
1971 positions_[i].determines_perfectly = false;
1972 }
1973 characters_ -= by;
1974 // We could change mask_ and value_ here but we would never advance unless
1975 // they had already been used in a check and they won't be used again because
1976 // it would gain us nothing. So there's no point.
1977}
1978
1979
1980void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1981 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001982 if (other->cannot_match_) {
1983 return;
1984 }
1985 if (cannot_match_) {
1986 *this = *other;
1987 return;
1988 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001989 for (int i = from_index; i < characters_; i++) {
1990 QuickCheckDetails::Position* pos = positions(i);
1991 QuickCheckDetails::Position* other_pos = other->positions(i);
1992 if (pos->mask != other_pos->mask ||
1993 pos->value != other_pos->value ||
1994 !other_pos->determines_perfectly) {
1995 // Our mask-compare operation will be approximate unless we have the
1996 // exact same operation on both sides of the alternation.
1997 pos->determines_perfectly = false;
1998 }
1999 pos->mask &= other_pos->mask;
2000 pos->value &= pos->mask;
2001 other_pos->value &= pos->mask;
2002 uc16 differing_bits = (pos->value ^ other_pos->value);
2003 pos->mask &= ~differing_bits;
2004 pos->value &= pos->mask;
2005 }
2006}
2007
2008
ager@chromium.org32912102009-01-16 10:38:43 +00002009class VisitMarker {
2010 public:
2011 explicit VisitMarker(NodeInfo* info) : info_(info) {
2012 ASSERT(!info->visited);
2013 info->visited = true;
2014 }
2015 ~VisitMarker() {
2016 info_->visited = false;
2017 }
2018 private:
2019 NodeInfo* info_;
2020};
2021
2022
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002023void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2024 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002025 int characters_filled_in,
2026 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002027 if (body_can_be_zero_length_ || info()->visited) return;
2028 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002029 return ChoiceNode::GetQuickCheckDetails(details,
2030 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002031 characters_filled_in,
2032 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002033}
2034
2035
2036void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2037 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002038 int characters_filled_in,
2039 bool not_at_start) {
2040 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002041 int choice_count = alternatives_->length();
2042 ASSERT(choice_count > 0);
2043 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2044 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002045 characters_filled_in,
2046 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002047 for (int i = 1; i < choice_count; i++) {
2048 QuickCheckDetails new_details(details->characters());
2049 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002050 node->GetQuickCheckDetails(&new_details, compiler,
2051 characters_filled_in,
2052 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002053 // Here we merge the quick match details of the two branches.
2054 details->Merge(&new_details, characters_filled_in);
2055 }
2056}
2057
2058
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002059// Check for [0-9A-Z_a-z].
2060static void EmitWordCheck(RegExpMacroAssembler* assembler,
2061 Label* word,
2062 Label* non_word,
2063 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002064 if (assembler->CheckSpecialCharacterClass(
2065 fall_through_on_word ? 'w' : 'W',
2066 fall_through_on_word ? non_word : word)) {
2067 // Optimized implementation available.
2068 return;
2069 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002070 assembler->CheckCharacterGT('z', non_word);
2071 assembler->CheckCharacterLT('0', non_word);
2072 assembler->CheckCharacterGT('a' - 1, word);
2073 assembler->CheckCharacterLT('9' + 1, word);
2074 assembler->CheckCharacterLT('A', non_word);
2075 assembler->CheckCharacterLT('Z' + 1, word);
2076 if (fall_through_on_word) {
2077 assembler->CheckNotCharacter('_', non_word);
2078 } else {
2079 assembler->CheckCharacter('_', word);
2080 }
2081}
2082
2083
2084// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2085// that matches newline or the start of input).
2086static void EmitHat(RegExpCompiler* compiler,
2087 RegExpNode* on_success,
2088 Trace* trace) {
2089 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2090 // We will be loading the previous character into the current character
2091 // register.
2092 Trace new_trace(*trace);
2093 new_trace.InvalidateCurrentCharacter();
2094
2095 Label ok;
2096 if (new_trace.cp_offset() == 0) {
2097 // The start of input counts as a newline in this context, so skip to
2098 // ok if we are at the start.
2099 assembler->CheckAtStart(&ok);
2100 }
2101 // We already checked that we are not at the start of input so it must be
2102 // OK to load the previous character.
2103 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2104 new_trace.backtrack(),
2105 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002106 if (!assembler->CheckSpecialCharacterClass('n',
2107 new_trace.backtrack())) {
2108 // Newline means \n, \r, 0x2028 or 0x2029.
2109 if (!compiler->ascii()) {
2110 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2111 }
2112 assembler->CheckCharacter('\n', &ok);
2113 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002114 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002115 assembler->Bind(&ok);
2116 on_success->Emit(compiler, &new_trace);
2117}
2118
2119
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002120// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2121// when we know whether the next character must be a word character or not.
2122static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2123 RegExpCompiler* compiler,
2124 RegExpNode* on_success,
2125 Trace* trace) {
2126 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2127 Label done;
2128
2129 Trace new_trace(*trace);
2130
2131 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2132 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2133 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2134
2135 // Check whether previous character was a word character.
2136 switch (trace->at_start()) {
2137 case Trace::TRUE:
2138 if (expect_word_character) {
2139 assembler->GoTo(on_non_word);
2140 }
2141 break;
2142 case Trace::UNKNOWN:
2143 ASSERT_EQ(0, trace->cp_offset());
2144 assembler->CheckAtStart(on_non_word);
2145 // Fall through.
2146 case Trace::FALSE:
2147 int prev_char_offset = trace->cp_offset() - 1;
2148 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2149 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2150 // We may or may not have loaded the previous character.
2151 new_trace.InvalidateCurrentCharacter();
2152 }
2153
2154 assembler->Bind(&done);
2155
2156 on_success->Emit(compiler, &new_trace);
2157}
2158
2159
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002160// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2161static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2162 RegExpCompiler* compiler,
2163 RegExpNode* on_success,
2164 Trace* trace) {
2165 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2166 Label before_non_word;
2167 Label before_word;
2168 if (trace->characters_preloaded() != 1) {
2169 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2170 }
2171 // Fall through on non-word.
2172 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2173
2174 // We will be loading the previous character into the current character
2175 // register.
2176 Trace new_trace(*trace);
2177 new_trace.InvalidateCurrentCharacter();
2178
2179 Label ok;
2180 Label* boundary;
2181 Label* not_boundary;
2182 if (type == AssertionNode::AT_BOUNDARY) {
2183 boundary = &ok;
2184 not_boundary = new_trace.backtrack();
2185 } else {
2186 not_boundary = &ok;
2187 boundary = new_trace.backtrack();
2188 }
2189
2190 // Next character is not a word character.
2191 assembler->Bind(&before_non_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(not_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 // Fall through on non-word.
2203 EmitWordCheck(assembler, boundary, not_boundary, false);
2204 assembler->GoTo(not_boundary);
2205
2206 // Next character is a word character.
2207 assembler->Bind(&before_word);
2208 if (new_trace.cp_offset() == 0) {
2209 // The start of input counts as a non-word character, so the question is
2210 // decided if we are at the start.
2211 assembler->CheckAtStart(boundary);
2212 }
2213 // We already checked that we are not at the start of input so it must be
2214 // OK to load the previous character.
2215 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2216 &ok, // Unused dummy label in this call.
2217 false);
2218 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2219 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2220
2221 assembler->Bind(&ok);
2222
2223 on_success->Emit(compiler, &new_trace);
2224}
2225
2226
iposva@chromium.org245aa852009-02-10 00:49:54 +00002227void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2228 RegExpCompiler* compiler,
2229 int filled_in,
2230 bool not_at_start) {
2231 if (type_ == AT_START && not_at_start) {
2232 details->set_cannot_match();
2233 return;
2234 }
2235 return on_success()->GetQuickCheckDetails(details,
2236 compiler,
2237 filled_in,
2238 not_at_start);
2239}
2240
2241
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002242void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2243 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2244 switch (type_) {
2245 case AT_END: {
2246 Label ok;
2247 assembler->CheckPosition(trace->cp_offset(), &ok);
2248 assembler->GoTo(trace->backtrack());
2249 assembler->Bind(&ok);
2250 break;
2251 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002252 case AT_START: {
2253 if (trace->at_start() == Trace::FALSE) {
2254 assembler->GoTo(trace->backtrack());
2255 return;
2256 }
2257 if (trace->at_start() == Trace::UNKNOWN) {
2258 assembler->CheckNotAtStart(trace->backtrack());
2259 Trace at_start_trace = *trace;
2260 at_start_trace.set_at_start(true);
2261 on_success()->Emit(compiler, &at_start_trace);
2262 return;
2263 }
2264 }
2265 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002266 case AFTER_NEWLINE:
2267 EmitHat(compiler, on_success(), trace);
2268 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002269 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002270 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002271 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2272 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002273 }
2274 case AFTER_WORD_CHARACTER:
2275 case AFTER_NONWORD_CHARACTER: {
2276 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2277 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002278 }
2279 on_success()->Emit(compiler, trace);
2280}
2281
2282
ager@chromium.org381abbb2009-02-25 13:23:22 +00002283static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2284 if (quick_check == NULL) return false;
2285 if (offset >= quick_check->characters()) return false;
2286 return quick_check->positions(offset)->determines_perfectly;
2287}
2288
2289
2290static void UpdateBoundsCheck(int index, int* checked_up_to) {
2291 if (index > *checked_up_to) {
2292 *checked_up_to = index;
2293 }
2294}
2295
2296
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002297// We call this repeatedly to generate code for each pass over the text node.
2298// The passes are in increasing order of difficulty because we hope one
2299// of the first passes will fail in which case we are saved the work of the
2300// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2301// we will check the '%' in the first pass, the case independent 'a' in the
2302// second pass and the character class in the last pass.
2303//
2304// The passes are done from right to left, so for example to test for /bar/
2305// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2306// and then a 'b' with offset 0. This means we can avoid the end-of-input
2307// bounds check most of the time. In the example we only need to check for
2308// end-of-input when loading the putative 'r'.
2309//
2310// A slight complication involves the fact that the first character may already
2311// be fetched into a register by the previous node. In this case we want to
2312// do the test for that character first. We do this in separate passes. The
2313// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2314// pass has been performed then subsequent passes will have true in
2315// first_element_checked to indicate that that character does not need to be
2316// checked again.
2317//
ager@chromium.org32912102009-01-16 10:38:43 +00002318// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002319// contain an AlternativeGeneration object. In this AlternativeGeneration
2320// object we can see details of any quick check that was already passed in
2321// order to get to the code we are now generating. The quick check can involve
2322// loading characters, which means we do not need to recheck the bounds
2323// up to the limit the quick check already checked. In addition the quick
2324// check can have involved a mask and compare operation which may simplify
2325// or obviate the need for further checks at some character positions.
2326void TextNode::TextEmitPass(RegExpCompiler* compiler,
2327 TextEmitPassType pass,
2328 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002329 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002330 bool first_element_checked,
2331 int* checked_up_to) {
2332 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2333 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002334 Label* backtrack = trace->backtrack();
2335 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002336 int element_count = elms_->length();
2337 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2338 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002339 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002340 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002341 Vector<const uc16> quarks = elm.data.u_atom->data();
2342 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2343 if (first_element_checked && i == 0 && j == 0) continue;
2344 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2345 EmitCharacterFunction* emit_function = NULL;
2346 switch (pass) {
2347 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002348 ASSERT(ascii);
2349 if (quarks[j] > String::kMaxAsciiCharCode) {
2350 assembler->GoTo(backtrack);
2351 return;
2352 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002353 break;
2354 case NON_LETTER_CHARACTER_MATCH:
2355 emit_function = &EmitAtomNonLetter;
2356 break;
2357 case SIMPLE_CHARACTER_MATCH:
2358 emit_function = &EmitSimpleCharacter;
2359 break;
2360 case CASE_CHARACTER_MATCH:
2361 emit_function = &EmitAtomLetter;
2362 break;
2363 default:
2364 break;
2365 }
2366 if (emit_function != NULL) {
2367 bool bound_checked = emit_function(compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002368 quarks[j],
2369 backtrack,
2370 cp_offset + j,
2371 *checked_up_to < cp_offset + j,
2372 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002373 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002374 }
2375 }
2376 } else {
2377 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002378 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002379 if (first_element_checked && i == 0) continue;
2380 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002381 RegExpCharacterClass* cc = elm.data.u_char_class;
2382 EmitCharClass(assembler,
2383 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002384 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002385 backtrack,
2386 cp_offset,
2387 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002388 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002389 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002390 }
2391 }
2392 }
2393}
2394
2395
2396int TextNode::Length() {
2397 TextElement elm = elms_->last();
2398 ASSERT(elm.cp_offset >= 0);
2399 if (elm.type == TextElement::ATOM) {
2400 return elm.cp_offset + elm.data.u_atom->data().length();
2401 } else {
2402 return elm.cp_offset + 1;
2403 }
2404}
2405
2406
ager@chromium.org381abbb2009-02-25 13:23:22 +00002407bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2408 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2409 if (ignore_case) {
2410 return pass == SIMPLE_CHARACTER_MATCH;
2411 } else {
2412 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2413 }
2414}
2415
2416
ager@chromium.org8bb60582008-12-11 12:02:20 +00002417// This generates the code to match a text node. A text node can contain
2418// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002419// way) and character classes. For efficiency we do not do this in a single
2420// pass from left to right. Instead we pass over the text node several times,
2421// emitting code for some character positions every time. See the comment on
2422// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002423void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002424 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002425 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002426 ASSERT(limit_result == CONTINUE);
2427
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002428 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2429 compiler->SetRegExpTooBig();
2430 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002431 }
2432
2433 if (compiler->ascii()) {
2434 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002435 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002436 }
2437
2438 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002439 int bound_checked_to = trace->cp_offset() - 1;
2440 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002441
2442 // If a character is preloaded into the current character register then
2443 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002444 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002445 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2446 if (!SkipPass(pass, compiler->ignore_case())) {
2447 TextEmitPass(compiler,
2448 static_cast<TextEmitPassType>(pass),
2449 true,
2450 trace,
2451 false,
2452 &bound_checked_to);
2453 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002454 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002455 first_elt_done = true;
2456 }
2457
ager@chromium.org381abbb2009-02-25 13:23:22 +00002458 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2459 if (!SkipPass(pass, compiler->ignore_case())) {
2460 TextEmitPass(compiler,
2461 static_cast<TextEmitPassType>(pass),
2462 false,
2463 trace,
2464 first_elt_done,
2465 &bound_checked_to);
2466 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002467 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002468
ager@chromium.org32912102009-01-16 10:38:43 +00002469 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002470 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002471 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002472 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002473 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002474}
2475
2476
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002477void Trace::InvalidateCurrentCharacter() {
2478 characters_preloaded_ = 0;
2479}
2480
2481
2482void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002483 ASSERT(by > 0);
2484 // We don't have an instruction for shifting the current character register
2485 // down or for using a shifted value for anything so lets just forget that
2486 // we preloaded any characters into it.
2487 characters_preloaded_ = 0;
2488 // Adjust the offsets of the quick check performed information. This
2489 // information is used to find out what we already determined about the
2490 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002491 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002492 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002493 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2494 compiler->SetRegExpTooBig();
2495 cp_offset_ = 0;
2496 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002497 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002498}
2499
2500
ager@chromium.org38e4c712009-11-11 09:11:58 +00002501void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002502 int element_count = elms_->length();
2503 for (int i = 0; i < element_count; i++) {
2504 TextElement elm = elms_->at(i);
2505 if (elm.type == TextElement::CHAR_CLASS) {
2506 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002507 // None of the standard character classses is different in the case
2508 // independent case and it slows us down if we don't know that.
2509 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002510 ZoneList<CharacterRange>* ranges = cc->ranges();
2511 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002512 for (int j = 0; j < range_count; j++) {
2513 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002514 }
2515 }
2516 }
2517}
2518
2519
ager@chromium.org8bb60582008-12-11 12:02:20 +00002520int TextNode::GreedyLoopTextLength() {
2521 TextElement elm = elms_->at(elms_->length() - 1);
2522 if (elm.type == TextElement::CHAR_CLASS) {
2523 return elm.cp_offset + 1;
2524 } else {
2525 return elm.cp_offset + elm.data.u_atom->data().length();
2526 }
2527}
2528
2529
2530// Finds the fixed match length of a sequence of nodes that goes from
2531// this alternative and back to this choice node. If there are variable
2532// length nodes or other complications in the way then return a sentinel
2533// value indicating that a greedy loop cannot be constructed.
2534int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2535 int length = 0;
2536 RegExpNode* node = alternative->node();
2537 // Later we will generate code for all these text nodes using recursion
2538 // so we have to limit the max number.
2539 int recursion_depth = 0;
2540 while (node != this) {
2541 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2542 return kNodeIsTooComplexForGreedyLoops;
2543 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002544 int node_length = node->GreedyLoopTextLength();
2545 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2546 return kNodeIsTooComplexForGreedyLoops;
2547 }
2548 length += node_length;
2549 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2550 node = seq_node->on_success();
2551 }
2552 return length;
2553}
2554
2555
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002556void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2557 ASSERT_EQ(loop_node_, NULL);
2558 AddAlternative(alt);
2559 loop_node_ = alt.node();
2560}
2561
2562
2563void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2564 ASSERT_EQ(continue_node_, NULL);
2565 AddAlternative(alt);
2566 continue_node_ = alt.node();
2567}
2568
2569
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002570void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002571 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002572 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002573 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2574 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2575 // Update the counter-based backtracking info on the stack. This is an
2576 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002577 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002578 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002579 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002580 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002581 }
ager@chromium.org32912102009-01-16 10:38:43 +00002582 ASSERT(trace->stop_node() == NULL);
2583 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002584 trace->Flush(compiler, this);
2585 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002586 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002587 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002588}
2589
2590
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002591int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002592 int preload_characters = EatsAtLeast(4, 0);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002593 if (compiler->macro_assembler()->CanReadUnaligned()) {
2594 bool ascii = compiler->ascii();
2595 if (ascii) {
2596 if (preload_characters > 4) preload_characters = 4;
2597 // We can't preload 3 characters because there is no machine instruction
2598 // to do that. We can't just load 4 because we could be reading
2599 // beyond the end of the string, which could cause a memory fault.
2600 if (preload_characters == 3) preload_characters = 2;
2601 } else {
2602 if (preload_characters > 2) preload_characters = 2;
2603 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002604 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002605 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002606 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002607 return preload_characters;
2608}
2609
2610
2611// This class is used when generating the alternatives in a choice node. It
2612// records the way the alternative is being code generated.
2613class AlternativeGeneration: public Malloced {
2614 public:
2615 AlternativeGeneration()
2616 : possible_success(),
2617 expects_preload(false),
2618 after(),
2619 quick_check_details() { }
2620 Label possible_success;
2621 bool expects_preload;
2622 Label after;
2623 QuickCheckDetails quick_check_details;
2624};
2625
2626
2627// Creates a list of AlternativeGenerations. If the list has a reasonable
2628// size then it is on the stack, otherwise the excess is on the heap.
2629class AlternativeGenerationList {
2630 public:
2631 explicit AlternativeGenerationList(int count)
2632 : alt_gens_(count) {
2633 for (int i = 0; i < count && i < kAFew; i++) {
2634 alt_gens_.Add(a_few_alt_gens_ + i);
2635 }
2636 for (int i = kAFew; i < count; i++) {
2637 alt_gens_.Add(new AlternativeGeneration());
2638 }
2639 }
2640 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002641 for (int i = kAFew; i < alt_gens_.length(); i++) {
2642 delete alt_gens_[i];
2643 alt_gens_[i] = NULL;
2644 }
2645 }
2646
2647 AlternativeGeneration* at(int i) {
2648 return alt_gens_[i];
2649 }
2650 private:
2651 static const int kAFew = 10;
2652 ZoneList<AlternativeGeneration*> alt_gens_;
2653 AlternativeGeneration a_few_alt_gens_[kAFew];
2654};
2655
2656
2657/* Code generation for choice nodes.
2658 *
2659 * We generate quick checks that do a mask and compare to eliminate a
2660 * choice. If the quick check succeeds then it jumps to the continuation to
2661 * do slow checks and check subsequent nodes. If it fails (the common case)
2662 * it falls through to the next choice.
2663 *
2664 * Here is the desired flow graph. Nodes directly below each other imply
2665 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2666 * 3 doesn't have a quick check so we have to call the slow check.
2667 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2668 * regexp continuation is generated directly after the Sn node, up to the
2669 * next GoTo if we decide to reuse some already generated code. Some
2670 * nodes expect preload_characters to be preloaded into the current
2671 * character register. R nodes do this preloading. Vertices are marked
2672 * F for failures and S for success (possible success in the case of quick
2673 * nodes). L, V, < and > are used as arrow heads.
2674 *
2675 * ----------> R
2676 * |
2677 * V
2678 * Q1 -----> S1
2679 * | S /
2680 * F| /
2681 * | F/
2682 * | /
2683 * | R
2684 * | /
2685 * V L
2686 * Q2 -----> S2
2687 * | S /
2688 * F| /
2689 * | F/
2690 * | /
2691 * | R
2692 * | /
2693 * V L
2694 * S3
2695 * |
2696 * F|
2697 * |
2698 * R
2699 * |
2700 * backtrack V
2701 * <----------Q4
2702 * \ F |
2703 * \ |S
2704 * \ F V
2705 * \-----S4
2706 *
2707 * For greedy loops we reverse our expectation and expect to match rather
2708 * than fail. Therefore we want the loop code to look like this (U is the
2709 * unwind code that steps back in the greedy loop). The following alternatives
2710 * look the same as above.
2711 * _____
2712 * / \
2713 * V |
2714 * ----------> S1 |
2715 * /| |
2716 * / |S |
2717 * F/ \_____/
2718 * /
2719 * |<-----------
2720 * | \
2721 * V \
2722 * Q2 ---> S2 \
2723 * | S / |
2724 * F| / |
2725 * | F/ |
2726 * | / |
2727 * | R |
2728 * | / |
2729 * F VL |
2730 * <------U |
2731 * back |S |
2732 * \______________/
2733 */
2734
2735
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002736void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002737 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2738 int choice_count = alternatives_->length();
2739#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002740 for (int i = 0; i < choice_count - 1; i++) {
2741 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002742 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002743 int guard_count = (guards == NULL) ? 0 : guards->length();
2744 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002745 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002746 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002747 }
2748#endif
2749
ager@chromium.org32912102009-01-16 10:38:43 +00002750 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002751 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002752 ASSERT(limit_result == CONTINUE);
2753
ager@chromium.org381abbb2009-02-25 13:23:22 +00002754 int new_flush_budget = trace->flush_budget() / choice_count;
2755 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2756 trace->Flush(compiler, this);
2757 return;
2758 }
2759
ager@chromium.org8bb60582008-12-11 12:02:20 +00002760 RecursionCheck rc(compiler);
2761
ager@chromium.org32912102009-01-16 10:38:43 +00002762 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002763
2764 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2765 bool greedy_loop = false;
2766 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002767 Trace counter_backtrack_trace;
2768 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002769 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2770
ager@chromium.org8bb60582008-12-11 12:02:20 +00002771 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2772 // Here we have special handling for greedy loops containing only text nodes
2773 // and other simple nodes. These are handled by pushing the current
2774 // position on the stack and then incrementing the current position each
2775 // time around the switch. On backtrack we decrement the current position
2776 // and check it against the pushed value. This avoids pushing backtrack
2777 // information for each iteration of the loop, which could take up a lot of
2778 // space.
2779 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002780 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002781 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002782 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002783 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002784 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002785 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002786 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002787 Label loop_label;
2788 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002789 greedy_match_trace.set_stop_node(this);
2790 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002791 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002792 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002793 }
2794
2795 Label second_choice; // For use in greedy matches.
2796 macro_assembler->Bind(&second_choice);
2797
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002798 int first_normal_choice = greedy_loop ? 1 : 0;
2799
2800 int preload_characters = CalculatePreloadCharacters(compiler);
2801 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002802 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002803 bool preload_has_checked_bounds = preload_is_current;
2804
2805 AlternativeGenerationList alt_gens(choice_count);
2806
ager@chromium.org8bb60582008-12-11 12:02:20 +00002807 // For now we just call all choices one after the other. The idea ultimately
2808 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002809 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002810 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002811 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002812 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002813 ZoneList<Guard*>* guards = alternative.guards();
2814 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002815 Trace new_trace(*current_trace);
2816 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002817 preload_characters :
2818 0);
2819 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002820 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002821 }
ager@chromium.org32912102009-01-16 10:38:43 +00002822 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002823 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002824 alt_gen->expects_preload = preload_is_current;
2825 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002826 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002827 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002828 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002829 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002830 preload_has_checked_bounds,
2831 &alt_gen->possible_success,
2832 &alt_gen->quick_check_details,
2833 i < choice_count - 1)) {
2834 // Quick check was generated for this choice.
2835 preload_is_current = true;
2836 preload_has_checked_bounds = true;
2837 // On the last choice in the ChoiceNode we generated the quick
2838 // check to fall through on possible success. So now we need to
2839 // generate the full check inline.
2840 if (i == choice_count - 1) {
2841 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002842 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2843 new_trace.set_characters_preloaded(preload_characters);
2844 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002845 generate_full_check_inline = true;
2846 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002847 } else if (alt_gen->quick_check_details.cannot_match()) {
2848 if (i == choice_count - 1 && !greedy_loop) {
2849 macro_assembler->GoTo(trace->backtrack());
2850 }
2851 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002852 } else {
2853 // No quick check was generated. Put the full code here.
2854 // If this is not the first choice then there could be slow checks from
2855 // previous cases that go here when they fail. There's no reason to
2856 // insist that they preload characters since the slow check we are about
2857 // to generate probably can't use it.
2858 if (i != first_normal_choice) {
2859 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002860 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002861 }
2862 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002863 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002864 }
2865 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002866 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002867 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002868 if (new_trace.actions() != NULL) {
2869 new_trace.set_flush_budget(new_flush_budget);
2870 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002871 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002872 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002873 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002874 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002875 preload_is_current = false;
2876 }
2877 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002878 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002879 if (greedy_loop) {
2880 macro_assembler->Bind(&greedy_loop_label);
2881 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002882 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002883 // Otherwise try the second priority at an earlier position.
2884 macro_assembler->AdvanceCurrentPosition(-text_length);
2885 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002886 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002887
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002888 // At this point we need to generate slow checks for the alternatives where
2889 // the quick check was inlined. We can recognize these because the associated
2890 // label was bound.
2891 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2892 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002893 Trace new_trace(*current_trace);
2894 // If there are actions to be flushed we have to limit how many times
2895 // they are flushed. Take the budget of the parent trace and distribute
2896 // it fairly amongst the children.
2897 if (new_trace.actions() != NULL) {
2898 new_trace.set_flush_budget(new_flush_budget);
2899 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002900 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002901 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002902 alternatives_->at(i),
2903 alt_gen,
2904 preload_characters,
2905 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002906 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002907}
2908
2909
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002910void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002911 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002912 GuardedAlternative alternative,
2913 AlternativeGeneration* alt_gen,
2914 int preload_characters,
2915 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002916 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002917
2918 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2919 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002920 Trace out_of_line_trace(*trace);
2921 out_of_line_trace.set_characters_preloaded(preload_characters);
2922 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002923 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002924 ZoneList<Guard*>* guards = alternative.guards();
2925 int guard_count = (guards == NULL) ? 0 : guards->length();
2926 if (next_expects_preload) {
2927 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00002928 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002929 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002930 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002931 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002932 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002933 macro_assembler->Bind(&reload_current_char);
2934 // Reload the current character, since the next quick check expects that.
2935 // We don't need to check bounds here because we only get into this
2936 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00002937 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002938 NULL,
2939 false,
2940 preload_characters);
2941 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002942 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00002943 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002944 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002945 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002946 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002947 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002948 }
2949}
2950
2951
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002952void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002953 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002954 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002955 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002956 ASSERT(limit_result == CONTINUE);
2957
2958 RecursionCheck rc(compiler);
2959
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002960 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002961 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00002962 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002963 new_capture(data_.u_position_register.reg,
2964 data_.u_position_register.is_capture,
2965 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002966 Trace new_trace = *trace;
2967 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002968 on_success()->Emit(compiler, &new_trace);
2969 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002970 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002971 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002972 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002973 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00002974 Trace new_trace = *trace;
2975 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002976 on_success()->Emit(compiler, &new_trace);
2977 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002978 }
2979 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002980 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002981 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00002982 Trace new_trace = *trace;
2983 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002984 on_success()->Emit(compiler, &new_trace);
2985 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002986 }
2987 case CLEAR_CAPTURES: {
2988 Trace::DeferredClearCaptures
2989 new_capture(Interval(data_.u_clear_captures.range_from,
2990 data_.u_clear_captures.range_to));
2991 Trace new_trace = *trace;
2992 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002993 on_success()->Emit(compiler, &new_trace);
2994 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002995 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002996 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002997 if (!trace->is_trivial()) {
2998 trace->Flush(compiler, this);
2999 } else {
3000 assembler->WriteCurrentPositionToRegister(
3001 data_.u_submatch.current_position_register, 0);
3002 assembler->WriteStackPointerToRegister(
3003 data_.u_submatch.stack_pointer_register);
3004 on_success()->Emit(compiler, trace);
3005 }
3006 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003007 case EMPTY_MATCH_CHECK: {
3008 int start_pos_reg = data_.u_empty_match_check.start_register;
3009 int stored_pos = 0;
3010 int rep_reg = data_.u_empty_match_check.repetition_register;
3011 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3012 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3013 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3014 // If we know we haven't advanced and there is no minimum we
3015 // can just backtrack immediately.
3016 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003017 } else if (know_dist && stored_pos < trace->cp_offset()) {
3018 // If we know we've advanced we can generate the continuation
3019 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003020 on_success()->Emit(compiler, trace);
3021 } else if (!trace->is_trivial()) {
3022 trace->Flush(compiler, this);
3023 } else {
3024 Label skip_empty_check;
3025 // If we have a minimum number of repetitions we check the current
3026 // number first and skip the empty check if it's not enough.
3027 if (has_minimum) {
3028 int limit = data_.u_empty_match_check.repetition_limit;
3029 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3030 }
3031 // If the match is empty we bail out, otherwise we fall through
3032 // to the on-success continuation.
3033 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3034 trace->backtrack());
3035 assembler->Bind(&skip_empty_check);
3036 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003037 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003038 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003039 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003040 case POSITIVE_SUBMATCH_SUCCESS: {
3041 if (!trace->is_trivial()) {
3042 trace->Flush(compiler, this);
3043 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003044 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003045 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003046 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003047 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003048 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003049 int clear_register_count = data_.u_submatch.clear_register_count;
3050 if (clear_register_count == 0) {
3051 on_success()->Emit(compiler, trace);
3052 return;
3053 }
3054 int clear_registers_from = data_.u_submatch.clear_register_from;
3055 Label clear_registers_backtrack;
3056 Trace new_trace = *trace;
3057 new_trace.set_backtrack(&clear_registers_backtrack);
3058 on_success()->Emit(compiler, &new_trace);
3059
3060 assembler->Bind(&clear_registers_backtrack);
3061 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3062 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3063
3064 ASSERT(trace->backtrack() == NULL);
3065 assembler->Backtrack();
3066 return;
3067 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003068 default:
3069 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003070 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003071}
3072
3073
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003074void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003075 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003076 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003077 trace->Flush(compiler, this);
3078 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003079 }
3080
ager@chromium.org32912102009-01-16 10:38:43 +00003081 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003082 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003083 ASSERT(limit_result == CONTINUE);
3084
3085 RecursionCheck rc(compiler);
3086
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003087 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003088 if (compiler->ignore_case()) {
3089 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3090 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003091 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003092 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003093 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003094 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003095}
3096
3097
3098// -------------------------------------------------------------------
3099// Dot/dotty output
3100
3101
3102#ifdef DEBUG
3103
3104
3105class DotPrinter: public NodeVisitor {
3106 public:
3107 explicit DotPrinter(bool ignore_case)
3108 : ignore_case_(ignore_case),
3109 stream_(&alloc_) { }
3110 void PrintNode(const char* label, RegExpNode* node);
3111 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003112 void PrintAttributes(RegExpNode* from);
3113 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003114 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003115#define DECLARE_VISIT(Type) \
3116 virtual void Visit##Type(Type##Node* that);
3117FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3118#undef DECLARE_VISIT
3119 private:
3120 bool ignore_case_;
3121 HeapStringAllocator alloc_;
3122 StringStream stream_;
3123};
3124
3125
3126void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3127 stream()->Add("digraph G {\n graph [label=\"");
3128 for (int i = 0; label[i]; i++) {
3129 switch (label[i]) {
3130 case '\\':
3131 stream()->Add("\\\\");
3132 break;
3133 case '"':
3134 stream()->Add("\"");
3135 break;
3136 default:
3137 stream()->Put(label[i]);
3138 break;
3139 }
3140 }
3141 stream()->Add("\"];\n");
3142 Visit(node);
3143 stream()->Add("}\n");
3144 printf("%s", *(stream()->ToCString()));
3145}
3146
3147
3148void DotPrinter::Visit(RegExpNode* node) {
3149 if (node->info()->visited) return;
3150 node->info()->visited = true;
3151 node->Accept(this);
3152}
3153
3154
3155void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003156 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3157 Visit(on_failure);
3158}
3159
3160
3161class TableEntryBodyPrinter {
3162 public:
3163 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3164 : stream_(stream), choice_(choice) { }
3165 void Call(uc16 from, DispatchTable::Entry entry) {
3166 OutSet* out_set = entry.out_set();
3167 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3168 if (out_set->Get(i)) {
3169 stream()->Add(" n%p:s%io%i -> n%p;\n",
3170 choice(),
3171 from,
3172 i,
3173 choice()->alternatives()->at(i).node());
3174 }
3175 }
3176 }
3177 private:
3178 StringStream* stream() { return stream_; }
3179 ChoiceNode* choice() { return choice_; }
3180 StringStream* stream_;
3181 ChoiceNode* choice_;
3182};
3183
3184
3185class TableEntryHeaderPrinter {
3186 public:
3187 explicit TableEntryHeaderPrinter(StringStream* stream)
3188 : first_(true), stream_(stream) { }
3189 void Call(uc16 from, DispatchTable::Entry entry) {
3190 if (first_) {
3191 first_ = false;
3192 } else {
3193 stream()->Add("|");
3194 }
3195 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3196 OutSet* out_set = entry.out_set();
3197 int priority = 0;
3198 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3199 if (out_set->Get(i)) {
3200 if (priority > 0) stream()->Add("|");
3201 stream()->Add("<s%io%i> %i", from, i, priority);
3202 priority++;
3203 }
3204 }
3205 stream()->Add("}}");
3206 }
3207 private:
3208 bool first_;
3209 StringStream* stream() { return stream_; }
3210 StringStream* stream_;
3211};
3212
3213
3214class AttributePrinter {
3215 public:
3216 explicit AttributePrinter(DotPrinter* out)
3217 : out_(out), first_(true) { }
3218 void PrintSeparator() {
3219 if (first_) {
3220 first_ = false;
3221 } else {
3222 out_->stream()->Add("|");
3223 }
3224 }
3225 void PrintBit(const char* name, bool value) {
3226 if (!value) return;
3227 PrintSeparator();
3228 out_->stream()->Add("{%s}", name);
3229 }
3230 void PrintPositive(const char* name, int value) {
3231 if (value < 0) return;
3232 PrintSeparator();
3233 out_->stream()->Add("{%s|%x}", name, value);
3234 }
3235 private:
3236 DotPrinter* out_;
3237 bool first_;
3238};
3239
3240
3241void DotPrinter::PrintAttributes(RegExpNode* that) {
3242 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3243 "margin=0.1, fontsize=10, label=\"{",
3244 that);
3245 AttributePrinter printer(this);
3246 NodeInfo* info = that->info();
3247 printer.PrintBit("NI", info->follows_newline_interest);
3248 printer.PrintBit("WI", info->follows_word_interest);
3249 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003250 Label* label = that->label();
3251 if (label->is_bound())
3252 printer.PrintPositive("@", label->pos());
3253 stream()->Add("}\"];\n");
3254 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3255 "arrowhead=none];\n", that, that);
3256}
3257
3258
3259static const bool kPrintDispatchTable = false;
3260void DotPrinter::VisitChoice(ChoiceNode* that) {
3261 if (kPrintDispatchTable) {
3262 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3263 TableEntryHeaderPrinter header_printer(stream());
3264 that->GetTable(ignore_case_)->ForEach(&header_printer);
3265 stream()->Add("\"]\n", that);
3266 PrintAttributes(that);
3267 TableEntryBodyPrinter body_printer(stream(), that);
3268 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003269 } else {
3270 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3271 for (int i = 0; i < that->alternatives()->length(); i++) {
3272 GuardedAlternative alt = that->alternatives()->at(i);
3273 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3274 }
3275 }
3276 for (int i = 0; i < that->alternatives()->length(); i++) {
3277 GuardedAlternative alt = that->alternatives()->at(i);
3278 alt.node()->Accept(this);
3279 }
3280}
3281
3282
3283void DotPrinter::VisitText(TextNode* that) {
3284 stream()->Add(" n%p [label=\"", that);
3285 for (int i = 0; i < that->elements()->length(); i++) {
3286 if (i > 0) stream()->Add(" ");
3287 TextElement elm = that->elements()->at(i);
3288 switch (elm.type) {
3289 case TextElement::ATOM: {
3290 stream()->Add("'%w'", elm.data.u_atom->data());
3291 break;
3292 }
3293 case TextElement::CHAR_CLASS: {
3294 RegExpCharacterClass* node = elm.data.u_char_class;
3295 stream()->Add("[");
3296 if (node->is_negated())
3297 stream()->Add("^");
3298 for (int j = 0; j < node->ranges()->length(); j++) {
3299 CharacterRange range = node->ranges()->at(j);
3300 stream()->Add("%k-%k", range.from(), range.to());
3301 }
3302 stream()->Add("]");
3303 break;
3304 }
3305 default:
3306 UNREACHABLE();
3307 }
3308 }
3309 stream()->Add("\", shape=box, peripheries=2];\n");
3310 PrintAttributes(that);
3311 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3312 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003313}
3314
3315
3316void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3317 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3318 that,
3319 that->start_register(),
3320 that->end_register());
3321 PrintAttributes(that);
3322 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3323 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003324}
3325
3326
3327void DotPrinter::VisitEnd(EndNode* that) {
3328 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3329 PrintAttributes(that);
3330}
3331
3332
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003333void DotPrinter::VisitAssertion(AssertionNode* that) {
3334 stream()->Add(" n%p [", that);
3335 switch (that->type()) {
3336 case AssertionNode::AT_END:
3337 stream()->Add("label=\"$\", shape=septagon");
3338 break;
3339 case AssertionNode::AT_START:
3340 stream()->Add("label=\"^\", shape=septagon");
3341 break;
3342 case AssertionNode::AT_BOUNDARY:
3343 stream()->Add("label=\"\\b\", shape=septagon");
3344 break;
3345 case AssertionNode::AT_NON_BOUNDARY:
3346 stream()->Add("label=\"\\B\", shape=septagon");
3347 break;
3348 case AssertionNode::AFTER_NEWLINE:
3349 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3350 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003351 case AssertionNode::AFTER_WORD_CHARACTER:
3352 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3353 break;
3354 case AssertionNode::AFTER_NONWORD_CHARACTER:
3355 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3356 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003357 }
3358 stream()->Add("];\n");
3359 PrintAttributes(that);
3360 RegExpNode* successor = that->on_success();
3361 stream()->Add(" n%p -> n%p;\n", that, successor);
3362 Visit(successor);
3363}
3364
3365
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003366void DotPrinter::VisitAction(ActionNode* that) {
3367 stream()->Add(" n%p [", that);
3368 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003369 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003370 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3371 that->data_.u_store_register.reg,
3372 that->data_.u_store_register.value);
3373 break;
3374 case ActionNode::INCREMENT_REGISTER:
3375 stream()->Add("label=\"$%i++\", shape=octagon",
3376 that->data_.u_increment_register.reg);
3377 break;
3378 case ActionNode::STORE_POSITION:
3379 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3380 that->data_.u_position_register.reg);
3381 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003382 case ActionNode::BEGIN_SUBMATCH:
3383 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3384 that->data_.u_submatch.current_position_register);
3385 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003386 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003387 stream()->Add("label=\"escape\", shape=septagon");
3388 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003389 case ActionNode::EMPTY_MATCH_CHECK:
3390 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3391 that->data_.u_empty_match_check.start_register,
3392 that->data_.u_empty_match_check.repetition_register,
3393 that->data_.u_empty_match_check.repetition_limit);
3394 break;
3395 case ActionNode::CLEAR_CAPTURES: {
3396 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3397 that->data_.u_clear_captures.range_from,
3398 that->data_.u_clear_captures.range_to);
3399 break;
3400 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003401 }
3402 stream()->Add("];\n");
3403 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003404 RegExpNode* successor = that->on_success();
3405 stream()->Add(" n%p -> n%p;\n", that, successor);
3406 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003407}
3408
3409
3410class DispatchTableDumper {
3411 public:
3412 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3413 void Call(uc16 key, DispatchTable::Entry entry);
3414 StringStream* stream() { return stream_; }
3415 private:
3416 StringStream* stream_;
3417};
3418
3419
3420void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3421 stream()->Add("[%k-%k]: {", key, entry.to());
3422 OutSet* set = entry.out_set();
3423 bool first = true;
3424 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3425 if (set->Get(i)) {
3426 if (first) {
3427 first = false;
3428 } else {
3429 stream()->Add(", ");
3430 }
3431 stream()->Add("%i", i);
3432 }
3433 }
3434 stream()->Add("}\n");
3435}
3436
3437
3438void DispatchTable::Dump() {
3439 HeapStringAllocator alloc;
3440 StringStream stream(&alloc);
3441 DispatchTableDumper dumper(&stream);
3442 tree()->ForEach(&dumper);
3443 OS::PrintError("%s", *stream.ToCString());
3444}
3445
3446
3447void RegExpEngine::DotPrint(const char* label,
3448 RegExpNode* node,
3449 bool ignore_case) {
3450 DotPrinter printer(ignore_case);
3451 printer.PrintNode(label, node);
3452}
3453
3454
3455#endif // DEBUG
3456
3457
3458// -------------------------------------------------------------------
3459// Tree to graph conversion
3460
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003461static const int kSpaceRangeCount = 20;
3462static const int kSpaceRangeAsciiCount = 4;
3463static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3464 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3465 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3466
3467static const int kWordRangeCount = 8;
3468static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3469 '_', 'a', 'z' };
3470
3471static const int kDigitRangeCount = 2;
3472static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3473
3474static const int kLineTerminatorRangeCount = 6;
3475static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3476 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003477
3478RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003479 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003480 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3481 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003482 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003483}
3484
3485
3486RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003487 RegExpNode* on_success) {
3488 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003489}
3490
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003491static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3492 const uc16* special_class,
3493 int length) {
3494 ASSERT(ranges->length() != 0);
3495 ASSERT(length != 0);
3496 ASSERT(special_class[0] != 0);
3497 if (ranges->length() != (length >> 1) + 1) {
3498 return false;
3499 }
3500 CharacterRange range = ranges->at(0);
3501 if (range.from() != 0) {
3502 return false;
3503 }
3504 for (int i = 0; i < length; i += 2) {
3505 if (special_class[i] != (range.to() + 1)) {
3506 return false;
3507 }
3508 range = ranges->at((i >> 1) + 1);
3509 if (special_class[i+1] != range.from() - 1) {
3510 return false;
3511 }
3512 }
3513 if (range.to() != 0xffff) {
3514 return false;
3515 }
3516 return true;
3517}
3518
3519
3520static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3521 const uc16* special_class,
3522 int length) {
3523 if (ranges->length() * 2 != length) {
3524 return false;
3525 }
3526 for (int i = 0; i < length; i += 2) {
3527 CharacterRange range = ranges->at(i >> 1);
3528 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3529 return false;
3530 }
3531 }
3532 return true;
3533}
3534
3535
3536bool RegExpCharacterClass::is_standard() {
3537 // TODO(lrn): Remove need for this function, by not throwing away information
3538 // along the way.
3539 if (is_negated_) {
3540 return false;
3541 }
3542 if (set_.is_standard()) {
3543 return true;
3544 }
3545 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3546 set_.set_standard_set_type('s');
3547 return true;
3548 }
3549 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3550 set_.set_standard_set_type('S');
3551 return true;
3552 }
3553 if (CompareInverseRanges(set_.ranges(),
3554 kLineTerminatorRanges,
3555 kLineTerminatorRangeCount)) {
3556 set_.set_standard_set_type('.');
3557 return true;
3558 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003559 if (CompareRanges(set_.ranges(),
3560 kLineTerminatorRanges,
3561 kLineTerminatorRangeCount)) {
3562 set_.set_standard_set_type('n');
3563 return true;
3564 }
3565 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3566 set_.set_standard_set_type('w');
3567 return true;
3568 }
3569 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3570 set_.set_standard_set_type('W');
3571 return true;
3572 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003573 return false;
3574}
3575
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003576
3577RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003578 RegExpNode* on_success) {
3579 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003580}
3581
3582
3583RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003584 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003585 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3586 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003587 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003588 for (int i = 0; i < length; i++) {
3589 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003590 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003591 result->AddAlternative(alternative);
3592 }
3593 return result;
3594}
3595
3596
3597RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003598 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003599 return ToNode(min(),
3600 max(),
3601 is_greedy(),
3602 body(),
3603 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003604 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003605}
3606
3607
3608RegExpNode* RegExpQuantifier::ToNode(int min,
3609 int max,
3610 bool is_greedy,
3611 RegExpTree* body,
3612 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003613 RegExpNode* on_success,
3614 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003615 // x{f, t} becomes this:
3616 //
3617 // (r++)<-.
3618 // | `
3619 // | (x)
3620 // v ^
3621 // (r=0)-->(?)---/ [if r < t]
3622 // |
3623 // [if r >= f] \----> ...
3624 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003625
3626 // 15.10.2.5 RepeatMatcher algorithm.
3627 // The parser has already eliminated the case where max is 0. In the case
3628 // where max_match is zero the parser has removed the quantifier if min was
3629 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3630
3631 // If we know that we cannot match zero length then things are a little
3632 // simpler since we don't need to make the special zero length match check
3633 // from step 2.1. If the min and max are small we can unroll a little in
3634 // this case.
3635 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3636 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3637 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003638 bool body_can_be_empty = (body->min_match() == 0);
3639 int body_start_reg = RegExpCompiler::kNoRegister;
3640 Interval capture_registers = body->CaptureRegisters();
3641 bool needs_capture_clearing = !capture_registers.is_empty();
3642 if (body_can_be_empty) {
3643 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003644 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003645 // Only unroll if there are no captures and the body can't be
3646 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003647 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3648 int new_max = (max == kInfinity) ? max : max - min;
3649 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003650 RegExpNode* answer = ToNode(
3651 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003652 // Unroll the forced matches from 0 to min. This can cause chains of
3653 // TextNodes (which the parser does not generate). These should be
3654 // combined if it turns out they hinder good code generation.
3655 for (int i = 0; i < min; i++) {
3656 answer = body->ToNode(compiler, answer);
3657 }
3658 return answer;
3659 }
3660 if (max <= kMaxUnrolledMaxMatches) {
3661 ASSERT(min == 0);
3662 // Unroll the optional matches up to max.
3663 RegExpNode* answer = on_success;
3664 for (int i = 0; i < max; i++) {
3665 ChoiceNode* alternation = new ChoiceNode(2);
3666 if (is_greedy) {
3667 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3668 answer)));
3669 alternation->AddAlternative(GuardedAlternative(on_success));
3670 } else {
3671 alternation->AddAlternative(GuardedAlternative(on_success));
3672 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3673 answer)));
3674 }
3675 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003676 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003677 }
3678 return answer;
3679 }
3680 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003681 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003682 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003683 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003684 int reg_ctr = needs_counter
3685 ? compiler->AllocateRegister()
3686 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003687 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003688 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003689 RegExpNode* loop_return = needs_counter
3690 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3691 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003692 if (body_can_be_empty) {
3693 // If the body can be empty we need to check if it was and then
3694 // backtrack.
3695 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3696 reg_ctr,
3697 min,
3698 loop_return);
3699 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003700 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003701 if (body_can_be_empty) {
3702 // If the body can be empty we need to store the start position
3703 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003704 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003705 }
3706 if (needs_capture_clearing) {
3707 // Before entering the body of this loop we need to clear captures.
3708 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3709 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003710 GuardedAlternative body_alt(body_node);
3711 if (has_max) {
3712 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3713 body_alt.AddGuard(body_guard);
3714 }
3715 GuardedAlternative rest_alt(on_success);
3716 if (has_min) {
3717 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3718 rest_alt.AddGuard(rest_guard);
3719 }
3720 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003721 center->AddLoopAlternative(body_alt);
3722 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003723 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003724 center->AddContinueAlternative(rest_alt);
3725 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003726 }
3727 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003728 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003729 } else {
3730 return center;
3731 }
3732}
3733
3734
3735RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003736 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003737 NodeInfo info;
3738 switch (type()) {
3739 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003740 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003741 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003742 return AssertionNode::AtStart(on_success);
3743 case BOUNDARY:
3744 return AssertionNode::AtBoundary(on_success);
3745 case NON_BOUNDARY:
3746 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003747 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003748 return AssertionNode::AtEnd(on_success);
3749 case END_OF_LINE: {
3750 // Compile $ in multiline regexps as an alternation with a positive
3751 // lookahead in one side and an end-of-input on the other side.
3752 // We need two registers for the lookahead.
3753 int stack_pointer_register = compiler->AllocateRegister();
3754 int position_register = compiler->AllocateRegister();
3755 // The ChoiceNode to distinguish between a newline and end-of-input.
3756 ChoiceNode* result = new ChoiceNode(2);
3757 // Create a newline atom.
3758 ZoneList<CharacterRange>* newline_ranges =
3759 new ZoneList<CharacterRange>(3);
3760 CharacterRange::AddClassEscape('n', newline_ranges);
3761 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3762 TextNode* newline_matcher = new TextNode(
3763 newline_atom,
3764 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3765 position_register,
3766 0, // No captures inside.
3767 -1, // Ignored if no captures.
3768 on_success));
3769 // Create an end-of-input matcher.
3770 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3771 stack_pointer_register,
3772 position_register,
3773 newline_matcher);
3774 // Add the two alternatives to the ChoiceNode.
3775 GuardedAlternative eol_alternative(end_of_line);
3776 result->AddAlternative(eol_alternative);
3777 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3778 result->AddAlternative(end_alternative);
3779 return result;
3780 }
3781 default:
3782 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003783 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003784 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003785}
3786
3787
3788RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003789 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003790 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3791 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003792 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003793}
3794
3795
3796RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003797 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003798 return on_success;
3799}
3800
3801
3802RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003803 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003804 int stack_pointer_register = compiler->AllocateRegister();
3805 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003806
3807 const int registers_per_capture = 2;
3808 const int register_of_first_capture = 2;
3809 int register_count = capture_count_ * registers_per_capture;
3810 int register_start =
3811 register_of_first_capture + capture_from_ * registers_per_capture;
3812
ager@chromium.org8bb60582008-12-11 12:02:20 +00003813 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003814 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003815 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003816 stack_pointer_register,
3817 position_register,
3818 body()->ToNode(
3819 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003820 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3821 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003822 register_count,
3823 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003824 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003825 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003826 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003827 // We use a ChoiceNode for a negative lookahead because it has most of
3828 // the characteristics we need. It has the body of the lookahead as its
3829 // first alternative and the expression after the lookahead of the second
3830 // alternative. If the first alternative succeeds then the
3831 // NegativeSubmatchSuccess will unwind the stack including everything the
3832 // choice node set up and backtrack. If the first alternative fails then
3833 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003834 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3835 // ChoiceNode that knows to ignore the first exit when calculating quick
3836 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003837 GuardedAlternative body_alt(
3838 body()->ToNode(
3839 compiler,
3840 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003841 position_register,
3842 register_count,
3843 register_start)));
3844 ChoiceNode* choice_node =
3845 new NegativeLookaheadChoiceNode(body_alt,
3846 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003847 return ActionNode::BeginSubmatch(stack_pointer_register,
3848 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003849 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003850 }
3851}
3852
3853
3854RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003855 RegExpNode* on_success) {
3856 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003857}
3858
3859
3860RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3861 int index,
3862 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003863 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003864 int start_reg = RegExpCapture::StartRegister(index);
3865 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003866 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003867 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003868 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003869}
3870
3871
3872RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003873 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003874 ZoneList<RegExpTree*>* children = nodes();
3875 RegExpNode* current = on_success;
3876 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003877 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003878 }
3879 return current;
3880}
3881
3882
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003883static void AddClass(const uc16* elmv,
3884 int elmc,
3885 ZoneList<CharacterRange>* ranges) {
3886 for (int i = 0; i < elmc; i += 2) {
3887 ASSERT(elmv[i] <= elmv[i + 1]);
3888 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3889 }
3890}
3891
3892
3893static void AddClassNegated(const uc16 *elmv,
3894 int elmc,
3895 ZoneList<CharacterRange>* ranges) {
3896 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003897 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003898 uc16 last = 0x0000;
3899 for (int i = 0; i < elmc; i += 2) {
3900 ASSERT(last <= elmv[i] - 1);
3901 ASSERT(elmv[i] <= elmv[i + 1]);
3902 ranges->Add(CharacterRange(last, elmv[i] - 1));
3903 last = elmv[i + 1] + 1;
3904 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003905 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003906}
3907
3908
3909void CharacterRange::AddClassEscape(uc16 type,
3910 ZoneList<CharacterRange>* ranges) {
3911 switch (type) {
3912 case 's':
3913 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3914 break;
3915 case 'S':
3916 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3917 break;
3918 case 'w':
3919 AddClass(kWordRanges, kWordRangeCount, ranges);
3920 break;
3921 case 'W':
3922 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3923 break;
3924 case 'd':
3925 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3926 break;
3927 case 'D':
3928 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3929 break;
3930 case '.':
3931 AddClassNegated(kLineTerminatorRanges,
3932 kLineTerminatorRangeCount,
3933 ranges);
3934 break;
3935 // This is not a character range as defined by the spec but a
3936 // convenient shorthand for a character class that matches any
3937 // character.
3938 case '*':
3939 ranges->Add(CharacterRange::Everything());
3940 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003941 // This is the set of characters matched by the $ and ^ symbols
3942 // in multiline mode.
3943 case 'n':
3944 AddClass(kLineTerminatorRanges,
3945 kLineTerminatorRangeCount,
3946 ranges);
3947 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003948 default:
3949 UNREACHABLE();
3950 }
3951}
3952
3953
3954Vector<const uc16> CharacterRange::GetWordBounds() {
3955 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3956}
3957
3958
3959class CharacterRangeSplitter {
3960 public:
3961 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3962 ZoneList<CharacterRange>** excluded)
3963 : included_(included),
3964 excluded_(excluded) { }
3965 void Call(uc16 from, DispatchTable::Entry entry);
3966
3967 static const int kInBase = 0;
3968 static const int kInOverlay = 1;
3969
3970 private:
3971 ZoneList<CharacterRange>** included_;
3972 ZoneList<CharacterRange>** excluded_;
3973};
3974
3975
3976void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3977 if (!entry.out_set()->Get(kInBase)) return;
3978 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3979 ? included_
3980 : excluded_;
3981 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3982 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3983}
3984
3985
3986void CharacterRange::Split(ZoneList<CharacterRange>* base,
3987 Vector<const uc16> overlay,
3988 ZoneList<CharacterRange>** included,
3989 ZoneList<CharacterRange>** excluded) {
3990 ASSERT_EQ(NULL, *included);
3991 ASSERT_EQ(NULL, *excluded);
3992 DispatchTable table;
3993 for (int i = 0; i < base->length(); i++)
3994 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3995 for (int i = 0; i < overlay.length(); i += 2) {
3996 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
3997 CharacterRangeSplitter::kInOverlay);
3998 }
3999 CharacterRangeSplitter callback(included, excluded);
4000 table.ForEach(&callback);
4001}
4002
4003
ager@chromium.org38e4c712009-11-11 09:11:58 +00004004static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4005 int bottom,
4006 int top);
4007
4008
4009void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4010 bool is_ascii) {
4011 uc16 bottom = from();
4012 uc16 top = to();
4013 if (is_ascii) {
4014 if (bottom > String::kMaxAsciiCharCode) return;
4015 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4016 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004017 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004018 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004019 // If this is a singleton we just expand the one character.
ager@chromium.org38e4c712009-11-11 09:11:58 +00004020 int length = uncanonicalize.get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004021 for (int i = 0; i < length; i++) {
4022 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004023 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004024 ranges->Add(CharacterRange::Singleton(chars[i]));
4025 }
4026 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004027 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004028 // If this is a range we expand the characters block by block,
4029 // expanding contiguous subranges (blocks) one at a time.
4030 // The approach is as follows. For a given start character we
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004031 // look up the remainder of the block that contains it (represented
4032 // by the end point), for instance we find 'z' if the character
4033 // is 'c'. A block is characterized by the property
4034 // that all characters uncanonicalize in the same way, except that
4035 // each entry in the result is incremented by the distance from the first
4036 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
4037 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
4038 // Once we've found the end point we look up its uncanonicalization
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004039 // and produce a range for each element. For instance for [c-f]
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004040 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004041 // add a range if it is not already contained in the input, so [c-f]
4042 // will be skipped but [C-F] will be added. If this range is not
4043 // completely contained in a block we do this for all the blocks
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004044 // covered by the range (handling characters that is not in a block
4045 // as a "singleton block").
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004046 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004047 int pos = bottom;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004048 while (pos < top) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004049 int length = canonrange.get(pos, '\0', range);
4050 uc16 block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004051 if (length == 0) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004052 block_end = pos;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004053 } else {
4054 ASSERT_EQ(1, length);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004055 block_end = range[0];
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004056 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004057 int end = (block_end > top) ? top : block_end;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004058 length = uncanonicalize.get(block_end, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004059 for (int i = 0; i < length; i++) {
4060 uc32 c = range[i];
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004061 uc16 range_from = c - (block_end - pos);
4062 uc16 range_to = c - (block_end - end);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004063 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004064 ranges->Add(CharacterRange(range_from, range_to));
4065 }
4066 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004067 pos = end + 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004068 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004069 }
4070}
4071
4072
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004073bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4074 ASSERT_NOT_NULL(ranges);
4075 int n = ranges->length();
4076 if (n <= 1) return true;
4077 int max = ranges->at(0).to();
4078 for (int i = 1; i < n; i++) {
4079 CharacterRange next_range = ranges->at(i);
4080 if (next_range.from() <= max + 1) return false;
4081 max = next_range.to();
4082 }
4083 return true;
4084}
4085
4086SetRelation CharacterRange::WordCharacterRelation(
4087 ZoneList<CharacterRange>* range) {
4088 ASSERT(IsCanonical(range));
4089 int i = 0; // Word character range index.
4090 int j = 0; // Argument range index.
4091 ASSERT_NE(0, kWordRangeCount);
4092 SetRelation result;
4093 if (range->length() == 0) {
4094 result.SetElementsInSecondSet();
4095 return result;
4096 }
4097 CharacterRange argument_range = range->at(0);
4098 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4099 while (i < kWordRangeCount && j < range->length()) {
4100 // Check the two ranges for the five cases:
4101 // - no overlap.
4102 // - partial overlap (there are elements in both ranges that isn't
4103 // in the other, and there are also elements that are in both).
4104 // - argument range entirely inside word range.
4105 // - word range entirely inside argument range.
4106 // - ranges are completely equal.
4107
4108 // First check for no overlap. The earlier range is not in the other set.
4109 if (argument_range.from() > word_range.to()) {
4110 // Ranges are disjoint. The earlier word range contains elements that
4111 // cannot be in the argument set.
4112 result.SetElementsInSecondSet();
4113 } else if (word_range.from() > argument_range.to()) {
4114 // Ranges are disjoint. The earlier argument range contains elements that
4115 // cannot be in the word set.
4116 result.SetElementsInFirstSet();
4117 } else if (word_range.from() <= argument_range.from() &&
4118 word_range.to() >= argument_range.from()) {
4119 result.SetElementsInBothSets();
4120 // argument range completely inside word range.
4121 if (word_range.from() < argument_range.from() ||
4122 word_range.to() > argument_range.from()) {
4123 result.SetElementsInSecondSet();
4124 }
4125 } else if (word_range.from() >= argument_range.from() &&
4126 word_range.to() <= argument_range.from()) {
4127 result.SetElementsInBothSets();
4128 result.SetElementsInFirstSet();
4129 } else {
4130 // There is overlap, and neither is a subrange of the other
4131 result.SetElementsInFirstSet();
4132 result.SetElementsInSecondSet();
4133 result.SetElementsInBothSets();
4134 }
4135 if (result.NonTrivialIntersection()) {
4136 // The result is as (im)precise as we can possibly make it.
4137 return result;
4138 }
4139 // Progress the range(s) with minimal to-character.
4140 uc16 word_to = word_range.to();
4141 uc16 argument_to = argument_range.to();
4142 if (argument_to <= word_to) {
4143 j++;
4144 if (j < range->length()) {
4145 argument_range = range->at(j);
4146 }
4147 }
4148 if (word_to <= argument_to) {
4149 i += 2;
4150 if (i < kWordRangeCount) {
4151 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4152 }
4153 }
4154 }
4155 // Check if anything wasn't compared in the loop.
4156 if (i < kWordRangeCount) {
4157 // word range contains something not in argument range.
4158 result.SetElementsInSecondSet();
4159 } else if (j < range->length()) {
4160 // Argument range contains something not in word range.
4161 result.SetElementsInFirstSet();
4162 }
4163
4164 return result;
4165}
4166
4167
ager@chromium.org38e4c712009-11-11 09:11:58 +00004168static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4169 int bottom,
4170 int top) {
4171 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4172 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4173 // this table is correct.
4174 // 0x0600 - 0x0fff
4175 // 0x1100 - 0x1cff
4176 // 0x2000 - 0x20ff
4177 // 0x2200 - 0x23ff
4178 // 0x2500 - 0x2bff
4179 // 0x2e00 - 0xa5ff
4180 // 0xa800 - 0xfaff
4181 // 0xfc00 - 0xfeff
4182 const int boundary_count = 18;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004183 int boundaries[] = {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004184 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4185 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4186
4187 // Special ASCII rule from spec can save us some work here.
4188 if (bottom == 0x80 && top == 0xffff) return;
4189
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004190 if (top <= boundaries[0]) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004191 CharacterRange range(bottom, top);
4192 range.AddCaseEquivalents(ranges, false);
4193 return;
4194 }
4195
4196 // Split up very large ranges. This helps remove ranges where there are no
4197 // case mappings.
4198 for (int i = 0; i < boundary_count; i++) {
4199 if (bottom < boundaries[i] && top >= boundaries[i]) {
4200 AddUncanonicals(ranges, bottom, boundaries[i] - 1);
4201 AddUncanonicals(ranges, boundaries[i], top);
4202 return;
4203 }
4204 }
4205
4206 // If we are completely in a zone with no case mappings then we are done.
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004207 for (int i = 0; i < boundary_count; i += 2) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004208 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4209#ifdef DEBUG
4210 for (int j = bottom; j <= top; j++) {
4211 unsigned current_char = j;
4212 int length = uncanonicalize.get(current_char, '\0', chars);
4213 for (int k = 0; k < length; k++) {
4214 ASSERT(chars[k] == current_char);
4215 }
4216 }
4217#endif
4218 return;
4219 }
4220 }
4221
4222 // Step through the range finding equivalent characters.
4223 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4224 for (int i = bottom; i <= top; i++) {
4225 int length = uncanonicalize.get(i, '\0', chars);
4226 for (int j = 0; j < length; j++) {
4227 uc32 chr = chars[j];
4228 if (chr != i && (chr < bottom || chr > top)) {
4229 characters->Add(chr);
4230 }
4231 }
4232 }
4233
4234 // Step through the equivalent characters finding simple ranges and
4235 // adding ranges to the character class.
4236 if (characters->length() > 0) {
4237 int new_from = characters->at(0);
4238 int new_to = new_from;
4239 for (int i = 1; i < characters->length(); i++) {
4240 int chr = characters->at(i);
4241 if (chr == new_to + 1) {
4242 new_to++;
4243 } else {
4244 if (new_to == new_from) {
4245 ranges->Add(CharacterRange::Singleton(new_from));
4246 } else {
4247 ranges->Add(CharacterRange(new_from, new_to));
4248 }
4249 new_from = new_to = chr;
4250 }
4251 }
4252 if (new_to == new_from) {
4253 ranges->Add(CharacterRange::Singleton(new_from));
4254 } else {
4255 ranges->Add(CharacterRange(new_from, new_to));
4256 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004257 }
4258}
4259
4260
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004261ZoneList<CharacterRange>* CharacterSet::ranges() {
4262 if (ranges_ == NULL) {
4263 ranges_ = new ZoneList<CharacterRange>(2);
4264 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4265 }
4266 return ranges_;
4267}
4268
4269
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004270// Move a number of elements in a zonelist to another position
4271// in the same list. Handles overlapping source and target areas.
4272static void MoveRanges(ZoneList<CharacterRange>* list,
4273 int from,
4274 int to,
4275 int count) {
4276 // Ranges are potentially overlapping.
4277 if (from < to) {
4278 for (int i = count - 1; i >= 0; i--) {
4279 list->at(to + i) = list->at(from + i);
4280 }
4281 } else {
4282 for (int i = 0; i < count; i++) {
4283 list->at(to + i) = list->at(from + i);
4284 }
4285 }
4286}
4287
4288
4289static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4290 int count,
4291 CharacterRange insert) {
4292 // Inserts a range into list[0..count[, which must be sorted
4293 // by from value and non-overlapping and non-adjacent, using at most
4294 // list[0..count] for the result. Returns the number of resulting
4295 // canonicalized ranges. Inserting a range may collapse existing ranges into
4296 // fewer ranges, so the return value can be anything in the range 1..count+1.
4297 uc16 from = insert.from();
4298 uc16 to = insert.to();
4299 int start_pos = 0;
4300 int end_pos = count;
4301 for (int i = count - 1; i >= 0; i--) {
4302 CharacterRange current = list->at(i);
4303 if (current.from() > to + 1) {
4304 end_pos = i;
4305 } else if (current.to() + 1 < from) {
4306 start_pos = i + 1;
4307 break;
4308 }
4309 }
4310
4311 // Inserted range overlaps, or is adjacent to, ranges at positions
4312 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4313 // not affected by the insertion.
4314 // If start_pos == end_pos, the range must be inserted before start_pos.
4315 // if start_pos < end_pos, the entire range from start_pos to end_pos
4316 // must be merged with the insert range.
4317
4318 if (start_pos == end_pos) {
4319 // Insert between existing ranges at position start_pos.
4320 if (start_pos < count) {
4321 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4322 }
4323 list->at(start_pos) = insert;
4324 return count + 1;
4325 }
4326 if (start_pos + 1 == end_pos) {
4327 // Replace single existing range at position start_pos.
4328 CharacterRange to_replace = list->at(start_pos);
4329 int new_from = Min(to_replace.from(), from);
4330 int new_to = Max(to_replace.to(), to);
4331 list->at(start_pos) = CharacterRange(new_from, new_to);
4332 return count;
4333 }
4334 // Replace a number of existing ranges from start_pos to end_pos - 1.
4335 // Move the remaining ranges down.
4336
4337 int new_from = Min(list->at(start_pos).from(), from);
4338 int new_to = Max(list->at(end_pos - 1).to(), to);
4339 if (end_pos < count) {
4340 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4341 }
4342 list->at(start_pos) = CharacterRange(new_from, new_to);
4343 return count - (end_pos - start_pos) + 1;
4344}
4345
4346
4347void CharacterSet::Canonicalize() {
4348 // Special/default classes are always considered canonical. The result
4349 // of calling ranges() will be sorted.
4350 if (ranges_ == NULL) return;
4351 CharacterRange::Canonicalize(ranges_);
4352}
4353
4354
4355void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4356 if (character_ranges->length() <= 1) return;
4357 // Check whether ranges are already canonical (increasing, non-overlapping,
4358 // non-adjacent).
4359 int n = character_ranges->length();
4360 int max = character_ranges->at(0).to();
4361 int i = 1;
4362 while (i < n) {
4363 CharacterRange current = character_ranges->at(i);
4364 if (current.from() <= max + 1) {
4365 break;
4366 }
4367 max = current.to();
4368 i++;
4369 }
4370 // Canonical until the i'th range. If that's all of them, we are done.
4371 if (i == n) return;
4372
4373 // The ranges at index i and forward are not canonicalized. Make them so by
4374 // doing the equivalent of insertion sort (inserting each into the previous
4375 // list, in order).
4376 // Notice that inserting a range can reduce the number of ranges in the
4377 // result due to combining of adjacent and overlapping ranges.
4378 int read = i; // Range to insert.
4379 int num_canonical = i; // Length of canonicalized part of list.
4380 do {
4381 num_canonical = InsertRangeInCanonicalList(character_ranges,
4382 num_canonical,
4383 character_ranges->at(read));
4384 read++;
4385 } while (read < n);
4386 character_ranges->Rewind(num_canonical);
4387
4388 ASSERT(CharacterRange::IsCanonical(character_ranges));
4389}
4390
4391
4392// Utility function for CharacterRange::Merge. Adds a range at the end of
4393// a canonicalized range list, if necessary merging the range with the last
4394// range of the list.
4395static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4396 if (set == NULL) return;
4397 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4398 int n = set->length();
4399 if (n > 0) {
4400 CharacterRange lastRange = set->at(n - 1);
4401 if (lastRange.to() == range.from() - 1) {
4402 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4403 return;
4404 }
4405 }
4406 set->Add(range);
4407}
4408
4409
4410static void AddRangeToSelectedSet(int selector,
4411 ZoneList<CharacterRange>* first_set,
4412 ZoneList<CharacterRange>* second_set,
4413 ZoneList<CharacterRange>* intersection_set,
4414 CharacterRange range) {
4415 switch (selector) {
4416 case kInsideFirst:
4417 AddRangeToSet(first_set, range);
4418 break;
4419 case kInsideSecond:
4420 AddRangeToSet(second_set, range);
4421 break;
4422 case kInsideBoth:
4423 AddRangeToSet(intersection_set, range);
4424 break;
4425 }
4426}
4427
4428
4429
4430void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4431 ZoneList<CharacterRange>* second_set,
4432 ZoneList<CharacterRange>* first_set_only_out,
4433 ZoneList<CharacterRange>* second_set_only_out,
4434 ZoneList<CharacterRange>* both_sets_out) {
4435 // Inputs are canonicalized.
4436 ASSERT(CharacterRange::IsCanonical(first_set));
4437 ASSERT(CharacterRange::IsCanonical(second_set));
4438 // Outputs are empty, if applicable.
4439 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4440 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4441 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4442
4443 // Merge sets by iterating through the lists in order of lowest "from" value,
4444 // and putting intervals into one of three sets.
4445
4446 if (first_set->length() == 0) {
4447 second_set_only_out->AddAll(*second_set);
4448 return;
4449 }
4450 if (second_set->length() == 0) {
4451 first_set_only_out->AddAll(*first_set);
4452 return;
4453 }
4454 // Indices into input lists.
4455 int i1 = 0;
4456 int i2 = 0;
4457 // Cache length of input lists.
4458 int n1 = first_set->length();
4459 int n2 = second_set->length();
4460 // Current range. May be invalid if state is kInsideNone.
4461 int from = 0;
4462 int to = -1;
4463 // Where current range comes from.
4464 int state = kInsideNone;
4465
4466 while (i1 < n1 || i2 < n2) {
4467 CharacterRange next_range;
4468 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004469 if (i2 == n2 ||
4470 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4471 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004472 next_range = first_set->at(i1++);
4473 range_source = kInsideFirst;
4474 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004475 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004476 next_range = second_set->at(i2++);
4477 range_source = kInsideSecond;
4478 }
4479 if (to < next_range.from()) {
4480 // Ranges disjoint: |current| |next|
4481 AddRangeToSelectedSet(state,
4482 first_set_only_out,
4483 second_set_only_out,
4484 both_sets_out,
4485 CharacterRange(from, to));
4486 from = next_range.from();
4487 to = next_range.to();
4488 state = range_source;
4489 } else {
4490 if (from < next_range.from()) {
4491 AddRangeToSelectedSet(state,
4492 first_set_only_out,
4493 second_set_only_out,
4494 both_sets_out,
4495 CharacterRange(from, next_range.from()-1));
4496 }
4497 if (to < next_range.to()) {
4498 // Ranges overlap: |current|
4499 // |next|
4500 AddRangeToSelectedSet(state | range_source,
4501 first_set_only_out,
4502 second_set_only_out,
4503 both_sets_out,
4504 CharacterRange(next_range.from(), to));
4505 from = to + 1;
4506 to = next_range.to();
4507 state = range_source;
4508 } else {
4509 // Range included: |current| , possibly ending at same character.
4510 // |next|
4511 AddRangeToSelectedSet(
4512 state | range_source,
4513 first_set_only_out,
4514 second_set_only_out,
4515 both_sets_out,
4516 CharacterRange(next_range.from(), next_range.to()));
4517 from = next_range.to() + 1;
4518 // If ranges end at same character, both ranges are consumed completely.
4519 if (next_range.to() == to) state = kInsideNone;
4520 }
4521 }
4522 }
4523 AddRangeToSelectedSet(state,
4524 first_set_only_out,
4525 second_set_only_out,
4526 both_sets_out,
4527 CharacterRange(from, to));
4528}
4529
4530
4531void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4532 ZoneList<CharacterRange>* negated_ranges) {
4533 ASSERT(CharacterRange::IsCanonical(ranges));
4534 ASSERT_EQ(0, negated_ranges->length());
4535 int range_count = ranges->length();
4536 uc16 from = 0;
4537 int i = 0;
4538 if (range_count > 0 && ranges->at(0).from() == 0) {
4539 from = ranges->at(0).to();
4540 i = 1;
4541 }
4542 while (i < range_count) {
4543 CharacterRange range = ranges->at(i);
4544 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4545 from = range.to();
4546 i++;
4547 }
4548 if (from < String::kMaxUC16CharCode) {
4549 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4550 }
4551}
4552
4553
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004554
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004555// -------------------------------------------------------------------
4556// Interest propagation
4557
4558
4559RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4560 for (int i = 0; i < siblings_.length(); i++) {
4561 RegExpNode* sibling = siblings_.Get(i);
4562 if (sibling->info()->Matches(info))
4563 return sibling;
4564 }
4565 return NULL;
4566}
4567
4568
4569RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4570 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004571 siblings_.Ensure(this);
4572 RegExpNode* result = TryGetSibling(info);
4573 if (result != NULL) return result;
4574 result = this->Clone();
4575 NodeInfo* new_info = result->info();
4576 new_info->ResetCompilationState();
4577 new_info->AddFromPreceding(info);
4578 AddSibling(result);
4579 *cloned = true;
4580 return result;
4581}
4582
4583
4584template <class C>
4585static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4586 NodeInfo full_info(*node->info());
4587 full_info.AddFromPreceding(info);
4588 bool cloned = false;
4589 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4590}
4591
4592
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004593// -------------------------------------------------------------------
4594// Splay tree
4595
4596
4597OutSet* OutSet::Extend(unsigned value) {
4598 if (Get(value))
4599 return this;
4600 if (successors() != NULL) {
4601 for (int i = 0; i < successors()->length(); i++) {
4602 OutSet* successor = successors()->at(i);
4603 if (successor->Get(value))
4604 return successor;
4605 }
4606 } else {
4607 successors_ = new ZoneList<OutSet*>(2);
4608 }
4609 OutSet* result = new OutSet(first_, remaining_);
4610 result->Set(value);
4611 successors()->Add(result);
4612 return result;
4613}
4614
4615
4616void OutSet::Set(unsigned value) {
4617 if (value < kFirstLimit) {
4618 first_ |= (1 << value);
4619 } else {
4620 if (remaining_ == NULL)
4621 remaining_ = new ZoneList<unsigned>(1);
4622 if (remaining_->is_empty() || !remaining_->Contains(value))
4623 remaining_->Add(value);
4624 }
4625}
4626
4627
4628bool OutSet::Get(unsigned value) {
4629 if (value < kFirstLimit) {
4630 return (first_ & (1 << value)) != 0;
4631 } else if (remaining_ == NULL) {
4632 return false;
4633 } else {
4634 return remaining_->Contains(value);
4635 }
4636}
4637
4638
4639const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4640const DispatchTable::Entry DispatchTable::Config::kNoValue;
4641
4642
4643void DispatchTable::AddRange(CharacterRange full_range, int value) {
4644 CharacterRange current = full_range;
4645 if (tree()->is_empty()) {
4646 // If this is the first range we just insert into the table.
4647 ZoneSplayTree<Config>::Locator loc;
4648 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4649 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4650 return;
4651 }
4652 // First see if there is a range to the left of this one that
4653 // overlaps.
4654 ZoneSplayTree<Config>::Locator loc;
4655 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4656 Entry* entry = &loc.value();
4657 // If we've found a range that overlaps with this one, and it
4658 // starts strictly to the left of this one, we have to fix it
4659 // because the following code only handles ranges that start on
4660 // or after the start point of the range we're adding.
4661 if (entry->from() < current.from() && entry->to() >= current.from()) {
4662 // Snap the overlapping range in half around the start point of
4663 // the range we're adding.
4664 CharacterRange left(entry->from(), current.from() - 1);
4665 CharacterRange right(current.from(), entry->to());
4666 // The left part of the overlapping range doesn't overlap.
4667 // Truncate the whole entry to be just the left part.
4668 entry->set_to(left.to());
4669 // The right part is the one that overlaps. We add this part
4670 // to the map and let the next step deal with merging it with
4671 // the range we're adding.
4672 ZoneSplayTree<Config>::Locator loc;
4673 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4674 loc.set_value(Entry(right.from(),
4675 right.to(),
4676 entry->out_set()));
4677 }
4678 }
4679 while (current.is_valid()) {
4680 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4681 (loc.value().from() <= current.to()) &&
4682 (loc.value().to() >= current.from())) {
4683 Entry* entry = &loc.value();
4684 // We have overlap. If there is space between the start point of
4685 // the range we're adding and where the overlapping range starts
4686 // then we have to add a range covering just that space.
4687 if (current.from() < entry->from()) {
4688 ZoneSplayTree<Config>::Locator ins;
4689 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4690 ins.set_value(Entry(current.from(),
4691 entry->from() - 1,
4692 empty()->Extend(value)));
4693 current.set_from(entry->from());
4694 }
4695 ASSERT_EQ(current.from(), entry->from());
4696 // If the overlapping range extends beyond the one we want to add
4697 // we have to snap the right part off and add it separately.
4698 if (entry->to() > current.to()) {
4699 ZoneSplayTree<Config>::Locator ins;
4700 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4701 ins.set_value(Entry(current.to() + 1,
4702 entry->to(),
4703 entry->out_set()));
4704 entry->set_to(current.to());
4705 }
4706 ASSERT(entry->to() <= current.to());
4707 // The overlapping range is now completely contained by the range
4708 // we're adding so we can just update it and move the start point
4709 // of the range we're adding just past it.
4710 entry->AddValue(value);
4711 // Bail out if the last interval ended at 0xFFFF since otherwise
4712 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004713 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004714 break;
4715 ASSERT(entry->to() + 1 > current.from());
4716 current.set_from(entry->to() + 1);
4717 } else {
4718 // There is no overlap so we can just add the range
4719 ZoneSplayTree<Config>::Locator ins;
4720 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4721 ins.set_value(Entry(current.from(),
4722 current.to(),
4723 empty()->Extend(value)));
4724 break;
4725 }
4726 }
4727}
4728
4729
4730OutSet* DispatchTable::Get(uc16 value) {
4731 ZoneSplayTree<Config>::Locator loc;
4732 if (!tree()->FindGreatestLessThan(value, &loc))
4733 return empty();
4734 Entry* entry = &loc.value();
4735 if (value <= entry->to())
4736 return entry->out_set();
4737 else
4738 return empty();
4739}
4740
4741
4742// -------------------------------------------------------------------
4743// Analysis
4744
4745
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004746void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004747 StackLimitCheck check;
4748 if (check.HasOverflowed()) {
4749 fail("Stack overflow");
4750 return;
4751 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004752 if (that->info()->been_analyzed || that->info()->being_analyzed)
4753 return;
4754 that->info()->being_analyzed = true;
4755 that->Accept(this);
4756 that->info()->being_analyzed = false;
4757 that->info()->been_analyzed = true;
4758}
4759
4760
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004761void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004762 // nothing to do
4763}
4764
4765
ager@chromium.org8bb60582008-12-11 12:02:20 +00004766void TextNode::CalculateOffsets() {
4767 int element_count = elements()->length();
4768 // Set up the offsets of the elements relative to the start. This is a fixed
4769 // quantity since a TextNode can only contain fixed-width things.
4770 int cp_offset = 0;
4771 for (int i = 0; i < element_count; i++) {
4772 TextElement& elm = elements()->at(i);
4773 elm.cp_offset = cp_offset;
4774 if (elm.type == TextElement::ATOM) {
4775 cp_offset += elm.data.u_atom->data().length();
4776 } else {
4777 cp_offset++;
4778 Vector<const uc16> quarks = elm.data.u_atom->data();
4779 }
4780 }
4781}
4782
4783
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004784void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004785 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004786 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004787 }
4788 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004789 if (!has_failed()) {
4790 that->CalculateOffsets();
4791 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004792}
4793
4794
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004795void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004796 RegExpNode* target = that->on_success();
4797 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004798 if (!has_failed()) {
4799 // If the next node is interested in what it follows then this node
4800 // has to be interested too so it can pass the information on.
4801 that->info()->AddFromFollowing(target->info());
4802 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004803}
4804
4805
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004806void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004807 NodeInfo* info = that->info();
4808 for (int i = 0; i < that->alternatives()->length(); i++) {
4809 RegExpNode* node = that->alternatives()->at(i).node();
4810 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004811 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004812 // Anything the following nodes need to know has to be known by
4813 // this node also, so it can pass it on.
4814 info->AddFromFollowing(node->info());
4815 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004816}
4817
4818
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004819void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4820 NodeInfo* info = that->info();
4821 for (int i = 0; i < that->alternatives()->length(); i++) {
4822 RegExpNode* node = that->alternatives()->at(i).node();
4823 if (node != that->loop_node()) {
4824 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004825 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004826 info->AddFromFollowing(node->info());
4827 }
4828 }
4829 // Check the loop last since it may need the value of this node
4830 // to get a correct result.
4831 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004832 if (!has_failed()) {
4833 info->AddFromFollowing(that->loop_node()->info());
4834 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004835}
4836
4837
4838void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004839 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004840}
4841
4842
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004843void Analysis::VisitAssertion(AssertionNode* that) {
4844 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004845 AssertionNode::AssertionNodeType type = that->type();
4846 if (type == AssertionNode::AT_BOUNDARY ||
4847 type == AssertionNode::AT_NON_BOUNDARY) {
4848 // Check if the following character is known to be a word character
4849 // or known to not be a word character.
4850 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4851
4852 CharacterRange::Canonicalize(following_chars);
4853
4854 SetRelation word_relation =
4855 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004856 if (word_relation.Disjoint()) {
4857 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004858 // Following character is definitely *not* a word character.
4859 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004860 AssertionNode::AFTER_WORD_CHARACTER :
4861 AssertionNode::AFTER_NONWORD_CHARACTER;
4862 that->set_type(type);
4863 } else if (word_relation.ContainedIn()) {
4864 // Following character is definitely a word character.
4865 type = (type == AssertionNode::AT_BOUNDARY) ?
4866 AssertionNode::AFTER_NONWORD_CHARACTER :
4867 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004868 that->set_type(type);
4869 }
4870 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004871}
4872
4873
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004874ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4875 if (first_character_set_ == NULL) {
4876 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4877 // If we can't find an exact solution within the budget, we
4878 // set the value to the set of every character, i.e., all characters
4879 // are possible.
4880 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4881 all_set->Add(CharacterRange::Everything());
4882 first_character_set_ = all_set;
4883 }
4884 }
4885 return first_character_set_;
4886}
4887
4888
4889int RegExpNode::ComputeFirstCharacterSet(int budget) {
4890 // Default behavior is to not be able to determine the first character.
4891 return kComputeFirstCharacterSetFail;
4892}
4893
4894
4895int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
4896 budget--;
4897 if (budget >= 0) {
4898 // Find loop min-iteration. It's the value of the guarded choice node
4899 // with a GEQ guard, if any.
4900 int min_repetition = 0;
4901
4902 for (int i = 0; i <= 1; i++) {
4903 GuardedAlternative alternative = alternatives()->at(i);
4904 ZoneList<Guard*>* guards = alternative.guards();
4905 if (guards != NULL && guards->length() > 0) {
4906 Guard* guard = guards->at(0);
4907 if (guard->op() == Guard::GEQ) {
4908 min_repetition = guard->value();
4909 break;
4910 }
4911 }
4912 }
4913
4914 budget = loop_node()->ComputeFirstCharacterSet(budget);
4915 if (budget >= 0) {
4916 ZoneList<CharacterRange>* character_set =
4917 loop_node()->first_character_set();
4918 if (body_can_be_zero_length() || min_repetition == 0) {
4919 budget = continue_node()->ComputeFirstCharacterSet(budget);
4920 if (budget < 0) return budget;
4921 ZoneList<CharacterRange>* body_set =
4922 continue_node()->first_character_set();
4923 ZoneList<CharacterRange>* union_set =
4924 new ZoneList<CharacterRange>(Max(character_set->length(),
4925 body_set->length()));
4926 CharacterRange::Merge(character_set,
4927 body_set,
4928 union_set,
4929 union_set,
4930 union_set);
4931 character_set = union_set;
4932 }
4933 set_first_character_set(character_set);
4934 }
4935 }
4936 return budget;
4937}
4938
4939
4940int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
4941 budget--;
4942 if (budget >= 0) {
4943 GuardedAlternative successor = this->alternatives()->at(1);
4944 RegExpNode* successor_node = successor.node();
4945 budget = successor_node->ComputeFirstCharacterSet(budget);
4946 if (budget >= 0) {
4947 set_first_character_set(successor_node->first_character_set());
4948 }
4949 }
4950 return budget;
4951}
4952
4953
4954// The first character set of an EndNode is unknowable. Just use the
4955// default implementation that fails and returns all characters as possible.
4956
4957
4958int AssertionNode::ComputeFirstCharacterSet(int budget) {
4959 budget -= 1;
4960 if (budget >= 0) {
4961 switch (type_) {
4962 case AT_END: {
4963 set_first_character_set(new ZoneList<CharacterRange>(0));
4964 break;
4965 }
4966 case AT_START:
4967 case AT_BOUNDARY:
4968 case AT_NON_BOUNDARY:
4969 case AFTER_NEWLINE:
4970 case AFTER_NONWORD_CHARACTER:
4971 case AFTER_WORD_CHARACTER: {
4972 ASSERT_NOT_NULL(on_success());
4973 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00004974 if (budget >= 0) {
4975 set_first_character_set(on_success()->first_character_set());
4976 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004977 break;
4978 }
4979 }
4980 }
4981 return budget;
4982}
4983
4984
4985int ActionNode::ComputeFirstCharacterSet(int budget) {
4986 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
4987 budget--;
4988 if (budget >= 0) {
4989 ASSERT_NOT_NULL(on_success());
4990 budget = on_success()->ComputeFirstCharacterSet(budget);
4991 if (budget >= 0) {
4992 set_first_character_set(on_success()->first_character_set());
4993 }
4994 }
4995 return budget;
4996}
4997
4998
4999int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5000 // We don't know anything about the first character of a backreference
5001 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005002 // The potential first characters are the first characters of the capture,
5003 // and the first characters of the on_success node, depending on whether the
5004 // capture can be empty and whether it is known to be participating or known
5005 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005006 return kComputeFirstCharacterSetFail;
5007}
5008
5009
5010int TextNode::ComputeFirstCharacterSet(int budget) {
5011 budget--;
5012 if (budget >= 0) {
5013 ASSERT_NE(0, elements()->length());
5014 TextElement text = elements()->at(0);
5015 if (text.type == TextElement::ATOM) {
5016 RegExpAtom* atom = text.data.u_atom;
5017 ASSERT_NE(0, atom->length());
5018 uc16 first_char = atom->data()[0];
5019 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5020 range->Add(CharacterRange(first_char, first_char));
5021 set_first_character_set(range);
5022 } else {
5023 ASSERT(text.type == TextElement::CHAR_CLASS);
5024 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005025 ZoneList<CharacterRange>* ranges = char_class->ranges();
5026 // TODO(lrn): Canonicalize ranges when they are created
5027 // instead of waiting until now.
5028 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005029 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005030 int length = ranges->length();
5031 int new_length = length + 1;
5032 if (length > 0) {
5033 if (ranges->at(0).from() == 0) new_length--;
5034 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5035 new_length--;
5036 }
5037 }
5038 ZoneList<CharacterRange>* negated_ranges =
5039 new ZoneList<CharacterRange>(new_length);
5040 CharacterRange::Negate(ranges, negated_ranges);
5041 set_first_character_set(negated_ranges);
5042 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005043 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005044 }
5045 }
5046 }
5047 return budget;
5048}
5049
5050
5051
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005052// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005053// Dispatch table construction
5054
5055
5056void DispatchTableConstructor::VisitEnd(EndNode* that) {
5057 AddRange(CharacterRange::Everything());
5058}
5059
5060
5061void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5062 node->set_being_calculated(true);
5063 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5064 for (int i = 0; i < alternatives->length(); i++) {
5065 set_choice_index(i);
5066 alternatives->at(i).node()->Accept(this);
5067 }
5068 node->set_being_calculated(false);
5069}
5070
5071
5072class AddDispatchRange {
5073 public:
5074 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5075 : constructor_(constructor) { }
5076 void Call(uc32 from, DispatchTable::Entry entry);
5077 private:
5078 DispatchTableConstructor* constructor_;
5079};
5080
5081
5082void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5083 CharacterRange range(from, entry.to());
5084 constructor_->AddRange(range);
5085}
5086
5087
5088void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5089 if (node->being_calculated())
5090 return;
5091 DispatchTable* table = node->GetTable(ignore_case_);
5092 AddDispatchRange adder(this);
5093 table->ForEach(&adder);
5094}
5095
5096
5097void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5098 // TODO(160): Find the node that we refer back to and propagate its start
5099 // set back to here. For now we just accept anything.
5100 AddRange(CharacterRange::Everything());
5101}
5102
5103
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005104void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5105 RegExpNode* target = that->on_success();
5106 target->Accept(this);
5107}
5108
5109
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005110static int CompareRangeByFrom(const CharacterRange* a,
5111 const CharacterRange* b) {
5112 return Compare<uc16>(a->from(), b->from());
5113}
5114
5115
5116void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5117 ranges->Sort(CompareRangeByFrom);
5118 uc16 last = 0;
5119 for (int i = 0; i < ranges->length(); i++) {
5120 CharacterRange range = ranges->at(i);
5121 if (last < range.from())
5122 AddRange(CharacterRange(last, range.from() - 1));
5123 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005124 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005125 return;
5126 } else {
5127 last = range.to() + 1;
5128 }
5129 }
5130 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005131 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005132}
5133
5134
5135void DispatchTableConstructor::VisitText(TextNode* that) {
5136 TextElement elm = that->elements()->at(0);
5137 switch (elm.type) {
5138 case TextElement::ATOM: {
5139 uc16 c = elm.data.u_atom->data()[0];
5140 AddRange(CharacterRange(c, c));
5141 break;
5142 }
5143 case TextElement::CHAR_CLASS: {
5144 RegExpCharacterClass* tree = elm.data.u_char_class;
5145 ZoneList<CharacterRange>* ranges = tree->ranges();
5146 if (tree->is_negated()) {
5147 AddInverse(ranges);
5148 } else {
5149 for (int i = 0; i < ranges->length(); i++)
5150 AddRange(ranges->at(i));
5151 }
5152 break;
5153 }
5154 default: {
5155 UNIMPLEMENTED();
5156 }
5157 }
5158}
5159
5160
5161void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005162 RegExpNode* target = that->on_success();
5163 target->Accept(this);
5164}
5165
5166
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005167RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5168 bool ignore_case,
5169 bool is_multiline,
5170 Handle<String> pattern,
5171 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005172 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005173 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005174 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005175 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005176 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005177 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005178 0,
5179 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005180 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005181 RegExpNode* node = captured_body;
5182 if (!data->tree->IsAnchored()) {
5183 // Add a .*? at the beginning, outside the body capture, unless
5184 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005185 RegExpNode* loop_node =
5186 RegExpQuantifier::ToNode(0,
5187 RegExpTree::kInfinity,
5188 false,
5189 new RegExpCharacterClass('*'),
5190 &compiler,
5191 captured_body,
5192 data->contains_anchor);
5193
5194 if (data->contains_anchor) {
5195 // Unroll loop once, to take care of the case that might start
5196 // at the start of input.
5197 ChoiceNode* first_step_node = new ChoiceNode(2);
5198 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5199 first_step_node->AddAlternative(GuardedAlternative(
5200 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5201 node = first_step_node;
5202 } else {
5203 node = loop_node;
5204 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005205 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005206 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005207 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005208 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005209 if (analysis.has_failed()) {
5210 const char* error_message = analysis.error_message();
5211 return CompilationResult(error_message);
5212 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005213
5214 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005215
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005216 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005217#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005218 // Native regexp implementation.
5219
5220 NativeRegExpMacroAssembler::Mode mode =
5221 is_ascii ? NativeRegExpMacroAssembler::ASCII
5222 : NativeRegExpMacroAssembler::UC16;
5223
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005224#if V8_TARGET_ARCH_IA32
5225 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5226#elif V8_TARGET_ARCH_X64
5227 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5228#elif V8_TARGET_ARCH_ARM
5229 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005230#endif
5231
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005232#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005233 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005234 EmbeddedVector<byte, 1024> codes;
5235 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005236#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005237
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005238 return compiler.Assemble(&macro_assembler,
5239 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005240 data->capture_count,
5241 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005242}
5243
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005244
5245int OffsetsVector::static_offsets_vector_[
5246 OffsetsVector::kStaticOffsetsVectorSize];
5247
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005248}} // namespace v8::internal