blob: 3ebfbdfc986cb823291fb08dd94f4372bdc92922 [file] [log] [blame]
rossberg@chromium.org717967f2011-07-20 13:44:42 +00001// Copyright 2011 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.orga5551262010-12-07 12:49:48 +000036#include "string-search.h"
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000037#include "runtime.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000038#include "compilation-cache.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000039#include "string-stream.h"
40#include "parser.h"
41#include "regexp-macro-assembler.h"
42#include "regexp-macro-assembler-tracer.h"
43#include "regexp-macro-assembler-irregexp.h"
ager@chromium.org32912102009-01-16 10:38:43 +000044#include "regexp-stack.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000045
ricow@chromium.orgc9c80822010-04-21 08:22:37 +000046#ifndef V8_INTERPRETED_REGEXP
kasperl@chromium.org71affb52009-05-26 05:44:31 +000047#if V8_TARGET_ARCH_IA32
ager@chromium.org3a37e9b2009-04-27 09:26:21 +000048#include "ia32/regexp-macro-assembler-ia32.h"
ager@chromium.org9085a012009-05-11 19:22:57 +000049#elif V8_TARGET_ARCH_X64
ager@chromium.org9085a012009-05-11 19:22:57 +000050#include "x64/regexp-macro-assembler-x64.h"
51#elif V8_TARGET_ARCH_ARM
52#include "arm/regexp-macro-assembler-arm.h"
lrn@chromium.org7516f052011-03-30 08:52:27 +000053#elif V8_TARGET_ARCH_MIPS
54#include "mips/regexp-macro-assembler-mips.h"
kasperl@chromium.org2abc4502009-07-02 07:00:29 +000055#else
56#error Unsupported target architecture.
ager@chromium.orga74f0da2008-12-03 16:05:52 +000057#endif
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000058#endif
ager@chromium.orga74f0da2008-12-03 16:05:52 +000059
60#include "interpreter-irregexp.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000061
ager@chromium.orga74f0da2008-12-03 16:05:52 +000062
kasperl@chromium.org71affb52009-05-26 05:44:31 +000063namespace v8 {
64namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000065
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000066Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
67 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000068 Handle<String> flags,
69 bool* has_pending_exception) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000070 // Call the construct code with 2 arguments.
71 Object** argv[2] = { Handle<Object>::cast(pattern).location(),
72 Handle<Object>::cast(flags).location() };
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000073 return Execution::New(constructor, 2, argv, has_pending_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000074}
75
76
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000077static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
78 int flags = JSRegExp::NONE;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000079 for (int i = 0; i < str->length(); i++) {
80 switch (str->Get(i)) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000081 case 'i':
82 flags |= JSRegExp::IGNORE_CASE;
83 break;
84 case 'g':
85 flags |= JSRegExp::GLOBAL;
86 break;
87 case 'm':
88 flags |= JSRegExp::MULTILINE;
89 break;
90 }
91 }
92 return JSRegExp::Flags(flags);
93}
94
95
ager@chromium.orga74f0da2008-12-03 16:05:52 +000096static inline void ThrowRegExpException(Handle<JSRegExp> re,
97 Handle<String> pattern,
98 Handle<String> error_text,
99 const char* message) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000100 Isolate* isolate = re->GetIsolate();
101 Factory* factory = isolate->factory();
102 Handle<FixedArray> elements = factory->NewFixedArray(2);
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000103 elements->set(0, *pattern);
104 elements->set(1, *error_text);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000105 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
106 Handle<Object> regexp_err = factory->NewSyntaxError(message, array);
107 isolate->Throw(*regexp_err);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000108}
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000109
110
ager@chromium.org8bb60582008-12-11 12:02:20 +0000111// Generic RegExp methods. Dispatches to implementation specific methods.
112
113
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000114Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
115 Handle<String> pattern,
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000116 Handle<String> flag_str) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000117 Isolate* isolate = re->GetIsolate();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000118 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000119 CompilationCache* compilation_cache = isolate->compilation_cache();
120 Handle<FixedArray> cached = compilation_cache->LookupRegExp(pattern, flags);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000121 bool in_cache = !cached.is_null();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000122 LOG(isolate, RegExpCompileEvent(re, in_cache));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000123
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000124 Handle<Object> result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000125 if (in_cache) {
126 re->set_data(*cached);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000127 return re;
128 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000129 pattern = FlattenGetString(pattern);
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000130 ZoneScope zone_scope(isolate, DELETE_ON_EXIT);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000131 PostponeInterruptsScope postpone(isolate);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000132 RegExpCompileData parse_result;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000133 FlatStringReader reader(isolate, pattern);
fschneider@chromium.orge03fb642010-11-01 12:34:09 +0000134 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
135 &parse_result)) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000136 // Throw an exception if we fail to parse the pattern.
137 ThrowRegExpException(re,
138 pattern,
139 parse_result.error,
140 "malformed_regexp");
141 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000142 }
143
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000144 if (parse_result.simple && !flags.is_ignore_case()) {
145 // Parse-tree is a single atom that is equal to the pattern.
146 AtomCompile(re, pattern, flags, pattern);
147 } else if (parse_result.tree->IsAtom() &&
148 !flags.is_ignore_case() &&
149 parse_result.capture_count == 0) {
150 RegExpAtom* atom = parse_result.tree->AsAtom();
151 Vector<const uc16> atom_pattern = atom->data();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000152 Handle<String> atom_string =
153 isolate->factory()->NewStringFromTwoByte(atom_pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000154 AtomCompile(re, pattern, flags, atom_string);
155 } else {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000156 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000157 }
158 ASSERT(re->data()->IsFixedArray());
159 // Compilation succeeded so the data is set on the regexp
160 // and we can store it in the cache.
161 Handle<FixedArray> data(FixedArray::cast(re->data()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000162 compilation_cache->PutRegExp(pattern, flags, data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000163
164 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000165}
166
167
168Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
169 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000170 int index,
171 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000172 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000173 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000174 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000175 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000176 Handle<Object> result =
177 IrregexpExec(regexp, subject, index, last_match_info);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000178 ASSERT(!result.is_null() || Isolate::Current()->has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000179 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000180 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000181 default:
182 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000183 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000184 }
185}
186
187
ager@chromium.org8bb60582008-12-11 12:02:20 +0000188// RegExp Atom implementation: Simple string search using indexOf.
189
190
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000191void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
192 Handle<String> pattern,
193 JSRegExp::Flags flags,
194 Handle<String> match_pattern) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000195 re->GetIsolate()->factory()->SetRegExpAtomData(re,
196 JSRegExp::ATOM,
197 pattern,
198 flags,
199 match_pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000200}
201
202
203static void SetAtomLastCapture(FixedArray* array,
204 String* subject,
205 int from,
206 int to) {
207 NoHandleAllocation no_handles;
208 RegExpImpl::SetLastCaptureCount(array, 2);
209 RegExpImpl::SetLastSubject(array, subject);
210 RegExpImpl::SetLastInput(array, subject);
211 RegExpImpl::SetCapture(array, 0, from);
212 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000213}
214
215
216Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
217 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000218 int index,
219 Handle<JSArray> last_match_info) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000220 Isolate* isolate = re->GetIsolate();
221
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000222 ASSERT(0 <= index);
223 ASSERT(index <= subject->length());
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000224
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000225 if (!subject->IsFlat()) FlattenString(subject);
226 AssertNoAllocation no_heap_allocation; // ensure vectors stay valid
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000227
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000228 String* needle = String::cast(re->DataAt(JSRegExp::kAtomPatternIndex));
229 int needle_len = needle->length();
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000230 ASSERT(needle->IsFlat());
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000231
232 if (needle_len != 0) {
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000233 if (index + needle_len > subject->length()) {
234 return isolate->factory()->null_value();
235 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000236
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000237 String::FlatContent needle_content = needle->GetFlatContent();
238 String::FlatContent subject_content = subject->GetFlatContent();
239 ASSERT(needle_content.IsFlat());
240 ASSERT(subject_content.IsFlat());
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000241 // dispatch on type of strings
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000242 index = (needle_content.IsAscii()
243 ? (subject_content.IsAscii()
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000244 ? SearchString(isolate,
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000245 subject_content.ToAsciiVector(),
246 needle_content.ToAsciiVector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000247 index)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000248 : SearchString(isolate,
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000249 subject_content.ToUC16Vector(),
250 needle_content.ToAsciiVector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000251 index))
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000252 : (subject_content.IsAscii()
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000253 ? SearchString(isolate,
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000254 subject_content.ToAsciiVector(),
255 needle_content.ToUC16Vector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000256 index)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000257 : SearchString(isolate,
ricow@chromium.orgddd545c2011-08-24 12:02:41 +0000258 subject_content.ToUC16Vector(),
259 needle_content.ToUC16Vector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000260 index)));
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +0000261 if (index == -1) return isolate->factory()->null_value();
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000262 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000263 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000264
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000265 {
266 NoHandleAllocation no_handles;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000267 FixedArray* array = FixedArray::cast(last_match_info->elements());
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000268 SetAtomLastCapture(array, *subject, index, index + needle_len);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000269 }
270 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000271}
272
273
ager@chromium.org8bb60582008-12-11 12:02:20 +0000274// Irregexp implementation.
275
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000276// Ensures that the regexp object contains a compiled version of the
277// source for either ASCII or non-ASCII strings.
278// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000279// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000280// If compilation fails, an exception is thrown and this function
281// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000282bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000283 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000284#ifdef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000285 if (compiled_code->IsByteArray()) return true;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000286#else // V8_INTERPRETED_REGEXP (RegExp native code)
287 if (compiled_code->IsCode()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000288#endif
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000289 // We could potentially have marked this as flushable, but have kept
290 // a saved version if we did not flush it yet.
291 Object* saved_code = re->DataAt(JSRegExp::saved_code_index(is_ascii));
292 if (saved_code->IsCode()) {
293 // Reinstate the code in the original place.
294 re->SetDataAt(JSRegExp::code_index(is_ascii), saved_code);
295 ASSERT(compiled_code->IsSmi());
296 return true;
297 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000298 return CompileIrregexp(re, is_ascii);
299}
ager@chromium.org8bb60582008-12-11 12:02:20 +0000300
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000301
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000302static bool CreateRegExpErrorObjectAndThrow(Handle<JSRegExp> re,
303 bool is_ascii,
304 Handle<String> error_message,
305 Isolate* isolate) {
306 Factory* factory = isolate->factory();
307 Handle<FixedArray> elements = factory->NewFixedArray(2);
308 elements->set(0, re->Pattern());
309 elements->set(1, *error_message);
310 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
311 Handle<Object> regexp_err =
312 factory->NewSyntaxError("malformed_regexp", array);
313 isolate->Throw(*regexp_err);
314 return false;
315}
316
317
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000318bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000319 // Compile the RegExp.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000320 Isolate* isolate = re->GetIsolate();
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000321 ZoneScope zone_scope(isolate, DELETE_ON_EXIT);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000322 PostponeInterruptsScope postpone(isolate);
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000323 // If we had a compilation error the last time this is saved at the
324 // saved code index.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000325 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000326 // When arriving here entry can only be a smi, either representing an
327 // uncompiled regexp, a previous compilation error, or code that has
328 // been flushed.
329 ASSERT(entry->IsSmi());
330 int entry_value = Smi::cast(entry)->value();
331 ASSERT(entry_value == JSRegExp::kUninitializedValue ||
332 entry_value == JSRegExp::kCompilationErrorValue ||
333 (entry_value < JSRegExp::kCodeAgeMask && entry_value >= 0));
334
335 if (entry_value == JSRegExp::kCompilationErrorValue) {
336 // A previous compilation failed and threw an error which we store in
337 // the saved code index (we store the error message, not the actual
338 // error). Recreate the error object and throw it.
339 Object* error_string = re->DataAt(JSRegExp::saved_code_index(is_ascii));
340 ASSERT(error_string->IsString());
341 Handle<String> error_message(String::cast(error_string));
342 CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000343 return false;
344 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000345
346 JSRegExp::Flags flags = re->GetFlags();
347
348 Handle<String> pattern(re->Pattern());
ricow@chromium.org4668a2c2011-08-29 10:41:00 +0000349 if (!pattern->IsFlat()) FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000350 RegExpCompileData compile_data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000351 FlatStringReader reader(isolate, pattern);
fschneider@chromium.orge03fb642010-11-01 12:34:09 +0000352 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
353 &compile_data)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000354 // Throw an exception if we fail to parse the pattern.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000355 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000356 ThrowRegExpException(re,
357 pattern,
358 compile_data.error,
359 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000360 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000361 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000362 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000363 RegExpEngine::Compile(&compile_data,
364 flags.is_ignore_case(),
365 flags.is_multiline(),
366 pattern,
367 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000368 if (result.error_message != NULL) {
369 // Unable to compile regexp.
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000370 Handle<String> error_message =
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000371 isolate->factory()->NewStringFromUtf8(CStrVector(result.error_message));
372 CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000373 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000374 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000375
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000376 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
377 data->set(JSRegExp::code_index(is_ascii), result.code);
378 int register_max = IrregexpMaxRegisterCount(*data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000379 if (result.num_registers > register_max) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000380 SetIrregexpMaxRegisterCount(*data, result.num_registers);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000381 }
382
383 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000384}
385
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000386
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000387int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
388 return Smi::cast(
389 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000390}
391
392
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000393void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
394 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000395}
396
397
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000398int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
399 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000400}
401
402
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000403int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
404 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000405}
406
407
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000408ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000409 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000410}
411
412
413Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000414 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000415}
416
417
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000418void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
419 Handle<String> pattern,
420 JSRegExp::Flags flags,
421 int capture_count) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000422 // Initialize compiled code entries to null.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000423 re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
424 JSRegExp::IRREGEXP,
425 pattern,
426 flags,
427 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000428}
429
430
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000431int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
432 Handle<String> subject) {
ricow@chromium.org4668a2c2011-08-29 10:41:00 +0000433 if (!subject->IsFlat()) FlattenString(subject);
434
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000435 // Check the asciiness of the underlying storage.
ricow@chromium.org4668a2c2011-08-29 10:41:00 +0000436 bool is_ascii = subject->IsAsciiRepresentationUnderneath();
437 if (!EnsureCompiledIrregexp(regexp, is_ascii)) return -1;
438
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000439#ifdef V8_INTERPRETED_REGEXP
440 // Byte-code regexp needs space allocated for all its registers.
441 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
442#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000443 // Native regexp only needs room to output captures. Registers are handled
444 // internally.
445 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000446#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000447}
448
449
erik.corry@gmail.com145eff52010-08-23 11:36:18 +0000450RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(
451 Handle<JSRegExp> regexp,
452 Handle<String> subject,
453 int index,
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000454 Vector<int> output) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000455 Isolate* isolate = regexp->GetIsolate();
456
457 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000458
459 ASSERT(index >= 0);
460 ASSERT(index <= subject->length());
461 ASSERT(subject->IsFlat());
462
ricow@chromium.org4668a2c2011-08-29 10:41:00 +0000463 bool is_ascii = subject->IsAsciiRepresentationUnderneath();
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000464
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000465#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000466 ASSERT(output.length() >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000467 do {
sgjesse@chromium.org6db88712011-07-11 11:41:22 +0000468 EnsureCompiledIrregexp(regexp, is_ascii);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000469 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000470 NativeRegExpMacroAssembler::Result res =
471 NativeRegExpMacroAssembler::Match(code,
472 subject,
473 output.start(),
474 output.length(),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000475 index,
476 isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000477 if (res != NativeRegExpMacroAssembler::RETRY) {
478 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000479 isolate->has_pending_exception());
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000480 STATIC_ASSERT(
481 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
482 STATIC_ASSERT(
483 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
484 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
485 == RE_EXCEPTION);
486 return static_cast<IrregexpResult>(res);
487 }
488 // If result is RETRY, the string has changed representation, and we
489 // must restart from scratch.
490 // In this case, it means we must make sure we are prepared to handle
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000491 // the, potentially, different subject (the string can switch between
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000492 // being internal and external, and even between being ASCII and UC16,
493 // but the characters are always the same).
494 IrregexpPrepare(regexp, subject);
ricow@chromium.org4668a2c2011-08-29 10:41:00 +0000495 is_ascii = subject->IsAsciiRepresentationUnderneath();
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000496 } while (true);
497 UNREACHABLE();
498 return RE_EXCEPTION;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000499#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000500
501 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000502 // We must have done EnsureCompiledIrregexp, so we can get the number of
503 // registers.
504 int* register_vector = output.start();
505 int number_of_capture_registers =
506 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
507 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
508 register_vector[i] = -1;
509 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000510 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000511
fschneider@chromium.org7979bbb2011-03-28 10:47:03 +0000512 if (IrregexpInterpreter::Match(isolate,
513 byte_codes,
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000514 subject,
515 register_vector,
516 index)) {
517 return RE_SUCCESS;
518 }
519 return RE_FAILURE;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000520#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000521}
522
523
ager@chromium.org41826e72009-03-30 13:30:57 +0000524Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000525 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000526 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000527 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000528 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000529
ager@chromium.org8bb60582008-12-11 12:02:20 +0000530 // Prepare space for the return values.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000531#ifdef V8_INTERPRETED_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000532#ifdef DEBUG
533 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000534 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000535 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
536 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
537 }
538#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000539#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000540 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
541 if (required_registers < 0) {
542 // Compiling failed with an exception.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000543 ASSERT(Isolate::Current()->has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000544 return Handle<Object>::null();
545 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000546
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000547 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000548
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000549 IrregexpResult res = RegExpImpl::IrregexpExecOnce(
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000550 jsregexp, subject, previous_index, Vector<int>(registers.vector(),
551 registers.length()));
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000552 if (res == RE_SUCCESS) {
553 int capture_register_count =
554 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
555 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
556 AssertNoAllocation no_gc;
557 int* register_vector = registers.vector();
558 FixedArray* array = FixedArray::cast(last_match_info->elements());
559 for (int i = 0; i < capture_register_count; i += 2) {
560 SetCapture(array, i, register_vector[i]);
561 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000562 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000563 SetLastCaptureCount(array, capture_register_count);
564 SetLastSubject(array, *subject);
565 SetLastInput(array, *subject);
566 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000567 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000568 if (res == RE_EXCEPTION) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000569 ASSERT(Isolate::Current()->has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000570 return Handle<Object>::null();
571 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000572 ASSERT(res == RE_FAILURE);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000573 return Isolate::Current()->factory()->null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000574}
575
576
577// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000578// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000579//
580// The Irregexp regular expression engine is intended to be a complete
581// implementation of ECMAScript regular expressions. It generates either
582// bytecodes or native code.
583
584// The Irregexp regexp engine is structured in three steps.
585// 1) The parser generates an abstract syntax tree. See ast.cc.
586// 2) From the AST a node network is created. The nodes are all
587// subclasses of RegExpNode. The nodes represent states when
588// executing a regular expression. Several optimizations are
589// performed on the node network.
590// 3) From the nodes we generate either byte codes or native code
591// that can actually execute the regular expression (perform
592// the search). The code generation step is described in more
593// detail below.
594
595// Code generation.
596//
597// The nodes are divided into four main categories.
598// * Choice nodes
599// These represent places where the regular expression can
600// match in more than one way. For example on entry to an
601// alternation (foo|bar) or a repetition (*, +, ? or {}).
602// * Action nodes
603// These represent places where some action should be
604// performed. Examples include recording the current position
605// in the input string to a register (in order to implement
606// captures) or other actions on register for example in order
607// to implement the counters needed for {} repetitions.
608// * Matching nodes
609// These attempt to match some element part of the input string.
610// Examples of elements include character classes, plain strings
611// or back references.
612// * End nodes
613// These are used to implement the actions required on finding
614// a successful match or failing to find a match.
615//
616// The code generated (whether as byte codes or native code) maintains
617// some state as it runs. This consists of the following elements:
618//
619// * The capture registers. Used for string captures.
620// * Other registers. Used for counters etc.
621// * The current position.
622// * The stack of backtracking information. Used when a matching node
623// fails to find a match and needs to try an alternative.
624//
625// Conceptual regular expression execution model:
626//
627// There is a simple conceptual model of regular expression execution
628// which will be presented first. The actual code generated is a more
629// efficient simulation of the simple conceptual model:
630//
631// * Choice nodes are implemented as follows:
632// For each choice except the last {
633// push current position
634// push backtrack code location
635// <generate code to test for choice>
636// backtrack code location:
637// pop current position
638// }
639// <generate code to test for last choice>
640//
641// * Actions nodes are generated as follows
642// <push affected registers on backtrack stack>
643// <generate code to perform action>
644// push backtrack code location
645// <generate code to test for following nodes>
646// backtrack code location:
647// <pop affected registers to restore their state>
648// <pop backtrack location from stack and go to it>
649//
650// * Matching nodes are generated as follows:
651// if input string matches at current position
652// update current position
653// <generate code to test for following nodes>
654// else
655// <pop backtrack location from stack and go to it>
656//
657// Thus it can be seen that the current position is saved and restored
658// by the choice nodes, whereas the registers are saved and restored by
659// by the action nodes that manipulate them.
660//
661// The other interesting aspect of this model is that nodes are generated
662// at the point where they are needed by a recursive call to Emit(). If
663// the node has already been code generated then the Emit() call will
664// generate a jump to the previously generated code instead. In order to
665// limit recursion it is possible for the Emit() function to put the node
666// on a work list for later generation and instead generate a jump. The
667// destination of the jump is resolved later when the code is generated.
668//
669// Actual regular expression code generation.
670//
671// Code generation is actually more complicated than the above. In order
672// to improve the efficiency of the generated code some optimizations are
673// performed
674//
675// * Choice nodes have 1-character lookahead.
676// A choice node looks at the following character and eliminates some of
677// the choices immediately based on that character. This is not yet
678// implemented.
679// * Simple greedy loops store reduced backtracking information.
680// A quantifier like /.*foo/m will greedily match the whole input. It will
681// then need to backtrack to a point where it can match "foo". The naive
682// implementation of this would push each character position onto the
683// backtracking stack, then pop them off one by one. This would use space
684// proportional to the length of the input string. However since the "."
685// can only match in one way and always has a constant length (in this case
686// of 1) it suffices to store the current position on the top of the stack
687// once. Matching now becomes merely incrementing the current position and
688// backtracking becomes decrementing the current position and checking the
689// result against the stored current position. This is faster and saves
690// space.
691// * The current state is virtualized.
692// This is used to defer expensive operations until it is clear that they
693// are needed and to generate code for a node more than once, allowing
694// specialized an efficient versions of the code to be created. This is
695// explained in the section below.
696//
697// Execution state virtualization.
698//
699// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000700// manipulation in an object called the Trace. The Trace object can record a
701// current position offset, an optional backtrack code location on the top of
702// the virtualized backtrack stack and some register changes. When a node is
703// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000704// will emit code to bring the actual state into line with the virtual state.
705// Avoiding flushing the state can postpone some work (eg updates of capture
706// registers). Postponing work can save time when executing the regular
707// expression since it may be found that the work never has to be done as a
708// failure to match can occur. In addition it is much faster to jump to a
709// known backtrack code location than it is to pop an unknown backtrack
710// location from the stack and jump there.
711//
ager@chromium.org32912102009-01-16 10:38:43 +0000712// The virtual state found in the Trace affects code generation. For example
713// the virtual state contains the difference between the actual current
714// position and the virtual current position, and matching code needs to use
715// this offset to attempt a match in the correct location of the input
716// string. Therefore code generated for a non-trivial trace is specialized
717// to that trace. The code generator therefore has the ability to generate
718// code for each node several times. In order to limit the size of the
719// generated code there is an arbitrary limit on how many specialized sets of
720// code may be generated for a given node. If the limit is reached, the
721// trace is flushed and a generic version of the code for a node is emitted.
722// This is subsequently used for that node. The code emitted for non-generic
723// trace is not recorded in the node and so it cannot currently be reused in
724// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000725
726
727void RegExpTree::AppendToText(RegExpText* text) {
728 UNREACHABLE();
729}
730
731
732void RegExpAtom::AppendToText(RegExpText* text) {
733 text->AddElement(TextElement::Atom(this));
734}
735
736
737void RegExpCharacterClass::AppendToText(RegExpText* text) {
738 text->AddElement(TextElement::CharClass(this));
739}
740
741
742void RegExpText::AppendToText(RegExpText* text) {
743 for (int i = 0; i < elements()->length(); i++)
744 text->AddElement(elements()->at(i));
745}
746
747
748TextElement TextElement::Atom(RegExpAtom* atom) {
749 TextElement result = TextElement(ATOM);
750 result.data.u_atom = atom;
751 return result;
752}
753
754
755TextElement TextElement::CharClass(
756 RegExpCharacterClass* char_class) {
757 TextElement result = TextElement(CHAR_CLASS);
758 result.data.u_char_class = char_class;
759 return result;
760}
761
762
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000763int TextElement::length() {
764 if (type == ATOM) {
765 return data.u_atom->length();
766 } else {
767 ASSERT(type == CHAR_CLASS);
768 return 1;
769 }
770}
771
772
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000773DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
774 if (table_ == NULL) {
775 table_ = new DispatchTable();
776 DispatchTableConstructor cons(table_, ignore_case);
777 cons.BuildTable(this);
778 }
779 return table_;
780}
781
782
783class RegExpCompiler {
784 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000785 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000786
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000787 int AllocateRegister() {
788 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
789 reg_exp_too_big_ = true;
790 return next_register_;
791 }
792 return next_register_++;
793 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000794
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000795 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
796 RegExpNode* start,
797 int capture_count,
798 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000799
800 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
801
802 static const int kImplementationOffset = 0;
803 static const int kNumberOfRegistersOffset = 0;
804 static const int kCodeOffset = 1;
805
806 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
807 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000808
809 static const int kMaxRecursion = 100;
810 inline int recursion_depth() { return recursion_depth_; }
811 inline void IncrementRecursionDepth() { recursion_depth_++; }
812 inline void DecrementRecursionDepth() { recursion_depth_--; }
813
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000814 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
815
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000816 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000817 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000818
whesse@chromium.org7b260152011-06-20 15:33:18 +0000819 int current_expansion_factor() { return current_expansion_factor_; }
820 void set_current_expansion_factor(int value) {
821 current_expansion_factor_ = value;
822 }
823
ager@chromium.org32912102009-01-16 10:38:43 +0000824 static const int kNoRegister = -1;
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000825
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000826 private:
827 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000828 int next_register_;
829 List<RegExpNode*>* work_list_;
830 int recursion_depth_;
831 RegExpMacroAssembler* macro_assembler_;
832 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000833 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000834 bool reg_exp_too_big_;
whesse@chromium.org7b260152011-06-20 15:33:18 +0000835 int current_expansion_factor_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000836};
837
838
839class RecursionCheck {
840 public:
841 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
842 compiler->IncrementRecursionDepth();
843 }
844 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
845 private:
846 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000847};
848
849
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000850static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
851 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000852}
853
854
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000855// Attempts to compile the regexp using an Irregexp code generator. Returns
856// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000857RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000858 : next_register_(2 * (capture_count + 1)),
859 work_list_(NULL),
860 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000861 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000862 ascii_(ascii),
whesse@chromium.org7b260152011-06-20 15:33:18 +0000863 reg_exp_too_big_(false),
864 current_expansion_factor_(1) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000865 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000866 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000867}
868
869
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000870RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000871 RegExpMacroAssembler* macro_assembler,
872 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000873 int capture_count,
874 Handle<String> pattern) {
karlklose@chromium.org83a47282011-05-11 11:54:09 +0000875 Heap* heap = pattern->GetHeap();
876
877 bool use_slow_safe_regexp_compiler = false;
878 if (heap->total_regexp_code_generated() >
879 RegExpImpl::kRegWxpCompiledLimit &&
880 heap->isolate()->memory_allocator()->SizeExecutable() >
881 RegExpImpl::kRegExpExecutableMemoryLimit) {
882 use_slow_safe_regexp_compiler = true;
883 }
884
885 macro_assembler->set_slow_safe(use_slow_safe_regexp_compiler);
886
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000887#ifdef DEBUG
888 if (FLAG_trace_regexp_assembler)
889 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
890 else
891#endif
892 macro_assembler_ = macro_assembler;
karlklose@chromium.org83a47282011-05-11 11:54:09 +0000893
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000894 List <RegExpNode*> work_list(0);
895 work_list_ = &work_list;
896 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000897 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000898 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000899 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000900 macro_assembler_->Bind(&fail);
901 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000902 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000903 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000904 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000905 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
906
karlklose@chromium.org83a47282011-05-11 11:54:09 +0000907 Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
908 heap->IncreaseTotalRegexpCodeGenerated(code->Size());
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000909 work_list_ = NULL;
910#ifdef DEBUG
danno@chromium.org4d3fe4e2011-03-10 10:14:28 +0000911 if (FLAG_print_code) {
912 Handle<Code>::cast(code)->Disassemble(*pattern->ToCString());
913 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000914 if (FLAG_trace_regexp_assembler) {
915 delete macro_assembler_;
916 }
917#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000918 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000919}
920
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000921
ager@chromium.org32912102009-01-16 10:38:43 +0000922bool Trace::DeferredAction::Mentions(int that) {
923 if (type() == ActionNode::CLEAR_CAPTURES) {
924 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
925 return range.Contains(that);
926 } else {
927 return reg() == that;
928 }
929}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000930
ager@chromium.org32912102009-01-16 10:38:43 +0000931
932bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000933 for (DeferredAction* action = actions_;
934 action != NULL;
935 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000936 if (action->Mentions(reg))
937 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000938 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000939 return false;
940}
941
942
ager@chromium.org32912102009-01-16 10:38:43 +0000943bool Trace::GetStoredPosition(int reg, int* cp_offset) {
944 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000945 for (DeferredAction* action = actions_;
946 action != NULL;
947 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000948 if (action->Mentions(reg)) {
949 if (action->type() == ActionNode::STORE_POSITION) {
950 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
951 return true;
952 } else {
953 return false;
954 }
955 }
956 }
957 return false;
958}
959
960
961int Trace::FindAffectedRegisters(OutSet* affected_registers) {
962 int max_register = RegExpCompiler::kNoRegister;
963 for (DeferredAction* action = actions_;
964 action != NULL;
965 action = action->next()) {
966 if (action->type() == ActionNode::CLEAR_CAPTURES) {
967 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
968 for (int i = range.from(); i <= range.to(); i++)
969 affected_registers->Set(i);
970 if (range.to() > max_register) max_register = range.to();
971 } else {
972 affected_registers->Set(action->reg());
973 if (action->reg() > max_register) max_register = action->reg();
974 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000975 }
976 return max_register;
977}
978
979
ager@chromium.org32912102009-01-16 10:38:43 +0000980void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
981 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000982 OutSet& registers_to_pop,
983 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000984 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000985 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
986 else if (registers_to_clear.Get(reg)) {
987 int clear_to = reg;
988 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
989 reg--;
990 }
991 assembler->ClearRegisters(reg, clear_to);
992 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000993 }
994}
995
996
ager@chromium.org32912102009-01-16 10:38:43 +0000997void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
998 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000999 OutSet& affected_registers,
1000 OutSet* registers_to_pop,
1001 OutSet* registers_to_clear) {
1002 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
1003 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
1004
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001005 // Count pushes performed to force a stack limit check occasionally.
1006 int pushes = 0;
1007
ager@chromium.org8bb60582008-12-11 12:02:20 +00001008 for (int reg = 0; reg <= max_register; reg++) {
1009 if (!affected_registers.Get(reg)) {
1010 continue;
1011 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001012
1013 // The chronologically first deferred action in the trace
1014 // is used to infer the action needed to restore a register
1015 // to its previous state (or not, if it's safe to ignore it).
1016 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
1017 DeferredActionUndoType undo_action = IGNORE;
1018
ager@chromium.org8bb60582008-12-11 12:02:20 +00001019 int value = 0;
1020 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +00001021 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001022 int store_position = -1;
1023 // This is a little tricky because we are scanning the actions in reverse
1024 // historical order (newest first).
1025 for (DeferredAction* action = actions_;
1026 action != NULL;
1027 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +00001028 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001029 switch (action->type()) {
1030 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00001031 Trace::DeferredSetRegister* psr =
1032 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001033 if (!absolute) {
1034 value += psr->value();
1035 absolute = true;
1036 }
1037 // SET_REGISTER is currently only used for newly introduced loop
1038 // counters. They can have a significant previous value if they
1039 // occour in a loop. TODO(lrn): Propagate this information, so
1040 // we can set undo_action to IGNORE if we know there is no value to
1041 // restore.
1042 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001043 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001044 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001045 break;
1046 }
1047 case ActionNode::INCREMENT_REGISTER:
1048 if (!absolute) {
1049 value++;
1050 }
1051 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001052 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001053 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001054 break;
1055 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00001056 Trace::DeferredCapture* pc =
1057 static_cast<Trace::DeferredCapture*>(action);
1058 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001059 store_position = pc->cp_offset();
1060 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001061
1062 // For captures we know that stores and clears alternate.
1063 // Other register, are never cleared, and if the occur
1064 // inside a loop, they might be assigned more than once.
1065 if (reg <= 1) {
1066 // Registers zero and one, aka "capture zero", is
1067 // always set correctly if we succeed. There is no
1068 // need to undo a setting on backtrack, because we
1069 // will set it again or fail.
1070 undo_action = IGNORE;
1071 } else {
1072 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1073 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001074 ASSERT(!absolute);
1075 ASSERT_EQ(value, 0);
1076 break;
1077 }
ager@chromium.org32912102009-01-16 10:38:43 +00001078 case ActionNode::CLEAR_CAPTURES: {
1079 // Since we're scanning in reverse order, if we've already
1080 // set the position we have to ignore historically earlier
1081 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001082 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +00001083 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001084 }
1085 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +00001086 ASSERT(!absolute);
1087 ASSERT_EQ(value, 0);
1088 break;
1089 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001090 default:
1091 UNREACHABLE();
1092 break;
1093 }
1094 }
1095 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001096 // Prepare for the undo-action (e.g., push if it's going to be popped).
1097 if (undo_action == RESTORE) {
1098 pushes++;
1099 RegExpMacroAssembler::StackCheckFlag stack_check =
1100 RegExpMacroAssembler::kNoStackLimitCheck;
1101 if (pushes == push_limit) {
1102 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1103 pushes = 0;
1104 }
1105
1106 assembler->PushRegister(reg, stack_check);
1107 registers_to_pop->Set(reg);
1108 } else if (undo_action == CLEAR) {
1109 registers_to_clear->Set(reg);
1110 }
1111 // Perform the chronologically last action (or accumulated increment)
1112 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001113 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001114 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001115 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001116 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001117 } else if (absolute) {
1118 assembler->SetRegister(reg, value);
1119 } else if (value != 0) {
1120 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001121 }
1122 }
1123}
1124
1125
ager@chromium.org8bb60582008-12-11 12:02:20 +00001126// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001127// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001128// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001129void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001130 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001131
iposva@chromium.org245aa852009-02-10 00:49:54 +00001132 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001133
1134 if (actions_ == NULL && backtrack() == NULL) {
1135 // 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 +00001136 // a normal situation. We may also have to forget some information gained
1137 // through a quick check that was already performed.
1138 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001139 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001140 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001141 successor->Emit(compiler, &new_state);
1142 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001143 }
1144
1145 // Generate deferred actions here along with code to undo them again.
1146 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001147
ager@chromium.org381abbb2009-02-25 13:23:22 +00001148 if (backtrack() != NULL) {
1149 // Here we have a concrete backtrack location. These are set up by choice
1150 // nodes and so they indicate that we have a deferred save of the current
1151 // position which we may need to emit here.
1152 assembler->PushCurrentPosition();
1153 }
1154
ager@chromium.org8bb60582008-12-11 12:02:20 +00001155 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001156 OutSet registers_to_pop;
1157 OutSet registers_to_clear;
1158 PerformDeferredActions(assembler,
1159 max_register,
1160 affected_registers,
1161 &registers_to_pop,
1162 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001163 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001164 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001165 }
1166
1167 // Create a new trivial state and generate the node with that.
1168 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001169 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001170 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001171 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001172
1173 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001174 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001175 RestoreAffectedRegisters(assembler,
1176 max_register,
1177 registers_to_pop,
1178 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001179 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001180 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001181 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001182 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001183 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001184 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001185}
1186
1187
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001188void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001189 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001190
1191 // Omit flushing the trace. We discard the entire stack frame anyway.
1192
ager@chromium.org8bb60582008-12-11 12:02:20 +00001193 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001194 // We are completely independent of the trace, since we ignore it,
1195 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001196 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001197 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001198
1199 // Throw away everything on the backtrack stack since the start
1200 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001201 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1202 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001203 if (clear_capture_count_ > 0) {
1204 // Clear any captures that might have been performed during the success
1205 // of the body of the negative look-ahead.
1206 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1207 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1208 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001209 // Now that we have unwound the stack we find at the top of the stack the
1210 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001211 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001212}
1213
1214
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001215void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001216 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001217 trace->Flush(compiler, this);
1218 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001219 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001220 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001221 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001222 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001223 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001224 switch (action_) {
1225 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001226 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001227 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001228 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001229 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001230 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001231 case NEGATIVE_SUBMATCH_SUCCESS:
1232 // This case is handled in a different virtual method.
1233 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001234 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001235 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001236}
1237
1238
1239void GuardedAlternative::AddGuard(Guard* guard) {
1240 if (guards_ == NULL)
1241 guards_ = new ZoneList<Guard*>(1);
1242 guards_->Add(guard);
1243}
1244
1245
ager@chromium.org8bb60582008-12-11 12:02:20 +00001246ActionNode* ActionNode::SetRegister(int reg,
1247 int val,
1248 RegExpNode* on_success) {
1249 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001250 result->data_.u_store_register.reg = reg;
1251 result->data_.u_store_register.value = val;
1252 return result;
1253}
1254
1255
1256ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1257 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1258 result->data_.u_increment_register.reg = reg;
1259 return result;
1260}
1261
1262
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001263ActionNode* ActionNode::StorePosition(int reg,
1264 bool is_capture,
1265 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001266 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1267 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001268 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001269 return result;
1270}
1271
1272
ager@chromium.org32912102009-01-16 10:38:43 +00001273ActionNode* ActionNode::ClearCaptures(Interval range,
1274 RegExpNode* on_success) {
1275 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1276 result->data_.u_clear_captures.range_from = range.from();
1277 result->data_.u_clear_captures.range_to = range.to();
1278 return result;
1279}
1280
1281
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001282ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1283 int position_reg,
1284 RegExpNode* on_success) {
1285 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1286 result->data_.u_submatch.stack_pointer_register = stack_reg;
1287 result->data_.u_submatch.current_position_register = position_reg;
1288 return result;
1289}
1290
1291
ager@chromium.org8bb60582008-12-11 12:02:20 +00001292ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1293 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001294 int clear_register_count,
1295 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001296 RegExpNode* on_success) {
1297 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001298 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001299 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001300 result->data_.u_submatch.clear_register_count = clear_register_count;
1301 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001302 return result;
1303}
1304
1305
ager@chromium.org32912102009-01-16 10:38:43 +00001306ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1307 int repetition_register,
1308 int repetition_limit,
1309 RegExpNode* on_success) {
1310 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1311 result->data_.u_empty_match_check.start_register = start_register;
1312 result->data_.u_empty_match_check.repetition_register = repetition_register;
1313 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1314 return result;
1315}
1316
1317
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001318#define DEFINE_ACCEPT(Type) \
1319 void Type##Node::Accept(NodeVisitor* visitor) { \
1320 visitor->Visit##Type(this); \
1321 }
1322FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1323#undef DEFINE_ACCEPT
1324
1325
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001326void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1327 visitor->VisitLoopChoice(this);
1328}
1329
1330
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001331// -------------------------------------------------------------------
1332// Emit code.
1333
1334
1335void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1336 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001337 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001338 switch (guard->op()) {
1339 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001340 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001341 macro_assembler->IfRegisterGE(guard->reg(),
1342 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001343 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001344 break;
1345 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001346 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001347 macro_assembler->IfRegisterLT(guard->reg(),
1348 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001349 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001350 break;
1351 }
1352}
1353
1354
ager@chromium.org381abbb2009-02-25 13:23:22 +00001355// Returns the number of characters in the equivalence class, omitting those
1356// that cannot occur in the source string because it is ASCII.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001357static int GetCaseIndependentLetters(Isolate* isolate,
1358 uc16 character,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001359 bool ascii_subject,
1360 unibrow::uchar* letters) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001361 int length =
1362 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00001363 // Unibrow returns 0 or 1 for characters where case independence is
ager@chromium.org381abbb2009-02-25 13:23:22 +00001364 // trivial.
1365 if (length == 0) {
1366 letters[0] = character;
1367 length = 1;
1368 }
1369 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1370 return length;
1371 }
1372 // The standard requires that non-ASCII characters cannot have ASCII
1373 // character codes in their equivalence class.
1374 return 0;
1375}
1376
1377
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001378static inline bool EmitSimpleCharacter(Isolate* isolate,
1379 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001380 uc16 c,
1381 Label* on_failure,
1382 int cp_offset,
1383 bool check,
1384 bool preloaded) {
1385 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1386 bool bound_checked = false;
1387 if (!preloaded) {
1388 assembler->LoadCurrentCharacter(
1389 cp_offset,
1390 on_failure,
1391 check);
1392 bound_checked = true;
1393 }
1394 assembler->CheckNotCharacter(c, on_failure);
1395 return bound_checked;
1396}
1397
1398
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001399// Only emits non-letters (things that don't have case). Only used for case
1400// independent matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001401static inline bool EmitAtomNonLetter(Isolate* isolate,
1402 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001403 uc16 c,
1404 Label* on_failure,
1405 int cp_offset,
1406 bool check,
1407 bool preloaded) {
1408 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1409 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001410 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001411 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001412 if (length < 1) {
1413 // This can't match. Must be an ASCII subject and a non-ASCII character.
1414 // We do not need to do anything since the ASCII pass already handled this.
1415 return false; // Bounds not checked.
1416 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001417 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001418 // We handle the length > 1 case in a later pass.
1419 if (length == 1) {
1420 if (ascii && c > String::kMaxAsciiCharCodeU) {
1421 // Can't match - see above.
1422 return false; // Bounds not checked.
1423 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001424 if (!preloaded) {
1425 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1426 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001427 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001428 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001429 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001430 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001431}
1432
1433
1434static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001435 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001436 uc16 c1,
1437 uc16 c2,
1438 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001439 uc16 char_mask;
1440 if (ascii) {
1441 char_mask = String::kMaxAsciiCharCode;
1442 } else {
1443 char_mask = String::kMaxUC16CharCode;
1444 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001445 uc16 exor = c1 ^ c2;
1446 // Check whether exor has only one bit set.
1447 if (((exor - 1) & exor) == 0) {
1448 // If c1 and c2 differ only by one bit.
1449 // Ecma262UnCanonicalize always gives the highest number last.
1450 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001451 uc16 mask = char_mask ^ exor;
1452 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001453 return true;
1454 }
1455 ASSERT(c2 > c1);
1456 uc16 diff = c2 - c1;
1457 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1458 // If the characters differ by 2^n but don't differ by one bit then
1459 // subtract the difference from the found character, then do the or
1460 // trick. We avoid the theoretical case where negative numbers are
1461 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001462 uc16 mask = char_mask ^ diff;
1463 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1464 diff,
1465 mask,
1466 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001467 return true;
1468 }
1469 return false;
1470}
1471
1472
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001473typedef bool EmitCharacterFunction(Isolate* isolate,
1474 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001475 uc16 c,
1476 Label* on_failure,
1477 int cp_offset,
1478 bool check,
1479 bool preloaded);
1480
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001481// Only emits letters (things that have case). Only used for case independent
1482// matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001483static inline bool EmitAtomLetter(Isolate* isolate,
1484 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001485 uc16 c,
1486 Label* on_failure,
1487 int cp_offset,
1488 bool check,
1489 bool preloaded) {
1490 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1491 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001492 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001493 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001494 if (length <= 1) return false;
1495 // We may not need to check against the end of the input string
1496 // if this character lies before a character that matched.
1497 if (!preloaded) {
1498 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001499 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001500 Label ok;
1501 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1502 switch (length) {
1503 case 2: {
1504 if (ShortCutEmitCharacterPair(macro_assembler,
1505 ascii,
1506 chars[0],
1507 chars[1],
1508 on_failure)) {
1509 } else {
1510 macro_assembler->CheckCharacter(chars[0], &ok);
1511 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1512 macro_assembler->Bind(&ok);
1513 }
1514 break;
1515 }
1516 case 4:
1517 macro_assembler->CheckCharacter(chars[3], &ok);
1518 // Fall through!
1519 case 3:
1520 macro_assembler->CheckCharacter(chars[0], &ok);
1521 macro_assembler->CheckCharacter(chars[1], &ok);
1522 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1523 macro_assembler->Bind(&ok);
1524 break;
1525 default:
1526 UNREACHABLE();
1527 break;
1528 }
1529 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001530}
1531
1532
1533static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1534 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001535 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001536 Label* on_failure,
1537 int cp_offset,
1538 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001539 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001540 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001541 int max_char;
1542 if (ascii) {
1543 max_char = String::kMaxAsciiCharCode;
1544 } else {
1545 max_char = String::kMaxUC16CharCode;
1546 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001547
1548 Label success;
1549
1550 Label* char_is_in_class =
1551 cc->is_negated() ? on_failure : &success;
1552
1553 int range_count = ranges->length();
1554
ager@chromium.org8bb60582008-12-11 12:02:20 +00001555 int last_valid_range = range_count - 1;
1556 while (last_valid_range >= 0) {
1557 CharacterRange& range = ranges->at(last_valid_range);
1558 if (range.from() <= max_char) {
1559 break;
1560 }
1561 last_valid_range--;
1562 }
1563
1564 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001565 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001566 // TODO(plesner): We can remove this when the node level does our
1567 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001568 macro_assembler->GoTo(on_failure);
1569 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001570 if (check_offset) {
1571 macro_assembler->CheckPosition(cp_offset, on_failure);
1572 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001573 return;
1574 }
1575
ager@chromium.org8bb60582008-12-11 12:02:20 +00001576 if (last_valid_range == 0 &&
1577 !cc->is_negated() &&
1578 ranges->at(0).IsEverything(max_char)) {
1579 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001580 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001581 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001582 }
1583 return;
1584 }
1585
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001586 if (!preloaded) {
1587 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001588 }
1589
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001590 if (cc->is_standard() &&
1591 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1592 on_failure)) {
1593 return;
1594 }
1595
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001596 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001597 CharacterRange& range = ranges->at(i);
1598 Label next_range;
1599 uc16 from = range.from();
1600 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001601 if (from > max_char) {
1602 continue;
1603 }
1604 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001605 if (to == from) {
1606 macro_assembler->CheckCharacter(to, char_is_in_class);
1607 } else {
1608 if (from != 0) {
1609 macro_assembler->CheckCharacterLT(from, &next_range);
1610 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001611 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001612 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1613 } else {
1614 macro_assembler->GoTo(char_is_in_class);
1615 }
1616 }
1617 macro_assembler->Bind(&next_range);
1618 }
1619
ager@chromium.org8bb60582008-12-11 12:02:20 +00001620 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001621 uc16 from = range.from();
1622 uc16 to = range.to();
1623
ager@chromium.org8bb60582008-12-11 12:02:20 +00001624 if (to > max_char) to = max_char;
1625 ASSERT(to >= from);
1626
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001627 if (to == from) {
1628 if (cc->is_negated()) {
1629 macro_assembler->CheckCharacter(to, on_failure);
1630 } else {
1631 macro_assembler->CheckNotCharacter(to, on_failure);
1632 }
1633 } else {
1634 if (from != 0) {
1635 if (cc->is_negated()) {
1636 macro_assembler->CheckCharacterLT(from, &success);
1637 } else {
1638 macro_assembler->CheckCharacterLT(from, on_failure);
1639 }
1640 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001641 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001642 if (cc->is_negated()) {
1643 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1644 } else {
1645 macro_assembler->CheckCharacterGT(to, on_failure);
1646 }
1647 } else {
1648 if (cc->is_negated()) {
1649 macro_assembler->GoTo(on_failure);
1650 }
1651 }
1652 }
1653 macro_assembler->Bind(&success);
1654}
1655
1656
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001657RegExpNode::~RegExpNode() {
1658}
1659
1660
ager@chromium.org8bb60582008-12-11 12:02:20 +00001661RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001662 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001663 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001664 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001665 return CONTINUE;
1666 }
1667
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001668 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001669 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001670 if (label_.is_bound()) {
1671 // We are being asked to generate a generic version, but that's already
1672 // been done so just go to it.
1673 macro_assembler->GoTo(&label_);
1674 return DONE;
1675 }
1676 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1677 // To avoid too deep recursion we push the node to the work queue and just
1678 // generate a goto here.
1679 compiler->AddWork(this);
1680 macro_assembler->GoTo(&label_);
1681 return DONE;
1682 }
1683 // Generate generic version of the node and bind the label for later use.
1684 macro_assembler->Bind(&label_);
1685 return CONTINUE;
1686 }
1687
1688 // We are being asked to make a non-generic version. Keep track of how many
1689 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001690 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001691 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001692 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001693 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1694 return CONTINUE;
1695 }
1696
ager@chromium.org32912102009-01-16 10:38:43 +00001697 // If we get here code has been generated for this node too many times or
1698 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001699 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001700 trace->Flush(compiler, this);
1701 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001702}
1703
1704
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001705int ActionNode::EatsAtLeast(int still_to_find,
1706 int recursion_depth,
1707 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001708 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1709 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001710 return on_success()->EatsAtLeast(still_to_find,
1711 recursion_depth + 1,
1712 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001713}
1714
1715
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001716int AssertionNode::EatsAtLeast(int still_to_find,
1717 int recursion_depth,
1718 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001719 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001720 // If we know we are not at the start and we are asked "how many characters
1721 // will you match if you succeed?" then we can answer anything since false
1722 // implies false. So lets just return the max answer (still_to_find) since
1723 // that won't prevent us from preloading a lot of characters for the other
1724 // branches in the node graph.
1725 if (type() == AT_START && not_at_start) return still_to_find;
1726 return on_success()->EatsAtLeast(still_to_find,
1727 recursion_depth + 1,
1728 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001729}
1730
1731
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001732int BackReferenceNode::EatsAtLeast(int still_to_find,
1733 int recursion_depth,
1734 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001735 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001736 return on_success()->EatsAtLeast(still_to_find,
1737 recursion_depth + 1,
1738 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001739}
1740
1741
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001742int TextNode::EatsAtLeast(int still_to_find,
1743 int recursion_depth,
1744 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001745 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001746 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001747 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001748 // We are not at start after this node so we set the last argument to 'true'.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001749 return answer + on_success()->EatsAtLeast(still_to_find - answer,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001750 recursion_depth + 1,
1751 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001752}
1753
1754
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001755int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001756 int recursion_depth,
1757 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001758 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1759 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1760 // afterwards.
1761 RegExpNode* node = alternatives_->at(1).node();
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001762 return node->EatsAtLeast(still_to_find, recursion_depth + 1, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001763}
1764
1765
1766void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1767 QuickCheckDetails* details,
1768 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001769 int filled_in,
1770 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001771 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1772 // afterwards.
1773 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001774 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001775}
1776
1777
1778int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1779 int recursion_depth,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001780 RegExpNode* ignore_this_node,
1781 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001782 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1783 int min = 100;
1784 int choice_count = alternatives_->length();
1785 for (int i = 0; i < choice_count; i++) {
1786 RegExpNode* node = alternatives_->at(i).node();
1787 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001788 int node_eats_at_least = node->EatsAtLeast(still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001789 recursion_depth + 1,
1790 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001791 if (node_eats_at_least < min) min = node_eats_at_least;
1792 }
1793 return min;
1794}
1795
1796
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001797int LoopChoiceNode::EatsAtLeast(int still_to_find,
1798 int recursion_depth,
1799 bool not_at_start) {
1800 return EatsAtLeastHelper(still_to_find,
1801 recursion_depth,
1802 loop_node_,
1803 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001804}
1805
1806
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001807int ChoiceNode::EatsAtLeast(int still_to_find,
1808 int recursion_depth,
1809 bool not_at_start) {
1810 return EatsAtLeastHelper(still_to_find,
1811 recursion_depth,
1812 NULL,
1813 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001814}
1815
1816
1817// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1818static inline uint32_t SmearBitsRight(uint32_t v) {
1819 v |= v >> 1;
1820 v |= v >> 2;
1821 v |= v >> 4;
1822 v |= v >> 8;
1823 v |= v >> 16;
1824 return v;
1825}
1826
1827
1828bool QuickCheckDetails::Rationalize(bool asc) {
1829 bool found_useful_op = false;
1830 uint32_t char_mask;
1831 if (asc) {
1832 char_mask = String::kMaxAsciiCharCode;
1833 } else {
1834 char_mask = String::kMaxUC16CharCode;
1835 }
1836 mask_ = 0;
1837 value_ = 0;
1838 int char_shift = 0;
1839 for (int i = 0; i < characters_; i++) {
1840 Position* pos = &positions_[i];
1841 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1842 found_useful_op = true;
1843 }
1844 mask_ |= (pos->mask & char_mask) << char_shift;
1845 value_ |= (pos->value & char_mask) << char_shift;
1846 char_shift += asc ? 8 : 16;
1847 }
1848 return found_useful_op;
1849}
1850
1851
1852bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001853 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001854 bool preload_has_checked_bounds,
1855 Label* on_possible_success,
1856 QuickCheckDetails* details,
1857 bool fall_through_on_failure) {
1858 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001859 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1860 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001861 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001862 ASSERT(details->characters() == 1 ||
1863 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001864 uint32_t mask = details->mask();
1865 uint32_t value = details->value();
1866
1867 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1868
ager@chromium.org32912102009-01-16 10:38:43 +00001869 if (trace->characters_preloaded() != details->characters()) {
1870 assembler->LoadCurrentCharacter(trace->cp_offset(),
1871 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001872 !preload_has_checked_bounds,
1873 details->characters());
1874 }
1875
1876
1877 bool need_mask = true;
1878
1879 if (details->characters() == 1) {
1880 // If number of characters preloaded is 1 then we used a byte or 16 bit
1881 // load so the value is already masked down.
1882 uint32_t char_mask;
1883 if (compiler->ascii()) {
1884 char_mask = String::kMaxAsciiCharCode;
1885 } else {
1886 char_mask = String::kMaxUC16CharCode;
1887 }
1888 if ((mask & char_mask) == char_mask) need_mask = false;
1889 mask &= char_mask;
1890 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001891 // For 2-character preloads in ASCII mode or 1-character preloads in
1892 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001893 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001894 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1895 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001896 if ((mask & 0xffff) == 0xffff) need_mask = false;
1897 } else {
1898 if (mask == 0xffffffff) need_mask = false;
1899 }
1900 }
1901
1902 if (fall_through_on_failure) {
1903 if (need_mask) {
1904 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1905 } else {
1906 assembler->CheckCharacter(value, on_possible_success);
1907 }
1908 } else {
1909 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001910 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001911 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001912 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001913 }
1914 }
1915 return true;
1916}
1917
1918
1919// Here is the meat of GetQuickCheckDetails (see also the comment on the
1920// super-class in the .h file).
1921//
1922// We iterate along the text object, building up for each character a
1923// mask and value that can be used to test for a quick failure to match.
1924// The masks and values for the positions will be combined into a single
1925// machine word for the current character width in order to be used in
1926// generating a quick check.
1927void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1928 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001929 int characters_filled_in,
1930 bool not_at_start) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001931 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001932 ASSERT(characters_filled_in < details->characters());
1933 int characters = details->characters();
1934 int char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001935 if (compiler->ascii()) {
1936 char_mask = String::kMaxAsciiCharCode;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001937 } else {
1938 char_mask = String::kMaxUC16CharCode;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001939 }
1940 for (int k = 0; k < elms_->length(); k++) {
1941 TextElement elm = elms_->at(k);
1942 if (elm.type == TextElement::ATOM) {
1943 Vector<const uc16> quarks = elm.data.u_atom->data();
1944 for (int i = 0; i < characters && i < quarks.length(); i++) {
1945 QuickCheckDetails::Position* pos =
1946 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001947 uc16 c = quarks[i];
1948 if (c > char_mask) {
1949 // If we expect a non-ASCII character from an ASCII string,
1950 // there is no way we can match. Not even case independent
1951 // matching can turn an ASCII character into non-ASCII or
1952 // vice versa.
1953 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001954 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001955 return;
1956 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001957 if (compiler->ignore_case()) {
1958 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001959 int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
1960 chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001961 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1962 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001963 // This letter has no case equivalents, so it's nice and simple
1964 // and the mask-compare will determine definitely whether we have
1965 // a match at this character position.
1966 pos->mask = char_mask;
1967 pos->value = c;
1968 pos->determines_perfectly = true;
1969 } else {
1970 uint32_t common_bits = char_mask;
1971 uint32_t bits = chars[0];
1972 for (int j = 1; j < length; j++) {
1973 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1974 common_bits ^= differing_bits;
1975 bits &= common_bits;
1976 }
1977 // If length is 2 and common bits has only one zero in it then
1978 // our mask and compare instruction will determine definitely
1979 // whether we have a match at this character position. Otherwise
1980 // it can only be an approximate check.
1981 uint32_t one_zero = (common_bits | ~char_mask);
1982 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1983 pos->determines_perfectly = true;
1984 }
1985 pos->mask = common_bits;
1986 pos->value = bits;
1987 }
1988 } else {
1989 // Don't ignore case. Nice simple case where the mask-compare will
1990 // determine definitely whether we have a match at this character
1991 // position.
1992 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001993 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001994 pos->determines_perfectly = true;
1995 }
1996 characters_filled_in++;
1997 ASSERT(characters_filled_in <= details->characters());
1998 if (characters_filled_in == details->characters()) {
1999 return;
2000 }
2001 }
2002 } else {
2003 QuickCheckDetails::Position* pos =
2004 details->positions(characters_filled_in);
2005 RegExpCharacterClass* tree = elm.data.u_char_class;
2006 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002007 if (tree->is_negated()) {
2008 // A quick check uses multi-character mask and compare. There is no
2009 // useful way to incorporate a negative char class into this scheme
2010 // so we just conservatively create a mask and value that will always
2011 // succeed.
2012 pos->mask = 0;
2013 pos->value = 0;
2014 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002015 int first_range = 0;
2016 while (ranges->at(first_range).from() > char_mask) {
2017 first_range++;
2018 if (first_range == ranges->length()) {
2019 details->set_cannot_match();
2020 pos->determines_perfectly = false;
2021 return;
2022 }
2023 }
2024 CharacterRange range = ranges->at(first_range);
2025 uc16 from = range.from();
2026 uc16 to = range.to();
2027 if (to > char_mask) {
2028 to = char_mask;
2029 }
2030 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002031 // A mask and compare is only perfect if the differing bits form a
2032 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002033 if ((differing_bits & (differing_bits + 1)) == 0 &&
2034 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002035 pos->determines_perfectly = true;
2036 }
2037 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002038 uint32_t bits = (from & common_bits);
2039 for (int i = first_range + 1; i < ranges->length(); i++) {
2040 CharacterRange range = ranges->at(i);
2041 uc16 from = range.from();
2042 uc16 to = range.to();
2043 if (from > char_mask) continue;
2044 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002045 // Here we are combining more ranges into the mask and compare
2046 // value. With each new range the mask becomes more sparse and
2047 // so the chances of a false positive rise. A character class
2048 // with multiple ranges is assumed never to be equivalent to a
2049 // mask and compare operation.
2050 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002051 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002052 new_common_bits = ~SmearBitsRight(new_common_bits);
2053 common_bits &= new_common_bits;
2054 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002055 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002056 common_bits ^= differing_bits;
2057 bits &= common_bits;
2058 }
2059 pos->mask = common_bits;
2060 pos->value = bits;
2061 }
2062 characters_filled_in++;
2063 ASSERT(characters_filled_in <= details->characters());
2064 if (characters_filled_in == details->characters()) {
2065 return;
2066 }
2067 }
2068 }
2069 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00002070 on_success()-> GetQuickCheckDetails(details,
2071 compiler,
2072 characters_filled_in,
2073 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002074}
2075
2076
2077void QuickCheckDetails::Clear() {
2078 for (int i = 0; i < characters_; i++) {
2079 positions_[i].mask = 0;
2080 positions_[i].value = 0;
2081 positions_[i].determines_perfectly = false;
2082 }
2083 characters_ = 0;
2084}
2085
2086
2087void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002088 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002089 if (by >= characters_) {
2090 Clear();
2091 return;
2092 }
2093 for (int i = 0; i < characters_ - by; i++) {
2094 positions_[i] = positions_[by + i];
2095 }
2096 for (int i = characters_ - by; i < characters_; i++) {
2097 positions_[i].mask = 0;
2098 positions_[i].value = 0;
2099 positions_[i].determines_perfectly = false;
2100 }
2101 characters_ -= by;
2102 // We could change mask_ and value_ here but we would never advance unless
2103 // they had already been used in a check and they won't be used again because
2104 // it would gain us nothing. So there's no point.
2105}
2106
2107
2108void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2109 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002110 if (other->cannot_match_) {
2111 return;
2112 }
2113 if (cannot_match_) {
2114 *this = *other;
2115 return;
2116 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002117 for (int i = from_index; i < characters_; i++) {
2118 QuickCheckDetails::Position* pos = positions(i);
2119 QuickCheckDetails::Position* other_pos = other->positions(i);
2120 if (pos->mask != other_pos->mask ||
2121 pos->value != other_pos->value ||
2122 !other_pos->determines_perfectly) {
2123 // Our mask-compare operation will be approximate unless we have the
2124 // exact same operation on both sides of the alternation.
2125 pos->determines_perfectly = false;
2126 }
2127 pos->mask &= other_pos->mask;
2128 pos->value &= pos->mask;
2129 other_pos->value &= pos->mask;
2130 uc16 differing_bits = (pos->value ^ other_pos->value);
2131 pos->mask &= ~differing_bits;
2132 pos->value &= pos->mask;
2133 }
2134}
2135
2136
ager@chromium.org32912102009-01-16 10:38:43 +00002137class VisitMarker {
2138 public:
2139 explicit VisitMarker(NodeInfo* info) : info_(info) {
2140 ASSERT(!info->visited);
2141 info->visited = true;
2142 }
2143 ~VisitMarker() {
2144 info_->visited = false;
2145 }
2146 private:
2147 NodeInfo* info_;
2148};
2149
2150
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002151void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2152 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002153 int characters_filled_in,
2154 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002155 if (body_can_be_zero_length_ || info()->visited) return;
2156 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002157 return ChoiceNode::GetQuickCheckDetails(details,
2158 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002159 characters_filled_in,
2160 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002161}
2162
2163
2164void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2165 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002166 int characters_filled_in,
2167 bool not_at_start) {
2168 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002169 int choice_count = alternatives_->length();
2170 ASSERT(choice_count > 0);
2171 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2172 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002173 characters_filled_in,
2174 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002175 for (int i = 1; i < choice_count; i++) {
2176 QuickCheckDetails new_details(details->characters());
2177 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002178 node->GetQuickCheckDetails(&new_details, compiler,
2179 characters_filled_in,
2180 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002181 // Here we merge the quick match details of the two branches.
2182 details->Merge(&new_details, characters_filled_in);
2183 }
2184}
2185
2186
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002187// Check for [0-9A-Z_a-z].
2188static void EmitWordCheck(RegExpMacroAssembler* assembler,
2189 Label* word,
2190 Label* non_word,
2191 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002192 if (assembler->CheckSpecialCharacterClass(
2193 fall_through_on_word ? 'w' : 'W',
2194 fall_through_on_word ? non_word : word)) {
2195 // Optimized implementation available.
2196 return;
2197 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002198 assembler->CheckCharacterGT('z', non_word);
2199 assembler->CheckCharacterLT('0', non_word);
2200 assembler->CheckCharacterGT('a' - 1, word);
2201 assembler->CheckCharacterLT('9' + 1, word);
2202 assembler->CheckCharacterLT('A', non_word);
2203 assembler->CheckCharacterLT('Z' + 1, word);
2204 if (fall_through_on_word) {
2205 assembler->CheckNotCharacter('_', non_word);
2206 } else {
2207 assembler->CheckCharacter('_', word);
2208 }
2209}
2210
2211
2212// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2213// that matches newline or the start of input).
2214static void EmitHat(RegExpCompiler* compiler,
2215 RegExpNode* on_success,
2216 Trace* trace) {
2217 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2218 // We will be loading the previous character into the current character
2219 // register.
2220 Trace new_trace(*trace);
2221 new_trace.InvalidateCurrentCharacter();
2222
2223 Label ok;
2224 if (new_trace.cp_offset() == 0) {
2225 // The start of input counts as a newline in this context, so skip to
2226 // ok if we are at the start.
2227 assembler->CheckAtStart(&ok);
2228 }
2229 // We already checked that we are not at the start of input so it must be
2230 // OK to load the previous character.
2231 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2232 new_trace.backtrack(),
2233 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002234 if (!assembler->CheckSpecialCharacterClass('n',
2235 new_trace.backtrack())) {
2236 // Newline means \n, \r, 0x2028 or 0x2029.
2237 if (!compiler->ascii()) {
2238 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2239 }
2240 assembler->CheckCharacter('\n', &ok);
2241 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002242 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002243 assembler->Bind(&ok);
2244 on_success->Emit(compiler, &new_trace);
2245}
2246
2247
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002248// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2249// when we know whether the next character must be a word character or not.
2250static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2251 RegExpCompiler* compiler,
2252 RegExpNode* on_success,
2253 Trace* trace) {
2254 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2255 Label done;
2256
2257 Trace new_trace(*trace);
2258
2259 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2260 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2261 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2262
2263 // Check whether previous character was a word character.
2264 switch (trace->at_start()) {
2265 case Trace::TRUE:
2266 if (expect_word_character) {
2267 assembler->GoTo(on_non_word);
2268 }
2269 break;
2270 case Trace::UNKNOWN:
2271 ASSERT_EQ(0, trace->cp_offset());
2272 assembler->CheckAtStart(on_non_word);
2273 // Fall through.
2274 case Trace::FALSE:
2275 int prev_char_offset = trace->cp_offset() - 1;
2276 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2277 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2278 // We may or may not have loaded the previous character.
2279 new_trace.InvalidateCurrentCharacter();
2280 }
2281
2282 assembler->Bind(&done);
2283
2284 on_success->Emit(compiler, &new_trace);
2285}
2286
2287
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002288// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2289static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2290 RegExpCompiler* compiler,
2291 RegExpNode* on_success,
2292 Trace* trace) {
2293 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2294 Label before_non_word;
2295 Label before_word;
2296 if (trace->characters_preloaded() != 1) {
2297 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2298 }
2299 // Fall through on non-word.
2300 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2301
2302 // We will be loading the previous character into the current character
2303 // register.
2304 Trace new_trace(*trace);
2305 new_trace.InvalidateCurrentCharacter();
2306
2307 Label ok;
2308 Label* boundary;
2309 Label* not_boundary;
2310 if (type == AssertionNode::AT_BOUNDARY) {
2311 boundary = &ok;
2312 not_boundary = new_trace.backtrack();
2313 } else {
2314 not_boundary = &ok;
2315 boundary = new_trace.backtrack();
2316 }
2317
2318 // Next character is not a word character.
2319 assembler->Bind(&before_non_word);
2320 if (new_trace.cp_offset() == 0) {
2321 // The start of input counts as a non-word character, so the question is
2322 // decided if we are at the start.
2323 assembler->CheckAtStart(not_boundary);
2324 }
2325 // We already checked that we are not at the start of input so it must be
2326 // OK to load the previous character.
2327 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2328 &ok, // Unused dummy label in this call.
2329 false);
2330 // Fall through on non-word.
2331 EmitWordCheck(assembler, boundary, not_boundary, false);
2332 assembler->GoTo(not_boundary);
2333
2334 // Next character is a word character.
2335 assembler->Bind(&before_word);
2336 if (new_trace.cp_offset() == 0) {
2337 // The start of input counts as a non-word character, so the question is
2338 // decided if we are at the start.
2339 assembler->CheckAtStart(boundary);
2340 }
2341 // We already checked that we are not at the start of input so it must be
2342 // OK to load the previous character.
2343 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2344 &ok, // Unused dummy label in this call.
2345 false);
2346 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2347 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2348
2349 assembler->Bind(&ok);
2350
2351 on_success->Emit(compiler, &new_trace);
2352}
2353
2354
iposva@chromium.org245aa852009-02-10 00:49:54 +00002355void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2356 RegExpCompiler* compiler,
2357 int filled_in,
2358 bool not_at_start) {
2359 if (type_ == AT_START && not_at_start) {
2360 details->set_cannot_match();
2361 return;
2362 }
2363 return on_success()->GetQuickCheckDetails(details,
2364 compiler,
2365 filled_in,
2366 not_at_start);
2367}
2368
2369
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002370void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2371 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2372 switch (type_) {
2373 case AT_END: {
2374 Label ok;
2375 assembler->CheckPosition(trace->cp_offset(), &ok);
2376 assembler->GoTo(trace->backtrack());
2377 assembler->Bind(&ok);
2378 break;
2379 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002380 case AT_START: {
2381 if (trace->at_start() == Trace::FALSE) {
2382 assembler->GoTo(trace->backtrack());
2383 return;
2384 }
2385 if (trace->at_start() == Trace::UNKNOWN) {
2386 assembler->CheckNotAtStart(trace->backtrack());
2387 Trace at_start_trace = *trace;
2388 at_start_trace.set_at_start(true);
2389 on_success()->Emit(compiler, &at_start_trace);
2390 return;
2391 }
2392 }
2393 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002394 case AFTER_NEWLINE:
2395 EmitHat(compiler, on_success(), trace);
2396 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002397 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002398 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002399 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2400 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002401 }
2402 case AFTER_WORD_CHARACTER:
2403 case AFTER_NONWORD_CHARACTER: {
2404 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2405 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002406 }
2407 on_success()->Emit(compiler, trace);
2408}
2409
2410
ager@chromium.org381abbb2009-02-25 13:23:22 +00002411static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2412 if (quick_check == NULL) return false;
2413 if (offset >= quick_check->characters()) return false;
2414 return quick_check->positions(offset)->determines_perfectly;
2415}
2416
2417
2418static void UpdateBoundsCheck(int index, int* checked_up_to) {
2419 if (index > *checked_up_to) {
2420 *checked_up_to = index;
2421 }
2422}
2423
2424
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002425// We call this repeatedly to generate code for each pass over the text node.
2426// The passes are in increasing order of difficulty because we hope one
2427// of the first passes will fail in which case we are saved the work of the
2428// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2429// we will check the '%' in the first pass, the case independent 'a' in the
2430// second pass and the character class in the last pass.
2431//
2432// The passes are done from right to left, so for example to test for /bar/
2433// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2434// and then a 'b' with offset 0. This means we can avoid the end-of-input
2435// bounds check most of the time. In the example we only need to check for
2436// end-of-input when loading the putative 'r'.
2437//
2438// A slight complication involves the fact that the first character may already
2439// be fetched into a register by the previous node. In this case we want to
2440// do the test for that character first. We do this in separate passes. The
2441// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2442// pass has been performed then subsequent passes will have true in
2443// first_element_checked to indicate that that character does not need to be
2444// checked again.
2445//
ager@chromium.org32912102009-01-16 10:38:43 +00002446// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002447// contain an AlternativeGeneration object. In this AlternativeGeneration
2448// object we can see details of any quick check that was already passed in
2449// order to get to the code we are now generating. The quick check can involve
2450// loading characters, which means we do not need to recheck the bounds
2451// up to the limit the quick check already checked. In addition the quick
2452// check can have involved a mask and compare operation which may simplify
2453// or obviate the need for further checks at some character positions.
2454void TextNode::TextEmitPass(RegExpCompiler* compiler,
2455 TextEmitPassType pass,
2456 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002457 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002458 bool first_element_checked,
2459 int* checked_up_to) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002460 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002461 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2462 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002463 Label* backtrack = trace->backtrack();
2464 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002465 int element_count = elms_->length();
2466 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2467 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002468 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002469 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002470 Vector<const uc16> quarks = elm.data.u_atom->data();
2471 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2472 if (first_element_checked && i == 0 && j == 0) continue;
2473 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2474 EmitCharacterFunction* emit_function = NULL;
2475 switch (pass) {
2476 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002477 ASSERT(ascii);
2478 if (quarks[j] > String::kMaxAsciiCharCode) {
2479 assembler->GoTo(backtrack);
2480 return;
2481 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002482 break;
2483 case NON_LETTER_CHARACTER_MATCH:
2484 emit_function = &EmitAtomNonLetter;
2485 break;
2486 case SIMPLE_CHARACTER_MATCH:
2487 emit_function = &EmitSimpleCharacter;
2488 break;
2489 case CASE_CHARACTER_MATCH:
2490 emit_function = &EmitAtomLetter;
2491 break;
2492 default:
2493 break;
2494 }
2495 if (emit_function != NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002496 bool bound_checked = emit_function(isolate,
2497 compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002498 quarks[j],
2499 backtrack,
2500 cp_offset + j,
2501 *checked_up_to < cp_offset + j,
2502 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002503 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002504 }
2505 }
2506 } else {
2507 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002508 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002509 if (first_element_checked && i == 0) continue;
2510 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002511 RegExpCharacterClass* cc = elm.data.u_char_class;
2512 EmitCharClass(assembler,
2513 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002514 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002515 backtrack,
2516 cp_offset,
2517 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002518 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002519 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002520 }
2521 }
2522 }
2523}
2524
2525
2526int TextNode::Length() {
2527 TextElement elm = elms_->last();
2528 ASSERT(elm.cp_offset >= 0);
2529 if (elm.type == TextElement::ATOM) {
2530 return elm.cp_offset + elm.data.u_atom->data().length();
2531 } else {
2532 return elm.cp_offset + 1;
2533 }
2534}
2535
2536
ager@chromium.org381abbb2009-02-25 13:23:22 +00002537bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2538 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2539 if (ignore_case) {
2540 return pass == SIMPLE_CHARACTER_MATCH;
2541 } else {
2542 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2543 }
2544}
2545
2546
ager@chromium.org8bb60582008-12-11 12:02:20 +00002547// This generates the code to match a text node. A text node can contain
2548// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002549// way) and character classes. For efficiency we do not do this in a single
2550// pass from left to right. Instead we pass over the text node several times,
2551// emitting code for some character positions every time. See the comment on
2552// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002553void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002554 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002555 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002556 ASSERT(limit_result == CONTINUE);
2557
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002558 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2559 compiler->SetRegExpTooBig();
2560 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002561 }
2562
2563 if (compiler->ascii()) {
2564 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002565 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002566 }
2567
2568 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002569 int bound_checked_to = trace->cp_offset() - 1;
2570 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002571
2572 // If a character is preloaded into the current character register then
2573 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002574 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002575 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2576 if (!SkipPass(pass, compiler->ignore_case())) {
2577 TextEmitPass(compiler,
2578 static_cast<TextEmitPassType>(pass),
2579 true,
2580 trace,
2581 false,
2582 &bound_checked_to);
2583 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002584 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002585 first_elt_done = true;
2586 }
2587
ager@chromium.org381abbb2009-02-25 13:23:22 +00002588 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2589 if (!SkipPass(pass, compiler->ignore_case())) {
2590 TextEmitPass(compiler,
2591 static_cast<TextEmitPassType>(pass),
2592 false,
2593 trace,
2594 first_elt_done,
2595 &bound_checked_to);
2596 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002597 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002598
ager@chromium.org32912102009-01-16 10:38:43 +00002599 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002600 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002601 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002602 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002603 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002604}
2605
2606
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002607void Trace::InvalidateCurrentCharacter() {
2608 characters_preloaded_ = 0;
2609}
2610
2611
2612void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002613 ASSERT(by > 0);
2614 // We don't have an instruction for shifting the current character register
2615 // down or for using a shifted value for anything so lets just forget that
2616 // we preloaded any characters into it.
2617 characters_preloaded_ = 0;
2618 // Adjust the offsets of the quick check performed information. This
2619 // information is used to find out what we already determined about the
2620 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002621 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002622 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002623 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2624 compiler->SetRegExpTooBig();
2625 cp_offset_ = 0;
2626 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002627 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002628}
2629
2630
ager@chromium.org38e4c712009-11-11 09:11:58 +00002631void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002632 int element_count = elms_->length();
2633 for (int i = 0; i < element_count; i++) {
2634 TextElement elm = elms_->at(i);
2635 if (elm.type == TextElement::CHAR_CLASS) {
2636 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002637 // None of the standard character classses is different in the case
2638 // independent case and it slows us down if we don't know that.
2639 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002640 ZoneList<CharacterRange>* ranges = cc->ranges();
2641 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002642 for (int j = 0; j < range_count; j++) {
2643 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002644 }
2645 }
2646 }
2647}
2648
2649
ager@chromium.org8bb60582008-12-11 12:02:20 +00002650int TextNode::GreedyLoopTextLength() {
2651 TextElement elm = elms_->at(elms_->length() - 1);
2652 if (elm.type == TextElement::CHAR_CLASS) {
2653 return elm.cp_offset + 1;
2654 } else {
2655 return elm.cp_offset + elm.data.u_atom->data().length();
2656 }
2657}
2658
2659
2660// Finds the fixed match length of a sequence of nodes that goes from
2661// this alternative and back to this choice node. If there are variable
2662// length nodes or other complications in the way then return a sentinel
2663// value indicating that a greedy loop cannot be constructed.
jkummerow@chromium.org486075a2011-09-07 12:44:28 +00002664int ChoiceNode::GreedyLoopTextLengthForAlternative(
2665 GuardedAlternative* alternative) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002666 int length = 0;
2667 RegExpNode* node = alternative->node();
2668 // Later we will generate code for all these text nodes using recursion
2669 // so we have to limit the max number.
2670 int recursion_depth = 0;
2671 while (node != this) {
2672 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2673 return kNodeIsTooComplexForGreedyLoops;
2674 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002675 int node_length = node->GreedyLoopTextLength();
2676 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2677 return kNodeIsTooComplexForGreedyLoops;
2678 }
2679 length += node_length;
2680 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2681 node = seq_node->on_success();
2682 }
2683 return length;
2684}
2685
2686
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002687void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2688 ASSERT_EQ(loop_node_, NULL);
2689 AddAlternative(alt);
2690 loop_node_ = alt.node();
2691}
2692
2693
2694void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2695 ASSERT_EQ(continue_node_, NULL);
2696 AddAlternative(alt);
2697 continue_node_ = alt.node();
2698}
2699
2700
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002701void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002702 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002703 if (trace->stop_node() == this) {
jkummerow@chromium.org486075a2011-09-07 12:44:28 +00002704 int text_length =
2705 GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
ager@chromium.org8bb60582008-12-11 12:02:20 +00002706 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2707 // Update the counter-based backtracking info on the stack. This is an
2708 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002709 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002710 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002711 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002712 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002713 }
ager@chromium.org32912102009-01-16 10:38:43 +00002714 ASSERT(trace->stop_node() == NULL);
2715 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002716 trace->Flush(compiler, this);
2717 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002718 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002719 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002720}
2721
2722
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002723int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
2724 bool not_at_start) {
2725 int preload_characters = EatsAtLeast(4, 0, not_at_start);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002726 if (compiler->macro_assembler()->CanReadUnaligned()) {
2727 bool ascii = compiler->ascii();
2728 if (ascii) {
2729 if (preload_characters > 4) preload_characters = 4;
2730 // We can't preload 3 characters because there is no machine instruction
2731 // to do that. We can't just load 4 because we could be reading
2732 // beyond the end of the string, which could cause a memory fault.
2733 if (preload_characters == 3) preload_characters = 2;
2734 } else {
2735 if (preload_characters > 2) preload_characters = 2;
2736 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002737 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002738 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002739 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002740 return preload_characters;
2741}
2742
2743
2744// This class is used when generating the alternatives in a choice node. It
2745// records the way the alternative is being code generated.
2746class AlternativeGeneration: public Malloced {
2747 public:
2748 AlternativeGeneration()
2749 : possible_success(),
2750 expects_preload(false),
2751 after(),
2752 quick_check_details() { }
2753 Label possible_success;
2754 bool expects_preload;
2755 Label after;
2756 QuickCheckDetails quick_check_details;
2757};
2758
2759
2760// Creates a list of AlternativeGenerations. If the list has a reasonable
2761// size then it is on the stack, otherwise the excess is on the heap.
2762class AlternativeGenerationList {
2763 public:
2764 explicit AlternativeGenerationList(int count)
2765 : alt_gens_(count) {
2766 for (int i = 0; i < count && i < kAFew; i++) {
2767 alt_gens_.Add(a_few_alt_gens_ + i);
2768 }
2769 for (int i = kAFew; i < count; i++) {
2770 alt_gens_.Add(new AlternativeGeneration());
2771 }
2772 }
2773 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002774 for (int i = kAFew; i < alt_gens_.length(); i++) {
2775 delete alt_gens_[i];
2776 alt_gens_[i] = NULL;
2777 }
2778 }
2779
2780 AlternativeGeneration* at(int i) {
2781 return alt_gens_[i];
2782 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00002783
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002784 private:
2785 static const int kAFew = 10;
2786 ZoneList<AlternativeGeneration*> alt_gens_;
2787 AlternativeGeneration a_few_alt_gens_[kAFew];
2788};
2789
2790
2791/* Code generation for choice nodes.
2792 *
2793 * We generate quick checks that do a mask and compare to eliminate a
2794 * choice. If the quick check succeeds then it jumps to the continuation to
2795 * do slow checks and check subsequent nodes. If it fails (the common case)
2796 * it falls through to the next choice.
2797 *
2798 * Here is the desired flow graph. Nodes directly below each other imply
2799 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2800 * 3 doesn't have a quick check so we have to call the slow check.
2801 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2802 * regexp continuation is generated directly after the Sn node, up to the
2803 * next GoTo if we decide to reuse some already generated code. Some
2804 * nodes expect preload_characters to be preloaded into the current
2805 * character register. R nodes do this preloading. Vertices are marked
2806 * F for failures and S for success (possible success in the case of quick
2807 * nodes). L, V, < and > are used as arrow heads.
2808 *
2809 * ----------> R
2810 * |
2811 * V
2812 * Q1 -----> S1
2813 * | S /
2814 * F| /
2815 * | F/
2816 * | /
2817 * | R
2818 * | /
2819 * V L
2820 * Q2 -----> S2
2821 * | S /
2822 * F| /
2823 * | F/
2824 * | /
2825 * | R
2826 * | /
2827 * V L
2828 * S3
2829 * |
2830 * F|
2831 * |
2832 * R
2833 * |
2834 * backtrack V
2835 * <----------Q4
2836 * \ F |
2837 * \ |S
2838 * \ F V
2839 * \-----S4
2840 *
2841 * For greedy loops we reverse our expectation and expect to match rather
2842 * than fail. Therefore we want the loop code to look like this (U is the
2843 * unwind code that steps back in the greedy loop). The following alternatives
2844 * look the same as above.
2845 * _____
2846 * / \
2847 * V |
2848 * ----------> S1 |
2849 * /| |
2850 * / |S |
2851 * F/ \_____/
2852 * /
2853 * |<-----------
2854 * | \
2855 * V \
2856 * Q2 ---> S2 \
2857 * | S / |
2858 * F| / |
2859 * | F/ |
2860 * | / |
2861 * | R |
2862 * | / |
2863 * F VL |
2864 * <------U |
2865 * back |S |
2866 * \______________/
2867 */
2868
2869
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002870void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002871 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2872 int choice_count = alternatives_->length();
2873#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002874 for (int i = 0; i < choice_count - 1; i++) {
2875 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002876 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002877 int guard_count = (guards == NULL) ? 0 : guards->length();
2878 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002879 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002880 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002881 }
2882#endif
2883
ager@chromium.org32912102009-01-16 10:38:43 +00002884 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002885 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002886 ASSERT(limit_result == CONTINUE);
2887
ager@chromium.org381abbb2009-02-25 13:23:22 +00002888 int new_flush_budget = trace->flush_budget() / choice_count;
2889 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2890 trace->Flush(compiler, this);
2891 return;
2892 }
2893
ager@chromium.org8bb60582008-12-11 12:02:20 +00002894 RecursionCheck rc(compiler);
2895
ager@chromium.org32912102009-01-16 10:38:43 +00002896 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002897
jkummerow@chromium.org486075a2011-09-07 12:44:28 +00002898 int text_length = GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
ager@chromium.org8bb60582008-12-11 12:02:20 +00002899 bool greedy_loop = false;
2900 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002901 Trace counter_backtrack_trace;
2902 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002903 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2904
ager@chromium.org8bb60582008-12-11 12:02:20 +00002905 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2906 // Here we have special handling for greedy loops containing only text nodes
2907 // and other simple nodes. These are handled by pushing the current
2908 // position on the stack and then incrementing the current position each
2909 // time around the switch. On backtrack we decrement the current position
2910 // and check it against the pushed value. This avoids pushing backtrack
2911 // information for each iteration of the loop, which could take up a lot of
2912 // space.
2913 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002914 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002915 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002916 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002917 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002918 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002919 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002920 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002921 Label loop_label;
2922 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002923 greedy_match_trace.set_stop_node(this);
2924 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002925 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002926 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002927 }
2928
2929 Label second_choice; // For use in greedy matches.
2930 macro_assembler->Bind(&second_choice);
2931
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002932 int first_normal_choice = greedy_loop ? 1 : 0;
2933
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002934 int preload_characters =
2935 CalculatePreloadCharacters(compiler,
2936 current_trace->at_start() == Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002937 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002938 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002939 bool preload_has_checked_bounds = preload_is_current;
2940
2941 AlternativeGenerationList alt_gens(choice_count);
2942
ager@chromium.org8bb60582008-12-11 12:02:20 +00002943 // For now we just call all choices one after the other. The idea ultimately
2944 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002945 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002946 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002947 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002948 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002949 ZoneList<Guard*>* guards = alternative.guards();
2950 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002951 Trace new_trace(*current_trace);
2952 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002953 preload_characters :
2954 0);
2955 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002956 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002957 }
ager@chromium.org32912102009-01-16 10:38:43 +00002958 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002959 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002960 alt_gen->expects_preload = preload_is_current;
2961 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002962 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002963 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002964 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002965 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002966 preload_has_checked_bounds,
2967 &alt_gen->possible_success,
2968 &alt_gen->quick_check_details,
2969 i < choice_count - 1)) {
2970 // Quick check was generated for this choice.
2971 preload_is_current = true;
2972 preload_has_checked_bounds = true;
2973 // On the last choice in the ChoiceNode we generated the quick
2974 // check to fall through on possible success. So now we need to
2975 // generate the full check inline.
2976 if (i == choice_count - 1) {
2977 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002978 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2979 new_trace.set_characters_preloaded(preload_characters);
2980 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002981 generate_full_check_inline = true;
2982 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002983 } else if (alt_gen->quick_check_details.cannot_match()) {
2984 if (i == choice_count - 1 && !greedy_loop) {
2985 macro_assembler->GoTo(trace->backtrack());
2986 }
2987 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002988 } else {
2989 // No quick check was generated. Put the full code here.
2990 // If this is not the first choice then there could be slow checks from
2991 // previous cases that go here when they fail. There's no reason to
2992 // insist that they preload characters since the slow check we are about
2993 // to generate probably can't use it.
2994 if (i != first_normal_choice) {
2995 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002996 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002997 }
2998 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002999 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003000 }
3001 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003002 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003003 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00003004 if (new_trace.actions() != NULL) {
3005 new_trace.set_flush_budget(new_flush_budget);
3006 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003007 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003008 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003009 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003010 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003011 preload_is_current = false;
3012 }
3013 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003014 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003015 if (greedy_loop) {
3016 macro_assembler->Bind(&greedy_loop_label);
3017 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00003018 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00003019 // Otherwise try the second priority at an earlier position.
3020 macro_assembler->AdvanceCurrentPosition(-text_length);
3021 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003022 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00003023
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003024 // At this point we need to generate slow checks for the alternatives where
3025 // the quick check was inlined. We can recognize these because the associated
3026 // label was bound.
3027 for (int i = first_normal_choice; i < choice_count - 1; i++) {
3028 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00003029 Trace new_trace(*current_trace);
3030 // If there are actions to be flushed we have to limit how many times
3031 // they are flushed. Take the budget of the parent trace and distribute
3032 // it fairly amongst the children.
3033 if (new_trace.actions() != NULL) {
3034 new_trace.set_flush_budget(new_flush_budget);
3035 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003036 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00003037 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003038 alternatives_->at(i),
3039 alt_gen,
3040 preload_characters,
3041 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003042 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003043}
3044
3045
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003046void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00003047 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003048 GuardedAlternative alternative,
3049 AlternativeGeneration* alt_gen,
3050 int preload_characters,
3051 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003052 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003053
3054 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3055 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00003056 Trace out_of_line_trace(*trace);
3057 out_of_line_trace.set_characters_preloaded(preload_characters);
3058 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003059 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003060 ZoneList<Guard*>* guards = alternative.guards();
3061 int guard_count = (guards == NULL) ? 0 : guards->length();
3062 if (next_expects_preload) {
3063 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00003064 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003065 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003066 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003067 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003068 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003069 macro_assembler->Bind(&reload_current_char);
3070 // Reload the current character, since the next quick check expects that.
3071 // We don't need to check bounds here because we only get into this
3072 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00003073 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003074 NULL,
3075 false,
3076 preload_characters);
3077 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003078 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00003079 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003080 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003081 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003082 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003083 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003084 }
3085}
3086
3087
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003088void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003089 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003090 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003091 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003092 ASSERT(limit_result == CONTINUE);
3093
3094 RecursionCheck rc(compiler);
3095
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003096 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003097 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00003098 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003099 new_capture(data_.u_position_register.reg,
3100 data_.u_position_register.is_capture,
3101 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003102 Trace new_trace = *trace;
3103 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003104 on_success()->Emit(compiler, &new_trace);
3105 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003106 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003107 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003108 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003109 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00003110 Trace new_trace = *trace;
3111 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003112 on_success()->Emit(compiler, &new_trace);
3113 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003114 }
3115 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003116 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003117 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00003118 Trace new_trace = *trace;
3119 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003120 on_success()->Emit(compiler, &new_trace);
3121 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003122 }
3123 case CLEAR_CAPTURES: {
3124 Trace::DeferredClearCaptures
3125 new_capture(Interval(data_.u_clear_captures.range_from,
3126 data_.u_clear_captures.range_to));
3127 Trace new_trace = *trace;
3128 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003129 on_success()->Emit(compiler, &new_trace);
3130 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003131 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003132 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003133 if (!trace->is_trivial()) {
3134 trace->Flush(compiler, this);
3135 } else {
3136 assembler->WriteCurrentPositionToRegister(
3137 data_.u_submatch.current_position_register, 0);
3138 assembler->WriteStackPointerToRegister(
3139 data_.u_submatch.stack_pointer_register);
3140 on_success()->Emit(compiler, trace);
3141 }
3142 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003143 case EMPTY_MATCH_CHECK: {
3144 int start_pos_reg = data_.u_empty_match_check.start_register;
3145 int stored_pos = 0;
3146 int rep_reg = data_.u_empty_match_check.repetition_register;
3147 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3148 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3149 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3150 // If we know we haven't advanced and there is no minimum we
3151 // can just backtrack immediately.
3152 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003153 } else if (know_dist && stored_pos < trace->cp_offset()) {
3154 // If we know we've advanced we can generate the continuation
3155 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003156 on_success()->Emit(compiler, trace);
3157 } else if (!trace->is_trivial()) {
3158 trace->Flush(compiler, this);
3159 } else {
3160 Label skip_empty_check;
3161 // If we have a minimum number of repetitions we check the current
3162 // number first and skip the empty check if it's not enough.
3163 if (has_minimum) {
3164 int limit = data_.u_empty_match_check.repetition_limit;
3165 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3166 }
3167 // If the match is empty we bail out, otherwise we fall through
3168 // to the on-success continuation.
3169 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3170 trace->backtrack());
3171 assembler->Bind(&skip_empty_check);
3172 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003173 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003174 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003175 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003176 case POSITIVE_SUBMATCH_SUCCESS: {
3177 if (!trace->is_trivial()) {
3178 trace->Flush(compiler, this);
3179 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003180 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003181 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003182 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003183 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003184 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003185 int clear_register_count = data_.u_submatch.clear_register_count;
3186 if (clear_register_count == 0) {
3187 on_success()->Emit(compiler, trace);
3188 return;
3189 }
3190 int clear_registers_from = data_.u_submatch.clear_register_from;
3191 Label clear_registers_backtrack;
3192 Trace new_trace = *trace;
3193 new_trace.set_backtrack(&clear_registers_backtrack);
3194 on_success()->Emit(compiler, &new_trace);
3195
3196 assembler->Bind(&clear_registers_backtrack);
3197 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3198 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3199
3200 ASSERT(trace->backtrack() == NULL);
3201 assembler->Backtrack();
3202 return;
3203 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003204 default:
3205 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003206 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003207}
3208
3209
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003210void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003211 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003212 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003213 trace->Flush(compiler, this);
3214 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003215 }
3216
ager@chromium.org32912102009-01-16 10:38:43 +00003217 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003218 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003219 ASSERT(limit_result == CONTINUE);
3220
3221 RecursionCheck rc(compiler);
3222
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003223 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003224 if (compiler->ignore_case()) {
3225 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3226 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003227 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003228 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003229 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003230 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003231}
3232
3233
3234// -------------------------------------------------------------------
3235// Dot/dotty output
3236
3237
3238#ifdef DEBUG
3239
3240
3241class DotPrinter: public NodeVisitor {
3242 public:
3243 explicit DotPrinter(bool ignore_case)
3244 : ignore_case_(ignore_case),
3245 stream_(&alloc_) { }
3246 void PrintNode(const char* label, RegExpNode* node);
3247 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003248 void PrintAttributes(RegExpNode* from);
3249 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003250 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003251#define DECLARE_VISIT(Type) \
3252 virtual void Visit##Type(Type##Node* that);
3253FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3254#undef DECLARE_VISIT
3255 private:
3256 bool ignore_case_;
3257 HeapStringAllocator alloc_;
3258 StringStream stream_;
3259};
3260
3261
3262void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3263 stream()->Add("digraph G {\n graph [label=\"");
3264 for (int i = 0; label[i]; i++) {
3265 switch (label[i]) {
3266 case '\\':
3267 stream()->Add("\\\\");
3268 break;
3269 case '"':
3270 stream()->Add("\"");
3271 break;
3272 default:
3273 stream()->Put(label[i]);
3274 break;
3275 }
3276 }
3277 stream()->Add("\"];\n");
3278 Visit(node);
3279 stream()->Add("}\n");
3280 printf("%s", *(stream()->ToCString()));
3281}
3282
3283
3284void DotPrinter::Visit(RegExpNode* node) {
3285 if (node->info()->visited) return;
3286 node->info()->visited = true;
3287 node->Accept(this);
3288}
3289
3290
3291void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003292 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3293 Visit(on_failure);
3294}
3295
3296
3297class TableEntryBodyPrinter {
3298 public:
3299 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3300 : stream_(stream), choice_(choice) { }
3301 void Call(uc16 from, DispatchTable::Entry entry) {
3302 OutSet* out_set = entry.out_set();
3303 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3304 if (out_set->Get(i)) {
3305 stream()->Add(" n%p:s%io%i -> n%p;\n",
3306 choice(),
3307 from,
3308 i,
3309 choice()->alternatives()->at(i).node());
3310 }
3311 }
3312 }
3313 private:
3314 StringStream* stream() { return stream_; }
3315 ChoiceNode* choice() { return choice_; }
3316 StringStream* stream_;
3317 ChoiceNode* choice_;
3318};
3319
3320
3321class TableEntryHeaderPrinter {
3322 public:
3323 explicit TableEntryHeaderPrinter(StringStream* stream)
3324 : first_(true), stream_(stream) { }
3325 void Call(uc16 from, DispatchTable::Entry entry) {
3326 if (first_) {
3327 first_ = false;
3328 } else {
3329 stream()->Add("|");
3330 }
3331 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3332 OutSet* out_set = entry.out_set();
3333 int priority = 0;
3334 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3335 if (out_set->Get(i)) {
3336 if (priority > 0) stream()->Add("|");
3337 stream()->Add("<s%io%i> %i", from, i, priority);
3338 priority++;
3339 }
3340 }
3341 stream()->Add("}}");
3342 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00003343
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003344 private:
3345 bool first_;
3346 StringStream* stream() { return stream_; }
3347 StringStream* stream_;
3348};
3349
3350
3351class AttributePrinter {
3352 public:
3353 explicit AttributePrinter(DotPrinter* out)
3354 : out_(out), first_(true) { }
3355 void PrintSeparator() {
3356 if (first_) {
3357 first_ = false;
3358 } else {
3359 out_->stream()->Add("|");
3360 }
3361 }
3362 void PrintBit(const char* name, bool value) {
3363 if (!value) return;
3364 PrintSeparator();
3365 out_->stream()->Add("{%s}", name);
3366 }
3367 void PrintPositive(const char* name, int value) {
3368 if (value < 0) return;
3369 PrintSeparator();
3370 out_->stream()->Add("{%s|%x}", name, value);
3371 }
3372 private:
3373 DotPrinter* out_;
3374 bool first_;
3375};
3376
3377
3378void DotPrinter::PrintAttributes(RegExpNode* that) {
3379 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3380 "margin=0.1, fontsize=10, label=\"{",
3381 that);
3382 AttributePrinter printer(this);
3383 NodeInfo* info = that->info();
3384 printer.PrintBit("NI", info->follows_newline_interest);
3385 printer.PrintBit("WI", info->follows_word_interest);
3386 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003387 Label* label = that->label();
3388 if (label->is_bound())
3389 printer.PrintPositive("@", label->pos());
3390 stream()->Add("}\"];\n");
3391 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3392 "arrowhead=none];\n", that, that);
3393}
3394
3395
3396static const bool kPrintDispatchTable = false;
3397void DotPrinter::VisitChoice(ChoiceNode* that) {
3398 if (kPrintDispatchTable) {
3399 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3400 TableEntryHeaderPrinter header_printer(stream());
3401 that->GetTable(ignore_case_)->ForEach(&header_printer);
3402 stream()->Add("\"]\n", that);
3403 PrintAttributes(that);
3404 TableEntryBodyPrinter body_printer(stream(), that);
3405 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003406 } else {
3407 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3408 for (int i = 0; i < that->alternatives()->length(); i++) {
3409 GuardedAlternative alt = that->alternatives()->at(i);
3410 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3411 }
3412 }
3413 for (int i = 0; i < that->alternatives()->length(); i++) {
3414 GuardedAlternative alt = that->alternatives()->at(i);
3415 alt.node()->Accept(this);
3416 }
3417}
3418
3419
3420void DotPrinter::VisitText(TextNode* that) {
3421 stream()->Add(" n%p [label=\"", that);
3422 for (int i = 0; i < that->elements()->length(); i++) {
3423 if (i > 0) stream()->Add(" ");
3424 TextElement elm = that->elements()->at(i);
3425 switch (elm.type) {
3426 case TextElement::ATOM: {
3427 stream()->Add("'%w'", elm.data.u_atom->data());
3428 break;
3429 }
3430 case TextElement::CHAR_CLASS: {
3431 RegExpCharacterClass* node = elm.data.u_char_class;
3432 stream()->Add("[");
3433 if (node->is_negated())
3434 stream()->Add("^");
3435 for (int j = 0; j < node->ranges()->length(); j++) {
3436 CharacterRange range = node->ranges()->at(j);
3437 stream()->Add("%k-%k", range.from(), range.to());
3438 }
3439 stream()->Add("]");
3440 break;
3441 }
3442 default:
3443 UNREACHABLE();
3444 }
3445 }
3446 stream()->Add("\", shape=box, peripheries=2];\n");
3447 PrintAttributes(that);
3448 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3449 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003450}
3451
3452
3453void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3454 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3455 that,
3456 that->start_register(),
3457 that->end_register());
3458 PrintAttributes(that);
3459 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3460 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003461}
3462
3463
3464void DotPrinter::VisitEnd(EndNode* that) {
3465 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3466 PrintAttributes(that);
3467}
3468
3469
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003470void DotPrinter::VisitAssertion(AssertionNode* that) {
3471 stream()->Add(" n%p [", that);
3472 switch (that->type()) {
3473 case AssertionNode::AT_END:
3474 stream()->Add("label=\"$\", shape=septagon");
3475 break;
3476 case AssertionNode::AT_START:
3477 stream()->Add("label=\"^\", shape=septagon");
3478 break;
3479 case AssertionNode::AT_BOUNDARY:
3480 stream()->Add("label=\"\\b\", shape=septagon");
3481 break;
3482 case AssertionNode::AT_NON_BOUNDARY:
3483 stream()->Add("label=\"\\B\", shape=septagon");
3484 break;
3485 case AssertionNode::AFTER_NEWLINE:
3486 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3487 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003488 case AssertionNode::AFTER_WORD_CHARACTER:
3489 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3490 break;
3491 case AssertionNode::AFTER_NONWORD_CHARACTER:
3492 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3493 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003494 }
3495 stream()->Add("];\n");
3496 PrintAttributes(that);
3497 RegExpNode* successor = that->on_success();
3498 stream()->Add(" n%p -> n%p;\n", that, successor);
3499 Visit(successor);
3500}
3501
3502
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003503void DotPrinter::VisitAction(ActionNode* that) {
3504 stream()->Add(" n%p [", that);
3505 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003506 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003507 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3508 that->data_.u_store_register.reg,
3509 that->data_.u_store_register.value);
3510 break;
3511 case ActionNode::INCREMENT_REGISTER:
3512 stream()->Add("label=\"$%i++\", shape=octagon",
3513 that->data_.u_increment_register.reg);
3514 break;
3515 case ActionNode::STORE_POSITION:
3516 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3517 that->data_.u_position_register.reg);
3518 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003519 case ActionNode::BEGIN_SUBMATCH:
3520 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3521 that->data_.u_submatch.current_position_register);
3522 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003523 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003524 stream()->Add("label=\"escape\", shape=septagon");
3525 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003526 case ActionNode::EMPTY_MATCH_CHECK:
3527 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3528 that->data_.u_empty_match_check.start_register,
3529 that->data_.u_empty_match_check.repetition_register,
3530 that->data_.u_empty_match_check.repetition_limit);
3531 break;
3532 case ActionNode::CLEAR_CAPTURES: {
3533 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3534 that->data_.u_clear_captures.range_from,
3535 that->data_.u_clear_captures.range_to);
3536 break;
3537 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003538 }
3539 stream()->Add("];\n");
3540 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003541 RegExpNode* successor = that->on_success();
3542 stream()->Add(" n%p -> n%p;\n", that, successor);
3543 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003544}
3545
3546
3547class DispatchTableDumper {
3548 public:
3549 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3550 void Call(uc16 key, DispatchTable::Entry entry);
3551 StringStream* stream() { return stream_; }
3552 private:
3553 StringStream* stream_;
3554};
3555
3556
3557void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3558 stream()->Add("[%k-%k]: {", key, entry.to());
3559 OutSet* set = entry.out_set();
3560 bool first = true;
3561 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3562 if (set->Get(i)) {
3563 if (first) {
3564 first = false;
3565 } else {
3566 stream()->Add(", ");
3567 }
3568 stream()->Add("%i", i);
3569 }
3570 }
3571 stream()->Add("}\n");
3572}
3573
3574
3575void DispatchTable::Dump() {
3576 HeapStringAllocator alloc;
3577 StringStream stream(&alloc);
3578 DispatchTableDumper dumper(&stream);
3579 tree()->ForEach(&dumper);
3580 OS::PrintError("%s", *stream.ToCString());
3581}
3582
3583
3584void RegExpEngine::DotPrint(const char* label,
3585 RegExpNode* node,
3586 bool ignore_case) {
3587 DotPrinter printer(ignore_case);
3588 printer.PrintNode(label, node);
3589}
3590
3591
3592#endif // DEBUG
3593
3594
3595// -------------------------------------------------------------------
3596// Tree to graph conversion
3597
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003598static const int kSpaceRangeCount = 20;
3599static const int kSpaceRangeAsciiCount = 4;
3600static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3601 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3602 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3603
3604static const int kWordRangeCount = 8;
3605static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3606 '_', 'a', 'z' };
3607
3608static const int kDigitRangeCount = 2;
3609static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3610
3611static const int kLineTerminatorRangeCount = 6;
3612static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3613 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003614
3615RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003616 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003617 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3618 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003619 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003620}
3621
3622
3623RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003624 RegExpNode* on_success) {
3625 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003626}
3627
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003628static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3629 const uc16* special_class,
3630 int length) {
3631 ASSERT(ranges->length() != 0);
3632 ASSERT(length != 0);
3633 ASSERT(special_class[0] != 0);
3634 if (ranges->length() != (length >> 1) + 1) {
3635 return false;
3636 }
3637 CharacterRange range = ranges->at(0);
3638 if (range.from() != 0) {
3639 return false;
3640 }
3641 for (int i = 0; i < length; i += 2) {
3642 if (special_class[i] != (range.to() + 1)) {
3643 return false;
3644 }
3645 range = ranges->at((i >> 1) + 1);
3646 if (special_class[i+1] != range.from() - 1) {
3647 return false;
3648 }
3649 }
3650 if (range.to() != 0xffff) {
3651 return false;
3652 }
3653 return true;
3654}
3655
3656
3657static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3658 const uc16* special_class,
3659 int length) {
3660 if (ranges->length() * 2 != length) {
3661 return false;
3662 }
3663 for (int i = 0; i < length; i += 2) {
3664 CharacterRange range = ranges->at(i >> 1);
3665 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3666 return false;
3667 }
3668 }
3669 return true;
3670}
3671
3672
3673bool RegExpCharacterClass::is_standard() {
3674 // TODO(lrn): Remove need for this function, by not throwing away information
3675 // along the way.
3676 if (is_negated_) {
3677 return false;
3678 }
3679 if (set_.is_standard()) {
3680 return true;
3681 }
3682 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3683 set_.set_standard_set_type('s');
3684 return true;
3685 }
3686 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3687 set_.set_standard_set_type('S');
3688 return true;
3689 }
3690 if (CompareInverseRanges(set_.ranges(),
3691 kLineTerminatorRanges,
3692 kLineTerminatorRangeCount)) {
3693 set_.set_standard_set_type('.');
3694 return true;
3695 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003696 if (CompareRanges(set_.ranges(),
3697 kLineTerminatorRanges,
3698 kLineTerminatorRangeCount)) {
3699 set_.set_standard_set_type('n');
3700 return true;
3701 }
3702 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3703 set_.set_standard_set_type('w');
3704 return true;
3705 }
3706 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3707 set_.set_standard_set_type('W');
3708 return true;
3709 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003710 return false;
3711}
3712
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003713
3714RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003715 RegExpNode* on_success) {
3716 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003717}
3718
3719
3720RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003721 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003722 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3723 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003724 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003725 for (int i = 0; i < length; i++) {
3726 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003727 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003728 result->AddAlternative(alternative);
3729 }
3730 return result;
3731}
3732
3733
3734RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003735 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003736 return ToNode(min(),
3737 max(),
3738 is_greedy(),
3739 body(),
3740 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003741 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003742}
3743
3744
whesse@chromium.org7b260152011-06-20 15:33:18 +00003745// Scoped object to keep track of how much we unroll quantifier loops in the
3746// regexp graph generator.
3747class RegExpExpansionLimiter {
3748 public:
3749 static const int kMaxExpansionFactor = 6;
3750 RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
3751 : compiler_(compiler),
3752 saved_expansion_factor_(compiler->current_expansion_factor()),
3753 ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
3754 ASSERT(factor > 0);
3755 if (ok_to_expand_) {
3756 if (factor > kMaxExpansionFactor) {
3757 // Avoid integer overflow of the current expansion factor.
3758 ok_to_expand_ = false;
3759 compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
3760 } else {
3761 int new_factor = saved_expansion_factor_ * factor;
3762 ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
3763 compiler->set_current_expansion_factor(new_factor);
3764 }
3765 }
3766 }
3767
3768 ~RegExpExpansionLimiter() {
3769 compiler_->set_current_expansion_factor(saved_expansion_factor_);
3770 }
3771
3772 bool ok_to_expand() { return ok_to_expand_; }
3773
3774 private:
3775 RegExpCompiler* compiler_;
3776 int saved_expansion_factor_;
3777 bool ok_to_expand_;
3778
3779 DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
3780};
3781
3782
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003783RegExpNode* RegExpQuantifier::ToNode(int min,
3784 int max,
3785 bool is_greedy,
3786 RegExpTree* body,
3787 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003788 RegExpNode* on_success,
3789 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003790 // x{f, t} becomes this:
3791 //
3792 // (r++)<-.
3793 // | `
3794 // | (x)
3795 // v ^
3796 // (r=0)-->(?)---/ [if r < t]
3797 // |
3798 // [if r >= f] \----> ...
3799 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003800
3801 // 15.10.2.5 RepeatMatcher algorithm.
3802 // The parser has already eliminated the case where max is 0. In the case
3803 // where max_match is zero the parser has removed the quantifier if min was
3804 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3805
3806 // If we know that we cannot match zero length then things are a little
3807 // simpler since we don't need to make the special zero length match check
3808 // from step 2.1. If the min and max are small we can unroll a little in
3809 // this case.
3810 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3811 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3812 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003813 bool body_can_be_empty = (body->min_match() == 0);
3814 int body_start_reg = RegExpCompiler::kNoRegister;
3815 Interval capture_registers = body->CaptureRegisters();
3816 bool needs_capture_clearing = !capture_registers.is_empty();
3817 if (body_can_be_empty) {
3818 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003819 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003820 // Only unroll if there are no captures and the body can't be
3821 // empty.
whesse@chromium.org7b260152011-06-20 15:33:18 +00003822 {
3823 RegExpExpansionLimiter limiter(
3824 compiler, min + ((max != min) ? 1 : 0));
3825 if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
3826 int new_max = (max == kInfinity) ? max : max - min;
3827 // Recurse once to get the loop or optional matches after the fixed
3828 // ones.
3829 RegExpNode* answer = ToNode(
3830 0, new_max, is_greedy, body, compiler, on_success, true);
3831 // Unroll the forced matches from 0 to min. This can cause chains of
3832 // TextNodes (which the parser does not generate). These should be
3833 // combined if it turns out they hinder good code generation.
3834 for (int i = 0; i < min; i++) {
3835 answer = body->ToNode(compiler, answer);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003836 }
whesse@chromium.org7b260152011-06-20 15:33:18 +00003837 return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003838 }
whesse@chromium.org7b260152011-06-20 15:33:18 +00003839 }
3840 if (max <= kMaxUnrolledMaxMatches && min == 0) {
3841 ASSERT(max > 0); // Due to the 'if' above.
3842 RegExpExpansionLimiter limiter(compiler, max);
3843 if (limiter.ok_to_expand()) {
3844 // Unroll the optional matches up to max.
3845 RegExpNode* answer = on_success;
3846 for (int i = 0; i < max; i++) {
3847 ChoiceNode* alternation = new ChoiceNode(2);
3848 if (is_greedy) {
3849 alternation->AddAlternative(
3850 GuardedAlternative(body->ToNode(compiler, answer)));
3851 alternation->AddAlternative(GuardedAlternative(on_success));
3852 } else {
3853 alternation->AddAlternative(GuardedAlternative(on_success));
3854 alternation->AddAlternative(
3855 GuardedAlternative(body->ToNode(compiler, answer)));
3856 }
3857 answer = alternation;
3858 if (not_at_start) alternation->set_not_at_start();
3859 }
3860 return answer;
3861 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003862 }
3863 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003864 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003865 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003866 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003867 int reg_ctr = needs_counter
3868 ? compiler->AllocateRegister()
3869 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003870 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003871 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003872 RegExpNode* loop_return = needs_counter
3873 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3874 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003875 if (body_can_be_empty) {
3876 // If the body can be empty we need to check if it was and then
3877 // backtrack.
3878 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3879 reg_ctr,
3880 min,
3881 loop_return);
3882 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003883 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003884 if (body_can_be_empty) {
3885 // If the body can be empty we need to store the start position
3886 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003887 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003888 }
3889 if (needs_capture_clearing) {
3890 // Before entering the body of this loop we need to clear captures.
3891 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3892 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003893 GuardedAlternative body_alt(body_node);
3894 if (has_max) {
3895 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3896 body_alt.AddGuard(body_guard);
3897 }
3898 GuardedAlternative rest_alt(on_success);
3899 if (has_min) {
3900 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3901 rest_alt.AddGuard(rest_guard);
3902 }
3903 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003904 center->AddLoopAlternative(body_alt);
3905 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003906 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003907 center->AddContinueAlternative(rest_alt);
3908 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003909 }
3910 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003911 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003912 } else {
3913 return center;
3914 }
3915}
3916
3917
3918RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003919 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003920 NodeInfo info;
3921 switch (type()) {
3922 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003923 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003924 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003925 return AssertionNode::AtStart(on_success);
3926 case BOUNDARY:
3927 return AssertionNode::AtBoundary(on_success);
3928 case NON_BOUNDARY:
3929 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003930 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003931 return AssertionNode::AtEnd(on_success);
3932 case END_OF_LINE: {
3933 // Compile $ in multiline regexps as an alternation with a positive
3934 // lookahead in one side and an end-of-input on the other side.
3935 // We need two registers for the lookahead.
3936 int stack_pointer_register = compiler->AllocateRegister();
3937 int position_register = compiler->AllocateRegister();
3938 // The ChoiceNode to distinguish between a newline and end-of-input.
3939 ChoiceNode* result = new ChoiceNode(2);
3940 // Create a newline atom.
3941 ZoneList<CharacterRange>* newline_ranges =
3942 new ZoneList<CharacterRange>(3);
3943 CharacterRange::AddClassEscape('n', newline_ranges);
3944 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3945 TextNode* newline_matcher = new TextNode(
3946 newline_atom,
3947 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3948 position_register,
3949 0, // No captures inside.
3950 -1, // Ignored if no captures.
3951 on_success));
3952 // Create an end-of-input matcher.
3953 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3954 stack_pointer_register,
3955 position_register,
3956 newline_matcher);
3957 // Add the two alternatives to the ChoiceNode.
3958 GuardedAlternative eol_alternative(end_of_line);
3959 result->AddAlternative(eol_alternative);
3960 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3961 result->AddAlternative(end_alternative);
3962 return result;
3963 }
3964 default:
3965 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003966 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003967 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003968}
3969
3970
3971RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003972 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003973 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3974 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003975 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003976}
3977
3978
3979RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003980 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003981 return on_success;
3982}
3983
3984
3985RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003986 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003987 int stack_pointer_register = compiler->AllocateRegister();
3988 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003989
3990 const int registers_per_capture = 2;
3991 const int register_of_first_capture = 2;
3992 int register_count = capture_count_ * registers_per_capture;
3993 int register_start =
3994 register_of_first_capture + capture_from_ * registers_per_capture;
3995
ager@chromium.org8bb60582008-12-11 12:02:20 +00003996 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003997 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003998 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003999 stack_pointer_register,
4000 position_register,
4001 body()->ToNode(
4002 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004003 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
4004 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004005 register_count,
4006 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004007 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004008 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004009 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004010 // We use a ChoiceNode for a negative lookahead because it has most of
4011 // the characteristics we need. It has the body of the lookahead as its
4012 // first alternative and the expression after the lookahead of the second
4013 // alternative. If the first alternative succeeds then the
4014 // NegativeSubmatchSuccess will unwind the stack including everything the
4015 // choice node set up and backtrack. If the first alternative fails then
4016 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004017 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
4018 // ChoiceNode that knows to ignore the first exit when calculating quick
4019 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004020 GuardedAlternative body_alt(
4021 body()->ToNode(
4022 compiler,
4023 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004024 position_register,
4025 register_count,
4026 register_start)));
4027 ChoiceNode* choice_node =
4028 new NegativeLookaheadChoiceNode(body_alt,
4029 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004030 return ActionNode::BeginSubmatch(stack_pointer_register,
4031 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004032 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004033 }
4034}
4035
4036
4037RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004038 RegExpNode* on_success) {
4039 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004040}
4041
4042
4043RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
4044 int index,
4045 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004046 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004047 int start_reg = RegExpCapture::StartRegister(index);
4048 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004049 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00004050 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004051 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004052}
4053
4054
4055RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004056 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004057 ZoneList<RegExpTree*>* children = nodes();
4058 RegExpNode* current = on_success;
4059 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004060 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004061 }
4062 return current;
4063}
4064
4065
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004066static void AddClass(const uc16* elmv,
4067 int elmc,
4068 ZoneList<CharacterRange>* ranges) {
4069 for (int i = 0; i < elmc; i += 2) {
4070 ASSERT(elmv[i] <= elmv[i + 1]);
4071 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
4072 }
4073}
4074
4075
4076static void AddClassNegated(const uc16 *elmv,
4077 int elmc,
4078 ZoneList<CharacterRange>* ranges) {
4079 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00004080 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004081 uc16 last = 0x0000;
4082 for (int i = 0; i < elmc; i += 2) {
4083 ASSERT(last <= elmv[i] - 1);
4084 ASSERT(elmv[i] <= elmv[i + 1]);
4085 ranges->Add(CharacterRange(last, elmv[i] - 1));
4086 last = elmv[i + 1] + 1;
4087 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004088 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004089}
4090
4091
4092void CharacterRange::AddClassEscape(uc16 type,
4093 ZoneList<CharacterRange>* ranges) {
4094 switch (type) {
4095 case 's':
4096 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
4097 break;
4098 case 'S':
4099 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
4100 break;
4101 case 'w':
4102 AddClass(kWordRanges, kWordRangeCount, ranges);
4103 break;
4104 case 'W':
4105 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
4106 break;
4107 case 'd':
4108 AddClass(kDigitRanges, kDigitRangeCount, ranges);
4109 break;
4110 case 'D':
4111 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
4112 break;
4113 case '.':
4114 AddClassNegated(kLineTerminatorRanges,
4115 kLineTerminatorRangeCount,
4116 ranges);
4117 break;
4118 // This is not a character range as defined by the spec but a
4119 // convenient shorthand for a character class that matches any
4120 // character.
4121 case '*':
4122 ranges->Add(CharacterRange::Everything());
4123 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004124 // This is the set of characters matched by the $ and ^ symbols
4125 // in multiline mode.
4126 case 'n':
4127 AddClass(kLineTerminatorRanges,
4128 kLineTerminatorRangeCount,
4129 ranges);
4130 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004131 default:
4132 UNREACHABLE();
4133 }
4134}
4135
4136
4137Vector<const uc16> CharacterRange::GetWordBounds() {
4138 return Vector<const uc16>(kWordRanges, kWordRangeCount);
4139}
4140
4141
4142class CharacterRangeSplitter {
4143 public:
4144 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
4145 ZoneList<CharacterRange>** excluded)
4146 : included_(included),
4147 excluded_(excluded) { }
4148 void Call(uc16 from, DispatchTable::Entry entry);
4149
4150 static const int kInBase = 0;
4151 static const int kInOverlay = 1;
4152
4153 private:
4154 ZoneList<CharacterRange>** included_;
4155 ZoneList<CharacterRange>** excluded_;
4156};
4157
4158
4159void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
4160 if (!entry.out_set()->Get(kInBase)) return;
4161 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
4162 ? included_
4163 : excluded_;
4164 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
4165 (*target)->Add(CharacterRange(entry.from(), entry.to()));
4166}
4167
4168
4169void CharacterRange::Split(ZoneList<CharacterRange>* base,
4170 Vector<const uc16> overlay,
4171 ZoneList<CharacterRange>** included,
4172 ZoneList<CharacterRange>** excluded) {
4173 ASSERT_EQ(NULL, *included);
4174 ASSERT_EQ(NULL, *excluded);
4175 DispatchTable table;
4176 for (int i = 0; i < base->length(); i++)
4177 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
4178 for (int i = 0; i < overlay.length(); i += 2) {
4179 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
4180 CharacterRangeSplitter::kInOverlay);
4181 }
4182 CharacterRangeSplitter callback(included, excluded);
4183 table.ForEach(&callback);
4184}
4185
4186
ager@chromium.org38e4c712009-11-11 09:11:58 +00004187void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4188 bool is_ascii) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004189 Isolate* isolate = Isolate::Current();
ager@chromium.org38e4c712009-11-11 09:11:58 +00004190 uc16 bottom = from();
4191 uc16 top = to();
4192 if (is_ascii) {
4193 if (bottom > String::kMaxAsciiCharCode) return;
4194 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4195 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004196 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004197 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004198 // If this is a singleton we just expand the one character.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004199 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004200 for (int i = 0; i < length; i++) {
4201 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004202 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004203 ranges->Add(CharacterRange::Singleton(chars[i]));
4204 }
4205 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004206 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004207 // If this is a range we expand the characters block by block,
4208 // expanding contiguous subranges (blocks) one at a time.
4209 // The approach is as follows. For a given start character we
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004210 // look up the remainder of the block that contains it (represented
4211 // by the end point), for instance we find 'z' if the character
4212 // is 'c'. A block is characterized by the property
4213 // that all characters uncanonicalize in the same way, except that
4214 // each entry in the result is incremented by the distance from the first
4215 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
4216 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
4217 // Once we've found the end point we look up its uncanonicalization
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004218 // and produce a range for each element. For instance for [c-f]
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004219 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004220 // add a range if it is not already contained in the input, so [c-f]
4221 // will be skipped but [C-F] will be added. If this range is not
4222 // completely contained in a block we do this for all the blocks
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004223 // covered by the range (handling characters that is not in a block
4224 // as a "singleton block").
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004225 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004226 int pos = bottom;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004227 while (pos < top) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004228 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004229 uc16 block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004230 if (length == 0) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004231 block_end = pos;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004232 } else {
4233 ASSERT_EQ(1, length);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004234 block_end = range[0];
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004235 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004236 int end = (block_end > top) ? top : block_end;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004237 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004238 for (int i = 0; i < length; i++) {
4239 uc32 c = range[i];
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004240 uc16 range_from = c - (block_end - pos);
4241 uc16 range_to = c - (block_end - end);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004242 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004243 ranges->Add(CharacterRange(range_from, range_to));
4244 }
4245 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004246 pos = end + 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004247 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004248 }
4249}
4250
4251
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004252bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4253 ASSERT_NOT_NULL(ranges);
4254 int n = ranges->length();
4255 if (n <= 1) return true;
4256 int max = ranges->at(0).to();
4257 for (int i = 1; i < n; i++) {
4258 CharacterRange next_range = ranges->at(i);
4259 if (next_range.from() <= max + 1) return false;
4260 max = next_range.to();
4261 }
4262 return true;
4263}
4264
4265SetRelation CharacterRange::WordCharacterRelation(
4266 ZoneList<CharacterRange>* range) {
4267 ASSERT(IsCanonical(range));
4268 int i = 0; // Word character range index.
4269 int j = 0; // Argument range index.
4270 ASSERT_NE(0, kWordRangeCount);
4271 SetRelation result;
4272 if (range->length() == 0) {
4273 result.SetElementsInSecondSet();
4274 return result;
4275 }
4276 CharacterRange argument_range = range->at(0);
4277 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4278 while (i < kWordRangeCount && j < range->length()) {
4279 // Check the two ranges for the five cases:
4280 // - no overlap.
4281 // - partial overlap (there are elements in both ranges that isn't
4282 // in the other, and there are also elements that are in both).
4283 // - argument range entirely inside word range.
4284 // - word range entirely inside argument range.
4285 // - ranges are completely equal.
4286
4287 // First check for no overlap. The earlier range is not in the other set.
4288 if (argument_range.from() > word_range.to()) {
4289 // Ranges are disjoint. The earlier word range contains elements that
4290 // cannot be in the argument set.
4291 result.SetElementsInSecondSet();
4292 } else if (word_range.from() > argument_range.to()) {
4293 // Ranges are disjoint. The earlier argument range contains elements that
4294 // cannot be in the word set.
4295 result.SetElementsInFirstSet();
4296 } else if (word_range.from() <= argument_range.from() &&
4297 word_range.to() >= argument_range.from()) {
4298 result.SetElementsInBothSets();
4299 // argument range completely inside word range.
4300 if (word_range.from() < argument_range.from() ||
4301 word_range.to() > argument_range.from()) {
4302 result.SetElementsInSecondSet();
4303 }
4304 } else if (word_range.from() >= argument_range.from() &&
4305 word_range.to() <= argument_range.from()) {
4306 result.SetElementsInBothSets();
4307 result.SetElementsInFirstSet();
4308 } else {
4309 // There is overlap, and neither is a subrange of the other
4310 result.SetElementsInFirstSet();
4311 result.SetElementsInSecondSet();
4312 result.SetElementsInBothSets();
4313 }
4314 if (result.NonTrivialIntersection()) {
4315 // The result is as (im)precise as we can possibly make it.
4316 return result;
4317 }
4318 // Progress the range(s) with minimal to-character.
4319 uc16 word_to = word_range.to();
4320 uc16 argument_to = argument_range.to();
4321 if (argument_to <= word_to) {
4322 j++;
4323 if (j < range->length()) {
4324 argument_range = range->at(j);
4325 }
4326 }
4327 if (word_to <= argument_to) {
4328 i += 2;
4329 if (i < kWordRangeCount) {
4330 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4331 }
4332 }
4333 }
4334 // Check if anything wasn't compared in the loop.
4335 if (i < kWordRangeCount) {
4336 // word range contains something not in argument range.
4337 result.SetElementsInSecondSet();
4338 } else if (j < range->length()) {
4339 // Argument range contains something not in word range.
4340 result.SetElementsInFirstSet();
4341 }
4342
4343 return result;
4344}
4345
4346
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004347ZoneList<CharacterRange>* CharacterSet::ranges() {
4348 if (ranges_ == NULL) {
4349 ranges_ = new ZoneList<CharacterRange>(2);
4350 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4351 }
4352 return ranges_;
4353}
4354
4355
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004356// Move a number of elements in a zonelist to another position
4357// in the same list. Handles overlapping source and target areas.
4358static void MoveRanges(ZoneList<CharacterRange>* list,
4359 int from,
4360 int to,
4361 int count) {
4362 // Ranges are potentially overlapping.
4363 if (from < to) {
4364 for (int i = count - 1; i >= 0; i--) {
4365 list->at(to + i) = list->at(from + i);
4366 }
4367 } else {
4368 for (int i = 0; i < count; i++) {
4369 list->at(to + i) = list->at(from + i);
4370 }
4371 }
4372}
4373
4374
4375static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4376 int count,
4377 CharacterRange insert) {
4378 // Inserts a range into list[0..count[, which must be sorted
4379 // by from value and non-overlapping and non-adjacent, using at most
4380 // list[0..count] for the result. Returns the number of resulting
4381 // canonicalized ranges. Inserting a range may collapse existing ranges into
4382 // fewer ranges, so the return value can be anything in the range 1..count+1.
4383 uc16 from = insert.from();
4384 uc16 to = insert.to();
4385 int start_pos = 0;
4386 int end_pos = count;
4387 for (int i = count - 1; i >= 0; i--) {
4388 CharacterRange current = list->at(i);
4389 if (current.from() > to + 1) {
4390 end_pos = i;
4391 } else if (current.to() + 1 < from) {
4392 start_pos = i + 1;
4393 break;
4394 }
4395 }
4396
4397 // Inserted range overlaps, or is adjacent to, ranges at positions
4398 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4399 // not affected by the insertion.
4400 // If start_pos == end_pos, the range must be inserted before start_pos.
4401 // if start_pos < end_pos, the entire range from start_pos to end_pos
4402 // must be merged with the insert range.
4403
4404 if (start_pos == end_pos) {
4405 // Insert between existing ranges at position start_pos.
4406 if (start_pos < count) {
4407 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4408 }
4409 list->at(start_pos) = insert;
4410 return count + 1;
4411 }
4412 if (start_pos + 1 == end_pos) {
4413 // Replace single existing range at position start_pos.
4414 CharacterRange to_replace = list->at(start_pos);
4415 int new_from = Min(to_replace.from(), from);
4416 int new_to = Max(to_replace.to(), to);
4417 list->at(start_pos) = CharacterRange(new_from, new_to);
4418 return count;
4419 }
4420 // Replace a number of existing ranges from start_pos to end_pos - 1.
4421 // Move the remaining ranges down.
4422
4423 int new_from = Min(list->at(start_pos).from(), from);
4424 int new_to = Max(list->at(end_pos - 1).to(), to);
4425 if (end_pos < count) {
4426 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4427 }
4428 list->at(start_pos) = CharacterRange(new_from, new_to);
4429 return count - (end_pos - start_pos) + 1;
4430}
4431
4432
4433void CharacterSet::Canonicalize() {
4434 // Special/default classes are always considered canonical. The result
4435 // of calling ranges() will be sorted.
4436 if (ranges_ == NULL) return;
4437 CharacterRange::Canonicalize(ranges_);
4438}
4439
4440
4441void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4442 if (character_ranges->length() <= 1) return;
4443 // Check whether ranges are already canonical (increasing, non-overlapping,
4444 // non-adjacent).
4445 int n = character_ranges->length();
4446 int max = character_ranges->at(0).to();
4447 int i = 1;
4448 while (i < n) {
4449 CharacterRange current = character_ranges->at(i);
4450 if (current.from() <= max + 1) {
4451 break;
4452 }
4453 max = current.to();
4454 i++;
4455 }
4456 // Canonical until the i'th range. If that's all of them, we are done.
4457 if (i == n) return;
4458
4459 // The ranges at index i and forward are not canonicalized. Make them so by
4460 // doing the equivalent of insertion sort (inserting each into the previous
4461 // list, in order).
4462 // Notice that inserting a range can reduce the number of ranges in the
4463 // result due to combining of adjacent and overlapping ranges.
4464 int read = i; // Range to insert.
4465 int num_canonical = i; // Length of canonicalized part of list.
4466 do {
4467 num_canonical = InsertRangeInCanonicalList(character_ranges,
4468 num_canonical,
4469 character_ranges->at(read));
4470 read++;
4471 } while (read < n);
4472 character_ranges->Rewind(num_canonical);
4473
4474 ASSERT(CharacterRange::IsCanonical(character_ranges));
4475}
4476
4477
4478// Utility function for CharacterRange::Merge. Adds a range at the end of
4479// a canonicalized range list, if necessary merging the range with the last
4480// range of the list.
4481static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4482 if (set == NULL) return;
4483 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4484 int n = set->length();
4485 if (n > 0) {
4486 CharacterRange lastRange = set->at(n - 1);
4487 if (lastRange.to() == range.from() - 1) {
4488 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4489 return;
4490 }
4491 }
4492 set->Add(range);
4493}
4494
4495
4496static void AddRangeToSelectedSet(int selector,
4497 ZoneList<CharacterRange>* first_set,
4498 ZoneList<CharacterRange>* second_set,
4499 ZoneList<CharacterRange>* intersection_set,
4500 CharacterRange range) {
4501 switch (selector) {
4502 case kInsideFirst:
4503 AddRangeToSet(first_set, range);
4504 break;
4505 case kInsideSecond:
4506 AddRangeToSet(second_set, range);
4507 break;
4508 case kInsideBoth:
4509 AddRangeToSet(intersection_set, range);
4510 break;
4511 }
4512}
4513
4514
4515
4516void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4517 ZoneList<CharacterRange>* second_set,
4518 ZoneList<CharacterRange>* first_set_only_out,
4519 ZoneList<CharacterRange>* second_set_only_out,
4520 ZoneList<CharacterRange>* both_sets_out) {
4521 // Inputs are canonicalized.
4522 ASSERT(CharacterRange::IsCanonical(first_set));
4523 ASSERT(CharacterRange::IsCanonical(second_set));
4524 // Outputs are empty, if applicable.
4525 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4526 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4527 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4528
4529 // Merge sets by iterating through the lists in order of lowest "from" value,
4530 // and putting intervals into one of three sets.
4531
4532 if (first_set->length() == 0) {
4533 second_set_only_out->AddAll(*second_set);
4534 return;
4535 }
4536 if (second_set->length() == 0) {
4537 first_set_only_out->AddAll(*first_set);
4538 return;
4539 }
4540 // Indices into input lists.
4541 int i1 = 0;
4542 int i2 = 0;
4543 // Cache length of input lists.
4544 int n1 = first_set->length();
4545 int n2 = second_set->length();
4546 // Current range. May be invalid if state is kInsideNone.
4547 int from = 0;
4548 int to = -1;
4549 // Where current range comes from.
4550 int state = kInsideNone;
4551
4552 while (i1 < n1 || i2 < n2) {
4553 CharacterRange next_range;
4554 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004555 if (i2 == n2 ||
4556 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4557 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004558 next_range = first_set->at(i1++);
4559 range_source = kInsideFirst;
4560 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004561 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004562 next_range = second_set->at(i2++);
4563 range_source = kInsideSecond;
4564 }
4565 if (to < next_range.from()) {
4566 // Ranges disjoint: |current| |next|
4567 AddRangeToSelectedSet(state,
4568 first_set_only_out,
4569 second_set_only_out,
4570 both_sets_out,
4571 CharacterRange(from, to));
4572 from = next_range.from();
4573 to = next_range.to();
4574 state = range_source;
4575 } else {
4576 if (from < next_range.from()) {
4577 AddRangeToSelectedSet(state,
4578 first_set_only_out,
4579 second_set_only_out,
4580 both_sets_out,
4581 CharacterRange(from, next_range.from()-1));
4582 }
4583 if (to < next_range.to()) {
4584 // Ranges overlap: |current|
4585 // |next|
4586 AddRangeToSelectedSet(state | range_source,
4587 first_set_only_out,
4588 second_set_only_out,
4589 both_sets_out,
4590 CharacterRange(next_range.from(), to));
4591 from = to + 1;
4592 to = next_range.to();
4593 state = range_source;
4594 } else {
4595 // Range included: |current| , possibly ending at same character.
4596 // |next|
4597 AddRangeToSelectedSet(
4598 state | range_source,
4599 first_set_only_out,
4600 second_set_only_out,
4601 both_sets_out,
4602 CharacterRange(next_range.from(), next_range.to()));
4603 from = next_range.to() + 1;
4604 // If ranges end at same character, both ranges are consumed completely.
4605 if (next_range.to() == to) state = kInsideNone;
4606 }
4607 }
4608 }
4609 AddRangeToSelectedSet(state,
4610 first_set_only_out,
4611 second_set_only_out,
4612 both_sets_out,
4613 CharacterRange(from, to));
4614}
4615
4616
4617void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4618 ZoneList<CharacterRange>* negated_ranges) {
4619 ASSERT(CharacterRange::IsCanonical(ranges));
4620 ASSERT_EQ(0, negated_ranges->length());
4621 int range_count = ranges->length();
4622 uc16 from = 0;
4623 int i = 0;
4624 if (range_count > 0 && ranges->at(0).from() == 0) {
4625 from = ranges->at(0).to();
4626 i = 1;
4627 }
4628 while (i < range_count) {
4629 CharacterRange range = ranges->at(i);
4630 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4631 from = range.to();
4632 i++;
4633 }
4634 if (from < String::kMaxUC16CharCode) {
4635 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4636 }
4637}
4638
4639
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004640
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004641// -------------------------------------------------------------------
4642// Interest propagation
4643
4644
4645RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4646 for (int i = 0; i < siblings_.length(); i++) {
4647 RegExpNode* sibling = siblings_.Get(i);
4648 if (sibling->info()->Matches(info))
4649 return sibling;
4650 }
4651 return NULL;
4652}
4653
4654
4655RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4656 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004657 siblings_.Ensure(this);
4658 RegExpNode* result = TryGetSibling(info);
4659 if (result != NULL) return result;
4660 result = this->Clone();
4661 NodeInfo* new_info = result->info();
4662 new_info->ResetCompilationState();
4663 new_info->AddFromPreceding(info);
4664 AddSibling(result);
4665 *cloned = true;
4666 return result;
4667}
4668
4669
4670template <class C>
4671static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4672 NodeInfo full_info(*node->info());
4673 full_info.AddFromPreceding(info);
4674 bool cloned = false;
4675 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4676}
4677
4678
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004679// -------------------------------------------------------------------
4680// Splay tree
4681
4682
4683OutSet* OutSet::Extend(unsigned value) {
4684 if (Get(value))
4685 return this;
4686 if (successors() != NULL) {
4687 for (int i = 0; i < successors()->length(); i++) {
4688 OutSet* successor = successors()->at(i);
4689 if (successor->Get(value))
4690 return successor;
4691 }
4692 } else {
4693 successors_ = new ZoneList<OutSet*>(2);
4694 }
4695 OutSet* result = new OutSet(first_, remaining_);
4696 result->Set(value);
4697 successors()->Add(result);
4698 return result;
4699}
4700
4701
4702void OutSet::Set(unsigned value) {
4703 if (value < kFirstLimit) {
4704 first_ |= (1 << value);
4705 } else {
4706 if (remaining_ == NULL)
4707 remaining_ = new ZoneList<unsigned>(1);
4708 if (remaining_->is_empty() || !remaining_->Contains(value))
4709 remaining_->Add(value);
4710 }
4711}
4712
4713
4714bool OutSet::Get(unsigned value) {
4715 if (value < kFirstLimit) {
4716 return (first_ & (1 << value)) != 0;
4717 } else if (remaining_ == NULL) {
4718 return false;
4719 } else {
4720 return remaining_->Contains(value);
4721 }
4722}
4723
4724
4725const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4726const DispatchTable::Entry DispatchTable::Config::kNoValue;
4727
4728
4729void DispatchTable::AddRange(CharacterRange full_range, int value) {
4730 CharacterRange current = full_range;
4731 if (tree()->is_empty()) {
4732 // If this is the first range we just insert into the table.
4733 ZoneSplayTree<Config>::Locator loc;
4734 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4735 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4736 return;
4737 }
4738 // First see if there is a range to the left of this one that
4739 // overlaps.
4740 ZoneSplayTree<Config>::Locator loc;
4741 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4742 Entry* entry = &loc.value();
4743 // If we've found a range that overlaps with this one, and it
4744 // starts strictly to the left of this one, we have to fix it
4745 // because the following code only handles ranges that start on
4746 // or after the start point of the range we're adding.
4747 if (entry->from() < current.from() && entry->to() >= current.from()) {
4748 // Snap the overlapping range in half around the start point of
4749 // the range we're adding.
4750 CharacterRange left(entry->from(), current.from() - 1);
4751 CharacterRange right(current.from(), entry->to());
4752 // The left part of the overlapping range doesn't overlap.
4753 // Truncate the whole entry to be just the left part.
4754 entry->set_to(left.to());
4755 // The right part is the one that overlaps. We add this part
4756 // to the map and let the next step deal with merging it with
4757 // the range we're adding.
4758 ZoneSplayTree<Config>::Locator loc;
4759 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4760 loc.set_value(Entry(right.from(),
4761 right.to(),
4762 entry->out_set()));
4763 }
4764 }
4765 while (current.is_valid()) {
4766 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4767 (loc.value().from() <= current.to()) &&
4768 (loc.value().to() >= current.from())) {
4769 Entry* entry = &loc.value();
4770 // We have overlap. If there is space between the start point of
4771 // the range we're adding and where the overlapping range starts
4772 // then we have to add a range covering just that space.
4773 if (current.from() < entry->from()) {
4774 ZoneSplayTree<Config>::Locator ins;
4775 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4776 ins.set_value(Entry(current.from(),
4777 entry->from() - 1,
4778 empty()->Extend(value)));
4779 current.set_from(entry->from());
4780 }
4781 ASSERT_EQ(current.from(), entry->from());
4782 // If the overlapping range extends beyond the one we want to add
4783 // we have to snap the right part off and add it separately.
4784 if (entry->to() > current.to()) {
4785 ZoneSplayTree<Config>::Locator ins;
4786 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4787 ins.set_value(Entry(current.to() + 1,
4788 entry->to(),
4789 entry->out_set()));
4790 entry->set_to(current.to());
4791 }
4792 ASSERT(entry->to() <= current.to());
4793 // The overlapping range is now completely contained by the range
4794 // we're adding so we can just update it and move the start point
4795 // of the range we're adding just past it.
4796 entry->AddValue(value);
4797 // Bail out if the last interval ended at 0xFFFF since otherwise
4798 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004799 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004800 break;
4801 ASSERT(entry->to() + 1 > current.from());
4802 current.set_from(entry->to() + 1);
4803 } else {
4804 // There is no overlap so we can just add the range
4805 ZoneSplayTree<Config>::Locator ins;
4806 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4807 ins.set_value(Entry(current.from(),
4808 current.to(),
4809 empty()->Extend(value)));
4810 break;
4811 }
4812 }
4813}
4814
4815
4816OutSet* DispatchTable::Get(uc16 value) {
4817 ZoneSplayTree<Config>::Locator loc;
4818 if (!tree()->FindGreatestLessThan(value, &loc))
4819 return empty();
4820 Entry* entry = &loc.value();
4821 if (value <= entry->to())
4822 return entry->out_set();
4823 else
4824 return empty();
4825}
4826
4827
4828// -------------------------------------------------------------------
4829// Analysis
4830
4831
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004832void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004833 StackLimitCheck check(Isolate::Current());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004834 if (check.HasOverflowed()) {
4835 fail("Stack overflow");
4836 return;
4837 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004838 if (that->info()->been_analyzed || that->info()->being_analyzed)
4839 return;
4840 that->info()->being_analyzed = true;
4841 that->Accept(this);
4842 that->info()->being_analyzed = false;
4843 that->info()->been_analyzed = true;
4844}
4845
4846
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004847void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004848 // nothing to do
4849}
4850
4851
ager@chromium.org8bb60582008-12-11 12:02:20 +00004852void TextNode::CalculateOffsets() {
4853 int element_count = elements()->length();
4854 // Set up the offsets of the elements relative to the start. This is a fixed
4855 // quantity since a TextNode can only contain fixed-width things.
4856 int cp_offset = 0;
4857 for (int i = 0; i < element_count; i++) {
4858 TextElement& elm = elements()->at(i);
4859 elm.cp_offset = cp_offset;
4860 if (elm.type == TextElement::ATOM) {
4861 cp_offset += elm.data.u_atom->data().length();
4862 } else {
4863 cp_offset++;
ager@chromium.org8bb60582008-12-11 12:02:20 +00004864 }
4865 }
4866}
4867
4868
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004869void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004870 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004871 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004872 }
4873 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004874 if (!has_failed()) {
4875 that->CalculateOffsets();
4876 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004877}
4878
4879
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004880void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004881 RegExpNode* target = that->on_success();
4882 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004883 if (!has_failed()) {
4884 // If the next node is interested in what it follows then this node
4885 // has to be interested too so it can pass the information on.
4886 that->info()->AddFromFollowing(target->info());
4887 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004888}
4889
4890
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004891void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004892 NodeInfo* info = that->info();
4893 for (int i = 0; i < that->alternatives()->length(); i++) {
4894 RegExpNode* node = that->alternatives()->at(i).node();
4895 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004896 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004897 // Anything the following nodes need to know has to be known by
4898 // this node also, so it can pass it on.
4899 info->AddFromFollowing(node->info());
4900 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004901}
4902
4903
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004904void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4905 NodeInfo* info = that->info();
4906 for (int i = 0; i < that->alternatives()->length(); i++) {
4907 RegExpNode* node = that->alternatives()->at(i).node();
4908 if (node != that->loop_node()) {
4909 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004910 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004911 info->AddFromFollowing(node->info());
4912 }
4913 }
4914 // Check the loop last since it may need the value of this node
4915 // to get a correct result.
4916 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004917 if (!has_failed()) {
4918 info->AddFromFollowing(that->loop_node()->info());
4919 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004920}
4921
4922
4923void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004924 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004925}
4926
4927
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004928void Analysis::VisitAssertion(AssertionNode* that) {
4929 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004930 AssertionNode::AssertionNodeType type = that->type();
4931 if (type == AssertionNode::AT_BOUNDARY ||
4932 type == AssertionNode::AT_NON_BOUNDARY) {
4933 // Check if the following character is known to be a word character
4934 // or known to not be a word character.
4935 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4936
4937 CharacterRange::Canonicalize(following_chars);
4938
4939 SetRelation word_relation =
4940 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004941 if (word_relation.Disjoint()) {
4942 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004943 // Following character is definitely *not* a word character.
4944 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004945 AssertionNode::AFTER_WORD_CHARACTER :
4946 AssertionNode::AFTER_NONWORD_CHARACTER;
4947 that->set_type(type);
4948 } else if (word_relation.ContainedIn()) {
4949 // Following character is definitely a word character.
4950 type = (type == AssertionNode::AT_BOUNDARY) ?
4951 AssertionNode::AFTER_NONWORD_CHARACTER :
4952 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004953 that->set_type(type);
4954 }
4955 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004956}
4957
4958
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004959ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4960 if (first_character_set_ == NULL) {
4961 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4962 // If we can't find an exact solution within the budget, we
4963 // set the value to the set of every character, i.e., all characters
4964 // are possible.
4965 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4966 all_set->Add(CharacterRange::Everything());
4967 first_character_set_ = all_set;
4968 }
4969 }
4970 return first_character_set_;
4971}
4972
4973
4974int RegExpNode::ComputeFirstCharacterSet(int budget) {
4975 // Default behavior is to not be able to determine the first character.
4976 return kComputeFirstCharacterSetFail;
4977}
4978
4979
4980int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
4981 budget--;
4982 if (budget >= 0) {
4983 // Find loop min-iteration. It's the value of the guarded choice node
4984 // with a GEQ guard, if any.
4985 int min_repetition = 0;
4986
4987 for (int i = 0; i <= 1; i++) {
4988 GuardedAlternative alternative = alternatives()->at(i);
4989 ZoneList<Guard*>* guards = alternative.guards();
4990 if (guards != NULL && guards->length() > 0) {
4991 Guard* guard = guards->at(0);
4992 if (guard->op() == Guard::GEQ) {
4993 min_repetition = guard->value();
4994 break;
4995 }
4996 }
4997 }
4998
4999 budget = loop_node()->ComputeFirstCharacterSet(budget);
5000 if (budget >= 0) {
5001 ZoneList<CharacterRange>* character_set =
5002 loop_node()->first_character_set();
5003 if (body_can_be_zero_length() || min_repetition == 0) {
5004 budget = continue_node()->ComputeFirstCharacterSet(budget);
5005 if (budget < 0) return budget;
5006 ZoneList<CharacterRange>* body_set =
5007 continue_node()->first_character_set();
5008 ZoneList<CharacterRange>* union_set =
5009 new ZoneList<CharacterRange>(Max(character_set->length(),
5010 body_set->length()));
5011 CharacterRange::Merge(character_set,
5012 body_set,
5013 union_set,
5014 union_set,
5015 union_set);
5016 character_set = union_set;
5017 }
5018 set_first_character_set(character_set);
5019 }
5020 }
5021 return budget;
5022}
5023
5024
5025int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
5026 budget--;
5027 if (budget >= 0) {
5028 GuardedAlternative successor = this->alternatives()->at(1);
5029 RegExpNode* successor_node = successor.node();
5030 budget = successor_node->ComputeFirstCharacterSet(budget);
5031 if (budget >= 0) {
5032 set_first_character_set(successor_node->first_character_set());
5033 }
5034 }
5035 return budget;
5036}
5037
5038
5039// The first character set of an EndNode is unknowable. Just use the
5040// default implementation that fails and returns all characters as possible.
5041
5042
5043int AssertionNode::ComputeFirstCharacterSet(int budget) {
5044 budget -= 1;
5045 if (budget >= 0) {
5046 switch (type_) {
5047 case AT_END: {
5048 set_first_character_set(new ZoneList<CharacterRange>(0));
5049 break;
5050 }
5051 case AT_START:
5052 case AT_BOUNDARY:
5053 case AT_NON_BOUNDARY:
5054 case AFTER_NEWLINE:
5055 case AFTER_NONWORD_CHARACTER:
5056 case AFTER_WORD_CHARACTER: {
5057 ASSERT_NOT_NULL(on_success());
5058 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005059 if (budget >= 0) {
5060 set_first_character_set(on_success()->first_character_set());
5061 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005062 break;
5063 }
5064 }
5065 }
5066 return budget;
5067}
5068
5069
5070int ActionNode::ComputeFirstCharacterSet(int budget) {
5071 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
5072 budget--;
5073 if (budget >= 0) {
5074 ASSERT_NOT_NULL(on_success());
5075 budget = on_success()->ComputeFirstCharacterSet(budget);
5076 if (budget >= 0) {
5077 set_first_character_set(on_success()->first_character_set());
5078 }
5079 }
5080 return budget;
5081}
5082
5083
5084int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5085 // We don't know anything about the first character of a backreference
5086 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005087 // The potential first characters are the first characters of the capture,
5088 // and the first characters of the on_success node, depending on whether the
5089 // capture can be empty and whether it is known to be participating or known
5090 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005091 return kComputeFirstCharacterSetFail;
5092}
5093
5094
5095int TextNode::ComputeFirstCharacterSet(int budget) {
5096 budget--;
5097 if (budget >= 0) {
5098 ASSERT_NE(0, elements()->length());
5099 TextElement text = elements()->at(0);
5100 if (text.type == TextElement::ATOM) {
5101 RegExpAtom* atom = text.data.u_atom;
5102 ASSERT_NE(0, atom->length());
5103 uc16 first_char = atom->data()[0];
5104 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5105 range->Add(CharacterRange(first_char, first_char));
5106 set_first_character_set(range);
5107 } else {
5108 ASSERT(text.type == TextElement::CHAR_CLASS);
5109 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005110 ZoneList<CharacterRange>* ranges = char_class->ranges();
5111 // TODO(lrn): Canonicalize ranges when they are created
5112 // instead of waiting until now.
5113 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005114 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005115 int length = ranges->length();
5116 int new_length = length + 1;
5117 if (length > 0) {
5118 if (ranges->at(0).from() == 0) new_length--;
5119 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5120 new_length--;
5121 }
5122 }
5123 ZoneList<CharacterRange>* negated_ranges =
5124 new ZoneList<CharacterRange>(new_length);
5125 CharacterRange::Negate(ranges, negated_ranges);
5126 set_first_character_set(negated_ranges);
5127 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005128 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005129 }
5130 }
5131 }
5132 return budget;
5133}
5134
5135
5136
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005137// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005138// Dispatch table construction
5139
5140
5141void DispatchTableConstructor::VisitEnd(EndNode* that) {
5142 AddRange(CharacterRange::Everything());
5143}
5144
5145
5146void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5147 node->set_being_calculated(true);
5148 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5149 for (int i = 0; i < alternatives->length(); i++) {
5150 set_choice_index(i);
5151 alternatives->at(i).node()->Accept(this);
5152 }
5153 node->set_being_calculated(false);
5154}
5155
5156
5157class AddDispatchRange {
5158 public:
5159 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5160 : constructor_(constructor) { }
5161 void Call(uc32 from, DispatchTable::Entry entry);
5162 private:
5163 DispatchTableConstructor* constructor_;
5164};
5165
5166
5167void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5168 CharacterRange range(from, entry.to());
5169 constructor_->AddRange(range);
5170}
5171
5172
5173void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5174 if (node->being_calculated())
5175 return;
5176 DispatchTable* table = node->GetTable(ignore_case_);
5177 AddDispatchRange adder(this);
5178 table->ForEach(&adder);
5179}
5180
5181
5182void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5183 // TODO(160): Find the node that we refer back to and propagate its start
5184 // set back to here. For now we just accept anything.
5185 AddRange(CharacterRange::Everything());
5186}
5187
5188
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005189void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5190 RegExpNode* target = that->on_success();
5191 target->Accept(this);
5192}
5193
5194
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005195static int CompareRangeByFrom(const CharacterRange* a,
5196 const CharacterRange* b) {
5197 return Compare<uc16>(a->from(), b->from());
5198}
5199
5200
5201void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5202 ranges->Sort(CompareRangeByFrom);
5203 uc16 last = 0;
5204 for (int i = 0; i < ranges->length(); i++) {
5205 CharacterRange range = ranges->at(i);
5206 if (last < range.from())
5207 AddRange(CharacterRange(last, range.from() - 1));
5208 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005209 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005210 return;
5211 } else {
5212 last = range.to() + 1;
5213 }
5214 }
5215 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005216 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005217}
5218
5219
5220void DispatchTableConstructor::VisitText(TextNode* that) {
5221 TextElement elm = that->elements()->at(0);
5222 switch (elm.type) {
5223 case TextElement::ATOM: {
5224 uc16 c = elm.data.u_atom->data()[0];
5225 AddRange(CharacterRange(c, c));
5226 break;
5227 }
5228 case TextElement::CHAR_CLASS: {
5229 RegExpCharacterClass* tree = elm.data.u_char_class;
5230 ZoneList<CharacterRange>* ranges = tree->ranges();
5231 if (tree->is_negated()) {
5232 AddInverse(ranges);
5233 } else {
5234 for (int i = 0; i < ranges->length(); i++)
5235 AddRange(ranges->at(i));
5236 }
5237 break;
5238 }
5239 default: {
5240 UNIMPLEMENTED();
5241 }
5242 }
5243}
5244
5245
5246void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005247 RegExpNode* target = that->on_success();
5248 target->Accept(this);
5249}
5250
5251
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005252RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5253 bool ignore_case,
5254 bool is_multiline,
5255 Handle<String> pattern,
5256 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005257 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005258 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005259 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005260 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005261 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005262 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005263 0,
5264 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005265 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005266 RegExpNode* node = captured_body;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005267 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
5268 bool is_start_anchored = data->tree->IsAnchoredAtStart();
5269 int max_length = data->tree->max_match();
5270 if (!is_start_anchored) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005271 // Add a .*? at the beginning, outside the body capture, unless
5272 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005273 RegExpNode* loop_node =
5274 RegExpQuantifier::ToNode(0,
5275 RegExpTree::kInfinity,
5276 false,
5277 new RegExpCharacterClass('*'),
5278 &compiler,
5279 captured_body,
5280 data->contains_anchor);
5281
5282 if (data->contains_anchor) {
5283 // Unroll loop once, to take care of the case that might start
5284 // at the start of input.
5285 ChoiceNode* first_step_node = new ChoiceNode(2);
5286 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5287 first_step_node->AddAlternative(GuardedAlternative(
5288 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5289 node = first_step_node;
5290 } else {
5291 node = loop_node;
5292 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005293 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005294 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005295 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005296 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005297 if (analysis.has_failed()) {
5298 const char* error_message = analysis.error_message();
5299 return CompilationResult(error_message);
5300 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005301
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005302 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005303#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005304 // Native regexp implementation.
5305
5306 NativeRegExpMacroAssembler::Mode mode =
5307 is_ascii ? NativeRegExpMacroAssembler::ASCII
5308 : NativeRegExpMacroAssembler::UC16;
5309
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005310#if V8_TARGET_ARCH_IA32
5311 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5312#elif V8_TARGET_ARCH_X64
5313 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5314#elif V8_TARGET_ARCH_ARM
5315 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
lrn@chromium.org7516f052011-03-30 08:52:27 +00005316#elif V8_TARGET_ARCH_MIPS
5317 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005318#endif
5319
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005320#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005321 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005322 EmbeddedVector<byte, 1024> codes;
5323 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005324#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005325
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005326 // Inserted here, instead of in Assembler, because it depends on information
5327 // in the AST that isn't replicated in the Node structure.
5328 static const int kMaxBacksearchLimit = 1024;
5329 if (is_end_anchored &&
5330 !is_start_anchored &&
5331 max_length < kMaxBacksearchLimit) {
5332 macro_assembler.SetCurrentPositionFromEnd(max_length);
5333 }
5334
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005335 return compiler.Assemble(&macro_assembler,
5336 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005337 data->capture_count,
5338 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005339}
5340
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005341
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005342}} // namespace v8::internal