blob: 8cd13bc4166e9f60e789faf44fb07c70fdcc48ed [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);
fschneider@chromium.orge03fb642010-11-01 12:34:09 +0000128 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
129 &parse_result)) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000130 // Throw an exception if we fail to parse the pattern.
131 ThrowRegExpException(re,
132 pattern,
133 parse_result.error,
134 "malformed_regexp");
135 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000136 }
137
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000138 if (parse_result.simple && !flags.is_ignore_case()) {
139 // Parse-tree is a single atom that is equal to the pattern.
140 AtomCompile(re, pattern, flags, pattern);
141 } else if (parse_result.tree->IsAtom() &&
142 !flags.is_ignore_case() &&
143 parse_result.capture_count == 0) {
144 RegExpAtom* atom = parse_result.tree->AsAtom();
145 Vector<const uc16> atom_pattern = atom->data();
146 Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern);
147 AtomCompile(re, pattern, flags, atom_string);
148 } else {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000149 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000150 }
151 ASSERT(re->data()->IsFixedArray());
152 // Compilation succeeded so the data is set on the regexp
153 // and we can store it in the cache.
154 Handle<FixedArray> data(FixedArray::cast(re->data()));
155 CompilationCache::PutRegExp(pattern, flags, data);
156
157 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000158}
159
160
161Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
162 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000163 int index,
164 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000165 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000166 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000167 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000168 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000169 Handle<Object> result =
170 IrregexpExec(regexp, subject, index, last_match_info);
ager@chromium.org6f10e412009-02-13 10:11:16 +0000171 ASSERT(!result.is_null() || Top::has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000172 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000173 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000174 default:
175 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000176 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000177 }
178}
179
180
ager@chromium.org8bb60582008-12-11 12:02:20 +0000181// RegExp Atom implementation: Simple string search using indexOf.
182
183
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000184void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
185 Handle<String> pattern,
186 JSRegExp::Flags flags,
187 Handle<String> match_pattern) {
188 Factory::SetRegExpAtomData(re,
189 JSRegExp::ATOM,
190 pattern,
191 flags,
192 match_pattern);
193}
194
195
196static void SetAtomLastCapture(FixedArray* array,
197 String* subject,
198 int from,
199 int to) {
200 NoHandleAllocation no_handles;
201 RegExpImpl::SetLastCaptureCount(array, 2);
202 RegExpImpl::SetLastSubject(array, subject);
203 RegExpImpl::SetLastInput(array, subject);
204 RegExpImpl::SetCapture(array, 0, from);
205 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000206}
207
208
209Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
210 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000211 int index,
212 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000213 Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex)));
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000214
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000215 uint32_t start_index = index;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000216
ager@chromium.org7c537e22008-10-16 08:43:32 +0000217 int value = Runtime::StringMatch(subject, needle, start_index);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000218 if (value == -1) return Factory::null_value();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000219 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000220
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000221 {
222 NoHandleAllocation no_handles;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000223 FixedArray* array = FixedArray::cast(last_match_info->elements());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000224 SetAtomLastCapture(array, *subject, value, value + needle->length());
225 }
226 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000227}
228
229
ager@chromium.org8bb60582008-12-11 12:02:20 +0000230// Irregexp implementation.
231
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000232// Ensures that the regexp object contains a compiled version of the
233// source for either ASCII or non-ASCII strings.
234// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000235// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000236// If compilation fails, an exception is thrown and this function
237// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000238bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000239 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000240#ifdef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000241 if (compiled_code->IsByteArray()) return true;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000242#else // V8_INTERPRETED_REGEXP (RegExp native code)
243 if (compiled_code->IsCode()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000244#endif
245 return CompileIrregexp(re, is_ascii);
246}
ager@chromium.org8bb60582008-12-11 12:02:20 +0000247
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000248
249bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000250 // Compile the RegExp.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000251 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000252 PostponeInterruptsScope postpone;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000253 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
254 if (entry->IsJSObject()) {
255 // If it's a JSObject, a previous compilation failed and threw this object.
256 // Re-throw the object without trying again.
257 Top::Throw(entry);
258 return false;
259 }
260 ASSERT(entry->IsTheHole());
ager@chromium.org8bb60582008-12-11 12:02:20 +0000261
262 JSRegExp::Flags flags = re->GetFlags();
263
264 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000265 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000266 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000267 }
268
269 RegExpCompileData compile_data;
270 FlatStringReader reader(pattern);
fschneider@chromium.orge03fb642010-11-01 12:34:09 +0000271 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
272 &compile_data)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000273 // Throw an exception if we fail to parse the pattern.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000274 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000275 ThrowRegExpException(re,
276 pattern,
277 compile_data.error,
278 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000279 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000280 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000281 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000282 RegExpEngine::Compile(&compile_data,
283 flags.is_ignore_case(),
284 flags.is_multiline(),
285 pattern,
286 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000287 if (result.error_message != NULL) {
288 // Unable to compile regexp.
289 Handle<JSArray> array = Factory::NewJSArray(2);
290 SetElement(array, 0, pattern);
291 SetElement(array,
292 1,
293 Factory::NewStringFromUtf8(CStrVector(result.error_message)));
294 Handle<Object> regexp_err =
295 Factory::NewSyntaxError("malformed_regexp", array);
296 Top::Throw(*regexp_err);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000297 re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000298 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000299 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000300
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000301 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
302 data->set(JSRegExp::code_index(is_ascii), result.code);
303 int register_max = IrregexpMaxRegisterCount(*data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000304 if (result.num_registers > register_max) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000305 SetIrregexpMaxRegisterCount(*data, result.num_registers);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000306 }
307
308 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000309}
310
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000311
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000312int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
313 return Smi::cast(
314 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000315}
316
317
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000318void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
319 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000320}
321
322
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000323int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
324 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000325}
326
327
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000328int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
329 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000330}
331
332
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000333ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000334 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000335}
336
337
338Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000339 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000340}
341
342
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000343void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
344 Handle<String> pattern,
345 JSRegExp::Flags flags,
346 int capture_count) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000347 // Initialize compiled code entries to null.
348 Factory::SetRegExpIrregexpData(re,
349 JSRegExp::IRREGEXP,
350 pattern,
351 flags,
352 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000353}
354
355
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000356int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
357 Handle<String> subject) {
358 if (!subject->IsFlat()) {
359 FlattenString(subject);
360 }
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000361 // Check the asciiness of the underlying storage.
362 bool is_ascii;
363 {
364 AssertNoAllocation no_gc;
365 String* sequential_string = *subject;
366 if (subject->IsConsString()) {
367 sequential_string = ConsString::cast(*subject)->first();
368 }
369 is_ascii = sequential_string->IsAsciiRepresentation();
370 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000371 if (!EnsureCompiledIrregexp(regexp, is_ascii)) {
372 return -1;
373 }
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000374#ifdef V8_INTERPRETED_REGEXP
375 // Byte-code regexp needs space allocated for all its registers.
376 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
377#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000378 // Native regexp only needs room to output captures. Registers are handled
379 // internally.
380 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000381#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000382}
383
384
erik.corry@gmail.com145eff52010-08-23 11:36:18 +0000385RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(
386 Handle<JSRegExp> regexp,
387 Handle<String> subject,
388 int index,
389 Vector<int32_t> output) {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000390 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()));
391
392 ASSERT(index >= 0);
393 ASSERT(index <= subject->length());
394 ASSERT(subject->IsFlat());
395
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000396 // A flat ASCII string might have a two-byte first part.
397 if (subject->IsConsString()) {
398 subject = Handle<String>(ConsString::cast(*subject)->first());
399 }
400
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000401#ifndef V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000402 ASSERT(output.length() >=
403 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
404 do {
405 bool is_ascii = subject->IsAsciiRepresentation();
406 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii));
407 NativeRegExpMacroAssembler::Result res =
408 NativeRegExpMacroAssembler::Match(code,
409 subject,
410 output.start(),
411 output.length(),
412 index);
413 if (res != NativeRegExpMacroAssembler::RETRY) {
414 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
415 Top::has_pending_exception());
416 STATIC_ASSERT(
417 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
418 STATIC_ASSERT(
419 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
420 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
421 == RE_EXCEPTION);
422 return static_cast<IrregexpResult>(res);
423 }
424 // If result is RETRY, the string has changed representation, and we
425 // must restart from scratch.
426 // In this case, it means we must make sure we are prepared to handle
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000427 // the, potentially, different subject (the string can switch between
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000428 // being internal and external, and even between being ASCII and UC16,
429 // but the characters are always the same).
430 IrregexpPrepare(regexp, subject);
431 } while (true);
432 UNREACHABLE();
433 return RE_EXCEPTION;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000434#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000435
436 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
437 bool is_ascii = subject->IsAsciiRepresentation();
438 // We must have done EnsureCompiledIrregexp, so we can get the number of
439 // registers.
440 int* register_vector = output.start();
441 int number_of_capture_registers =
442 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
443 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
444 register_vector[i] = -1;
445 }
446 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii));
447
448 if (IrregexpInterpreter::Match(byte_codes,
449 subject,
450 register_vector,
451 index)) {
452 return RE_SUCCESS;
453 }
454 return RE_FAILURE;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000455#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000456}
457
458
ager@chromium.org41826e72009-03-30 13:30:57 +0000459Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000460 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000461 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000462 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000463 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000464
ager@chromium.org8bb60582008-12-11 12:02:20 +0000465 // Prepare space for the return values.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000466#ifdef V8_INTERPRETED_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000467#ifdef DEBUG
468 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000469 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000470 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
471 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
472 }
473#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000474#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000475 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
476 if (required_registers < 0) {
477 // Compiling failed with an exception.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000478 ASSERT(Top::has_pending_exception());
479 return Handle<Object>::null();
480 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000481
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000482 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000483
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000484 IrregexpResult res = RegExpImpl::IrregexpExecOnce(
erik.corry@gmail.com145eff52010-08-23 11:36:18 +0000485 jsregexp, subject, previous_index, Vector<int32_t>(registers.vector(),
486 registers.length()));
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000487 if (res == RE_SUCCESS) {
488 int capture_register_count =
489 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
490 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
491 AssertNoAllocation no_gc;
492 int* register_vector = registers.vector();
493 FixedArray* array = FixedArray::cast(last_match_info->elements());
494 for (int i = 0; i < capture_register_count; i += 2) {
495 SetCapture(array, i, register_vector[i]);
496 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000497 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000498 SetLastCaptureCount(array, capture_register_count);
499 SetLastSubject(array, *subject);
500 SetLastInput(array, *subject);
501 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000502 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000503 if (res == RE_EXCEPTION) {
504 ASSERT(Top::has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000505 return Handle<Object>::null();
506 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000507 ASSERT(res == RE_FAILURE);
508 return Factory::null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000509}
510
511
512// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000513// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000514//
515// The Irregexp regular expression engine is intended to be a complete
516// implementation of ECMAScript regular expressions. It generates either
517// bytecodes or native code.
518
519// The Irregexp regexp engine is structured in three steps.
520// 1) The parser generates an abstract syntax tree. See ast.cc.
521// 2) From the AST a node network is created. The nodes are all
522// subclasses of RegExpNode. The nodes represent states when
523// executing a regular expression. Several optimizations are
524// performed on the node network.
525// 3) From the nodes we generate either byte codes or native code
526// that can actually execute the regular expression (perform
527// the search). The code generation step is described in more
528// detail below.
529
530// Code generation.
531//
532// The nodes are divided into four main categories.
533// * Choice nodes
534// These represent places where the regular expression can
535// match in more than one way. For example on entry to an
536// alternation (foo|bar) or a repetition (*, +, ? or {}).
537// * Action nodes
538// These represent places where some action should be
539// performed. Examples include recording the current position
540// in the input string to a register (in order to implement
541// captures) or other actions on register for example in order
542// to implement the counters needed for {} repetitions.
543// * Matching nodes
544// These attempt to match some element part of the input string.
545// Examples of elements include character classes, plain strings
546// or back references.
547// * End nodes
548// These are used to implement the actions required on finding
549// a successful match or failing to find a match.
550//
551// The code generated (whether as byte codes or native code) maintains
552// some state as it runs. This consists of the following elements:
553//
554// * The capture registers. Used for string captures.
555// * Other registers. Used for counters etc.
556// * The current position.
557// * The stack of backtracking information. Used when a matching node
558// fails to find a match and needs to try an alternative.
559//
560// Conceptual regular expression execution model:
561//
562// There is a simple conceptual model of regular expression execution
563// which will be presented first. The actual code generated is a more
564// efficient simulation of the simple conceptual model:
565//
566// * Choice nodes are implemented as follows:
567// For each choice except the last {
568// push current position
569// push backtrack code location
570// <generate code to test for choice>
571// backtrack code location:
572// pop current position
573// }
574// <generate code to test for last choice>
575//
576// * Actions nodes are generated as follows
577// <push affected registers on backtrack stack>
578// <generate code to perform action>
579// push backtrack code location
580// <generate code to test for following nodes>
581// backtrack code location:
582// <pop affected registers to restore their state>
583// <pop backtrack location from stack and go to it>
584//
585// * Matching nodes are generated as follows:
586// if input string matches at current position
587// update current position
588// <generate code to test for following nodes>
589// else
590// <pop backtrack location from stack and go to it>
591//
592// Thus it can be seen that the current position is saved and restored
593// by the choice nodes, whereas the registers are saved and restored by
594// by the action nodes that manipulate them.
595//
596// The other interesting aspect of this model is that nodes are generated
597// at the point where they are needed by a recursive call to Emit(). If
598// the node has already been code generated then the Emit() call will
599// generate a jump to the previously generated code instead. In order to
600// limit recursion it is possible for the Emit() function to put the node
601// on a work list for later generation and instead generate a jump. The
602// destination of the jump is resolved later when the code is generated.
603//
604// Actual regular expression code generation.
605//
606// Code generation is actually more complicated than the above. In order
607// to improve the efficiency of the generated code some optimizations are
608// performed
609//
610// * Choice nodes have 1-character lookahead.
611// A choice node looks at the following character and eliminates some of
612// the choices immediately based on that character. This is not yet
613// implemented.
614// * Simple greedy loops store reduced backtracking information.
615// A quantifier like /.*foo/m will greedily match the whole input. It will
616// then need to backtrack to a point where it can match "foo". The naive
617// implementation of this would push each character position onto the
618// backtracking stack, then pop them off one by one. This would use space
619// proportional to the length of the input string. However since the "."
620// can only match in one way and always has a constant length (in this case
621// of 1) it suffices to store the current position on the top of the stack
622// once. Matching now becomes merely incrementing the current position and
623// backtracking becomes decrementing the current position and checking the
624// result against the stored current position. This is faster and saves
625// space.
626// * The current state is virtualized.
627// This is used to defer expensive operations until it is clear that they
628// are needed and to generate code for a node more than once, allowing
629// specialized an efficient versions of the code to be created. This is
630// explained in the section below.
631//
632// Execution state virtualization.
633//
634// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000635// manipulation in an object called the Trace. The Trace object can record a
636// current position offset, an optional backtrack code location on the top of
637// the virtualized backtrack stack and some register changes. When a node is
638// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000639// will emit code to bring the actual state into line with the virtual state.
640// Avoiding flushing the state can postpone some work (eg updates of capture
641// registers). Postponing work can save time when executing the regular
642// expression since it may be found that the work never has to be done as a
643// failure to match can occur. In addition it is much faster to jump to a
644// known backtrack code location than it is to pop an unknown backtrack
645// location from the stack and jump there.
646//
ager@chromium.org32912102009-01-16 10:38:43 +0000647// The virtual state found in the Trace affects code generation. For example
648// the virtual state contains the difference between the actual current
649// position and the virtual current position, and matching code needs to use
650// this offset to attempt a match in the correct location of the input
651// string. Therefore code generated for a non-trivial trace is specialized
652// to that trace. The code generator therefore has the ability to generate
653// code for each node several times. In order to limit the size of the
654// generated code there is an arbitrary limit on how many specialized sets of
655// code may be generated for a given node. If the limit is reached, the
656// trace is flushed and a generic version of the code for a node is emitted.
657// This is subsequently used for that node. The code emitted for non-generic
658// trace is not recorded in the node and so it cannot currently be reused in
659// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000660
661
662void RegExpTree::AppendToText(RegExpText* text) {
663 UNREACHABLE();
664}
665
666
667void RegExpAtom::AppendToText(RegExpText* text) {
668 text->AddElement(TextElement::Atom(this));
669}
670
671
672void RegExpCharacterClass::AppendToText(RegExpText* text) {
673 text->AddElement(TextElement::CharClass(this));
674}
675
676
677void RegExpText::AppendToText(RegExpText* text) {
678 for (int i = 0; i < elements()->length(); i++)
679 text->AddElement(elements()->at(i));
680}
681
682
683TextElement TextElement::Atom(RegExpAtom* atom) {
684 TextElement result = TextElement(ATOM);
685 result.data.u_atom = atom;
686 return result;
687}
688
689
690TextElement TextElement::CharClass(
691 RegExpCharacterClass* char_class) {
692 TextElement result = TextElement(CHAR_CLASS);
693 result.data.u_char_class = char_class;
694 return result;
695}
696
697
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000698int TextElement::length() {
699 if (type == ATOM) {
700 return data.u_atom->length();
701 } else {
702 ASSERT(type == CHAR_CLASS);
703 return 1;
704 }
705}
706
707
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000708DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
709 if (table_ == NULL) {
710 table_ = new DispatchTable();
711 DispatchTableConstructor cons(table_, ignore_case);
712 cons.BuildTable(this);
713 }
714 return table_;
715}
716
717
718class RegExpCompiler {
719 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000720 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000721
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000722 int AllocateRegister() {
723 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
724 reg_exp_too_big_ = true;
725 return next_register_;
726 }
727 return next_register_++;
728 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000729
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000730 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
731 RegExpNode* start,
732 int capture_count,
733 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000734
735 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
736
737 static const int kImplementationOffset = 0;
738 static const int kNumberOfRegistersOffset = 0;
739 static const int kCodeOffset = 1;
740
741 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
742 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000743
744 static const int kMaxRecursion = 100;
745 inline int recursion_depth() { return recursion_depth_; }
746 inline void IncrementRecursionDepth() { recursion_depth_++; }
747 inline void DecrementRecursionDepth() { recursion_depth_--; }
748
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000749 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
750
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000751 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000752 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000753
ager@chromium.org32912102009-01-16 10:38:43 +0000754 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000755 private:
756 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000757 int next_register_;
758 List<RegExpNode*>* work_list_;
759 int recursion_depth_;
760 RegExpMacroAssembler* macro_assembler_;
761 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000762 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000763 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000764};
765
766
767class RecursionCheck {
768 public:
769 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
770 compiler->IncrementRecursionDepth();
771 }
772 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
773 private:
774 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000775};
776
777
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000778static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
779 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000780}
781
782
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000783// Attempts to compile the regexp using an Irregexp code generator. Returns
784// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000785RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000786 : next_register_(2 * (capture_count + 1)),
787 work_list_(NULL),
788 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000789 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000790 ascii_(ascii),
791 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000792 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000793 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000794}
795
796
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000797RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000798 RegExpMacroAssembler* macro_assembler,
799 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000800 int capture_count,
801 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000802#ifdef DEBUG
803 if (FLAG_trace_regexp_assembler)
804 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
805 else
806#endif
807 macro_assembler_ = macro_assembler;
808 List <RegExpNode*> work_list(0);
809 work_list_ = &work_list;
810 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000811 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000812 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000813 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000814 macro_assembler_->Bind(&fail);
815 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000816 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000817 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000818 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000819 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
820
ager@chromium.org8bb60582008-12-11 12:02:20 +0000821 Handle<Object> code = macro_assembler_->GetCode(pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000822
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000823 work_list_ = NULL;
824#ifdef DEBUG
825 if (FLAG_trace_regexp_assembler) {
826 delete macro_assembler_;
827 }
828#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000829 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000830}
831
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000832
ager@chromium.org32912102009-01-16 10:38:43 +0000833bool Trace::DeferredAction::Mentions(int that) {
834 if (type() == ActionNode::CLEAR_CAPTURES) {
835 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
836 return range.Contains(that);
837 } else {
838 return reg() == that;
839 }
840}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000841
ager@chromium.org32912102009-01-16 10:38:43 +0000842
843bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000844 for (DeferredAction* action = actions_;
845 action != NULL;
846 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000847 if (action->Mentions(reg))
848 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000849 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000850 return false;
851}
852
853
ager@chromium.org32912102009-01-16 10:38:43 +0000854bool Trace::GetStoredPosition(int reg, int* cp_offset) {
855 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000856 for (DeferredAction* action = actions_;
857 action != NULL;
858 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000859 if (action->Mentions(reg)) {
860 if (action->type() == ActionNode::STORE_POSITION) {
861 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
862 return true;
863 } else {
864 return false;
865 }
866 }
867 }
868 return false;
869}
870
871
872int Trace::FindAffectedRegisters(OutSet* affected_registers) {
873 int max_register = RegExpCompiler::kNoRegister;
874 for (DeferredAction* action = actions_;
875 action != NULL;
876 action = action->next()) {
877 if (action->type() == ActionNode::CLEAR_CAPTURES) {
878 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
879 for (int i = range.from(); i <= range.to(); i++)
880 affected_registers->Set(i);
881 if (range.to() > max_register) max_register = range.to();
882 } else {
883 affected_registers->Set(action->reg());
884 if (action->reg() > max_register) max_register = action->reg();
885 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000886 }
887 return max_register;
888}
889
890
ager@chromium.org32912102009-01-16 10:38:43 +0000891void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
892 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000893 OutSet& registers_to_pop,
894 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000895 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000896 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
897 else if (registers_to_clear.Get(reg)) {
898 int clear_to = reg;
899 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
900 reg--;
901 }
902 assembler->ClearRegisters(reg, clear_to);
903 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000904 }
905}
906
907
ager@chromium.org32912102009-01-16 10:38:43 +0000908void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
909 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000910 OutSet& affected_registers,
911 OutSet* registers_to_pop,
912 OutSet* registers_to_clear) {
913 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
914 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
915
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000916 // Count pushes performed to force a stack limit check occasionally.
917 int pushes = 0;
918
ager@chromium.org8bb60582008-12-11 12:02:20 +0000919 for (int reg = 0; reg <= max_register; reg++) {
920 if (!affected_registers.Get(reg)) {
921 continue;
922 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000923
924 // The chronologically first deferred action in the trace
925 // is used to infer the action needed to restore a register
926 // to its previous state (or not, if it's safe to ignore it).
927 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
928 DeferredActionUndoType undo_action = IGNORE;
929
ager@chromium.org8bb60582008-12-11 12:02:20 +0000930 int value = 0;
931 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000932 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000933 int store_position = -1;
934 // This is a little tricky because we are scanning the actions in reverse
935 // historical order (newest first).
936 for (DeferredAction* action = actions_;
937 action != NULL;
938 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000939 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000940 switch (action->type()) {
941 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +0000942 Trace::DeferredSetRegister* psr =
943 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000944 if (!absolute) {
945 value += psr->value();
946 absolute = true;
947 }
948 // SET_REGISTER is currently only used for newly introduced loop
949 // counters. They can have a significant previous value if they
950 // occour in a loop. TODO(lrn): Propagate this information, so
951 // we can set undo_action to IGNORE if we know there is no value to
952 // restore.
953 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000954 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000955 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000956 break;
957 }
958 case ActionNode::INCREMENT_REGISTER:
959 if (!absolute) {
960 value++;
961 }
962 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000963 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000964 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000965 break;
966 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +0000967 Trace::DeferredCapture* pc =
968 static_cast<Trace::DeferredCapture*>(action);
969 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000970 store_position = pc->cp_offset();
971 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000972
973 // For captures we know that stores and clears alternate.
974 // Other register, are never cleared, and if the occur
975 // inside a loop, they might be assigned more than once.
976 if (reg <= 1) {
977 // Registers zero and one, aka "capture zero", is
978 // always set correctly if we succeed. There is no
979 // need to undo a setting on backtrack, because we
980 // will set it again or fail.
981 undo_action = IGNORE;
982 } else {
983 undo_action = pc->is_capture() ? CLEAR : RESTORE;
984 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000985 ASSERT(!absolute);
986 ASSERT_EQ(value, 0);
987 break;
988 }
ager@chromium.org32912102009-01-16 10:38:43 +0000989 case ActionNode::CLEAR_CAPTURES: {
990 // Since we're scanning in reverse order, if we've already
991 // set the position we have to ignore historically earlier
992 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000993 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +0000994 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000995 }
996 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +0000997 ASSERT(!absolute);
998 ASSERT_EQ(value, 0);
999 break;
1000 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001001 default:
1002 UNREACHABLE();
1003 break;
1004 }
1005 }
1006 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001007 // Prepare for the undo-action (e.g., push if it's going to be popped).
1008 if (undo_action == RESTORE) {
1009 pushes++;
1010 RegExpMacroAssembler::StackCheckFlag stack_check =
1011 RegExpMacroAssembler::kNoStackLimitCheck;
1012 if (pushes == push_limit) {
1013 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1014 pushes = 0;
1015 }
1016
1017 assembler->PushRegister(reg, stack_check);
1018 registers_to_pop->Set(reg);
1019 } else if (undo_action == CLEAR) {
1020 registers_to_clear->Set(reg);
1021 }
1022 // Perform the chronologically last action (or accumulated increment)
1023 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001024 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001025 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001026 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001027 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001028 } else if (absolute) {
1029 assembler->SetRegister(reg, value);
1030 } else if (value != 0) {
1031 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001032 }
1033 }
1034}
1035
1036
ager@chromium.org8bb60582008-12-11 12:02:20 +00001037// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001038// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001039// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001040void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001041 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001042
iposva@chromium.org245aa852009-02-10 00:49:54 +00001043 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001044
1045 if (actions_ == NULL && backtrack() == NULL) {
1046 // 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 +00001047 // a normal situation. We may also have to forget some information gained
1048 // through a quick check that was already performed.
1049 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001050 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001051 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001052 successor->Emit(compiler, &new_state);
1053 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001054 }
1055
1056 // Generate deferred actions here along with code to undo them again.
1057 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001058
ager@chromium.org381abbb2009-02-25 13:23:22 +00001059 if (backtrack() != NULL) {
1060 // Here we have a concrete backtrack location. These are set up by choice
1061 // nodes and so they indicate that we have a deferred save of the current
1062 // position which we may need to emit here.
1063 assembler->PushCurrentPosition();
1064 }
1065
ager@chromium.org8bb60582008-12-11 12:02:20 +00001066 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001067 OutSet registers_to_pop;
1068 OutSet registers_to_clear;
1069 PerformDeferredActions(assembler,
1070 max_register,
1071 affected_registers,
1072 &registers_to_pop,
1073 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001074 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001075 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001076 }
1077
1078 // Create a new trivial state and generate the node with that.
1079 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001080 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001081 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001082 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001083
1084 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001085 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001086 RestoreAffectedRegisters(assembler,
1087 max_register,
1088 registers_to_pop,
1089 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001090 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001091 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001092 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001093 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001094 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001095 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001096}
1097
1098
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001099void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001100 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001101
1102 // Omit flushing the trace. We discard the entire stack frame anyway.
1103
ager@chromium.org8bb60582008-12-11 12:02:20 +00001104 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001105 // We are completely independent of the trace, since we ignore it,
1106 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001107 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001108 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001109
1110 // Throw away everything on the backtrack stack since the start
1111 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001112 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1113 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001114 if (clear_capture_count_ > 0) {
1115 // Clear any captures that might have been performed during the success
1116 // of the body of the negative look-ahead.
1117 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1118 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1119 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001120 // Now that we have unwound the stack we find at the top of the stack the
1121 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001122 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001123}
1124
1125
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001126void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001127 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001128 trace->Flush(compiler, this);
1129 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001130 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001131 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001132 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001133 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001134 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001135 switch (action_) {
1136 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001137 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001138 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001139 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001140 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001141 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001142 case NEGATIVE_SUBMATCH_SUCCESS:
1143 // This case is handled in a different virtual method.
1144 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001145 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001146 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001147}
1148
1149
1150void GuardedAlternative::AddGuard(Guard* guard) {
1151 if (guards_ == NULL)
1152 guards_ = new ZoneList<Guard*>(1);
1153 guards_->Add(guard);
1154}
1155
1156
ager@chromium.org8bb60582008-12-11 12:02:20 +00001157ActionNode* ActionNode::SetRegister(int reg,
1158 int val,
1159 RegExpNode* on_success) {
1160 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001161 result->data_.u_store_register.reg = reg;
1162 result->data_.u_store_register.value = val;
1163 return result;
1164}
1165
1166
1167ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1168 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1169 result->data_.u_increment_register.reg = reg;
1170 return result;
1171}
1172
1173
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001174ActionNode* ActionNode::StorePosition(int reg,
1175 bool is_capture,
1176 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001177 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1178 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001179 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001180 return result;
1181}
1182
1183
ager@chromium.org32912102009-01-16 10:38:43 +00001184ActionNode* ActionNode::ClearCaptures(Interval range,
1185 RegExpNode* on_success) {
1186 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1187 result->data_.u_clear_captures.range_from = range.from();
1188 result->data_.u_clear_captures.range_to = range.to();
1189 return result;
1190}
1191
1192
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001193ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1194 int position_reg,
1195 RegExpNode* on_success) {
1196 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1197 result->data_.u_submatch.stack_pointer_register = stack_reg;
1198 result->data_.u_submatch.current_position_register = position_reg;
1199 return result;
1200}
1201
1202
ager@chromium.org8bb60582008-12-11 12:02:20 +00001203ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1204 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001205 int clear_register_count,
1206 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001207 RegExpNode* on_success) {
1208 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001209 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001210 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001211 result->data_.u_submatch.clear_register_count = clear_register_count;
1212 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001213 return result;
1214}
1215
1216
ager@chromium.org32912102009-01-16 10:38:43 +00001217ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1218 int repetition_register,
1219 int repetition_limit,
1220 RegExpNode* on_success) {
1221 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1222 result->data_.u_empty_match_check.start_register = start_register;
1223 result->data_.u_empty_match_check.repetition_register = repetition_register;
1224 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1225 return result;
1226}
1227
1228
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001229#define DEFINE_ACCEPT(Type) \
1230 void Type##Node::Accept(NodeVisitor* visitor) { \
1231 visitor->Visit##Type(this); \
1232 }
1233FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1234#undef DEFINE_ACCEPT
1235
1236
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001237void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1238 visitor->VisitLoopChoice(this);
1239}
1240
1241
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001242// -------------------------------------------------------------------
1243// Emit code.
1244
1245
1246void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1247 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001248 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001249 switch (guard->op()) {
1250 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001251 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001252 macro_assembler->IfRegisterGE(guard->reg(),
1253 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001254 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001255 break;
1256 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001257 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001258 macro_assembler->IfRegisterLT(guard->reg(),
1259 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001260 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001261 break;
1262 }
1263}
1264
1265
1266static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1267static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1268
1269
ager@chromium.org381abbb2009-02-25 13:23:22 +00001270// Returns the number of characters in the equivalence class, omitting those
1271// that cannot occur in the source string because it is ASCII.
1272static int GetCaseIndependentLetters(uc16 character,
1273 bool ascii_subject,
1274 unibrow::uchar* letters) {
1275 int length = uncanonicalize.get(character, '\0', letters);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00001276 // Unibrow returns 0 or 1 for characters where case independence is
ager@chromium.org381abbb2009-02-25 13:23:22 +00001277 // trivial.
1278 if (length == 0) {
1279 letters[0] = character;
1280 length = 1;
1281 }
1282 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1283 return length;
1284 }
1285 // The standard requires that non-ASCII characters cannot have ASCII
1286 // character codes in their equivalence class.
1287 return 0;
1288}
1289
1290
1291static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1292 uc16 c,
1293 Label* on_failure,
1294 int cp_offset,
1295 bool check,
1296 bool preloaded) {
1297 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1298 bool bound_checked = false;
1299 if (!preloaded) {
1300 assembler->LoadCurrentCharacter(
1301 cp_offset,
1302 on_failure,
1303 check);
1304 bound_checked = true;
1305 }
1306 assembler->CheckNotCharacter(c, on_failure);
1307 return bound_checked;
1308}
1309
1310
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001311// Only emits non-letters (things that don't have case). Only used for case
1312// independent matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001313static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1314 uc16 c,
1315 Label* on_failure,
1316 int cp_offset,
1317 bool check,
1318 bool preloaded) {
1319 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1320 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001321 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001322 int length = GetCaseIndependentLetters(c, ascii, chars);
1323 if (length < 1) {
1324 // This can't match. Must be an ASCII subject and a non-ASCII character.
1325 // We do not need to do anything since the ASCII pass already handled this.
1326 return false; // Bounds not checked.
1327 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001328 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001329 // We handle the length > 1 case in a later pass.
1330 if (length == 1) {
1331 if (ascii && c > String::kMaxAsciiCharCodeU) {
1332 // Can't match - see above.
1333 return false; // Bounds not checked.
1334 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001335 if (!preloaded) {
1336 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1337 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001338 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001339 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001340 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001341 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001342}
1343
1344
1345static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001346 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001347 uc16 c1,
1348 uc16 c2,
1349 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001350 uc16 char_mask;
1351 if (ascii) {
1352 char_mask = String::kMaxAsciiCharCode;
1353 } else {
1354 char_mask = String::kMaxUC16CharCode;
1355 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001356 uc16 exor = c1 ^ c2;
1357 // Check whether exor has only one bit set.
1358 if (((exor - 1) & exor) == 0) {
1359 // If c1 and c2 differ only by one bit.
1360 // Ecma262UnCanonicalize always gives the highest number last.
1361 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001362 uc16 mask = char_mask ^ exor;
1363 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001364 return true;
1365 }
1366 ASSERT(c2 > c1);
1367 uc16 diff = c2 - c1;
1368 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1369 // If the characters differ by 2^n but don't differ by one bit then
1370 // subtract the difference from the found character, then do the or
1371 // trick. We avoid the theoretical case where negative numbers are
1372 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001373 uc16 mask = char_mask ^ diff;
1374 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1375 diff,
1376 mask,
1377 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001378 return true;
1379 }
1380 return false;
1381}
1382
1383
ager@chromium.org381abbb2009-02-25 13:23:22 +00001384typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1385 uc16 c,
1386 Label* on_failure,
1387 int cp_offset,
1388 bool check,
1389 bool preloaded);
1390
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001391// Only emits letters (things that have case). Only used for case independent
1392// matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001393static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1394 uc16 c,
1395 Label* on_failure,
1396 int cp_offset,
1397 bool check,
1398 bool preloaded) {
1399 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1400 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001401 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001402 int length = GetCaseIndependentLetters(c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001403 if (length <= 1) return false;
1404 // We may not need to check against the end of the input string
1405 // if this character lies before a character that matched.
1406 if (!preloaded) {
1407 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001408 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001409 Label ok;
1410 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1411 switch (length) {
1412 case 2: {
1413 if (ShortCutEmitCharacterPair(macro_assembler,
1414 ascii,
1415 chars[0],
1416 chars[1],
1417 on_failure)) {
1418 } else {
1419 macro_assembler->CheckCharacter(chars[0], &ok);
1420 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1421 macro_assembler->Bind(&ok);
1422 }
1423 break;
1424 }
1425 case 4:
1426 macro_assembler->CheckCharacter(chars[3], &ok);
1427 // Fall through!
1428 case 3:
1429 macro_assembler->CheckCharacter(chars[0], &ok);
1430 macro_assembler->CheckCharacter(chars[1], &ok);
1431 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1432 macro_assembler->Bind(&ok);
1433 break;
1434 default:
1435 UNREACHABLE();
1436 break;
1437 }
1438 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001439}
1440
1441
1442static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1443 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001444 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001445 Label* on_failure,
1446 int cp_offset,
1447 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001448 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001449 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001450 int max_char;
1451 if (ascii) {
1452 max_char = String::kMaxAsciiCharCode;
1453 } else {
1454 max_char = String::kMaxUC16CharCode;
1455 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001456
1457 Label success;
1458
1459 Label* char_is_in_class =
1460 cc->is_negated() ? on_failure : &success;
1461
1462 int range_count = ranges->length();
1463
ager@chromium.org8bb60582008-12-11 12:02:20 +00001464 int last_valid_range = range_count - 1;
1465 while (last_valid_range >= 0) {
1466 CharacterRange& range = ranges->at(last_valid_range);
1467 if (range.from() <= max_char) {
1468 break;
1469 }
1470 last_valid_range--;
1471 }
1472
1473 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001474 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001475 // TODO(plesner): We can remove this when the node level does our
1476 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001477 macro_assembler->GoTo(on_failure);
1478 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001479 if (check_offset) {
1480 macro_assembler->CheckPosition(cp_offset, on_failure);
1481 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001482 return;
1483 }
1484
ager@chromium.org8bb60582008-12-11 12:02:20 +00001485 if (last_valid_range == 0 &&
1486 !cc->is_negated() &&
1487 ranges->at(0).IsEverything(max_char)) {
1488 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001489 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001490 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001491 }
1492 return;
1493 }
1494
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001495 if (!preloaded) {
1496 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001497 }
1498
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001499 if (cc->is_standard() &&
1500 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1501 on_failure)) {
1502 return;
1503 }
1504
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001505 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001506 CharacterRange& range = ranges->at(i);
1507 Label next_range;
1508 uc16 from = range.from();
1509 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001510 if (from > max_char) {
1511 continue;
1512 }
1513 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001514 if (to == from) {
1515 macro_assembler->CheckCharacter(to, char_is_in_class);
1516 } else {
1517 if (from != 0) {
1518 macro_assembler->CheckCharacterLT(from, &next_range);
1519 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001520 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001521 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1522 } else {
1523 macro_assembler->GoTo(char_is_in_class);
1524 }
1525 }
1526 macro_assembler->Bind(&next_range);
1527 }
1528
ager@chromium.org8bb60582008-12-11 12:02:20 +00001529 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001530 uc16 from = range.from();
1531 uc16 to = range.to();
1532
ager@chromium.org8bb60582008-12-11 12:02:20 +00001533 if (to > max_char) to = max_char;
1534 ASSERT(to >= from);
1535
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001536 if (to == from) {
1537 if (cc->is_negated()) {
1538 macro_assembler->CheckCharacter(to, on_failure);
1539 } else {
1540 macro_assembler->CheckNotCharacter(to, on_failure);
1541 }
1542 } else {
1543 if (from != 0) {
1544 if (cc->is_negated()) {
1545 macro_assembler->CheckCharacterLT(from, &success);
1546 } else {
1547 macro_assembler->CheckCharacterLT(from, on_failure);
1548 }
1549 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001550 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001551 if (cc->is_negated()) {
1552 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1553 } else {
1554 macro_assembler->CheckCharacterGT(to, on_failure);
1555 }
1556 } else {
1557 if (cc->is_negated()) {
1558 macro_assembler->GoTo(on_failure);
1559 }
1560 }
1561 }
1562 macro_assembler->Bind(&success);
1563}
1564
1565
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001566RegExpNode::~RegExpNode() {
1567}
1568
1569
ager@chromium.org8bb60582008-12-11 12:02:20 +00001570RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001571 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001572 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001573 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001574 return CONTINUE;
1575 }
1576
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001577 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001578 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001579 if (label_.is_bound()) {
1580 // We are being asked to generate a generic version, but that's already
1581 // been done so just go to it.
1582 macro_assembler->GoTo(&label_);
1583 return DONE;
1584 }
1585 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1586 // To avoid too deep recursion we push the node to the work queue and just
1587 // generate a goto here.
1588 compiler->AddWork(this);
1589 macro_assembler->GoTo(&label_);
1590 return DONE;
1591 }
1592 // Generate generic version of the node and bind the label for later use.
1593 macro_assembler->Bind(&label_);
1594 return CONTINUE;
1595 }
1596
1597 // We are being asked to make a non-generic version. Keep track of how many
1598 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001599 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001600 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001601 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001602 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1603 return CONTINUE;
1604 }
1605
ager@chromium.org32912102009-01-16 10:38:43 +00001606 // If we get here code has been generated for this node too many times or
1607 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001608 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001609 trace->Flush(compiler, this);
1610 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001611}
1612
1613
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001614int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001615 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1616 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001617 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001618}
1619
1620
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001621int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1622 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1623 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1624}
1625
1626
1627int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1628 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1629 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1630}
1631
1632
1633int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001634 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001635 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001636 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001637 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1638 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001639}
1640
1641
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001642int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
1643 int recursion_depth) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001644 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1645 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1646 // afterwards.
1647 RegExpNode* node = alternatives_->at(1).node();
1648 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1649}
1650
1651
1652void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1653 QuickCheckDetails* details,
1654 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001655 int filled_in,
1656 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001657 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1658 // afterwards.
1659 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001660 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001661}
1662
1663
1664int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1665 int recursion_depth,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001666 RegExpNode* ignore_this_node) {
1667 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1668 int min = 100;
1669 int choice_count = alternatives_->length();
1670 for (int i = 0; i < choice_count; i++) {
1671 RegExpNode* node = alternatives_->at(i).node();
1672 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001673 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1674 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001675 if (node_eats_at_least < min) min = node_eats_at_least;
1676 }
1677 return min;
1678}
1679
1680
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001681int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1682 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001683}
1684
1685
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001686int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1687 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001688}
1689
1690
1691// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1692static inline uint32_t SmearBitsRight(uint32_t v) {
1693 v |= v >> 1;
1694 v |= v >> 2;
1695 v |= v >> 4;
1696 v |= v >> 8;
1697 v |= v >> 16;
1698 return v;
1699}
1700
1701
1702bool QuickCheckDetails::Rationalize(bool asc) {
1703 bool found_useful_op = false;
1704 uint32_t char_mask;
1705 if (asc) {
1706 char_mask = String::kMaxAsciiCharCode;
1707 } else {
1708 char_mask = String::kMaxUC16CharCode;
1709 }
1710 mask_ = 0;
1711 value_ = 0;
1712 int char_shift = 0;
1713 for (int i = 0; i < characters_; i++) {
1714 Position* pos = &positions_[i];
1715 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1716 found_useful_op = true;
1717 }
1718 mask_ |= (pos->mask & char_mask) << char_shift;
1719 value_ |= (pos->value & char_mask) << char_shift;
1720 char_shift += asc ? 8 : 16;
1721 }
1722 return found_useful_op;
1723}
1724
1725
1726bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001727 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001728 bool preload_has_checked_bounds,
1729 Label* on_possible_success,
1730 QuickCheckDetails* details,
1731 bool fall_through_on_failure) {
1732 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001733 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1734 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001735 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001736 ASSERT(details->characters() == 1 ||
1737 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001738 uint32_t mask = details->mask();
1739 uint32_t value = details->value();
1740
1741 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1742
ager@chromium.org32912102009-01-16 10:38:43 +00001743 if (trace->characters_preloaded() != details->characters()) {
1744 assembler->LoadCurrentCharacter(trace->cp_offset(),
1745 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001746 !preload_has_checked_bounds,
1747 details->characters());
1748 }
1749
1750
1751 bool need_mask = true;
1752
1753 if (details->characters() == 1) {
1754 // If number of characters preloaded is 1 then we used a byte or 16 bit
1755 // load so the value is already masked down.
1756 uint32_t char_mask;
1757 if (compiler->ascii()) {
1758 char_mask = String::kMaxAsciiCharCode;
1759 } else {
1760 char_mask = String::kMaxUC16CharCode;
1761 }
1762 if ((mask & char_mask) == char_mask) need_mask = false;
1763 mask &= char_mask;
1764 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001765 // For 2-character preloads in ASCII mode or 1-character preloads in
1766 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001767 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001768 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1769 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001770 if ((mask & 0xffff) == 0xffff) need_mask = false;
1771 } else {
1772 if (mask == 0xffffffff) need_mask = false;
1773 }
1774 }
1775
1776 if (fall_through_on_failure) {
1777 if (need_mask) {
1778 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1779 } else {
1780 assembler->CheckCharacter(value, on_possible_success);
1781 }
1782 } else {
1783 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001784 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001785 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001786 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001787 }
1788 }
1789 return true;
1790}
1791
1792
1793// Here is the meat of GetQuickCheckDetails (see also the comment on the
1794// super-class in the .h file).
1795//
1796// We iterate along the text object, building up for each character a
1797// mask and value that can be used to test for a quick failure to match.
1798// The masks and values for the positions will be combined into a single
1799// machine word for the current character width in order to be used in
1800// generating a quick check.
1801void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1802 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001803 int characters_filled_in,
1804 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001805 ASSERT(characters_filled_in < details->characters());
1806 int characters = details->characters();
1807 int char_mask;
1808 int char_shift;
1809 if (compiler->ascii()) {
1810 char_mask = String::kMaxAsciiCharCode;
1811 char_shift = 8;
1812 } else {
1813 char_mask = String::kMaxUC16CharCode;
1814 char_shift = 16;
1815 }
1816 for (int k = 0; k < elms_->length(); k++) {
1817 TextElement elm = elms_->at(k);
1818 if (elm.type == TextElement::ATOM) {
1819 Vector<const uc16> quarks = elm.data.u_atom->data();
1820 for (int i = 0; i < characters && i < quarks.length(); i++) {
1821 QuickCheckDetails::Position* pos =
1822 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001823 uc16 c = quarks[i];
1824 if (c > char_mask) {
1825 // If we expect a non-ASCII character from an ASCII string,
1826 // there is no way we can match. Not even case independent
1827 // matching can turn an ASCII character into non-ASCII or
1828 // vice versa.
1829 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001830 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001831 return;
1832 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001833 if (compiler->ignore_case()) {
1834 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001835 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1836 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1837 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001838 // This letter has no case equivalents, so it's nice and simple
1839 // and the mask-compare will determine definitely whether we have
1840 // a match at this character position.
1841 pos->mask = char_mask;
1842 pos->value = c;
1843 pos->determines_perfectly = true;
1844 } else {
1845 uint32_t common_bits = char_mask;
1846 uint32_t bits = chars[0];
1847 for (int j = 1; j < length; j++) {
1848 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1849 common_bits ^= differing_bits;
1850 bits &= common_bits;
1851 }
1852 // If length is 2 and common bits has only one zero in it then
1853 // our mask and compare instruction will determine definitely
1854 // whether we have a match at this character position. Otherwise
1855 // it can only be an approximate check.
1856 uint32_t one_zero = (common_bits | ~char_mask);
1857 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1858 pos->determines_perfectly = true;
1859 }
1860 pos->mask = common_bits;
1861 pos->value = bits;
1862 }
1863 } else {
1864 // Don't ignore case. Nice simple case where the mask-compare will
1865 // determine definitely whether we have a match at this character
1866 // position.
1867 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001868 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001869 pos->determines_perfectly = true;
1870 }
1871 characters_filled_in++;
1872 ASSERT(characters_filled_in <= details->characters());
1873 if (characters_filled_in == details->characters()) {
1874 return;
1875 }
1876 }
1877 } else {
1878 QuickCheckDetails::Position* pos =
1879 details->positions(characters_filled_in);
1880 RegExpCharacterClass* tree = elm.data.u_char_class;
1881 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001882 if (tree->is_negated()) {
1883 // A quick check uses multi-character mask and compare. There is no
1884 // useful way to incorporate a negative char class into this scheme
1885 // so we just conservatively create a mask and value that will always
1886 // succeed.
1887 pos->mask = 0;
1888 pos->value = 0;
1889 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001890 int first_range = 0;
1891 while (ranges->at(first_range).from() > char_mask) {
1892 first_range++;
1893 if (first_range == ranges->length()) {
1894 details->set_cannot_match();
1895 pos->determines_perfectly = false;
1896 return;
1897 }
1898 }
1899 CharacterRange range = ranges->at(first_range);
1900 uc16 from = range.from();
1901 uc16 to = range.to();
1902 if (to > char_mask) {
1903 to = char_mask;
1904 }
1905 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001906 // A mask and compare is only perfect if the differing bits form a
1907 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001908 if ((differing_bits & (differing_bits + 1)) == 0 &&
1909 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001910 pos->determines_perfectly = true;
1911 }
1912 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001913 uint32_t bits = (from & common_bits);
1914 for (int i = first_range + 1; i < ranges->length(); i++) {
1915 CharacterRange range = ranges->at(i);
1916 uc16 from = range.from();
1917 uc16 to = range.to();
1918 if (from > char_mask) continue;
1919 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001920 // Here we are combining more ranges into the mask and compare
1921 // value. With each new range the mask becomes more sparse and
1922 // so the chances of a false positive rise. A character class
1923 // with multiple ranges is assumed never to be equivalent to a
1924 // mask and compare operation.
1925 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001926 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001927 new_common_bits = ~SmearBitsRight(new_common_bits);
1928 common_bits &= new_common_bits;
1929 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001930 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001931 common_bits ^= differing_bits;
1932 bits &= common_bits;
1933 }
1934 pos->mask = common_bits;
1935 pos->value = bits;
1936 }
1937 characters_filled_in++;
1938 ASSERT(characters_filled_in <= details->characters());
1939 if (characters_filled_in == details->characters()) {
1940 return;
1941 }
1942 }
1943 }
1944 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00001945 on_success()-> GetQuickCheckDetails(details,
1946 compiler,
1947 characters_filled_in,
1948 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001949}
1950
1951
1952void QuickCheckDetails::Clear() {
1953 for (int i = 0; i < characters_; i++) {
1954 positions_[i].mask = 0;
1955 positions_[i].value = 0;
1956 positions_[i].determines_perfectly = false;
1957 }
1958 characters_ = 0;
1959}
1960
1961
1962void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001963 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001964 if (by >= characters_) {
1965 Clear();
1966 return;
1967 }
1968 for (int i = 0; i < characters_ - by; i++) {
1969 positions_[i] = positions_[by + i];
1970 }
1971 for (int i = characters_ - by; i < characters_; i++) {
1972 positions_[i].mask = 0;
1973 positions_[i].value = 0;
1974 positions_[i].determines_perfectly = false;
1975 }
1976 characters_ -= by;
1977 // We could change mask_ and value_ here but we would never advance unless
1978 // they had already been used in a check and they won't be used again because
1979 // it would gain us nothing. So there's no point.
1980}
1981
1982
1983void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1984 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001985 if (other->cannot_match_) {
1986 return;
1987 }
1988 if (cannot_match_) {
1989 *this = *other;
1990 return;
1991 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001992 for (int i = from_index; i < characters_; i++) {
1993 QuickCheckDetails::Position* pos = positions(i);
1994 QuickCheckDetails::Position* other_pos = other->positions(i);
1995 if (pos->mask != other_pos->mask ||
1996 pos->value != other_pos->value ||
1997 !other_pos->determines_perfectly) {
1998 // Our mask-compare operation will be approximate unless we have the
1999 // exact same operation on both sides of the alternation.
2000 pos->determines_perfectly = false;
2001 }
2002 pos->mask &= other_pos->mask;
2003 pos->value &= pos->mask;
2004 other_pos->value &= pos->mask;
2005 uc16 differing_bits = (pos->value ^ other_pos->value);
2006 pos->mask &= ~differing_bits;
2007 pos->value &= pos->mask;
2008 }
2009}
2010
2011
ager@chromium.org32912102009-01-16 10:38:43 +00002012class VisitMarker {
2013 public:
2014 explicit VisitMarker(NodeInfo* info) : info_(info) {
2015 ASSERT(!info->visited);
2016 info->visited = true;
2017 }
2018 ~VisitMarker() {
2019 info_->visited = false;
2020 }
2021 private:
2022 NodeInfo* info_;
2023};
2024
2025
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002026void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2027 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002028 int characters_filled_in,
2029 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002030 if (body_can_be_zero_length_ || info()->visited) return;
2031 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002032 return ChoiceNode::GetQuickCheckDetails(details,
2033 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002034 characters_filled_in,
2035 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002036}
2037
2038
2039void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2040 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002041 int characters_filled_in,
2042 bool not_at_start) {
2043 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002044 int choice_count = alternatives_->length();
2045 ASSERT(choice_count > 0);
2046 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2047 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002048 characters_filled_in,
2049 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002050 for (int i = 1; i < choice_count; i++) {
2051 QuickCheckDetails new_details(details->characters());
2052 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002053 node->GetQuickCheckDetails(&new_details, compiler,
2054 characters_filled_in,
2055 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002056 // Here we merge the quick match details of the two branches.
2057 details->Merge(&new_details, characters_filled_in);
2058 }
2059}
2060
2061
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002062// Check for [0-9A-Z_a-z].
2063static void EmitWordCheck(RegExpMacroAssembler* assembler,
2064 Label* word,
2065 Label* non_word,
2066 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002067 if (assembler->CheckSpecialCharacterClass(
2068 fall_through_on_word ? 'w' : 'W',
2069 fall_through_on_word ? non_word : word)) {
2070 // Optimized implementation available.
2071 return;
2072 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002073 assembler->CheckCharacterGT('z', non_word);
2074 assembler->CheckCharacterLT('0', non_word);
2075 assembler->CheckCharacterGT('a' - 1, word);
2076 assembler->CheckCharacterLT('9' + 1, word);
2077 assembler->CheckCharacterLT('A', non_word);
2078 assembler->CheckCharacterLT('Z' + 1, word);
2079 if (fall_through_on_word) {
2080 assembler->CheckNotCharacter('_', non_word);
2081 } else {
2082 assembler->CheckCharacter('_', word);
2083 }
2084}
2085
2086
2087// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2088// that matches newline or the start of input).
2089static void EmitHat(RegExpCompiler* compiler,
2090 RegExpNode* on_success,
2091 Trace* trace) {
2092 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2093 // We will be loading the previous character into the current character
2094 // register.
2095 Trace new_trace(*trace);
2096 new_trace.InvalidateCurrentCharacter();
2097
2098 Label ok;
2099 if (new_trace.cp_offset() == 0) {
2100 // The start of input counts as a newline in this context, so skip to
2101 // ok if we are at the start.
2102 assembler->CheckAtStart(&ok);
2103 }
2104 // We already checked that we are not at the start of input so it must be
2105 // OK to load the previous character.
2106 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2107 new_trace.backtrack(),
2108 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002109 if (!assembler->CheckSpecialCharacterClass('n',
2110 new_trace.backtrack())) {
2111 // Newline means \n, \r, 0x2028 or 0x2029.
2112 if (!compiler->ascii()) {
2113 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2114 }
2115 assembler->CheckCharacter('\n', &ok);
2116 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002117 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002118 assembler->Bind(&ok);
2119 on_success->Emit(compiler, &new_trace);
2120}
2121
2122
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002123// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2124// when we know whether the next character must be a word character or not.
2125static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2126 RegExpCompiler* compiler,
2127 RegExpNode* on_success,
2128 Trace* trace) {
2129 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2130 Label done;
2131
2132 Trace new_trace(*trace);
2133
2134 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2135 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2136 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2137
2138 // Check whether previous character was a word character.
2139 switch (trace->at_start()) {
2140 case Trace::TRUE:
2141 if (expect_word_character) {
2142 assembler->GoTo(on_non_word);
2143 }
2144 break;
2145 case Trace::UNKNOWN:
2146 ASSERT_EQ(0, trace->cp_offset());
2147 assembler->CheckAtStart(on_non_word);
2148 // Fall through.
2149 case Trace::FALSE:
2150 int prev_char_offset = trace->cp_offset() - 1;
2151 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2152 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2153 // We may or may not have loaded the previous character.
2154 new_trace.InvalidateCurrentCharacter();
2155 }
2156
2157 assembler->Bind(&done);
2158
2159 on_success->Emit(compiler, &new_trace);
2160}
2161
2162
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002163// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2164static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2165 RegExpCompiler* compiler,
2166 RegExpNode* on_success,
2167 Trace* trace) {
2168 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2169 Label before_non_word;
2170 Label before_word;
2171 if (trace->characters_preloaded() != 1) {
2172 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2173 }
2174 // Fall through on non-word.
2175 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2176
2177 // We will be loading the previous character into the current character
2178 // register.
2179 Trace new_trace(*trace);
2180 new_trace.InvalidateCurrentCharacter();
2181
2182 Label ok;
2183 Label* boundary;
2184 Label* not_boundary;
2185 if (type == AssertionNode::AT_BOUNDARY) {
2186 boundary = &ok;
2187 not_boundary = new_trace.backtrack();
2188 } else {
2189 not_boundary = &ok;
2190 boundary = new_trace.backtrack();
2191 }
2192
2193 // Next character is not a word character.
2194 assembler->Bind(&before_non_word);
2195 if (new_trace.cp_offset() == 0) {
2196 // The start of input counts as a non-word character, so the question is
2197 // decided if we are at the start.
2198 assembler->CheckAtStart(not_boundary);
2199 }
2200 // We already checked that we are not at the start of input so it must be
2201 // OK to load the previous character.
2202 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2203 &ok, // Unused dummy label in this call.
2204 false);
2205 // Fall through on non-word.
2206 EmitWordCheck(assembler, boundary, not_boundary, false);
2207 assembler->GoTo(not_boundary);
2208
2209 // Next character is a word character.
2210 assembler->Bind(&before_word);
2211 if (new_trace.cp_offset() == 0) {
2212 // The start of input counts as a non-word character, so the question is
2213 // decided if we are at the start.
2214 assembler->CheckAtStart(boundary);
2215 }
2216 // We already checked that we are not at the start of input so it must be
2217 // OK to load the previous character.
2218 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2219 &ok, // Unused dummy label in this call.
2220 false);
2221 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2222 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2223
2224 assembler->Bind(&ok);
2225
2226 on_success->Emit(compiler, &new_trace);
2227}
2228
2229
iposva@chromium.org245aa852009-02-10 00:49:54 +00002230void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2231 RegExpCompiler* compiler,
2232 int filled_in,
2233 bool not_at_start) {
2234 if (type_ == AT_START && not_at_start) {
2235 details->set_cannot_match();
2236 return;
2237 }
2238 return on_success()->GetQuickCheckDetails(details,
2239 compiler,
2240 filled_in,
2241 not_at_start);
2242}
2243
2244
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002245void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2246 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2247 switch (type_) {
2248 case AT_END: {
2249 Label ok;
2250 assembler->CheckPosition(trace->cp_offset(), &ok);
2251 assembler->GoTo(trace->backtrack());
2252 assembler->Bind(&ok);
2253 break;
2254 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002255 case AT_START: {
2256 if (trace->at_start() == Trace::FALSE) {
2257 assembler->GoTo(trace->backtrack());
2258 return;
2259 }
2260 if (trace->at_start() == Trace::UNKNOWN) {
2261 assembler->CheckNotAtStart(trace->backtrack());
2262 Trace at_start_trace = *trace;
2263 at_start_trace.set_at_start(true);
2264 on_success()->Emit(compiler, &at_start_trace);
2265 return;
2266 }
2267 }
2268 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002269 case AFTER_NEWLINE:
2270 EmitHat(compiler, on_success(), trace);
2271 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002272 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002273 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002274 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2275 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002276 }
2277 case AFTER_WORD_CHARACTER:
2278 case AFTER_NONWORD_CHARACTER: {
2279 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2280 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002281 }
2282 on_success()->Emit(compiler, trace);
2283}
2284
2285
ager@chromium.org381abbb2009-02-25 13:23:22 +00002286static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2287 if (quick_check == NULL) return false;
2288 if (offset >= quick_check->characters()) return false;
2289 return quick_check->positions(offset)->determines_perfectly;
2290}
2291
2292
2293static void UpdateBoundsCheck(int index, int* checked_up_to) {
2294 if (index > *checked_up_to) {
2295 *checked_up_to = index;
2296 }
2297}
2298
2299
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002300// We call this repeatedly to generate code for each pass over the text node.
2301// The passes are in increasing order of difficulty because we hope one
2302// of the first passes will fail in which case we are saved the work of the
2303// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2304// we will check the '%' in the first pass, the case independent 'a' in the
2305// second pass and the character class in the last pass.
2306//
2307// The passes are done from right to left, so for example to test for /bar/
2308// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2309// and then a 'b' with offset 0. This means we can avoid the end-of-input
2310// bounds check most of the time. In the example we only need to check for
2311// end-of-input when loading the putative 'r'.
2312//
2313// A slight complication involves the fact that the first character may already
2314// be fetched into a register by the previous node. In this case we want to
2315// do the test for that character first. We do this in separate passes. The
2316// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2317// pass has been performed then subsequent passes will have true in
2318// first_element_checked to indicate that that character does not need to be
2319// checked again.
2320//
ager@chromium.org32912102009-01-16 10:38:43 +00002321// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002322// contain an AlternativeGeneration object. In this AlternativeGeneration
2323// object we can see details of any quick check that was already passed in
2324// order to get to the code we are now generating. The quick check can involve
2325// loading characters, which means we do not need to recheck the bounds
2326// up to the limit the quick check already checked. In addition the quick
2327// check can have involved a mask and compare operation which may simplify
2328// or obviate the need for further checks at some character positions.
2329void TextNode::TextEmitPass(RegExpCompiler* compiler,
2330 TextEmitPassType pass,
2331 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002332 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002333 bool first_element_checked,
2334 int* checked_up_to) {
2335 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2336 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002337 Label* backtrack = trace->backtrack();
2338 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002339 int element_count = elms_->length();
2340 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2341 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002342 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002343 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002344 Vector<const uc16> quarks = elm.data.u_atom->data();
2345 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2346 if (first_element_checked && i == 0 && j == 0) continue;
2347 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2348 EmitCharacterFunction* emit_function = NULL;
2349 switch (pass) {
2350 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002351 ASSERT(ascii);
2352 if (quarks[j] > String::kMaxAsciiCharCode) {
2353 assembler->GoTo(backtrack);
2354 return;
2355 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002356 break;
2357 case NON_LETTER_CHARACTER_MATCH:
2358 emit_function = &EmitAtomNonLetter;
2359 break;
2360 case SIMPLE_CHARACTER_MATCH:
2361 emit_function = &EmitSimpleCharacter;
2362 break;
2363 case CASE_CHARACTER_MATCH:
2364 emit_function = &EmitAtomLetter;
2365 break;
2366 default:
2367 break;
2368 }
2369 if (emit_function != NULL) {
2370 bool bound_checked = emit_function(compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002371 quarks[j],
2372 backtrack,
2373 cp_offset + j,
2374 *checked_up_to < cp_offset + j,
2375 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002376 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002377 }
2378 }
2379 } else {
2380 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002381 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002382 if (first_element_checked && i == 0) continue;
2383 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002384 RegExpCharacterClass* cc = elm.data.u_char_class;
2385 EmitCharClass(assembler,
2386 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002387 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002388 backtrack,
2389 cp_offset,
2390 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002391 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002392 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002393 }
2394 }
2395 }
2396}
2397
2398
2399int TextNode::Length() {
2400 TextElement elm = elms_->last();
2401 ASSERT(elm.cp_offset >= 0);
2402 if (elm.type == TextElement::ATOM) {
2403 return elm.cp_offset + elm.data.u_atom->data().length();
2404 } else {
2405 return elm.cp_offset + 1;
2406 }
2407}
2408
2409
ager@chromium.org381abbb2009-02-25 13:23:22 +00002410bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2411 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2412 if (ignore_case) {
2413 return pass == SIMPLE_CHARACTER_MATCH;
2414 } else {
2415 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2416 }
2417}
2418
2419
ager@chromium.org8bb60582008-12-11 12:02:20 +00002420// This generates the code to match a text node. A text node can contain
2421// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002422// way) and character classes. For efficiency we do not do this in a single
2423// pass from left to right. Instead we pass over the text node several times,
2424// emitting code for some character positions every time. See the comment on
2425// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002426void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002427 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002428 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002429 ASSERT(limit_result == CONTINUE);
2430
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002431 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2432 compiler->SetRegExpTooBig();
2433 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002434 }
2435
2436 if (compiler->ascii()) {
2437 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002438 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002439 }
2440
2441 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002442 int bound_checked_to = trace->cp_offset() - 1;
2443 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002444
2445 // If a character is preloaded into the current character register then
2446 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002447 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002448 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2449 if (!SkipPass(pass, compiler->ignore_case())) {
2450 TextEmitPass(compiler,
2451 static_cast<TextEmitPassType>(pass),
2452 true,
2453 trace,
2454 false,
2455 &bound_checked_to);
2456 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002457 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002458 first_elt_done = true;
2459 }
2460
ager@chromium.org381abbb2009-02-25 13:23:22 +00002461 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2462 if (!SkipPass(pass, compiler->ignore_case())) {
2463 TextEmitPass(compiler,
2464 static_cast<TextEmitPassType>(pass),
2465 false,
2466 trace,
2467 first_elt_done,
2468 &bound_checked_to);
2469 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002470 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002471
ager@chromium.org32912102009-01-16 10:38:43 +00002472 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002473 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002474 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002475 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002476 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002477}
2478
2479
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002480void Trace::InvalidateCurrentCharacter() {
2481 characters_preloaded_ = 0;
2482}
2483
2484
2485void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002486 ASSERT(by > 0);
2487 // We don't have an instruction for shifting the current character register
2488 // down or for using a shifted value for anything so lets just forget that
2489 // we preloaded any characters into it.
2490 characters_preloaded_ = 0;
2491 // Adjust the offsets of the quick check performed information. This
2492 // information is used to find out what we already determined about the
2493 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002494 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002495 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002496 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2497 compiler->SetRegExpTooBig();
2498 cp_offset_ = 0;
2499 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002500 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002501}
2502
2503
ager@chromium.org38e4c712009-11-11 09:11:58 +00002504void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002505 int element_count = elms_->length();
2506 for (int i = 0; i < element_count; i++) {
2507 TextElement elm = elms_->at(i);
2508 if (elm.type == TextElement::CHAR_CLASS) {
2509 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002510 // None of the standard character classses is different in the case
2511 // independent case and it slows us down if we don't know that.
2512 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002513 ZoneList<CharacterRange>* ranges = cc->ranges();
2514 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002515 for (int j = 0; j < range_count; j++) {
2516 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002517 }
2518 }
2519 }
2520}
2521
2522
ager@chromium.org8bb60582008-12-11 12:02:20 +00002523int TextNode::GreedyLoopTextLength() {
2524 TextElement elm = elms_->at(elms_->length() - 1);
2525 if (elm.type == TextElement::CHAR_CLASS) {
2526 return elm.cp_offset + 1;
2527 } else {
2528 return elm.cp_offset + elm.data.u_atom->data().length();
2529 }
2530}
2531
2532
2533// Finds the fixed match length of a sequence of nodes that goes from
2534// this alternative and back to this choice node. If there are variable
2535// length nodes or other complications in the way then return a sentinel
2536// value indicating that a greedy loop cannot be constructed.
2537int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2538 int length = 0;
2539 RegExpNode* node = alternative->node();
2540 // Later we will generate code for all these text nodes using recursion
2541 // so we have to limit the max number.
2542 int recursion_depth = 0;
2543 while (node != this) {
2544 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2545 return kNodeIsTooComplexForGreedyLoops;
2546 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002547 int node_length = node->GreedyLoopTextLength();
2548 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2549 return kNodeIsTooComplexForGreedyLoops;
2550 }
2551 length += node_length;
2552 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2553 node = seq_node->on_success();
2554 }
2555 return length;
2556}
2557
2558
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002559void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2560 ASSERT_EQ(loop_node_, NULL);
2561 AddAlternative(alt);
2562 loop_node_ = alt.node();
2563}
2564
2565
2566void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2567 ASSERT_EQ(continue_node_, NULL);
2568 AddAlternative(alt);
2569 continue_node_ = alt.node();
2570}
2571
2572
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002573void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002574 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002575 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002576 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2577 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2578 // Update the counter-based backtracking info on the stack. This is an
2579 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002580 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002581 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002582 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002583 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002584 }
ager@chromium.org32912102009-01-16 10:38:43 +00002585 ASSERT(trace->stop_node() == NULL);
2586 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002587 trace->Flush(compiler, this);
2588 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002589 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002590 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002591}
2592
2593
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002594int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002595 int preload_characters = EatsAtLeast(4, 0);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002596 if (compiler->macro_assembler()->CanReadUnaligned()) {
2597 bool ascii = compiler->ascii();
2598 if (ascii) {
2599 if (preload_characters > 4) preload_characters = 4;
2600 // We can't preload 3 characters because there is no machine instruction
2601 // to do that. We can't just load 4 because we could be reading
2602 // beyond the end of the string, which could cause a memory fault.
2603 if (preload_characters == 3) preload_characters = 2;
2604 } else {
2605 if (preload_characters > 2) preload_characters = 2;
2606 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002607 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002608 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002609 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002610 return preload_characters;
2611}
2612
2613
2614// This class is used when generating the alternatives in a choice node. It
2615// records the way the alternative is being code generated.
2616class AlternativeGeneration: public Malloced {
2617 public:
2618 AlternativeGeneration()
2619 : possible_success(),
2620 expects_preload(false),
2621 after(),
2622 quick_check_details() { }
2623 Label possible_success;
2624 bool expects_preload;
2625 Label after;
2626 QuickCheckDetails quick_check_details;
2627};
2628
2629
2630// Creates a list of AlternativeGenerations. If the list has a reasonable
2631// size then it is on the stack, otherwise the excess is on the heap.
2632class AlternativeGenerationList {
2633 public:
2634 explicit AlternativeGenerationList(int count)
2635 : alt_gens_(count) {
2636 for (int i = 0; i < count && i < kAFew; i++) {
2637 alt_gens_.Add(a_few_alt_gens_ + i);
2638 }
2639 for (int i = kAFew; i < count; i++) {
2640 alt_gens_.Add(new AlternativeGeneration());
2641 }
2642 }
2643 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002644 for (int i = kAFew; i < alt_gens_.length(); i++) {
2645 delete alt_gens_[i];
2646 alt_gens_[i] = NULL;
2647 }
2648 }
2649
2650 AlternativeGeneration* at(int i) {
2651 return alt_gens_[i];
2652 }
2653 private:
2654 static const int kAFew = 10;
2655 ZoneList<AlternativeGeneration*> alt_gens_;
2656 AlternativeGeneration a_few_alt_gens_[kAFew];
2657};
2658
2659
2660/* Code generation for choice nodes.
2661 *
2662 * We generate quick checks that do a mask and compare to eliminate a
2663 * choice. If the quick check succeeds then it jumps to the continuation to
2664 * do slow checks and check subsequent nodes. If it fails (the common case)
2665 * it falls through to the next choice.
2666 *
2667 * Here is the desired flow graph. Nodes directly below each other imply
2668 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2669 * 3 doesn't have a quick check so we have to call the slow check.
2670 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2671 * regexp continuation is generated directly after the Sn node, up to the
2672 * next GoTo if we decide to reuse some already generated code. Some
2673 * nodes expect preload_characters to be preloaded into the current
2674 * character register. R nodes do this preloading. Vertices are marked
2675 * F for failures and S for success (possible success in the case of quick
2676 * nodes). L, V, < and > are used as arrow heads.
2677 *
2678 * ----------> R
2679 * |
2680 * V
2681 * Q1 -----> S1
2682 * | S /
2683 * F| /
2684 * | F/
2685 * | /
2686 * | R
2687 * | /
2688 * V L
2689 * Q2 -----> S2
2690 * | S /
2691 * F| /
2692 * | F/
2693 * | /
2694 * | R
2695 * | /
2696 * V L
2697 * S3
2698 * |
2699 * F|
2700 * |
2701 * R
2702 * |
2703 * backtrack V
2704 * <----------Q4
2705 * \ F |
2706 * \ |S
2707 * \ F V
2708 * \-----S4
2709 *
2710 * For greedy loops we reverse our expectation and expect to match rather
2711 * than fail. Therefore we want the loop code to look like this (U is the
2712 * unwind code that steps back in the greedy loop). The following alternatives
2713 * look the same as above.
2714 * _____
2715 * / \
2716 * V |
2717 * ----------> S1 |
2718 * /| |
2719 * / |S |
2720 * F/ \_____/
2721 * /
2722 * |<-----------
2723 * | \
2724 * V \
2725 * Q2 ---> S2 \
2726 * | S / |
2727 * F| / |
2728 * | F/ |
2729 * | / |
2730 * | R |
2731 * | / |
2732 * F VL |
2733 * <------U |
2734 * back |S |
2735 * \______________/
2736 */
2737
2738
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002739void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002740 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2741 int choice_count = alternatives_->length();
2742#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002743 for (int i = 0; i < choice_count - 1; i++) {
2744 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002745 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002746 int guard_count = (guards == NULL) ? 0 : guards->length();
2747 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002748 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002749 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002750 }
2751#endif
2752
ager@chromium.org32912102009-01-16 10:38:43 +00002753 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002754 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002755 ASSERT(limit_result == CONTINUE);
2756
ager@chromium.org381abbb2009-02-25 13:23:22 +00002757 int new_flush_budget = trace->flush_budget() / choice_count;
2758 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2759 trace->Flush(compiler, this);
2760 return;
2761 }
2762
ager@chromium.org8bb60582008-12-11 12:02:20 +00002763 RecursionCheck rc(compiler);
2764
ager@chromium.org32912102009-01-16 10:38:43 +00002765 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002766
2767 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2768 bool greedy_loop = false;
2769 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002770 Trace counter_backtrack_trace;
2771 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002772 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2773
ager@chromium.org8bb60582008-12-11 12:02:20 +00002774 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2775 // Here we have special handling for greedy loops containing only text nodes
2776 // and other simple nodes. These are handled by pushing the current
2777 // position on the stack and then incrementing the current position each
2778 // time around the switch. On backtrack we decrement the current position
2779 // and check it against the pushed value. This avoids pushing backtrack
2780 // information for each iteration of the loop, which could take up a lot of
2781 // space.
2782 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002783 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002784 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002785 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002786 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002787 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002788 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002789 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002790 Label loop_label;
2791 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002792 greedy_match_trace.set_stop_node(this);
2793 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002794 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002795 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002796 }
2797
2798 Label second_choice; // For use in greedy matches.
2799 macro_assembler->Bind(&second_choice);
2800
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002801 int first_normal_choice = greedy_loop ? 1 : 0;
2802
2803 int preload_characters = CalculatePreloadCharacters(compiler);
2804 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002805 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002806 bool preload_has_checked_bounds = preload_is_current;
2807
2808 AlternativeGenerationList alt_gens(choice_count);
2809
ager@chromium.org8bb60582008-12-11 12:02:20 +00002810 // For now we just call all choices one after the other. The idea ultimately
2811 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002812 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002813 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002814 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002815 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002816 ZoneList<Guard*>* guards = alternative.guards();
2817 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002818 Trace new_trace(*current_trace);
2819 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002820 preload_characters :
2821 0);
2822 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002823 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002824 }
ager@chromium.org32912102009-01-16 10:38:43 +00002825 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002826 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002827 alt_gen->expects_preload = preload_is_current;
2828 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002829 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002830 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002831 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002832 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002833 preload_has_checked_bounds,
2834 &alt_gen->possible_success,
2835 &alt_gen->quick_check_details,
2836 i < choice_count - 1)) {
2837 // Quick check was generated for this choice.
2838 preload_is_current = true;
2839 preload_has_checked_bounds = true;
2840 // On the last choice in the ChoiceNode we generated the quick
2841 // check to fall through on possible success. So now we need to
2842 // generate the full check inline.
2843 if (i == choice_count - 1) {
2844 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002845 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2846 new_trace.set_characters_preloaded(preload_characters);
2847 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002848 generate_full_check_inline = true;
2849 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002850 } else if (alt_gen->quick_check_details.cannot_match()) {
2851 if (i == choice_count - 1 && !greedy_loop) {
2852 macro_assembler->GoTo(trace->backtrack());
2853 }
2854 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002855 } else {
2856 // No quick check was generated. Put the full code here.
2857 // If this is not the first choice then there could be slow checks from
2858 // previous cases that go here when they fail. There's no reason to
2859 // insist that they preload characters since the slow check we are about
2860 // to generate probably can't use it.
2861 if (i != first_normal_choice) {
2862 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002863 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002864 }
2865 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002866 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002867 }
2868 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002869 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002870 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002871 if (new_trace.actions() != NULL) {
2872 new_trace.set_flush_budget(new_flush_budget);
2873 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002874 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002875 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002876 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002877 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002878 preload_is_current = false;
2879 }
2880 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002881 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002882 if (greedy_loop) {
2883 macro_assembler->Bind(&greedy_loop_label);
2884 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002885 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002886 // Otherwise try the second priority at an earlier position.
2887 macro_assembler->AdvanceCurrentPosition(-text_length);
2888 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002889 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002890
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002891 // At this point we need to generate slow checks for the alternatives where
2892 // the quick check was inlined. We can recognize these because the associated
2893 // label was bound.
2894 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2895 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002896 Trace new_trace(*current_trace);
2897 // If there are actions to be flushed we have to limit how many times
2898 // they are flushed. Take the budget of the parent trace and distribute
2899 // it fairly amongst the children.
2900 if (new_trace.actions() != NULL) {
2901 new_trace.set_flush_budget(new_flush_budget);
2902 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002903 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002904 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002905 alternatives_->at(i),
2906 alt_gen,
2907 preload_characters,
2908 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002909 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002910}
2911
2912
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002913void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002914 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002915 GuardedAlternative alternative,
2916 AlternativeGeneration* alt_gen,
2917 int preload_characters,
2918 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002919 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002920
2921 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2922 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002923 Trace out_of_line_trace(*trace);
2924 out_of_line_trace.set_characters_preloaded(preload_characters);
2925 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002926 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002927 ZoneList<Guard*>* guards = alternative.guards();
2928 int guard_count = (guards == NULL) ? 0 : guards->length();
2929 if (next_expects_preload) {
2930 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00002931 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002932 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002933 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002934 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002935 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002936 macro_assembler->Bind(&reload_current_char);
2937 // Reload the current character, since the next quick check expects that.
2938 // We don't need to check bounds here because we only get into this
2939 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00002940 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002941 NULL,
2942 false,
2943 preload_characters);
2944 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002945 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00002946 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002947 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002948 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002949 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002950 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002951 }
2952}
2953
2954
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002955void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002956 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002957 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002958 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002959 ASSERT(limit_result == CONTINUE);
2960
2961 RecursionCheck rc(compiler);
2962
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002963 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002964 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00002965 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002966 new_capture(data_.u_position_register.reg,
2967 data_.u_position_register.is_capture,
2968 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002969 Trace new_trace = *trace;
2970 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002971 on_success()->Emit(compiler, &new_trace);
2972 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002973 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002974 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002975 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002976 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00002977 Trace new_trace = *trace;
2978 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002979 on_success()->Emit(compiler, &new_trace);
2980 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002981 }
2982 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002983 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002984 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00002985 Trace new_trace = *trace;
2986 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002987 on_success()->Emit(compiler, &new_trace);
2988 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002989 }
2990 case CLEAR_CAPTURES: {
2991 Trace::DeferredClearCaptures
2992 new_capture(Interval(data_.u_clear_captures.range_from,
2993 data_.u_clear_captures.range_to));
2994 Trace new_trace = *trace;
2995 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002996 on_success()->Emit(compiler, &new_trace);
2997 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002998 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002999 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003000 if (!trace->is_trivial()) {
3001 trace->Flush(compiler, this);
3002 } else {
3003 assembler->WriteCurrentPositionToRegister(
3004 data_.u_submatch.current_position_register, 0);
3005 assembler->WriteStackPointerToRegister(
3006 data_.u_submatch.stack_pointer_register);
3007 on_success()->Emit(compiler, trace);
3008 }
3009 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003010 case EMPTY_MATCH_CHECK: {
3011 int start_pos_reg = data_.u_empty_match_check.start_register;
3012 int stored_pos = 0;
3013 int rep_reg = data_.u_empty_match_check.repetition_register;
3014 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3015 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3016 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3017 // If we know we haven't advanced and there is no minimum we
3018 // can just backtrack immediately.
3019 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003020 } else if (know_dist && stored_pos < trace->cp_offset()) {
3021 // If we know we've advanced we can generate the continuation
3022 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003023 on_success()->Emit(compiler, trace);
3024 } else if (!trace->is_trivial()) {
3025 trace->Flush(compiler, this);
3026 } else {
3027 Label skip_empty_check;
3028 // If we have a minimum number of repetitions we check the current
3029 // number first and skip the empty check if it's not enough.
3030 if (has_minimum) {
3031 int limit = data_.u_empty_match_check.repetition_limit;
3032 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3033 }
3034 // If the match is empty we bail out, otherwise we fall through
3035 // to the on-success continuation.
3036 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3037 trace->backtrack());
3038 assembler->Bind(&skip_empty_check);
3039 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003040 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003041 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003042 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003043 case POSITIVE_SUBMATCH_SUCCESS: {
3044 if (!trace->is_trivial()) {
3045 trace->Flush(compiler, this);
3046 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003047 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003048 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003049 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003050 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003051 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003052 int clear_register_count = data_.u_submatch.clear_register_count;
3053 if (clear_register_count == 0) {
3054 on_success()->Emit(compiler, trace);
3055 return;
3056 }
3057 int clear_registers_from = data_.u_submatch.clear_register_from;
3058 Label clear_registers_backtrack;
3059 Trace new_trace = *trace;
3060 new_trace.set_backtrack(&clear_registers_backtrack);
3061 on_success()->Emit(compiler, &new_trace);
3062
3063 assembler->Bind(&clear_registers_backtrack);
3064 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3065 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3066
3067 ASSERT(trace->backtrack() == NULL);
3068 assembler->Backtrack();
3069 return;
3070 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003071 default:
3072 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003073 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003074}
3075
3076
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003077void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003078 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003079 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003080 trace->Flush(compiler, this);
3081 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003082 }
3083
ager@chromium.org32912102009-01-16 10:38:43 +00003084 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003085 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003086 ASSERT(limit_result == CONTINUE);
3087
3088 RecursionCheck rc(compiler);
3089
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003090 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003091 if (compiler->ignore_case()) {
3092 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3093 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003094 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003095 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003096 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003097 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003098}
3099
3100
3101// -------------------------------------------------------------------
3102// Dot/dotty output
3103
3104
3105#ifdef DEBUG
3106
3107
3108class DotPrinter: public NodeVisitor {
3109 public:
3110 explicit DotPrinter(bool ignore_case)
3111 : ignore_case_(ignore_case),
3112 stream_(&alloc_) { }
3113 void PrintNode(const char* label, RegExpNode* node);
3114 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003115 void PrintAttributes(RegExpNode* from);
3116 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003117 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003118#define DECLARE_VISIT(Type) \
3119 virtual void Visit##Type(Type##Node* that);
3120FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3121#undef DECLARE_VISIT
3122 private:
3123 bool ignore_case_;
3124 HeapStringAllocator alloc_;
3125 StringStream stream_;
3126};
3127
3128
3129void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3130 stream()->Add("digraph G {\n graph [label=\"");
3131 for (int i = 0; label[i]; i++) {
3132 switch (label[i]) {
3133 case '\\':
3134 stream()->Add("\\\\");
3135 break;
3136 case '"':
3137 stream()->Add("\"");
3138 break;
3139 default:
3140 stream()->Put(label[i]);
3141 break;
3142 }
3143 }
3144 stream()->Add("\"];\n");
3145 Visit(node);
3146 stream()->Add("}\n");
3147 printf("%s", *(stream()->ToCString()));
3148}
3149
3150
3151void DotPrinter::Visit(RegExpNode* node) {
3152 if (node->info()->visited) return;
3153 node->info()->visited = true;
3154 node->Accept(this);
3155}
3156
3157
3158void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003159 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3160 Visit(on_failure);
3161}
3162
3163
3164class TableEntryBodyPrinter {
3165 public:
3166 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3167 : stream_(stream), choice_(choice) { }
3168 void Call(uc16 from, DispatchTable::Entry entry) {
3169 OutSet* out_set = entry.out_set();
3170 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3171 if (out_set->Get(i)) {
3172 stream()->Add(" n%p:s%io%i -> n%p;\n",
3173 choice(),
3174 from,
3175 i,
3176 choice()->alternatives()->at(i).node());
3177 }
3178 }
3179 }
3180 private:
3181 StringStream* stream() { return stream_; }
3182 ChoiceNode* choice() { return choice_; }
3183 StringStream* stream_;
3184 ChoiceNode* choice_;
3185};
3186
3187
3188class TableEntryHeaderPrinter {
3189 public:
3190 explicit TableEntryHeaderPrinter(StringStream* stream)
3191 : first_(true), stream_(stream) { }
3192 void Call(uc16 from, DispatchTable::Entry entry) {
3193 if (first_) {
3194 first_ = false;
3195 } else {
3196 stream()->Add("|");
3197 }
3198 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3199 OutSet* out_set = entry.out_set();
3200 int priority = 0;
3201 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3202 if (out_set->Get(i)) {
3203 if (priority > 0) stream()->Add("|");
3204 stream()->Add("<s%io%i> %i", from, i, priority);
3205 priority++;
3206 }
3207 }
3208 stream()->Add("}}");
3209 }
3210 private:
3211 bool first_;
3212 StringStream* stream() { return stream_; }
3213 StringStream* stream_;
3214};
3215
3216
3217class AttributePrinter {
3218 public:
3219 explicit AttributePrinter(DotPrinter* out)
3220 : out_(out), first_(true) { }
3221 void PrintSeparator() {
3222 if (first_) {
3223 first_ = false;
3224 } else {
3225 out_->stream()->Add("|");
3226 }
3227 }
3228 void PrintBit(const char* name, bool value) {
3229 if (!value) return;
3230 PrintSeparator();
3231 out_->stream()->Add("{%s}", name);
3232 }
3233 void PrintPositive(const char* name, int value) {
3234 if (value < 0) return;
3235 PrintSeparator();
3236 out_->stream()->Add("{%s|%x}", name, value);
3237 }
3238 private:
3239 DotPrinter* out_;
3240 bool first_;
3241};
3242
3243
3244void DotPrinter::PrintAttributes(RegExpNode* that) {
3245 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3246 "margin=0.1, fontsize=10, label=\"{",
3247 that);
3248 AttributePrinter printer(this);
3249 NodeInfo* info = that->info();
3250 printer.PrintBit("NI", info->follows_newline_interest);
3251 printer.PrintBit("WI", info->follows_word_interest);
3252 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003253 Label* label = that->label();
3254 if (label->is_bound())
3255 printer.PrintPositive("@", label->pos());
3256 stream()->Add("}\"];\n");
3257 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3258 "arrowhead=none];\n", that, that);
3259}
3260
3261
3262static const bool kPrintDispatchTable = false;
3263void DotPrinter::VisitChoice(ChoiceNode* that) {
3264 if (kPrintDispatchTable) {
3265 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3266 TableEntryHeaderPrinter header_printer(stream());
3267 that->GetTable(ignore_case_)->ForEach(&header_printer);
3268 stream()->Add("\"]\n", that);
3269 PrintAttributes(that);
3270 TableEntryBodyPrinter body_printer(stream(), that);
3271 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003272 } else {
3273 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3274 for (int i = 0; i < that->alternatives()->length(); i++) {
3275 GuardedAlternative alt = that->alternatives()->at(i);
3276 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3277 }
3278 }
3279 for (int i = 0; i < that->alternatives()->length(); i++) {
3280 GuardedAlternative alt = that->alternatives()->at(i);
3281 alt.node()->Accept(this);
3282 }
3283}
3284
3285
3286void DotPrinter::VisitText(TextNode* that) {
3287 stream()->Add(" n%p [label=\"", that);
3288 for (int i = 0; i < that->elements()->length(); i++) {
3289 if (i > 0) stream()->Add(" ");
3290 TextElement elm = that->elements()->at(i);
3291 switch (elm.type) {
3292 case TextElement::ATOM: {
3293 stream()->Add("'%w'", elm.data.u_atom->data());
3294 break;
3295 }
3296 case TextElement::CHAR_CLASS: {
3297 RegExpCharacterClass* node = elm.data.u_char_class;
3298 stream()->Add("[");
3299 if (node->is_negated())
3300 stream()->Add("^");
3301 for (int j = 0; j < node->ranges()->length(); j++) {
3302 CharacterRange range = node->ranges()->at(j);
3303 stream()->Add("%k-%k", range.from(), range.to());
3304 }
3305 stream()->Add("]");
3306 break;
3307 }
3308 default:
3309 UNREACHABLE();
3310 }
3311 }
3312 stream()->Add("\", shape=box, peripheries=2];\n");
3313 PrintAttributes(that);
3314 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3315 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003316}
3317
3318
3319void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3320 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3321 that,
3322 that->start_register(),
3323 that->end_register());
3324 PrintAttributes(that);
3325 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3326 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003327}
3328
3329
3330void DotPrinter::VisitEnd(EndNode* that) {
3331 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3332 PrintAttributes(that);
3333}
3334
3335
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003336void DotPrinter::VisitAssertion(AssertionNode* that) {
3337 stream()->Add(" n%p [", that);
3338 switch (that->type()) {
3339 case AssertionNode::AT_END:
3340 stream()->Add("label=\"$\", shape=septagon");
3341 break;
3342 case AssertionNode::AT_START:
3343 stream()->Add("label=\"^\", shape=septagon");
3344 break;
3345 case AssertionNode::AT_BOUNDARY:
3346 stream()->Add("label=\"\\b\", shape=septagon");
3347 break;
3348 case AssertionNode::AT_NON_BOUNDARY:
3349 stream()->Add("label=\"\\B\", shape=septagon");
3350 break;
3351 case AssertionNode::AFTER_NEWLINE:
3352 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3353 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003354 case AssertionNode::AFTER_WORD_CHARACTER:
3355 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3356 break;
3357 case AssertionNode::AFTER_NONWORD_CHARACTER:
3358 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3359 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003360 }
3361 stream()->Add("];\n");
3362 PrintAttributes(that);
3363 RegExpNode* successor = that->on_success();
3364 stream()->Add(" n%p -> n%p;\n", that, successor);
3365 Visit(successor);
3366}
3367
3368
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003369void DotPrinter::VisitAction(ActionNode* that) {
3370 stream()->Add(" n%p [", that);
3371 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003372 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003373 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3374 that->data_.u_store_register.reg,
3375 that->data_.u_store_register.value);
3376 break;
3377 case ActionNode::INCREMENT_REGISTER:
3378 stream()->Add("label=\"$%i++\", shape=octagon",
3379 that->data_.u_increment_register.reg);
3380 break;
3381 case ActionNode::STORE_POSITION:
3382 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3383 that->data_.u_position_register.reg);
3384 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003385 case ActionNode::BEGIN_SUBMATCH:
3386 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3387 that->data_.u_submatch.current_position_register);
3388 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003389 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003390 stream()->Add("label=\"escape\", shape=septagon");
3391 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003392 case ActionNode::EMPTY_MATCH_CHECK:
3393 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3394 that->data_.u_empty_match_check.start_register,
3395 that->data_.u_empty_match_check.repetition_register,
3396 that->data_.u_empty_match_check.repetition_limit);
3397 break;
3398 case ActionNode::CLEAR_CAPTURES: {
3399 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3400 that->data_.u_clear_captures.range_from,
3401 that->data_.u_clear_captures.range_to);
3402 break;
3403 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003404 }
3405 stream()->Add("];\n");
3406 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003407 RegExpNode* successor = that->on_success();
3408 stream()->Add(" n%p -> n%p;\n", that, successor);
3409 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003410}
3411
3412
3413class DispatchTableDumper {
3414 public:
3415 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3416 void Call(uc16 key, DispatchTable::Entry entry);
3417 StringStream* stream() { return stream_; }
3418 private:
3419 StringStream* stream_;
3420};
3421
3422
3423void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3424 stream()->Add("[%k-%k]: {", key, entry.to());
3425 OutSet* set = entry.out_set();
3426 bool first = true;
3427 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3428 if (set->Get(i)) {
3429 if (first) {
3430 first = false;
3431 } else {
3432 stream()->Add(", ");
3433 }
3434 stream()->Add("%i", i);
3435 }
3436 }
3437 stream()->Add("}\n");
3438}
3439
3440
3441void DispatchTable::Dump() {
3442 HeapStringAllocator alloc;
3443 StringStream stream(&alloc);
3444 DispatchTableDumper dumper(&stream);
3445 tree()->ForEach(&dumper);
3446 OS::PrintError("%s", *stream.ToCString());
3447}
3448
3449
3450void RegExpEngine::DotPrint(const char* label,
3451 RegExpNode* node,
3452 bool ignore_case) {
3453 DotPrinter printer(ignore_case);
3454 printer.PrintNode(label, node);
3455}
3456
3457
3458#endif // DEBUG
3459
3460
3461// -------------------------------------------------------------------
3462// Tree to graph conversion
3463
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003464static const int kSpaceRangeCount = 20;
3465static const int kSpaceRangeAsciiCount = 4;
3466static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3467 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3468 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3469
3470static const int kWordRangeCount = 8;
3471static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3472 '_', 'a', 'z' };
3473
3474static const int kDigitRangeCount = 2;
3475static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3476
3477static const int kLineTerminatorRangeCount = 6;
3478static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3479 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003480
3481RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003482 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003483 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3484 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003485 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003486}
3487
3488
3489RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003490 RegExpNode* on_success) {
3491 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003492}
3493
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003494static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3495 const uc16* special_class,
3496 int length) {
3497 ASSERT(ranges->length() != 0);
3498 ASSERT(length != 0);
3499 ASSERT(special_class[0] != 0);
3500 if (ranges->length() != (length >> 1) + 1) {
3501 return false;
3502 }
3503 CharacterRange range = ranges->at(0);
3504 if (range.from() != 0) {
3505 return false;
3506 }
3507 for (int i = 0; i < length; i += 2) {
3508 if (special_class[i] != (range.to() + 1)) {
3509 return false;
3510 }
3511 range = ranges->at((i >> 1) + 1);
3512 if (special_class[i+1] != range.from() - 1) {
3513 return false;
3514 }
3515 }
3516 if (range.to() != 0xffff) {
3517 return false;
3518 }
3519 return true;
3520}
3521
3522
3523static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3524 const uc16* special_class,
3525 int length) {
3526 if (ranges->length() * 2 != length) {
3527 return false;
3528 }
3529 for (int i = 0; i < length; i += 2) {
3530 CharacterRange range = ranges->at(i >> 1);
3531 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3532 return false;
3533 }
3534 }
3535 return true;
3536}
3537
3538
3539bool RegExpCharacterClass::is_standard() {
3540 // TODO(lrn): Remove need for this function, by not throwing away information
3541 // along the way.
3542 if (is_negated_) {
3543 return false;
3544 }
3545 if (set_.is_standard()) {
3546 return true;
3547 }
3548 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3549 set_.set_standard_set_type('s');
3550 return true;
3551 }
3552 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3553 set_.set_standard_set_type('S');
3554 return true;
3555 }
3556 if (CompareInverseRanges(set_.ranges(),
3557 kLineTerminatorRanges,
3558 kLineTerminatorRangeCount)) {
3559 set_.set_standard_set_type('.');
3560 return true;
3561 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003562 if (CompareRanges(set_.ranges(),
3563 kLineTerminatorRanges,
3564 kLineTerminatorRangeCount)) {
3565 set_.set_standard_set_type('n');
3566 return true;
3567 }
3568 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3569 set_.set_standard_set_type('w');
3570 return true;
3571 }
3572 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3573 set_.set_standard_set_type('W');
3574 return true;
3575 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003576 return false;
3577}
3578
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003579
3580RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003581 RegExpNode* on_success) {
3582 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003583}
3584
3585
3586RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003587 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003588 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3589 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003590 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003591 for (int i = 0; i < length; i++) {
3592 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003593 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003594 result->AddAlternative(alternative);
3595 }
3596 return result;
3597}
3598
3599
3600RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003601 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003602 return ToNode(min(),
3603 max(),
3604 is_greedy(),
3605 body(),
3606 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003607 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003608}
3609
3610
3611RegExpNode* RegExpQuantifier::ToNode(int min,
3612 int max,
3613 bool is_greedy,
3614 RegExpTree* body,
3615 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003616 RegExpNode* on_success,
3617 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003618 // x{f, t} becomes this:
3619 //
3620 // (r++)<-.
3621 // | `
3622 // | (x)
3623 // v ^
3624 // (r=0)-->(?)---/ [if r < t]
3625 // |
3626 // [if r >= f] \----> ...
3627 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003628
3629 // 15.10.2.5 RepeatMatcher algorithm.
3630 // The parser has already eliminated the case where max is 0. In the case
3631 // where max_match is zero the parser has removed the quantifier if min was
3632 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3633
3634 // If we know that we cannot match zero length then things are a little
3635 // simpler since we don't need to make the special zero length match check
3636 // from step 2.1. If the min and max are small we can unroll a little in
3637 // this case.
3638 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3639 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3640 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003641 bool body_can_be_empty = (body->min_match() == 0);
3642 int body_start_reg = RegExpCompiler::kNoRegister;
3643 Interval capture_registers = body->CaptureRegisters();
3644 bool needs_capture_clearing = !capture_registers.is_empty();
3645 if (body_can_be_empty) {
3646 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003647 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003648 // Only unroll if there are no captures and the body can't be
3649 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003650 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3651 int new_max = (max == kInfinity) ? max : max - min;
3652 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003653 RegExpNode* answer = ToNode(
3654 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003655 // Unroll the forced matches from 0 to min. This can cause chains of
3656 // TextNodes (which the parser does not generate). These should be
3657 // combined if it turns out they hinder good code generation.
3658 for (int i = 0; i < min; i++) {
3659 answer = body->ToNode(compiler, answer);
3660 }
3661 return answer;
3662 }
3663 if (max <= kMaxUnrolledMaxMatches) {
3664 ASSERT(min == 0);
3665 // Unroll the optional matches up to max.
3666 RegExpNode* answer = on_success;
3667 for (int i = 0; i < max; i++) {
3668 ChoiceNode* alternation = new ChoiceNode(2);
3669 if (is_greedy) {
3670 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3671 answer)));
3672 alternation->AddAlternative(GuardedAlternative(on_success));
3673 } else {
3674 alternation->AddAlternative(GuardedAlternative(on_success));
3675 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3676 answer)));
3677 }
3678 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003679 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003680 }
3681 return answer;
3682 }
3683 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003684 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003685 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003686 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003687 int reg_ctr = needs_counter
3688 ? compiler->AllocateRegister()
3689 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003690 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003691 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003692 RegExpNode* loop_return = needs_counter
3693 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3694 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003695 if (body_can_be_empty) {
3696 // If the body can be empty we need to check if it was and then
3697 // backtrack.
3698 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3699 reg_ctr,
3700 min,
3701 loop_return);
3702 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003703 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003704 if (body_can_be_empty) {
3705 // If the body can be empty we need to store the start position
3706 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003707 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003708 }
3709 if (needs_capture_clearing) {
3710 // Before entering the body of this loop we need to clear captures.
3711 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3712 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003713 GuardedAlternative body_alt(body_node);
3714 if (has_max) {
3715 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3716 body_alt.AddGuard(body_guard);
3717 }
3718 GuardedAlternative rest_alt(on_success);
3719 if (has_min) {
3720 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3721 rest_alt.AddGuard(rest_guard);
3722 }
3723 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003724 center->AddLoopAlternative(body_alt);
3725 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003726 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003727 center->AddContinueAlternative(rest_alt);
3728 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003729 }
3730 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003731 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003732 } else {
3733 return center;
3734 }
3735}
3736
3737
3738RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003739 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003740 NodeInfo info;
3741 switch (type()) {
3742 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003743 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003744 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003745 return AssertionNode::AtStart(on_success);
3746 case BOUNDARY:
3747 return AssertionNode::AtBoundary(on_success);
3748 case NON_BOUNDARY:
3749 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003750 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003751 return AssertionNode::AtEnd(on_success);
3752 case END_OF_LINE: {
3753 // Compile $ in multiline regexps as an alternation with a positive
3754 // lookahead in one side and an end-of-input on the other side.
3755 // We need two registers for the lookahead.
3756 int stack_pointer_register = compiler->AllocateRegister();
3757 int position_register = compiler->AllocateRegister();
3758 // The ChoiceNode to distinguish between a newline and end-of-input.
3759 ChoiceNode* result = new ChoiceNode(2);
3760 // Create a newline atom.
3761 ZoneList<CharacterRange>* newline_ranges =
3762 new ZoneList<CharacterRange>(3);
3763 CharacterRange::AddClassEscape('n', newline_ranges);
3764 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3765 TextNode* newline_matcher = new TextNode(
3766 newline_atom,
3767 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3768 position_register,
3769 0, // No captures inside.
3770 -1, // Ignored if no captures.
3771 on_success));
3772 // Create an end-of-input matcher.
3773 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3774 stack_pointer_register,
3775 position_register,
3776 newline_matcher);
3777 // Add the two alternatives to the ChoiceNode.
3778 GuardedAlternative eol_alternative(end_of_line);
3779 result->AddAlternative(eol_alternative);
3780 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3781 result->AddAlternative(end_alternative);
3782 return result;
3783 }
3784 default:
3785 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003786 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003787 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003788}
3789
3790
3791RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003792 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003793 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3794 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003795 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003796}
3797
3798
3799RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003800 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003801 return on_success;
3802}
3803
3804
3805RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003806 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003807 int stack_pointer_register = compiler->AllocateRegister();
3808 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003809
3810 const int registers_per_capture = 2;
3811 const int register_of_first_capture = 2;
3812 int register_count = capture_count_ * registers_per_capture;
3813 int register_start =
3814 register_of_first_capture + capture_from_ * registers_per_capture;
3815
ager@chromium.org8bb60582008-12-11 12:02:20 +00003816 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003817 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003818 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003819 stack_pointer_register,
3820 position_register,
3821 body()->ToNode(
3822 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003823 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3824 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003825 register_count,
3826 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003827 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003828 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003829 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003830 // We use a ChoiceNode for a negative lookahead because it has most of
3831 // the characteristics we need. It has the body of the lookahead as its
3832 // first alternative and the expression after the lookahead of the second
3833 // alternative. If the first alternative succeeds then the
3834 // NegativeSubmatchSuccess will unwind the stack including everything the
3835 // choice node set up and backtrack. If the first alternative fails then
3836 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003837 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3838 // ChoiceNode that knows to ignore the first exit when calculating quick
3839 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003840 GuardedAlternative body_alt(
3841 body()->ToNode(
3842 compiler,
3843 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003844 position_register,
3845 register_count,
3846 register_start)));
3847 ChoiceNode* choice_node =
3848 new NegativeLookaheadChoiceNode(body_alt,
3849 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003850 return ActionNode::BeginSubmatch(stack_pointer_register,
3851 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003852 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003853 }
3854}
3855
3856
3857RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003858 RegExpNode* on_success) {
3859 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003860}
3861
3862
3863RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3864 int index,
3865 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003866 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003867 int start_reg = RegExpCapture::StartRegister(index);
3868 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003869 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003870 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003871 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003872}
3873
3874
3875RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003876 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003877 ZoneList<RegExpTree*>* children = nodes();
3878 RegExpNode* current = on_success;
3879 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003880 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003881 }
3882 return current;
3883}
3884
3885
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003886static void AddClass(const uc16* elmv,
3887 int elmc,
3888 ZoneList<CharacterRange>* ranges) {
3889 for (int i = 0; i < elmc; i += 2) {
3890 ASSERT(elmv[i] <= elmv[i + 1]);
3891 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3892 }
3893}
3894
3895
3896static void AddClassNegated(const uc16 *elmv,
3897 int elmc,
3898 ZoneList<CharacterRange>* ranges) {
3899 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003900 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003901 uc16 last = 0x0000;
3902 for (int i = 0; i < elmc; i += 2) {
3903 ASSERT(last <= elmv[i] - 1);
3904 ASSERT(elmv[i] <= elmv[i + 1]);
3905 ranges->Add(CharacterRange(last, elmv[i] - 1));
3906 last = elmv[i + 1] + 1;
3907 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003908 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003909}
3910
3911
3912void CharacterRange::AddClassEscape(uc16 type,
3913 ZoneList<CharacterRange>* ranges) {
3914 switch (type) {
3915 case 's':
3916 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3917 break;
3918 case 'S':
3919 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3920 break;
3921 case 'w':
3922 AddClass(kWordRanges, kWordRangeCount, ranges);
3923 break;
3924 case 'W':
3925 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3926 break;
3927 case 'd':
3928 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3929 break;
3930 case 'D':
3931 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3932 break;
3933 case '.':
3934 AddClassNegated(kLineTerminatorRanges,
3935 kLineTerminatorRangeCount,
3936 ranges);
3937 break;
3938 // This is not a character range as defined by the spec but a
3939 // convenient shorthand for a character class that matches any
3940 // character.
3941 case '*':
3942 ranges->Add(CharacterRange::Everything());
3943 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003944 // This is the set of characters matched by the $ and ^ symbols
3945 // in multiline mode.
3946 case 'n':
3947 AddClass(kLineTerminatorRanges,
3948 kLineTerminatorRangeCount,
3949 ranges);
3950 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003951 default:
3952 UNREACHABLE();
3953 }
3954}
3955
3956
3957Vector<const uc16> CharacterRange::GetWordBounds() {
3958 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3959}
3960
3961
3962class CharacterRangeSplitter {
3963 public:
3964 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3965 ZoneList<CharacterRange>** excluded)
3966 : included_(included),
3967 excluded_(excluded) { }
3968 void Call(uc16 from, DispatchTable::Entry entry);
3969
3970 static const int kInBase = 0;
3971 static const int kInOverlay = 1;
3972
3973 private:
3974 ZoneList<CharacterRange>** included_;
3975 ZoneList<CharacterRange>** excluded_;
3976};
3977
3978
3979void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3980 if (!entry.out_set()->Get(kInBase)) return;
3981 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3982 ? included_
3983 : excluded_;
3984 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3985 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3986}
3987
3988
3989void CharacterRange::Split(ZoneList<CharacterRange>* base,
3990 Vector<const uc16> overlay,
3991 ZoneList<CharacterRange>** included,
3992 ZoneList<CharacterRange>** excluded) {
3993 ASSERT_EQ(NULL, *included);
3994 ASSERT_EQ(NULL, *excluded);
3995 DispatchTable table;
3996 for (int i = 0; i < base->length(); i++)
3997 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3998 for (int i = 0; i < overlay.length(); i += 2) {
3999 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
4000 CharacterRangeSplitter::kInOverlay);
4001 }
4002 CharacterRangeSplitter callback(included, excluded);
4003 table.ForEach(&callback);
4004}
4005
4006
ager@chromium.org38e4c712009-11-11 09:11:58 +00004007static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4008 int bottom,
4009 int top);
4010
4011
4012void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4013 bool is_ascii) {
4014 uc16 bottom = from();
4015 uc16 top = to();
4016 if (is_ascii) {
4017 if (bottom > String::kMaxAsciiCharCode) return;
4018 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4019 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004020 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004021 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004022 // If this is a singleton we just expand the one character.
ager@chromium.org38e4c712009-11-11 09:11:58 +00004023 int length = uncanonicalize.get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004024 for (int i = 0; i < length; i++) {
4025 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004026 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004027 ranges->Add(CharacterRange::Singleton(chars[i]));
4028 }
4029 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004030 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004031 // If this is a range we expand the characters block by block,
4032 // expanding contiguous subranges (blocks) one at a time.
4033 // The approach is as follows. For a given start character we
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004034 // look up the remainder of the block that contains it (represented
4035 // by the end point), for instance we find 'z' if the character
4036 // is 'c'. A block is characterized by the property
4037 // that all characters uncanonicalize in the same way, except that
4038 // each entry in the result is incremented by the distance from the first
4039 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
4040 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
4041 // Once we've found the end point we look up its uncanonicalization
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004042 // and produce a range for each element. For instance for [c-f]
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004043 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004044 // add a range if it is not already contained in the input, so [c-f]
4045 // will be skipped but [C-F] will be added. If this range is not
4046 // completely contained in a block we do this for all the blocks
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004047 // covered by the range (handling characters that is not in a block
4048 // as a "singleton block").
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004049 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004050 int pos = bottom;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004051 while (pos < top) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004052 int length = canonrange.get(pos, '\0', range);
4053 uc16 block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004054 if (length == 0) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004055 block_end = pos;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004056 } else {
4057 ASSERT_EQ(1, length);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004058 block_end = range[0];
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004059 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004060 int end = (block_end > top) ? top : block_end;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004061 length = uncanonicalize.get(block_end, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004062 for (int i = 0; i < length; i++) {
4063 uc32 c = range[i];
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004064 uc16 range_from = c - (block_end - pos);
4065 uc16 range_to = c - (block_end - end);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004066 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004067 ranges->Add(CharacterRange(range_from, range_to));
4068 }
4069 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004070 pos = end + 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004071 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004072 }
4073}
4074
4075
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004076bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4077 ASSERT_NOT_NULL(ranges);
4078 int n = ranges->length();
4079 if (n <= 1) return true;
4080 int max = ranges->at(0).to();
4081 for (int i = 1; i < n; i++) {
4082 CharacterRange next_range = ranges->at(i);
4083 if (next_range.from() <= max + 1) return false;
4084 max = next_range.to();
4085 }
4086 return true;
4087}
4088
4089SetRelation CharacterRange::WordCharacterRelation(
4090 ZoneList<CharacterRange>* range) {
4091 ASSERT(IsCanonical(range));
4092 int i = 0; // Word character range index.
4093 int j = 0; // Argument range index.
4094 ASSERT_NE(0, kWordRangeCount);
4095 SetRelation result;
4096 if (range->length() == 0) {
4097 result.SetElementsInSecondSet();
4098 return result;
4099 }
4100 CharacterRange argument_range = range->at(0);
4101 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4102 while (i < kWordRangeCount && j < range->length()) {
4103 // Check the two ranges for the five cases:
4104 // - no overlap.
4105 // - partial overlap (there are elements in both ranges that isn't
4106 // in the other, and there are also elements that are in both).
4107 // - argument range entirely inside word range.
4108 // - word range entirely inside argument range.
4109 // - ranges are completely equal.
4110
4111 // First check for no overlap. The earlier range is not in the other set.
4112 if (argument_range.from() > word_range.to()) {
4113 // Ranges are disjoint. The earlier word range contains elements that
4114 // cannot be in the argument set.
4115 result.SetElementsInSecondSet();
4116 } else if (word_range.from() > argument_range.to()) {
4117 // Ranges are disjoint. The earlier argument range contains elements that
4118 // cannot be in the word set.
4119 result.SetElementsInFirstSet();
4120 } else if (word_range.from() <= argument_range.from() &&
4121 word_range.to() >= argument_range.from()) {
4122 result.SetElementsInBothSets();
4123 // argument range completely inside word range.
4124 if (word_range.from() < argument_range.from() ||
4125 word_range.to() > argument_range.from()) {
4126 result.SetElementsInSecondSet();
4127 }
4128 } else if (word_range.from() >= argument_range.from() &&
4129 word_range.to() <= argument_range.from()) {
4130 result.SetElementsInBothSets();
4131 result.SetElementsInFirstSet();
4132 } else {
4133 // There is overlap, and neither is a subrange of the other
4134 result.SetElementsInFirstSet();
4135 result.SetElementsInSecondSet();
4136 result.SetElementsInBothSets();
4137 }
4138 if (result.NonTrivialIntersection()) {
4139 // The result is as (im)precise as we can possibly make it.
4140 return result;
4141 }
4142 // Progress the range(s) with minimal to-character.
4143 uc16 word_to = word_range.to();
4144 uc16 argument_to = argument_range.to();
4145 if (argument_to <= word_to) {
4146 j++;
4147 if (j < range->length()) {
4148 argument_range = range->at(j);
4149 }
4150 }
4151 if (word_to <= argument_to) {
4152 i += 2;
4153 if (i < kWordRangeCount) {
4154 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4155 }
4156 }
4157 }
4158 // Check if anything wasn't compared in the loop.
4159 if (i < kWordRangeCount) {
4160 // word range contains something not in argument range.
4161 result.SetElementsInSecondSet();
4162 } else if (j < range->length()) {
4163 // Argument range contains something not in word range.
4164 result.SetElementsInFirstSet();
4165 }
4166
4167 return result;
4168}
4169
4170
ager@chromium.org38e4c712009-11-11 09:11:58 +00004171static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4172 int bottom,
4173 int top) {
4174 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4175 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4176 // this table is correct.
4177 // 0x0600 - 0x0fff
4178 // 0x1100 - 0x1cff
4179 // 0x2000 - 0x20ff
4180 // 0x2200 - 0x23ff
4181 // 0x2500 - 0x2bff
4182 // 0x2e00 - 0xa5ff
4183 // 0xa800 - 0xfaff
4184 // 0xfc00 - 0xfeff
4185 const int boundary_count = 18;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004186 int boundaries[] = {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004187 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4188 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4189
4190 // Special ASCII rule from spec can save us some work here.
4191 if (bottom == 0x80 && top == 0xffff) return;
4192
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004193 if (top <= boundaries[0]) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004194 CharacterRange range(bottom, top);
4195 range.AddCaseEquivalents(ranges, false);
4196 return;
4197 }
4198
4199 // Split up very large ranges. This helps remove ranges where there are no
4200 // case mappings.
4201 for (int i = 0; i < boundary_count; i++) {
4202 if (bottom < boundaries[i] && top >= boundaries[i]) {
4203 AddUncanonicals(ranges, bottom, boundaries[i] - 1);
4204 AddUncanonicals(ranges, boundaries[i], top);
4205 return;
4206 }
4207 }
4208
4209 // If we are completely in a zone with no case mappings then we are done.
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004210 for (int i = 0; i < boundary_count; i += 2) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004211 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4212#ifdef DEBUG
4213 for (int j = bottom; j <= top; j++) {
4214 unsigned current_char = j;
4215 int length = uncanonicalize.get(current_char, '\0', chars);
4216 for (int k = 0; k < length; k++) {
4217 ASSERT(chars[k] == current_char);
4218 }
4219 }
4220#endif
4221 return;
4222 }
4223 }
4224
4225 // Step through the range finding equivalent characters.
4226 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4227 for (int i = bottom; i <= top; i++) {
4228 int length = uncanonicalize.get(i, '\0', chars);
4229 for (int j = 0; j < length; j++) {
4230 uc32 chr = chars[j];
4231 if (chr != i && (chr < bottom || chr > top)) {
4232 characters->Add(chr);
4233 }
4234 }
4235 }
4236
4237 // Step through the equivalent characters finding simple ranges and
4238 // adding ranges to the character class.
4239 if (characters->length() > 0) {
4240 int new_from = characters->at(0);
4241 int new_to = new_from;
4242 for (int i = 1; i < characters->length(); i++) {
4243 int chr = characters->at(i);
4244 if (chr == new_to + 1) {
4245 new_to++;
4246 } else {
4247 if (new_to == new_from) {
4248 ranges->Add(CharacterRange::Singleton(new_from));
4249 } else {
4250 ranges->Add(CharacterRange(new_from, new_to));
4251 }
4252 new_from = new_to = chr;
4253 }
4254 }
4255 if (new_to == new_from) {
4256 ranges->Add(CharacterRange::Singleton(new_from));
4257 } else {
4258 ranges->Add(CharacterRange(new_from, new_to));
4259 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004260 }
4261}
4262
4263
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004264ZoneList<CharacterRange>* CharacterSet::ranges() {
4265 if (ranges_ == NULL) {
4266 ranges_ = new ZoneList<CharacterRange>(2);
4267 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4268 }
4269 return ranges_;
4270}
4271
4272
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004273// Move a number of elements in a zonelist to another position
4274// in the same list. Handles overlapping source and target areas.
4275static void MoveRanges(ZoneList<CharacterRange>* list,
4276 int from,
4277 int to,
4278 int count) {
4279 // Ranges are potentially overlapping.
4280 if (from < to) {
4281 for (int i = count - 1; i >= 0; i--) {
4282 list->at(to + i) = list->at(from + i);
4283 }
4284 } else {
4285 for (int i = 0; i < count; i++) {
4286 list->at(to + i) = list->at(from + i);
4287 }
4288 }
4289}
4290
4291
4292static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4293 int count,
4294 CharacterRange insert) {
4295 // Inserts a range into list[0..count[, which must be sorted
4296 // by from value and non-overlapping and non-adjacent, using at most
4297 // list[0..count] for the result. Returns the number of resulting
4298 // canonicalized ranges. Inserting a range may collapse existing ranges into
4299 // fewer ranges, so the return value can be anything in the range 1..count+1.
4300 uc16 from = insert.from();
4301 uc16 to = insert.to();
4302 int start_pos = 0;
4303 int end_pos = count;
4304 for (int i = count - 1; i >= 0; i--) {
4305 CharacterRange current = list->at(i);
4306 if (current.from() > to + 1) {
4307 end_pos = i;
4308 } else if (current.to() + 1 < from) {
4309 start_pos = i + 1;
4310 break;
4311 }
4312 }
4313
4314 // Inserted range overlaps, or is adjacent to, ranges at positions
4315 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4316 // not affected by the insertion.
4317 // If start_pos == end_pos, the range must be inserted before start_pos.
4318 // if start_pos < end_pos, the entire range from start_pos to end_pos
4319 // must be merged with the insert range.
4320
4321 if (start_pos == end_pos) {
4322 // Insert between existing ranges at position start_pos.
4323 if (start_pos < count) {
4324 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4325 }
4326 list->at(start_pos) = insert;
4327 return count + 1;
4328 }
4329 if (start_pos + 1 == end_pos) {
4330 // Replace single existing range at position start_pos.
4331 CharacterRange to_replace = list->at(start_pos);
4332 int new_from = Min(to_replace.from(), from);
4333 int new_to = Max(to_replace.to(), to);
4334 list->at(start_pos) = CharacterRange(new_from, new_to);
4335 return count;
4336 }
4337 // Replace a number of existing ranges from start_pos to end_pos - 1.
4338 // Move the remaining ranges down.
4339
4340 int new_from = Min(list->at(start_pos).from(), from);
4341 int new_to = Max(list->at(end_pos - 1).to(), to);
4342 if (end_pos < count) {
4343 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4344 }
4345 list->at(start_pos) = CharacterRange(new_from, new_to);
4346 return count - (end_pos - start_pos) + 1;
4347}
4348
4349
4350void CharacterSet::Canonicalize() {
4351 // Special/default classes are always considered canonical. The result
4352 // of calling ranges() will be sorted.
4353 if (ranges_ == NULL) return;
4354 CharacterRange::Canonicalize(ranges_);
4355}
4356
4357
4358void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4359 if (character_ranges->length() <= 1) return;
4360 // Check whether ranges are already canonical (increasing, non-overlapping,
4361 // non-adjacent).
4362 int n = character_ranges->length();
4363 int max = character_ranges->at(0).to();
4364 int i = 1;
4365 while (i < n) {
4366 CharacterRange current = character_ranges->at(i);
4367 if (current.from() <= max + 1) {
4368 break;
4369 }
4370 max = current.to();
4371 i++;
4372 }
4373 // Canonical until the i'th range. If that's all of them, we are done.
4374 if (i == n) return;
4375
4376 // The ranges at index i and forward are not canonicalized. Make them so by
4377 // doing the equivalent of insertion sort (inserting each into the previous
4378 // list, in order).
4379 // Notice that inserting a range can reduce the number of ranges in the
4380 // result due to combining of adjacent and overlapping ranges.
4381 int read = i; // Range to insert.
4382 int num_canonical = i; // Length of canonicalized part of list.
4383 do {
4384 num_canonical = InsertRangeInCanonicalList(character_ranges,
4385 num_canonical,
4386 character_ranges->at(read));
4387 read++;
4388 } while (read < n);
4389 character_ranges->Rewind(num_canonical);
4390
4391 ASSERT(CharacterRange::IsCanonical(character_ranges));
4392}
4393
4394
4395// Utility function for CharacterRange::Merge. Adds a range at the end of
4396// a canonicalized range list, if necessary merging the range with the last
4397// range of the list.
4398static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4399 if (set == NULL) return;
4400 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4401 int n = set->length();
4402 if (n > 0) {
4403 CharacterRange lastRange = set->at(n - 1);
4404 if (lastRange.to() == range.from() - 1) {
4405 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4406 return;
4407 }
4408 }
4409 set->Add(range);
4410}
4411
4412
4413static void AddRangeToSelectedSet(int selector,
4414 ZoneList<CharacterRange>* first_set,
4415 ZoneList<CharacterRange>* second_set,
4416 ZoneList<CharacterRange>* intersection_set,
4417 CharacterRange range) {
4418 switch (selector) {
4419 case kInsideFirst:
4420 AddRangeToSet(first_set, range);
4421 break;
4422 case kInsideSecond:
4423 AddRangeToSet(second_set, range);
4424 break;
4425 case kInsideBoth:
4426 AddRangeToSet(intersection_set, range);
4427 break;
4428 }
4429}
4430
4431
4432
4433void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4434 ZoneList<CharacterRange>* second_set,
4435 ZoneList<CharacterRange>* first_set_only_out,
4436 ZoneList<CharacterRange>* second_set_only_out,
4437 ZoneList<CharacterRange>* both_sets_out) {
4438 // Inputs are canonicalized.
4439 ASSERT(CharacterRange::IsCanonical(first_set));
4440 ASSERT(CharacterRange::IsCanonical(second_set));
4441 // Outputs are empty, if applicable.
4442 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4443 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4444 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4445
4446 // Merge sets by iterating through the lists in order of lowest "from" value,
4447 // and putting intervals into one of three sets.
4448
4449 if (first_set->length() == 0) {
4450 second_set_only_out->AddAll(*second_set);
4451 return;
4452 }
4453 if (second_set->length() == 0) {
4454 first_set_only_out->AddAll(*first_set);
4455 return;
4456 }
4457 // Indices into input lists.
4458 int i1 = 0;
4459 int i2 = 0;
4460 // Cache length of input lists.
4461 int n1 = first_set->length();
4462 int n2 = second_set->length();
4463 // Current range. May be invalid if state is kInsideNone.
4464 int from = 0;
4465 int to = -1;
4466 // Where current range comes from.
4467 int state = kInsideNone;
4468
4469 while (i1 < n1 || i2 < n2) {
4470 CharacterRange next_range;
4471 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004472 if (i2 == n2 ||
4473 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4474 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004475 next_range = first_set->at(i1++);
4476 range_source = kInsideFirst;
4477 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004478 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004479 next_range = second_set->at(i2++);
4480 range_source = kInsideSecond;
4481 }
4482 if (to < next_range.from()) {
4483 // Ranges disjoint: |current| |next|
4484 AddRangeToSelectedSet(state,
4485 first_set_only_out,
4486 second_set_only_out,
4487 both_sets_out,
4488 CharacterRange(from, to));
4489 from = next_range.from();
4490 to = next_range.to();
4491 state = range_source;
4492 } else {
4493 if (from < next_range.from()) {
4494 AddRangeToSelectedSet(state,
4495 first_set_only_out,
4496 second_set_only_out,
4497 both_sets_out,
4498 CharacterRange(from, next_range.from()-1));
4499 }
4500 if (to < next_range.to()) {
4501 // Ranges overlap: |current|
4502 // |next|
4503 AddRangeToSelectedSet(state | range_source,
4504 first_set_only_out,
4505 second_set_only_out,
4506 both_sets_out,
4507 CharacterRange(next_range.from(), to));
4508 from = to + 1;
4509 to = next_range.to();
4510 state = range_source;
4511 } else {
4512 // Range included: |current| , possibly ending at same character.
4513 // |next|
4514 AddRangeToSelectedSet(
4515 state | range_source,
4516 first_set_only_out,
4517 second_set_only_out,
4518 both_sets_out,
4519 CharacterRange(next_range.from(), next_range.to()));
4520 from = next_range.to() + 1;
4521 // If ranges end at same character, both ranges are consumed completely.
4522 if (next_range.to() == to) state = kInsideNone;
4523 }
4524 }
4525 }
4526 AddRangeToSelectedSet(state,
4527 first_set_only_out,
4528 second_set_only_out,
4529 both_sets_out,
4530 CharacterRange(from, to));
4531}
4532
4533
4534void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4535 ZoneList<CharacterRange>* negated_ranges) {
4536 ASSERT(CharacterRange::IsCanonical(ranges));
4537 ASSERT_EQ(0, negated_ranges->length());
4538 int range_count = ranges->length();
4539 uc16 from = 0;
4540 int i = 0;
4541 if (range_count > 0 && ranges->at(0).from() == 0) {
4542 from = ranges->at(0).to();
4543 i = 1;
4544 }
4545 while (i < range_count) {
4546 CharacterRange range = ranges->at(i);
4547 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4548 from = range.to();
4549 i++;
4550 }
4551 if (from < String::kMaxUC16CharCode) {
4552 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4553 }
4554}
4555
4556
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004557
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004558// -------------------------------------------------------------------
4559// Interest propagation
4560
4561
4562RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4563 for (int i = 0; i < siblings_.length(); i++) {
4564 RegExpNode* sibling = siblings_.Get(i);
4565 if (sibling->info()->Matches(info))
4566 return sibling;
4567 }
4568 return NULL;
4569}
4570
4571
4572RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4573 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004574 siblings_.Ensure(this);
4575 RegExpNode* result = TryGetSibling(info);
4576 if (result != NULL) return result;
4577 result = this->Clone();
4578 NodeInfo* new_info = result->info();
4579 new_info->ResetCompilationState();
4580 new_info->AddFromPreceding(info);
4581 AddSibling(result);
4582 *cloned = true;
4583 return result;
4584}
4585
4586
4587template <class C>
4588static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4589 NodeInfo full_info(*node->info());
4590 full_info.AddFromPreceding(info);
4591 bool cloned = false;
4592 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4593}
4594
4595
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004596// -------------------------------------------------------------------
4597// Splay tree
4598
4599
4600OutSet* OutSet::Extend(unsigned value) {
4601 if (Get(value))
4602 return this;
4603 if (successors() != NULL) {
4604 for (int i = 0; i < successors()->length(); i++) {
4605 OutSet* successor = successors()->at(i);
4606 if (successor->Get(value))
4607 return successor;
4608 }
4609 } else {
4610 successors_ = new ZoneList<OutSet*>(2);
4611 }
4612 OutSet* result = new OutSet(first_, remaining_);
4613 result->Set(value);
4614 successors()->Add(result);
4615 return result;
4616}
4617
4618
4619void OutSet::Set(unsigned value) {
4620 if (value < kFirstLimit) {
4621 first_ |= (1 << value);
4622 } else {
4623 if (remaining_ == NULL)
4624 remaining_ = new ZoneList<unsigned>(1);
4625 if (remaining_->is_empty() || !remaining_->Contains(value))
4626 remaining_->Add(value);
4627 }
4628}
4629
4630
4631bool OutSet::Get(unsigned value) {
4632 if (value < kFirstLimit) {
4633 return (first_ & (1 << value)) != 0;
4634 } else if (remaining_ == NULL) {
4635 return false;
4636 } else {
4637 return remaining_->Contains(value);
4638 }
4639}
4640
4641
4642const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4643const DispatchTable::Entry DispatchTable::Config::kNoValue;
4644
4645
4646void DispatchTable::AddRange(CharacterRange full_range, int value) {
4647 CharacterRange current = full_range;
4648 if (tree()->is_empty()) {
4649 // If this is the first range we just insert into the table.
4650 ZoneSplayTree<Config>::Locator loc;
4651 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4652 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4653 return;
4654 }
4655 // First see if there is a range to the left of this one that
4656 // overlaps.
4657 ZoneSplayTree<Config>::Locator loc;
4658 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4659 Entry* entry = &loc.value();
4660 // If we've found a range that overlaps with this one, and it
4661 // starts strictly to the left of this one, we have to fix it
4662 // because the following code only handles ranges that start on
4663 // or after the start point of the range we're adding.
4664 if (entry->from() < current.from() && entry->to() >= current.from()) {
4665 // Snap the overlapping range in half around the start point of
4666 // the range we're adding.
4667 CharacterRange left(entry->from(), current.from() - 1);
4668 CharacterRange right(current.from(), entry->to());
4669 // The left part of the overlapping range doesn't overlap.
4670 // Truncate the whole entry to be just the left part.
4671 entry->set_to(left.to());
4672 // The right part is the one that overlaps. We add this part
4673 // to the map and let the next step deal with merging it with
4674 // the range we're adding.
4675 ZoneSplayTree<Config>::Locator loc;
4676 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4677 loc.set_value(Entry(right.from(),
4678 right.to(),
4679 entry->out_set()));
4680 }
4681 }
4682 while (current.is_valid()) {
4683 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4684 (loc.value().from() <= current.to()) &&
4685 (loc.value().to() >= current.from())) {
4686 Entry* entry = &loc.value();
4687 // We have overlap. If there is space between the start point of
4688 // the range we're adding and where the overlapping range starts
4689 // then we have to add a range covering just that space.
4690 if (current.from() < entry->from()) {
4691 ZoneSplayTree<Config>::Locator ins;
4692 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4693 ins.set_value(Entry(current.from(),
4694 entry->from() - 1,
4695 empty()->Extend(value)));
4696 current.set_from(entry->from());
4697 }
4698 ASSERT_EQ(current.from(), entry->from());
4699 // If the overlapping range extends beyond the one we want to add
4700 // we have to snap the right part off and add it separately.
4701 if (entry->to() > current.to()) {
4702 ZoneSplayTree<Config>::Locator ins;
4703 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4704 ins.set_value(Entry(current.to() + 1,
4705 entry->to(),
4706 entry->out_set()));
4707 entry->set_to(current.to());
4708 }
4709 ASSERT(entry->to() <= current.to());
4710 // The overlapping range is now completely contained by the range
4711 // we're adding so we can just update it and move the start point
4712 // of the range we're adding just past it.
4713 entry->AddValue(value);
4714 // Bail out if the last interval ended at 0xFFFF since otherwise
4715 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004716 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004717 break;
4718 ASSERT(entry->to() + 1 > current.from());
4719 current.set_from(entry->to() + 1);
4720 } else {
4721 // There is no overlap so we can just add the range
4722 ZoneSplayTree<Config>::Locator ins;
4723 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4724 ins.set_value(Entry(current.from(),
4725 current.to(),
4726 empty()->Extend(value)));
4727 break;
4728 }
4729 }
4730}
4731
4732
4733OutSet* DispatchTable::Get(uc16 value) {
4734 ZoneSplayTree<Config>::Locator loc;
4735 if (!tree()->FindGreatestLessThan(value, &loc))
4736 return empty();
4737 Entry* entry = &loc.value();
4738 if (value <= entry->to())
4739 return entry->out_set();
4740 else
4741 return empty();
4742}
4743
4744
4745// -------------------------------------------------------------------
4746// Analysis
4747
4748
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004749void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004750 StackLimitCheck check;
4751 if (check.HasOverflowed()) {
4752 fail("Stack overflow");
4753 return;
4754 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004755 if (that->info()->been_analyzed || that->info()->being_analyzed)
4756 return;
4757 that->info()->being_analyzed = true;
4758 that->Accept(this);
4759 that->info()->being_analyzed = false;
4760 that->info()->been_analyzed = true;
4761}
4762
4763
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004764void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004765 // nothing to do
4766}
4767
4768
ager@chromium.org8bb60582008-12-11 12:02:20 +00004769void TextNode::CalculateOffsets() {
4770 int element_count = elements()->length();
4771 // Set up the offsets of the elements relative to the start. This is a fixed
4772 // quantity since a TextNode can only contain fixed-width things.
4773 int cp_offset = 0;
4774 for (int i = 0; i < element_count; i++) {
4775 TextElement& elm = elements()->at(i);
4776 elm.cp_offset = cp_offset;
4777 if (elm.type == TextElement::ATOM) {
4778 cp_offset += elm.data.u_atom->data().length();
4779 } else {
4780 cp_offset++;
4781 Vector<const uc16> quarks = elm.data.u_atom->data();
4782 }
4783 }
4784}
4785
4786
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004787void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004788 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004789 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004790 }
4791 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004792 if (!has_failed()) {
4793 that->CalculateOffsets();
4794 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004795}
4796
4797
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004798void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004799 RegExpNode* target = that->on_success();
4800 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004801 if (!has_failed()) {
4802 // If the next node is interested in what it follows then this node
4803 // has to be interested too so it can pass the information on.
4804 that->info()->AddFromFollowing(target->info());
4805 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004806}
4807
4808
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004809void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004810 NodeInfo* info = that->info();
4811 for (int i = 0; i < that->alternatives()->length(); i++) {
4812 RegExpNode* node = that->alternatives()->at(i).node();
4813 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004814 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004815 // Anything the following nodes need to know has to be known by
4816 // this node also, so it can pass it on.
4817 info->AddFromFollowing(node->info());
4818 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004819}
4820
4821
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004822void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4823 NodeInfo* info = that->info();
4824 for (int i = 0; i < that->alternatives()->length(); i++) {
4825 RegExpNode* node = that->alternatives()->at(i).node();
4826 if (node != that->loop_node()) {
4827 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004828 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004829 info->AddFromFollowing(node->info());
4830 }
4831 }
4832 // Check the loop last since it may need the value of this node
4833 // to get a correct result.
4834 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004835 if (!has_failed()) {
4836 info->AddFromFollowing(that->loop_node()->info());
4837 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004838}
4839
4840
4841void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004842 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004843}
4844
4845
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004846void Analysis::VisitAssertion(AssertionNode* that) {
4847 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004848 AssertionNode::AssertionNodeType type = that->type();
4849 if (type == AssertionNode::AT_BOUNDARY ||
4850 type == AssertionNode::AT_NON_BOUNDARY) {
4851 // Check if the following character is known to be a word character
4852 // or known to not be a word character.
4853 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4854
4855 CharacterRange::Canonicalize(following_chars);
4856
4857 SetRelation word_relation =
4858 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004859 if (word_relation.Disjoint()) {
4860 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004861 // Following character is definitely *not* a word character.
4862 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004863 AssertionNode::AFTER_WORD_CHARACTER :
4864 AssertionNode::AFTER_NONWORD_CHARACTER;
4865 that->set_type(type);
4866 } else if (word_relation.ContainedIn()) {
4867 // Following character is definitely a word character.
4868 type = (type == AssertionNode::AT_BOUNDARY) ?
4869 AssertionNode::AFTER_NONWORD_CHARACTER :
4870 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004871 that->set_type(type);
4872 }
4873 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004874}
4875
4876
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004877ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4878 if (first_character_set_ == NULL) {
4879 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4880 // If we can't find an exact solution within the budget, we
4881 // set the value to the set of every character, i.e., all characters
4882 // are possible.
4883 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4884 all_set->Add(CharacterRange::Everything());
4885 first_character_set_ = all_set;
4886 }
4887 }
4888 return first_character_set_;
4889}
4890
4891
4892int RegExpNode::ComputeFirstCharacterSet(int budget) {
4893 // Default behavior is to not be able to determine the first character.
4894 return kComputeFirstCharacterSetFail;
4895}
4896
4897
4898int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
4899 budget--;
4900 if (budget >= 0) {
4901 // Find loop min-iteration. It's the value of the guarded choice node
4902 // with a GEQ guard, if any.
4903 int min_repetition = 0;
4904
4905 for (int i = 0; i <= 1; i++) {
4906 GuardedAlternative alternative = alternatives()->at(i);
4907 ZoneList<Guard*>* guards = alternative.guards();
4908 if (guards != NULL && guards->length() > 0) {
4909 Guard* guard = guards->at(0);
4910 if (guard->op() == Guard::GEQ) {
4911 min_repetition = guard->value();
4912 break;
4913 }
4914 }
4915 }
4916
4917 budget = loop_node()->ComputeFirstCharacterSet(budget);
4918 if (budget >= 0) {
4919 ZoneList<CharacterRange>* character_set =
4920 loop_node()->first_character_set();
4921 if (body_can_be_zero_length() || min_repetition == 0) {
4922 budget = continue_node()->ComputeFirstCharacterSet(budget);
4923 if (budget < 0) return budget;
4924 ZoneList<CharacterRange>* body_set =
4925 continue_node()->first_character_set();
4926 ZoneList<CharacterRange>* union_set =
4927 new ZoneList<CharacterRange>(Max(character_set->length(),
4928 body_set->length()));
4929 CharacterRange::Merge(character_set,
4930 body_set,
4931 union_set,
4932 union_set,
4933 union_set);
4934 character_set = union_set;
4935 }
4936 set_first_character_set(character_set);
4937 }
4938 }
4939 return budget;
4940}
4941
4942
4943int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
4944 budget--;
4945 if (budget >= 0) {
4946 GuardedAlternative successor = this->alternatives()->at(1);
4947 RegExpNode* successor_node = successor.node();
4948 budget = successor_node->ComputeFirstCharacterSet(budget);
4949 if (budget >= 0) {
4950 set_first_character_set(successor_node->first_character_set());
4951 }
4952 }
4953 return budget;
4954}
4955
4956
4957// The first character set of an EndNode is unknowable. Just use the
4958// default implementation that fails and returns all characters as possible.
4959
4960
4961int AssertionNode::ComputeFirstCharacterSet(int budget) {
4962 budget -= 1;
4963 if (budget >= 0) {
4964 switch (type_) {
4965 case AT_END: {
4966 set_first_character_set(new ZoneList<CharacterRange>(0));
4967 break;
4968 }
4969 case AT_START:
4970 case AT_BOUNDARY:
4971 case AT_NON_BOUNDARY:
4972 case AFTER_NEWLINE:
4973 case AFTER_NONWORD_CHARACTER:
4974 case AFTER_WORD_CHARACTER: {
4975 ASSERT_NOT_NULL(on_success());
4976 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00004977 if (budget >= 0) {
4978 set_first_character_set(on_success()->first_character_set());
4979 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004980 break;
4981 }
4982 }
4983 }
4984 return budget;
4985}
4986
4987
4988int ActionNode::ComputeFirstCharacterSet(int budget) {
4989 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
4990 budget--;
4991 if (budget >= 0) {
4992 ASSERT_NOT_NULL(on_success());
4993 budget = on_success()->ComputeFirstCharacterSet(budget);
4994 if (budget >= 0) {
4995 set_first_character_set(on_success()->first_character_set());
4996 }
4997 }
4998 return budget;
4999}
5000
5001
5002int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5003 // We don't know anything about the first character of a backreference
5004 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005005 // The potential first characters are the first characters of the capture,
5006 // and the first characters of the on_success node, depending on whether the
5007 // capture can be empty and whether it is known to be participating or known
5008 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005009 return kComputeFirstCharacterSetFail;
5010}
5011
5012
5013int TextNode::ComputeFirstCharacterSet(int budget) {
5014 budget--;
5015 if (budget >= 0) {
5016 ASSERT_NE(0, elements()->length());
5017 TextElement text = elements()->at(0);
5018 if (text.type == TextElement::ATOM) {
5019 RegExpAtom* atom = text.data.u_atom;
5020 ASSERT_NE(0, atom->length());
5021 uc16 first_char = atom->data()[0];
5022 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5023 range->Add(CharacterRange(first_char, first_char));
5024 set_first_character_set(range);
5025 } else {
5026 ASSERT(text.type == TextElement::CHAR_CLASS);
5027 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005028 ZoneList<CharacterRange>* ranges = char_class->ranges();
5029 // TODO(lrn): Canonicalize ranges when they are created
5030 // instead of waiting until now.
5031 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005032 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005033 int length = ranges->length();
5034 int new_length = length + 1;
5035 if (length > 0) {
5036 if (ranges->at(0).from() == 0) new_length--;
5037 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5038 new_length--;
5039 }
5040 }
5041 ZoneList<CharacterRange>* negated_ranges =
5042 new ZoneList<CharacterRange>(new_length);
5043 CharacterRange::Negate(ranges, negated_ranges);
5044 set_first_character_set(negated_ranges);
5045 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005046 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005047 }
5048 }
5049 }
5050 return budget;
5051}
5052
5053
5054
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005055// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005056// Dispatch table construction
5057
5058
5059void DispatchTableConstructor::VisitEnd(EndNode* that) {
5060 AddRange(CharacterRange::Everything());
5061}
5062
5063
5064void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5065 node->set_being_calculated(true);
5066 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5067 for (int i = 0; i < alternatives->length(); i++) {
5068 set_choice_index(i);
5069 alternatives->at(i).node()->Accept(this);
5070 }
5071 node->set_being_calculated(false);
5072}
5073
5074
5075class AddDispatchRange {
5076 public:
5077 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5078 : constructor_(constructor) { }
5079 void Call(uc32 from, DispatchTable::Entry entry);
5080 private:
5081 DispatchTableConstructor* constructor_;
5082};
5083
5084
5085void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5086 CharacterRange range(from, entry.to());
5087 constructor_->AddRange(range);
5088}
5089
5090
5091void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5092 if (node->being_calculated())
5093 return;
5094 DispatchTable* table = node->GetTable(ignore_case_);
5095 AddDispatchRange adder(this);
5096 table->ForEach(&adder);
5097}
5098
5099
5100void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5101 // TODO(160): Find the node that we refer back to and propagate its start
5102 // set back to here. For now we just accept anything.
5103 AddRange(CharacterRange::Everything());
5104}
5105
5106
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005107void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5108 RegExpNode* target = that->on_success();
5109 target->Accept(this);
5110}
5111
5112
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005113static int CompareRangeByFrom(const CharacterRange* a,
5114 const CharacterRange* b) {
5115 return Compare<uc16>(a->from(), b->from());
5116}
5117
5118
5119void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5120 ranges->Sort(CompareRangeByFrom);
5121 uc16 last = 0;
5122 for (int i = 0; i < ranges->length(); i++) {
5123 CharacterRange range = ranges->at(i);
5124 if (last < range.from())
5125 AddRange(CharacterRange(last, range.from() - 1));
5126 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005127 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005128 return;
5129 } else {
5130 last = range.to() + 1;
5131 }
5132 }
5133 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005134 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005135}
5136
5137
5138void DispatchTableConstructor::VisitText(TextNode* that) {
5139 TextElement elm = that->elements()->at(0);
5140 switch (elm.type) {
5141 case TextElement::ATOM: {
5142 uc16 c = elm.data.u_atom->data()[0];
5143 AddRange(CharacterRange(c, c));
5144 break;
5145 }
5146 case TextElement::CHAR_CLASS: {
5147 RegExpCharacterClass* tree = elm.data.u_char_class;
5148 ZoneList<CharacterRange>* ranges = tree->ranges();
5149 if (tree->is_negated()) {
5150 AddInverse(ranges);
5151 } else {
5152 for (int i = 0; i < ranges->length(); i++)
5153 AddRange(ranges->at(i));
5154 }
5155 break;
5156 }
5157 default: {
5158 UNIMPLEMENTED();
5159 }
5160 }
5161}
5162
5163
5164void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005165 RegExpNode* target = that->on_success();
5166 target->Accept(this);
5167}
5168
5169
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005170RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5171 bool ignore_case,
5172 bool is_multiline,
5173 Handle<String> pattern,
5174 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005175 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005176 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005177 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005178 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005179 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005180 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005181 0,
5182 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005183 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005184 RegExpNode* node = captured_body;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005185 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
5186 bool is_start_anchored = data->tree->IsAnchoredAtStart();
5187 int max_length = data->tree->max_match();
5188 if (!is_start_anchored) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005189 // Add a .*? at the beginning, outside the body capture, unless
5190 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005191 RegExpNode* loop_node =
5192 RegExpQuantifier::ToNode(0,
5193 RegExpTree::kInfinity,
5194 false,
5195 new RegExpCharacterClass('*'),
5196 &compiler,
5197 captured_body,
5198 data->contains_anchor);
5199
5200 if (data->contains_anchor) {
5201 // Unroll loop once, to take care of the case that might start
5202 // at the start of input.
5203 ChoiceNode* first_step_node = new ChoiceNode(2);
5204 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5205 first_step_node->AddAlternative(GuardedAlternative(
5206 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5207 node = first_step_node;
5208 } else {
5209 node = loop_node;
5210 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005211 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005212 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005213 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005214 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005215 if (analysis.has_failed()) {
5216 const char* error_message = analysis.error_message();
5217 return CompilationResult(error_message);
5218 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005219
5220 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005221
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005222 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005223#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005224 // Native regexp implementation.
5225
5226 NativeRegExpMacroAssembler::Mode mode =
5227 is_ascii ? NativeRegExpMacroAssembler::ASCII
5228 : NativeRegExpMacroAssembler::UC16;
5229
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005230#if V8_TARGET_ARCH_IA32
5231 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5232#elif V8_TARGET_ARCH_X64
5233 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5234#elif V8_TARGET_ARCH_ARM
5235 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005236#endif
5237
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005238#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005239 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005240 EmbeddedVector<byte, 1024> codes;
5241 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005242#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005243
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005244 // Inserted here, instead of in Assembler, because it depends on information
5245 // in the AST that isn't replicated in the Node structure.
5246 static const int kMaxBacksearchLimit = 1024;
5247 if (is_end_anchored &&
5248 !is_start_anchored &&
5249 max_length < kMaxBacksearchLimit) {
5250 macro_assembler.SetCurrentPositionFromEnd(max_length);
5251 }
5252
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005253 return compiler.Assemble(&macro_assembler,
5254 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005255 data->capture_count,
5256 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005257}
5258
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005259
5260int OffsetsVector::static_offsets_vector_[
5261 OffsetsVector::kStaticOffsetsVectorSize];
5262
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005263}} // namespace v8::internal