blob: 06aae352e7a4d6a451447412194c1f194fe6ef39 [file] [log] [blame]
ager@chromium.org381abbb2009-02-25 13:23:22 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
ager@chromium.orga74f0da2008-12-03 16:05:52 +000030#include "ast.h"
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +000031#include "compiler.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032#include "execution.h"
33#include "factory.h"
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +000034#include "jsregexp.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "platform.h"
kasperl@chromium.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);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000130 CompilationZoneScope zone_scope(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
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000215 /* template <typename SubjectChar>, typename PatternChar>
216static int ReStringMatch(Vector<const SubjectChar> sub_vector,
217 Vector<const PatternChar> pat_vector,
218 int start_index) {
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000219
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000220 int pattern_length = pat_vector.length();
221 if (pattern_length == 0) return start_index;
222
223 int subject_length = sub_vector.length();
224 if (start_index + pattern_length > subject_length) return -1;
225 return SearchString(sub_vector, pat_vector, start_index);
226}
227 */
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000228Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
229 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000230 int index,
231 Handle<JSArray> last_match_info) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000232 Isolate* isolate = re->GetIsolate();
233
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000234 ASSERT(0 <= index);
235 ASSERT(index <= subject->length());
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000236
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000237 if (!subject->IsFlat()) FlattenString(subject);
238 AssertNoAllocation no_heap_allocation; // ensure vectors stay valid
239 // Extract flattened substrings of cons strings before determining asciiness.
240 String* seq_sub = *subject;
241 if (seq_sub->IsConsString()) seq_sub = ConsString::cast(seq_sub)->first();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000242
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000243 String* needle = String::cast(re->DataAt(JSRegExp::kAtomPatternIndex));
244 int needle_len = needle->length();
245
246 if (needle_len != 0) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000247 if (index + needle_len > subject->length())
248 return isolate->factory()->null_value();
249
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000250 // dispatch on type of strings
251 index = (needle->IsAsciiRepresentation()
252 ? (seq_sub->IsAsciiRepresentation()
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000253 ? SearchString(isolate,
254 seq_sub->ToAsciiVector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000255 needle->ToAsciiVector(),
256 index)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000257 : SearchString(isolate,
258 seq_sub->ToUC16Vector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000259 needle->ToAsciiVector(),
260 index))
261 : (seq_sub->IsAsciiRepresentation()
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000262 ? SearchString(isolate,
263 seq_sub->ToAsciiVector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000264 needle->ToUC16Vector(),
265 index)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000266 : SearchString(isolate,
267 seq_sub->ToUC16Vector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000268 needle->ToUC16Vector(),
269 index)));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000270 if (index == -1) return FACTORY->null_value();
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000271 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000272 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000273
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000274 {
275 NoHandleAllocation no_handles;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000276 FixedArray* array = FixedArray::cast(last_match_info->elements());
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000277 SetAtomLastCapture(array, *subject, index, index + needle_len);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000278 }
279 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000280}
281
282
ager@chromium.org8bb60582008-12-11 12:02:20 +0000283// Irregexp implementation.
284
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000285// Ensures that the regexp object contains a compiled version of the
286// source for either ASCII or non-ASCII strings.
287// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000288// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000289// If compilation fails, an exception is thrown and this function
290// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000291bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000292 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000293#ifdef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000294 if (compiled_code->IsByteArray()) return true;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000295#else // V8_INTERPRETED_REGEXP (RegExp native code)
296 if (compiled_code->IsCode()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000297#endif
298 return CompileIrregexp(re, is_ascii);
299}
ager@chromium.org8bb60582008-12-11 12:02:20 +0000300
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000301
302bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000303 // Compile the RegExp.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000304 Isolate* isolate = re->GetIsolate();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000305 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000306 PostponeInterruptsScope postpone(isolate);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000307 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
308 if (entry->IsJSObject()) {
309 // If it's a JSObject, a previous compilation failed and threw this object.
310 // Re-throw the object without trying again.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000311 isolate->Throw(entry);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000312 return false;
313 }
314 ASSERT(entry->IsTheHole());
ager@chromium.org8bb60582008-12-11 12:02:20 +0000315
316 JSRegExp::Flags flags = re->GetFlags();
317
318 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000319 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000320 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000321 }
322
323 RegExpCompileData compile_data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000324 FlatStringReader reader(isolate, pattern);
fschneider@chromium.orge03fb642010-11-01 12:34:09 +0000325 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
326 &compile_data)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000327 // Throw an exception if we fail to parse the pattern.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000328 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000329 ThrowRegExpException(re,
330 pattern,
331 compile_data.error,
332 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000333 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000334 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000335 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000336 RegExpEngine::Compile(&compile_data,
337 flags.is_ignore_case(),
338 flags.is_multiline(),
339 pattern,
340 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000341 if (result.error_message != NULL) {
342 // Unable to compile regexp.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000343 Factory* factory = isolate->factory();
344 Handle<FixedArray> elements = factory->NewFixedArray(2);
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000345 elements->set(0, *pattern);
346 Handle<String> error_message =
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000347 factory->NewStringFromUtf8(CStrVector(result.error_message));
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000348 elements->set(1, *error_message);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000349 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000350 Handle<Object> regexp_err =
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000351 factory->NewSyntaxError("malformed_regexp", array);
352 isolate->Throw(*regexp_err);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000353 re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000354 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000355 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000356
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000357 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
358 data->set(JSRegExp::code_index(is_ascii), result.code);
359 int register_max = IrregexpMaxRegisterCount(*data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000360 if (result.num_registers > register_max) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000361 SetIrregexpMaxRegisterCount(*data, result.num_registers);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000362 }
363
364 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000365}
366
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000367
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000368int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
369 return Smi::cast(
370 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000371}
372
373
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000374void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
375 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000376}
377
378
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000379int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
380 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000381}
382
383
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000384int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
385 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000386}
387
388
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000389ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000390 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000391}
392
393
394Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000395 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000396}
397
398
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000399void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
400 Handle<String> pattern,
401 JSRegExp::Flags flags,
402 int capture_count) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000403 // Initialize compiled code entries to null.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000404 re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
405 JSRegExp::IRREGEXP,
406 pattern,
407 flags,
408 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000409}
410
411
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000412int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
413 Handle<String> subject) {
414 if (!subject->IsFlat()) {
415 FlattenString(subject);
416 }
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000417 // Check the asciiness of the underlying storage.
418 bool is_ascii;
419 {
420 AssertNoAllocation no_gc;
421 String* sequential_string = *subject;
422 if (subject->IsConsString()) {
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000423 sequential_string = ConsString::cast(*subject)->first();
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000424 }
425 is_ascii = sequential_string->IsAsciiRepresentation();
426 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000427 if (!EnsureCompiledIrregexp(regexp, is_ascii)) {
428 return -1;
429 }
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000430#ifdef V8_INTERPRETED_REGEXP
431 // Byte-code regexp needs space allocated for all its registers.
432 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
433#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000434 // Native regexp only needs room to output captures. Registers are handled
435 // internally.
436 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000437#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000438}
439
440
erik.corry@gmail.com145eff52010-08-23 11:36:18 +0000441RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(
442 Handle<JSRegExp> regexp,
443 Handle<String> subject,
444 int index,
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000445 Vector<int> output) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000446 Isolate* isolate = regexp->GetIsolate();
447
448 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000449
450 ASSERT(index >= 0);
451 ASSERT(index <= subject->length());
452 ASSERT(subject->IsFlat());
453
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000454 // A flat ASCII string might have a two-byte first part.
455 if (subject->IsConsString()) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000456 subject = Handle<String>(ConsString::cast(*subject)->first(), isolate);
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000457 }
458
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000459#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000460 ASSERT(output.length() >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000461 do {
462 bool is_ascii = subject->IsAsciiRepresentation();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000463 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000464 NativeRegExpMacroAssembler::Result res =
465 NativeRegExpMacroAssembler::Match(code,
466 subject,
467 output.start(),
468 output.length(),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000469 index,
470 isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000471 if (res != NativeRegExpMacroAssembler::RETRY) {
472 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000473 isolate->has_pending_exception());
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000474 STATIC_ASSERT(
475 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
476 STATIC_ASSERT(
477 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
478 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
479 == RE_EXCEPTION);
480 return static_cast<IrregexpResult>(res);
481 }
482 // If result is RETRY, the string has changed representation, and we
483 // must restart from scratch.
484 // In this case, it means we must make sure we are prepared to handle
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000485 // the, potentially, different subject (the string can switch between
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000486 // being internal and external, and even between being ASCII and UC16,
487 // but the characters are always the same).
488 IrregexpPrepare(regexp, subject);
489 } while (true);
490 UNREACHABLE();
491 return RE_EXCEPTION;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000492#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000493
494 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
495 bool is_ascii = subject->IsAsciiRepresentation();
496 // We must have done EnsureCompiledIrregexp, so we can get the number of
497 // registers.
498 int* register_vector = output.start();
499 int number_of_capture_registers =
500 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
501 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
502 register_vector[i] = -1;
503 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000504 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000505
fschneider@chromium.org7979bbb2011-03-28 10:47:03 +0000506 if (IrregexpInterpreter::Match(isolate,
507 byte_codes,
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000508 subject,
509 register_vector,
510 index)) {
511 return RE_SUCCESS;
512 }
513 return RE_FAILURE;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000514#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000515}
516
517
ager@chromium.org41826e72009-03-30 13:30:57 +0000518Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000519 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000520 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000521 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000522 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000523
ager@chromium.org8bb60582008-12-11 12:02:20 +0000524 // Prepare space for the return values.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000525#ifdef V8_INTERPRETED_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000526#ifdef DEBUG
527 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000528 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000529 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
530 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
531 }
532#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000533#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000534 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
535 if (required_registers < 0) {
536 // Compiling failed with an exception.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000537 ASSERT(Isolate::Current()->has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000538 return Handle<Object>::null();
539 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000540
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000541 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000542
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000543 IrregexpResult res = RegExpImpl::IrregexpExecOnce(
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000544 jsregexp, subject, previous_index, Vector<int>(registers.vector(),
545 registers.length()));
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000546 if (res == RE_SUCCESS) {
547 int capture_register_count =
548 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
549 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
550 AssertNoAllocation no_gc;
551 int* register_vector = registers.vector();
552 FixedArray* array = FixedArray::cast(last_match_info->elements());
553 for (int i = 0; i < capture_register_count; i += 2) {
554 SetCapture(array, i, register_vector[i]);
555 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000556 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000557 SetLastCaptureCount(array, capture_register_count);
558 SetLastSubject(array, *subject);
559 SetLastInput(array, *subject);
560 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000561 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000562 if (res == RE_EXCEPTION) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000563 ASSERT(Isolate::Current()->has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000564 return Handle<Object>::null();
565 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000566 ASSERT(res == RE_FAILURE);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000567 return Isolate::Current()->factory()->null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000568}
569
570
571// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000572// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000573//
574// The Irregexp regular expression engine is intended to be a complete
575// implementation of ECMAScript regular expressions. It generates either
576// bytecodes or native code.
577
578// The Irregexp regexp engine is structured in three steps.
579// 1) The parser generates an abstract syntax tree. See ast.cc.
580// 2) From the AST a node network is created. The nodes are all
581// subclasses of RegExpNode. The nodes represent states when
582// executing a regular expression. Several optimizations are
583// performed on the node network.
584// 3) From the nodes we generate either byte codes or native code
585// that can actually execute the regular expression (perform
586// the search). The code generation step is described in more
587// detail below.
588
589// Code generation.
590//
591// The nodes are divided into four main categories.
592// * Choice nodes
593// These represent places where the regular expression can
594// match in more than one way. For example on entry to an
595// alternation (foo|bar) or a repetition (*, +, ? or {}).
596// * Action nodes
597// These represent places where some action should be
598// performed. Examples include recording the current position
599// in the input string to a register (in order to implement
600// captures) or other actions on register for example in order
601// to implement the counters needed for {} repetitions.
602// * Matching nodes
603// These attempt to match some element part of the input string.
604// Examples of elements include character classes, plain strings
605// or back references.
606// * End nodes
607// These are used to implement the actions required on finding
608// a successful match or failing to find a match.
609//
610// The code generated (whether as byte codes or native code) maintains
611// some state as it runs. This consists of the following elements:
612//
613// * The capture registers. Used for string captures.
614// * Other registers. Used for counters etc.
615// * The current position.
616// * The stack of backtracking information. Used when a matching node
617// fails to find a match and needs to try an alternative.
618//
619// Conceptual regular expression execution model:
620//
621// There is a simple conceptual model of regular expression execution
622// which will be presented first. The actual code generated is a more
623// efficient simulation of the simple conceptual model:
624//
625// * Choice nodes are implemented as follows:
626// For each choice except the last {
627// push current position
628// push backtrack code location
629// <generate code to test for choice>
630// backtrack code location:
631// pop current position
632// }
633// <generate code to test for last choice>
634//
635// * Actions nodes are generated as follows
636// <push affected registers on backtrack stack>
637// <generate code to perform action>
638// push backtrack code location
639// <generate code to test for following nodes>
640// backtrack code location:
641// <pop affected registers to restore their state>
642// <pop backtrack location from stack and go to it>
643//
644// * Matching nodes are generated as follows:
645// if input string matches at current position
646// update current position
647// <generate code to test for following nodes>
648// else
649// <pop backtrack location from stack and go to it>
650//
651// Thus it can be seen that the current position is saved and restored
652// by the choice nodes, whereas the registers are saved and restored by
653// by the action nodes that manipulate them.
654//
655// The other interesting aspect of this model is that nodes are generated
656// at the point where they are needed by a recursive call to Emit(). If
657// the node has already been code generated then the Emit() call will
658// generate a jump to the previously generated code instead. In order to
659// limit recursion it is possible for the Emit() function to put the node
660// on a work list for later generation and instead generate a jump. The
661// destination of the jump is resolved later when the code is generated.
662//
663// Actual regular expression code generation.
664//
665// Code generation is actually more complicated than the above. In order
666// to improve the efficiency of the generated code some optimizations are
667// performed
668//
669// * Choice nodes have 1-character lookahead.
670// A choice node looks at the following character and eliminates some of
671// the choices immediately based on that character. This is not yet
672// implemented.
673// * Simple greedy loops store reduced backtracking information.
674// A quantifier like /.*foo/m will greedily match the whole input. It will
675// then need to backtrack to a point where it can match "foo". The naive
676// implementation of this would push each character position onto the
677// backtracking stack, then pop them off one by one. This would use space
678// proportional to the length of the input string. However since the "."
679// can only match in one way and always has a constant length (in this case
680// of 1) it suffices to store the current position on the top of the stack
681// once. Matching now becomes merely incrementing the current position and
682// backtracking becomes decrementing the current position and checking the
683// result against the stored current position. This is faster and saves
684// space.
685// * The current state is virtualized.
686// This is used to defer expensive operations until it is clear that they
687// are needed and to generate code for a node more than once, allowing
688// specialized an efficient versions of the code to be created. This is
689// explained in the section below.
690//
691// Execution state virtualization.
692//
693// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000694// manipulation in an object called the Trace. The Trace object can record a
695// current position offset, an optional backtrack code location on the top of
696// the virtualized backtrack stack and some register changes. When a node is
697// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000698// will emit code to bring the actual state into line with the virtual state.
699// Avoiding flushing the state can postpone some work (eg updates of capture
700// registers). Postponing work can save time when executing the regular
701// expression since it may be found that the work never has to be done as a
702// failure to match can occur. In addition it is much faster to jump to a
703// known backtrack code location than it is to pop an unknown backtrack
704// location from the stack and jump there.
705//
ager@chromium.org32912102009-01-16 10:38:43 +0000706// The virtual state found in the Trace affects code generation. For example
707// the virtual state contains the difference between the actual current
708// position and the virtual current position, and matching code needs to use
709// this offset to attempt a match in the correct location of the input
710// string. Therefore code generated for a non-trivial trace is specialized
711// to that trace. The code generator therefore has the ability to generate
712// code for each node several times. In order to limit the size of the
713// generated code there is an arbitrary limit on how many specialized sets of
714// code may be generated for a given node. If the limit is reached, the
715// trace is flushed and a generic version of the code for a node is emitted.
716// This is subsequently used for that node. The code emitted for non-generic
717// trace is not recorded in the node and so it cannot currently be reused in
718// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000719
720
721void RegExpTree::AppendToText(RegExpText* text) {
722 UNREACHABLE();
723}
724
725
726void RegExpAtom::AppendToText(RegExpText* text) {
727 text->AddElement(TextElement::Atom(this));
728}
729
730
731void RegExpCharacterClass::AppendToText(RegExpText* text) {
732 text->AddElement(TextElement::CharClass(this));
733}
734
735
736void RegExpText::AppendToText(RegExpText* text) {
737 for (int i = 0; i < elements()->length(); i++)
738 text->AddElement(elements()->at(i));
739}
740
741
742TextElement TextElement::Atom(RegExpAtom* atom) {
743 TextElement result = TextElement(ATOM);
744 result.data.u_atom = atom;
745 return result;
746}
747
748
749TextElement TextElement::CharClass(
750 RegExpCharacterClass* char_class) {
751 TextElement result = TextElement(CHAR_CLASS);
752 result.data.u_char_class = char_class;
753 return result;
754}
755
756
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000757int TextElement::length() {
758 if (type == ATOM) {
759 return data.u_atom->length();
760 } else {
761 ASSERT(type == CHAR_CLASS);
762 return 1;
763 }
764}
765
766
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000767DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
768 if (table_ == NULL) {
769 table_ = new DispatchTable();
770 DispatchTableConstructor cons(table_, ignore_case);
771 cons.BuildTable(this);
772 }
773 return table_;
774}
775
776
777class RegExpCompiler {
778 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000779 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000780
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000781 int AllocateRegister() {
782 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
783 reg_exp_too_big_ = true;
784 return next_register_;
785 }
786 return next_register_++;
787 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000788
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000789 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
790 RegExpNode* start,
791 int capture_count,
792 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000793
794 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
795
796 static const int kImplementationOffset = 0;
797 static const int kNumberOfRegistersOffset = 0;
798 static const int kCodeOffset = 1;
799
800 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
801 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000802
803 static const int kMaxRecursion = 100;
804 inline int recursion_depth() { return recursion_depth_; }
805 inline void IncrementRecursionDepth() { recursion_depth_++; }
806 inline void DecrementRecursionDepth() { recursion_depth_--; }
807
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000808 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
809
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000810 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000811 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000812
ager@chromium.org32912102009-01-16 10:38:43 +0000813 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000814 private:
815 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000816 int next_register_;
817 List<RegExpNode*>* work_list_;
818 int recursion_depth_;
819 RegExpMacroAssembler* macro_assembler_;
820 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000821 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000822 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000823};
824
825
826class RecursionCheck {
827 public:
828 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
829 compiler->IncrementRecursionDepth();
830 }
831 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
832 private:
833 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000834};
835
836
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000837static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
838 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000839}
840
841
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000842// Attempts to compile the regexp using an Irregexp code generator. Returns
843// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000844RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000845 : next_register_(2 * (capture_count + 1)),
846 work_list_(NULL),
847 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000848 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000849 ascii_(ascii),
850 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000851 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000852 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000853}
854
855
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000856RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000857 RegExpMacroAssembler* macro_assembler,
858 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000859 int capture_count,
860 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000861#ifdef DEBUG
862 if (FLAG_trace_regexp_assembler)
863 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
864 else
865#endif
866 macro_assembler_ = macro_assembler;
867 List <RegExpNode*> work_list(0);
868 work_list_ = &work_list;
869 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000870 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000871 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000872 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000873 macro_assembler_->Bind(&fail);
874 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000875 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000876 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000877 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000878 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
879
ager@chromium.org8bb60582008-12-11 12:02:20 +0000880 Handle<Object> code = macro_assembler_->GetCode(pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000881 work_list_ = NULL;
882#ifdef DEBUG
danno@chromium.org4d3fe4e2011-03-10 10:14:28 +0000883 if (FLAG_print_code) {
884 Handle<Code>::cast(code)->Disassemble(*pattern->ToCString());
885 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000886 if (FLAG_trace_regexp_assembler) {
887 delete macro_assembler_;
888 }
889#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000890 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000891}
892
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000893
ager@chromium.org32912102009-01-16 10:38:43 +0000894bool Trace::DeferredAction::Mentions(int that) {
895 if (type() == ActionNode::CLEAR_CAPTURES) {
896 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
897 return range.Contains(that);
898 } else {
899 return reg() == that;
900 }
901}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000902
ager@chromium.org32912102009-01-16 10:38:43 +0000903
904bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000905 for (DeferredAction* action = actions_;
906 action != NULL;
907 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000908 if (action->Mentions(reg))
909 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000910 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000911 return false;
912}
913
914
ager@chromium.org32912102009-01-16 10:38:43 +0000915bool Trace::GetStoredPosition(int reg, int* cp_offset) {
916 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000917 for (DeferredAction* action = actions_;
918 action != NULL;
919 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000920 if (action->Mentions(reg)) {
921 if (action->type() == ActionNode::STORE_POSITION) {
922 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
923 return true;
924 } else {
925 return false;
926 }
927 }
928 }
929 return false;
930}
931
932
933int Trace::FindAffectedRegisters(OutSet* affected_registers) {
934 int max_register = RegExpCompiler::kNoRegister;
935 for (DeferredAction* action = actions_;
936 action != NULL;
937 action = action->next()) {
938 if (action->type() == ActionNode::CLEAR_CAPTURES) {
939 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
940 for (int i = range.from(); i <= range.to(); i++)
941 affected_registers->Set(i);
942 if (range.to() > max_register) max_register = range.to();
943 } else {
944 affected_registers->Set(action->reg());
945 if (action->reg() > max_register) max_register = action->reg();
946 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000947 }
948 return max_register;
949}
950
951
ager@chromium.org32912102009-01-16 10:38:43 +0000952void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
953 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000954 OutSet& registers_to_pop,
955 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000956 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000957 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
958 else if (registers_to_clear.Get(reg)) {
959 int clear_to = reg;
960 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
961 reg--;
962 }
963 assembler->ClearRegisters(reg, clear_to);
964 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000965 }
966}
967
968
ager@chromium.org32912102009-01-16 10:38:43 +0000969void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
970 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000971 OutSet& affected_registers,
972 OutSet* registers_to_pop,
973 OutSet* registers_to_clear) {
974 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
975 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
976
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000977 // Count pushes performed to force a stack limit check occasionally.
978 int pushes = 0;
979
ager@chromium.org8bb60582008-12-11 12:02:20 +0000980 for (int reg = 0; reg <= max_register; reg++) {
981 if (!affected_registers.Get(reg)) {
982 continue;
983 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000984
985 // The chronologically first deferred action in the trace
986 // is used to infer the action needed to restore a register
987 // to its previous state (or not, if it's safe to ignore it).
988 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
989 DeferredActionUndoType undo_action = IGNORE;
990
ager@chromium.org8bb60582008-12-11 12:02:20 +0000991 int value = 0;
992 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000993 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000994 int store_position = -1;
995 // This is a little tricky because we are scanning the actions in reverse
996 // historical order (newest first).
997 for (DeferredAction* action = actions_;
998 action != NULL;
999 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +00001000 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001001 switch (action->type()) {
1002 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00001003 Trace::DeferredSetRegister* psr =
1004 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001005 if (!absolute) {
1006 value += psr->value();
1007 absolute = true;
1008 }
1009 // SET_REGISTER is currently only used for newly introduced loop
1010 // counters. They can have a significant previous value if they
1011 // occour in a loop. TODO(lrn): Propagate this information, so
1012 // we can set undo_action to IGNORE if we know there is no value to
1013 // restore.
1014 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001015 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001016 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001017 break;
1018 }
1019 case ActionNode::INCREMENT_REGISTER:
1020 if (!absolute) {
1021 value++;
1022 }
1023 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001024 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001025 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001026 break;
1027 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00001028 Trace::DeferredCapture* pc =
1029 static_cast<Trace::DeferredCapture*>(action);
1030 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001031 store_position = pc->cp_offset();
1032 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001033
1034 // For captures we know that stores and clears alternate.
1035 // Other register, are never cleared, and if the occur
1036 // inside a loop, they might be assigned more than once.
1037 if (reg <= 1) {
1038 // Registers zero and one, aka "capture zero", is
1039 // always set correctly if we succeed. There is no
1040 // need to undo a setting on backtrack, because we
1041 // will set it again or fail.
1042 undo_action = IGNORE;
1043 } else {
1044 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1045 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001046 ASSERT(!absolute);
1047 ASSERT_EQ(value, 0);
1048 break;
1049 }
ager@chromium.org32912102009-01-16 10:38:43 +00001050 case ActionNode::CLEAR_CAPTURES: {
1051 // Since we're scanning in reverse order, if we've already
1052 // set the position we have to ignore historically earlier
1053 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001054 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +00001055 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001056 }
1057 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +00001058 ASSERT(!absolute);
1059 ASSERT_EQ(value, 0);
1060 break;
1061 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001062 default:
1063 UNREACHABLE();
1064 break;
1065 }
1066 }
1067 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001068 // Prepare for the undo-action (e.g., push if it's going to be popped).
1069 if (undo_action == RESTORE) {
1070 pushes++;
1071 RegExpMacroAssembler::StackCheckFlag stack_check =
1072 RegExpMacroAssembler::kNoStackLimitCheck;
1073 if (pushes == push_limit) {
1074 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1075 pushes = 0;
1076 }
1077
1078 assembler->PushRegister(reg, stack_check);
1079 registers_to_pop->Set(reg);
1080 } else if (undo_action == CLEAR) {
1081 registers_to_clear->Set(reg);
1082 }
1083 // Perform the chronologically last action (or accumulated increment)
1084 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001085 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001086 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001087 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001088 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001089 } else if (absolute) {
1090 assembler->SetRegister(reg, value);
1091 } else if (value != 0) {
1092 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001093 }
1094 }
1095}
1096
1097
ager@chromium.org8bb60582008-12-11 12:02:20 +00001098// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001099// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001100// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001101void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001102 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001103
iposva@chromium.org245aa852009-02-10 00:49:54 +00001104 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001105
1106 if (actions_ == NULL && backtrack() == NULL) {
1107 // 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 +00001108 // a normal situation. We may also have to forget some information gained
1109 // through a quick check that was already performed.
1110 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001111 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001112 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001113 successor->Emit(compiler, &new_state);
1114 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001115 }
1116
1117 // Generate deferred actions here along with code to undo them again.
1118 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001119
ager@chromium.org381abbb2009-02-25 13:23:22 +00001120 if (backtrack() != NULL) {
1121 // Here we have a concrete backtrack location. These are set up by choice
1122 // nodes and so they indicate that we have a deferred save of the current
1123 // position which we may need to emit here.
1124 assembler->PushCurrentPosition();
1125 }
1126
ager@chromium.org8bb60582008-12-11 12:02:20 +00001127 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001128 OutSet registers_to_pop;
1129 OutSet registers_to_clear;
1130 PerformDeferredActions(assembler,
1131 max_register,
1132 affected_registers,
1133 &registers_to_pop,
1134 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001135 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001136 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001137 }
1138
1139 // Create a new trivial state and generate the node with that.
1140 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001141 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001142 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001143 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001144
1145 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001146 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001147 RestoreAffectedRegisters(assembler,
1148 max_register,
1149 registers_to_pop,
1150 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001151 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001152 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001153 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001154 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001155 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001156 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001157}
1158
1159
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001160void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001161 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001162
1163 // Omit flushing the trace. We discard the entire stack frame anyway.
1164
ager@chromium.org8bb60582008-12-11 12:02:20 +00001165 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001166 // We are completely independent of the trace, since we ignore it,
1167 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001168 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001169 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001170
1171 // Throw away everything on the backtrack stack since the start
1172 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001173 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1174 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001175 if (clear_capture_count_ > 0) {
1176 // Clear any captures that might have been performed during the success
1177 // of the body of the negative look-ahead.
1178 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1179 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1180 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001181 // Now that we have unwound the stack we find at the top of the stack the
1182 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001183 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001184}
1185
1186
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001187void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001188 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001189 trace->Flush(compiler, this);
1190 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001191 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001192 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001193 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001194 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001195 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001196 switch (action_) {
1197 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001198 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001199 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001200 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001201 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001202 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001203 case NEGATIVE_SUBMATCH_SUCCESS:
1204 // This case is handled in a different virtual method.
1205 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001206 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001207 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001208}
1209
1210
1211void GuardedAlternative::AddGuard(Guard* guard) {
1212 if (guards_ == NULL)
1213 guards_ = new ZoneList<Guard*>(1);
1214 guards_->Add(guard);
1215}
1216
1217
ager@chromium.org8bb60582008-12-11 12:02:20 +00001218ActionNode* ActionNode::SetRegister(int reg,
1219 int val,
1220 RegExpNode* on_success) {
1221 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001222 result->data_.u_store_register.reg = reg;
1223 result->data_.u_store_register.value = val;
1224 return result;
1225}
1226
1227
1228ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1229 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1230 result->data_.u_increment_register.reg = reg;
1231 return result;
1232}
1233
1234
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001235ActionNode* ActionNode::StorePosition(int reg,
1236 bool is_capture,
1237 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001238 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1239 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001240 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001241 return result;
1242}
1243
1244
ager@chromium.org32912102009-01-16 10:38:43 +00001245ActionNode* ActionNode::ClearCaptures(Interval range,
1246 RegExpNode* on_success) {
1247 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1248 result->data_.u_clear_captures.range_from = range.from();
1249 result->data_.u_clear_captures.range_to = range.to();
1250 return result;
1251}
1252
1253
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001254ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1255 int position_reg,
1256 RegExpNode* on_success) {
1257 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1258 result->data_.u_submatch.stack_pointer_register = stack_reg;
1259 result->data_.u_submatch.current_position_register = position_reg;
1260 return result;
1261}
1262
1263
ager@chromium.org8bb60582008-12-11 12:02:20 +00001264ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1265 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001266 int clear_register_count,
1267 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001268 RegExpNode* on_success) {
1269 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001270 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001271 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001272 result->data_.u_submatch.clear_register_count = clear_register_count;
1273 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001274 return result;
1275}
1276
1277
ager@chromium.org32912102009-01-16 10:38:43 +00001278ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1279 int repetition_register,
1280 int repetition_limit,
1281 RegExpNode* on_success) {
1282 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1283 result->data_.u_empty_match_check.start_register = start_register;
1284 result->data_.u_empty_match_check.repetition_register = repetition_register;
1285 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1286 return result;
1287}
1288
1289
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001290#define DEFINE_ACCEPT(Type) \
1291 void Type##Node::Accept(NodeVisitor* visitor) { \
1292 visitor->Visit##Type(this); \
1293 }
1294FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1295#undef DEFINE_ACCEPT
1296
1297
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001298void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1299 visitor->VisitLoopChoice(this);
1300}
1301
1302
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001303// -------------------------------------------------------------------
1304// Emit code.
1305
1306
1307void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1308 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001309 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001310 switch (guard->op()) {
1311 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001312 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001313 macro_assembler->IfRegisterGE(guard->reg(),
1314 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001315 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001316 break;
1317 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001318 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001319 macro_assembler->IfRegisterLT(guard->reg(),
1320 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001321 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001322 break;
1323 }
1324}
1325
1326
ager@chromium.org381abbb2009-02-25 13:23:22 +00001327// Returns the number of characters in the equivalence class, omitting those
1328// that cannot occur in the source string because it is ASCII.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001329static int GetCaseIndependentLetters(Isolate* isolate,
1330 uc16 character,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001331 bool ascii_subject,
1332 unibrow::uchar* letters) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001333 int length =
1334 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00001335 // Unibrow returns 0 or 1 for characters where case independence is
ager@chromium.org381abbb2009-02-25 13:23:22 +00001336 // trivial.
1337 if (length == 0) {
1338 letters[0] = character;
1339 length = 1;
1340 }
1341 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1342 return length;
1343 }
1344 // The standard requires that non-ASCII characters cannot have ASCII
1345 // character codes in their equivalence class.
1346 return 0;
1347}
1348
1349
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001350static inline bool EmitSimpleCharacter(Isolate* isolate,
1351 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001352 uc16 c,
1353 Label* on_failure,
1354 int cp_offset,
1355 bool check,
1356 bool preloaded) {
1357 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1358 bool bound_checked = false;
1359 if (!preloaded) {
1360 assembler->LoadCurrentCharacter(
1361 cp_offset,
1362 on_failure,
1363 check);
1364 bound_checked = true;
1365 }
1366 assembler->CheckNotCharacter(c, on_failure);
1367 return bound_checked;
1368}
1369
1370
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001371// Only emits non-letters (things that don't have case). Only used for case
1372// independent matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001373static inline bool EmitAtomNonLetter(Isolate* isolate,
1374 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001375 uc16 c,
1376 Label* on_failure,
1377 int cp_offset,
1378 bool check,
1379 bool preloaded) {
1380 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1381 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001382 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001383 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001384 if (length < 1) {
1385 // This can't match. Must be an ASCII subject and a non-ASCII character.
1386 // We do not need to do anything since the ASCII pass already handled this.
1387 return false; // Bounds not checked.
1388 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001389 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001390 // We handle the length > 1 case in a later pass.
1391 if (length == 1) {
1392 if (ascii && c > String::kMaxAsciiCharCodeU) {
1393 // Can't match - see above.
1394 return false; // Bounds not checked.
1395 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001396 if (!preloaded) {
1397 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1398 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001399 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001400 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001401 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001402 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001403}
1404
1405
1406static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001407 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001408 uc16 c1,
1409 uc16 c2,
1410 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001411 uc16 char_mask;
1412 if (ascii) {
1413 char_mask = String::kMaxAsciiCharCode;
1414 } else {
1415 char_mask = String::kMaxUC16CharCode;
1416 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001417 uc16 exor = c1 ^ c2;
1418 // Check whether exor has only one bit set.
1419 if (((exor - 1) & exor) == 0) {
1420 // If c1 and c2 differ only by one bit.
1421 // Ecma262UnCanonicalize always gives the highest number last.
1422 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001423 uc16 mask = char_mask ^ exor;
1424 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001425 return true;
1426 }
1427 ASSERT(c2 > c1);
1428 uc16 diff = c2 - c1;
1429 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1430 // If the characters differ by 2^n but don't differ by one bit then
1431 // subtract the difference from the found character, then do the or
1432 // trick. We avoid the theoretical case where negative numbers are
1433 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001434 uc16 mask = char_mask ^ diff;
1435 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1436 diff,
1437 mask,
1438 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001439 return true;
1440 }
1441 return false;
1442}
1443
1444
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001445typedef bool EmitCharacterFunction(Isolate* isolate,
1446 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001447 uc16 c,
1448 Label* on_failure,
1449 int cp_offset,
1450 bool check,
1451 bool preloaded);
1452
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001453// Only emits letters (things that have case). Only used for case independent
1454// matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001455static inline bool EmitAtomLetter(Isolate* isolate,
1456 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001457 uc16 c,
1458 Label* on_failure,
1459 int cp_offset,
1460 bool check,
1461 bool preloaded) {
1462 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1463 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001464 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001465 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001466 if (length <= 1) return false;
1467 // We may not need to check against the end of the input string
1468 // if this character lies before a character that matched.
1469 if (!preloaded) {
1470 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001471 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001472 Label ok;
1473 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1474 switch (length) {
1475 case 2: {
1476 if (ShortCutEmitCharacterPair(macro_assembler,
1477 ascii,
1478 chars[0],
1479 chars[1],
1480 on_failure)) {
1481 } else {
1482 macro_assembler->CheckCharacter(chars[0], &ok);
1483 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1484 macro_assembler->Bind(&ok);
1485 }
1486 break;
1487 }
1488 case 4:
1489 macro_assembler->CheckCharacter(chars[3], &ok);
1490 // Fall through!
1491 case 3:
1492 macro_assembler->CheckCharacter(chars[0], &ok);
1493 macro_assembler->CheckCharacter(chars[1], &ok);
1494 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1495 macro_assembler->Bind(&ok);
1496 break;
1497 default:
1498 UNREACHABLE();
1499 break;
1500 }
1501 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001502}
1503
1504
1505static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1506 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001507 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001508 Label* on_failure,
1509 int cp_offset,
1510 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001511 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001512 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001513 int max_char;
1514 if (ascii) {
1515 max_char = String::kMaxAsciiCharCode;
1516 } else {
1517 max_char = String::kMaxUC16CharCode;
1518 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001519
1520 Label success;
1521
1522 Label* char_is_in_class =
1523 cc->is_negated() ? on_failure : &success;
1524
1525 int range_count = ranges->length();
1526
ager@chromium.org8bb60582008-12-11 12:02:20 +00001527 int last_valid_range = range_count - 1;
1528 while (last_valid_range >= 0) {
1529 CharacterRange& range = ranges->at(last_valid_range);
1530 if (range.from() <= max_char) {
1531 break;
1532 }
1533 last_valid_range--;
1534 }
1535
1536 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001537 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001538 // TODO(plesner): We can remove this when the node level does our
1539 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001540 macro_assembler->GoTo(on_failure);
1541 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001542 if (check_offset) {
1543 macro_assembler->CheckPosition(cp_offset, on_failure);
1544 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001545 return;
1546 }
1547
ager@chromium.org8bb60582008-12-11 12:02:20 +00001548 if (last_valid_range == 0 &&
1549 !cc->is_negated() &&
1550 ranges->at(0).IsEverything(max_char)) {
1551 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001552 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001553 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001554 }
1555 return;
1556 }
1557
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001558 if (!preloaded) {
1559 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001560 }
1561
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001562 if (cc->is_standard() &&
1563 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1564 on_failure)) {
1565 return;
1566 }
1567
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001568 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001569 CharacterRange& range = ranges->at(i);
1570 Label next_range;
1571 uc16 from = range.from();
1572 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001573 if (from > max_char) {
1574 continue;
1575 }
1576 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001577 if (to == from) {
1578 macro_assembler->CheckCharacter(to, char_is_in_class);
1579 } else {
1580 if (from != 0) {
1581 macro_assembler->CheckCharacterLT(from, &next_range);
1582 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001583 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001584 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1585 } else {
1586 macro_assembler->GoTo(char_is_in_class);
1587 }
1588 }
1589 macro_assembler->Bind(&next_range);
1590 }
1591
ager@chromium.org8bb60582008-12-11 12:02:20 +00001592 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001593 uc16 from = range.from();
1594 uc16 to = range.to();
1595
ager@chromium.org8bb60582008-12-11 12:02:20 +00001596 if (to > max_char) to = max_char;
1597 ASSERT(to >= from);
1598
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001599 if (to == from) {
1600 if (cc->is_negated()) {
1601 macro_assembler->CheckCharacter(to, on_failure);
1602 } else {
1603 macro_assembler->CheckNotCharacter(to, on_failure);
1604 }
1605 } else {
1606 if (from != 0) {
1607 if (cc->is_negated()) {
1608 macro_assembler->CheckCharacterLT(from, &success);
1609 } else {
1610 macro_assembler->CheckCharacterLT(from, on_failure);
1611 }
1612 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001613 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001614 if (cc->is_negated()) {
1615 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1616 } else {
1617 macro_assembler->CheckCharacterGT(to, on_failure);
1618 }
1619 } else {
1620 if (cc->is_negated()) {
1621 macro_assembler->GoTo(on_failure);
1622 }
1623 }
1624 }
1625 macro_assembler->Bind(&success);
1626}
1627
1628
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001629RegExpNode::~RegExpNode() {
1630}
1631
1632
ager@chromium.org8bb60582008-12-11 12:02:20 +00001633RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001634 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001635 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001636 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001637 return CONTINUE;
1638 }
1639
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001640 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001641 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001642 if (label_.is_bound()) {
1643 // We are being asked to generate a generic version, but that's already
1644 // been done so just go to it.
1645 macro_assembler->GoTo(&label_);
1646 return DONE;
1647 }
1648 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1649 // To avoid too deep recursion we push the node to the work queue and just
1650 // generate a goto here.
1651 compiler->AddWork(this);
1652 macro_assembler->GoTo(&label_);
1653 return DONE;
1654 }
1655 // Generate generic version of the node and bind the label for later use.
1656 macro_assembler->Bind(&label_);
1657 return CONTINUE;
1658 }
1659
1660 // We are being asked to make a non-generic version. Keep track of how many
1661 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001662 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001663 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001664 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001665 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1666 return CONTINUE;
1667 }
1668
ager@chromium.org32912102009-01-16 10:38:43 +00001669 // If we get here code has been generated for this node too many times or
1670 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001671 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001672 trace->Flush(compiler, this);
1673 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001674}
1675
1676
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001677int ActionNode::EatsAtLeast(int still_to_find,
1678 int recursion_depth,
1679 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001680 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1681 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001682 return on_success()->EatsAtLeast(still_to_find,
1683 recursion_depth + 1,
1684 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001685}
1686
1687
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001688int AssertionNode::EatsAtLeast(int still_to_find,
1689 int recursion_depth,
1690 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001691 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001692 // If we know we are not at the start and we are asked "how many characters
1693 // will you match if you succeed?" then we can answer anything since false
1694 // implies false. So lets just return the max answer (still_to_find) since
1695 // that won't prevent us from preloading a lot of characters for the other
1696 // branches in the node graph.
1697 if (type() == AT_START && not_at_start) return still_to_find;
1698 return on_success()->EatsAtLeast(still_to_find,
1699 recursion_depth + 1,
1700 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001701}
1702
1703
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001704int BackReferenceNode::EatsAtLeast(int still_to_find,
1705 int recursion_depth,
1706 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001707 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001708 return on_success()->EatsAtLeast(still_to_find,
1709 recursion_depth + 1,
1710 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001711}
1712
1713
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001714int TextNode::EatsAtLeast(int still_to_find,
1715 int recursion_depth,
1716 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001717 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001718 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001719 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001720 // We are not at start after this node so we set the last argument to 'true'.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001721 return answer + on_success()->EatsAtLeast(still_to_find - answer,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001722 recursion_depth + 1,
1723 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001724}
1725
1726
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001727int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001728 int recursion_depth,
1729 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001730 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1731 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1732 // afterwards.
1733 RegExpNode* node = alternatives_->at(1).node();
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001734 return node->EatsAtLeast(still_to_find, recursion_depth + 1, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001735}
1736
1737
1738void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1739 QuickCheckDetails* details,
1740 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001741 int filled_in,
1742 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001743 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1744 // afterwards.
1745 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001746 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001747}
1748
1749
1750int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1751 int recursion_depth,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001752 RegExpNode* ignore_this_node,
1753 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001754 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1755 int min = 100;
1756 int choice_count = alternatives_->length();
1757 for (int i = 0; i < choice_count; i++) {
1758 RegExpNode* node = alternatives_->at(i).node();
1759 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001760 int node_eats_at_least = node->EatsAtLeast(still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001761 recursion_depth + 1,
1762 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001763 if (node_eats_at_least < min) min = node_eats_at_least;
1764 }
1765 return min;
1766}
1767
1768
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001769int LoopChoiceNode::EatsAtLeast(int still_to_find,
1770 int recursion_depth,
1771 bool not_at_start) {
1772 return EatsAtLeastHelper(still_to_find,
1773 recursion_depth,
1774 loop_node_,
1775 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001776}
1777
1778
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001779int ChoiceNode::EatsAtLeast(int still_to_find,
1780 int recursion_depth,
1781 bool not_at_start) {
1782 return EatsAtLeastHelper(still_to_find,
1783 recursion_depth,
1784 NULL,
1785 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001786}
1787
1788
1789// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1790static inline uint32_t SmearBitsRight(uint32_t v) {
1791 v |= v >> 1;
1792 v |= v >> 2;
1793 v |= v >> 4;
1794 v |= v >> 8;
1795 v |= v >> 16;
1796 return v;
1797}
1798
1799
1800bool QuickCheckDetails::Rationalize(bool asc) {
1801 bool found_useful_op = false;
1802 uint32_t char_mask;
1803 if (asc) {
1804 char_mask = String::kMaxAsciiCharCode;
1805 } else {
1806 char_mask = String::kMaxUC16CharCode;
1807 }
1808 mask_ = 0;
1809 value_ = 0;
1810 int char_shift = 0;
1811 for (int i = 0; i < characters_; i++) {
1812 Position* pos = &positions_[i];
1813 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1814 found_useful_op = true;
1815 }
1816 mask_ |= (pos->mask & char_mask) << char_shift;
1817 value_ |= (pos->value & char_mask) << char_shift;
1818 char_shift += asc ? 8 : 16;
1819 }
1820 return found_useful_op;
1821}
1822
1823
1824bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001825 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001826 bool preload_has_checked_bounds,
1827 Label* on_possible_success,
1828 QuickCheckDetails* details,
1829 bool fall_through_on_failure) {
1830 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001831 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1832 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001833 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001834 ASSERT(details->characters() == 1 ||
1835 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001836 uint32_t mask = details->mask();
1837 uint32_t value = details->value();
1838
1839 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1840
ager@chromium.org32912102009-01-16 10:38:43 +00001841 if (trace->characters_preloaded() != details->characters()) {
1842 assembler->LoadCurrentCharacter(trace->cp_offset(),
1843 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001844 !preload_has_checked_bounds,
1845 details->characters());
1846 }
1847
1848
1849 bool need_mask = true;
1850
1851 if (details->characters() == 1) {
1852 // If number of characters preloaded is 1 then we used a byte or 16 bit
1853 // load so the value is already masked down.
1854 uint32_t char_mask;
1855 if (compiler->ascii()) {
1856 char_mask = String::kMaxAsciiCharCode;
1857 } else {
1858 char_mask = String::kMaxUC16CharCode;
1859 }
1860 if ((mask & char_mask) == char_mask) need_mask = false;
1861 mask &= char_mask;
1862 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001863 // For 2-character preloads in ASCII mode or 1-character preloads in
1864 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001865 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001866 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1867 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001868 if ((mask & 0xffff) == 0xffff) need_mask = false;
1869 } else {
1870 if (mask == 0xffffffff) need_mask = false;
1871 }
1872 }
1873
1874 if (fall_through_on_failure) {
1875 if (need_mask) {
1876 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1877 } else {
1878 assembler->CheckCharacter(value, on_possible_success);
1879 }
1880 } else {
1881 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001882 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001883 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001884 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001885 }
1886 }
1887 return true;
1888}
1889
1890
1891// Here is the meat of GetQuickCheckDetails (see also the comment on the
1892// super-class in the .h file).
1893//
1894// We iterate along the text object, building up for each character a
1895// mask and value that can be used to test for a quick failure to match.
1896// The masks and values for the positions will be combined into a single
1897// machine word for the current character width in order to be used in
1898// generating a quick check.
1899void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1900 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001901 int characters_filled_in,
1902 bool not_at_start) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001903 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001904 ASSERT(characters_filled_in < details->characters());
1905 int characters = details->characters();
1906 int char_mask;
1907 int char_shift;
1908 if (compiler->ascii()) {
1909 char_mask = String::kMaxAsciiCharCode;
1910 char_shift = 8;
1911 } else {
1912 char_mask = String::kMaxUC16CharCode;
1913 char_shift = 16;
1914 }
1915 for (int k = 0; k < elms_->length(); k++) {
1916 TextElement elm = elms_->at(k);
1917 if (elm.type == TextElement::ATOM) {
1918 Vector<const uc16> quarks = elm.data.u_atom->data();
1919 for (int i = 0; i < characters && i < quarks.length(); i++) {
1920 QuickCheckDetails::Position* pos =
1921 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001922 uc16 c = quarks[i];
1923 if (c > char_mask) {
1924 // If we expect a non-ASCII character from an ASCII string,
1925 // there is no way we can match. Not even case independent
1926 // matching can turn an ASCII character into non-ASCII or
1927 // vice versa.
1928 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001929 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001930 return;
1931 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001932 if (compiler->ignore_case()) {
1933 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001934 int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
1935 chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001936 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1937 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001938 // This letter has no case equivalents, so it's nice and simple
1939 // and the mask-compare will determine definitely whether we have
1940 // a match at this character position.
1941 pos->mask = char_mask;
1942 pos->value = c;
1943 pos->determines_perfectly = true;
1944 } else {
1945 uint32_t common_bits = char_mask;
1946 uint32_t bits = chars[0];
1947 for (int j = 1; j < length; j++) {
1948 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1949 common_bits ^= differing_bits;
1950 bits &= common_bits;
1951 }
1952 // If length is 2 and common bits has only one zero in it then
1953 // our mask and compare instruction will determine definitely
1954 // whether we have a match at this character position. Otherwise
1955 // it can only be an approximate check.
1956 uint32_t one_zero = (common_bits | ~char_mask);
1957 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1958 pos->determines_perfectly = true;
1959 }
1960 pos->mask = common_bits;
1961 pos->value = bits;
1962 }
1963 } else {
1964 // Don't ignore case. Nice simple case where the mask-compare will
1965 // determine definitely whether we have a match at this character
1966 // position.
1967 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001968 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001969 pos->determines_perfectly = true;
1970 }
1971 characters_filled_in++;
1972 ASSERT(characters_filled_in <= details->characters());
1973 if (characters_filled_in == details->characters()) {
1974 return;
1975 }
1976 }
1977 } else {
1978 QuickCheckDetails::Position* pos =
1979 details->positions(characters_filled_in);
1980 RegExpCharacterClass* tree = elm.data.u_char_class;
1981 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001982 if (tree->is_negated()) {
1983 // A quick check uses multi-character mask and compare. There is no
1984 // useful way to incorporate a negative char class into this scheme
1985 // so we just conservatively create a mask and value that will always
1986 // succeed.
1987 pos->mask = 0;
1988 pos->value = 0;
1989 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001990 int first_range = 0;
1991 while (ranges->at(first_range).from() > char_mask) {
1992 first_range++;
1993 if (first_range == ranges->length()) {
1994 details->set_cannot_match();
1995 pos->determines_perfectly = false;
1996 return;
1997 }
1998 }
1999 CharacterRange range = ranges->at(first_range);
2000 uc16 from = range.from();
2001 uc16 to = range.to();
2002 if (to > char_mask) {
2003 to = char_mask;
2004 }
2005 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002006 // A mask and compare is only perfect if the differing bits form a
2007 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002008 if ((differing_bits & (differing_bits + 1)) == 0 &&
2009 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002010 pos->determines_perfectly = true;
2011 }
2012 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002013 uint32_t bits = (from & common_bits);
2014 for (int i = first_range + 1; i < ranges->length(); i++) {
2015 CharacterRange range = ranges->at(i);
2016 uc16 from = range.from();
2017 uc16 to = range.to();
2018 if (from > char_mask) continue;
2019 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002020 // Here we are combining more ranges into the mask and compare
2021 // value. With each new range the mask becomes more sparse and
2022 // so the chances of a false positive rise. A character class
2023 // with multiple ranges is assumed never to be equivalent to a
2024 // mask and compare operation.
2025 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002026 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002027 new_common_bits = ~SmearBitsRight(new_common_bits);
2028 common_bits &= new_common_bits;
2029 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002030 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002031 common_bits ^= differing_bits;
2032 bits &= common_bits;
2033 }
2034 pos->mask = common_bits;
2035 pos->value = bits;
2036 }
2037 characters_filled_in++;
2038 ASSERT(characters_filled_in <= details->characters());
2039 if (characters_filled_in == details->characters()) {
2040 return;
2041 }
2042 }
2043 }
2044 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00002045 on_success()-> GetQuickCheckDetails(details,
2046 compiler,
2047 characters_filled_in,
2048 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002049}
2050
2051
2052void QuickCheckDetails::Clear() {
2053 for (int i = 0; i < characters_; i++) {
2054 positions_[i].mask = 0;
2055 positions_[i].value = 0;
2056 positions_[i].determines_perfectly = false;
2057 }
2058 characters_ = 0;
2059}
2060
2061
2062void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002063 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002064 if (by >= characters_) {
2065 Clear();
2066 return;
2067 }
2068 for (int i = 0; i < characters_ - by; i++) {
2069 positions_[i] = positions_[by + i];
2070 }
2071 for (int i = characters_ - by; i < characters_; i++) {
2072 positions_[i].mask = 0;
2073 positions_[i].value = 0;
2074 positions_[i].determines_perfectly = false;
2075 }
2076 characters_ -= by;
2077 // We could change mask_ and value_ here but we would never advance unless
2078 // they had already been used in a check and they won't be used again because
2079 // it would gain us nothing. So there's no point.
2080}
2081
2082
2083void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2084 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002085 if (other->cannot_match_) {
2086 return;
2087 }
2088 if (cannot_match_) {
2089 *this = *other;
2090 return;
2091 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002092 for (int i = from_index; i < characters_; i++) {
2093 QuickCheckDetails::Position* pos = positions(i);
2094 QuickCheckDetails::Position* other_pos = other->positions(i);
2095 if (pos->mask != other_pos->mask ||
2096 pos->value != other_pos->value ||
2097 !other_pos->determines_perfectly) {
2098 // Our mask-compare operation will be approximate unless we have the
2099 // exact same operation on both sides of the alternation.
2100 pos->determines_perfectly = false;
2101 }
2102 pos->mask &= other_pos->mask;
2103 pos->value &= pos->mask;
2104 other_pos->value &= pos->mask;
2105 uc16 differing_bits = (pos->value ^ other_pos->value);
2106 pos->mask &= ~differing_bits;
2107 pos->value &= pos->mask;
2108 }
2109}
2110
2111
ager@chromium.org32912102009-01-16 10:38:43 +00002112class VisitMarker {
2113 public:
2114 explicit VisitMarker(NodeInfo* info) : info_(info) {
2115 ASSERT(!info->visited);
2116 info->visited = true;
2117 }
2118 ~VisitMarker() {
2119 info_->visited = false;
2120 }
2121 private:
2122 NodeInfo* info_;
2123};
2124
2125
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002126void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2127 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002128 int characters_filled_in,
2129 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002130 if (body_can_be_zero_length_ || info()->visited) return;
2131 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002132 return ChoiceNode::GetQuickCheckDetails(details,
2133 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002134 characters_filled_in,
2135 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002136}
2137
2138
2139void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2140 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002141 int characters_filled_in,
2142 bool not_at_start) {
2143 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002144 int choice_count = alternatives_->length();
2145 ASSERT(choice_count > 0);
2146 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2147 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002148 characters_filled_in,
2149 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002150 for (int i = 1; i < choice_count; i++) {
2151 QuickCheckDetails new_details(details->characters());
2152 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002153 node->GetQuickCheckDetails(&new_details, compiler,
2154 characters_filled_in,
2155 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002156 // Here we merge the quick match details of the two branches.
2157 details->Merge(&new_details, characters_filled_in);
2158 }
2159}
2160
2161
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002162// Check for [0-9A-Z_a-z].
2163static void EmitWordCheck(RegExpMacroAssembler* assembler,
2164 Label* word,
2165 Label* non_word,
2166 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002167 if (assembler->CheckSpecialCharacterClass(
2168 fall_through_on_word ? 'w' : 'W',
2169 fall_through_on_word ? non_word : word)) {
2170 // Optimized implementation available.
2171 return;
2172 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002173 assembler->CheckCharacterGT('z', non_word);
2174 assembler->CheckCharacterLT('0', non_word);
2175 assembler->CheckCharacterGT('a' - 1, word);
2176 assembler->CheckCharacterLT('9' + 1, word);
2177 assembler->CheckCharacterLT('A', non_word);
2178 assembler->CheckCharacterLT('Z' + 1, word);
2179 if (fall_through_on_word) {
2180 assembler->CheckNotCharacter('_', non_word);
2181 } else {
2182 assembler->CheckCharacter('_', word);
2183 }
2184}
2185
2186
2187// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2188// that matches newline or the start of input).
2189static void EmitHat(RegExpCompiler* compiler,
2190 RegExpNode* on_success,
2191 Trace* trace) {
2192 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2193 // We will be loading the previous character into the current character
2194 // register.
2195 Trace new_trace(*trace);
2196 new_trace.InvalidateCurrentCharacter();
2197
2198 Label ok;
2199 if (new_trace.cp_offset() == 0) {
2200 // The start of input counts as a newline in this context, so skip to
2201 // ok if we are at the start.
2202 assembler->CheckAtStart(&ok);
2203 }
2204 // We already checked that we are not at the start of input so it must be
2205 // OK to load the previous character.
2206 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2207 new_trace.backtrack(),
2208 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002209 if (!assembler->CheckSpecialCharacterClass('n',
2210 new_trace.backtrack())) {
2211 // Newline means \n, \r, 0x2028 or 0x2029.
2212 if (!compiler->ascii()) {
2213 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2214 }
2215 assembler->CheckCharacter('\n', &ok);
2216 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002217 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002218 assembler->Bind(&ok);
2219 on_success->Emit(compiler, &new_trace);
2220}
2221
2222
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002223// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2224// when we know whether the next character must be a word character or not.
2225static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2226 RegExpCompiler* compiler,
2227 RegExpNode* on_success,
2228 Trace* trace) {
2229 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2230 Label done;
2231
2232 Trace new_trace(*trace);
2233
2234 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2235 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2236 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2237
2238 // Check whether previous character was a word character.
2239 switch (trace->at_start()) {
2240 case Trace::TRUE:
2241 if (expect_word_character) {
2242 assembler->GoTo(on_non_word);
2243 }
2244 break;
2245 case Trace::UNKNOWN:
2246 ASSERT_EQ(0, trace->cp_offset());
2247 assembler->CheckAtStart(on_non_word);
2248 // Fall through.
2249 case Trace::FALSE:
2250 int prev_char_offset = trace->cp_offset() - 1;
2251 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2252 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2253 // We may or may not have loaded the previous character.
2254 new_trace.InvalidateCurrentCharacter();
2255 }
2256
2257 assembler->Bind(&done);
2258
2259 on_success->Emit(compiler, &new_trace);
2260}
2261
2262
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002263// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2264static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2265 RegExpCompiler* compiler,
2266 RegExpNode* on_success,
2267 Trace* trace) {
2268 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2269 Label before_non_word;
2270 Label before_word;
2271 if (trace->characters_preloaded() != 1) {
2272 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2273 }
2274 // Fall through on non-word.
2275 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2276
2277 // We will be loading the previous character into the current character
2278 // register.
2279 Trace new_trace(*trace);
2280 new_trace.InvalidateCurrentCharacter();
2281
2282 Label ok;
2283 Label* boundary;
2284 Label* not_boundary;
2285 if (type == AssertionNode::AT_BOUNDARY) {
2286 boundary = &ok;
2287 not_boundary = new_trace.backtrack();
2288 } else {
2289 not_boundary = &ok;
2290 boundary = new_trace.backtrack();
2291 }
2292
2293 // Next character is not a word character.
2294 assembler->Bind(&before_non_word);
2295 if (new_trace.cp_offset() == 0) {
2296 // The start of input counts as a non-word character, so the question is
2297 // decided if we are at the start.
2298 assembler->CheckAtStart(not_boundary);
2299 }
2300 // We already checked that we are not at the start of input so it must be
2301 // OK to load the previous character.
2302 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2303 &ok, // Unused dummy label in this call.
2304 false);
2305 // Fall through on non-word.
2306 EmitWordCheck(assembler, boundary, not_boundary, false);
2307 assembler->GoTo(not_boundary);
2308
2309 // Next character is a word character.
2310 assembler->Bind(&before_word);
2311 if (new_trace.cp_offset() == 0) {
2312 // The start of input counts as a non-word character, so the question is
2313 // decided if we are at the start.
2314 assembler->CheckAtStart(boundary);
2315 }
2316 // We already checked that we are not at the start of input so it must be
2317 // OK to load the previous character.
2318 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2319 &ok, // Unused dummy label in this call.
2320 false);
2321 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2322 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2323
2324 assembler->Bind(&ok);
2325
2326 on_success->Emit(compiler, &new_trace);
2327}
2328
2329
iposva@chromium.org245aa852009-02-10 00:49:54 +00002330void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2331 RegExpCompiler* compiler,
2332 int filled_in,
2333 bool not_at_start) {
2334 if (type_ == AT_START && not_at_start) {
2335 details->set_cannot_match();
2336 return;
2337 }
2338 return on_success()->GetQuickCheckDetails(details,
2339 compiler,
2340 filled_in,
2341 not_at_start);
2342}
2343
2344
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002345void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2346 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2347 switch (type_) {
2348 case AT_END: {
2349 Label ok;
2350 assembler->CheckPosition(trace->cp_offset(), &ok);
2351 assembler->GoTo(trace->backtrack());
2352 assembler->Bind(&ok);
2353 break;
2354 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002355 case AT_START: {
2356 if (trace->at_start() == Trace::FALSE) {
2357 assembler->GoTo(trace->backtrack());
2358 return;
2359 }
2360 if (trace->at_start() == Trace::UNKNOWN) {
2361 assembler->CheckNotAtStart(trace->backtrack());
2362 Trace at_start_trace = *trace;
2363 at_start_trace.set_at_start(true);
2364 on_success()->Emit(compiler, &at_start_trace);
2365 return;
2366 }
2367 }
2368 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002369 case AFTER_NEWLINE:
2370 EmitHat(compiler, on_success(), trace);
2371 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002372 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002373 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002374 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2375 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002376 }
2377 case AFTER_WORD_CHARACTER:
2378 case AFTER_NONWORD_CHARACTER: {
2379 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2380 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002381 }
2382 on_success()->Emit(compiler, trace);
2383}
2384
2385
ager@chromium.org381abbb2009-02-25 13:23:22 +00002386static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2387 if (quick_check == NULL) return false;
2388 if (offset >= quick_check->characters()) return false;
2389 return quick_check->positions(offset)->determines_perfectly;
2390}
2391
2392
2393static void UpdateBoundsCheck(int index, int* checked_up_to) {
2394 if (index > *checked_up_to) {
2395 *checked_up_to = index;
2396 }
2397}
2398
2399
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002400// We call this repeatedly to generate code for each pass over the text node.
2401// The passes are in increasing order of difficulty because we hope one
2402// of the first passes will fail in which case we are saved the work of the
2403// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2404// we will check the '%' in the first pass, the case independent 'a' in the
2405// second pass and the character class in the last pass.
2406//
2407// The passes are done from right to left, so for example to test for /bar/
2408// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2409// and then a 'b' with offset 0. This means we can avoid the end-of-input
2410// bounds check most of the time. In the example we only need to check for
2411// end-of-input when loading the putative 'r'.
2412//
2413// A slight complication involves the fact that the first character may already
2414// be fetched into a register by the previous node. In this case we want to
2415// do the test for that character first. We do this in separate passes. The
2416// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2417// pass has been performed then subsequent passes will have true in
2418// first_element_checked to indicate that that character does not need to be
2419// checked again.
2420//
ager@chromium.org32912102009-01-16 10:38:43 +00002421// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002422// contain an AlternativeGeneration object. In this AlternativeGeneration
2423// object we can see details of any quick check that was already passed in
2424// order to get to the code we are now generating. The quick check can involve
2425// loading characters, which means we do not need to recheck the bounds
2426// up to the limit the quick check already checked. In addition the quick
2427// check can have involved a mask and compare operation which may simplify
2428// or obviate the need for further checks at some character positions.
2429void TextNode::TextEmitPass(RegExpCompiler* compiler,
2430 TextEmitPassType pass,
2431 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002432 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002433 bool first_element_checked,
2434 int* checked_up_to) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002435 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002436 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2437 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002438 Label* backtrack = trace->backtrack();
2439 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002440 int element_count = elms_->length();
2441 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2442 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002443 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002444 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002445 Vector<const uc16> quarks = elm.data.u_atom->data();
2446 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2447 if (first_element_checked && i == 0 && j == 0) continue;
2448 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2449 EmitCharacterFunction* emit_function = NULL;
2450 switch (pass) {
2451 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002452 ASSERT(ascii);
2453 if (quarks[j] > String::kMaxAsciiCharCode) {
2454 assembler->GoTo(backtrack);
2455 return;
2456 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002457 break;
2458 case NON_LETTER_CHARACTER_MATCH:
2459 emit_function = &EmitAtomNonLetter;
2460 break;
2461 case SIMPLE_CHARACTER_MATCH:
2462 emit_function = &EmitSimpleCharacter;
2463 break;
2464 case CASE_CHARACTER_MATCH:
2465 emit_function = &EmitAtomLetter;
2466 break;
2467 default:
2468 break;
2469 }
2470 if (emit_function != NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002471 bool bound_checked = emit_function(isolate,
2472 compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002473 quarks[j],
2474 backtrack,
2475 cp_offset + j,
2476 *checked_up_to < cp_offset + j,
2477 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002478 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002479 }
2480 }
2481 } else {
2482 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002483 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002484 if (first_element_checked && i == 0) continue;
2485 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002486 RegExpCharacterClass* cc = elm.data.u_char_class;
2487 EmitCharClass(assembler,
2488 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002489 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002490 backtrack,
2491 cp_offset,
2492 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002493 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002494 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002495 }
2496 }
2497 }
2498}
2499
2500
2501int TextNode::Length() {
2502 TextElement elm = elms_->last();
2503 ASSERT(elm.cp_offset >= 0);
2504 if (elm.type == TextElement::ATOM) {
2505 return elm.cp_offset + elm.data.u_atom->data().length();
2506 } else {
2507 return elm.cp_offset + 1;
2508 }
2509}
2510
2511
ager@chromium.org381abbb2009-02-25 13:23:22 +00002512bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2513 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2514 if (ignore_case) {
2515 return pass == SIMPLE_CHARACTER_MATCH;
2516 } else {
2517 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2518 }
2519}
2520
2521
ager@chromium.org8bb60582008-12-11 12:02:20 +00002522// This generates the code to match a text node. A text node can contain
2523// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002524// way) and character classes. For efficiency we do not do this in a single
2525// pass from left to right. Instead we pass over the text node several times,
2526// emitting code for some character positions every time. See the comment on
2527// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002528void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002529 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002530 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002531 ASSERT(limit_result == CONTINUE);
2532
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002533 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2534 compiler->SetRegExpTooBig();
2535 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002536 }
2537
2538 if (compiler->ascii()) {
2539 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002540 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002541 }
2542
2543 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002544 int bound_checked_to = trace->cp_offset() - 1;
2545 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002546
2547 // If a character is preloaded into the current character register then
2548 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002549 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002550 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2551 if (!SkipPass(pass, compiler->ignore_case())) {
2552 TextEmitPass(compiler,
2553 static_cast<TextEmitPassType>(pass),
2554 true,
2555 trace,
2556 false,
2557 &bound_checked_to);
2558 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002559 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002560 first_elt_done = true;
2561 }
2562
ager@chromium.org381abbb2009-02-25 13:23:22 +00002563 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2564 if (!SkipPass(pass, compiler->ignore_case())) {
2565 TextEmitPass(compiler,
2566 static_cast<TextEmitPassType>(pass),
2567 false,
2568 trace,
2569 first_elt_done,
2570 &bound_checked_to);
2571 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002572 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002573
ager@chromium.org32912102009-01-16 10:38:43 +00002574 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002575 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002576 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002577 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002578 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002579}
2580
2581
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002582void Trace::InvalidateCurrentCharacter() {
2583 characters_preloaded_ = 0;
2584}
2585
2586
2587void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002588 ASSERT(by > 0);
2589 // We don't have an instruction for shifting the current character register
2590 // down or for using a shifted value for anything so lets just forget that
2591 // we preloaded any characters into it.
2592 characters_preloaded_ = 0;
2593 // Adjust the offsets of the quick check performed information. This
2594 // information is used to find out what we already determined about the
2595 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002596 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002597 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002598 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2599 compiler->SetRegExpTooBig();
2600 cp_offset_ = 0;
2601 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002602 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002603}
2604
2605
ager@chromium.org38e4c712009-11-11 09:11:58 +00002606void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002607 int element_count = elms_->length();
2608 for (int i = 0; i < element_count; i++) {
2609 TextElement elm = elms_->at(i);
2610 if (elm.type == TextElement::CHAR_CLASS) {
2611 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002612 // None of the standard character classses is different in the case
2613 // independent case and it slows us down if we don't know that.
2614 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002615 ZoneList<CharacterRange>* ranges = cc->ranges();
2616 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002617 for (int j = 0; j < range_count; j++) {
2618 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002619 }
2620 }
2621 }
2622}
2623
2624
ager@chromium.org8bb60582008-12-11 12:02:20 +00002625int TextNode::GreedyLoopTextLength() {
2626 TextElement elm = elms_->at(elms_->length() - 1);
2627 if (elm.type == TextElement::CHAR_CLASS) {
2628 return elm.cp_offset + 1;
2629 } else {
2630 return elm.cp_offset + elm.data.u_atom->data().length();
2631 }
2632}
2633
2634
2635// Finds the fixed match length of a sequence of nodes that goes from
2636// this alternative and back to this choice node. If there are variable
2637// length nodes or other complications in the way then return a sentinel
2638// value indicating that a greedy loop cannot be constructed.
2639int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2640 int length = 0;
2641 RegExpNode* node = alternative->node();
2642 // Later we will generate code for all these text nodes using recursion
2643 // so we have to limit the max number.
2644 int recursion_depth = 0;
2645 while (node != this) {
2646 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2647 return kNodeIsTooComplexForGreedyLoops;
2648 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002649 int node_length = node->GreedyLoopTextLength();
2650 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2651 return kNodeIsTooComplexForGreedyLoops;
2652 }
2653 length += node_length;
2654 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2655 node = seq_node->on_success();
2656 }
2657 return length;
2658}
2659
2660
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002661void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2662 ASSERT_EQ(loop_node_, NULL);
2663 AddAlternative(alt);
2664 loop_node_ = alt.node();
2665}
2666
2667
2668void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2669 ASSERT_EQ(continue_node_, NULL);
2670 AddAlternative(alt);
2671 continue_node_ = alt.node();
2672}
2673
2674
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002675void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002676 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002677 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002678 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2679 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2680 // Update the counter-based backtracking info on the stack. This is an
2681 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002682 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002683 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002684 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002685 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002686 }
ager@chromium.org32912102009-01-16 10:38:43 +00002687 ASSERT(trace->stop_node() == NULL);
2688 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002689 trace->Flush(compiler, this);
2690 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002691 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002692 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002693}
2694
2695
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002696int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
2697 bool not_at_start) {
2698 int preload_characters = EatsAtLeast(4, 0, not_at_start);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002699 if (compiler->macro_assembler()->CanReadUnaligned()) {
2700 bool ascii = compiler->ascii();
2701 if (ascii) {
2702 if (preload_characters > 4) preload_characters = 4;
2703 // We can't preload 3 characters because there is no machine instruction
2704 // to do that. We can't just load 4 because we could be reading
2705 // beyond the end of the string, which could cause a memory fault.
2706 if (preload_characters == 3) preload_characters = 2;
2707 } else {
2708 if (preload_characters > 2) preload_characters = 2;
2709 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002710 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002711 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002712 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002713 return preload_characters;
2714}
2715
2716
2717// This class is used when generating the alternatives in a choice node. It
2718// records the way the alternative is being code generated.
2719class AlternativeGeneration: public Malloced {
2720 public:
2721 AlternativeGeneration()
2722 : possible_success(),
2723 expects_preload(false),
2724 after(),
2725 quick_check_details() { }
2726 Label possible_success;
2727 bool expects_preload;
2728 Label after;
2729 QuickCheckDetails quick_check_details;
2730};
2731
2732
2733// Creates a list of AlternativeGenerations. If the list has a reasonable
2734// size then it is on the stack, otherwise the excess is on the heap.
2735class AlternativeGenerationList {
2736 public:
2737 explicit AlternativeGenerationList(int count)
2738 : alt_gens_(count) {
2739 for (int i = 0; i < count && i < kAFew; i++) {
2740 alt_gens_.Add(a_few_alt_gens_ + i);
2741 }
2742 for (int i = kAFew; i < count; i++) {
2743 alt_gens_.Add(new AlternativeGeneration());
2744 }
2745 }
2746 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002747 for (int i = kAFew; i < alt_gens_.length(); i++) {
2748 delete alt_gens_[i];
2749 alt_gens_[i] = NULL;
2750 }
2751 }
2752
2753 AlternativeGeneration* at(int i) {
2754 return alt_gens_[i];
2755 }
2756 private:
2757 static const int kAFew = 10;
2758 ZoneList<AlternativeGeneration*> alt_gens_;
2759 AlternativeGeneration a_few_alt_gens_[kAFew];
2760};
2761
2762
2763/* Code generation for choice nodes.
2764 *
2765 * We generate quick checks that do a mask and compare to eliminate a
2766 * choice. If the quick check succeeds then it jumps to the continuation to
2767 * do slow checks and check subsequent nodes. If it fails (the common case)
2768 * it falls through to the next choice.
2769 *
2770 * Here is the desired flow graph. Nodes directly below each other imply
2771 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2772 * 3 doesn't have a quick check so we have to call the slow check.
2773 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2774 * regexp continuation is generated directly after the Sn node, up to the
2775 * next GoTo if we decide to reuse some already generated code. Some
2776 * nodes expect preload_characters to be preloaded into the current
2777 * character register. R nodes do this preloading. Vertices are marked
2778 * F for failures and S for success (possible success in the case of quick
2779 * nodes). L, V, < and > are used as arrow heads.
2780 *
2781 * ----------> R
2782 * |
2783 * V
2784 * Q1 -----> S1
2785 * | S /
2786 * F| /
2787 * | F/
2788 * | /
2789 * | R
2790 * | /
2791 * V L
2792 * Q2 -----> S2
2793 * | S /
2794 * F| /
2795 * | F/
2796 * | /
2797 * | R
2798 * | /
2799 * V L
2800 * S3
2801 * |
2802 * F|
2803 * |
2804 * R
2805 * |
2806 * backtrack V
2807 * <----------Q4
2808 * \ F |
2809 * \ |S
2810 * \ F V
2811 * \-----S4
2812 *
2813 * For greedy loops we reverse our expectation and expect to match rather
2814 * than fail. Therefore we want the loop code to look like this (U is the
2815 * unwind code that steps back in the greedy loop). The following alternatives
2816 * look the same as above.
2817 * _____
2818 * / \
2819 * V |
2820 * ----------> S1 |
2821 * /| |
2822 * / |S |
2823 * F/ \_____/
2824 * /
2825 * |<-----------
2826 * | \
2827 * V \
2828 * Q2 ---> S2 \
2829 * | S / |
2830 * F| / |
2831 * | F/ |
2832 * | / |
2833 * | R |
2834 * | / |
2835 * F VL |
2836 * <------U |
2837 * back |S |
2838 * \______________/
2839 */
2840
2841
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002842void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002843 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2844 int choice_count = alternatives_->length();
2845#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002846 for (int i = 0; i < choice_count - 1; i++) {
2847 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002848 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002849 int guard_count = (guards == NULL) ? 0 : guards->length();
2850 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002851 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002852 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002853 }
2854#endif
2855
ager@chromium.org32912102009-01-16 10:38:43 +00002856 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002857 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002858 ASSERT(limit_result == CONTINUE);
2859
ager@chromium.org381abbb2009-02-25 13:23:22 +00002860 int new_flush_budget = trace->flush_budget() / choice_count;
2861 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2862 trace->Flush(compiler, this);
2863 return;
2864 }
2865
ager@chromium.org8bb60582008-12-11 12:02:20 +00002866 RecursionCheck rc(compiler);
2867
ager@chromium.org32912102009-01-16 10:38:43 +00002868 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002869
2870 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2871 bool greedy_loop = false;
2872 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002873 Trace counter_backtrack_trace;
2874 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002875 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2876
ager@chromium.org8bb60582008-12-11 12:02:20 +00002877 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2878 // Here we have special handling for greedy loops containing only text nodes
2879 // and other simple nodes. These are handled by pushing the current
2880 // position on the stack and then incrementing the current position each
2881 // time around the switch. On backtrack we decrement the current position
2882 // and check it against the pushed value. This avoids pushing backtrack
2883 // information for each iteration of the loop, which could take up a lot of
2884 // space.
2885 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002886 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002887 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002888 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002889 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002890 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002891 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002892 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002893 Label loop_label;
2894 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002895 greedy_match_trace.set_stop_node(this);
2896 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002897 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002898 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002899 }
2900
2901 Label second_choice; // For use in greedy matches.
2902 macro_assembler->Bind(&second_choice);
2903
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002904 int first_normal_choice = greedy_loop ? 1 : 0;
2905
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002906 int preload_characters =
2907 CalculatePreloadCharacters(compiler,
2908 current_trace->at_start() == Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002909 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002910 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002911 bool preload_has_checked_bounds = preload_is_current;
2912
2913 AlternativeGenerationList alt_gens(choice_count);
2914
ager@chromium.org8bb60582008-12-11 12:02:20 +00002915 // For now we just call all choices one after the other. The idea ultimately
2916 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002917 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002918 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002919 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002920 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002921 ZoneList<Guard*>* guards = alternative.guards();
2922 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002923 Trace new_trace(*current_trace);
2924 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002925 preload_characters :
2926 0);
2927 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002928 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002929 }
ager@chromium.org32912102009-01-16 10:38:43 +00002930 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002931 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002932 alt_gen->expects_preload = preload_is_current;
2933 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002934 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002935 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002936 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002937 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002938 preload_has_checked_bounds,
2939 &alt_gen->possible_success,
2940 &alt_gen->quick_check_details,
2941 i < choice_count - 1)) {
2942 // Quick check was generated for this choice.
2943 preload_is_current = true;
2944 preload_has_checked_bounds = true;
2945 // On the last choice in the ChoiceNode we generated the quick
2946 // check to fall through on possible success. So now we need to
2947 // generate the full check inline.
2948 if (i == choice_count - 1) {
2949 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002950 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2951 new_trace.set_characters_preloaded(preload_characters);
2952 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002953 generate_full_check_inline = true;
2954 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002955 } else if (alt_gen->quick_check_details.cannot_match()) {
2956 if (i == choice_count - 1 && !greedy_loop) {
2957 macro_assembler->GoTo(trace->backtrack());
2958 }
2959 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002960 } else {
2961 // No quick check was generated. Put the full code here.
2962 // If this is not the first choice then there could be slow checks from
2963 // previous cases that go here when they fail. There's no reason to
2964 // insist that they preload characters since the slow check we are about
2965 // to generate probably can't use it.
2966 if (i != first_normal_choice) {
2967 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002968 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002969 }
2970 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002971 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002972 }
2973 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002974 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002975 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002976 if (new_trace.actions() != NULL) {
2977 new_trace.set_flush_budget(new_flush_budget);
2978 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002979 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002980 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002981 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002982 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002983 preload_is_current = false;
2984 }
2985 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002986 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002987 if (greedy_loop) {
2988 macro_assembler->Bind(&greedy_loop_label);
2989 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002990 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002991 // Otherwise try the second priority at an earlier position.
2992 macro_assembler->AdvanceCurrentPosition(-text_length);
2993 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002994 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002995
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002996 // At this point we need to generate slow checks for the alternatives where
2997 // the quick check was inlined. We can recognize these because the associated
2998 // label was bound.
2999 for (int i = first_normal_choice; i < choice_count - 1; i++) {
3000 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00003001 Trace new_trace(*current_trace);
3002 // If there are actions to be flushed we have to limit how many times
3003 // they are flushed. Take the budget of the parent trace and distribute
3004 // it fairly amongst the children.
3005 if (new_trace.actions() != NULL) {
3006 new_trace.set_flush_budget(new_flush_budget);
3007 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003008 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00003009 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003010 alternatives_->at(i),
3011 alt_gen,
3012 preload_characters,
3013 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003014 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003015}
3016
3017
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003018void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00003019 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003020 GuardedAlternative alternative,
3021 AlternativeGeneration* alt_gen,
3022 int preload_characters,
3023 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003024 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003025
3026 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3027 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00003028 Trace out_of_line_trace(*trace);
3029 out_of_line_trace.set_characters_preloaded(preload_characters);
3030 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003031 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003032 ZoneList<Guard*>* guards = alternative.guards();
3033 int guard_count = (guards == NULL) ? 0 : guards->length();
3034 if (next_expects_preload) {
3035 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00003036 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003037 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003038 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003039 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003040 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003041 macro_assembler->Bind(&reload_current_char);
3042 // Reload the current character, since the next quick check expects that.
3043 // We don't need to check bounds here because we only get into this
3044 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00003045 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003046 NULL,
3047 false,
3048 preload_characters);
3049 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003050 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00003051 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003052 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003053 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003054 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003055 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003056 }
3057}
3058
3059
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003060void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003061 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003062 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003063 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003064 ASSERT(limit_result == CONTINUE);
3065
3066 RecursionCheck rc(compiler);
3067
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003068 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003069 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00003070 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003071 new_capture(data_.u_position_register.reg,
3072 data_.u_position_register.is_capture,
3073 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003074 Trace new_trace = *trace;
3075 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003076 on_success()->Emit(compiler, &new_trace);
3077 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003078 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003079 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003080 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003081 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00003082 Trace new_trace = *trace;
3083 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003084 on_success()->Emit(compiler, &new_trace);
3085 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003086 }
3087 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003088 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003089 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00003090 Trace new_trace = *trace;
3091 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003092 on_success()->Emit(compiler, &new_trace);
3093 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003094 }
3095 case CLEAR_CAPTURES: {
3096 Trace::DeferredClearCaptures
3097 new_capture(Interval(data_.u_clear_captures.range_from,
3098 data_.u_clear_captures.range_to));
3099 Trace new_trace = *trace;
3100 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003101 on_success()->Emit(compiler, &new_trace);
3102 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003103 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003104 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003105 if (!trace->is_trivial()) {
3106 trace->Flush(compiler, this);
3107 } else {
3108 assembler->WriteCurrentPositionToRegister(
3109 data_.u_submatch.current_position_register, 0);
3110 assembler->WriteStackPointerToRegister(
3111 data_.u_submatch.stack_pointer_register);
3112 on_success()->Emit(compiler, trace);
3113 }
3114 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003115 case EMPTY_MATCH_CHECK: {
3116 int start_pos_reg = data_.u_empty_match_check.start_register;
3117 int stored_pos = 0;
3118 int rep_reg = data_.u_empty_match_check.repetition_register;
3119 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3120 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3121 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3122 // If we know we haven't advanced and there is no minimum we
3123 // can just backtrack immediately.
3124 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003125 } else if (know_dist && stored_pos < trace->cp_offset()) {
3126 // If we know we've advanced we can generate the continuation
3127 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003128 on_success()->Emit(compiler, trace);
3129 } else if (!trace->is_trivial()) {
3130 trace->Flush(compiler, this);
3131 } else {
3132 Label skip_empty_check;
3133 // If we have a minimum number of repetitions we check the current
3134 // number first and skip the empty check if it's not enough.
3135 if (has_minimum) {
3136 int limit = data_.u_empty_match_check.repetition_limit;
3137 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3138 }
3139 // If the match is empty we bail out, otherwise we fall through
3140 // to the on-success continuation.
3141 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3142 trace->backtrack());
3143 assembler->Bind(&skip_empty_check);
3144 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003145 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003146 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003147 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003148 case POSITIVE_SUBMATCH_SUCCESS: {
3149 if (!trace->is_trivial()) {
3150 trace->Flush(compiler, this);
3151 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003152 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003153 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003154 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003155 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003156 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003157 int clear_register_count = data_.u_submatch.clear_register_count;
3158 if (clear_register_count == 0) {
3159 on_success()->Emit(compiler, trace);
3160 return;
3161 }
3162 int clear_registers_from = data_.u_submatch.clear_register_from;
3163 Label clear_registers_backtrack;
3164 Trace new_trace = *trace;
3165 new_trace.set_backtrack(&clear_registers_backtrack);
3166 on_success()->Emit(compiler, &new_trace);
3167
3168 assembler->Bind(&clear_registers_backtrack);
3169 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3170 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3171
3172 ASSERT(trace->backtrack() == NULL);
3173 assembler->Backtrack();
3174 return;
3175 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003176 default:
3177 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003178 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003179}
3180
3181
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003182void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003183 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003184 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003185 trace->Flush(compiler, this);
3186 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003187 }
3188
ager@chromium.org32912102009-01-16 10:38:43 +00003189 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003190 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003191 ASSERT(limit_result == CONTINUE);
3192
3193 RecursionCheck rc(compiler);
3194
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003195 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003196 if (compiler->ignore_case()) {
3197 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3198 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003199 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003200 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003201 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003202 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003203}
3204
3205
3206// -------------------------------------------------------------------
3207// Dot/dotty output
3208
3209
3210#ifdef DEBUG
3211
3212
3213class DotPrinter: public NodeVisitor {
3214 public:
3215 explicit DotPrinter(bool ignore_case)
3216 : ignore_case_(ignore_case),
3217 stream_(&alloc_) { }
3218 void PrintNode(const char* label, RegExpNode* node);
3219 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003220 void PrintAttributes(RegExpNode* from);
3221 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003222 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003223#define DECLARE_VISIT(Type) \
3224 virtual void Visit##Type(Type##Node* that);
3225FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3226#undef DECLARE_VISIT
3227 private:
3228 bool ignore_case_;
3229 HeapStringAllocator alloc_;
3230 StringStream stream_;
3231};
3232
3233
3234void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3235 stream()->Add("digraph G {\n graph [label=\"");
3236 for (int i = 0; label[i]; i++) {
3237 switch (label[i]) {
3238 case '\\':
3239 stream()->Add("\\\\");
3240 break;
3241 case '"':
3242 stream()->Add("\"");
3243 break;
3244 default:
3245 stream()->Put(label[i]);
3246 break;
3247 }
3248 }
3249 stream()->Add("\"];\n");
3250 Visit(node);
3251 stream()->Add("}\n");
3252 printf("%s", *(stream()->ToCString()));
3253}
3254
3255
3256void DotPrinter::Visit(RegExpNode* node) {
3257 if (node->info()->visited) return;
3258 node->info()->visited = true;
3259 node->Accept(this);
3260}
3261
3262
3263void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003264 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3265 Visit(on_failure);
3266}
3267
3268
3269class TableEntryBodyPrinter {
3270 public:
3271 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3272 : stream_(stream), choice_(choice) { }
3273 void Call(uc16 from, DispatchTable::Entry entry) {
3274 OutSet* out_set = entry.out_set();
3275 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3276 if (out_set->Get(i)) {
3277 stream()->Add(" n%p:s%io%i -> n%p;\n",
3278 choice(),
3279 from,
3280 i,
3281 choice()->alternatives()->at(i).node());
3282 }
3283 }
3284 }
3285 private:
3286 StringStream* stream() { return stream_; }
3287 ChoiceNode* choice() { return choice_; }
3288 StringStream* stream_;
3289 ChoiceNode* choice_;
3290};
3291
3292
3293class TableEntryHeaderPrinter {
3294 public:
3295 explicit TableEntryHeaderPrinter(StringStream* stream)
3296 : first_(true), stream_(stream) { }
3297 void Call(uc16 from, DispatchTable::Entry entry) {
3298 if (first_) {
3299 first_ = false;
3300 } else {
3301 stream()->Add("|");
3302 }
3303 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3304 OutSet* out_set = entry.out_set();
3305 int priority = 0;
3306 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3307 if (out_set->Get(i)) {
3308 if (priority > 0) stream()->Add("|");
3309 stream()->Add("<s%io%i> %i", from, i, priority);
3310 priority++;
3311 }
3312 }
3313 stream()->Add("}}");
3314 }
3315 private:
3316 bool first_;
3317 StringStream* stream() { return stream_; }
3318 StringStream* stream_;
3319};
3320
3321
3322class AttributePrinter {
3323 public:
3324 explicit AttributePrinter(DotPrinter* out)
3325 : out_(out), first_(true) { }
3326 void PrintSeparator() {
3327 if (first_) {
3328 first_ = false;
3329 } else {
3330 out_->stream()->Add("|");
3331 }
3332 }
3333 void PrintBit(const char* name, bool value) {
3334 if (!value) return;
3335 PrintSeparator();
3336 out_->stream()->Add("{%s}", name);
3337 }
3338 void PrintPositive(const char* name, int value) {
3339 if (value < 0) return;
3340 PrintSeparator();
3341 out_->stream()->Add("{%s|%x}", name, value);
3342 }
3343 private:
3344 DotPrinter* out_;
3345 bool first_;
3346};
3347
3348
3349void DotPrinter::PrintAttributes(RegExpNode* that) {
3350 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3351 "margin=0.1, fontsize=10, label=\"{",
3352 that);
3353 AttributePrinter printer(this);
3354 NodeInfo* info = that->info();
3355 printer.PrintBit("NI", info->follows_newline_interest);
3356 printer.PrintBit("WI", info->follows_word_interest);
3357 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003358 Label* label = that->label();
3359 if (label->is_bound())
3360 printer.PrintPositive("@", label->pos());
3361 stream()->Add("}\"];\n");
3362 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3363 "arrowhead=none];\n", that, that);
3364}
3365
3366
3367static const bool kPrintDispatchTable = false;
3368void DotPrinter::VisitChoice(ChoiceNode* that) {
3369 if (kPrintDispatchTable) {
3370 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3371 TableEntryHeaderPrinter header_printer(stream());
3372 that->GetTable(ignore_case_)->ForEach(&header_printer);
3373 stream()->Add("\"]\n", that);
3374 PrintAttributes(that);
3375 TableEntryBodyPrinter body_printer(stream(), that);
3376 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003377 } else {
3378 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3379 for (int i = 0; i < that->alternatives()->length(); i++) {
3380 GuardedAlternative alt = that->alternatives()->at(i);
3381 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3382 }
3383 }
3384 for (int i = 0; i < that->alternatives()->length(); i++) {
3385 GuardedAlternative alt = that->alternatives()->at(i);
3386 alt.node()->Accept(this);
3387 }
3388}
3389
3390
3391void DotPrinter::VisitText(TextNode* that) {
3392 stream()->Add(" n%p [label=\"", that);
3393 for (int i = 0; i < that->elements()->length(); i++) {
3394 if (i > 0) stream()->Add(" ");
3395 TextElement elm = that->elements()->at(i);
3396 switch (elm.type) {
3397 case TextElement::ATOM: {
3398 stream()->Add("'%w'", elm.data.u_atom->data());
3399 break;
3400 }
3401 case TextElement::CHAR_CLASS: {
3402 RegExpCharacterClass* node = elm.data.u_char_class;
3403 stream()->Add("[");
3404 if (node->is_negated())
3405 stream()->Add("^");
3406 for (int j = 0; j < node->ranges()->length(); j++) {
3407 CharacterRange range = node->ranges()->at(j);
3408 stream()->Add("%k-%k", range.from(), range.to());
3409 }
3410 stream()->Add("]");
3411 break;
3412 }
3413 default:
3414 UNREACHABLE();
3415 }
3416 }
3417 stream()->Add("\", shape=box, peripheries=2];\n");
3418 PrintAttributes(that);
3419 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3420 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003421}
3422
3423
3424void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3425 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3426 that,
3427 that->start_register(),
3428 that->end_register());
3429 PrintAttributes(that);
3430 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3431 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003432}
3433
3434
3435void DotPrinter::VisitEnd(EndNode* that) {
3436 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3437 PrintAttributes(that);
3438}
3439
3440
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003441void DotPrinter::VisitAssertion(AssertionNode* that) {
3442 stream()->Add(" n%p [", that);
3443 switch (that->type()) {
3444 case AssertionNode::AT_END:
3445 stream()->Add("label=\"$\", shape=septagon");
3446 break;
3447 case AssertionNode::AT_START:
3448 stream()->Add("label=\"^\", shape=septagon");
3449 break;
3450 case AssertionNode::AT_BOUNDARY:
3451 stream()->Add("label=\"\\b\", shape=septagon");
3452 break;
3453 case AssertionNode::AT_NON_BOUNDARY:
3454 stream()->Add("label=\"\\B\", shape=septagon");
3455 break;
3456 case AssertionNode::AFTER_NEWLINE:
3457 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3458 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003459 case AssertionNode::AFTER_WORD_CHARACTER:
3460 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3461 break;
3462 case AssertionNode::AFTER_NONWORD_CHARACTER:
3463 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3464 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003465 }
3466 stream()->Add("];\n");
3467 PrintAttributes(that);
3468 RegExpNode* successor = that->on_success();
3469 stream()->Add(" n%p -> n%p;\n", that, successor);
3470 Visit(successor);
3471}
3472
3473
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003474void DotPrinter::VisitAction(ActionNode* that) {
3475 stream()->Add(" n%p [", that);
3476 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003477 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003478 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3479 that->data_.u_store_register.reg,
3480 that->data_.u_store_register.value);
3481 break;
3482 case ActionNode::INCREMENT_REGISTER:
3483 stream()->Add("label=\"$%i++\", shape=octagon",
3484 that->data_.u_increment_register.reg);
3485 break;
3486 case ActionNode::STORE_POSITION:
3487 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3488 that->data_.u_position_register.reg);
3489 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003490 case ActionNode::BEGIN_SUBMATCH:
3491 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3492 that->data_.u_submatch.current_position_register);
3493 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003494 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003495 stream()->Add("label=\"escape\", shape=septagon");
3496 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003497 case ActionNode::EMPTY_MATCH_CHECK:
3498 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3499 that->data_.u_empty_match_check.start_register,
3500 that->data_.u_empty_match_check.repetition_register,
3501 that->data_.u_empty_match_check.repetition_limit);
3502 break;
3503 case ActionNode::CLEAR_CAPTURES: {
3504 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3505 that->data_.u_clear_captures.range_from,
3506 that->data_.u_clear_captures.range_to);
3507 break;
3508 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003509 }
3510 stream()->Add("];\n");
3511 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003512 RegExpNode* successor = that->on_success();
3513 stream()->Add(" n%p -> n%p;\n", that, successor);
3514 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003515}
3516
3517
3518class DispatchTableDumper {
3519 public:
3520 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3521 void Call(uc16 key, DispatchTable::Entry entry);
3522 StringStream* stream() { return stream_; }
3523 private:
3524 StringStream* stream_;
3525};
3526
3527
3528void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3529 stream()->Add("[%k-%k]: {", key, entry.to());
3530 OutSet* set = entry.out_set();
3531 bool first = true;
3532 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3533 if (set->Get(i)) {
3534 if (first) {
3535 first = false;
3536 } else {
3537 stream()->Add(", ");
3538 }
3539 stream()->Add("%i", i);
3540 }
3541 }
3542 stream()->Add("}\n");
3543}
3544
3545
3546void DispatchTable::Dump() {
3547 HeapStringAllocator alloc;
3548 StringStream stream(&alloc);
3549 DispatchTableDumper dumper(&stream);
3550 tree()->ForEach(&dumper);
3551 OS::PrintError("%s", *stream.ToCString());
3552}
3553
3554
3555void RegExpEngine::DotPrint(const char* label,
3556 RegExpNode* node,
3557 bool ignore_case) {
3558 DotPrinter printer(ignore_case);
3559 printer.PrintNode(label, node);
3560}
3561
3562
3563#endif // DEBUG
3564
3565
3566// -------------------------------------------------------------------
3567// Tree to graph conversion
3568
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003569static const int kSpaceRangeCount = 20;
3570static const int kSpaceRangeAsciiCount = 4;
3571static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3572 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3573 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3574
3575static const int kWordRangeCount = 8;
3576static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3577 '_', 'a', 'z' };
3578
3579static const int kDigitRangeCount = 2;
3580static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3581
3582static const int kLineTerminatorRangeCount = 6;
3583static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3584 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003585
3586RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003587 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003588 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3589 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003590 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003591}
3592
3593
3594RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003595 RegExpNode* on_success) {
3596 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003597}
3598
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003599static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3600 const uc16* special_class,
3601 int length) {
3602 ASSERT(ranges->length() != 0);
3603 ASSERT(length != 0);
3604 ASSERT(special_class[0] != 0);
3605 if (ranges->length() != (length >> 1) + 1) {
3606 return false;
3607 }
3608 CharacterRange range = ranges->at(0);
3609 if (range.from() != 0) {
3610 return false;
3611 }
3612 for (int i = 0; i < length; i += 2) {
3613 if (special_class[i] != (range.to() + 1)) {
3614 return false;
3615 }
3616 range = ranges->at((i >> 1) + 1);
3617 if (special_class[i+1] != range.from() - 1) {
3618 return false;
3619 }
3620 }
3621 if (range.to() != 0xffff) {
3622 return false;
3623 }
3624 return true;
3625}
3626
3627
3628static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3629 const uc16* special_class,
3630 int length) {
3631 if (ranges->length() * 2 != length) {
3632 return false;
3633 }
3634 for (int i = 0; i < length; i += 2) {
3635 CharacterRange range = ranges->at(i >> 1);
3636 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3637 return false;
3638 }
3639 }
3640 return true;
3641}
3642
3643
3644bool RegExpCharacterClass::is_standard() {
3645 // TODO(lrn): Remove need for this function, by not throwing away information
3646 // along the way.
3647 if (is_negated_) {
3648 return false;
3649 }
3650 if (set_.is_standard()) {
3651 return true;
3652 }
3653 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3654 set_.set_standard_set_type('s');
3655 return true;
3656 }
3657 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3658 set_.set_standard_set_type('S');
3659 return true;
3660 }
3661 if (CompareInverseRanges(set_.ranges(),
3662 kLineTerminatorRanges,
3663 kLineTerminatorRangeCount)) {
3664 set_.set_standard_set_type('.');
3665 return true;
3666 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003667 if (CompareRanges(set_.ranges(),
3668 kLineTerminatorRanges,
3669 kLineTerminatorRangeCount)) {
3670 set_.set_standard_set_type('n');
3671 return true;
3672 }
3673 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3674 set_.set_standard_set_type('w');
3675 return true;
3676 }
3677 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3678 set_.set_standard_set_type('W');
3679 return true;
3680 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003681 return false;
3682}
3683
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003684
3685RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003686 RegExpNode* on_success) {
3687 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003688}
3689
3690
3691RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003692 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003693 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3694 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003695 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003696 for (int i = 0; i < length; i++) {
3697 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003698 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003699 result->AddAlternative(alternative);
3700 }
3701 return result;
3702}
3703
3704
3705RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003706 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003707 return ToNode(min(),
3708 max(),
3709 is_greedy(),
3710 body(),
3711 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003712 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003713}
3714
3715
3716RegExpNode* RegExpQuantifier::ToNode(int min,
3717 int max,
3718 bool is_greedy,
3719 RegExpTree* body,
3720 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003721 RegExpNode* on_success,
3722 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003723 // x{f, t} becomes this:
3724 //
3725 // (r++)<-.
3726 // | `
3727 // | (x)
3728 // v ^
3729 // (r=0)-->(?)---/ [if r < t]
3730 // |
3731 // [if r >= f] \----> ...
3732 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003733
3734 // 15.10.2.5 RepeatMatcher algorithm.
3735 // The parser has already eliminated the case where max is 0. In the case
3736 // where max_match is zero the parser has removed the quantifier if min was
3737 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3738
3739 // If we know that we cannot match zero length then things are a little
3740 // simpler since we don't need to make the special zero length match check
3741 // from step 2.1. If the min and max are small we can unroll a little in
3742 // this case.
3743 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3744 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3745 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003746 bool body_can_be_empty = (body->min_match() == 0);
3747 int body_start_reg = RegExpCompiler::kNoRegister;
3748 Interval capture_registers = body->CaptureRegisters();
3749 bool needs_capture_clearing = !capture_registers.is_empty();
3750 if (body_can_be_empty) {
3751 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003752 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003753 // Only unroll if there are no captures and the body can't be
3754 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003755 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3756 int new_max = (max == kInfinity) ? max : max - min;
3757 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003758 RegExpNode* answer = ToNode(
3759 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003760 // Unroll the forced matches from 0 to min. This can cause chains of
3761 // TextNodes (which the parser does not generate). These should be
3762 // combined if it turns out they hinder good code generation.
3763 for (int i = 0; i < min; i++) {
3764 answer = body->ToNode(compiler, answer);
3765 }
3766 return answer;
3767 }
3768 if (max <= kMaxUnrolledMaxMatches) {
3769 ASSERT(min == 0);
3770 // Unroll the optional matches up to max.
3771 RegExpNode* answer = on_success;
3772 for (int i = 0; i < max; i++) {
3773 ChoiceNode* alternation = new ChoiceNode(2);
3774 if (is_greedy) {
3775 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3776 answer)));
3777 alternation->AddAlternative(GuardedAlternative(on_success));
3778 } else {
3779 alternation->AddAlternative(GuardedAlternative(on_success));
3780 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3781 answer)));
3782 }
3783 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003784 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003785 }
3786 return answer;
3787 }
3788 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003789 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003790 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003791 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003792 int reg_ctr = needs_counter
3793 ? compiler->AllocateRegister()
3794 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003795 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003796 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003797 RegExpNode* loop_return = needs_counter
3798 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3799 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003800 if (body_can_be_empty) {
3801 // If the body can be empty we need to check if it was and then
3802 // backtrack.
3803 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3804 reg_ctr,
3805 min,
3806 loop_return);
3807 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003808 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003809 if (body_can_be_empty) {
3810 // If the body can be empty we need to store the start position
3811 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003812 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003813 }
3814 if (needs_capture_clearing) {
3815 // Before entering the body of this loop we need to clear captures.
3816 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3817 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003818 GuardedAlternative body_alt(body_node);
3819 if (has_max) {
3820 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3821 body_alt.AddGuard(body_guard);
3822 }
3823 GuardedAlternative rest_alt(on_success);
3824 if (has_min) {
3825 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3826 rest_alt.AddGuard(rest_guard);
3827 }
3828 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003829 center->AddLoopAlternative(body_alt);
3830 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003831 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003832 center->AddContinueAlternative(rest_alt);
3833 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003834 }
3835 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003836 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003837 } else {
3838 return center;
3839 }
3840}
3841
3842
3843RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003844 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003845 NodeInfo info;
3846 switch (type()) {
3847 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003848 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003849 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003850 return AssertionNode::AtStart(on_success);
3851 case BOUNDARY:
3852 return AssertionNode::AtBoundary(on_success);
3853 case NON_BOUNDARY:
3854 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003855 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003856 return AssertionNode::AtEnd(on_success);
3857 case END_OF_LINE: {
3858 // Compile $ in multiline regexps as an alternation with a positive
3859 // lookahead in one side and an end-of-input on the other side.
3860 // We need two registers for the lookahead.
3861 int stack_pointer_register = compiler->AllocateRegister();
3862 int position_register = compiler->AllocateRegister();
3863 // The ChoiceNode to distinguish between a newline and end-of-input.
3864 ChoiceNode* result = new ChoiceNode(2);
3865 // Create a newline atom.
3866 ZoneList<CharacterRange>* newline_ranges =
3867 new ZoneList<CharacterRange>(3);
3868 CharacterRange::AddClassEscape('n', newline_ranges);
3869 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3870 TextNode* newline_matcher = new TextNode(
3871 newline_atom,
3872 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3873 position_register,
3874 0, // No captures inside.
3875 -1, // Ignored if no captures.
3876 on_success));
3877 // Create an end-of-input matcher.
3878 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3879 stack_pointer_register,
3880 position_register,
3881 newline_matcher);
3882 // Add the two alternatives to the ChoiceNode.
3883 GuardedAlternative eol_alternative(end_of_line);
3884 result->AddAlternative(eol_alternative);
3885 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3886 result->AddAlternative(end_alternative);
3887 return result;
3888 }
3889 default:
3890 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003891 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003892 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003893}
3894
3895
3896RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003897 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003898 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3899 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003900 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003901}
3902
3903
3904RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003905 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003906 return on_success;
3907}
3908
3909
3910RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003911 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003912 int stack_pointer_register = compiler->AllocateRegister();
3913 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003914
3915 const int registers_per_capture = 2;
3916 const int register_of_first_capture = 2;
3917 int register_count = capture_count_ * registers_per_capture;
3918 int register_start =
3919 register_of_first_capture + capture_from_ * registers_per_capture;
3920
ager@chromium.org8bb60582008-12-11 12:02:20 +00003921 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003922 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003923 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003924 stack_pointer_register,
3925 position_register,
3926 body()->ToNode(
3927 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003928 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3929 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003930 register_count,
3931 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003932 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003933 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003934 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003935 // We use a ChoiceNode for a negative lookahead because it has most of
3936 // the characteristics we need. It has the body of the lookahead as its
3937 // first alternative and the expression after the lookahead of the second
3938 // alternative. If the first alternative succeeds then the
3939 // NegativeSubmatchSuccess will unwind the stack including everything the
3940 // choice node set up and backtrack. If the first alternative fails then
3941 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003942 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3943 // ChoiceNode that knows to ignore the first exit when calculating quick
3944 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003945 GuardedAlternative body_alt(
3946 body()->ToNode(
3947 compiler,
3948 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003949 position_register,
3950 register_count,
3951 register_start)));
3952 ChoiceNode* choice_node =
3953 new NegativeLookaheadChoiceNode(body_alt,
3954 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003955 return ActionNode::BeginSubmatch(stack_pointer_register,
3956 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003957 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003958 }
3959}
3960
3961
3962RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003963 RegExpNode* on_success) {
3964 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003965}
3966
3967
3968RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3969 int index,
3970 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003971 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003972 int start_reg = RegExpCapture::StartRegister(index);
3973 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003974 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003975 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003976 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003977}
3978
3979
3980RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003981 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003982 ZoneList<RegExpTree*>* children = nodes();
3983 RegExpNode* current = on_success;
3984 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003985 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003986 }
3987 return current;
3988}
3989
3990
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003991static void AddClass(const uc16* elmv,
3992 int elmc,
3993 ZoneList<CharacterRange>* ranges) {
3994 for (int i = 0; i < elmc; i += 2) {
3995 ASSERT(elmv[i] <= elmv[i + 1]);
3996 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3997 }
3998}
3999
4000
4001static void AddClassNegated(const uc16 *elmv,
4002 int elmc,
4003 ZoneList<CharacterRange>* ranges) {
4004 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00004005 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004006 uc16 last = 0x0000;
4007 for (int i = 0; i < elmc; i += 2) {
4008 ASSERT(last <= elmv[i] - 1);
4009 ASSERT(elmv[i] <= elmv[i + 1]);
4010 ranges->Add(CharacterRange(last, elmv[i] - 1));
4011 last = elmv[i + 1] + 1;
4012 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004013 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004014}
4015
4016
4017void CharacterRange::AddClassEscape(uc16 type,
4018 ZoneList<CharacterRange>* ranges) {
4019 switch (type) {
4020 case 's':
4021 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
4022 break;
4023 case 'S':
4024 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
4025 break;
4026 case 'w':
4027 AddClass(kWordRanges, kWordRangeCount, ranges);
4028 break;
4029 case 'W':
4030 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
4031 break;
4032 case 'd':
4033 AddClass(kDigitRanges, kDigitRangeCount, ranges);
4034 break;
4035 case 'D':
4036 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
4037 break;
4038 case '.':
4039 AddClassNegated(kLineTerminatorRanges,
4040 kLineTerminatorRangeCount,
4041 ranges);
4042 break;
4043 // This is not a character range as defined by the spec but a
4044 // convenient shorthand for a character class that matches any
4045 // character.
4046 case '*':
4047 ranges->Add(CharacterRange::Everything());
4048 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004049 // This is the set of characters matched by the $ and ^ symbols
4050 // in multiline mode.
4051 case 'n':
4052 AddClass(kLineTerminatorRanges,
4053 kLineTerminatorRangeCount,
4054 ranges);
4055 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004056 default:
4057 UNREACHABLE();
4058 }
4059}
4060
4061
4062Vector<const uc16> CharacterRange::GetWordBounds() {
4063 return Vector<const uc16>(kWordRanges, kWordRangeCount);
4064}
4065
4066
4067class CharacterRangeSplitter {
4068 public:
4069 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
4070 ZoneList<CharacterRange>** excluded)
4071 : included_(included),
4072 excluded_(excluded) { }
4073 void Call(uc16 from, DispatchTable::Entry entry);
4074
4075 static const int kInBase = 0;
4076 static const int kInOverlay = 1;
4077
4078 private:
4079 ZoneList<CharacterRange>** included_;
4080 ZoneList<CharacterRange>** excluded_;
4081};
4082
4083
4084void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
4085 if (!entry.out_set()->Get(kInBase)) return;
4086 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
4087 ? included_
4088 : excluded_;
4089 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
4090 (*target)->Add(CharacterRange(entry.from(), entry.to()));
4091}
4092
4093
4094void CharacterRange::Split(ZoneList<CharacterRange>* base,
4095 Vector<const uc16> overlay,
4096 ZoneList<CharacterRange>** included,
4097 ZoneList<CharacterRange>** excluded) {
4098 ASSERT_EQ(NULL, *included);
4099 ASSERT_EQ(NULL, *excluded);
4100 DispatchTable table;
4101 for (int i = 0; i < base->length(); i++)
4102 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
4103 for (int i = 0; i < overlay.length(); i += 2) {
4104 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
4105 CharacterRangeSplitter::kInOverlay);
4106 }
4107 CharacterRangeSplitter callback(included, excluded);
4108 table.ForEach(&callback);
4109}
4110
4111
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004112static void AddUncanonicals(Isolate* isolate,
4113 ZoneList<CharacterRange>* ranges,
ager@chromium.org38e4c712009-11-11 09:11:58 +00004114 int bottom,
4115 int top);
4116
4117
4118void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4119 bool is_ascii) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004120 Isolate* isolate = Isolate::Current();
ager@chromium.org38e4c712009-11-11 09:11:58 +00004121 uc16 bottom = from();
4122 uc16 top = to();
4123 if (is_ascii) {
4124 if (bottom > String::kMaxAsciiCharCode) return;
4125 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4126 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004127 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004128 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004129 // If this is a singleton we just expand the one character.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004130 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004131 for (int i = 0; i < length; i++) {
4132 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004133 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004134 ranges->Add(CharacterRange::Singleton(chars[i]));
4135 }
4136 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004137 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004138 // If this is a range we expand the characters block by block,
4139 // expanding contiguous subranges (blocks) one at a time.
4140 // The approach is as follows. For a given start character we
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004141 // look up the remainder of the block that contains it (represented
4142 // by the end point), for instance we find 'z' if the character
4143 // is 'c'. A block is characterized by the property
4144 // that all characters uncanonicalize in the same way, except that
4145 // each entry in the result is incremented by the distance from the first
4146 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
4147 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
4148 // Once we've found the end point we look up its uncanonicalization
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004149 // and produce a range for each element. For instance for [c-f]
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004150 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004151 // add a range if it is not already contained in the input, so [c-f]
4152 // will be skipped but [C-F] will be added. If this range is not
4153 // completely contained in a block we do this for all the blocks
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004154 // covered by the range (handling characters that is not in a block
4155 // as a "singleton block").
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004156 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004157 int pos = bottom;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004158 while (pos < top) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004159 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004160 uc16 block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004161 if (length == 0) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004162 block_end = pos;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004163 } else {
4164 ASSERT_EQ(1, length);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004165 block_end = range[0];
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004166 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004167 int end = (block_end > top) ? top : block_end;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004168 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004169 for (int i = 0; i < length; i++) {
4170 uc32 c = range[i];
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004171 uc16 range_from = c - (block_end - pos);
4172 uc16 range_to = c - (block_end - end);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004173 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004174 ranges->Add(CharacterRange(range_from, range_to));
4175 }
4176 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004177 pos = end + 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004178 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004179 }
4180}
4181
4182
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004183bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4184 ASSERT_NOT_NULL(ranges);
4185 int n = ranges->length();
4186 if (n <= 1) return true;
4187 int max = ranges->at(0).to();
4188 for (int i = 1; i < n; i++) {
4189 CharacterRange next_range = ranges->at(i);
4190 if (next_range.from() <= max + 1) return false;
4191 max = next_range.to();
4192 }
4193 return true;
4194}
4195
4196SetRelation CharacterRange::WordCharacterRelation(
4197 ZoneList<CharacterRange>* range) {
4198 ASSERT(IsCanonical(range));
4199 int i = 0; // Word character range index.
4200 int j = 0; // Argument range index.
4201 ASSERT_NE(0, kWordRangeCount);
4202 SetRelation result;
4203 if (range->length() == 0) {
4204 result.SetElementsInSecondSet();
4205 return result;
4206 }
4207 CharacterRange argument_range = range->at(0);
4208 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4209 while (i < kWordRangeCount && j < range->length()) {
4210 // Check the two ranges for the five cases:
4211 // - no overlap.
4212 // - partial overlap (there are elements in both ranges that isn't
4213 // in the other, and there are also elements that are in both).
4214 // - argument range entirely inside word range.
4215 // - word range entirely inside argument range.
4216 // - ranges are completely equal.
4217
4218 // First check for no overlap. The earlier range is not in the other set.
4219 if (argument_range.from() > word_range.to()) {
4220 // Ranges are disjoint. The earlier word range contains elements that
4221 // cannot be in the argument set.
4222 result.SetElementsInSecondSet();
4223 } else if (word_range.from() > argument_range.to()) {
4224 // Ranges are disjoint. The earlier argument range contains elements that
4225 // cannot be in the word set.
4226 result.SetElementsInFirstSet();
4227 } else if (word_range.from() <= argument_range.from() &&
4228 word_range.to() >= argument_range.from()) {
4229 result.SetElementsInBothSets();
4230 // argument range completely inside word range.
4231 if (word_range.from() < argument_range.from() ||
4232 word_range.to() > argument_range.from()) {
4233 result.SetElementsInSecondSet();
4234 }
4235 } else if (word_range.from() >= argument_range.from() &&
4236 word_range.to() <= argument_range.from()) {
4237 result.SetElementsInBothSets();
4238 result.SetElementsInFirstSet();
4239 } else {
4240 // There is overlap, and neither is a subrange of the other
4241 result.SetElementsInFirstSet();
4242 result.SetElementsInSecondSet();
4243 result.SetElementsInBothSets();
4244 }
4245 if (result.NonTrivialIntersection()) {
4246 // The result is as (im)precise as we can possibly make it.
4247 return result;
4248 }
4249 // Progress the range(s) with minimal to-character.
4250 uc16 word_to = word_range.to();
4251 uc16 argument_to = argument_range.to();
4252 if (argument_to <= word_to) {
4253 j++;
4254 if (j < range->length()) {
4255 argument_range = range->at(j);
4256 }
4257 }
4258 if (word_to <= argument_to) {
4259 i += 2;
4260 if (i < kWordRangeCount) {
4261 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4262 }
4263 }
4264 }
4265 // Check if anything wasn't compared in the loop.
4266 if (i < kWordRangeCount) {
4267 // word range contains something not in argument range.
4268 result.SetElementsInSecondSet();
4269 } else if (j < range->length()) {
4270 // Argument range contains something not in word range.
4271 result.SetElementsInFirstSet();
4272 }
4273
4274 return result;
4275}
4276
4277
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004278static void AddUncanonicals(Isolate* isolate,
4279 ZoneList<CharacterRange>* ranges,
ager@chromium.org38e4c712009-11-11 09:11:58 +00004280 int bottom,
4281 int top) {
4282 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4283 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4284 // this table is correct.
4285 // 0x0600 - 0x0fff
4286 // 0x1100 - 0x1cff
4287 // 0x2000 - 0x20ff
4288 // 0x2200 - 0x23ff
4289 // 0x2500 - 0x2bff
4290 // 0x2e00 - 0xa5ff
4291 // 0xa800 - 0xfaff
4292 // 0xfc00 - 0xfeff
4293 const int boundary_count = 18;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004294 int boundaries[] = {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004295 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4296 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4297
4298 // Special ASCII rule from spec can save us some work here.
4299 if (bottom == 0x80 && top == 0xffff) return;
4300
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004301 if (top <= boundaries[0]) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004302 CharacterRange range(bottom, top);
4303 range.AddCaseEquivalents(ranges, false);
4304 return;
4305 }
4306
4307 // Split up very large ranges. This helps remove ranges where there are no
4308 // case mappings.
4309 for (int i = 0; i < boundary_count; i++) {
4310 if (bottom < boundaries[i] && top >= boundaries[i]) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004311 AddUncanonicals(isolate, ranges, bottom, boundaries[i] - 1);
4312 AddUncanonicals(isolate, ranges, boundaries[i], top);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004313 return;
4314 }
4315 }
4316
4317 // If we are completely in a zone with no case mappings then we are done.
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004318 for (int i = 0; i < boundary_count; i += 2) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004319 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4320#ifdef DEBUG
4321 for (int j = bottom; j <= top; j++) {
4322 unsigned current_char = j;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004323 int length = isolate->jsregexp_uncanonicalize()->get(current_char,
4324 '\0', chars);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004325 for (int k = 0; k < length; k++) {
4326 ASSERT(chars[k] == current_char);
4327 }
4328 }
4329#endif
4330 return;
4331 }
4332 }
4333
4334 // Step through the range finding equivalent characters.
4335 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4336 for (int i = bottom; i <= top; i++) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004337 int length = isolate->jsregexp_uncanonicalize()->get(i, '\0', chars);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004338 for (int j = 0; j < length; j++) {
4339 uc32 chr = chars[j];
4340 if (chr != i && (chr < bottom || chr > top)) {
4341 characters->Add(chr);
4342 }
4343 }
4344 }
4345
4346 // Step through the equivalent characters finding simple ranges and
4347 // adding ranges to the character class.
4348 if (characters->length() > 0) {
4349 int new_from = characters->at(0);
4350 int new_to = new_from;
4351 for (int i = 1; i < characters->length(); i++) {
4352 int chr = characters->at(i);
4353 if (chr == new_to + 1) {
4354 new_to++;
4355 } else {
4356 if (new_to == new_from) {
4357 ranges->Add(CharacterRange::Singleton(new_from));
4358 } else {
4359 ranges->Add(CharacterRange(new_from, new_to));
4360 }
4361 new_from = new_to = chr;
4362 }
4363 }
4364 if (new_to == new_from) {
4365 ranges->Add(CharacterRange::Singleton(new_from));
4366 } else {
4367 ranges->Add(CharacterRange(new_from, new_to));
4368 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004369 }
4370}
4371
4372
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004373ZoneList<CharacterRange>* CharacterSet::ranges() {
4374 if (ranges_ == NULL) {
4375 ranges_ = new ZoneList<CharacterRange>(2);
4376 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4377 }
4378 return ranges_;
4379}
4380
4381
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004382// Move a number of elements in a zonelist to another position
4383// in the same list. Handles overlapping source and target areas.
4384static void MoveRanges(ZoneList<CharacterRange>* list,
4385 int from,
4386 int to,
4387 int count) {
4388 // Ranges are potentially overlapping.
4389 if (from < to) {
4390 for (int i = count - 1; i >= 0; i--) {
4391 list->at(to + i) = list->at(from + i);
4392 }
4393 } else {
4394 for (int i = 0; i < count; i++) {
4395 list->at(to + i) = list->at(from + i);
4396 }
4397 }
4398}
4399
4400
4401static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4402 int count,
4403 CharacterRange insert) {
4404 // Inserts a range into list[0..count[, which must be sorted
4405 // by from value and non-overlapping and non-adjacent, using at most
4406 // list[0..count] for the result. Returns the number of resulting
4407 // canonicalized ranges. Inserting a range may collapse existing ranges into
4408 // fewer ranges, so the return value can be anything in the range 1..count+1.
4409 uc16 from = insert.from();
4410 uc16 to = insert.to();
4411 int start_pos = 0;
4412 int end_pos = count;
4413 for (int i = count - 1; i >= 0; i--) {
4414 CharacterRange current = list->at(i);
4415 if (current.from() > to + 1) {
4416 end_pos = i;
4417 } else if (current.to() + 1 < from) {
4418 start_pos = i + 1;
4419 break;
4420 }
4421 }
4422
4423 // Inserted range overlaps, or is adjacent to, ranges at positions
4424 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4425 // not affected by the insertion.
4426 // If start_pos == end_pos, the range must be inserted before start_pos.
4427 // if start_pos < end_pos, the entire range from start_pos to end_pos
4428 // must be merged with the insert range.
4429
4430 if (start_pos == end_pos) {
4431 // Insert between existing ranges at position start_pos.
4432 if (start_pos < count) {
4433 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4434 }
4435 list->at(start_pos) = insert;
4436 return count + 1;
4437 }
4438 if (start_pos + 1 == end_pos) {
4439 // Replace single existing range at position start_pos.
4440 CharacterRange to_replace = list->at(start_pos);
4441 int new_from = Min(to_replace.from(), from);
4442 int new_to = Max(to_replace.to(), to);
4443 list->at(start_pos) = CharacterRange(new_from, new_to);
4444 return count;
4445 }
4446 // Replace a number of existing ranges from start_pos to end_pos - 1.
4447 // Move the remaining ranges down.
4448
4449 int new_from = Min(list->at(start_pos).from(), from);
4450 int new_to = Max(list->at(end_pos - 1).to(), to);
4451 if (end_pos < count) {
4452 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4453 }
4454 list->at(start_pos) = CharacterRange(new_from, new_to);
4455 return count - (end_pos - start_pos) + 1;
4456}
4457
4458
4459void CharacterSet::Canonicalize() {
4460 // Special/default classes are always considered canonical. The result
4461 // of calling ranges() will be sorted.
4462 if (ranges_ == NULL) return;
4463 CharacterRange::Canonicalize(ranges_);
4464}
4465
4466
4467void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4468 if (character_ranges->length() <= 1) return;
4469 // Check whether ranges are already canonical (increasing, non-overlapping,
4470 // non-adjacent).
4471 int n = character_ranges->length();
4472 int max = character_ranges->at(0).to();
4473 int i = 1;
4474 while (i < n) {
4475 CharacterRange current = character_ranges->at(i);
4476 if (current.from() <= max + 1) {
4477 break;
4478 }
4479 max = current.to();
4480 i++;
4481 }
4482 // Canonical until the i'th range. If that's all of them, we are done.
4483 if (i == n) return;
4484
4485 // The ranges at index i and forward are not canonicalized. Make them so by
4486 // doing the equivalent of insertion sort (inserting each into the previous
4487 // list, in order).
4488 // Notice that inserting a range can reduce the number of ranges in the
4489 // result due to combining of adjacent and overlapping ranges.
4490 int read = i; // Range to insert.
4491 int num_canonical = i; // Length of canonicalized part of list.
4492 do {
4493 num_canonical = InsertRangeInCanonicalList(character_ranges,
4494 num_canonical,
4495 character_ranges->at(read));
4496 read++;
4497 } while (read < n);
4498 character_ranges->Rewind(num_canonical);
4499
4500 ASSERT(CharacterRange::IsCanonical(character_ranges));
4501}
4502
4503
4504// Utility function for CharacterRange::Merge. Adds a range at the end of
4505// a canonicalized range list, if necessary merging the range with the last
4506// range of the list.
4507static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4508 if (set == NULL) return;
4509 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4510 int n = set->length();
4511 if (n > 0) {
4512 CharacterRange lastRange = set->at(n - 1);
4513 if (lastRange.to() == range.from() - 1) {
4514 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4515 return;
4516 }
4517 }
4518 set->Add(range);
4519}
4520
4521
4522static void AddRangeToSelectedSet(int selector,
4523 ZoneList<CharacterRange>* first_set,
4524 ZoneList<CharacterRange>* second_set,
4525 ZoneList<CharacterRange>* intersection_set,
4526 CharacterRange range) {
4527 switch (selector) {
4528 case kInsideFirst:
4529 AddRangeToSet(first_set, range);
4530 break;
4531 case kInsideSecond:
4532 AddRangeToSet(second_set, range);
4533 break;
4534 case kInsideBoth:
4535 AddRangeToSet(intersection_set, range);
4536 break;
4537 }
4538}
4539
4540
4541
4542void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4543 ZoneList<CharacterRange>* second_set,
4544 ZoneList<CharacterRange>* first_set_only_out,
4545 ZoneList<CharacterRange>* second_set_only_out,
4546 ZoneList<CharacterRange>* both_sets_out) {
4547 // Inputs are canonicalized.
4548 ASSERT(CharacterRange::IsCanonical(first_set));
4549 ASSERT(CharacterRange::IsCanonical(second_set));
4550 // Outputs are empty, if applicable.
4551 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4552 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4553 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4554
4555 // Merge sets by iterating through the lists in order of lowest "from" value,
4556 // and putting intervals into one of three sets.
4557
4558 if (first_set->length() == 0) {
4559 second_set_only_out->AddAll(*second_set);
4560 return;
4561 }
4562 if (second_set->length() == 0) {
4563 first_set_only_out->AddAll(*first_set);
4564 return;
4565 }
4566 // Indices into input lists.
4567 int i1 = 0;
4568 int i2 = 0;
4569 // Cache length of input lists.
4570 int n1 = first_set->length();
4571 int n2 = second_set->length();
4572 // Current range. May be invalid if state is kInsideNone.
4573 int from = 0;
4574 int to = -1;
4575 // Where current range comes from.
4576 int state = kInsideNone;
4577
4578 while (i1 < n1 || i2 < n2) {
4579 CharacterRange next_range;
4580 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004581 if (i2 == n2 ||
4582 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4583 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004584 next_range = first_set->at(i1++);
4585 range_source = kInsideFirst;
4586 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004587 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004588 next_range = second_set->at(i2++);
4589 range_source = kInsideSecond;
4590 }
4591 if (to < next_range.from()) {
4592 // Ranges disjoint: |current| |next|
4593 AddRangeToSelectedSet(state,
4594 first_set_only_out,
4595 second_set_only_out,
4596 both_sets_out,
4597 CharacterRange(from, to));
4598 from = next_range.from();
4599 to = next_range.to();
4600 state = range_source;
4601 } else {
4602 if (from < next_range.from()) {
4603 AddRangeToSelectedSet(state,
4604 first_set_only_out,
4605 second_set_only_out,
4606 both_sets_out,
4607 CharacterRange(from, next_range.from()-1));
4608 }
4609 if (to < next_range.to()) {
4610 // Ranges overlap: |current|
4611 // |next|
4612 AddRangeToSelectedSet(state | range_source,
4613 first_set_only_out,
4614 second_set_only_out,
4615 both_sets_out,
4616 CharacterRange(next_range.from(), to));
4617 from = to + 1;
4618 to = next_range.to();
4619 state = range_source;
4620 } else {
4621 // Range included: |current| , possibly ending at same character.
4622 // |next|
4623 AddRangeToSelectedSet(
4624 state | range_source,
4625 first_set_only_out,
4626 second_set_only_out,
4627 both_sets_out,
4628 CharacterRange(next_range.from(), next_range.to()));
4629 from = next_range.to() + 1;
4630 // If ranges end at same character, both ranges are consumed completely.
4631 if (next_range.to() == to) state = kInsideNone;
4632 }
4633 }
4634 }
4635 AddRangeToSelectedSet(state,
4636 first_set_only_out,
4637 second_set_only_out,
4638 both_sets_out,
4639 CharacterRange(from, to));
4640}
4641
4642
4643void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4644 ZoneList<CharacterRange>* negated_ranges) {
4645 ASSERT(CharacterRange::IsCanonical(ranges));
4646 ASSERT_EQ(0, negated_ranges->length());
4647 int range_count = ranges->length();
4648 uc16 from = 0;
4649 int i = 0;
4650 if (range_count > 0 && ranges->at(0).from() == 0) {
4651 from = ranges->at(0).to();
4652 i = 1;
4653 }
4654 while (i < range_count) {
4655 CharacterRange range = ranges->at(i);
4656 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4657 from = range.to();
4658 i++;
4659 }
4660 if (from < String::kMaxUC16CharCode) {
4661 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4662 }
4663}
4664
4665
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004666
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004667// -------------------------------------------------------------------
4668// Interest propagation
4669
4670
4671RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4672 for (int i = 0; i < siblings_.length(); i++) {
4673 RegExpNode* sibling = siblings_.Get(i);
4674 if (sibling->info()->Matches(info))
4675 return sibling;
4676 }
4677 return NULL;
4678}
4679
4680
4681RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4682 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004683 siblings_.Ensure(this);
4684 RegExpNode* result = TryGetSibling(info);
4685 if (result != NULL) return result;
4686 result = this->Clone();
4687 NodeInfo* new_info = result->info();
4688 new_info->ResetCompilationState();
4689 new_info->AddFromPreceding(info);
4690 AddSibling(result);
4691 *cloned = true;
4692 return result;
4693}
4694
4695
4696template <class C>
4697static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4698 NodeInfo full_info(*node->info());
4699 full_info.AddFromPreceding(info);
4700 bool cloned = false;
4701 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4702}
4703
4704
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004705// -------------------------------------------------------------------
4706// Splay tree
4707
4708
4709OutSet* OutSet::Extend(unsigned value) {
4710 if (Get(value))
4711 return this;
4712 if (successors() != NULL) {
4713 for (int i = 0; i < successors()->length(); i++) {
4714 OutSet* successor = successors()->at(i);
4715 if (successor->Get(value))
4716 return successor;
4717 }
4718 } else {
4719 successors_ = new ZoneList<OutSet*>(2);
4720 }
4721 OutSet* result = new OutSet(first_, remaining_);
4722 result->Set(value);
4723 successors()->Add(result);
4724 return result;
4725}
4726
4727
4728void OutSet::Set(unsigned value) {
4729 if (value < kFirstLimit) {
4730 first_ |= (1 << value);
4731 } else {
4732 if (remaining_ == NULL)
4733 remaining_ = new ZoneList<unsigned>(1);
4734 if (remaining_->is_empty() || !remaining_->Contains(value))
4735 remaining_->Add(value);
4736 }
4737}
4738
4739
4740bool OutSet::Get(unsigned value) {
4741 if (value < kFirstLimit) {
4742 return (first_ & (1 << value)) != 0;
4743 } else if (remaining_ == NULL) {
4744 return false;
4745 } else {
4746 return remaining_->Contains(value);
4747 }
4748}
4749
4750
4751const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4752const DispatchTable::Entry DispatchTable::Config::kNoValue;
4753
4754
4755void DispatchTable::AddRange(CharacterRange full_range, int value) {
4756 CharacterRange current = full_range;
4757 if (tree()->is_empty()) {
4758 // If this is the first range we just insert into the table.
4759 ZoneSplayTree<Config>::Locator loc;
4760 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4761 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4762 return;
4763 }
4764 // First see if there is a range to the left of this one that
4765 // overlaps.
4766 ZoneSplayTree<Config>::Locator loc;
4767 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4768 Entry* entry = &loc.value();
4769 // If we've found a range that overlaps with this one, and it
4770 // starts strictly to the left of this one, we have to fix it
4771 // because the following code only handles ranges that start on
4772 // or after the start point of the range we're adding.
4773 if (entry->from() < current.from() && entry->to() >= current.from()) {
4774 // Snap the overlapping range in half around the start point of
4775 // the range we're adding.
4776 CharacterRange left(entry->from(), current.from() - 1);
4777 CharacterRange right(current.from(), entry->to());
4778 // The left part of the overlapping range doesn't overlap.
4779 // Truncate the whole entry to be just the left part.
4780 entry->set_to(left.to());
4781 // The right part is the one that overlaps. We add this part
4782 // to the map and let the next step deal with merging it with
4783 // the range we're adding.
4784 ZoneSplayTree<Config>::Locator loc;
4785 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4786 loc.set_value(Entry(right.from(),
4787 right.to(),
4788 entry->out_set()));
4789 }
4790 }
4791 while (current.is_valid()) {
4792 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4793 (loc.value().from() <= current.to()) &&
4794 (loc.value().to() >= current.from())) {
4795 Entry* entry = &loc.value();
4796 // We have overlap. If there is space between the start point of
4797 // the range we're adding and where the overlapping range starts
4798 // then we have to add a range covering just that space.
4799 if (current.from() < entry->from()) {
4800 ZoneSplayTree<Config>::Locator ins;
4801 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4802 ins.set_value(Entry(current.from(),
4803 entry->from() - 1,
4804 empty()->Extend(value)));
4805 current.set_from(entry->from());
4806 }
4807 ASSERT_EQ(current.from(), entry->from());
4808 // If the overlapping range extends beyond the one we want to add
4809 // we have to snap the right part off and add it separately.
4810 if (entry->to() > current.to()) {
4811 ZoneSplayTree<Config>::Locator ins;
4812 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4813 ins.set_value(Entry(current.to() + 1,
4814 entry->to(),
4815 entry->out_set()));
4816 entry->set_to(current.to());
4817 }
4818 ASSERT(entry->to() <= current.to());
4819 // The overlapping range is now completely contained by the range
4820 // we're adding so we can just update it and move the start point
4821 // of the range we're adding just past it.
4822 entry->AddValue(value);
4823 // Bail out if the last interval ended at 0xFFFF since otherwise
4824 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004825 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004826 break;
4827 ASSERT(entry->to() + 1 > current.from());
4828 current.set_from(entry->to() + 1);
4829 } else {
4830 // There is no overlap so we can just add the range
4831 ZoneSplayTree<Config>::Locator ins;
4832 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4833 ins.set_value(Entry(current.from(),
4834 current.to(),
4835 empty()->Extend(value)));
4836 break;
4837 }
4838 }
4839}
4840
4841
4842OutSet* DispatchTable::Get(uc16 value) {
4843 ZoneSplayTree<Config>::Locator loc;
4844 if (!tree()->FindGreatestLessThan(value, &loc))
4845 return empty();
4846 Entry* entry = &loc.value();
4847 if (value <= entry->to())
4848 return entry->out_set();
4849 else
4850 return empty();
4851}
4852
4853
4854// -------------------------------------------------------------------
4855// Analysis
4856
4857
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004858void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004859 StackLimitCheck check(Isolate::Current());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004860 if (check.HasOverflowed()) {
4861 fail("Stack overflow");
4862 return;
4863 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004864 if (that->info()->been_analyzed || that->info()->being_analyzed)
4865 return;
4866 that->info()->being_analyzed = true;
4867 that->Accept(this);
4868 that->info()->being_analyzed = false;
4869 that->info()->been_analyzed = true;
4870}
4871
4872
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004873void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004874 // nothing to do
4875}
4876
4877
ager@chromium.org8bb60582008-12-11 12:02:20 +00004878void TextNode::CalculateOffsets() {
4879 int element_count = elements()->length();
4880 // Set up the offsets of the elements relative to the start. This is a fixed
4881 // quantity since a TextNode can only contain fixed-width things.
4882 int cp_offset = 0;
4883 for (int i = 0; i < element_count; i++) {
4884 TextElement& elm = elements()->at(i);
4885 elm.cp_offset = cp_offset;
4886 if (elm.type == TextElement::ATOM) {
4887 cp_offset += elm.data.u_atom->data().length();
4888 } else {
4889 cp_offset++;
4890 Vector<const uc16> quarks = elm.data.u_atom->data();
4891 }
4892 }
4893}
4894
4895
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004896void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004897 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004898 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004899 }
4900 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004901 if (!has_failed()) {
4902 that->CalculateOffsets();
4903 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004904}
4905
4906
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004907void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004908 RegExpNode* target = that->on_success();
4909 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004910 if (!has_failed()) {
4911 // If the next node is interested in what it follows then this node
4912 // has to be interested too so it can pass the information on.
4913 that->info()->AddFromFollowing(target->info());
4914 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004915}
4916
4917
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004918void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004919 NodeInfo* info = that->info();
4920 for (int i = 0; i < that->alternatives()->length(); i++) {
4921 RegExpNode* node = that->alternatives()->at(i).node();
4922 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004923 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004924 // Anything the following nodes need to know has to be known by
4925 // this node also, so it can pass it on.
4926 info->AddFromFollowing(node->info());
4927 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004928}
4929
4930
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004931void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4932 NodeInfo* info = that->info();
4933 for (int i = 0; i < that->alternatives()->length(); i++) {
4934 RegExpNode* node = that->alternatives()->at(i).node();
4935 if (node != that->loop_node()) {
4936 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004937 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004938 info->AddFromFollowing(node->info());
4939 }
4940 }
4941 // Check the loop last since it may need the value of this node
4942 // to get a correct result.
4943 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004944 if (!has_failed()) {
4945 info->AddFromFollowing(that->loop_node()->info());
4946 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004947}
4948
4949
4950void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004951 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004952}
4953
4954
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004955void Analysis::VisitAssertion(AssertionNode* that) {
4956 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004957 AssertionNode::AssertionNodeType type = that->type();
4958 if (type == AssertionNode::AT_BOUNDARY ||
4959 type == AssertionNode::AT_NON_BOUNDARY) {
4960 // Check if the following character is known to be a word character
4961 // or known to not be a word character.
4962 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4963
4964 CharacterRange::Canonicalize(following_chars);
4965
4966 SetRelation word_relation =
4967 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004968 if (word_relation.Disjoint()) {
4969 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004970 // Following character is definitely *not* a word character.
4971 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004972 AssertionNode::AFTER_WORD_CHARACTER :
4973 AssertionNode::AFTER_NONWORD_CHARACTER;
4974 that->set_type(type);
4975 } else if (word_relation.ContainedIn()) {
4976 // Following character is definitely a word character.
4977 type = (type == AssertionNode::AT_BOUNDARY) ?
4978 AssertionNode::AFTER_NONWORD_CHARACTER :
4979 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004980 that->set_type(type);
4981 }
4982 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004983}
4984
4985
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004986ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4987 if (first_character_set_ == NULL) {
4988 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4989 // If we can't find an exact solution within the budget, we
4990 // set the value to the set of every character, i.e., all characters
4991 // are possible.
4992 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4993 all_set->Add(CharacterRange::Everything());
4994 first_character_set_ = all_set;
4995 }
4996 }
4997 return first_character_set_;
4998}
4999
5000
5001int RegExpNode::ComputeFirstCharacterSet(int budget) {
5002 // Default behavior is to not be able to determine the first character.
5003 return kComputeFirstCharacterSetFail;
5004}
5005
5006
5007int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
5008 budget--;
5009 if (budget >= 0) {
5010 // Find loop min-iteration. It's the value of the guarded choice node
5011 // with a GEQ guard, if any.
5012 int min_repetition = 0;
5013
5014 for (int i = 0; i <= 1; i++) {
5015 GuardedAlternative alternative = alternatives()->at(i);
5016 ZoneList<Guard*>* guards = alternative.guards();
5017 if (guards != NULL && guards->length() > 0) {
5018 Guard* guard = guards->at(0);
5019 if (guard->op() == Guard::GEQ) {
5020 min_repetition = guard->value();
5021 break;
5022 }
5023 }
5024 }
5025
5026 budget = loop_node()->ComputeFirstCharacterSet(budget);
5027 if (budget >= 0) {
5028 ZoneList<CharacterRange>* character_set =
5029 loop_node()->first_character_set();
5030 if (body_can_be_zero_length() || min_repetition == 0) {
5031 budget = continue_node()->ComputeFirstCharacterSet(budget);
5032 if (budget < 0) return budget;
5033 ZoneList<CharacterRange>* body_set =
5034 continue_node()->first_character_set();
5035 ZoneList<CharacterRange>* union_set =
5036 new ZoneList<CharacterRange>(Max(character_set->length(),
5037 body_set->length()));
5038 CharacterRange::Merge(character_set,
5039 body_set,
5040 union_set,
5041 union_set,
5042 union_set);
5043 character_set = union_set;
5044 }
5045 set_first_character_set(character_set);
5046 }
5047 }
5048 return budget;
5049}
5050
5051
5052int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
5053 budget--;
5054 if (budget >= 0) {
5055 GuardedAlternative successor = this->alternatives()->at(1);
5056 RegExpNode* successor_node = successor.node();
5057 budget = successor_node->ComputeFirstCharacterSet(budget);
5058 if (budget >= 0) {
5059 set_first_character_set(successor_node->first_character_set());
5060 }
5061 }
5062 return budget;
5063}
5064
5065
5066// The first character set of an EndNode is unknowable. Just use the
5067// default implementation that fails and returns all characters as possible.
5068
5069
5070int AssertionNode::ComputeFirstCharacterSet(int budget) {
5071 budget -= 1;
5072 if (budget >= 0) {
5073 switch (type_) {
5074 case AT_END: {
5075 set_first_character_set(new ZoneList<CharacterRange>(0));
5076 break;
5077 }
5078 case AT_START:
5079 case AT_BOUNDARY:
5080 case AT_NON_BOUNDARY:
5081 case AFTER_NEWLINE:
5082 case AFTER_NONWORD_CHARACTER:
5083 case AFTER_WORD_CHARACTER: {
5084 ASSERT_NOT_NULL(on_success());
5085 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005086 if (budget >= 0) {
5087 set_first_character_set(on_success()->first_character_set());
5088 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005089 break;
5090 }
5091 }
5092 }
5093 return budget;
5094}
5095
5096
5097int ActionNode::ComputeFirstCharacterSet(int budget) {
5098 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
5099 budget--;
5100 if (budget >= 0) {
5101 ASSERT_NOT_NULL(on_success());
5102 budget = on_success()->ComputeFirstCharacterSet(budget);
5103 if (budget >= 0) {
5104 set_first_character_set(on_success()->first_character_set());
5105 }
5106 }
5107 return budget;
5108}
5109
5110
5111int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5112 // We don't know anything about the first character of a backreference
5113 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005114 // The potential first characters are the first characters of the capture,
5115 // and the first characters of the on_success node, depending on whether the
5116 // capture can be empty and whether it is known to be participating or known
5117 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005118 return kComputeFirstCharacterSetFail;
5119}
5120
5121
5122int TextNode::ComputeFirstCharacterSet(int budget) {
5123 budget--;
5124 if (budget >= 0) {
5125 ASSERT_NE(0, elements()->length());
5126 TextElement text = elements()->at(0);
5127 if (text.type == TextElement::ATOM) {
5128 RegExpAtom* atom = text.data.u_atom;
5129 ASSERT_NE(0, atom->length());
5130 uc16 first_char = atom->data()[0];
5131 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5132 range->Add(CharacterRange(first_char, first_char));
5133 set_first_character_set(range);
5134 } else {
5135 ASSERT(text.type == TextElement::CHAR_CLASS);
5136 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005137 ZoneList<CharacterRange>* ranges = char_class->ranges();
5138 // TODO(lrn): Canonicalize ranges when they are created
5139 // instead of waiting until now.
5140 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005141 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005142 int length = ranges->length();
5143 int new_length = length + 1;
5144 if (length > 0) {
5145 if (ranges->at(0).from() == 0) new_length--;
5146 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5147 new_length--;
5148 }
5149 }
5150 ZoneList<CharacterRange>* negated_ranges =
5151 new ZoneList<CharacterRange>(new_length);
5152 CharacterRange::Negate(ranges, negated_ranges);
5153 set_first_character_set(negated_ranges);
5154 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005155 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005156 }
5157 }
5158 }
5159 return budget;
5160}
5161
5162
5163
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005164// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005165// Dispatch table construction
5166
5167
5168void DispatchTableConstructor::VisitEnd(EndNode* that) {
5169 AddRange(CharacterRange::Everything());
5170}
5171
5172
5173void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5174 node->set_being_calculated(true);
5175 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5176 for (int i = 0; i < alternatives->length(); i++) {
5177 set_choice_index(i);
5178 alternatives->at(i).node()->Accept(this);
5179 }
5180 node->set_being_calculated(false);
5181}
5182
5183
5184class AddDispatchRange {
5185 public:
5186 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5187 : constructor_(constructor) { }
5188 void Call(uc32 from, DispatchTable::Entry entry);
5189 private:
5190 DispatchTableConstructor* constructor_;
5191};
5192
5193
5194void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5195 CharacterRange range(from, entry.to());
5196 constructor_->AddRange(range);
5197}
5198
5199
5200void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5201 if (node->being_calculated())
5202 return;
5203 DispatchTable* table = node->GetTable(ignore_case_);
5204 AddDispatchRange adder(this);
5205 table->ForEach(&adder);
5206}
5207
5208
5209void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5210 // TODO(160): Find the node that we refer back to and propagate its start
5211 // set back to here. For now we just accept anything.
5212 AddRange(CharacterRange::Everything());
5213}
5214
5215
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005216void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5217 RegExpNode* target = that->on_success();
5218 target->Accept(this);
5219}
5220
5221
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005222static int CompareRangeByFrom(const CharacterRange* a,
5223 const CharacterRange* b) {
5224 return Compare<uc16>(a->from(), b->from());
5225}
5226
5227
5228void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5229 ranges->Sort(CompareRangeByFrom);
5230 uc16 last = 0;
5231 for (int i = 0; i < ranges->length(); i++) {
5232 CharacterRange range = ranges->at(i);
5233 if (last < range.from())
5234 AddRange(CharacterRange(last, range.from() - 1));
5235 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005236 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005237 return;
5238 } else {
5239 last = range.to() + 1;
5240 }
5241 }
5242 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005243 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005244}
5245
5246
5247void DispatchTableConstructor::VisitText(TextNode* that) {
5248 TextElement elm = that->elements()->at(0);
5249 switch (elm.type) {
5250 case TextElement::ATOM: {
5251 uc16 c = elm.data.u_atom->data()[0];
5252 AddRange(CharacterRange(c, c));
5253 break;
5254 }
5255 case TextElement::CHAR_CLASS: {
5256 RegExpCharacterClass* tree = elm.data.u_char_class;
5257 ZoneList<CharacterRange>* ranges = tree->ranges();
5258 if (tree->is_negated()) {
5259 AddInverse(ranges);
5260 } else {
5261 for (int i = 0; i < ranges->length(); i++)
5262 AddRange(ranges->at(i));
5263 }
5264 break;
5265 }
5266 default: {
5267 UNIMPLEMENTED();
5268 }
5269 }
5270}
5271
5272
5273void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005274 RegExpNode* target = that->on_success();
5275 target->Accept(this);
5276}
5277
5278
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005279RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5280 bool ignore_case,
5281 bool is_multiline,
5282 Handle<String> pattern,
5283 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005284 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005285 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005286 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005287 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005288 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005289 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005290 0,
5291 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005292 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005293 RegExpNode* node = captured_body;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005294 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
5295 bool is_start_anchored = data->tree->IsAnchoredAtStart();
5296 int max_length = data->tree->max_match();
5297 if (!is_start_anchored) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005298 // Add a .*? at the beginning, outside the body capture, unless
5299 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005300 RegExpNode* loop_node =
5301 RegExpQuantifier::ToNode(0,
5302 RegExpTree::kInfinity,
5303 false,
5304 new RegExpCharacterClass('*'),
5305 &compiler,
5306 captured_body,
5307 data->contains_anchor);
5308
5309 if (data->contains_anchor) {
5310 // Unroll loop once, to take care of the case that might start
5311 // at the start of input.
5312 ChoiceNode* first_step_node = new ChoiceNode(2);
5313 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5314 first_step_node->AddAlternative(GuardedAlternative(
5315 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5316 node = first_step_node;
5317 } else {
5318 node = loop_node;
5319 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005320 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005321 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005322 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005323 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005324 if (analysis.has_failed()) {
5325 const char* error_message = analysis.error_message();
5326 return CompilationResult(error_message);
5327 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005328
5329 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005330
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005331 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005332#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005333 // Native regexp implementation.
5334
5335 NativeRegExpMacroAssembler::Mode mode =
5336 is_ascii ? NativeRegExpMacroAssembler::ASCII
5337 : NativeRegExpMacroAssembler::UC16;
5338
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005339#if V8_TARGET_ARCH_IA32
5340 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5341#elif V8_TARGET_ARCH_X64
5342 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5343#elif V8_TARGET_ARCH_ARM
5344 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
lrn@chromium.org7516f052011-03-30 08:52:27 +00005345#elif V8_TARGET_ARCH_MIPS
5346 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005347#endif
5348
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005349#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005350 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005351 EmbeddedVector<byte, 1024> codes;
5352 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005353#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005354
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005355 // Inserted here, instead of in Assembler, because it depends on information
5356 // in the AST that isn't replicated in the Node structure.
5357 static const int kMaxBacksearchLimit = 1024;
5358 if (is_end_anchored &&
5359 !is_start_anchored &&
5360 max_length < kMaxBacksearchLimit) {
5361 macro_assembler.SetCurrentPositionFromEnd(max_length);
5362 }
5363
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005364 return compiler.Assemble(&macro_assembler,
5365 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005366 data->capture_count,
5367 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005368}
5369
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005370
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005371}} // namespace v8::internal