blob: 8af472d39e18f6a65933c7191e808074d9aa0529 [file] [log] [blame]
ager@chromium.org381abbb2009-02-25 13:23:22 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
ager@chromium.orga74f0da2008-12-03 16:05:52 +000030#include "ast.h"
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +000031#include "compiler.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032#include "execution.h"
33#include "factory.h"
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +000034#include "jsregexp.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "platform.h"
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000036#include "runtime.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "top.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000038#include "compilation-cache.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000039#include "string-stream.h"
40#include "parser.h"
41#include "regexp-macro-assembler.h"
42#include "regexp-macro-assembler-tracer.h"
43#include "regexp-macro-assembler-irregexp.h"
ager@chromium.org32912102009-01-16 10:38:43 +000044#include "regexp-stack.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000045
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000046#ifdef V8_NATIVE_REGEXP
kasperl@chromium.org71affb52009-05-26 05:44:31 +000047#if V8_TARGET_ARCH_IA32
ager@chromium.org3a37e9b2009-04-27 09:26:21 +000048#include "ia32/regexp-macro-assembler-ia32.h"
ager@chromium.org9085a012009-05-11 19:22:57 +000049#elif V8_TARGET_ARCH_X64
ager@chromium.org9085a012009-05-11 19:22:57 +000050#include "x64/regexp-macro-assembler-x64.h"
51#elif V8_TARGET_ARCH_ARM
52#include "arm/regexp-macro-assembler-arm.h"
kasperl@chromium.org2abc4502009-07-02 07:00:29 +000053#else
54#error Unsupported target architecture.
ager@chromium.orga74f0da2008-12-03 16:05:52 +000055#endif
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000056#endif
ager@chromium.orga74f0da2008-12-03 16:05:52 +000057
58#include "interpreter-irregexp.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000059
ager@chromium.orga74f0da2008-12-03 16:05:52 +000060
kasperl@chromium.org71affb52009-05-26 05:44:31 +000061namespace v8 {
62namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063
64
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000065Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
66 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067 Handle<String> flags,
68 bool* has_pending_exception) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000069 // Ensure that the constructor function has been loaded.
70 if (!constructor->IsLoaded()) {
71 LoadLazy(constructor, has_pending_exception);
ager@chromium.orga74f0da2008-12-03 16:05:52 +000072 if (*has_pending_exception) return Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073 }
74 // Call the construct code with 2 arguments.
75 Object** argv[2] = { Handle<Object>::cast(pattern).location(),
76 Handle<Object>::cast(flags).location() };
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000077 return Execution::New(constructor, 2, argv, has_pending_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000078}
79
80
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000081static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
82 int flags = JSRegExp::NONE;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000083 for (int i = 0; i < str->length(); i++) {
84 switch (str->Get(i)) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000085 case 'i':
86 flags |= JSRegExp::IGNORE_CASE;
87 break;
88 case 'g':
89 flags |= JSRegExp::GLOBAL;
90 break;
91 case 'm':
92 flags |= JSRegExp::MULTILINE;
93 break;
94 }
95 }
96 return JSRegExp::Flags(flags);
97}
98
99
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000100static inline void ThrowRegExpException(Handle<JSRegExp> re,
101 Handle<String> pattern,
102 Handle<String> error_text,
103 const char* message) {
104 Handle<JSArray> array = Factory::NewJSArray(2);
105 SetElement(array, 0, pattern);
106 SetElement(array, 1, error_text);
107 Handle<Object> regexp_err = Factory::NewSyntaxError(message, array);
108 Top::Throw(*regexp_err);
109}
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000110
111
ager@chromium.org8bb60582008-12-11 12:02:20 +0000112// Generic RegExp methods. Dispatches to implementation specific methods.
113
114
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000115Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
116 Handle<String> pattern,
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000117 Handle<String> flag_str) {
118 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
119 Handle<FixedArray> cached = CompilationCache::LookupRegExp(pattern, flags);
120 bool in_cache = !cached.is_null();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000121 LOG(RegExpCompileEvent(re, in_cache));
122
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000123 Handle<Object> result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000124 if (in_cache) {
125 re->set_data(*cached);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000126 return re;
127 }
128 FlattenString(pattern);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000129 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000130 RegExpCompileData parse_result;
131 FlatStringReader reader(pattern);
132 if (!ParseRegExp(&reader, flags.is_multiline(), &parse_result)) {
133 // Throw an exception if we fail to parse the pattern.
134 ThrowRegExpException(re,
135 pattern,
136 parse_result.error,
137 "malformed_regexp");
138 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000139 }
140
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000141 if (parse_result.simple && !flags.is_ignore_case()) {
142 // Parse-tree is a single atom that is equal to the pattern.
143 AtomCompile(re, pattern, flags, pattern);
144 } else if (parse_result.tree->IsAtom() &&
145 !flags.is_ignore_case() &&
146 parse_result.capture_count == 0) {
147 RegExpAtom* atom = parse_result.tree->AsAtom();
148 Vector<const uc16> atom_pattern = atom->data();
149 Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern);
150 AtomCompile(re, pattern, flags, atom_string);
151 } else {
152 IrregexpPrepare(re, pattern, flags, parse_result.capture_count);
153 }
154 ASSERT(re->data()->IsFixedArray());
155 // Compilation succeeded so the data is set on the regexp
156 // and we can store it in the cache.
157 Handle<FixedArray> data(FixedArray::cast(re->data()));
158 CompilationCache::PutRegExp(pattern, flags, data);
159
160 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000161}
162
163
164Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
165 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000166 int index,
167 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000168 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000169 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000170 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000171 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000172 Handle<Object> result =
173 IrregexpExec(regexp, subject, index, last_match_info);
ager@chromium.org6f10e412009-02-13 10:11:16 +0000174 ASSERT(!result.is_null() || Top::has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000175 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000176 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000177 default:
178 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000179 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000180 }
181}
182
183
ager@chromium.org8bb60582008-12-11 12:02:20 +0000184// RegExp Atom implementation: Simple string search using indexOf.
185
186
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000187void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
188 Handle<String> pattern,
189 JSRegExp::Flags flags,
190 Handle<String> match_pattern) {
191 Factory::SetRegExpAtomData(re,
192 JSRegExp::ATOM,
193 pattern,
194 flags,
195 match_pattern);
196}
197
198
199static void SetAtomLastCapture(FixedArray* array,
200 String* subject,
201 int from,
202 int to) {
203 NoHandleAllocation no_handles;
204 RegExpImpl::SetLastCaptureCount(array, 2);
205 RegExpImpl::SetLastSubject(array, subject);
206 RegExpImpl::SetLastInput(array, subject);
207 RegExpImpl::SetCapture(array, 0, from);
208 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000209}
210
211
212Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
213 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000214 int index,
215 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000216 Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex)));
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000217
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000218 uint32_t start_index = index;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000219
ager@chromium.org7c537e22008-10-16 08:43:32 +0000220 int value = Runtime::StringMatch(subject, needle, start_index);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000221 if (value == -1) return Factory::null_value();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000222 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000223
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000224 {
225 NoHandleAllocation no_handles;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000226 FixedArray* array = FixedArray::cast(last_match_info->elements());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000227 SetAtomLastCapture(array, *subject, value, value + needle->length());
228 }
229 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000230}
231
232
ager@chromium.org8bb60582008-12-11 12:02:20 +0000233// Irregexp implementation.
234
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000235// Ensures that the regexp object contains a compiled version of the
236// source for either ASCII or non-ASCII strings.
237// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000238// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000239// If compilation fails, an exception is thrown and this function
240// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000241bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000242 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000243#ifdef V8_NATIVE_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000244 if (compiled_code->IsCode()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000245#else // ! V8_NATIVE_REGEXP (RegExp interpreter code)
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000246 if (compiled_code->IsByteArray()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000247#endif
248 return CompileIrregexp(re, is_ascii);
249}
ager@chromium.org8bb60582008-12-11 12:02:20 +0000250
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000251
252bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000253 // Compile the RegExp.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000254 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000255 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
256 if (entry->IsJSObject()) {
257 // If it's a JSObject, a previous compilation failed and threw this object.
258 // Re-throw the object without trying again.
259 Top::Throw(entry);
260 return false;
261 }
262 ASSERT(entry->IsTheHole());
ager@chromium.org8bb60582008-12-11 12:02:20 +0000263
264 JSRegExp::Flags flags = re->GetFlags();
265
266 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000267 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000268 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000269 }
270
271 RegExpCompileData compile_data;
272 FlatStringReader reader(pattern);
273 if (!ParseRegExp(&reader, flags.is_multiline(), &compile_data)) {
274 // Throw an exception if we fail to parse the pattern.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000275 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000276 ThrowRegExpException(re,
277 pattern,
278 compile_data.error,
279 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000280 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000281 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000282 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000283 RegExpEngine::Compile(&compile_data,
284 flags.is_ignore_case(),
285 flags.is_multiline(),
286 pattern,
287 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000288 if (result.error_message != NULL) {
289 // Unable to compile regexp.
290 Handle<JSArray> array = Factory::NewJSArray(2);
291 SetElement(array, 0, pattern);
292 SetElement(array,
293 1,
294 Factory::NewStringFromUtf8(CStrVector(result.error_message)));
295 Handle<Object> regexp_err =
296 Factory::NewSyntaxError("malformed_regexp", array);
297 Top::Throw(*regexp_err);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000298 re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000299 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000300 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000301
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000302 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
303 data->set(JSRegExp::code_index(is_ascii), result.code);
304 int register_max = IrregexpMaxRegisterCount(*data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000305 if (result.num_registers > register_max) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000306 SetIrregexpMaxRegisterCount(*data, result.num_registers);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000307 }
308
309 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000310}
311
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000312
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000313int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
314 return Smi::cast(
315 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000316}
317
318
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000319void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
320 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000321}
322
323
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000324int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
325 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000326}
327
328
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000329int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
330 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000331}
332
333
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000334ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000335 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000336}
337
338
339Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000340 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000341}
342
343
344void RegExpImpl::IrregexpPrepare(Handle<JSRegExp> re,
345 Handle<String> pattern,
346 JSRegExp::Flags flags,
347 int capture_count) {
348 // Initialize compiled code entries to null.
349 Factory::SetRegExpIrregexpData(re,
350 JSRegExp::IRREGEXP,
351 pattern,
352 flags,
353 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000354}
355
356
ager@chromium.org41826e72009-03-30 13:30:57 +0000357Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000358 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000359 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000360 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000361 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000362
ager@chromium.org8bb60582008-12-11 12:02:20 +0000363 // Prepare space for the return values.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000364 int number_of_capture_registers =
ager@chromium.org41826e72009-03-30 13:30:57 +0000365 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000366
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000367#ifndef V8_NATIVE_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000368#ifdef DEBUG
369 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000370 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000371 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
372 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
373 }
374#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000375#endif
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000376
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000377 if (!subject->IsFlat()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000378 FlattenString(subject);
379 }
380
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000381 last_match_info->EnsureSize(number_of_capture_registers + kLastMatchOverhead);
382
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000383 Handle<FixedArray> array;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000384
ager@chromium.org41826e72009-03-30 13:30:57 +0000385 // Dispatch to the correct RegExp implementation.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000386 Handle<FixedArray> regexp(FixedArray::cast(jsregexp->data()));
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000387
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000388#ifdef V8_NATIVE_REGEXP
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000389
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000390 OffsetsVector captures(number_of_capture_registers);
391 int* captures_vector = captures.vector();
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000392 NativeRegExpMacroAssembler::Result res;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000393 do {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000394 bool is_ascii = subject->IsAsciiRepresentation();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000395 if (!EnsureCompiledIrregexp(jsregexp, is_ascii)) {
396 return Handle<Object>::null();
397 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000398 Handle<Code> code(RegExpImpl::IrregexpNativeCode(*regexp, is_ascii));
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000399 res = NativeRegExpMacroAssembler::Match(code,
400 subject,
401 captures_vector,
402 captures.length(),
403 previous_index);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000404 // If result is RETRY, the string have changed representation, and we
405 // must restart from scratch.
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000406 } while (res == NativeRegExpMacroAssembler::RETRY);
407 if (res == NativeRegExpMacroAssembler::EXCEPTION) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000408 ASSERT(Top::has_pending_exception());
409 return Handle<Object>::null();
410 }
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000411 ASSERT(res == NativeRegExpMacroAssembler::SUCCESS
412 || res == NativeRegExpMacroAssembler::FAILURE);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000413
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000414 if (res != NativeRegExpMacroAssembler::SUCCESS) return Factory::null_value();
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000415
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000416 array = Handle<FixedArray>(FixedArray::cast(last_match_info->elements()));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000417 ASSERT(array->length() >= number_of_capture_registers + kLastMatchOverhead);
418 // The captures come in (start, end+1) pairs.
419 for (int i = 0; i < number_of_capture_registers; i += 2) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000420 // Capture values are relative to start_offset only.
421 // Convert them to be relative to start of string.
422 if (captures_vector[i] >= 0) {
423 captures_vector[i] += previous_index;
424 }
425 if (captures_vector[i + 1] >= 0) {
426 captures_vector[i + 1] += previous_index;
427 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000428 SetCapture(*array, i, captures_vector[i]);
429 SetCapture(*array, i + 1, captures_vector[i + 1]);
430 }
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000431
432#else // ! V8_NATIVE_REGEXP
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000433
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000434 bool is_ascii = subject->IsAsciiRepresentation();
435 if (!EnsureCompiledIrregexp(jsregexp, is_ascii)) {
436 return Handle<Object>::null();
437 }
438 // Now that we have done EnsureCompiledIrregexp we can get the number of
439 // registers.
440 int number_of_registers =
441 IrregexpNumberOfRegisters(FixedArray::cast(jsregexp->data()));
442 OffsetsVector registers(number_of_registers);
443 int* register_vector = registers.vector();
444 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
445 register_vector[i] = -1;
446 }
447 Handle<ByteArray> byte_codes(IrregexpByteCode(*regexp, is_ascii));
448
449 if (!IrregexpInterpreter::Match(byte_codes,
450 subject,
451 register_vector,
452 previous_index)) {
453 return Factory::null_value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000454 }
455
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000456 array = Handle<FixedArray>(FixedArray::cast(last_match_info->elements()));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000457 ASSERT(array->length() >= number_of_capture_registers + kLastMatchOverhead);
458 // The captures come in (start, end+1) pairs.
459 for (int i = 0; i < number_of_capture_registers; i += 2) {
460 SetCapture(*array, i, register_vector[i]);
461 SetCapture(*array, i + 1, register_vector[i + 1]);
462 }
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000463
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000464#endif // V8_NATIVE_REGEXP
465
466 SetLastCaptureCount(*array, number_of_capture_registers);
467 SetLastSubject(*array, *subject);
468 SetLastInput(*array, *subject);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000469
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000470 return last_match_info;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000471}
472
473
474// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000475// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000476//
477// The Irregexp regular expression engine is intended to be a complete
478// implementation of ECMAScript regular expressions. It generates either
479// bytecodes or native code.
480
481// The Irregexp regexp engine is structured in three steps.
482// 1) The parser generates an abstract syntax tree. See ast.cc.
483// 2) From the AST a node network is created. The nodes are all
484// subclasses of RegExpNode. The nodes represent states when
485// executing a regular expression. Several optimizations are
486// performed on the node network.
487// 3) From the nodes we generate either byte codes or native code
488// that can actually execute the regular expression (perform
489// the search). The code generation step is described in more
490// detail below.
491
492// Code generation.
493//
494// The nodes are divided into four main categories.
495// * Choice nodes
496// These represent places where the regular expression can
497// match in more than one way. For example on entry to an
498// alternation (foo|bar) or a repetition (*, +, ? or {}).
499// * Action nodes
500// These represent places where some action should be
501// performed. Examples include recording the current position
502// in the input string to a register (in order to implement
503// captures) or other actions on register for example in order
504// to implement the counters needed for {} repetitions.
505// * Matching nodes
506// These attempt to match some element part of the input string.
507// Examples of elements include character classes, plain strings
508// or back references.
509// * End nodes
510// These are used to implement the actions required on finding
511// a successful match or failing to find a match.
512//
513// The code generated (whether as byte codes or native code) maintains
514// some state as it runs. This consists of the following elements:
515//
516// * The capture registers. Used for string captures.
517// * Other registers. Used for counters etc.
518// * The current position.
519// * The stack of backtracking information. Used when a matching node
520// fails to find a match and needs to try an alternative.
521//
522// Conceptual regular expression execution model:
523//
524// There is a simple conceptual model of regular expression execution
525// which will be presented first. The actual code generated is a more
526// efficient simulation of the simple conceptual model:
527//
528// * Choice nodes are implemented as follows:
529// For each choice except the last {
530// push current position
531// push backtrack code location
532// <generate code to test for choice>
533// backtrack code location:
534// pop current position
535// }
536// <generate code to test for last choice>
537//
538// * Actions nodes are generated as follows
539// <push affected registers on backtrack stack>
540// <generate code to perform action>
541// push backtrack code location
542// <generate code to test for following nodes>
543// backtrack code location:
544// <pop affected registers to restore their state>
545// <pop backtrack location from stack and go to it>
546//
547// * Matching nodes are generated as follows:
548// if input string matches at current position
549// update current position
550// <generate code to test for following nodes>
551// else
552// <pop backtrack location from stack and go to it>
553//
554// Thus it can be seen that the current position is saved and restored
555// by the choice nodes, whereas the registers are saved and restored by
556// by the action nodes that manipulate them.
557//
558// The other interesting aspect of this model is that nodes are generated
559// at the point where they are needed by a recursive call to Emit(). If
560// the node has already been code generated then the Emit() call will
561// generate a jump to the previously generated code instead. In order to
562// limit recursion it is possible for the Emit() function to put the node
563// on a work list for later generation and instead generate a jump. The
564// destination of the jump is resolved later when the code is generated.
565//
566// Actual regular expression code generation.
567//
568// Code generation is actually more complicated than the above. In order
569// to improve the efficiency of the generated code some optimizations are
570// performed
571//
572// * Choice nodes have 1-character lookahead.
573// A choice node looks at the following character and eliminates some of
574// the choices immediately based on that character. This is not yet
575// implemented.
576// * Simple greedy loops store reduced backtracking information.
577// A quantifier like /.*foo/m will greedily match the whole input. It will
578// then need to backtrack to a point where it can match "foo". The naive
579// implementation of this would push each character position onto the
580// backtracking stack, then pop them off one by one. This would use space
581// proportional to the length of the input string. However since the "."
582// can only match in one way and always has a constant length (in this case
583// of 1) it suffices to store the current position on the top of the stack
584// once. Matching now becomes merely incrementing the current position and
585// backtracking becomes decrementing the current position and checking the
586// result against the stored current position. This is faster and saves
587// space.
588// * The current state is virtualized.
589// This is used to defer expensive operations until it is clear that they
590// are needed and to generate code for a node more than once, allowing
591// specialized an efficient versions of the code to be created. This is
592// explained in the section below.
593//
594// Execution state virtualization.
595//
596// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000597// manipulation in an object called the Trace. The Trace object can record a
598// current position offset, an optional backtrack code location on the top of
599// the virtualized backtrack stack and some register changes. When a node is
600// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000601// will emit code to bring the actual state into line with the virtual state.
602// Avoiding flushing the state can postpone some work (eg updates of capture
603// registers). Postponing work can save time when executing the regular
604// expression since it may be found that the work never has to be done as a
605// failure to match can occur. In addition it is much faster to jump to a
606// known backtrack code location than it is to pop an unknown backtrack
607// location from the stack and jump there.
608//
ager@chromium.org32912102009-01-16 10:38:43 +0000609// The virtual state found in the Trace affects code generation. For example
610// the virtual state contains the difference between the actual current
611// position and the virtual current position, and matching code needs to use
612// this offset to attempt a match in the correct location of the input
613// string. Therefore code generated for a non-trivial trace is specialized
614// to that trace. The code generator therefore has the ability to generate
615// code for each node several times. In order to limit the size of the
616// generated code there is an arbitrary limit on how many specialized sets of
617// code may be generated for a given node. If the limit is reached, the
618// trace is flushed and a generic version of the code for a node is emitted.
619// This is subsequently used for that node. The code emitted for non-generic
620// trace is not recorded in the node and so it cannot currently be reused in
621// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000622
623
624void RegExpTree::AppendToText(RegExpText* text) {
625 UNREACHABLE();
626}
627
628
629void RegExpAtom::AppendToText(RegExpText* text) {
630 text->AddElement(TextElement::Atom(this));
631}
632
633
634void RegExpCharacterClass::AppendToText(RegExpText* text) {
635 text->AddElement(TextElement::CharClass(this));
636}
637
638
639void RegExpText::AppendToText(RegExpText* text) {
640 for (int i = 0; i < elements()->length(); i++)
641 text->AddElement(elements()->at(i));
642}
643
644
645TextElement TextElement::Atom(RegExpAtom* atom) {
646 TextElement result = TextElement(ATOM);
647 result.data.u_atom = atom;
648 return result;
649}
650
651
652TextElement TextElement::CharClass(
653 RegExpCharacterClass* char_class) {
654 TextElement result = TextElement(CHAR_CLASS);
655 result.data.u_char_class = char_class;
656 return result;
657}
658
659
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000660int TextElement::length() {
661 if (type == ATOM) {
662 return data.u_atom->length();
663 } else {
664 ASSERT(type == CHAR_CLASS);
665 return 1;
666 }
667}
668
669
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000670DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
671 if (table_ == NULL) {
672 table_ = new DispatchTable();
673 DispatchTableConstructor cons(table_, ignore_case);
674 cons.BuildTable(this);
675 }
676 return table_;
677}
678
679
680class RegExpCompiler {
681 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000682 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000683
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000684 int AllocateRegister() {
685 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
686 reg_exp_too_big_ = true;
687 return next_register_;
688 }
689 return next_register_++;
690 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000691
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000692 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
693 RegExpNode* start,
694 int capture_count,
695 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000696
697 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
698
699 static const int kImplementationOffset = 0;
700 static const int kNumberOfRegistersOffset = 0;
701 static const int kCodeOffset = 1;
702
703 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
704 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000705
706 static const int kMaxRecursion = 100;
707 inline int recursion_depth() { return recursion_depth_; }
708 inline void IncrementRecursionDepth() { recursion_depth_++; }
709 inline void DecrementRecursionDepth() { recursion_depth_--; }
710
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000711 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
712
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000713 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000714 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000715
ager@chromium.org32912102009-01-16 10:38:43 +0000716 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000717 private:
718 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000719 int next_register_;
720 List<RegExpNode*>* work_list_;
721 int recursion_depth_;
722 RegExpMacroAssembler* macro_assembler_;
723 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000724 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000725 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000726};
727
728
729class RecursionCheck {
730 public:
731 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
732 compiler->IncrementRecursionDepth();
733 }
734 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
735 private:
736 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000737};
738
739
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000740static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
741 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000742}
743
744
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000745// Attempts to compile the regexp using an Irregexp code generator. Returns
746// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000747RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000748 : next_register_(2 * (capture_count + 1)),
749 work_list_(NULL),
750 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000751 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000752 ascii_(ascii),
753 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000754 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000755 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000756}
757
758
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000759RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000760 RegExpMacroAssembler* macro_assembler,
761 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000762 int capture_count,
763 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000764#ifdef DEBUG
765 if (FLAG_trace_regexp_assembler)
766 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
767 else
768#endif
769 macro_assembler_ = macro_assembler;
770 List <RegExpNode*> work_list(0);
771 work_list_ = &work_list;
772 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000773 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000774 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000775 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000776 macro_assembler_->Bind(&fail);
777 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000778 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000779 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000780 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000781 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
782
ager@chromium.org8bb60582008-12-11 12:02:20 +0000783 Handle<Object> code = macro_assembler_->GetCode(pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000784
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000785 work_list_ = NULL;
786#ifdef DEBUG
787 if (FLAG_trace_regexp_assembler) {
788 delete macro_assembler_;
789 }
790#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000791 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000792}
793
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000794
ager@chromium.org32912102009-01-16 10:38:43 +0000795bool Trace::DeferredAction::Mentions(int that) {
796 if (type() == ActionNode::CLEAR_CAPTURES) {
797 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
798 return range.Contains(that);
799 } else {
800 return reg() == that;
801 }
802}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000803
ager@chromium.org32912102009-01-16 10:38:43 +0000804
805bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000806 for (DeferredAction* action = actions_;
807 action != NULL;
808 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000809 if (action->Mentions(reg))
810 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000811 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000812 return false;
813}
814
815
ager@chromium.org32912102009-01-16 10:38:43 +0000816bool Trace::GetStoredPosition(int reg, int* cp_offset) {
817 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000818 for (DeferredAction* action = actions_;
819 action != NULL;
820 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000821 if (action->Mentions(reg)) {
822 if (action->type() == ActionNode::STORE_POSITION) {
823 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
824 return true;
825 } else {
826 return false;
827 }
828 }
829 }
830 return false;
831}
832
833
834int Trace::FindAffectedRegisters(OutSet* affected_registers) {
835 int max_register = RegExpCompiler::kNoRegister;
836 for (DeferredAction* action = actions_;
837 action != NULL;
838 action = action->next()) {
839 if (action->type() == ActionNode::CLEAR_CAPTURES) {
840 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
841 for (int i = range.from(); i <= range.to(); i++)
842 affected_registers->Set(i);
843 if (range.to() > max_register) max_register = range.to();
844 } else {
845 affected_registers->Set(action->reg());
846 if (action->reg() > max_register) max_register = action->reg();
847 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000848 }
849 return max_register;
850}
851
852
ager@chromium.org32912102009-01-16 10:38:43 +0000853void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
854 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000855 OutSet& registers_to_pop,
856 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000857 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000858 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
859 else if (registers_to_clear.Get(reg)) {
860 int clear_to = reg;
861 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
862 reg--;
863 }
864 assembler->ClearRegisters(reg, clear_to);
865 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000866 }
867}
868
869
ager@chromium.org32912102009-01-16 10:38:43 +0000870void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
871 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000872 OutSet& affected_registers,
873 OutSet* registers_to_pop,
874 OutSet* registers_to_clear) {
875 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
876 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
877
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000878 // Count pushes performed to force a stack limit check occasionally.
879 int pushes = 0;
880
ager@chromium.org8bb60582008-12-11 12:02:20 +0000881 for (int reg = 0; reg <= max_register; reg++) {
882 if (!affected_registers.Get(reg)) {
883 continue;
884 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000885
886 // The chronologically first deferred action in the trace
887 // is used to infer the action needed to restore a register
888 // to its previous state (or not, if it's safe to ignore it).
889 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
890 DeferredActionUndoType undo_action = IGNORE;
891
ager@chromium.org8bb60582008-12-11 12:02:20 +0000892 int value = 0;
893 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000894 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000895 int store_position = -1;
896 // This is a little tricky because we are scanning the actions in reverse
897 // historical order (newest first).
898 for (DeferredAction* action = actions_;
899 action != NULL;
900 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000901 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000902 switch (action->type()) {
903 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +0000904 Trace::DeferredSetRegister* psr =
905 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000906 if (!absolute) {
907 value += psr->value();
908 absolute = true;
909 }
910 // SET_REGISTER is currently only used for newly introduced loop
911 // counters. They can have a significant previous value if they
912 // occour in a loop. TODO(lrn): Propagate this information, so
913 // we can set undo_action to IGNORE if we know there is no value to
914 // restore.
915 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000916 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000917 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000918 break;
919 }
920 case ActionNode::INCREMENT_REGISTER:
921 if (!absolute) {
922 value++;
923 }
924 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000925 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000926 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000927 break;
928 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +0000929 Trace::DeferredCapture* pc =
930 static_cast<Trace::DeferredCapture*>(action);
931 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000932 store_position = pc->cp_offset();
933 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000934
935 // For captures we know that stores and clears alternate.
936 // Other register, are never cleared, and if the occur
937 // inside a loop, they might be assigned more than once.
938 if (reg <= 1) {
939 // Registers zero and one, aka "capture zero", is
940 // always set correctly if we succeed. There is no
941 // need to undo a setting on backtrack, because we
942 // will set it again or fail.
943 undo_action = IGNORE;
944 } else {
945 undo_action = pc->is_capture() ? CLEAR : RESTORE;
946 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000947 ASSERT(!absolute);
948 ASSERT_EQ(value, 0);
949 break;
950 }
ager@chromium.org32912102009-01-16 10:38:43 +0000951 case ActionNode::CLEAR_CAPTURES: {
952 // Since we're scanning in reverse order, if we've already
953 // set the position we have to ignore historically earlier
954 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000955 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +0000956 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000957 }
958 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +0000959 ASSERT(!absolute);
960 ASSERT_EQ(value, 0);
961 break;
962 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000963 default:
964 UNREACHABLE();
965 break;
966 }
967 }
968 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000969 // Prepare for the undo-action (e.g., push if it's going to be popped).
970 if (undo_action == RESTORE) {
971 pushes++;
972 RegExpMacroAssembler::StackCheckFlag stack_check =
973 RegExpMacroAssembler::kNoStackLimitCheck;
974 if (pushes == push_limit) {
975 stack_check = RegExpMacroAssembler::kCheckStackLimit;
976 pushes = 0;
977 }
978
979 assembler->PushRegister(reg, stack_check);
980 registers_to_pop->Set(reg);
981 } else if (undo_action == CLEAR) {
982 registers_to_clear->Set(reg);
983 }
984 // Perform the chronologically last action (or accumulated increment)
985 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000986 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000987 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +0000988 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000989 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +0000990 } else if (absolute) {
991 assembler->SetRegister(reg, value);
992 } else if (value != 0) {
993 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000994 }
995 }
996}
997
998
ager@chromium.org8bb60582008-12-11 12:02:20 +0000999// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001000// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001001// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001002void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001003 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001004
iposva@chromium.org245aa852009-02-10 00:49:54 +00001005 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001006
1007 if (actions_ == NULL && backtrack() == NULL) {
1008 // 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 +00001009 // a normal situation. We may also have to forget some information gained
1010 // through a quick check that was already performed.
1011 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001012 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001013 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001014 successor->Emit(compiler, &new_state);
1015 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001016 }
1017
1018 // Generate deferred actions here along with code to undo them again.
1019 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001020
ager@chromium.org381abbb2009-02-25 13:23:22 +00001021 if (backtrack() != NULL) {
1022 // Here we have a concrete backtrack location. These are set up by choice
1023 // nodes and so they indicate that we have a deferred save of the current
1024 // position which we may need to emit here.
1025 assembler->PushCurrentPosition();
1026 }
1027
ager@chromium.org8bb60582008-12-11 12:02:20 +00001028 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001029 OutSet registers_to_pop;
1030 OutSet registers_to_clear;
1031 PerformDeferredActions(assembler,
1032 max_register,
1033 affected_registers,
1034 &registers_to_pop,
1035 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001036 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001037 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001038 }
1039
1040 // Create a new trivial state and generate the node with that.
1041 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001042 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001043 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001044 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001045
1046 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001047 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001048 RestoreAffectedRegisters(assembler,
1049 max_register,
1050 registers_to_pop,
1051 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001052 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001053 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001054 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001055 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001056 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001057 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001058}
1059
1060
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001061void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001062 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001063
1064 // Omit flushing the trace. We discard the entire stack frame anyway.
1065
ager@chromium.org8bb60582008-12-11 12:02:20 +00001066 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001067 // We are completely independent of the trace, since we ignore it,
1068 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001069 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001070 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001071
1072 // Throw away everything on the backtrack stack since the start
1073 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001074 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1075 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001076 if (clear_capture_count_ > 0) {
1077 // Clear any captures that might have been performed during the success
1078 // of the body of the negative look-ahead.
1079 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1080 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1081 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001082 // Now that we have unwound the stack we find at the top of the stack the
1083 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001084 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001085}
1086
1087
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001088void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001089 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001090 trace->Flush(compiler, this);
1091 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001092 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001093 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001094 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001095 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001096 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001097 switch (action_) {
1098 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001099 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001100 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001101 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001102 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001103 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001104 case NEGATIVE_SUBMATCH_SUCCESS:
1105 // This case is handled in a different virtual method.
1106 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001107 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001108 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001109}
1110
1111
1112void GuardedAlternative::AddGuard(Guard* guard) {
1113 if (guards_ == NULL)
1114 guards_ = new ZoneList<Guard*>(1);
1115 guards_->Add(guard);
1116}
1117
1118
ager@chromium.org8bb60582008-12-11 12:02:20 +00001119ActionNode* ActionNode::SetRegister(int reg,
1120 int val,
1121 RegExpNode* on_success) {
1122 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001123 result->data_.u_store_register.reg = reg;
1124 result->data_.u_store_register.value = val;
1125 return result;
1126}
1127
1128
1129ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1130 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1131 result->data_.u_increment_register.reg = reg;
1132 return result;
1133}
1134
1135
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001136ActionNode* ActionNode::StorePosition(int reg,
1137 bool is_capture,
1138 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001139 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1140 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001141 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001142 return result;
1143}
1144
1145
ager@chromium.org32912102009-01-16 10:38:43 +00001146ActionNode* ActionNode::ClearCaptures(Interval range,
1147 RegExpNode* on_success) {
1148 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1149 result->data_.u_clear_captures.range_from = range.from();
1150 result->data_.u_clear_captures.range_to = range.to();
1151 return result;
1152}
1153
1154
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001155ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1156 int position_reg,
1157 RegExpNode* on_success) {
1158 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1159 result->data_.u_submatch.stack_pointer_register = stack_reg;
1160 result->data_.u_submatch.current_position_register = position_reg;
1161 return result;
1162}
1163
1164
ager@chromium.org8bb60582008-12-11 12:02:20 +00001165ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1166 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001167 int clear_register_count,
1168 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001169 RegExpNode* on_success) {
1170 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001171 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001172 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001173 result->data_.u_submatch.clear_register_count = clear_register_count;
1174 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001175 return result;
1176}
1177
1178
ager@chromium.org32912102009-01-16 10:38:43 +00001179ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1180 int repetition_register,
1181 int repetition_limit,
1182 RegExpNode* on_success) {
1183 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1184 result->data_.u_empty_match_check.start_register = start_register;
1185 result->data_.u_empty_match_check.repetition_register = repetition_register;
1186 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1187 return result;
1188}
1189
1190
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001191#define DEFINE_ACCEPT(Type) \
1192 void Type##Node::Accept(NodeVisitor* visitor) { \
1193 visitor->Visit##Type(this); \
1194 }
1195FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1196#undef DEFINE_ACCEPT
1197
1198
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001199void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1200 visitor->VisitLoopChoice(this);
1201}
1202
1203
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001204// -------------------------------------------------------------------
1205// Emit code.
1206
1207
1208void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1209 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001210 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001211 switch (guard->op()) {
1212 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001213 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001214 macro_assembler->IfRegisterGE(guard->reg(),
1215 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001216 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001217 break;
1218 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001219 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001220 macro_assembler->IfRegisterLT(guard->reg(),
1221 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001222 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001223 break;
1224 }
1225}
1226
1227
1228static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1229static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1230
1231
ager@chromium.org381abbb2009-02-25 13:23:22 +00001232// Returns the number of characters in the equivalence class, omitting those
1233// that cannot occur in the source string because it is ASCII.
1234static int GetCaseIndependentLetters(uc16 character,
1235 bool ascii_subject,
1236 unibrow::uchar* letters) {
1237 int length = uncanonicalize.get(character, '\0', letters);
1238 // Unibrow returns 0 or 1 for characters where case independependence is
1239 // trivial.
1240 if (length == 0) {
1241 letters[0] = character;
1242 length = 1;
1243 }
1244 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1245 return length;
1246 }
1247 // The standard requires that non-ASCII characters cannot have ASCII
1248 // character codes in their equivalence class.
1249 return 0;
1250}
1251
1252
1253static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1254 uc16 c,
1255 Label* on_failure,
1256 int cp_offset,
1257 bool check,
1258 bool preloaded) {
1259 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1260 bool bound_checked = false;
1261 if (!preloaded) {
1262 assembler->LoadCurrentCharacter(
1263 cp_offset,
1264 on_failure,
1265 check);
1266 bound_checked = true;
1267 }
1268 assembler->CheckNotCharacter(c, on_failure);
1269 return bound_checked;
1270}
1271
1272
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001273// Only emits non-letters (things that don't have case). Only used for case
1274// independent matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001275static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1276 uc16 c,
1277 Label* on_failure,
1278 int cp_offset,
1279 bool check,
1280 bool preloaded) {
1281 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1282 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001283 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001284 int length = GetCaseIndependentLetters(c, ascii, chars);
1285 if (length < 1) {
1286 // This can't match. Must be an ASCII subject and a non-ASCII character.
1287 // We do not need to do anything since the ASCII pass already handled this.
1288 return false; // Bounds not checked.
1289 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001290 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001291 // We handle the length > 1 case in a later pass.
1292 if (length == 1) {
1293 if (ascii && c > String::kMaxAsciiCharCodeU) {
1294 // Can't match - see above.
1295 return false; // Bounds not checked.
1296 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001297 if (!preloaded) {
1298 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1299 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001300 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001301 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001302 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001303 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001304}
1305
1306
1307static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001308 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001309 uc16 c1,
1310 uc16 c2,
1311 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001312 uc16 char_mask;
1313 if (ascii) {
1314 char_mask = String::kMaxAsciiCharCode;
1315 } else {
1316 char_mask = String::kMaxUC16CharCode;
1317 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001318 uc16 exor = c1 ^ c2;
1319 // Check whether exor has only one bit set.
1320 if (((exor - 1) & exor) == 0) {
1321 // If c1 and c2 differ only by one bit.
1322 // Ecma262UnCanonicalize always gives the highest number last.
1323 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001324 uc16 mask = char_mask ^ exor;
1325 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001326 return true;
1327 }
1328 ASSERT(c2 > c1);
1329 uc16 diff = c2 - c1;
1330 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1331 // If the characters differ by 2^n but don't differ by one bit then
1332 // subtract the difference from the found character, then do the or
1333 // trick. We avoid the theoretical case where negative numbers are
1334 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001335 uc16 mask = char_mask ^ diff;
1336 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1337 diff,
1338 mask,
1339 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001340 return true;
1341 }
1342 return false;
1343}
1344
1345
ager@chromium.org381abbb2009-02-25 13:23:22 +00001346typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1347 uc16 c,
1348 Label* on_failure,
1349 int cp_offset,
1350 bool check,
1351 bool preloaded);
1352
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001353// Only emits letters (things that have case). Only used for case independent
1354// matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001355static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1356 uc16 c,
1357 Label* on_failure,
1358 int cp_offset,
1359 bool check,
1360 bool preloaded) {
1361 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1362 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001363 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001364 int length = GetCaseIndependentLetters(c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001365 if (length <= 1) return false;
1366 // We may not need to check against the end of the input string
1367 // if this character lies before a character that matched.
1368 if (!preloaded) {
1369 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001370 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001371 Label ok;
1372 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1373 switch (length) {
1374 case 2: {
1375 if (ShortCutEmitCharacterPair(macro_assembler,
1376 ascii,
1377 chars[0],
1378 chars[1],
1379 on_failure)) {
1380 } else {
1381 macro_assembler->CheckCharacter(chars[0], &ok);
1382 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1383 macro_assembler->Bind(&ok);
1384 }
1385 break;
1386 }
1387 case 4:
1388 macro_assembler->CheckCharacter(chars[3], &ok);
1389 // Fall through!
1390 case 3:
1391 macro_assembler->CheckCharacter(chars[0], &ok);
1392 macro_assembler->CheckCharacter(chars[1], &ok);
1393 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1394 macro_assembler->Bind(&ok);
1395 break;
1396 default:
1397 UNREACHABLE();
1398 break;
1399 }
1400 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001401}
1402
1403
1404static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1405 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001406 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001407 Label* on_failure,
1408 int cp_offset,
1409 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001410 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001411 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001412 int max_char;
1413 if (ascii) {
1414 max_char = String::kMaxAsciiCharCode;
1415 } else {
1416 max_char = String::kMaxUC16CharCode;
1417 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001418
1419 Label success;
1420
1421 Label* char_is_in_class =
1422 cc->is_negated() ? on_failure : &success;
1423
1424 int range_count = ranges->length();
1425
ager@chromium.org8bb60582008-12-11 12:02:20 +00001426 int last_valid_range = range_count - 1;
1427 while (last_valid_range >= 0) {
1428 CharacterRange& range = ranges->at(last_valid_range);
1429 if (range.from() <= max_char) {
1430 break;
1431 }
1432 last_valid_range--;
1433 }
1434
1435 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001436 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001437 // TODO(plesner): We can remove this when the node level does our
1438 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001439 macro_assembler->GoTo(on_failure);
1440 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001441 if (check_offset) {
1442 macro_assembler->CheckPosition(cp_offset, on_failure);
1443 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001444 return;
1445 }
1446
ager@chromium.org8bb60582008-12-11 12:02:20 +00001447 if (last_valid_range == 0 &&
1448 !cc->is_negated() &&
1449 ranges->at(0).IsEverything(max_char)) {
1450 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001451 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001452 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001453 }
1454 return;
1455 }
1456
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001457 if (!preloaded) {
1458 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001459 }
1460
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001461 if (cc->is_standard() &&
1462 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1463 on_failure)) {
1464 return;
1465 }
1466
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001467 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001468 CharacterRange& range = ranges->at(i);
1469 Label next_range;
1470 uc16 from = range.from();
1471 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001472 if (from > max_char) {
1473 continue;
1474 }
1475 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001476 if (to == from) {
1477 macro_assembler->CheckCharacter(to, char_is_in_class);
1478 } else {
1479 if (from != 0) {
1480 macro_assembler->CheckCharacterLT(from, &next_range);
1481 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001482 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001483 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1484 } else {
1485 macro_assembler->GoTo(char_is_in_class);
1486 }
1487 }
1488 macro_assembler->Bind(&next_range);
1489 }
1490
ager@chromium.org8bb60582008-12-11 12:02:20 +00001491 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001492 uc16 from = range.from();
1493 uc16 to = range.to();
1494
ager@chromium.org8bb60582008-12-11 12:02:20 +00001495 if (to > max_char) to = max_char;
1496 ASSERT(to >= from);
1497
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001498 if (to == from) {
1499 if (cc->is_negated()) {
1500 macro_assembler->CheckCharacter(to, on_failure);
1501 } else {
1502 macro_assembler->CheckNotCharacter(to, on_failure);
1503 }
1504 } else {
1505 if (from != 0) {
1506 if (cc->is_negated()) {
1507 macro_assembler->CheckCharacterLT(from, &success);
1508 } else {
1509 macro_assembler->CheckCharacterLT(from, on_failure);
1510 }
1511 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001512 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001513 if (cc->is_negated()) {
1514 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1515 } else {
1516 macro_assembler->CheckCharacterGT(to, on_failure);
1517 }
1518 } else {
1519 if (cc->is_negated()) {
1520 macro_assembler->GoTo(on_failure);
1521 }
1522 }
1523 }
1524 macro_assembler->Bind(&success);
1525}
1526
1527
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001528RegExpNode::~RegExpNode() {
1529}
1530
1531
ager@chromium.org8bb60582008-12-11 12:02:20 +00001532RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001533 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001534 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001535 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001536 return CONTINUE;
1537 }
1538
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001539 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001540 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001541 if (label_.is_bound()) {
1542 // We are being asked to generate a generic version, but that's already
1543 // been done so just go to it.
1544 macro_assembler->GoTo(&label_);
1545 return DONE;
1546 }
1547 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1548 // To avoid too deep recursion we push the node to the work queue and just
1549 // generate a goto here.
1550 compiler->AddWork(this);
1551 macro_assembler->GoTo(&label_);
1552 return DONE;
1553 }
1554 // Generate generic version of the node and bind the label for later use.
1555 macro_assembler->Bind(&label_);
1556 return CONTINUE;
1557 }
1558
1559 // We are being asked to make a non-generic version. Keep track of how many
1560 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001561 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001562 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001563 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001564 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1565 return CONTINUE;
1566 }
1567
ager@chromium.org32912102009-01-16 10:38:43 +00001568 // If we get here code has been generated for this node too many times or
1569 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001570 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001571 trace->Flush(compiler, this);
1572 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001573}
1574
1575
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001576int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001577 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1578 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001579 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001580}
1581
1582
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001583int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1584 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1585 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1586}
1587
1588
1589int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1590 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1591 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1592}
1593
1594
1595int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001596 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001597 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001598 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001599 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1600 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001601}
1602
1603
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001604int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
1605 int recursion_depth) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001606 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1607 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1608 // afterwards.
1609 RegExpNode* node = alternatives_->at(1).node();
1610 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1611}
1612
1613
1614void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1615 QuickCheckDetails* details,
1616 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001617 int filled_in,
1618 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001619 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1620 // afterwards.
1621 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001622 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001623}
1624
1625
1626int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1627 int recursion_depth,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001628 RegExpNode* ignore_this_node) {
1629 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1630 int min = 100;
1631 int choice_count = alternatives_->length();
1632 for (int i = 0; i < choice_count; i++) {
1633 RegExpNode* node = alternatives_->at(i).node();
1634 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001635 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1636 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001637 if (node_eats_at_least < min) min = node_eats_at_least;
1638 }
1639 return min;
1640}
1641
1642
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001643int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1644 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001645}
1646
1647
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001648int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1649 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001650}
1651
1652
1653// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1654static inline uint32_t SmearBitsRight(uint32_t v) {
1655 v |= v >> 1;
1656 v |= v >> 2;
1657 v |= v >> 4;
1658 v |= v >> 8;
1659 v |= v >> 16;
1660 return v;
1661}
1662
1663
1664bool QuickCheckDetails::Rationalize(bool asc) {
1665 bool found_useful_op = false;
1666 uint32_t char_mask;
1667 if (asc) {
1668 char_mask = String::kMaxAsciiCharCode;
1669 } else {
1670 char_mask = String::kMaxUC16CharCode;
1671 }
1672 mask_ = 0;
1673 value_ = 0;
1674 int char_shift = 0;
1675 for (int i = 0; i < characters_; i++) {
1676 Position* pos = &positions_[i];
1677 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1678 found_useful_op = true;
1679 }
1680 mask_ |= (pos->mask & char_mask) << char_shift;
1681 value_ |= (pos->value & char_mask) << char_shift;
1682 char_shift += asc ? 8 : 16;
1683 }
1684 return found_useful_op;
1685}
1686
1687
1688bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001689 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001690 bool preload_has_checked_bounds,
1691 Label* on_possible_success,
1692 QuickCheckDetails* details,
1693 bool fall_through_on_failure) {
1694 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001695 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1696 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001697 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001698 ASSERT(details->characters() == 1 ||
1699 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001700 uint32_t mask = details->mask();
1701 uint32_t value = details->value();
1702
1703 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1704
ager@chromium.org32912102009-01-16 10:38:43 +00001705 if (trace->characters_preloaded() != details->characters()) {
1706 assembler->LoadCurrentCharacter(trace->cp_offset(),
1707 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001708 !preload_has_checked_bounds,
1709 details->characters());
1710 }
1711
1712
1713 bool need_mask = true;
1714
1715 if (details->characters() == 1) {
1716 // If number of characters preloaded is 1 then we used a byte or 16 bit
1717 // load so the value is already masked down.
1718 uint32_t char_mask;
1719 if (compiler->ascii()) {
1720 char_mask = String::kMaxAsciiCharCode;
1721 } else {
1722 char_mask = String::kMaxUC16CharCode;
1723 }
1724 if ((mask & char_mask) == char_mask) need_mask = false;
1725 mask &= char_mask;
1726 } else {
1727 // For 2-character preloads in ASCII mode we also use a 16 bit load with
1728 // zero extend.
1729 if (details->characters() == 2 && compiler->ascii()) {
1730 if ((mask & 0xffff) == 0xffff) need_mask = false;
1731 } else {
1732 if (mask == 0xffffffff) need_mask = false;
1733 }
1734 }
1735
1736 if (fall_through_on_failure) {
1737 if (need_mask) {
1738 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1739 } else {
1740 assembler->CheckCharacter(value, on_possible_success);
1741 }
1742 } else {
1743 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001744 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001745 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001746 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001747 }
1748 }
1749 return true;
1750}
1751
1752
1753// Here is the meat of GetQuickCheckDetails (see also the comment on the
1754// super-class in the .h file).
1755//
1756// We iterate along the text object, building up for each character a
1757// mask and value that can be used to test for a quick failure to match.
1758// The masks and values for the positions will be combined into a single
1759// machine word for the current character width in order to be used in
1760// generating a quick check.
1761void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1762 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001763 int characters_filled_in,
1764 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001765 ASSERT(characters_filled_in < details->characters());
1766 int characters = details->characters();
1767 int char_mask;
1768 int char_shift;
1769 if (compiler->ascii()) {
1770 char_mask = String::kMaxAsciiCharCode;
1771 char_shift = 8;
1772 } else {
1773 char_mask = String::kMaxUC16CharCode;
1774 char_shift = 16;
1775 }
1776 for (int k = 0; k < elms_->length(); k++) {
1777 TextElement elm = elms_->at(k);
1778 if (elm.type == TextElement::ATOM) {
1779 Vector<const uc16> quarks = elm.data.u_atom->data();
1780 for (int i = 0; i < characters && i < quarks.length(); i++) {
1781 QuickCheckDetails::Position* pos =
1782 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001783 uc16 c = quarks[i];
1784 if (c > char_mask) {
1785 // If we expect a non-ASCII character from an ASCII string,
1786 // there is no way we can match. Not even case independent
1787 // matching can turn an ASCII character into non-ASCII or
1788 // vice versa.
1789 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001790 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001791 return;
1792 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001793 if (compiler->ignore_case()) {
1794 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001795 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1796 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1797 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001798 // This letter has no case equivalents, so it's nice and simple
1799 // and the mask-compare will determine definitely whether we have
1800 // a match at this character position.
1801 pos->mask = char_mask;
1802 pos->value = c;
1803 pos->determines_perfectly = true;
1804 } else {
1805 uint32_t common_bits = char_mask;
1806 uint32_t bits = chars[0];
1807 for (int j = 1; j < length; j++) {
1808 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1809 common_bits ^= differing_bits;
1810 bits &= common_bits;
1811 }
1812 // If length is 2 and common bits has only one zero in it then
1813 // our mask and compare instruction will determine definitely
1814 // whether we have a match at this character position. Otherwise
1815 // it can only be an approximate check.
1816 uint32_t one_zero = (common_bits | ~char_mask);
1817 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1818 pos->determines_perfectly = true;
1819 }
1820 pos->mask = common_bits;
1821 pos->value = bits;
1822 }
1823 } else {
1824 // Don't ignore case. Nice simple case where the mask-compare will
1825 // determine definitely whether we have a match at this character
1826 // position.
1827 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001828 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001829 pos->determines_perfectly = true;
1830 }
1831 characters_filled_in++;
1832 ASSERT(characters_filled_in <= details->characters());
1833 if (characters_filled_in == details->characters()) {
1834 return;
1835 }
1836 }
1837 } else {
1838 QuickCheckDetails::Position* pos =
1839 details->positions(characters_filled_in);
1840 RegExpCharacterClass* tree = elm.data.u_char_class;
1841 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001842 if (tree->is_negated()) {
1843 // A quick check uses multi-character mask and compare. There is no
1844 // useful way to incorporate a negative char class into this scheme
1845 // so we just conservatively create a mask and value that will always
1846 // succeed.
1847 pos->mask = 0;
1848 pos->value = 0;
1849 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001850 int first_range = 0;
1851 while (ranges->at(first_range).from() > char_mask) {
1852 first_range++;
1853 if (first_range == ranges->length()) {
1854 details->set_cannot_match();
1855 pos->determines_perfectly = false;
1856 return;
1857 }
1858 }
1859 CharacterRange range = ranges->at(first_range);
1860 uc16 from = range.from();
1861 uc16 to = range.to();
1862 if (to > char_mask) {
1863 to = char_mask;
1864 }
1865 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001866 // A mask and compare is only perfect if the differing bits form a
1867 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001868 if ((differing_bits & (differing_bits + 1)) == 0 &&
1869 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001870 pos->determines_perfectly = true;
1871 }
1872 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001873 uint32_t bits = (from & common_bits);
1874 for (int i = first_range + 1; i < ranges->length(); i++) {
1875 CharacterRange range = ranges->at(i);
1876 uc16 from = range.from();
1877 uc16 to = range.to();
1878 if (from > char_mask) continue;
1879 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001880 // Here we are combining more ranges into the mask and compare
1881 // value. With each new range the mask becomes more sparse and
1882 // so the chances of a false positive rise. A character class
1883 // with multiple ranges is assumed never to be equivalent to a
1884 // mask and compare operation.
1885 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001886 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001887 new_common_bits = ~SmearBitsRight(new_common_bits);
1888 common_bits &= new_common_bits;
1889 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001890 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001891 common_bits ^= differing_bits;
1892 bits &= common_bits;
1893 }
1894 pos->mask = common_bits;
1895 pos->value = bits;
1896 }
1897 characters_filled_in++;
1898 ASSERT(characters_filled_in <= details->characters());
1899 if (characters_filled_in == details->characters()) {
1900 return;
1901 }
1902 }
1903 }
1904 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00001905 on_success()-> GetQuickCheckDetails(details,
1906 compiler,
1907 characters_filled_in,
1908 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001909}
1910
1911
1912void QuickCheckDetails::Clear() {
1913 for (int i = 0; i < characters_; i++) {
1914 positions_[i].mask = 0;
1915 positions_[i].value = 0;
1916 positions_[i].determines_perfectly = false;
1917 }
1918 characters_ = 0;
1919}
1920
1921
1922void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001923 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001924 if (by >= characters_) {
1925 Clear();
1926 return;
1927 }
1928 for (int i = 0; i < characters_ - by; i++) {
1929 positions_[i] = positions_[by + i];
1930 }
1931 for (int i = characters_ - by; i < characters_; i++) {
1932 positions_[i].mask = 0;
1933 positions_[i].value = 0;
1934 positions_[i].determines_perfectly = false;
1935 }
1936 characters_ -= by;
1937 // We could change mask_ and value_ here but we would never advance unless
1938 // they had already been used in a check and they won't be used again because
1939 // it would gain us nothing. So there's no point.
1940}
1941
1942
1943void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1944 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001945 if (other->cannot_match_) {
1946 return;
1947 }
1948 if (cannot_match_) {
1949 *this = *other;
1950 return;
1951 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001952 for (int i = from_index; i < characters_; i++) {
1953 QuickCheckDetails::Position* pos = positions(i);
1954 QuickCheckDetails::Position* other_pos = other->positions(i);
1955 if (pos->mask != other_pos->mask ||
1956 pos->value != other_pos->value ||
1957 !other_pos->determines_perfectly) {
1958 // Our mask-compare operation will be approximate unless we have the
1959 // exact same operation on both sides of the alternation.
1960 pos->determines_perfectly = false;
1961 }
1962 pos->mask &= other_pos->mask;
1963 pos->value &= pos->mask;
1964 other_pos->value &= pos->mask;
1965 uc16 differing_bits = (pos->value ^ other_pos->value);
1966 pos->mask &= ~differing_bits;
1967 pos->value &= pos->mask;
1968 }
1969}
1970
1971
ager@chromium.org32912102009-01-16 10:38:43 +00001972class VisitMarker {
1973 public:
1974 explicit VisitMarker(NodeInfo* info) : info_(info) {
1975 ASSERT(!info->visited);
1976 info->visited = true;
1977 }
1978 ~VisitMarker() {
1979 info_->visited = false;
1980 }
1981 private:
1982 NodeInfo* info_;
1983};
1984
1985
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001986void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
1987 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001988 int characters_filled_in,
1989 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00001990 if (body_can_be_zero_length_ || info()->visited) return;
1991 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001992 return ChoiceNode::GetQuickCheckDetails(details,
1993 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001994 characters_filled_in,
1995 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001996}
1997
1998
1999void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2000 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002001 int characters_filled_in,
2002 bool not_at_start) {
2003 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002004 int choice_count = alternatives_->length();
2005 ASSERT(choice_count > 0);
2006 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2007 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002008 characters_filled_in,
2009 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002010 for (int i = 1; i < choice_count; i++) {
2011 QuickCheckDetails new_details(details->characters());
2012 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002013 node->GetQuickCheckDetails(&new_details, compiler,
2014 characters_filled_in,
2015 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002016 // Here we merge the quick match details of the two branches.
2017 details->Merge(&new_details, characters_filled_in);
2018 }
2019}
2020
2021
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002022// Check for [0-9A-Z_a-z].
2023static void EmitWordCheck(RegExpMacroAssembler* assembler,
2024 Label* word,
2025 Label* non_word,
2026 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002027 if (assembler->CheckSpecialCharacterClass(
2028 fall_through_on_word ? 'w' : 'W',
2029 fall_through_on_word ? non_word : word)) {
2030 // Optimized implementation available.
2031 return;
2032 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002033 assembler->CheckCharacterGT('z', non_word);
2034 assembler->CheckCharacterLT('0', non_word);
2035 assembler->CheckCharacterGT('a' - 1, word);
2036 assembler->CheckCharacterLT('9' + 1, word);
2037 assembler->CheckCharacterLT('A', non_word);
2038 assembler->CheckCharacterLT('Z' + 1, word);
2039 if (fall_through_on_word) {
2040 assembler->CheckNotCharacter('_', non_word);
2041 } else {
2042 assembler->CheckCharacter('_', word);
2043 }
2044}
2045
2046
2047// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2048// that matches newline or the start of input).
2049static void EmitHat(RegExpCompiler* compiler,
2050 RegExpNode* on_success,
2051 Trace* trace) {
2052 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2053 // We will be loading the previous character into the current character
2054 // register.
2055 Trace new_trace(*trace);
2056 new_trace.InvalidateCurrentCharacter();
2057
2058 Label ok;
2059 if (new_trace.cp_offset() == 0) {
2060 // The start of input counts as a newline in this context, so skip to
2061 // ok if we are at the start.
2062 assembler->CheckAtStart(&ok);
2063 }
2064 // We already checked that we are not at the start of input so it must be
2065 // OK to load the previous character.
2066 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2067 new_trace.backtrack(),
2068 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002069 if (!assembler->CheckSpecialCharacterClass('n',
2070 new_trace.backtrack())) {
2071 // Newline means \n, \r, 0x2028 or 0x2029.
2072 if (!compiler->ascii()) {
2073 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2074 }
2075 assembler->CheckCharacter('\n', &ok);
2076 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002077 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002078 assembler->Bind(&ok);
2079 on_success->Emit(compiler, &new_trace);
2080}
2081
2082
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002083// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2084// when we know whether the next character must be a word character or not.
2085static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2086 RegExpCompiler* compiler,
2087 RegExpNode* on_success,
2088 Trace* trace) {
2089 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2090 Label done;
2091
2092 Trace new_trace(*trace);
2093
2094 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2095 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2096 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2097
2098 // Check whether previous character was a word character.
2099 switch (trace->at_start()) {
2100 case Trace::TRUE:
2101 if (expect_word_character) {
2102 assembler->GoTo(on_non_word);
2103 }
2104 break;
2105 case Trace::UNKNOWN:
2106 ASSERT_EQ(0, trace->cp_offset());
2107 assembler->CheckAtStart(on_non_word);
2108 // Fall through.
2109 case Trace::FALSE:
2110 int prev_char_offset = trace->cp_offset() - 1;
2111 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2112 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2113 // We may or may not have loaded the previous character.
2114 new_trace.InvalidateCurrentCharacter();
2115 }
2116
2117 assembler->Bind(&done);
2118
2119 on_success->Emit(compiler, &new_trace);
2120}
2121
2122
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002123// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2124static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2125 RegExpCompiler* compiler,
2126 RegExpNode* on_success,
2127 Trace* trace) {
2128 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2129 Label before_non_word;
2130 Label before_word;
2131 if (trace->characters_preloaded() != 1) {
2132 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2133 }
2134 // Fall through on non-word.
2135 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2136
2137 // We will be loading the previous character into the current character
2138 // register.
2139 Trace new_trace(*trace);
2140 new_trace.InvalidateCurrentCharacter();
2141
2142 Label ok;
2143 Label* boundary;
2144 Label* not_boundary;
2145 if (type == AssertionNode::AT_BOUNDARY) {
2146 boundary = &ok;
2147 not_boundary = new_trace.backtrack();
2148 } else {
2149 not_boundary = &ok;
2150 boundary = new_trace.backtrack();
2151 }
2152
2153 // Next character is not a word character.
2154 assembler->Bind(&before_non_word);
2155 if (new_trace.cp_offset() == 0) {
2156 // The start of input counts as a non-word character, so the question is
2157 // decided if we are at the start.
2158 assembler->CheckAtStart(not_boundary);
2159 }
2160 // We already checked that we are not at the start of input so it must be
2161 // OK to load the previous character.
2162 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2163 &ok, // Unused dummy label in this call.
2164 false);
2165 // Fall through on non-word.
2166 EmitWordCheck(assembler, boundary, not_boundary, false);
2167 assembler->GoTo(not_boundary);
2168
2169 // Next character is a word character.
2170 assembler->Bind(&before_word);
2171 if (new_trace.cp_offset() == 0) {
2172 // The start of input counts as a non-word character, so the question is
2173 // decided if we are at the start.
2174 assembler->CheckAtStart(boundary);
2175 }
2176 // We already checked that we are not at the start of input so it must be
2177 // OK to load the previous character.
2178 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2179 &ok, // Unused dummy label in this call.
2180 false);
2181 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2182 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2183
2184 assembler->Bind(&ok);
2185
2186 on_success->Emit(compiler, &new_trace);
2187}
2188
2189
iposva@chromium.org245aa852009-02-10 00:49:54 +00002190void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2191 RegExpCompiler* compiler,
2192 int filled_in,
2193 bool not_at_start) {
2194 if (type_ == AT_START && not_at_start) {
2195 details->set_cannot_match();
2196 return;
2197 }
2198 return on_success()->GetQuickCheckDetails(details,
2199 compiler,
2200 filled_in,
2201 not_at_start);
2202}
2203
2204
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002205void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2206 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2207 switch (type_) {
2208 case AT_END: {
2209 Label ok;
2210 assembler->CheckPosition(trace->cp_offset(), &ok);
2211 assembler->GoTo(trace->backtrack());
2212 assembler->Bind(&ok);
2213 break;
2214 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002215 case AT_START: {
2216 if (trace->at_start() == Trace::FALSE) {
2217 assembler->GoTo(trace->backtrack());
2218 return;
2219 }
2220 if (trace->at_start() == Trace::UNKNOWN) {
2221 assembler->CheckNotAtStart(trace->backtrack());
2222 Trace at_start_trace = *trace;
2223 at_start_trace.set_at_start(true);
2224 on_success()->Emit(compiler, &at_start_trace);
2225 return;
2226 }
2227 }
2228 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002229 case AFTER_NEWLINE:
2230 EmitHat(compiler, on_success(), trace);
2231 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002232 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002233 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002234 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2235 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002236 }
2237 case AFTER_WORD_CHARACTER:
2238 case AFTER_NONWORD_CHARACTER: {
2239 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2240 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002241 }
2242 on_success()->Emit(compiler, trace);
2243}
2244
2245
ager@chromium.org381abbb2009-02-25 13:23:22 +00002246static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2247 if (quick_check == NULL) return false;
2248 if (offset >= quick_check->characters()) return false;
2249 return quick_check->positions(offset)->determines_perfectly;
2250}
2251
2252
2253static void UpdateBoundsCheck(int index, int* checked_up_to) {
2254 if (index > *checked_up_to) {
2255 *checked_up_to = index;
2256 }
2257}
2258
2259
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002260// We call this repeatedly to generate code for each pass over the text node.
2261// The passes are in increasing order of difficulty because we hope one
2262// of the first passes will fail in which case we are saved the work of the
2263// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2264// we will check the '%' in the first pass, the case independent 'a' in the
2265// second pass and the character class in the last pass.
2266//
2267// The passes are done from right to left, so for example to test for /bar/
2268// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2269// and then a 'b' with offset 0. This means we can avoid the end-of-input
2270// bounds check most of the time. In the example we only need to check for
2271// end-of-input when loading the putative 'r'.
2272//
2273// A slight complication involves the fact that the first character may already
2274// be fetched into a register by the previous node. In this case we want to
2275// do the test for that character first. We do this in separate passes. The
2276// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2277// pass has been performed then subsequent passes will have true in
2278// first_element_checked to indicate that that character does not need to be
2279// checked again.
2280//
ager@chromium.org32912102009-01-16 10:38:43 +00002281// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002282// contain an AlternativeGeneration object. In this AlternativeGeneration
2283// object we can see details of any quick check that was already passed in
2284// order to get to the code we are now generating. The quick check can involve
2285// loading characters, which means we do not need to recheck the bounds
2286// up to the limit the quick check already checked. In addition the quick
2287// check can have involved a mask and compare operation which may simplify
2288// or obviate the need for further checks at some character positions.
2289void TextNode::TextEmitPass(RegExpCompiler* compiler,
2290 TextEmitPassType pass,
2291 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002292 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002293 bool first_element_checked,
2294 int* checked_up_to) {
2295 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2296 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002297 Label* backtrack = trace->backtrack();
2298 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002299 int element_count = elms_->length();
2300 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2301 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002302 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002303 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002304 Vector<const uc16> quarks = elm.data.u_atom->data();
2305 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2306 if (first_element_checked && i == 0 && j == 0) continue;
2307 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2308 EmitCharacterFunction* emit_function = NULL;
2309 switch (pass) {
2310 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002311 ASSERT(ascii);
2312 if (quarks[j] > String::kMaxAsciiCharCode) {
2313 assembler->GoTo(backtrack);
2314 return;
2315 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002316 break;
2317 case NON_LETTER_CHARACTER_MATCH:
2318 emit_function = &EmitAtomNonLetter;
2319 break;
2320 case SIMPLE_CHARACTER_MATCH:
2321 emit_function = &EmitSimpleCharacter;
2322 break;
2323 case CASE_CHARACTER_MATCH:
2324 emit_function = &EmitAtomLetter;
2325 break;
2326 default:
2327 break;
2328 }
2329 if (emit_function != NULL) {
2330 bool bound_checked = emit_function(compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002331 quarks[j],
2332 backtrack,
2333 cp_offset + j,
2334 *checked_up_to < cp_offset + j,
2335 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002336 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002337 }
2338 }
2339 } else {
2340 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002341 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002342 if (first_element_checked && i == 0) continue;
2343 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002344 RegExpCharacterClass* cc = elm.data.u_char_class;
2345 EmitCharClass(assembler,
2346 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002347 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002348 backtrack,
2349 cp_offset,
2350 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002351 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002352 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002353 }
2354 }
2355 }
2356}
2357
2358
2359int TextNode::Length() {
2360 TextElement elm = elms_->last();
2361 ASSERT(elm.cp_offset >= 0);
2362 if (elm.type == TextElement::ATOM) {
2363 return elm.cp_offset + elm.data.u_atom->data().length();
2364 } else {
2365 return elm.cp_offset + 1;
2366 }
2367}
2368
2369
ager@chromium.org381abbb2009-02-25 13:23:22 +00002370bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2371 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2372 if (ignore_case) {
2373 return pass == SIMPLE_CHARACTER_MATCH;
2374 } else {
2375 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2376 }
2377}
2378
2379
ager@chromium.org8bb60582008-12-11 12:02:20 +00002380// This generates the code to match a text node. A text node can contain
2381// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002382// way) and character classes. For efficiency we do not do this in a single
2383// pass from left to right. Instead we pass over the text node several times,
2384// emitting code for some character positions every time. See the comment on
2385// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002386void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002387 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002388 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002389 ASSERT(limit_result == CONTINUE);
2390
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002391 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2392 compiler->SetRegExpTooBig();
2393 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002394 }
2395
2396 if (compiler->ascii()) {
2397 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002398 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002399 }
2400
2401 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002402 int bound_checked_to = trace->cp_offset() - 1;
2403 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002404
2405 // If a character is preloaded into the current character register then
2406 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002407 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002408 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2409 if (!SkipPass(pass, compiler->ignore_case())) {
2410 TextEmitPass(compiler,
2411 static_cast<TextEmitPassType>(pass),
2412 true,
2413 trace,
2414 false,
2415 &bound_checked_to);
2416 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002417 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002418 first_elt_done = true;
2419 }
2420
ager@chromium.org381abbb2009-02-25 13:23:22 +00002421 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2422 if (!SkipPass(pass, compiler->ignore_case())) {
2423 TextEmitPass(compiler,
2424 static_cast<TextEmitPassType>(pass),
2425 false,
2426 trace,
2427 first_elt_done,
2428 &bound_checked_to);
2429 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002430 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002431
ager@chromium.org32912102009-01-16 10:38:43 +00002432 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002433 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002434 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002435 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002436 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002437}
2438
2439
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002440void Trace::InvalidateCurrentCharacter() {
2441 characters_preloaded_ = 0;
2442}
2443
2444
2445void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002446 ASSERT(by > 0);
2447 // We don't have an instruction for shifting the current character register
2448 // down or for using a shifted value for anything so lets just forget that
2449 // we preloaded any characters into it.
2450 characters_preloaded_ = 0;
2451 // Adjust the offsets of the quick check performed information. This
2452 // information is used to find out what we already determined about the
2453 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002454 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002455 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002456 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2457 compiler->SetRegExpTooBig();
2458 cp_offset_ = 0;
2459 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002460 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002461}
2462
2463
ager@chromium.org38e4c712009-11-11 09:11:58 +00002464void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002465 int element_count = elms_->length();
2466 for (int i = 0; i < element_count; i++) {
2467 TextElement elm = elms_->at(i);
2468 if (elm.type == TextElement::CHAR_CLASS) {
2469 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002470 // None of the standard character classses is different in the case
2471 // independent case and it slows us down if we don't know that.
2472 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002473 ZoneList<CharacterRange>* ranges = cc->ranges();
2474 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002475 for (int j = 0; j < range_count; j++) {
2476 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002477 }
2478 }
2479 }
2480}
2481
2482
ager@chromium.org8bb60582008-12-11 12:02:20 +00002483int TextNode::GreedyLoopTextLength() {
2484 TextElement elm = elms_->at(elms_->length() - 1);
2485 if (elm.type == TextElement::CHAR_CLASS) {
2486 return elm.cp_offset + 1;
2487 } else {
2488 return elm.cp_offset + elm.data.u_atom->data().length();
2489 }
2490}
2491
2492
2493// Finds the fixed match length of a sequence of nodes that goes from
2494// this alternative and back to this choice node. If there are variable
2495// length nodes or other complications in the way then return a sentinel
2496// value indicating that a greedy loop cannot be constructed.
2497int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2498 int length = 0;
2499 RegExpNode* node = alternative->node();
2500 // Later we will generate code for all these text nodes using recursion
2501 // so we have to limit the max number.
2502 int recursion_depth = 0;
2503 while (node != this) {
2504 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2505 return kNodeIsTooComplexForGreedyLoops;
2506 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002507 int node_length = node->GreedyLoopTextLength();
2508 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2509 return kNodeIsTooComplexForGreedyLoops;
2510 }
2511 length += node_length;
2512 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2513 node = seq_node->on_success();
2514 }
2515 return length;
2516}
2517
2518
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002519void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2520 ASSERT_EQ(loop_node_, NULL);
2521 AddAlternative(alt);
2522 loop_node_ = alt.node();
2523}
2524
2525
2526void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2527 ASSERT_EQ(continue_node_, NULL);
2528 AddAlternative(alt);
2529 continue_node_ = alt.node();
2530}
2531
2532
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002533void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002534 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002535 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002536 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2537 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2538 // Update the counter-based backtracking info on the stack. This is an
2539 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002540 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002541 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002542 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002543 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002544 }
ager@chromium.org32912102009-01-16 10:38:43 +00002545 ASSERT(trace->stop_node() == NULL);
2546 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002547 trace->Flush(compiler, this);
2548 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002549 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002550 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002551}
2552
2553
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002554int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002555 int preload_characters = EatsAtLeast(4, 0);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002556 if (compiler->macro_assembler()->CanReadUnaligned()) {
2557 bool ascii = compiler->ascii();
2558 if (ascii) {
2559 if (preload_characters > 4) preload_characters = 4;
2560 // We can't preload 3 characters because there is no machine instruction
2561 // to do that. We can't just load 4 because we could be reading
2562 // beyond the end of the string, which could cause a memory fault.
2563 if (preload_characters == 3) preload_characters = 2;
2564 } else {
2565 if (preload_characters > 2) preload_characters = 2;
2566 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002567 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002568 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002569 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002570 return preload_characters;
2571}
2572
2573
2574// This class is used when generating the alternatives in a choice node. It
2575// records the way the alternative is being code generated.
2576class AlternativeGeneration: public Malloced {
2577 public:
2578 AlternativeGeneration()
2579 : possible_success(),
2580 expects_preload(false),
2581 after(),
2582 quick_check_details() { }
2583 Label possible_success;
2584 bool expects_preload;
2585 Label after;
2586 QuickCheckDetails quick_check_details;
2587};
2588
2589
2590// Creates a list of AlternativeGenerations. If the list has a reasonable
2591// size then it is on the stack, otherwise the excess is on the heap.
2592class AlternativeGenerationList {
2593 public:
2594 explicit AlternativeGenerationList(int count)
2595 : alt_gens_(count) {
2596 for (int i = 0; i < count && i < kAFew; i++) {
2597 alt_gens_.Add(a_few_alt_gens_ + i);
2598 }
2599 for (int i = kAFew; i < count; i++) {
2600 alt_gens_.Add(new AlternativeGeneration());
2601 }
2602 }
2603 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002604 for (int i = kAFew; i < alt_gens_.length(); i++) {
2605 delete alt_gens_[i];
2606 alt_gens_[i] = NULL;
2607 }
2608 }
2609
2610 AlternativeGeneration* at(int i) {
2611 return alt_gens_[i];
2612 }
2613 private:
2614 static const int kAFew = 10;
2615 ZoneList<AlternativeGeneration*> alt_gens_;
2616 AlternativeGeneration a_few_alt_gens_[kAFew];
2617};
2618
2619
2620/* Code generation for choice nodes.
2621 *
2622 * We generate quick checks that do a mask and compare to eliminate a
2623 * choice. If the quick check succeeds then it jumps to the continuation to
2624 * do slow checks and check subsequent nodes. If it fails (the common case)
2625 * it falls through to the next choice.
2626 *
2627 * Here is the desired flow graph. Nodes directly below each other imply
2628 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2629 * 3 doesn't have a quick check so we have to call the slow check.
2630 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2631 * regexp continuation is generated directly after the Sn node, up to the
2632 * next GoTo if we decide to reuse some already generated code. Some
2633 * nodes expect preload_characters to be preloaded into the current
2634 * character register. R nodes do this preloading. Vertices are marked
2635 * F for failures and S for success (possible success in the case of quick
2636 * nodes). L, V, < and > are used as arrow heads.
2637 *
2638 * ----------> R
2639 * |
2640 * V
2641 * Q1 -----> S1
2642 * | S /
2643 * F| /
2644 * | F/
2645 * | /
2646 * | R
2647 * | /
2648 * V L
2649 * Q2 -----> S2
2650 * | S /
2651 * F| /
2652 * | F/
2653 * | /
2654 * | R
2655 * | /
2656 * V L
2657 * S3
2658 * |
2659 * F|
2660 * |
2661 * R
2662 * |
2663 * backtrack V
2664 * <----------Q4
2665 * \ F |
2666 * \ |S
2667 * \ F V
2668 * \-----S4
2669 *
2670 * For greedy loops we reverse our expectation and expect to match rather
2671 * than fail. Therefore we want the loop code to look like this (U is the
2672 * unwind code that steps back in the greedy loop). The following alternatives
2673 * look the same as above.
2674 * _____
2675 * / \
2676 * V |
2677 * ----------> S1 |
2678 * /| |
2679 * / |S |
2680 * F/ \_____/
2681 * /
2682 * |<-----------
2683 * | \
2684 * V \
2685 * Q2 ---> S2 \
2686 * | S / |
2687 * F| / |
2688 * | F/ |
2689 * | / |
2690 * | R |
2691 * | / |
2692 * F VL |
2693 * <------U |
2694 * back |S |
2695 * \______________/
2696 */
2697
2698
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002699void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002700 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2701 int choice_count = alternatives_->length();
2702#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002703 for (int i = 0; i < choice_count - 1; i++) {
2704 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002705 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002706 int guard_count = (guards == NULL) ? 0 : guards->length();
2707 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002708 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002709 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002710 }
2711#endif
2712
ager@chromium.org32912102009-01-16 10:38:43 +00002713 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002714 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002715 ASSERT(limit_result == CONTINUE);
2716
ager@chromium.org381abbb2009-02-25 13:23:22 +00002717 int new_flush_budget = trace->flush_budget() / choice_count;
2718 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2719 trace->Flush(compiler, this);
2720 return;
2721 }
2722
ager@chromium.org8bb60582008-12-11 12:02:20 +00002723 RecursionCheck rc(compiler);
2724
ager@chromium.org32912102009-01-16 10:38:43 +00002725 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002726
2727 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2728 bool greedy_loop = false;
2729 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002730 Trace counter_backtrack_trace;
2731 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002732 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2733
ager@chromium.org8bb60582008-12-11 12:02:20 +00002734 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2735 // Here we have special handling for greedy loops containing only text nodes
2736 // and other simple nodes. These are handled by pushing the current
2737 // position on the stack and then incrementing the current position each
2738 // time around the switch. On backtrack we decrement the current position
2739 // and check it against the pushed value. This avoids pushing backtrack
2740 // information for each iteration of the loop, which could take up a lot of
2741 // space.
2742 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002743 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002744 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002745 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002746 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002747 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002748 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002749 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002750 Label loop_label;
2751 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002752 greedy_match_trace.set_stop_node(this);
2753 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002754 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002755 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002756 }
2757
2758 Label second_choice; // For use in greedy matches.
2759 macro_assembler->Bind(&second_choice);
2760
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002761 int first_normal_choice = greedy_loop ? 1 : 0;
2762
2763 int preload_characters = CalculatePreloadCharacters(compiler);
2764 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002765 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002766 bool preload_has_checked_bounds = preload_is_current;
2767
2768 AlternativeGenerationList alt_gens(choice_count);
2769
ager@chromium.org8bb60582008-12-11 12:02:20 +00002770 // For now we just call all choices one after the other. The idea ultimately
2771 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002772 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002773 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002774 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002775 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002776 ZoneList<Guard*>* guards = alternative.guards();
2777 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002778 Trace new_trace(*current_trace);
2779 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002780 preload_characters :
2781 0);
2782 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002783 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002784 }
ager@chromium.org32912102009-01-16 10:38:43 +00002785 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002786 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002787 alt_gen->expects_preload = preload_is_current;
2788 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002789 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002790 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002791 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002792 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002793 preload_has_checked_bounds,
2794 &alt_gen->possible_success,
2795 &alt_gen->quick_check_details,
2796 i < choice_count - 1)) {
2797 // Quick check was generated for this choice.
2798 preload_is_current = true;
2799 preload_has_checked_bounds = true;
2800 // On the last choice in the ChoiceNode we generated the quick
2801 // check to fall through on possible success. So now we need to
2802 // generate the full check inline.
2803 if (i == choice_count - 1) {
2804 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002805 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2806 new_trace.set_characters_preloaded(preload_characters);
2807 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002808 generate_full_check_inline = true;
2809 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002810 } else if (alt_gen->quick_check_details.cannot_match()) {
2811 if (i == choice_count - 1 && !greedy_loop) {
2812 macro_assembler->GoTo(trace->backtrack());
2813 }
2814 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002815 } else {
2816 // No quick check was generated. Put the full code here.
2817 // If this is not the first choice then there could be slow checks from
2818 // previous cases that go here when they fail. There's no reason to
2819 // insist that they preload characters since the slow check we are about
2820 // to generate probably can't use it.
2821 if (i != first_normal_choice) {
2822 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002823 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002824 }
2825 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002826 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002827 }
2828 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002829 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002830 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002831 if (new_trace.actions() != NULL) {
2832 new_trace.set_flush_budget(new_flush_budget);
2833 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002834 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002835 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002836 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002837 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002838 preload_is_current = false;
2839 }
2840 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002841 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002842 if (greedy_loop) {
2843 macro_assembler->Bind(&greedy_loop_label);
2844 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002845 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002846 // Otherwise try the second priority at an earlier position.
2847 macro_assembler->AdvanceCurrentPosition(-text_length);
2848 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002849 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002850
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002851 // At this point we need to generate slow checks for the alternatives where
2852 // the quick check was inlined. We can recognize these because the associated
2853 // label was bound.
2854 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2855 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002856 Trace new_trace(*current_trace);
2857 // If there are actions to be flushed we have to limit how many times
2858 // they are flushed. Take the budget of the parent trace and distribute
2859 // it fairly amongst the children.
2860 if (new_trace.actions() != NULL) {
2861 new_trace.set_flush_budget(new_flush_budget);
2862 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002863 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002864 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002865 alternatives_->at(i),
2866 alt_gen,
2867 preload_characters,
2868 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002869 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002870}
2871
2872
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002873void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002874 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002875 GuardedAlternative alternative,
2876 AlternativeGeneration* alt_gen,
2877 int preload_characters,
2878 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002879 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002880
2881 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2882 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002883 Trace out_of_line_trace(*trace);
2884 out_of_line_trace.set_characters_preloaded(preload_characters);
2885 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002886 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002887 ZoneList<Guard*>* guards = alternative.guards();
2888 int guard_count = (guards == NULL) ? 0 : guards->length();
2889 if (next_expects_preload) {
2890 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00002891 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002892 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002893 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002894 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002895 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002896 macro_assembler->Bind(&reload_current_char);
2897 // Reload the current character, since the next quick check expects that.
2898 // We don't need to check bounds here because we only get into this
2899 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00002900 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002901 NULL,
2902 false,
2903 preload_characters);
2904 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002905 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00002906 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002907 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002908 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002909 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002910 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002911 }
2912}
2913
2914
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002915void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002916 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002917 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002918 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002919 ASSERT(limit_result == CONTINUE);
2920
2921 RecursionCheck rc(compiler);
2922
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002923 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002924 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00002925 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002926 new_capture(data_.u_position_register.reg,
2927 data_.u_position_register.is_capture,
2928 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002929 Trace new_trace = *trace;
2930 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002931 on_success()->Emit(compiler, &new_trace);
2932 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002933 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002934 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002935 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002936 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00002937 Trace new_trace = *trace;
2938 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002939 on_success()->Emit(compiler, &new_trace);
2940 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002941 }
2942 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002943 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002944 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00002945 Trace new_trace = *trace;
2946 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002947 on_success()->Emit(compiler, &new_trace);
2948 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002949 }
2950 case CLEAR_CAPTURES: {
2951 Trace::DeferredClearCaptures
2952 new_capture(Interval(data_.u_clear_captures.range_from,
2953 data_.u_clear_captures.range_to));
2954 Trace new_trace = *trace;
2955 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002956 on_success()->Emit(compiler, &new_trace);
2957 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002958 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002959 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002960 if (!trace->is_trivial()) {
2961 trace->Flush(compiler, this);
2962 } else {
2963 assembler->WriteCurrentPositionToRegister(
2964 data_.u_submatch.current_position_register, 0);
2965 assembler->WriteStackPointerToRegister(
2966 data_.u_submatch.stack_pointer_register);
2967 on_success()->Emit(compiler, trace);
2968 }
2969 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002970 case EMPTY_MATCH_CHECK: {
2971 int start_pos_reg = data_.u_empty_match_check.start_register;
2972 int stored_pos = 0;
2973 int rep_reg = data_.u_empty_match_check.repetition_register;
2974 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
2975 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
2976 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
2977 // If we know we haven't advanced and there is no minimum we
2978 // can just backtrack immediately.
2979 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00002980 } else if (know_dist && stored_pos < trace->cp_offset()) {
2981 // If we know we've advanced we can generate the continuation
2982 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002983 on_success()->Emit(compiler, trace);
2984 } else if (!trace->is_trivial()) {
2985 trace->Flush(compiler, this);
2986 } else {
2987 Label skip_empty_check;
2988 // If we have a minimum number of repetitions we check the current
2989 // number first and skip the empty check if it's not enough.
2990 if (has_minimum) {
2991 int limit = data_.u_empty_match_check.repetition_limit;
2992 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
2993 }
2994 // If the match is empty we bail out, otherwise we fall through
2995 // to the on-success continuation.
2996 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
2997 trace->backtrack());
2998 assembler->Bind(&skip_empty_check);
2999 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003000 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003001 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003002 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003003 case POSITIVE_SUBMATCH_SUCCESS: {
3004 if (!trace->is_trivial()) {
3005 trace->Flush(compiler, this);
3006 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003007 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003008 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003009 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003010 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003011 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003012 int clear_register_count = data_.u_submatch.clear_register_count;
3013 if (clear_register_count == 0) {
3014 on_success()->Emit(compiler, trace);
3015 return;
3016 }
3017 int clear_registers_from = data_.u_submatch.clear_register_from;
3018 Label clear_registers_backtrack;
3019 Trace new_trace = *trace;
3020 new_trace.set_backtrack(&clear_registers_backtrack);
3021 on_success()->Emit(compiler, &new_trace);
3022
3023 assembler->Bind(&clear_registers_backtrack);
3024 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3025 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3026
3027 ASSERT(trace->backtrack() == NULL);
3028 assembler->Backtrack();
3029 return;
3030 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003031 default:
3032 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003033 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003034}
3035
3036
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003037void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003038 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003039 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003040 trace->Flush(compiler, this);
3041 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003042 }
3043
ager@chromium.org32912102009-01-16 10:38:43 +00003044 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003045 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003046 ASSERT(limit_result == CONTINUE);
3047
3048 RecursionCheck rc(compiler);
3049
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003050 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003051 if (compiler->ignore_case()) {
3052 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3053 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003054 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003055 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003056 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003057 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003058}
3059
3060
3061// -------------------------------------------------------------------
3062// Dot/dotty output
3063
3064
3065#ifdef DEBUG
3066
3067
3068class DotPrinter: public NodeVisitor {
3069 public:
3070 explicit DotPrinter(bool ignore_case)
3071 : ignore_case_(ignore_case),
3072 stream_(&alloc_) { }
3073 void PrintNode(const char* label, RegExpNode* node);
3074 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003075 void PrintAttributes(RegExpNode* from);
3076 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003077 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003078#define DECLARE_VISIT(Type) \
3079 virtual void Visit##Type(Type##Node* that);
3080FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3081#undef DECLARE_VISIT
3082 private:
3083 bool ignore_case_;
3084 HeapStringAllocator alloc_;
3085 StringStream stream_;
3086};
3087
3088
3089void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3090 stream()->Add("digraph G {\n graph [label=\"");
3091 for (int i = 0; label[i]; i++) {
3092 switch (label[i]) {
3093 case '\\':
3094 stream()->Add("\\\\");
3095 break;
3096 case '"':
3097 stream()->Add("\"");
3098 break;
3099 default:
3100 stream()->Put(label[i]);
3101 break;
3102 }
3103 }
3104 stream()->Add("\"];\n");
3105 Visit(node);
3106 stream()->Add("}\n");
3107 printf("%s", *(stream()->ToCString()));
3108}
3109
3110
3111void DotPrinter::Visit(RegExpNode* node) {
3112 if (node->info()->visited) return;
3113 node->info()->visited = true;
3114 node->Accept(this);
3115}
3116
3117
3118void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003119 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3120 Visit(on_failure);
3121}
3122
3123
3124class TableEntryBodyPrinter {
3125 public:
3126 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3127 : stream_(stream), choice_(choice) { }
3128 void Call(uc16 from, DispatchTable::Entry entry) {
3129 OutSet* out_set = entry.out_set();
3130 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3131 if (out_set->Get(i)) {
3132 stream()->Add(" n%p:s%io%i -> n%p;\n",
3133 choice(),
3134 from,
3135 i,
3136 choice()->alternatives()->at(i).node());
3137 }
3138 }
3139 }
3140 private:
3141 StringStream* stream() { return stream_; }
3142 ChoiceNode* choice() { return choice_; }
3143 StringStream* stream_;
3144 ChoiceNode* choice_;
3145};
3146
3147
3148class TableEntryHeaderPrinter {
3149 public:
3150 explicit TableEntryHeaderPrinter(StringStream* stream)
3151 : first_(true), stream_(stream) { }
3152 void Call(uc16 from, DispatchTable::Entry entry) {
3153 if (first_) {
3154 first_ = false;
3155 } else {
3156 stream()->Add("|");
3157 }
3158 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3159 OutSet* out_set = entry.out_set();
3160 int priority = 0;
3161 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3162 if (out_set->Get(i)) {
3163 if (priority > 0) stream()->Add("|");
3164 stream()->Add("<s%io%i> %i", from, i, priority);
3165 priority++;
3166 }
3167 }
3168 stream()->Add("}}");
3169 }
3170 private:
3171 bool first_;
3172 StringStream* stream() { return stream_; }
3173 StringStream* stream_;
3174};
3175
3176
3177class AttributePrinter {
3178 public:
3179 explicit AttributePrinter(DotPrinter* out)
3180 : out_(out), first_(true) { }
3181 void PrintSeparator() {
3182 if (first_) {
3183 first_ = false;
3184 } else {
3185 out_->stream()->Add("|");
3186 }
3187 }
3188 void PrintBit(const char* name, bool value) {
3189 if (!value) return;
3190 PrintSeparator();
3191 out_->stream()->Add("{%s}", name);
3192 }
3193 void PrintPositive(const char* name, int value) {
3194 if (value < 0) return;
3195 PrintSeparator();
3196 out_->stream()->Add("{%s|%x}", name, value);
3197 }
3198 private:
3199 DotPrinter* out_;
3200 bool first_;
3201};
3202
3203
3204void DotPrinter::PrintAttributes(RegExpNode* that) {
3205 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3206 "margin=0.1, fontsize=10, label=\"{",
3207 that);
3208 AttributePrinter printer(this);
3209 NodeInfo* info = that->info();
3210 printer.PrintBit("NI", info->follows_newline_interest);
3211 printer.PrintBit("WI", info->follows_word_interest);
3212 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003213 Label* label = that->label();
3214 if (label->is_bound())
3215 printer.PrintPositive("@", label->pos());
3216 stream()->Add("}\"];\n");
3217 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3218 "arrowhead=none];\n", that, that);
3219}
3220
3221
3222static const bool kPrintDispatchTable = false;
3223void DotPrinter::VisitChoice(ChoiceNode* that) {
3224 if (kPrintDispatchTable) {
3225 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3226 TableEntryHeaderPrinter header_printer(stream());
3227 that->GetTable(ignore_case_)->ForEach(&header_printer);
3228 stream()->Add("\"]\n", that);
3229 PrintAttributes(that);
3230 TableEntryBodyPrinter body_printer(stream(), that);
3231 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003232 } else {
3233 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3234 for (int i = 0; i < that->alternatives()->length(); i++) {
3235 GuardedAlternative alt = that->alternatives()->at(i);
3236 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3237 }
3238 }
3239 for (int i = 0; i < that->alternatives()->length(); i++) {
3240 GuardedAlternative alt = that->alternatives()->at(i);
3241 alt.node()->Accept(this);
3242 }
3243}
3244
3245
3246void DotPrinter::VisitText(TextNode* that) {
3247 stream()->Add(" n%p [label=\"", that);
3248 for (int i = 0; i < that->elements()->length(); i++) {
3249 if (i > 0) stream()->Add(" ");
3250 TextElement elm = that->elements()->at(i);
3251 switch (elm.type) {
3252 case TextElement::ATOM: {
3253 stream()->Add("'%w'", elm.data.u_atom->data());
3254 break;
3255 }
3256 case TextElement::CHAR_CLASS: {
3257 RegExpCharacterClass* node = elm.data.u_char_class;
3258 stream()->Add("[");
3259 if (node->is_negated())
3260 stream()->Add("^");
3261 for (int j = 0; j < node->ranges()->length(); j++) {
3262 CharacterRange range = node->ranges()->at(j);
3263 stream()->Add("%k-%k", range.from(), range.to());
3264 }
3265 stream()->Add("]");
3266 break;
3267 }
3268 default:
3269 UNREACHABLE();
3270 }
3271 }
3272 stream()->Add("\", shape=box, peripheries=2];\n");
3273 PrintAttributes(that);
3274 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3275 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003276}
3277
3278
3279void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3280 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3281 that,
3282 that->start_register(),
3283 that->end_register());
3284 PrintAttributes(that);
3285 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3286 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003287}
3288
3289
3290void DotPrinter::VisitEnd(EndNode* that) {
3291 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3292 PrintAttributes(that);
3293}
3294
3295
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003296void DotPrinter::VisitAssertion(AssertionNode* that) {
3297 stream()->Add(" n%p [", that);
3298 switch (that->type()) {
3299 case AssertionNode::AT_END:
3300 stream()->Add("label=\"$\", shape=septagon");
3301 break;
3302 case AssertionNode::AT_START:
3303 stream()->Add("label=\"^\", shape=septagon");
3304 break;
3305 case AssertionNode::AT_BOUNDARY:
3306 stream()->Add("label=\"\\b\", shape=septagon");
3307 break;
3308 case AssertionNode::AT_NON_BOUNDARY:
3309 stream()->Add("label=\"\\B\", shape=septagon");
3310 break;
3311 case AssertionNode::AFTER_NEWLINE:
3312 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3313 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003314 case AssertionNode::AFTER_WORD_CHARACTER:
3315 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3316 break;
3317 case AssertionNode::AFTER_NONWORD_CHARACTER:
3318 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3319 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003320 }
3321 stream()->Add("];\n");
3322 PrintAttributes(that);
3323 RegExpNode* successor = that->on_success();
3324 stream()->Add(" n%p -> n%p;\n", that, successor);
3325 Visit(successor);
3326}
3327
3328
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003329void DotPrinter::VisitAction(ActionNode* that) {
3330 stream()->Add(" n%p [", that);
3331 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003332 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003333 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3334 that->data_.u_store_register.reg,
3335 that->data_.u_store_register.value);
3336 break;
3337 case ActionNode::INCREMENT_REGISTER:
3338 stream()->Add("label=\"$%i++\", shape=octagon",
3339 that->data_.u_increment_register.reg);
3340 break;
3341 case ActionNode::STORE_POSITION:
3342 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3343 that->data_.u_position_register.reg);
3344 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003345 case ActionNode::BEGIN_SUBMATCH:
3346 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3347 that->data_.u_submatch.current_position_register);
3348 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003349 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003350 stream()->Add("label=\"escape\", shape=septagon");
3351 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003352 case ActionNode::EMPTY_MATCH_CHECK:
3353 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3354 that->data_.u_empty_match_check.start_register,
3355 that->data_.u_empty_match_check.repetition_register,
3356 that->data_.u_empty_match_check.repetition_limit);
3357 break;
3358 case ActionNode::CLEAR_CAPTURES: {
3359 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3360 that->data_.u_clear_captures.range_from,
3361 that->data_.u_clear_captures.range_to);
3362 break;
3363 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003364 }
3365 stream()->Add("];\n");
3366 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003367 RegExpNode* successor = that->on_success();
3368 stream()->Add(" n%p -> n%p;\n", that, successor);
3369 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003370}
3371
3372
3373class DispatchTableDumper {
3374 public:
3375 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3376 void Call(uc16 key, DispatchTable::Entry entry);
3377 StringStream* stream() { return stream_; }
3378 private:
3379 StringStream* stream_;
3380};
3381
3382
3383void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3384 stream()->Add("[%k-%k]: {", key, entry.to());
3385 OutSet* set = entry.out_set();
3386 bool first = true;
3387 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3388 if (set->Get(i)) {
3389 if (first) {
3390 first = false;
3391 } else {
3392 stream()->Add(", ");
3393 }
3394 stream()->Add("%i", i);
3395 }
3396 }
3397 stream()->Add("}\n");
3398}
3399
3400
3401void DispatchTable::Dump() {
3402 HeapStringAllocator alloc;
3403 StringStream stream(&alloc);
3404 DispatchTableDumper dumper(&stream);
3405 tree()->ForEach(&dumper);
3406 OS::PrintError("%s", *stream.ToCString());
3407}
3408
3409
3410void RegExpEngine::DotPrint(const char* label,
3411 RegExpNode* node,
3412 bool ignore_case) {
3413 DotPrinter printer(ignore_case);
3414 printer.PrintNode(label, node);
3415}
3416
3417
3418#endif // DEBUG
3419
3420
3421// -------------------------------------------------------------------
3422// Tree to graph conversion
3423
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003424static const int kSpaceRangeCount = 20;
3425static const int kSpaceRangeAsciiCount = 4;
3426static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3427 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3428 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3429
3430static const int kWordRangeCount = 8;
3431static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3432 '_', 'a', 'z' };
3433
3434static const int kDigitRangeCount = 2;
3435static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3436
3437static const int kLineTerminatorRangeCount = 6;
3438static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3439 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003440
3441RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003442 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003443 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3444 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003445 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003446}
3447
3448
3449RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003450 RegExpNode* on_success) {
3451 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003452}
3453
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003454static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3455 const uc16* special_class,
3456 int length) {
3457 ASSERT(ranges->length() != 0);
3458 ASSERT(length != 0);
3459 ASSERT(special_class[0] != 0);
3460 if (ranges->length() != (length >> 1) + 1) {
3461 return false;
3462 }
3463 CharacterRange range = ranges->at(0);
3464 if (range.from() != 0) {
3465 return false;
3466 }
3467 for (int i = 0; i < length; i += 2) {
3468 if (special_class[i] != (range.to() + 1)) {
3469 return false;
3470 }
3471 range = ranges->at((i >> 1) + 1);
3472 if (special_class[i+1] != range.from() - 1) {
3473 return false;
3474 }
3475 }
3476 if (range.to() != 0xffff) {
3477 return false;
3478 }
3479 return true;
3480}
3481
3482
3483static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3484 const uc16* special_class,
3485 int length) {
3486 if (ranges->length() * 2 != length) {
3487 return false;
3488 }
3489 for (int i = 0; i < length; i += 2) {
3490 CharacterRange range = ranges->at(i >> 1);
3491 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3492 return false;
3493 }
3494 }
3495 return true;
3496}
3497
3498
3499bool RegExpCharacterClass::is_standard() {
3500 // TODO(lrn): Remove need for this function, by not throwing away information
3501 // along the way.
3502 if (is_negated_) {
3503 return false;
3504 }
3505 if (set_.is_standard()) {
3506 return true;
3507 }
3508 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3509 set_.set_standard_set_type('s');
3510 return true;
3511 }
3512 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3513 set_.set_standard_set_type('S');
3514 return true;
3515 }
3516 if (CompareInverseRanges(set_.ranges(),
3517 kLineTerminatorRanges,
3518 kLineTerminatorRangeCount)) {
3519 set_.set_standard_set_type('.');
3520 return true;
3521 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003522 if (CompareRanges(set_.ranges(),
3523 kLineTerminatorRanges,
3524 kLineTerminatorRangeCount)) {
3525 set_.set_standard_set_type('n');
3526 return true;
3527 }
3528 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3529 set_.set_standard_set_type('w');
3530 return true;
3531 }
3532 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3533 set_.set_standard_set_type('W');
3534 return true;
3535 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003536 return false;
3537}
3538
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003539
3540RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003541 RegExpNode* on_success) {
3542 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003543}
3544
3545
3546RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003547 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003548 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3549 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003550 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003551 for (int i = 0; i < length; i++) {
3552 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003553 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003554 result->AddAlternative(alternative);
3555 }
3556 return result;
3557}
3558
3559
3560RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003561 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003562 return ToNode(min(),
3563 max(),
3564 is_greedy(),
3565 body(),
3566 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003567 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003568}
3569
3570
3571RegExpNode* RegExpQuantifier::ToNode(int min,
3572 int max,
3573 bool is_greedy,
3574 RegExpTree* body,
3575 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003576 RegExpNode* on_success,
3577 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003578 // x{f, t} becomes this:
3579 //
3580 // (r++)<-.
3581 // | `
3582 // | (x)
3583 // v ^
3584 // (r=0)-->(?)---/ [if r < t]
3585 // |
3586 // [if r >= f] \----> ...
3587 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003588
3589 // 15.10.2.5 RepeatMatcher algorithm.
3590 // The parser has already eliminated the case where max is 0. In the case
3591 // where max_match is zero the parser has removed the quantifier if min was
3592 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3593
3594 // If we know that we cannot match zero length then things are a little
3595 // simpler since we don't need to make the special zero length match check
3596 // from step 2.1. If the min and max are small we can unroll a little in
3597 // this case.
3598 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3599 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3600 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003601 bool body_can_be_empty = (body->min_match() == 0);
3602 int body_start_reg = RegExpCompiler::kNoRegister;
3603 Interval capture_registers = body->CaptureRegisters();
3604 bool needs_capture_clearing = !capture_registers.is_empty();
3605 if (body_can_be_empty) {
3606 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003607 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003608 // Only unroll if there are no captures and the body can't be
3609 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003610 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3611 int new_max = (max == kInfinity) ? max : max - min;
3612 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003613 RegExpNode* answer = ToNode(
3614 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003615 // Unroll the forced matches from 0 to min. This can cause chains of
3616 // TextNodes (which the parser does not generate). These should be
3617 // combined if it turns out they hinder good code generation.
3618 for (int i = 0; i < min; i++) {
3619 answer = body->ToNode(compiler, answer);
3620 }
3621 return answer;
3622 }
3623 if (max <= kMaxUnrolledMaxMatches) {
3624 ASSERT(min == 0);
3625 // Unroll the optional matches up to max.
3626 RegExpNode* answer = on_success;
3627 for (int i = 0; i < max; i++) {
3628 ChoiceNode* alternation = new ChoiceNode(2);
3629 if (is_greedy) {
3630 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3631 answer)));
3632 alternation->AddAlternative(GuardedAlternative(on_success));
3633 } else {
3634 alternation->AddAlternative(GuardedAlternative(on_success));
3635 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3636 answer)));
3637 }
3638 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003639 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003640 }
3641 return answer;
3642 }
3643 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003644 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003645 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003646 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003647 int reg_ctr = needs_counter
3648 ? compiler->AllocateRegister()
3649 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003650 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003651 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003652 RegExpNode* loop_return = needs_counter
3653 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3654 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003655 if (body_can_be_empty) {
3656 // If the body can be empty we need to check if it was and then
3657 // backtrack.
3658 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3659 reg_ctr,
3660 min,
3661 loop_return);
3662 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003663 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003664 if (body_can_be_empty) {
3665 // If the body can be empty we need to store the start position
3666 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003667 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003668 }
3669 if (needs_capture_clearing) {
3670 // Before entering the body of this loop we need to clear captures.
3671 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3672 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003673 GuardedAlternative body_alt(body_node);
3674 if (has_max) {
3675 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3676 body_alt.AddGuard(body_guard);
3677 }
3678 GuardedAlternative rest_alt(on_success);
3679 if (has_min) {
3680 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3681 rest_alt.AddGuard(rest_guard);
3682 }
3683 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003684 center->AddLoopAlternative(body_alt);
3685 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003686 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003687 center->AddContinueAlternative(rest_alt);
3688 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003689 }
3690 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003691 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003692 } else {
3693 return center;
3694 }
3695}
3696
3697
3698RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003699 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003700 NodeInfo info;
3701 switch (type()) {
3702 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003703 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003704 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003705 return AssertionNode::AtStart(on_success);
3706 case BOUNDARY:
3707 return AssertionNode::AtBoundary(on_success);
3708 case NON_BOUNDARY:
3709 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003710 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003711 return AssertionNode::AtEnd(on_success);
3712 case END_OF_LINE: {
3713 // Compile $ in multiline regexps as an alternation with a positive
3714 // lookahead in one side and an end-of-input on the other side.
3715 // We need two registers for the lookahead.
3716 int stack_pointer_register = compiler->AllocateRegister();
3717 int position_register = compiler->AllocateRegister();
3718 // The ChoiceNode to distinguish between a newline and end-of-input.
3719 ChoiceNode* result = new ChoiceNode(2);
3720 // Create a newline atom.
3721 ZoneList<CharacterRange>* newline_ranges =
3722 new ZoneList<CharacterRange>(3);
3723 CharacterRange::AddClassEscape('n', newline_ranges);
3724 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3725 TextNode* newline_matcher = new TextNode(
3726 newline_atom,
3727 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3728 position_register,
3729 0, // No captures inside.
3730 -1, // Ignored if no captures.
3731 on_success));
3732 // Create an end-of-input matcher.
3733 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3734 stack_pointer_register,
3735 position_register,
3736 newline_matcher);
3737 // Add the two alternatives to the ChoiceNode.
3738 GuardedAlternative eol_alternative(end_of_line);
3739 result->AddAlternative(eol_alternative);
3740 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3741 result->AddAlternative(end_alternative);
3742 return result;
3743 }
3744 default:
3745 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003746 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003747 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003748}
3749
3750
3751RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003752 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003753 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3754 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003755 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003756}
3757
3758
3759RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003760 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003761 return on_success;
3762}
3763
3764
3765RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003766 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003767 int stack_pointer_register = compiler->AllocateRegister();
3768 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003769
3770 const int registers_per_capture = 2;
3771 const int register_of_first_capture = 2;
3772 int register_count = capture_count_ * registers_per_capture;
3773 int register_start =
3774 register_of_first_capture + capture_from_ * registers_per_capture;
3775
ager@chromium.org8bb60582008-12-11 12:02:20 +00003776 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003777 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003778 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003779 stack_pointer_register,
3780 position_register,
3781 body()->ToNode(
3782 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003783 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3784 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003785 register_count,
3786 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003787 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003788 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003789 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003790 // We use a ChoiceNode for a negative lookahead because it has most of
3791 // the characteristics we need. It has the body of the lookahead as its
3792 // first alternative and the expression after the lookahead of the second
3793 // alternative. If the first alternative succeeds then the
3794 // NegativeSubmatchSuccess will unwind the stack including everything the
3795 // choice node set up and backtrack. If the first alternative fails then
3796 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003797 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3798 // ChoiceNode that knows to ignore the first exit when calculating quick
3799 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003800 GuardedAlternative body_alt(
3801 body()->ToNode(
3802 compiler,
3803 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003804 position_register,
3805 register_count,
3806 register_start)));
3807 ChoiceNode* choice_node =
3808 new NegativeLookaheadChoiceNode(body_alt,
3809 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003810 return ActionNode::BeginSubmatch(stack_pointer_register,
3811 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003812 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003813 }
3814}
3815
3816
3817RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003818 RegExpNode* on_success) {
3819 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003820}
3821
3822
3823RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3824 int index,
3825 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003826 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003827 int start_reg = RegExpCapture::StartRegister(index);
3828 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003829 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003830 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003831 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003832}
3833
3834
3835RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003836 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003837 ZoneList<RegExpTree*>* children = nodes();
3838 RegExpNode* current = on_success;
3839 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003840 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003841 }
3842 return current;
3843}
3844
3845
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003846static void AddClass(const uc16* elmv,
3847 int elmc,
3848 ZoneList<CharacterRange>* ranges) {
3849 for (int i = 0; i < elmc; i += 2) {
3850 ASSERT(elmv[i] <= elmv[i + 1]);
3851 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3852 }
3853}
3854
3855
3856static void AddClassNegated(const uc16 *elmv,
3857 int elmc,
3858 ZoneList<CharacterRange>* ranges) {
3859 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003860 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003861 uc16 last = 0x0000;
3862 for (int i = 0; i < elmc; i += 2) {
3863 ASSERT(last <= elmv[i] - 1);
3864 ASSERT(elmv[i] <= elmv[i + 1]);
3865 ranges->Add(CharacterRange(last, elmv[i] - 1));
3866 last = elmv[i + 1] + 1;
3867 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003868 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003869}
3870
3871
3872void CharacterRange::AddClassEscape(uc16 type,
3873 ZoneList<CharacterRange>* ranges) {
3874 switch (type) {
3875 case 's':
3876 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3877 break;
3878 case 'S':
3879 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3880 break;
3881 case 'w':
3882 AddClass(kWordRanges, kWordRangeCount, ranges);
3883 break;
3884 case 'W':
3885 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3886 break;
3887 case 'd':
3888 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3889 break;
3890 case 'D':
3891 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3892 break;
3893 case '.':
3894 AddClassNegated(kLineTerminatorRanges,
3895 kLineTerminatorRangeCount,
3896 ranges);
3897 break;
3898 // This is not a character range as defined by the spec but a
3899 // convenient shorthand for a character class that matches any
3900 // character.
3901 case '*':
3902 ranges->Add(CharacterRange::Everything());
3903 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003904 // This is the set of characters matched by the $ and ^ symbols
3905 // in multiline mode.
3906 case 'n':
3907 AddClass(kLineTerminatorRanges,
3908 kLineTerminatorRangeCount,
3909 ranges);
3910 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003911 default:
3912 UNREACHABLE();
3913 }
3914}
3915
3916
3917Vector<const uc16> CharacterRange::GetWordBounds() {
3918 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3919}
3920
3921
3922class CharacterRangeSplitter {
3923 public:
3924 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3925 ZoneList<CharacterRange>** excluded)
3926 : included_(included),
3927 excluded_(excluded) { }
3928 void Call(uc16 from, DispatchTable::Entry entry);
3929
3930 static const int kInBase = 0;
3931 static const int kInOverlay = 1;
3932
3933 private:
3934 ZoneList<CharacterRange>** included_;
3935 ZoneList<CharacterRange>** excluded_;
3936};
3937
3938
3939void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3940 if (!entry.out_set()->Get(kInBase)) return;
3941 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3942 ? included_
3943 : excluded_;
3944 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3945 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3946}
3947
3948
3949void CharacterRange::Split(ZoneList<CharacterRange>* base,
3950 Vector<const uc16> overlay,
3951 ZoneList<CharacterRange>** included,
3952 ZoneList<CharacterRange>** excluded) {
3953 ASSERT_EQ(NULL, *included);
3954 ASSERT_EQ(NULL, *excluded);
3955 DispatchTable table;
3956 for (int i = 0; i < base->length(); i++)
3957 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3958 for (int i = 0; i < overlay.length(); i += 2) {
3959 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
3960 CharacterRangeSplitter::kInOverlay);
3961 }
3962 CharacterRangeSplitter callback(included, excluded);
3963 table.ForEach(&callback);
3964}
3965
3966
ager@chromium.org38e4c712009-11-11 09:11:58 +00003967static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
3968 int bottom,
3969 int top);
3970
3971
3972void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
3973 bool is_ascii) {
3974 uc16 bottom = from();
3975 uc16 top = to();
3976 if (is_ascii) {
3977 if (bottom > String::kMaxAsciiCharCode) return;
3978 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
3979 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003980 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00003981 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003982 // If this is a singleton we just expand the one character.
ager@chromium.org38e4c712009-11-11 09:11:58 +00003983 int length = uncanonicalize.get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003984 for (int i = 0; i < length; i++) {
3985 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00003986 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003987 ranges->Add(CharacterRange::Singleton(chars[i]));
3988 }
3989 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00003990 } else if (bottom <= kRangeCanonicalizeMax &&
3991 top <= kRangeCanonicalizeMax) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003992 // If this is a range we expand the characters block by block,
3993 // expanding contiguous subranges (blocks) one at a time.
3994 // The approach is as follows. For a given start character we
3995 // look up the block that contains it, for instance 'a' if the
3996 // start character is 'c'. A block is characterized by the property
3997 // that all characters uncanonicalize in the same way as the first
3998 // element, except that each entry in the result is incremented
3999 // by the distance from the first element. So a-z is a block
4000 // because 'a' uncanonicalizes to ['a', 'A'] and the k'th letter
4001 // uncanonicalizes to ['a' + k, 'A' + k].
4002 // Once we've found the start point we look up its uncanonicalization
4003 // and produce a range for each element. For instance for [c-f]
4004 // we look up ['a', 'A'] and produce [c-f] and [C-F]. We then only
4005 // add a range if it is not already contained in the input, so [c-f]
4006 // will be skipped but [C-F] will be added. If this range is not
4007 // completely contained in a block we do this for all the blocks
4008 // covered by the range.
4009 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004010 // First, look up the block that contains the 'bottom' character.
4011 int length = canonrange.get(bottom, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004012 if (length == 0) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004013 range[0] = bottom;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004014 } else {
4015 ASSERT_EQ(1, length);
4016 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004017 int pos = bottom;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004018 // The start of the current block. Note that except for the first
4019 // iteration 'start' is always equal to 'pos'.
4020 int start;
4021 // If it is not the start point of a block the entry contains the
4022 // offset of the character from the start point.
4023 if ((range[0] & kStartMarker) == 0) {
4024 start = pos - range[0];
4025 } else {
4026 start = pos;
4027 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004028 // Then we add the ranges one at a time, incrementing the current
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004029 // position to be after the last block each time. The position
4030 // always points to the start of a block.
ager@chromium.org38e4c712009-11-11 09:11:58 +00004031 while (pos < top) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004032 length = canonrange.get(start, '\0', range);
4033 if (length == 0) {
4034 range[0] = start;
4035 } else {
4036 ASSERT_EQ(1, length);
4037 }
4038 ASSERT((range[0] & kStartMarker) != 0);
4039 // The start point of a block contains the distance to the end
4040 // of the range.
4041 int block_end = start + (range[0] & kPayloadMask) - 1;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004042 int end = (block_end > top) ? top : block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004043 length = uncanonicalize.get(start, '\0', range);
4044 for (int i = 0; i < length; i++) {
4045 uc32 c = range[i];
4046 uc16 range_from = c + (pos - start);
4047 uc16 range_to = c + (end - start);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004048 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004049 ranges->Add(CharacterRange(range_from, range_to));
4050 }
4051 }
4052 start = pos = block_end + 1;
4053 }
4054 } else {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004055 // Unibrow ranges don't work for high characters due to the "2^11 bug".
4056 // Therefore we do something dumber for these ranges.
4057 AddUncanonicals(ranges, bottom, top);
4058 }
4059}
4060
4061
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004062bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4063 ASSERT_NOT_NULL(ranges);
4064 int n = ranges->length();
4065 if (n <= 1) return true;
4066 int max = ranges->at(0).to();
4067 for (int i = 1; i < n; i++) {
4068 CharacterRange next_range = ranges->at(i);
4069 if (next_range.from() <= max + 1) return false;
4070 max = next_range.to();
4071 }
4072 return true;
4073}
4074
4075SetRelation CharacterRange::WordCharacterRelation(
4076 ZoneList<CharacterRange>* range) {
4077 ASSERT(IsCanonical(range));
4078 int i = 0; // Word character range index.
4079 int j = 0; // Argument range index.
4080 ASSERT_NE(0, kWordRangeCount);
4081 SetRelation result;
4082 if (range->length() == 0) {
4083 result.SetElementsInSecondSet();
4084 return result;
4085 }
4086 CharacterRange argument_range = range->at(0);
4087 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4088 while (i < kWordRangeCount && j < range->length()) {
4089 // Check the two ranges for the five cases:
4090 // - no overlap.
4091 // - partial overlap (there are elements in both ranges that isn't
4092 // in the other, and there are also elements that are in both).
4093 // - argument range entirely inside word range.
4094 // - word range entirely inside argument range.
4095 // - ranges are completely equal.
4096
4097 // First check for no overlap. The earlier range is not in the other set.
4098 if (argument_range.from() > word_range.to()) {
4099 // Ranges are disjoint. The earlier word range contains elements that
4100 // cannot be in the argument set.
4101 result.SetElementsInSecondSet();
4102 } else if (word_range.from() > argument_range.to()) {
4103 // Ranges are disjoint. The earlier argument range contains elements that
4104 // cannot be in the word set.
4105 result.SetElementsInFirstSet();
4106 } else if (word_range.from() <= argument_range.from() &&
4107 word_range.to() >= argument_range.from()) {
4108 result.SetElementsInBothSets();
4109 // argument range completely inside word range.
4110 if (word_range.from() < argument_range.from() ||
4111 word_range.to() > argument_range.from()) {
4112 result.SetElementsInSecondSet();
4113 }
4114 } else if (word_range.from() >= argument_range.from() &&
4115 word_range.to() <= argument_range.from()) {
4116 result.SetElementsInBothSets();
4117 result.SetElementsInFirstSet();
4118 } else {
4119 // There is overlap, and neither is a subrange of the other
4120 result.SetElementsInFirstSet();
4121 result.SetElementsInSecondSet();
4122 result.SetElementsInBothSets();
4123 }
4124 if (result.NonTrivialIntersection()) {
4125 // The result is as (im)precise as we can possibly make it.
4126 return result;
4127 }
4128 // Progress the range(s) with minimal to-character.
4129 uc16 word_to = word_range.to();
4130 uc16 argument_to = argument_range.to();
4131 if (argument_to <= word_to) {
4132 j++;
4133 if (j < range->length()) {
4134 argument_range = range->at(j);
4135 }
4136 }
4137 if (word_to <= argument_to) {
4138 i += 2;
4139 if (i < kWordRangeCount) {
4140 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4141 }
4142 }
4143 }
4144 // Check if anything wasn't compared in the loop.
4145 if (i < kWordRangeCount) {
4146 // word range contains something not in argument range.
4147 result.SetElementsInSecondSet();
4148 } else if (j < range->length()) {
4149 // Argument range contains something not in word range.
4150 result.SetElementsInFirstSet();
4151 }
4152
4153 return result;
4154}
4155
4156
ager@chromium.org38e4c712009-11-11 09:11:58 +00004157static void AddUncanonicals(ZoneList<CharacterRange>* ranges,
4158 int bottom,
4159 int top) {
4160 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4161 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4162 // this table is correct.
4163 // 0x0600 - 0x0fff
4164 // 0x1100 - 0x1cff
4165 // 0x2000 - 0x20ff
4166 // 0x2200 - 0x23ff
4167 // 0x2500 - 0x2bff
4168 // 0x2e00 - 0xa5ff
4169 // 0xa800 - 0xfaff
4170 // 0xfc00 - 0xfeff
4171 const int boundary_count = 18;
4172 // The ASCII boundary and the kRangeCanonicalizeMax boundary are also in this
4173 // array. This is to split up big ranges and not because they actually denote
4174 // a case-mapping-free-zone.
4175 ASSERT(CharacterRange::kRangeCanonicalizeMax < 0x600);
4176 const int kFirstRealCaselessZoneIndex = 2;
4177 int boundaries[] = {0x80, CharacterRange::kRangeCanonicalizeMax,
4178 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4179 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4180
4181 // Special ASCII rule from spec can save us some work here.
4182 if (bottom == 0x80 && top == 0xffff) return;
4183
4184 // We have optimized support for this range.
4185 if (top <= CharacterRange::kRangeCanonicalizeMax) {
4186 CharacterRange range(bottom, top);
4187 range.AddCaseEquivalents(ranges, false);
4188 return;
4189 }
4190
4191 // Split up very large ranges. This helps remove ranges where there are no
4192 // case mappings.
4193 for (int i = 0; i < boundary_count; i++) {
4194 if (bottom < boundaries[i] && top >= boundaries[i]) {
4195 AddUncanonicals(ranges, bottom, boundaries[i] - 1);
4196 AddUncanonicals(ranges, boundaries[i], top);
4197 return;
4198 }
4199 }
4200
4201 // If we are completely in a zone with no case mappings then we are done.
4202 // We start at 2 so as not to except the ASCII range from mappings.
4203 for (int i = kFirstRealCaselessZoneIndex; i < boundary_count; i += 2) {
4204 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4205#ifdef DEBUG
4206 for (int j = bottom; j <= top; j++) {
4207 unsigned current_char = j;
4208 int length = uncanonicalize.get(current_char, '\0', chars);
4209 for (int k = 0; k < length; k++) {
4210 ASSERT(chars[k] == current_char);
4211 }
4212 }
4213#endif
4214 return;
4215 }
4216 }
4217
4218 // Step through the range finding equivalent characters.
4219 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4220 for (int i = bottom; i <= top; i++) {
4221 int length = uncanonicalize.get(i, '\0', chars);
4222 for (int j = 0; j < length; j++) {
4223 uc32 chr = chars[j];
4224 if (chr != i && (chr < bottom || chr > top)) {
4225 characters->Add(chr);
4226 }
4227 }
4228 }
4229
4230 // Step through the equivalent characters finding simple ranges and
4231 // adding ranges to the character class.
4232 if (characters->length() > 0) {
4233 int new_from = characters->at(0);
4234 int new_to = new_from;
4235 for (int i = 1; i < characters->length(); i++) {
4236 int chr = characters->at(i);
4237 if (chr == new_to + 1) {
4238 new_to++;
4239 } else {
4240 if (new_to == new_from) {
4241 ranges->Add(CharacterRange::Singleton(new_from));
4242 } else {
4243 ranges->Add(CharacterRange(new_from, new_to));
4244 }
4245 new_from = new_to = chr;
4246 }
4247 }
4248 if (new_to == new_from) {
4249 ranges->Add(CharacterRange::Singleton(new_from));
4250 } else {
4251 ranges->Add(CharacterRange(new_from, new_to));
4252 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004253 }
4254}
4255
4256
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004257ZoneList<CharacterRange>* CharacterSet::ranges() {
4258 if (ranges_ == NULL) {
4259 ranges_ = new ZoneList<CharacterRange>(2);
4260 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4261 }
4262 return ranges_;
4263}
4264
4265
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004266// Move a number of elements in a zonelist to another position
4267// in the same list. Handles overlapping source and target areas.
4268static void MoveRanges(ZoneList<CharacterRange>* list,
4269 int from,
4270 int to,
4271 int count) {
4272 // Ranges are potentially overlapping.
4273 if (from < to) {
4274 for (int i = count - 1; i >= 0; i--) {
4275 list->at(to + i) = list->at(from + i);
4276 }
4277 } else {
4278 for (int i = 0; i < count; i++) {
4279 list->at(to + i) = list->at(from + i);
4280 }
4281 }
4282}
4283
4284
4285static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4286 int count,
4287 CharacterRange insert) {
4288 // Inserts a range into list[0..count[, which must be sorted
4289 // by from value and non-overlapping and non-adjacent, using at most
4290 // list[0..count] for the result. Returns the number of resulting
4291 // canonicalized ranges. Inserting a range may collapse existing ranges into
4292 // fewer ranges, so the return value can be anything in the range 1..count+1.
4293 uc16 from = insert.from();
4294 uc16 to = insert.to();
4295 int start_pos = 0;
4296 int end_pos = count;
4297 for (int i = count - 1; i >= 0; i--) {
4298 CharacterRange current = list->at(i);
4299 if (current.from() > to + 1) {
4300 end_pos = i;
4301 } else if (current.to() + 1 < from) {
4302 start_pos = i + 1;
4303 break;
4304 }
4305 }
4306
4307 // Inserted range overlaps, or is adjacent to, ranges at positions
4308 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4309 // not affected by the insertion.
4310 // If start_pos == end_pos, the range must be inserted before start_pos.
4311 // if start_pos < end_pos, the entire range from start_pos to end_pos
4312 // must be merged with the insert range.
4313
4314 if (start_pos == end_pos) {
4315 // Insert between existing ranges at position start_pos.
4316 if (start_pos < count) {
4317 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4318 }
4319 list->at(start_pos) = insert;
4320 return count + 1;
4321 }
4322 if (start_pos + 1 == end_pos) {
4323 // Replace single existing range at position start_pos.
4324 CharacterRange to_replace = list->at(start_pos);
4325 int new_from = Min(to_replace.from(), from);
4326 int new_to = Max(to_replace.to(), to);
4327 list->at(start_pos) = CharacterRange(new_from, new_to);
4328 return count;
4329 }
4330 // Replace a number of existing ranges from start_pos to end_pos - 1.
4331 // Move the remaining ranges down.
4332
4333 int new_from = Min(list->at(start_pos).from(), from);
4334 int new_to = Max(list->at(end_pos - 1).to(), to);
4335 if (end_pos < count) {
4336 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4337 }
4338 list->at(start_pos) = CharacterRange(new_from, new_to);
4339 return count - (end_pos - start_pos) + 1;
4340}
4341
4342
4343void CharacterSet::Canonicalize() {
4344 // Special/default classes are always considered canonical. The result
4345 // of calling ranges() will be sorted.
4346 if (ranges_ == NULL) return;
4347 CharacterRange::Canonicalize(ranges_);
4348}
4349
4350
4351void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4352 if (character_ranges->length() <= 1) return;
4353 // Check whether ranges are already canonical (increasing, non-overlapping,
4354 // non-adjacent).
4355 int n = character_ranges->length();
4356 int max = character_ranges->at(0).to();
4357 int i = 1;
4358 while (i < n) {
4359 CharacterRange current = character_ranges->at(i);
4360 if (current.from() <= max + 1) {
4361 break;
4362 }
4363 max = current.to();
4364 i++;
4365 }
4366 // Canonical until the i'th range. If that's all of them, we are done.
4367 if (i == n) return;
4368
4369 // The ranges at index i and forward are not canonicalized. Make them so by
4370 // doing the equivalent of insertion sort (inserting each into the previous
4371 // list, in order).
4372 // Notice that inserting a range can reduce the number of ranges in the
4373 // result due to combining of adjacent and overlapping ranges.
4374 int read = i; // Range to insert.
4375 int num_canonical = i; // Length of canonicalized part of list.
4376 do {
4377 num_canonical = InsertRangeInCanonicalList(character_ranges,
4378 num_canonical,
4379 character_ranges->at(read));
4380 read++;
4381 } while (read < n);
4382 character_ranges->Rewind(num_canonical);
4383
4384 ASSERT(CharacterRange::IsCanonical(character_ranges));
4385}
4386
4387
4388// Utility function for CharacterRange::Merge. Adds a range at the end of
4389// a canonicalized range list, if necessary merging the range with the last
4390// range of the list.
4391static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4392 if (set == NULL) return;
4393 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4394 int n = set->length();
4395 if (n > 0) {
4396 CharacterRange lastRange = set->at(n - 1);
4397 if (lastRange.to() == range.from() - 1) {
4398 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4399 return;
4400 }
4401 }
4402 set->Add(range);
4403}
4404
4405
4406static void AddRangeToSelectedSet(int selector,
4407 ZoneList<CharacterRange>* first_set,
4408 ZoneList<CharacterRange>* second_set,
4409 ZoneList<CharacterRange>* intersection_set,
4410 CharacterRange range) {
4411 switch (selector) {
4412 case kInsideFirst:
4413 AddRangeToSet(first_set, range);
4414 break;
4415 case kInsideSecond:
4416 AddRangeToSet(second_set, range);
4417 break;
4418 case kInsideBoth:
4419 AddRangeToSet(intersection_set, range);
4420 break;
4421 }
4422}
4423
4424
4425
4426void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4427 ZoneList<CharacterRange>* second_set,
4428 ZoneList<CharacterRange>* first_set_only_out,
4429 ZoneList<CharacterRange>* second_set_only_out,
4430 ZoneList<CharacterRange>* both_sets_out) {
4431 // Inputs are canonicalized.
4432 ASSERT(CharacterRange::IsCanonical(first_set));
4433 ASSERT(CharacterRange::IsCanonical(second_set));
4434 // Outputs are empty, if applicable.
4435 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4436 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4437 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4438
4439 // Merge sets by iterating through the lists in order of lowest "from" value,
4440 // and putting intervals into one of three sets.
4441
4442 if (first_set->length() == 0) {
4443 second_set_only_out->AddAll(*second_set);
4444 return;
4445 }
4446 if (second_set->length() == 0) {
4447 first_set_only_out->AddAll(*first_set);
4448 return;
4449 }
4450 // Indices into input lists.
4451 int i1 = 0;
4452 int i2 = 0;
4453 // Cache length of input lists.
4454 int n1 = first_set->length();
4455 int n2 = second_set->length();
4456 // Current range. May be invalid if state is kInsideNone.
4457 int from = 0;
4458 int to = -1;
4459 // Where current range comes from.
4460 int state = kInsideNone;
4461
4462 while (i1 < n1 || i2 < n2) {
4463 CharacterRange next_range;
4464 int range_source;
4465 if (i2 == n2 || first_set->at(i1).from() < second_set->at(i2).from()) {
4466 next_range = first_set->at(i1++);
4467 range_source = kInsideFirst;
4468 } else {
4469 next_range = second_set->at(i2++);
4470 range_source = kInsideSecond;
4471 }
4472 if (to < next_range.from()) {
4473 // Ranges disjoint: |current| |next|
4474 AddRangeToSelectedSet(state,
4475 first_set_only_out,
4476 second_set_only_out,
4477 both_sets_out,
4478 CharacterRange(from, to));
4479 from = next_range.from();
4480 to = next_range.to();
4481 state = range_source;
4482 } else {
4483 if (from < next_range.from()) {
4484 AddRangeToSelectedSet(state,
4485 first_set_only_out,
4486 second_set_only_out,
4487 both_sets_out,
4488 CharacterRange(from, next_range.from()-1));
4489 }
4490 if (to < next_range.to()) {
4491 // Ranges overlap: |current|
4492 // |next|
4493 AddRangeToSelectedSet(state | range_source,
4494 first_set_only_out,
4495 second_set_only_out,
4496 both_sets_out,
4497 CharacterRange(next_range.from(), to));
4498 from = to + 1;
4499 to = next_range.to();
4500 state = range_source;
4501 } else {
4502 // Range included: |current| , possibly ending at same character.
4503 // |next|
4504 AddRangeToSelectedSet(
4505 state | range_source,
4506 first_set_only_out,
4507 second_set_only_out,
4508 both_sets_out,
4509 CharacterRange(next_range.from(), next_range.to()));
4510 from = next_range.to() + 1;
4511 // If ranges end at same character, both ranges are consumed completely.
4512 if (next_range.to() == to) state = kInsideNone;
4513 }
4514 }
4515 }
4516 AddRangeToSelectedSet(state,
4517 first_set_only_out,
4518 second_set_only_out,
4519 both_sets_out,
4520 CharacterRange(from, to));
4521}
4522
4523
4524void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4525 ZoneList<CharacterRange>* negated_ranges) {
4526 ASSERT(CharacterRange::IsCanonical(ranges));
4527 ASSERT_EQ(0, negated_ranges->length());
4528 int range_count = ranges->length();
4529 uc16 from = 0;
4530 int i = 0;
4531 if (range_count > 0 && ranges->at(0).from() == 0) {
4532 from = ranges->at(0).to();
4533 i = 1;
4534 }
4535 while (i < range_count) {
4536 CharacterRange range = ranges->at(i);
4537 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4538 from = range.to();
4539 i++;
4540 }
4541 if (from < String::kMaxUC16CharCode) {
4542 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4543 }
4544}
4545
4546
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004547
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004548// -------------------------------------------------------------------
4549// Interest propagation
4550
4551
4552RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4553 for (int i = 0; i < siblings_.length(); i++) {
4554 RegExpNode* sibling = siblings_.Get(i);
4555 if (sibling->info()->Matches(info))
4556 return sibling;
4557 }
4558 return NULL;
4559}
4560
4561
4562RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4563 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004564 siblings_.Ensure(this);
4565 RegExpNode* result = TryGetSibling(info);
4566 if (result != NULL) return result;
4567 result = this->Clone();
4568 NodeInfo* new_info = result->info();
4569 new_info->ResetCompilationState();
4570 new_info->AddFromPreceding(info);
4571 AddSibling(result);
4572 *cloned = true;
4573 return result;
4574}
4575
4576
4577template <class C>
4578static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4579 NodeInfo full_info(*node->info());
4580 full_info.AddFromPreceding(info);
4581 bool cloned = false;
4582 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4583}
4584
4585
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004586// -------------------------------------------------------------------
4587// Splay tree
4588
4589
4590OutSet* OutSet::Extend(unsigned value) {
4591 if (Get(value))
4592 return this;
4593 if (successors() != NULL) {
4594 for (int i = 0; i < successors()->length(); i++) {
4595 OutSet* successor = successors()->at(i);
4596 if (successor->Get(value))
4597 return successor;
4598 }
4599 } else {
4600 successors_ = new ZoneList<OutSet*>(2);
4601 }
4602 OutSet* result = new OutSet(first_, remaining_);
4603 result->Set(value);
4604 successors()->Add(result);
4605 return result;
4606}
4607
4608
4609void OutSet::Set(unsigned value) {
4610 if (value < kFirstLimit) {
4611 first_ |= (1 << value);
4612 } else {
4613 if (remaining_ == NULL)
4614 remaining_ = new ZoneList<unsigned>(1);
4615 if (remaining_->is_empty() || !remaining_->Contains(value))
4616 remaining_->Add(value);
4617 }
4618}
4619
4620
4621bool OutSet::Get(unsigned value) {
4622 if (value < kFirstLimit) {
4623 return (first_ & (1 << value)) != 0;
4624 } else if (remaining_ == NULL) {
4625 return false;
4626 } else {
4627 return remaining_->Contains(value);
4628 }
4629}
4630
4631
4632const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4633const DispatchTable::Entry DispatchTable::Config::kNoValue;
4634
4635
4636void DispatchTable::AddRange(CharacterRange full_range, int value) {
4637 CharacterRange current = full_range;
4638 if (tree()->is_empty()) {
4639 // If this is the first range we just insert into the table.
4640 ZoneSplayTree<Config>::Locator loc;
4641 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4642 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4643 return;
4644 }
4645 // First see if there is a range to the left of this one that
4646 // overlaps.
4647 ZoneSplayTree<Config>::Locator loc;
4648 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4649 Entry* entry = &loc.value();
4650 // If we've found a range that overlaps with this one, and it
4651 // starts strictly to the left of this one, we have to fix it
4652 // because the following code only handles ranges that start on
4653 // or after the start point of the range we're adding.
4654 if (entry->from() < current.from() && entry->to() >= current.from()) {
4655 // Snap the overlapping range in half around the start point of
4656 // the range we're adding.
4657 CharacterRange left(entry->from(), current.from() - 1);
4658 CharacterRange right(current.from(), entry->to());
4659 // The left part of the overlapping range doesn't overlap.
4660 // Truncate the whole entry to be just the left part.
4661 entry->set_to(left.to());
4662 // The right part is the one that overlaps. We add this part
4663 // to the map and let the next step deal with merging it with
4664 // the range we're adding.
4665 ZoneSplayTree<Config>::Locator loc;
4666 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4667 loc.set_value(Entry(right.from(),
4668 right.to(),
4669 entry->out_set()));
4670 }
4671 }
4672 while (current.is_valid()) {
4673 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4674 (loc.value().from() <= current.to()) &&
4675 (loc.value().to() >= current.from())) {
4676 Entry* entry = &loc.value();
4677 // We have overlap. If there is space between the start point of
4678 // the range we're adding and where the overlapping range starts
4679 // then we have to add a range covering just that space.
4680 if (current.from() < entry->from()) {
4681 ZoneSplayTree<Config>::Locator ins;
4682 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4683 ins.set_value(Entry(current.from(),
4684 entry->from() - 1,
4685 empty()->Extend(value)));
4686 current.set_from(entry->from());
4687 }
4688 ASSERT_EQ(current.from(), entry->from());
4689 // If the overlapping range extends beyond the one we want to add
4690 // we have to snap the right part off and add it separately.
4691 if (entry->to() > current.to()) {
4692 ZoneSplayTree<Config>::Locator ins;
4693 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4694 ins.set_value(Entry(current.to() + 1,
4695 entry->to(),
4696 entry->out_set()));
4697 entry->set_to(current.to());
4698 }
4699 ASSERT(entry->to() <= current.to());
4700 // The overlapping range is now completely contained by the range
4701 // we're adding so we can just update it and move the start point
4702 // of the range we're adding just past it.
4703 entry->AddValue(value);
4704 // Bail out if the last interval ended at 0xFFFF since otherwise
4705 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004706 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004707 break;
4708 ASSERT(entry->to() + 1 > current.from());
4709 current.set_from(entry->to() + 1);
4710 } else {
4711 // There is no overlap so we can just add the range
4712 ZoneSplayTree<Config>::Locator ins;
4713 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4714 ins.set_value(Entry(current.from(),
4715 current.to(),
4716 empty()->Extend(value)));
4717 break;
4718 }
4719 }
4720}
4721
4722
4723OutSet* DispatchTable::Get(uc16 value) {
4724 ZoneSplayTree<Config>::Locator loc;
4725 if (!tree()->FindGreatestLessThan(value, &loc))
4726 return empty();
4727 Entry* entry = &loc.value();
4728 if (value <= entry->to())
4729 return entry->out_set();
4730 else
4731 return empty();
4732}
4733
4734
4735// -------------------------------------------------------------------
4736// Analysis
4737
4738
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004739void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004740 StackLimitCheck check;
4741 if (check.HasOverflowed()) {
4742 fail("Stack overflow");
4743 return;
4744 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004745 if (that->info()->been_analyzed || that->info()->being_analyzed)
4746 return;
4747 that->info()->being_analyzed = true;
4748 that->Accept(this);
4749 that->info()->being_analyzed = false;
4750 that->info()->been_analyzed = true;
4751}
4752
4753
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004754void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004755 // nothing to do
4756}
4757
4758
ager@chromium.org8bb60582008-12-11 12:02:20 +00004759void TextNode::CalculateOffsets() {
4760 int element_count = elements()->length();
4761 // Set up the offsets of the elements relative to the start. This is a fixed
4762 // quantity since a TextNode can only contain fixed-width things.
4763 int cp_offset = 0;
4764 for (int i = 0; i < element_count; i++) {
4765 TextElement& elm = elements()->at(i);
4766 elm.cp_offset = cp_offset;
4767 if (elm.type == TextElement::ATOM) {
4768 cp_offset += elm.data.u_atom->data().length();
4769 } else {
4770 cp_offset++;
4771 Vector<const uc16> quarks = elm.data.u_atom->data();
4772 }
4773 }
4774}
4775
4776
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004777void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004778 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004779 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004780 }
4781 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004782 if (!has_failed()) {
4783 that->CalculateOffsets();
4784 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004785}
4786
4787
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004788void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004789 RegExpNode* target = that->on_success();
4790 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004791 if (!has_failed()) {
4792 // If the next node is interested in what it follows then this node
4793 // has to be interested too so it can pass the information on.
4794 that->info()->AddFromFollowing(target->info());
4795 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004796}
4797
4798
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004799void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004800 NodeInfo* info = that->info();
4801 for (int i = 0; i < that->alternatives()->length(); i++) {
4802 RegExpNode* node = that->alternatives()->at(i).node();
4803 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004804 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004805 // Anything the following nodes need to know has to be known by
4806 // this node also, so it can pass it on.
4807 info->AddFromFollowing(node->info());
4808 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004809}
4810
4811
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004812void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4813 NodeInfo* info = that->info();
4814 for (int i = 0; i < that->alternatives()->length(); i++) {
4815 RegExpNode* node = that->alternatives()->at(i).node();
4816 if (node != that->loop_node()) {
4817 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004818 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004819 info->AddFromFollowing(node->info());
4820 }
4821 }
4822 // Check the loop last since it may need the value of this node
4823 // to get a correct result.
4824 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004825 if (!has_failed()) {
4826 info->AddFromFollowing(that->loop_node()->info());
4827 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004828}
4829
4830
4831void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004832 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004833}
4834
4835
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004836void Analysis::VisitAssertion(AssertionNode* that) {
4837 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004838 AssertionNode::AssertionNodeType type = that->type();
4839 if (type == AssertionNode::AT_BOUNDARY ||
4840 type == AssertionNode::AT_NON_BOUNDARY) {
4841 // Check if the following character is known to be a word character
4842 // or known to not be a word character.
4843 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4844
4845 CharacterRange::Canonicalize(following_chars);
4846
4847 SetRelation word_relation =
4848 CharacterRange::WordCharacterRelation(following_chars);
4849 if (word_relation.ContainedIn()) {
4850 // Following character is definitely a word character.
4851 type = (type == AssertionNode::AT_BOUNDARY) ?
4852 AssertionNode::AFTER_NONWORD_CHARACTER :
4853 AssertionNode::AFTER_WORD_CHARACTER;
4854 that->set_type(type);
4855 } else if (word_relation.Disjoint()) {
4856 // Following character is definitely *not* a word character.
4857 type = (type == AssertionNode::AT_BOUNDARY) ?
4858 AssertionNode::AFTER_WORD_CHARACTER :
4859 AssertionNode::AFTER_NONWORD_CHARACTER;
4860 that->set_type(type);
4861 }
4862 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004863}
4864
4865
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004866ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4867 if (first_character_set_ == NULL) {
4868 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4869 // If we can't find an exact solution within the budget, we
4870 // set the value to the set of every character, i.e., all characters
4871 // are possible.
4872 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4873 all_set->Add(CharacterRange::Everything());
4874 first_character_set_ = all_set;
4875 }
4876 }
4877 return first_character_set_;
4878}
4879
4880
4881int RegExpNode::ComputeFirstCharacterSet(int budget) {
4882 // Default behavior is to not be able to determine the first character.
4883 return kComputeFirstCharacterSetFail;
4884}
4885
4886
4887int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
4888 budget--;
4889 if (budget >= 0) {
4890 // Find loop min-iteration. It's the value of the guarded choice node
4891 // with a GEQ guard, if any.
4892 int min_repetition = 0;
4893
4894 for (int i = 0; i <= 1; i++) {
4895 GuardedAlternative alternative = alternatives()->at(i);
4896 ZoneList<Guard*>* guards = alternative.guards();
4897 if (guards != NULL && guards->length() > 0) {
4898 Guard* guard = guards->at(0);
4899 if (guard->op() == Guard::GEQ) {
4900 min_repetition = guard->value();
4901 break;
4902 }
4903 }
4904 }
4905
4906 budget = loop_node()->ComputeFirstCharacterSet(budget);
4907 if (budget >= 0) {
4908 ZoneList<CharacterRange>* character_set =
4909 loop_node()->first_character_set();
4910 if (body_can_be_zero_length() || min_repetition == 0) {
4911 budget = continue_node()->ComputeFirstCharacterSet(budget);
4912 if (budget < 0) return budget;
4913 ZoneList<CharacterRange>* body_set =
4914 continue_node()->first_character_set();
4915 ZoneList<CharacterRange>* union_set =
4916 new ZoneList<CharacterRange>(Max(character_set->length(),
4917 body_set->length()));
4918 CharacterRange::Merge(character_set,
4919 body_set,
4920 union_set,
4921 union_set,
4922 union_set);
4923 character_set = union_set;
4924 }
4925 set_first_character_set(character_set);
4926 }
4927 }
4928 return budget;
4929}
4930
4931
4932int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
4933 budget--;
4934 if (budget >= 0) {
4935 GuardedAlternative successor = this->alternatives()->at(1);
4936 RegExpNode* successor_node = successor.node();
4937 budget = successor_node->ComputeFirstCharacterSet(budget);
4938 if (budget >= 0) {
4939 set_first_character_set(successor_node->first_character_set());
4940 }
4941 }
4942 return budget;
4943}
4944
4945
4946// The first character set of an EndNode is unknowable. Just use the
4947// default implementation that fails and returns all characters as possible.
4948
4949
4950int AssertionNode::ComputeFirstCharacterSet(int budget) {
4951 budget -= 1;
4952 if (budget >= 0) {
4953 switch (type_) {
4954 case AT_END: {
4955 set_first_character_set(new ZoneList<CharacterRange>(0));
4956 break;
4957 }
4958 case AT_START:
4959 case AT_BOUNDARY:
4960 case AT_NON_BOUNDARY:
4961 case AFTER_NEWLINE:
4962 case AFTER_NONWORD_CHARACTER:
4963 case AFTER_WORD_CHARACTER: {
4964 ASSERT_NOT_NULL(on_success());
4965 budget = on_success()->ComputeFirstCharacterSet(budget);
4966 set_first_character_set(on_success()->first_character_set());
4967 break;
4968 }
4969 }
4970 }
4971 return budget;
4972}
4973
4974
4975int ActionNode::ComputeFirstCharacterSet(int budget) {
4976 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
4977 budget--;
4978 if (budget >= 0) {
4979 ASSERT_NOT_NULL(on_success());
4980 budget = on_success()->ComputeFirstCharacterSet(budget);
4981 if (budget >= 0) {
4982 set_first_character_set(on_success()->first_character_set());
4983 }
4984 }
4985 return budget;
4986}
4987
4988
4989int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
4990 // We don't know anything about the first character of a backreference
4991 // at this point.
4992 return kComputeFirstCharacterSetFail;
4993}
4994
4995
4996int TextNode::ComputeFirstCharacterSet(int budget) {
4997 budget--;
4998 if (budget >= 0) {
4999 ASSERT_NE(0, elements()->length());
5000 TextElement text = elements()->at(0);
5001 if (text.type == TextElement::ATOM) {
5002 RegExpAtom* atom = text.data.u_atom;
5003 ASSERT_NE(0, atom->length());
5004 uc16 first_char = atom->data()[0];
5005 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5006 range->Add(CharacterRange(first_char, first_char));
5007 set_first_character_set(range);
5008 } else {
5009 ASSERT(text.type == TextElement::CHAR_CLASS);
5010 RegExpCharacterClass* char_class = text.data.u_char_class;
5011 if (char_class->is_negated()) {
5012 ZoneList<CharacterRange>* ranges = char_class->ranges();
5013 int length = ranges->length();
5014 int new_length = length + 1;
5015 if (length > 0) {
5016 if (ranges->at(0).from() == 0) new_length--;
5017 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5018 new_length--;
5019 }
5020 }
5021 ZoneList<CharacterRange>* negated_ranges =
5022 new ZoneList<CharacterRange>(new_length);
5023 CharacterRange::Negate(ranges, negated_ranges);
5024 set_first_character_set(negated_ranges);
5025 } else {
5026 set_first_character_set(char_class->ranges());
5027 }
5028 }
5029 }
5030 return budget;
5031}
5032
5033
5034
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005035// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005036// Dispatch table construction
5037
5038
5039void DispatchTableConstructor::VisitEnd(EndNode* that) {
5040 AddRange(CharacterRange::Everything());
5041}
5042
5043
5044void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5045 node->set_being_calculated(true);
5046 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5047 for (int i = 0; i < alternatives->length(); i++) {
5048 set_choice_index(i);
5049 alternatives->at(i).node()->Accept(this);
5050 }
5051 node->set_being_calculated(false);
5052}
5053
5054
5055class AddDispatchRange {
5056 public:
5057 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5058 : constructor_(constructor) { }
5059 void Call(uc32 from, DispatchTable::Entry entry);
5060 private:
5061 DispatchTableConstructor* constructor_;
5062};
5063
5064
5065void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5066 CharacterRange range(from, entry.to());
5067 constructor_->AddRange(range);
5068}
5069
5070
5071void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5072 if (node->being_calculated())
5073 return;
5074 DispatchTable* table = node->GetTable(ignore_case_);
5075 AddDispatchRange adder(this);
5076 table->ForEach(&adder);
5077}
5078
5079
5080void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5081 // TODO(160): Find the node that we refer back to and propagate its start
5082 // set back to here. For now we just accept anything.
5083 AddRange(CharacterRange::Everything());
5084}
5085
5086
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005087void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5088 RegExpNode* target = that->on_success();
5089 target->Accept(this);
5090}
5091
5092
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005093static int CompareRangeByFrom(const CharacterRange* a,
5094 const CharacterRange* b) {
5095 return Compare<uc16>(a->from(), b->from());
5096}
5097
5098
5099void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5100 ranges->Sort(CompareRangeByFrom);
5101 uc16 last = 0;
5102 for (int i = 0; i < ranges->length(); i++) {
5103 CharacterRange range = ranges->at(i);
5104 if (last < range.from())
5105 AddRange(CharacterRange(last, range.from() - 1));
5106 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005107 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005108 return;
5109 } else {
5110 last = range.to() + 1;
5111 }
5112 }
5113 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005114 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005115}
5116
5117
5118void DispatchTableConstructor::VisitText(TextNode* that) {
5119 TextElement elm = that->elements()->at(0);
5120 switch (elm.type) {
5121 case TextElement::ATOM: {
5122 uc16 c = elm.data.u_atom->data()[0];
5123 AddRange(CharacterRange(c, c));
5124 break;
5125 }
5126 case TextElement::CHAR_CLASS: {
5127 RegExpCharacterClass* tree = elm.data.u_char_class;
5128 ZoneList<CharacterRange>* ranges = tree->ranges();
5129 if (tree->is_negated()) {
5130 AddInverse(ranges);
5131 } else {
5132 for (int i = 0; i < ranges->length(); i++)
5133 AddRange(ranges->at(i));
5134 }
5135 break;
5136 }
5137 default: {
5138 UNIMPLEMENTED();
5139 }
5140 }
5141}
5142
5143
5144void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005145 RegExpNode* target = that->on_success();
5146 target->Accept(this);
5147}
5148
5149
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005150RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5151 bool ignore_case,
5152 bool is_multiline,
5153 Handle<String> pattern,
5154 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005155 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005156 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005157 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005158 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005159 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005160 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005161 0,
5162 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005163 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005164 RegExpNode* node = captured_body;
5165 if (!data->tree->IsAnchored()) {
5166 // Add a .*? at the beginning, outside the body capture, unless
5167 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005168 RegExpNode* loop_node =
5169 RegExpQuantifier::ToNode(0,
5170 RegExpTree::kInfinity,
5171 false,
5172 new RegExpCharacterClass('*'),
5173 &compiler,
5174 captured_body,
5175 data->contains_anchor);
5176
5177 if (data->contains_anchor) {
5178 // Unroll loop once, to take care of the case that might start
5179 // at the start of input.
5180 ChoiceNode* first_step_node = new ChoiceNode(2);
5181 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5182 first_step_node->AddAlternative(GuardedAlternative(
5183 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5184 node = first_step_node;
5185 } else {
5186 node = loop_node;
5187 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005188 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005189 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005190 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005191 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005192 if (analysis.has_failed()) {
5193 const char* error_message = analysis.error_message();
5194 return CompilationResult(error_message);
5195 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005196
5197 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005198
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005199 // Create the correct assembler for the architecture.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00005200#ifdef V8_NATIVE_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005201 // Native regexp implementation.
5202
5203 NativeRegExpMacroAssembler::Mode mode =
5204 is_ascii ? NativeRegExpMacroAssembler::ASCII
5205 : NativeRegExpMacroAssembler::UC16;
5206
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005207#if V8_TARGET_ARCH_IA32
5208 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5209#elif V8_TARGET_ARCH_X64
5210 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5211#elif V8_TARGET_ARCH_ARM
5212 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005213#endif
5214
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00005215#else // ! V8_NATIVE_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005216 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005217 EmbeddedVector<byte, 1024> codes;
5218 RegExpMacroAssemblerIrregexp macro_assembler(codes);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005219#endif
5220
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005221 return compiler.Assemble(&macro_assembler,
5222 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005223 data->capture_count,
5224 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005225}
5226
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005227
5228int OffsetsVector::static_offsets_vector_[
5229 OffsetsVector::kStaticOffsetsVectorSize];
5230
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005231}} // namespace v8::internal