blob: ec150c6f46ebd39ffadc961a8fa57cd3889b4fa5 [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);
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000130 ZoneScope zone_scope(isolate, DELETE_ON_EXIT);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000131 PostponeInterruptsScope postpone(isolate);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000132 RegExpCompileData parse_result;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000133 FlatStringReader reader(isolate, pattern);
fschneider@chromium.orge03fb642010-11-01 12:34:09 +0000134 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
135 &parse_result)) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000136 // Throw an exception if we fail to parse the pattern.
137 ThrowRegExpException(re,
138 pattern,
139 parse_result.error,
140 "malformed_regexp");
141 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000142 }
143
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000144 if (parse_result.simple && !flags.is_ignore_case()) {
145 // Parse-tree is a single atom that is equal to the pattern.
146 AtomCompile(re, pattern, flags, pattern);
147 } else if (parse_result.tree->IsAtom() &&
148 !flags.is_ignore_case() &&
149 parse_result.capture_count == 0) {
150 RegExpAtom* atom = parse_result.tree->AsAtom();
151 Vector<const uc16> atom_pattern = atom->data();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000152 Handle<String> atom_string =
153 isolate->factory()->NewStringFromTwoByte(atom_pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000154 AtomCompile(re, pattern, flags, atom_string);
155 } else {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000156 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000157 }
158 ASSERT(re->data()->IsFixedArray());
159 // Compilation succeeded so the data is set on the regexp
160 // and we can store it in the cache.
161 Handle<FixedArray> data(FixedArray::cast(re->data()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000162 compilation_cache->PutRegExp(pattern, flags, data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000163
164 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000165}
166
167
168Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
169 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000170 int index,
171 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000172 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000173 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000174 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000175 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000176 Handle<Object> result =
177 IrregexpExec(regexp, subject, index, last_match_info);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000178 ASSERT(!result.is_null() || Isolate::Current()->has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000179 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000180 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000181 default:
182 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000183 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000184 }
185}
186
187
ager@chromium.org8bb60582008-12-11 12:02:20 +0000188// RegExp Atom implementation: Simple string search using indexOf.
189
190
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000191void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
192 Handle<String> pattern,
193 JSRegExp::Flags flags,
194 Handle<String> match_pattern) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000195 re->GetIsolate()->factory()->SetRegExpAtomData(re,
196 JSRegExp::ATOM,
197 pattern,
198 flags,
199 match_pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000200}
201
202
203static void SetAtomLastCapture(FixedArray* array,
204 String* subject,
205 int from,
206 int to) {
207 NoHandleAllocation no_handles;
208 RegExpImpl::SetLastCaptureCount(array, 2);
209 RegExpImpl::SetLastSubject(array, subject);
210 RegExpImpl::SetLastInput(array, subject);
211 RegExpImpl::SetCapture(array, 0, from);
212 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000213}
214
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();
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000305 ZoneScope zone_scope(isolate, 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;
jkummerow@chromium.orge297f592011-06-08 10:05:15 +0000814
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000815 private:
816 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000817 int next_register_;
818 List<RegExpNode*>* work_list_;
819 int recursion_depth_;
820 RegExpMacroAssembler* macro_assembler_;
821 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000822 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000823 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000824};
825
826
827class RecursionCheck {
828 public:
829 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
830 compiler->IncrementRecursionDepth();
831 }
832 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
833 private:
834 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000835};
836
837
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000838static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
839 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000840}
841
842
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000843// Attempts to compile the regexp using an Irregexp code generator. Returns
844// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000845RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000846 : next_register_(2 * (capture_count + 1)),
847 work_list_(NULL),
848 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000849 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000850 ascii_(ascii),
851 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000852 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000853 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000854}
855
856
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000857RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000858 RegExpMacroAssembler* macro_assembler,
859 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000860 int capture_count,
861 Handle<String> pattern) {
karlklose@chromium.org83a47282011-05-11 11:54:09 +0000862 Heap* heap = pattern->GetHeap();
863
864 bool use_slow_safe_regexp_compiler = false;
865 if (heap->total_regexp_code_generated() >
866 RegExpImpl::kRegWxpCompiledLimit &&
867 heap->isolate()->memory_allocator()->SizeExecutable() >
868 RegExpImpl::kRegExpExecutableMemoryLimit) {
869 use_slow_safe_regexp_compiler = true;
870 }
871
872 macro_assembler->set_slow_safe(use_slow_safe_regexp_compiler);
873
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000874#ifdef DEBUG
875 if (FLAG_trace_regexp_assembler)
876 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
877 else
878#endif
879 macro_assembler_ = macro_assembler;
karlklose@chromium.org83a47282011-05-11 11:54:09 +0000880
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000881 List <RegExpNode*> work_list(0);
882 work_list_ = &work_list;
883 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000884 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000885 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000886 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000887 macro_assembler_->Bind(&fail);
888 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000889 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000890 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000891 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000892 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
893
karlklose@chromium.org83a47282011-05-11 11:54:09 +0000894 Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
895 heap->IncreaseTotalRegexpCodeGenerated(code->Size());
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000896 work_list_ = NULL;
897#ifdef DEBUG
danno@chromium.org4d3fe4e2011-03-10 10:14:28 +0000898 if (FLAG_print_code) {
899 Handle<Code>::cast(code)->Disassemble(*pattern->ToCString());
900 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000901 if (FLAG_trace_regexp_assembler) {
902 delete macro_assembler_;
903 }
904#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000905 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000906}
907
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000908
ager@chromium.org32912102009-01-16 10:38:43 +0000909bool Trace::DeferredAction::Mentions(int that) {
910 if (type() == ActionNode::CLEAR_CAPTURES) {
911 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
912 return range.Contains(that);
913 } else {
914 return reg() == that;
915 }
916}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000917
ager@chromium.org32912102009-01-16 10:38:43 +0000918
919bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000920 for (DeferredAction* action = actions_;
921 action != NULL;
922 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000923 if (action->Mentions(reg))
924 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000925 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000926 return false;
927}
928
929
ager@chromium.org32912102009-01-16 10:38:43 +0000930bool Trace::GetStoredPosition(int reg, int* cp_offset) {
931 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000932 for (DeferredAction* action = actions_;
933 action != NULL;
934 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000935 if (action->Mentions(reg)) {
936 if (action->type() == ActionNode::STORE_POSITION) {
937 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
938 return true;
939 } else {
940 return false;
941 }
942 }
943 }
944 return false;
945}
946
947
948int Trace::FindAffectedRegisters(OutSet* affected_registers) {
949 int max_register = RegExpCompiler::kNoRegister;
950 for (DeferredAction* action = actions_;
951 action != NULL;
952 action = action->next()) {
953 if (action->type() == ActionNode::CLEAR_CAPTURES) {
954 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
955 for (int i = range.from(); i <= range.to(); i++)
956 affected_registers->Set(i);
957 if (range.to() > max_register) max_register = range.to();
958 } else {
959 affected_registers->Set(action->reg());
960 if (action->reg() > max_register) max_register = action->reg();
961 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000962 }
963 return max_register;
964}
965
966
ager@chromium.org32912102009-01-16 10:38:43 +0000967void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
968 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000969 OutSet& registers_to_pop,
970 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000971 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000972 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
973 else if (registers_to_clear.Get(reg)) {
974 int clear_to = reg;
975 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
976 reg--;
977 }
978 assembler->ClearRegisters(reg, clear_to);
979 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000980 }
981}
982
983
ager@chromium.org32912102009-01-16 10:38:43 +0000984void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
985 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000986 OutSet& affected_registers,
987 OutSet* registers_to_pop,
988 OutSet* registers_to_clear) {
989 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
990 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
991
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000992 // Count pushes performed to force a stack limit check occasionally.
993 int pushes = 0;
994
ager@chromium.org8bb60582008-12-11 12:02:20 +0000995 for (int reg = 0; reg <= max_register; reg++) {
996 if (!affected_registers.Get(reg)) {
997 continue;
998 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000999
1000 // The chronologically first deferred action in the trace
1001 // is used to infer the action needed to restore a register
1002 // to its previous state (or not, if it's safe to ignore it).
1003 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
1004 DeferredActionUndoType undo_action = IGNORE;
1005
ager@chromium.org8bb60582008-12-11 12:02:20 +00001006 int value = 0;
1007 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +00001008 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001009 int store_position = -1;
1010 // This is a little tricky because we are scanning the actions in reverse
1011 // historical order (newest first).
1012 for (DeferredAction* action = actions_;
1013 action != NULL;
1014 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +00001015 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001016 switch (action->type()) {
1017 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00001018 Trace::DeferredSetRegister* psr =
1019 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001020 if (!absolute) {
1021 value += psr->value();
1022 absolute = true;
1023 }
1024 // SET_REGISTER is currently only used for newly introduced loop
1025 // counters. They can have a significant previous value if they
1026 // occour in a loop. TODO(lrn): Propagate this information, so
1027 // we can set undo_action to IGNORE if we know there is no value to
1028 // restore.
1029 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001030 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001031 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001032 break;
1033 }
1034 case ActionNode::INCREMENT_REGISTER:
1035 if (!absolute) {
1036 value++;
1037 }
1038 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001039 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001040 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001041 break;
1042 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00001043 Trace::DeferredCapture* pc =
1044 static_cast<Trace::DeferredCapture*>(action);
1045 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001046 store_position = pc->cp_offset();
1047 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001048
1049 // For captures we know that stores and clears alternate.
1050 // Other register, are never cleared, and if the occur
1051 // inside a loop, they might be assigned more than once.
1052 if (reg <= 1) {
1053 // Registers zero and one, aka "capture zero", is
1054 // always set correctly if we succeed. There is no
1055 // need to undo a setting on backtrack, because we
1056 // will set it again or fail.
1057 undo_action = IGNORE;
1058 } else {
1059 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1060 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001061 ASSERT(!absolute);
1062 ASSERT_EQ(value, 0);
1063 break;
1064 }
ager@chromium.org32912102009-01-16 10:38:43 +00001065 case ActionNode::CLEAR_CAPTURES: {
1066 // Since we're scanning in reverse order, if we've already
1067 // set the position we have to ignore historically earlier
1068 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001069 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +00001070 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001071 }
1072 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +00001073 ASSERT(!absolute);
1074 ASSERT_EQ(value, 0);
1075 break;
1076 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001077 default:
1078 UNREACHABLE();
1079 break;
1080 }
1081 }
1082 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001083 // Prepare for the undo-action (e.g., push if it's going to be popped).
1084 if (undo_action == RESTORE) {
1085 pushes++;
1086 RegExpMacroAssembler::StackCheckFlag stack_check =
1087 RegExpMacroAssembler::kNoStackLimitCheck;
1088 if (pushes == push_limit) {
1089 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1090 pushes = 0;
1091 }
1092
1093 assembler->PushRegister(reg, stack_check);
1094 registers_to_pop->Set(reg);
1095 } else if (undo_action == CLEAR) {
1096 registers_to_clear->Set(reg);
1097 }
1098 // Perform the chronologically last action (or accumulated increment)
1099 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001100 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001101 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001102 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001103 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001104 } else if (absolute) {
1105 assembler->SetRegister(reg, value);
1106 } else if (value != 0) {
1107 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001108 }
1109 }
1110}
1111
1112
ager@chromium.org8bb60582008-12-11 12:02:20 +00001113// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001114// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001115// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001116void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001117 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001118
iposva@chromium.org245aa852009-02-10 00:49:54 +00001119 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001120
1121 if (actions_ == NULL && backtrack() == NULL) {
1122 // 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 +00001123 // a normal situation. We may also have to forget some information gained
1124 // through a quick check that was already performed.
1125 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001126 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001127 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001128 successor->Emit(compiler, &new_state);
1129 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001130 }
1131
1132 // Generate deferred actions here along with code to undo them again.
1133 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001134
ager@chromium.org381abbb2009-02-25 13:23:22 +00001135 if (backtrack() != NULL) {
1136 // Here we have a concrete backtrack location. These are set up by choice
1137 // nodes and so they indicate that we have a deferred save of the current
1138 // position which we may need to emit here.
1139 assembler->PushCurrentPosition();
1140 }
1141
ager@chromium.org8bb60582008-12-11 12:02:20 +00001142 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001143 OutSet registers_to_pop;
1144 OutSet registers_to_clear;
1145 PerformDeferredActions(assembler,
1146 max_register,
1147 affected_registers,
1148 &registers_to_pop,
1149 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001150 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001151 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001152 }
1153
1154 // Create a new trivial state and generate the node with that.
1155 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001156 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001157 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001158 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001159
1160 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001161 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001162 RestoreAffectedRegisters(assembler,
1163 max_register,
1164 registers_to_pop,
1165 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001166 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001167 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001168 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001169 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001170 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001171 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001172}
1173
1174
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001175void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001176 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001177
1178 // Omit flushing the trace. We discard the entire stack frame anyway.
1179
ager@chromium.org8bb60582008-12-11 12:02:20 +00001180 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001181 // We are completely independent of the trace, since we ignore it,
1182 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001183 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001184 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001185
1186 // Throw away everything on the backtrack stack since the start
1187 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001188 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1189 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001190 if (clear_capture_count_ > 0) {
1191 // Clear any captures that might have been performed during the success
1192 // of the body of the negative look-ahead.
1193 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1194 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1195 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001196 // Now that we have unwound the stack we find at the top of the stack the
1197 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001198 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001199}
1200
1201
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001202void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001203 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001204 trace->Flush(compiler, this);
1205 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001206 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001207 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001208 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001209 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001210 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001211 switch (action_) {
1212 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001213 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001214 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001215 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001216 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001217 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001218 case NEGATIVE_SUBMATCH_SUCCESS:
1219 // This case is handled in a different virtual method.
1220 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001221 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001222 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001223}
1224
1225
1226void GuardedAlternative::AddGuard(Guard* guard) {
1227 if (guards_ == NULL)
1228 guards_ = new ZoneList<Guard*>(1);
1229 guards_->Add(guard);
1230}
1231
1232
ager@chromium.org8bb60582008-12-11 12:02:20 +00001233ActionNode* ActionNode::SetRegister(int reg,
1234 int val,
1235 RegExpNode* on_success) {
1236 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001237 result->data_.u_store_register.reg = reg;
1238 result->data_.u_store_register.value = val;
1239 return result;
1240}
1241
1242
1243ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1244 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1245 result->data_.u_increment_register.reg = reg;
1246 return result;
1247}
1248
1249
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001250ActionNode* ActionNode::StorePosition(int reg,
1251 bool is_capture,
1252 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001253 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1254 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001255 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001256 return result;
1257}
1258
1259
ager@chromium.org32912102009-01-16 10:38:43 +00001260ActionNode* ActionNode::ClearCaptures(Interval range,
1261 RegExpNode* on_success) {
1262 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1263 result->data_.u_clear_captures.range_from = range.from();
1264 result->data_.u_clear_captures.range_to = range.to();
1265 return result;
1266}
1267
1268
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001269ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1270 int position_reg,
1271 RegExpNode* on_success) {
1272 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1273 result->data_.u_submatch.stack_pointer_register = stack_reg;
1274 result->data_.u_submatch.current_position_register = position_reg;
1275 return result;
1276}
1277
1278
ager@chromium.org8bb60582008-12-11 12:02:20 +00001279ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1280 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001281 int clear_register_count,
1282 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001283 RegExpNode* on_success) {
1284 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001285 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001286 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001287 result->data_.u_submatch.clear_register_count = clear_register_count;
1288 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001289 return result;
1290}
1291
1292
ager@chromium.org32912102009-01-16 10:38:43 +00001293ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1294 int repetition_register,
1295 int repetition_limit,
1296 RegExpNode* on_success) {
1297 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1298 result->data_.u_empty_match_check.start_register = start_register;
1299 result->data_.u_empty_match_check.repetition_register = repetition_register;
1300 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1301 return result;
1302}
1303
1304
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001305#define DEFINE_ACCEPT(Type) \
1306 void Type##Node::Accept(NodeVisitor* visitor) { \
1307 visitor->Visit##Type(this); \
1308 }
1309FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1310#undef DEFINE_ACCEPT
1311
1312
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001313void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1314 visitor->VisitLoopChoice(this);
1315}
1316
1317
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001318// -------------------------------------------------------------------
1319// Emit code.
1320
1321
1322void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1323 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001324 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001325 switch (guard->op()) {
1326 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001327 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001328 macro_assembler->IfRegisterGE(guard->reg(),
1329 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001330 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001331 break;
1332 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001333 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001334 macro_assembler->IfRegisterLT(guard->reg(),
1335 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001336 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001337 break;
1338 }
1339}
1340
1341
ager@chromium.org381abbb2009-02-25 13:23:22 +00001342// Returns the number of characters in the equivalence class, omitting those
1343// that cannot occur in the source string because it is ASCII.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001344static int GetCaseIndependentLetters(Isolate* isolate,
1345 uc16 character,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001346 bool ascii_subject,
1347 unibrow::uchar* letters) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001348 int length =
1349 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00001350 // Unibrow returns 0 or 1 for characters where case independence is
ager@chromium.org381abbb2009-02-25 13:23:22 +00001351 // trivial.
1352 if (length == 0) {
1353 letters[0] = character;
1354 length = 1;
1355 }
1356 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1357 return length;
1358 }
1359 // The standard requires that non-ASCII characters cannot have ASCII
1360 // character codes in their equivalence class.
1361 return 0;
1362}
1363
1364
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001365static inline bool EmitSimpleCharacter(Isolate* isolate,
1366 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001367 uc16 c,
1368 Label* on_failure,
1369 int cp_offset,
1370 bool check,
1371 bool preloaded) {
1372 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1373 bool bound_checked = false;
1374 if (!preloaded) {
1375 assembler->LoadCurrentCharacter(
1376 cp_offset,
1377 on_failure,
1378 check);
1379 bound_checked = true;
1380 }
1381 assembler->CheckNotCharacter(c, on_failure);
1382 return bound_checked;
1383}
1384
1385
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001386// Only emits non-letters (things that don't have case). Only used for case
1387// independent matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001388static inline bool EmitAtomNonLetter(Isolate* isolate,
1389 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001390 uc16 c,
1391 Label* on_failure,
1392 int cp_offset,
1393 bool check,
1394 bool preloaded) {
1395 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1396 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001397 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001398 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001399 if (length < 1) {
1400 // This can't match. Must be an ASCII subject and a non-ASCII character.
1401 // We do not need to do anything since the ASCII pass already handled this.
1402 return false; // Bounds not checked.
1403 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001404 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001405 // We handle the length > 1 case in a later pass.
1406 if (length == 1) {
1407 if (ascii && c > String::kMaxAsciiCharCodeU) {
1408 // Can't match - see above.
1409 return false; // Bounds not checked.
1410 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001411 if (!preloaded) {
1412 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1413 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001414 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001415 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001416 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001417 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001418}
1419
1420
1421static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001422 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001423 uc16 c1,
1424 uc16 c2,
1425 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001426 uc16 char_mask;
1427 if (ascii) {
1428 char_mask = String::kMaxAsciiCharCode;
1429 } else {
1430 char_mask = String::kMaxUC16CharCode;
1431 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001432 uc16 exor = c1 ^ c2;
1433 // Check whether exor has only one bit set.
1434 if (((exor - 1) & exor) == 0) {
1435 // If c1 and c2 differ only by one bit.
1436 // Ecma262UnCanonicalize always gives the highest number last.
1437 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001438 uc16 mask = char_mask ^ exor;
1439 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001440 return true;
1441 }
1442 ASSERT(c2 > c1);
1443 uc16 diff = c2 - c1;
1444 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1445 // If the characters differ by 2^n but don't differ by one bit then
1446 // subtract the difference from the found character, then do the or
1447 // trick. We avoid the theoretical case where negative numbers are
1448 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001449 uc16 mask = char_mask ^ diff;
1450 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1451 diff,
1452 mask,
1453 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001454 return true;
1455 }
1456 return false;
1457}
1458
1459
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001460typedef bool EmitCharacterFunction(Isolate* isolate,
1461 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001462 uc16 c,
1463 Label* on_failure,
1464 int cp_offset,
1465 bool check,
1466 bool preloaded);
1467
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001468// Only emits letters (things that have case). Only used for case independent
1469// matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001470static inline bool EmitAtomLetter(Isolate* isolate,
1471 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001472 uc16 c,
1473 Label* on_failure,
1474 int cp_offset,
1475 bool check,
1476 bool preloaded) {
1477 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1478 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001479 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001480 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001481 if (length <= 1) return false;
1482 // We may not need to check against the end of the input string
1483 // if this character lies before a character that matched.
1484 if (!preloaded) {
1485 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001486 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001487 Label ok;
1488 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1489 switch (length) {
1490 case 2: {
1491 if (ShortCutEmitCharacterPair(macro_assembler,
1492 ascii,
1493 chars[0],
1494 chars[1],
1495 on_failure)) {
1496 } else {
1497 macro_assembler->CheckCharacter(chars[0], &ok);
1498 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1499 macro_assembler->Bind(&ok);
1500 }
1501 break;
1502 }
1503 case 4:
1504 macro_assembler->CheckCharacter(chars[3], &ok);
1505 // Fall through!
1506 case 3:
1507 macro_assembler->CheckCharacter(chars[0], &ok);
1508 macro_assembler->CheckCharacter(chars[1], &ok);
1509 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1510 macro_assembler->Bind(&ok);
1511 break;
1512 default:
1513 UNREACHABLE();
1514 break;
1515 }
1516 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001517}
1518
1519
1520static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1521 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001522 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001523 Label* on_failure,
1524 int cp_offset,
1525 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001526 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001527 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001528 int max_char;
1529 if (ascii) {
1530 max_char = String::kMaxAsciiCharCode;
1531 } else {
1532 max_char = String::kMaxUC16CharCode;
1533 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001534
1535 Label success;
1536
1537 Label* char_is_in_class =
1538 cc->is_negated() ? on_failure : &success;
1539
1540 int range_count = ranges->length();
1541
ager@chromium.org8bb60582008-12-11 12:02:20 +00001542 int last_valid_range = range_count - 1;
1543 while (last_valid_range >= 0) {
1544 CharacterRange& range = ranges->at(last_valid_range);
1545 if (range.from() <= max_char) {
1546 break;
1547 }
1548 last_valid_range--;
1549 }
1550
1551 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001552 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001553 // TODO(plesner): We can remove this when the node level does our
1554 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001555 macro_assembler->GoTo(on_failure);
1556 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001557 if (check_offset) {
1558 macro_assembler->CheckPosition(cp_offset, on_failure);
1559 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001560 return;
1561 }
1562
ager@chromium.org8bb60582008-12-11 12:02:20 +00001563 if (last_valid_range == 0 &&
1564 !cc->is_negated() &&
1565 ranges->at(0).IsEverything(max_char)) {
1566 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001567 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001568 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001569 }
1570 return;
1571 }
1572
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001573 if (!preloaded) {
1574 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001575 }
1576
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001577 if (cc->is_standard() &&
1578 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1579 on_failure)) {
1580 return;
1581 }
1582
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001583 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001584 CharacterRange& range = ranges->at(i);
1585 Label next_range;
1586 uc16 from = range.from();
1587 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001588 if (from > max_char) {
1589 continue;
1590 }
1591 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001592 if (to == from) {
1593 macro_assembler->CheckCharacter(to, char_is_in_class);
1594 } else {
1595 if (from != 0) {
1596 macro_assembler->CheckCharacterLT(from, &next_range);
1597 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001598 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001599 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1600 } else {
1601 macro_assembler->GoTo(char_is_in_class);
1602 }
1603 }
1604 macro_assembler->Bind(&next_range);
1605 }
1606
ager@chromium.org8bb60582008-12-11 12:02:20 +00001607 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001608 uc16 from = range.from();
1609 uc16 to = range.to();
1610
ager@chromium.org8bb60582008-12-11 12:02:20 +00001611 if (to > max_char) to = max_char;
1612 ASSERT(to >= from);
1613
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001614 if (to == from) {
1615 if (cc->is_negated()) {
1616 macro_assembler->CheckCharacter(to, on_failure);
1617 } else {
1618 macro_assembler->CheckNotCharacter(to, on_failure);
1619 }
1620 } else {
1621 if (from != 0) {
1622 if (cc->is_negated()) {
1623 macro_assembler->CheckCharacterLT(from, &success);
1624 } else {
1625 macro_assembler->CheckCharacterLT(from, on_failure);
1626 }
1627 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001628 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001629 if (cc->is_negated()) {
1630 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1631 } else {
1632 macro_assembler->CheckCharacterGT(to, on_failure);
1633 }
1634 } else {
1635 if (cc->is_negated()) {
1636 macro_assembler->GoTo(on_failure);
1637 }
1638 }
1639 }
1640 macro_assembler->Bind(&success);
1641}
1642
1643
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001644RegExpNode::~RegExpNode() {
1645}
1646
1647
ager@chromium.org8bb60582008-12-11 12:02:20 +00001648RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001649 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001650 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001651 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001652 return CONTINUE;
1653 }
1654
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001655 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001656 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001657 if (label_.is_bound()) {
1658 // We are being asked to generate a generic version, but that's already
1659 // been done so just go to it.
1660 macro_assembler->GoTo(&label_);
1661 return DONE;
1662 }
1663 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1664 // To avoid too deep recursion we push the node to the work queue and just
1665 // generate a goto here.
1666 compiler->AddWork(this);
1667 macro_assembler->GoTo(&label_);
1668 return DONE;
1669 }
1670 // Generate generic version of the node and bind the label for later use.
1671 macro_assembler->Bind(&label_);
1672 return CONTINUE;
1673 }
1674
1675 // We are being asked to make a non-generic version. Keep track of how many
1676 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001677 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001678 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001679 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001680 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1681 return CONTINUE;
1682 }
1683
ager@chromium.org32912102009-01-16 10:38:43 +00001684 // If we get here code has been generated for this node too many times or
1685 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001686 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001687 trace->Flush(compiler, this);
1688 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001689}
1690
1691
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001692int ActionNode::EatsAtLeast(int still_to_find,
1693 int recursion_depth,
1694 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001695 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1696 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001697 return on_success()->EatsAtLeast(still_to_find,
1698 recursion_depth + 1,
1699 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001700}
1701
1702
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001703int AssertionNode::EatsAtLeast(int still_to_find,
1704 int recursion_depth,
1705 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001706 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001707 // If we know we are not at the start and we are asked "how many characters
1708 // will you match if you succeed?" then we can answer anything since false
1709 // implies false. So lets just return the max answer (still_to_find) since
1710 // that won't prevent us from preloading a lot of characters for the other
1711 // branches in the node graph.
1712 if (type() == AT_START && not_at_start) return still_to_find;
1713 return on_success()->EatsAtLeast(still_to_find,
1714 recursion_depth + 1,
1715 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001716}
1717
1718
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001719int BackReferenceNode::EatsAtLeast(int still_to_find,
1720 int recursion_depth,
1721 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001722 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001723 return on_success()->EatsAtLeast(still_to_find,
1724 recursion_depth + 1,
1725 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001726}
1727
1728
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001729int TextNode::EatsAtLeast(int still_to_find,
1730 int recursion_depth,
1731 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001732 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001733 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001734 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001735 // We are not at start after this node so we set the last argument to 'true'.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001736 return answer + on_success()->EatsAtLeast(still_to_find - answer,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001737 recursion_depth + 1,
1738 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001739}
1740
1741
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001742int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001743 int recursion_depth,
1744 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001745 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1746 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1747 // afterwards.
1748 RegExpNode* node = alternatives_->at(1).node();
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001749 return node->EatsAtLeast(still_to_find, recursion_depth + 1, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001750}
1751
1752
1753void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1754 QuickCheckDetails* details,
1755 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001756 int filled_in,
1757 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001758 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1759 // afterwards.
1760 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001761 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001762}
1763
1764
1765int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1766 int recursion_depth,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001767 RegExpNode* ignore_this_node,
1768 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001769 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1770 int min = 100;
1771 int choice_count = alternatives_->length();
1772 for (int i = 0; i < choice_count; i++) {
1773 RegExpNode* node = alternatives_->at(i).node();
1774 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001775 int node_eats_at_least = node->EatsAtLeast(still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001776 recursion_depth + 1,
1777 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001778 if (node_eats_at_least < min) min = node_eats_at_least;
1779 }
1780 return min;
1781}
1782
1783
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001784int LoopChoiceNode::EatsAtLeast(int still_to_find,
1785 int recursion_depth,
1786 bool not_at_start) {
1787 return EatsAtLeastHelper(still_to_find,
1788 recursion_depth,
1789 loop_node_,
1790 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001791}
1792
1793
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001794int ChoiceNode::EatsAtLeast(int still_to_find,
1795 int recursion_depth,
1796 bool not_at_start) {
1797 return EatsAtLeastHelper(still_to_find,
1798 recursion_depth,
1799 NULL,
1800 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001801}
1802
1803
1804// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1805static inline uint32_t SmearBitsRight(uint32_t v) {
1806 v |= v >> 1;
1807 v |= v >> 2;
1808 v |= v >> 4;
1809 v |= v >> 8;
1810 v |= v >> 16;
1811 return v;
1812}
1813
1814
1815bool QuickCheckDetails::Rationalize(bool asc) {
1816 bool found_useful_op = false;
1817 uint32_t char_mask;
1818 if (asc) {
1819 char_mask = String::kMaxAsciiCharCode;
1820 } else {
1821 char_mask = String::kMaxUC16CharCode;
1822 }
1823 mask_ = 0;
1824 value_ = 0;
1825 int char_shift = 0;
1826 for (int i = 0; i < characters_; i++) {
1827 Position* pos = &positions_[i];
1828 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1829 found_useful_op = true;
1830 }
1831 mask_ |= (pos->mask & char_mask) << char_shift;
1832 value_ |= (pos->value & char_mask) << char_shift;
1833 char_shift += asc ? 8 : 16;
1834 }
1835 return found_useful_op;
1836}
1837
1838
1839bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001840 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001841 bool preload_has_checked_bounds,
1842 Label* on_possible_success,
1843 QuickCheckDetails* details,
1844 bool fall_through_on_failure) {
1845 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001846 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1847 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001848 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001849 ASSERT(details->characters() == 1 ||
1850 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001851 uint32_t mask = details->mask();
1852 uint32_t value = details->value();
1853
1854 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1855
ager@chromium.org32912102009-01-16 10:38:43 +00001856 if (trace->characters_preloaded() != details->characters()) {
1857 assembler->LoadCurrentCharacter(trace->cp_offset(),
1858 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001859 !preload_has_checked_bounds,
1860 details->characters());
1861 }
1862
1863
1864 bool need_mask = true;
1865
1866 if (details->characters() == 1) {
1867 // If number of characters preloaded is 1 then we used a byte or 16 bit
1868 // load so the value is already masked down.
1869 uint32_t char_mask;
1870 if (compiler->ascii()) {
1871 char_mask = String::kMaxAsciiCharCode;
1872 } else {
1873 char_mask = String::kMaxUC16CharCode;
1874 }
1875 if ((mask & char_mask) == char_mask) need_mask = false;
1876 mask &= char_mask;
1877 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001878 // For 2-character preloads in ASCII mode or 1-character preloads in
1879 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001880 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001881 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1882 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001883 if ((mask & 0xffff) == 0xffff) need_mask = false;
1884 } else {
1885 if (mask == 0xffffffff) need_mask = false;
1886 }
1887 }
1888
1889 if (fall_through_on_failure) {
1890 if (need_mask) {
1891 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1892 } else {
1893 assembler->CheckCharacter(value, on_possible_success);
1894 }
1895 } else {
1896 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001897 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001898 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001899 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001900 }
1901 }
1902 return true;
1903}
1904
1905
1906// Here is the meat of GetQuickCheckDetails (see also the comment on the
1907// super-class in the .h file).
1908//
1909// We iterate along the text object, building up for each character a
1910// mask and value that can be used to test for a quick failure to match.
1911// The masks and values for the positions will be combined into a single
1912// machine word for the current character width in order to be used in
1913// generating a quick check.
1914void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1915 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001916 int characters_filled_in,
1917 bool not_at_start) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001918 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001919 ASSERT(characters_filled_in < details->characters());
1920 int characters = details->characters();
1921 int char_mask;
1922 int char_shift;
1923 if (compiler->ascii()) {
1924 char_mask = String::kMaxAsciiCharCode;
1925 char_shift = 8;
1926 } else {
1927 char_mask = String::kMaxUC16CharCode;
1928 char_shift = 16;
1929 }
1930 for (int k = 0; k < elms_->length(); k++) {
1931 TextElement elm = elms_->at(k);
1932 if (elm.type == TextElement::ATOM) {
1933 Vector<const uc16> quarks = elm.data.u_atom->data();
1934 for (int i = 0; i < characters && i < quarks.length(); i++) {
1935 QuickCheckDetails::Position* pos =
1936 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001937 uc16 c = quarks[i];
1938 if (c > char_mask) {
1939 // If we expect a non-ASCII character from an ASCII string,
1940 // there is no way we can match. Not even case independent
1941 // matching can turn an ASCII character into non-ASCII or
1942 // vice versa.
1943 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001944 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001945 return;
1946 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001947 if (compiler->ignore_case()) {
1948 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001949 int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
1950 chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001951 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1952 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001953 // This letter has no case equivalents, so it's nice and simple
1954 // and the mask-compare will determine definitely whether we have
1955 // a match at this character position.
1956 pos->mask = char_mask;
1957 pos->value = c;
1958 pos->determines_perfectly = true;
1959 } else {
1960 uint32_t common_bits = char_mask;
1961 uint32_t bits = chars[0];
1962 for (int j = 1; j < length; j++) {
1963 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1964 common_bits ^= differing_bits;
1965 bits &= common_bits;
1966 }
1967 // If length is 2 and common bits has only one zero in it then
1968 // our mask and compare instruction will determine definitely
1969 // whether we have a match at this character position. Otherwise
1970 // it can only be an approximate check.
1971 uint32_t one_zero = (common_bits | ~char_mask);
1972 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1973 pos->determines_perfectly = true;
1974 }
1975 pos->mask = common_bits;
1976 pos->value = bits;
1977 }
1978 } else {
1979 // Don't ignore case. Nice simple case where the mask-compare will
1980 // determine definitely whether we have a match at this character
1981 // position.
1982 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001983 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001984 pos->determines_perfectly = true;
1985 }
1986 characters_filled_in++;
1987 ASSERT(characters_filled_in <= details->characters());
1988 if (characters_filled_in == details->characters()) {
1989 return;
1990 }
1991 }
1992 } else {
1993 QuickCheckDetails::Position* pos =
1994 details->positions(characters_filled_in);
1995 RegExpCharacterClass* tree = elm.data.u_char_class;
1996 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001997 if (tree->is_negated()) {
1998 // A quick check uses multi-character mask and compare. There is no
1999 // useful way to incorporate a negative char class into this scheme
2000 // so we just conservatively create a mask and value that will always
2001 // succeed.
2002 pos->mask = 0;
2003 pos->value = 0;
2004 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002005 int first_range = 0;
2006 while (ranges->at(first_range).from() > char_mask) {
2007 first_range++;
2008 if (first_range == ranges->length()) {
2009 details->set_cannot_match();
2010 pos->determines_perfectly = false;
2011 return;
2012 }
2013 }
2014 CharacterRange range = ranges->at(first_range);
2015 uc16 from = range.from();
2016 uc16 to = range.to();
2017 if (to > char_mask) {
2018 to = char_mask;
2019 }
2020 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002021 // A mask and compare is only perfect if the differing bits form a
2022 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002023 if ((differing_bits & (differing_bits + 1)) == 0 &&
2024 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002025 pos->determines_perfectly = true;
2026 }
2027 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002028 uint32_t bits = (from & common_bits);
2029 for (int i = first_range + 1; i < ranges->length(); i++) {
2030 CharacterRange range = ranges->at(i);
2031 uc16 from = range.from();
2032 uc16 to = range.to();
2033 if (from > char_mask) continue;
2034 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002035 // Here we are combining more ranges into the mask and compare
2036 // value. With each new range the mask becomes more sparse and
2037 // so the chances of a false positive rise. A character class
2038 // with multiple ranges is assumed never to be equivalent to a
2039 // mask and compare operation.
2040 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002041 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002042 new_common_bits = ~SmearBitsRight(new_common_bits);
2043 common_bits &= new_common_bits;
2044 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002045 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002046 common_bits ^= differing_bits;
2047 bits &= common_bits;
2048 }
2049 pos->mask = common_bits;
2050 pos->value = bits;
2051 }
2052 characters_filled_in++;
2053 ASSERT(characters_filled_in <= details->characters());
2054 if (characters_filled_in == details->characters()) {
2055 return;
2056 }
2057 }
2058 }
2059 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00002060 on_success()-> GetQuickCheckDetails(details,
2061 compiler,
2062 characters_filled_in,
2063 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002064}
2065
2066
2067void QuickCheckDetails::Clear() {
2068 for (int i = 0; i < characters_; i++) {
2069 positions_[i].mask = 0;
2070 positions_[i].value = 0;
2071 positions_[i].determines_perfectly = false;
2072 }
2073 characters_ = 0;
2074}
2075
2076
2077void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002078 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002079 if (by >= characters_) {
2080 Clear();
2081 return;
2082 }
2083 for (int i = 0; i < characters_ - by; i++) {
2084 positions_[i] = positions_[by + i];
2085 }
2086 for (int i = characters_ - by; i < characters_; i++) {
2087 positions_[i].mask = 0;
2088 positions_[i].value = 0;
2089 positions_[i].determines_perfectly = false;
2090 }
2091 characters_ -= by;
2092 // We could change mask_ and value_ here but we would never advance unless
2093 // they had already been used in a check and they won't be used again because
2094 // it would gain us nothing. So there's no point.
2095}
2096
2097
2098void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2099 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002100 if (other->cannot_match_) {
2101 return;
2102 }
2103 if (cannot_match_) {
2104 *this = *other;
2105 return;
2106 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002107 for (int i = from_index; i < characters_; i++) {
2108 QuickCheckDetails::Position* pos = positions(i);
2109 QuickCheckDetails::Position* other_pos = other->positions(i);
2110 if (pos->mask != other_pos->mask ||
2111 pos->value != other_pos->value ||
2112 !other_pos->determines_perfectly) {
2113 // Our mask-compare operation will be approximate unless we have the
2114 // exact same operation on both sides of the alternation.
2115 pos->determines_perfectly = false;
2116 }
2117 pos->mask &= other_pos->mask;
2118 pos->value &= pos->mask;
2119 other_pos->value &= pos->mask;
2120 uc16 differing_bits = (pos->value ^ other_pos->value);
2121 pos->mask &= ~differing_bits;
2122 pos->value &= pos->mask;
2123 }
2124}
2125
2126
ager@chromium.org32912102009-01-16 10:38:43 +00002127class VisitMarker {
2128 public:
2129 explicit VisitMarker(NodeInfo* info) : info_(info) {
2130 ASSERT(!info->visited);
2131 info->visited = true;
2132 }
2133 ~VisitMarker() {
2134 info_->visited = false;
2135 }
2136 private:
2137 NodeInfo* info_;
2138};
2139
2140
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002141void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2142 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002143 int characters_filled_in,
2144 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002145 if (body_can_be_zero_length_ || info()->visited) return;
2146 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002147 return ChoiceNode::GetQuickCheckDetails(details,
2148 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002149 characters_filled_in,
2150 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002151}
2152
2153
2154void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2155 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002156 int characters_filled_in,
2157 bool not_at_start) {
2158 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002159 int choice_count = alternatives_->length();
2160 ASSERT(choice_count > 0);
2161 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2162 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002163 characters_filled_in,
2164 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002165 for (int i = 1; i < choice_count; i++) {
2166 QuickCheckDetails new_details(details->characters());
2167 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002168 node->GetQuickCheckDetails(&new_details, compiler,
2169 characters_filled_in,
2170 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002171 // Here we merge the quick match details of the two branches.
2172 details->Merge(&new_details, characters_filled_in);
2173 }
2174}
2175
2176
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002177// Check for [0-9A-Z_a-z].
2178static void EmitWordCheck(RegExpMacroAssembler* assembler,
2179 Label* word,
2180 Label* non_word,
2181 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002182 if (assembler->CheckSpecialCharacterClass(
2183 fall_through_on_word ? 'w' : 'W',
2184 fall_through_on_word ? non_word : word)) {
2185 // Optimized implementation available.
2186 return;
2187 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002188 assembler->CheckCharacterGT('z', non_word);
2189 assembler->CheckCharacterLT('0', non_word);
2190 assembler->CheckCharacterGT('a' - 1, word);
2191 assembler->CheckCharacterLT('9' + 1, word);
2192 assembler->CheckCharacterLT('A', non_word);
2193 assembler->CheckCharacterLT('Z' + 1, word);
2194 if (fall_through_on_word) {
2195 assembler->CheckNotCharacter('_', non_word);
2196 } else {
2197 assembler->CheckCharacter('_', word);
2198 }
2199}
2200
2201
2202// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2203// that matches newline or the start of input).
2204static void EmitHat(RegExpCompiler* compiler,
2205 RegExpNode* on_success,
2206 Trace* trace) {
2207 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2208 // We will be loading the previous character into the current character
2209 // register.
2210 Trace new_trace(*trace);
2211 new_trace.InvalidateCurrentCharacter();
2212
2213 Label ok;
2214 if (new_trace.cp_offset() == 0) {
2215 // The start of input counts as a newline in this context, so skip to
2216 // ok if we are at the start.
2217 assembler->CheckAtStart(&ok);
2218 }
2219 // We already checked that we are not at the start of input so it must be
2220 // OK to load the previous character.
2221 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2222 new_trace.backtrack(),
2223 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002224 if (!assembler->CheckSpecialCharacterClass('n',
2225 new_trace.backtrack())) {
2226 // Newline means \n, \r, 0x2028 or 0x2029.
2227 if (!compiler->ascii()) {
2228 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2229 }
2230 assembler->CheckCharacter('\n', &ok);
2231 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002232 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002233 assembler->Bind(&ok);
2234 on_success->Emit(compiler, &new_trace);
2235}
2236
2237
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002238// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2239// when we know whether the next character must be a word character or not.
2240static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2241 RegExpCompiler* compiler,
2242 RegExpNode* on_success,
2243 Trace* trace) {
2244 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2245 Label done;
2246
2247 Trace new_trace(*trace);
2248
2249 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2250 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2251 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2252
2253 // Check whether previous character was a word character.
2254 switch (trace->at_start()) {
2255 case Trace::TRUE:
2256 if (expect_word_character) {
2257 assembler->GoTo(on_non_word);
2258 }
2259 break;
2260 case Trace::UNKNOWN:
2261 ASSERT_EQ(0, trace->cp_offset());
2262 assembler->CheckAtStart(on_non_word);
2263 // Fall through.
2264 case Trace::FALSE:
2265 int prev_char_offset = trace->cp_offset() - 1;
2266 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2267 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2268 // We may or may not have loaded the previous character.
2269 new_trace.InvalidateCurrentCharacter();
2270 }
2271
2272 assembler->Bind(&done);
2273
2274 on_success->Emit(compiler, &new_trace);
2275}
2276
2277
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002278// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2279static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2280 RegExpCompiler* compiler,
2281 RegExpNode* on_success,
2282 Trace* trace) {
2283 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2284 Label before_non_word;
2285 Label before_word;
2286 if (trace->characters_preloaded() != 1) {
2287 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2288 }
2289 // Fall through on non-word.
2290 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2291
2292 // We will be loading the previous character into the current character
2293 // register.
2294 Trace new_trace(*trace);
2295 new_trace.InvalidateCurrentCharacter();
2296
2297 Label ok;
2298 Label* boundary;
2299 Label* not_boundary;
2300 if (type == AssertionNode::AT_BOUNDARY) {
2301 boundary = &ok;
2302 not_boundary = new_trace.backtrack();
2303 } else {
2304 not_boundary = &ok;
2305 boundary = new_trace.backtrack();
2306 }
2307
2308 // Next character is not a word character.
2309 assembler->Bind(&before_non_word);
2310 if (new_trace.cp_offset() == 0) {
2311 // The start of input counts as a non-word character, so the question is
2312 // decided if we are at the start.
2313 assembler->CheckAtStart(not_boundary);
2314 }
2315 // We already checked that we are not at the start of input so it must be
2316 // OK to load the previous character.
2317 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2318 &ok, // Unused dummy label in this call.
2319 false);
2320 // Fall through on non-word.
2321 EmitWordCheck(assembler, boundary, not_boundary, false);
2322 assembler->GoTo(not_boundary);
2323
2324 // Next character is a word character.
2325 assembler->Bind(&before_word);
2326 if (new_trace.cp_offset() == 0) {
2327 // The start of input counts as a non-word character, so the question is
2328 // decided if we are at the start.
2329 assembler->CheckAtStart(boundary);
2330 }
2331 // We already checked that we are not at the start of input so it must be
2332 // OK to load the previous character.
2333 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2334 &ok, // Unused dummy label in this call.
2335 false);
2336 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2337 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2338
2339 assembler->Bind(&ok);
2340
2341 on_success->Emit(compiler, &new_trace);
2342}
2343
2344
iposva@chromium.org245aa852009-02-10 00:49:54 +00002345void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2346 RegExpCompiler* compiler,
2347 int filled_in,
2348 bool not_at_start) {
2349 if (type_ == AT_START && not_at_start) {
2350 details->set_cannot_match();
2351 return;
2352 }
2353 return on_success()->GetQuickCheckDetails(details,
2354 compiler,
2355 filled_in,
2356 not_at_start);
2357}
2358
2359
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002360void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2361 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2362 switch (type_) {
2363 case AT_END: {
2364 Label ok;
2365 assembler->CheckPosition(trace->cp_offset(), &ok);
2366 assembler->GoTo(trace->backtrack());
2367 assembler->Bind(&ok);
2368 break;
2369 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002370 case AT_START: {
2371 if (trace->at_start() == Trace::FALSE) {
2372 assembler->GoTo(trace->backtrack());
2373 return;
2374 }
2375 if (trace->at_start() == Trace::UNKNOWN) {
2376 assembler->CheckNotAtStart(trace->backtrack());
2377 Trace at_start_trace = *trace;
2378 at_start_trace.set_at_start(true);
2379 on_success()->Emit(compiler, &at_start_trace);
2380 return;
2381 }
2382 }
2383 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002384 case AFTER_NEWLINE:
2385 EmitHat(compiler, on_success(), trace);
2386 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002387 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002388 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002389 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2390 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002391 }
2392 case AFTER_WORD_CHARACTER:
2393 case AFTER_NONWORD_CHARACTER: {
2394 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2395 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002396 }
2397 on_success()->Emit(compiler, trace);
2398}
2399
2400
ager@chromium.org381abbb2009-02-25 13:23:22 +00002401static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2402 if (quick_check == NULL) return false;
2403 if (offset >= quick_check->characters()) return false;
2404 return quick_check->positions(offset)->determines_perfectly;
2405}
2406
2407
2408static void UpdateBoundsCheck(int index, int* checked_up_to) {
2409 if (index > *checked_up_to) {
2410 *checked_up_to = index;
2411 }
2412}
2413
2414
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002415// We call this repeatedly to generate code for each pass over the text node.
2416// The passes are in increasing order of difficulty because we hope one
2417// of the first passes will fail in which case we are saved the work of the
2418// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2419// we will check the '%' in the first pass, the case independent 'a' in the
2420// second pass and the character class in the last pass.
2421//
2422// The passes are done from right to left, so for example to test for /bar/
2423// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2424// and then a 'b' with offset 0. This means we can avoid the end-of-input
2425// bounds check most of the time. In the example we only need to check for
2426// end-of-input when loading the putative 'r'.
2427//
2428// A slight complication involves the fact that the first character may already
2429// be fetched into a register by the previous node. In this case we want to
2430// do the test for that character first. We do this in separate passes. The
2431// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2432// pass has been performed then subsequent passes will have true in
2433// first_element_checked to indicate that that character does not need to be
2434// checked again.
2435//
ager@chromium.org32912102009-01-16 10:38:43 +00002436// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002437// contain an AlternativeGeneration object. In this AlternativeGeneration
2438// object we can see details of any quick check that was already passed in
2439// order to get to the code we are now generating. The quick check can involve
2440// loading characters, which means we do not need to recheck the bounds
2441// up to the limit the quick check already checked. In addition the quick
2442// check can have involved a mask and compare operation which may simplify
2443// or obviate the need for further checks at some character positions.
2444void TextNode::TextEmitPass(RegExpCompiler* compiler,
2445 TextEmitPassType pass,
2446 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002447 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002448 bool first_element_checked,
2449 int* checked_up_to) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002450 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002451 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2452 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002453 Label* backtrack = trace->backtrack();
2454 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002455 int element_count = elms_->length();
2456 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2457 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002458 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002459 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002460 Vector<const uc16> quarks = elm.data.u_atom->data();
2461 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2462 if (first_element_checked && i == 0 && j == 0) continue;
2463 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2464 EmitCharacterFunction* emit_function = NULL;
2465 switch (pass) {
2466 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002467 ASSERT(ascii);
2468 if (quarks[j] > String::kMaxAsciiCharCode) {
2469 assembler->GoTo(backtrack);
2470 return;
2471 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002472 break;
2473 case NON_LETTER_CHARACTER_MATCH:
2474 emit_function = &EmitAtomNonLetter;
2475 break;
2476 case SIMPLE_CHARACTER_MATCH:
2477 emit_function = &EmitSimpleCharacter;
2478 break;
2479 case CASE_CHARACTER_MATCH:
2480 emit_function = &EmitAtomLetter;
2481 break;
2482 default:
2483 break;
2484 }
2485 if (emit_function != NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002486 bool bound_checked = emit_function(isolate,
2487 compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002488 quarks[j],
2489 backtrack,
2490 cp_offset + j,
2491 *checked_up_to < cp_offset + j,
2492 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002493 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002494 }
2495 }
2496 } else {
2497 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002498 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002499 if (first_element_checked && i == 0) continue;
2500 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002501 RegExpCharacterClass* cc = elm.data.u_char_class;
2502 EmitCharClass(assembler,
2503 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002504 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002505 backtrack,
2506 cp_offset,
2507 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002508 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002509 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002510 }
2511 }
2512 }
2513}
2514
2515
2516int TextNode::Length() {
2517 TextElement elm = elms_->last();
2518 ASSERT(elm.cp_offset >= 0);
2519 if (elm.type == TextElement::ATOM) {
2520 return elm.cp_offset + elm.data.u_atom->data().length();
2521 } else {
2522 return elm.cp_offset + 1;
2523 }
2524}
2525
2526
ager@chromium.org381abbb2009-02-25 13:23:22 +00002527bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2528 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2529 if (ignore_case) {
2530 return pass == SIMPLE_CHARACTER_MATCH;
2531 } else {
2532 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2533 }
2534}
2535
2536
ager@chromium.org8bb60582008-12-11 12:02:20 +00002537// This generates the code to match a text node. A text node can contain
2538// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002539// way) and character classes. For efficiency we do not do this in a single
2540// pass from left to right. Instead we pass over the text node several times,
2541// emitting code for some character positions every time. See the comment on
2542// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002543void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002544 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002545 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002546 ASSERT(limit_result == CONTINUE);
2547
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002548 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2549 compiler->SetRegExpTooBig();
2550 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002551 }
2552
2553 if (compiler->ascii()) {
2554 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002555 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002556 }
2557
2558 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002559 int bound_checked_to = trace->cp_offset() - 1;
2560 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002561
2562 // If a character is preloaded into the current character register then
2563 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002564 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002565 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2566 if (!SkipPass(pass, compiler->ignore_case())) {
2567 TextEmitPass(compiler,
2568 static_cast<TextEmitPassType>(pass),
2569 true,
2570 trace,
2571 false,
2572 &bound_checked_to);
2573 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002574 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002575 first_elt_done = true;
2576 }
2577
ager@chromium.org381abbb2009-02-25 13:23:22 +00002578 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2579 if (!SkipPass(pass, compiler->ignore_case())) {
2580 TextEmitPass(compiler,
2581 static_cast<TextEmitPassType>(pass),
2582 false,
2583 trace,
2584 first_elt_done,
2585 &bound_checked_to);
2586 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002587 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002588
ager@chromium.org32912102009-01-16 10:38:43 +00002589 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002590 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002591 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002592 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002593 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002594}
2595
2596
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002597void Trace::InvalidateCurrentCharacter() {
2598 characters_preloaded_ = 0;
2599}
2600
2601
2602void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002603 ASSERT(by > 0);
2604 // We don't have an instruction for shifting the current character register
2605 // down or for using a shifted value for anything so lets just forget that
2606 // we preloaded any characters into it.
2607 characters_preloaded_ = 0;
2608 // Adjust the offsets of the quick check performed information. This
2609 // information is used to find out what we already determined about the
2610 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002611 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002612 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002613 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2614 compiler->SetRegExpTooBig();
2615 cp_offset_ = 0;
2616 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002617 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002618}
2619
2620
ager@chromium.org38e4c712009-11-11 09:11:58 +00002621void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002622 int element_count = elms_->length();
2623 for (int i = 0; i < element_count; i++) {
2624 TextElement elm = elms_->at(i);
2625 if (elm.type == TextElement::CHAR_CLASS) {
2626 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002627 // None of the standard character classses is different in the case
2628 // independent case and it slows us down if we don't know that.
2629 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002630 ZoneList<CharacterRange>* ranges = cc->ranges();
2631 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002632 for (int j = 0; j < range_count; j++) {
2633 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002634 }
2635 }
2636 }
2637}
2638
2639
ager@chromium.org8bb60582008-12-11 12:02:20 +00002640int TextNode::GreedyLoopTextLength() {
2641 TextElement elm = elms_->at(elms_->length() - 1);
2642 if (elm.type == TextElement::CHAR_CLASS) {
2643 return elm.cp_offset + 1;
2644 } else {
2645 return elm.cp_offset + elm.data.u_atom->data().length();
2646 }
2647}
2648
2649
2650// Finds the fixed match length of a sequence of nodes that goes from
2651// this alternative and back to this choice node. If there are variable
2652// length nodes or other complications in the way then return a sentinel
2653// value indicating that a greedy loop cannot be constructed.
2654int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2655 int length = 0;
2656 RegExpNode* node = alternative->node();
2657 // Later we will generate code for all these text nodes using recursion
2658 // so we have to limit the max number.
2659 int recursion_depth = 0;
2660 while (node != this) {
2661 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2662 return kNodeIsTooComplexForGreedyLoops;
2663 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002664 int node_length = node->GreedyLoopTextLength();
2665 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2666 return kNodeIsTooComplexForGreedyLoops;
2667 }
2668 length += node_length;
2669 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2670 node = seq_node->on_success();
2671 }
2672 return length;
2673}
2674
2675
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002676void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2677 ASSERT_EQ(loop_node_, NULL);
2678 AddAlternative(alt);
2679 loop_node_ = alt.node();
2680}
2681
2682
2683void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2684 ASSERT_EQ(continue_node_, NULL);
2685 AddAlternative(alt);
2686 continue_node_ = alt.node();
2687}
2688
2689
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002690void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002691 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002692 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002693 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2694 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2695 // Update the counter-based backtracking info on the stack. This is an
2696 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002697 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002698 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002699 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002700 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002701 }
ager@chromium.org32912102009-01-16 10:38:43 +00002702 ASSERT(trace->stop_node() == NULL);
2703 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002704 trace->Flush(compiler, this);
2705 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002706 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002707 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002708}
2709
2710
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002711int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
2712 bool not_at_start) {
2713 int preload_characters = EatsAtLeast(4, 0, not_at_start);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002714 if (compiler->macro_assembler()->CanReadUnaligned()) {
2715 bool ascii = compiler->ascii();
2716 if (ascii) {
2717 if (preload_characters > 4) preload_characters = 4;
2718 // We can't preload 3 characters because there is no machine instruction
2719 // to do that. We can't just load 4 because we could be reading
2720 // beyond the end of the string, which could cause a memory fault.
2721 if (preload_characters == 3) preload_characters = 2;
2722 } else {
2723 if (preload_characters > 2) preload_characters = 2;
2724 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002725 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002726 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002727 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002728 return preload_characters;
2729}
2730
2731
2732// This class is used when generating the alternatives in a choice node. It
2733// records the way the alternative is being code generated.
2734class AlternativeGeneration: public Malloced {
2735 public:
2736 AlternativeGeneration()
2737 : possible_success(),
2738 expects_preload(false),
2739 after(),
2740 quick_check_details() { }
2741 Label possible_success;
2742 bool expects_preload;
2743 Label after;
2744 QuickCheckDetails quick_check_details;
2745};
2746
2747
2748// Creates a list of AlternativeGenerations. If the list has a reasonable
2749// size then it is on the stack, otherwise the excess is on the heap.
2750class AlternativeGenerationList {
2751 public:
2752 explicit AlternativeGenerationList(int count)
2753 : alt_gens_(count) {
2754 for (int i = 0; i < count && i < kAFew; i++) {
2755 alt_gens_.Add(a_few_alt_gens_ + i);
2756 }
2757 for (int i = kAFew; i < count; i++) {
2758 alt_gens_.Add(new AlternativeGeneration());
2759 }
2760 }
2761 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002762 for (int i = kAFew; i < alt_gens_.length(); i++) {
2763 delete alt_gens_[i];
2764 alt_gens_[i] = NULL;
2765 }
2766 }
2767
2768 AlternativeGeneration* at(int i) {
2769 return alt_gens_[i];
2770 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00002771
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002772 private:
2773 static const int kAFew = 10;
2774 ZoneList<AlternativeGeneration*> alt_gens_;
2775 AlternativeGeneration a_few_alt_gens_[kAFew];
2776};
2777
2778
2779/* Code generation for choice nodes.
2780 *
2781 * We generate quick checks that do a mask and compare to eliminate a
2782 * choice. If the quick check succeeds then it jumps to the continuation to
2783 * do slow checks and check subsequent nodes. If it fails (the common case)
2784 * it falls through to the next choice.
2785 *
2786 * Here is the desired flow graph. Nodes directly below each other imply
2787 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2788 * 3 doesn't have a quick check so we have to call the slow check.
2789 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2790 * regexp continuation is generated directly after the Sn node, up to the
2791 * next GoTo if we decide to reuse some already generated code. Some
2792 * nodes expect preload_characters to be preloaded into the current
2793 * character register. R nodes do this preloading. Vertices are marked
2794 * F for failures and S for success (possible success in the case of quick
2795 * nodes). L, V, < and > are used as arrow heads.
2796 *
2797 * ----------> R
2798 * |
2799 * V
2800 * Q1 -----> S1
2801 * | S /
2802 * F| /
2803 * | F/
2804 * | /
2805 * | R
2806 * | /
2807 * V L
2808 * Q2 -----> S2
2809 * | S /
2810 * F| /
2811 * | F/
2812 * | /
2813 * | R
2814 * | /
2815 * V L
2816 * S3
2817 * |
2818 * F|
2819 * |
2820 * R
2821 * |
2822 * backtrack V
2823 * <----------Q4
2824 * \ F |
2825 * \ |S
2826 * \ F V
2827 * \-----S4
2828 *
2829 * For greedy loops we reverse our expectation and expect to match rather
2830 * than fail. Therefore we want the loop code to look like this (U is the
2831 * unwind code that steps back in the greedy loop). The following alternatives
2832 * look the same as above.
2833 * _____
2834 * / \
2835 * V |
2836 * ----------> S1 |
2837 * /| |
2838 * / |S |
2839 * F/ \_____/
2840 * /
2841 * |<-----------
2842 * | \
2843 * V \
2844 * Q2 ---> S2 \
2845 * | S / |
2846 * F| / |
2847 * | F/ |
2848 * | / |
2849 * | R |
2850 * | / |
2851 * F VL |
2852 * <------U |
2853 * back |S |
2854 * \______________/
2855 */
2856
2857
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002858void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002859 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2860 int choice_count = alternatives_->length();
2861#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002862 for (int i = 0; i < choice_count - 1; i++) {
2863 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002864 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002865 int guard_count = (guards == NULL) ? 0 : guards->length();
2866 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002867 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002868 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002869 }
2870#endif
2871
ager@chromium.org32912102009-01-16 10:38:43 +00002872 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002873 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002874 ASSERT(limit_result == CONTINUE);
2875
ager@chromium.org381abbb2009-02-25 13:23:22 +00002876 int new_flush_budget = trace->flush_budget() / choice_count;
2877 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2878 trace->Flush(compiler, this);
2879 return;
2880 }
2881
ager@chromium.org8bb60582008-12-11 12:02:20 +00002882 RecursionCheck rc(compiler);
2883
ager@chromium.org32912102009-01-16 10:38:43 +00002884 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002885
2886 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2887 bool greedy_loop = false;
2888 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002889 Trace counter_backtrack_trace;
2890 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002891 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2892
ager@chromium.org8bb60582008-12-11 12:02:20 +00002893 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2894 // Here we have special handling for greedy loops containing only text nodes
2895 // and other simple nodes. These are handled by pushing the current
2896 // position on the stack and then incrementing the current position each
2897 // time around the switch. On backtrack we decrement the current position
2898 // and check it against the pushed value. This avoids pushing backtrack
2899 // information for each iteration of the loop, which could take up a lot of
2900 // space.
2901 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002902 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002903 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002904 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002905 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002906 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002907 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002908 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002909 Label loop_label;
2910 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002911 greedy_match_trace.set_stop_node(this);
2912 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002913 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002914 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002915 }
2916
2917 Label second_choice; // For use in greedy matches.
2918 macro_assembler->Bind(&second_choice);
2919
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002920 int first_normal_choice = greedy_loop ? 1 : 0;
2921
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002922 int preload_characters =
2923 CalculatePreloadCharacters(compiler,
2924 current_trace->at_start() == Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002925 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002926 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002927 bool preload_has_checked_bounds = preload_is_current;
2928
2929 AlternativeGenerationList alt_gens(choice_count);
2930
ager@chromium.org8bb60582008-12-11 12:02:20 +00002931 // For now we just call all choices one after the other. The idea ultimately
2932 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002933 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002934 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002935 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002936 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002937 ZoneList<Guard*>* guards = alternative.guards();
2938 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002939 Trace new_trace(*current_trace);
2940 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002941 preload_characters :
2942 0);
2943 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002944 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002945 }
ager@chromium.org32912102009-01-16 10:38:43 +00002946 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002947 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002948 alt_gen->expects_preload = preload_is_current;
2949 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002950 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002951 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002952 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002953 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002954 preload_has_checked_bounds,
2955 &alt_gen->possible_success,
2956 &alt_gen->quick_check_details,
2957 i < choice_count - 1)) {
2958 // Quick check was generated for this choice.
2959 preload_is_current = true;
2960 preload_has_checked_bounds = true;
2961 // On the last choice in the ChoiceNode we generated the quick
2962 // check to fall through on possible success. So now we need to
2963 // generate the full check inline.
2964 if (i == choice_count - 1) {
2965 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002966 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2967 new_trace.set_characters_preloaded(preload_characters);
2968 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002969 generate_full_check_inline = true;
2970 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002971 } else if (alt_gen->quick_check_details.cannot_match()) {
2972 if (i == choice_count - 1 && !greedy_loop) {
2973 macro_assembler->GoTo(trace->backtrack());
2974 }
2975 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002976 } else {
2977 // No quick check was generated. Put the full code here.
2978 // If this is not the first choice then there could be slow checks from
2979 // previous cases that go here when they fail. There's no reason to
2980 // insist that they preload characters since the slow check we are about
2981 // to generate probably can't use it.
2982 if (i != first_normal_choice) {
2983 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002984 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002985 }
2986 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002987 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002988 }
2989 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002990 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002991 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002992 if (new_trace.actions() != NULL) {
2993 new_trace.set_flush_budget(new_flush_budget);
2994 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002995 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002996 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002997 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002998 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002999 preload_is_current = false;
3000 }
3001 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003002 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003003 if (greedy_loop) {
3004 macro_assembler->Bind(&greedy_loop_label);
3005 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00003006 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00003007 // Otherwise try the second priority at an earlier position.
3008 macro_assembler->AdvanceCurrentPosition(-text_length);
3009 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003010 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00003011
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003012 // At this point we need to generate slow checks for the alternatives where
3013 // the quick check was inlined. We can recognize these because the associated
3014 // label was bound.
3015 for (int i = first_normal_choice; i < choice_count - 1; i++) {
3016 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00003017 Trace new_trace(*current_trace);
3018 // If there are actions to be flushed we have to limit how many times
3019 // they are flushed. Take the budget of the parent trace and distribute
3020 // it fairly amongst the children.
3021 if (new_trace.actions() != NULL) {
3022 new_trace.set_flush_budget(new_flush_budget);
3023 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003024 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00003025 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003026 alternatives_->at(i),
3027 alt_gen,
3028 preload_characters,
3029 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003030 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003031}
3032
3033
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003034void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00003035 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003036 GuardedAlternative alternative,
3037 AlternativeGeneration* alt_gen,
3038 int preload_characters,
3039 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003040 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003041
3042 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3043 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00003044 Trace out_of_line_trace(*trace);
3045 out_of_line_trace.set_characters_preloaded(preload_characters);
3046 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003047 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003048 ZoneList<Guard*>* guards = alternative.guards();
3049 int guard_count = (guards == NULL) ? 0 : guards->length();
3050 if (next_expects_preload) {
3051 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00003052 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003053 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003054 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003055 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003056 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003057 macro_assembler->Bind(&reload_current_char);
3058 // Reload the current character, since the next quick check expects that.
3059 // We don't need to check bounds here because we only get into this
3060 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00003061 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003062 NULL,
3063 false,
3064 preload_characters);
3065 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003066 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00003067 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003068 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003069 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003070 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003071 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003072 }
3073}
3074
3075
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003076void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003077 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003078 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003079 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003080 ASSERT(limit_result == CONTINUE);
3081
3082 RecursionCheck rc(compiler);
3083
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003084 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003085 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00003086 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003087 new_capture(data_.u_position_register.reg,
3088 data_.u_position_register.is_capture,
3089 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003090 Trace new_trace = *trace;
3091 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003092 on_success()->Emit(compiler, &new_trace);
3093 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003094 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003095 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003096 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003097 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00003098 Trace new_trace = *trace;
3099 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003100 on_success()->Emit(compiler, &new_trace);
3101 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003102 }
3103 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003104 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003105 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00003106 Trace new_trace = *trace;
3107 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003108 on_success()->Emit(compiler, &new_trace);
3109 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003110 }
3111 case CLEAR_CAPTURES: {
3112 Trace::DeferredClearCaptures
3113 new_capture(Interval(data_.u_clear_captures.range_from,
3114 data_.u_clear_captures.range_to));
3115 Trace new_trace = *trace;
3116 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003117 on_success()->Emit(compiler, &new_trace);
3118 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003119 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003120 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003121 if (!trace->is_trivial()) {
3122 trace->Flush(compiler, this);
3123 } else {
3124 assembler->WriteCurrentPositionToRegister(
3125 data_.u_submatch.current_position_register, 0);
3126 assembler->WriteStackPointerToRegister(
3127 data_.u_submatch.stack_pointer_register);
3128 on_success()->Emit(compiler, trace);
3129 }
3130 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003131 case EMPTY_MATCH_CHECK: {
3132 int start_pos_reg = data_.u_empty_match_check.start_register;
3133 int stored_pos = 0;
3134 int rep_reg = data_.u_empty_match_check.repetition_register;
3135 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3136 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3137 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3138 // If we know we haven't advanced and there is no minimum we
3139 // can just backtrack immediately.
3140 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003141 } else if (know_dist && stored_pos < trace->cp_offset()) {
3142 // If we know we've advanced we can generate the continuation
3143 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003144 on_success()->Emit(compiler, trace);
3145 } else if (!trace->is_trivial()) {
3146 trace->Flush(compiler, this);
3147 } else {
3148 Label skip_empty_check;
3149 // If we have a minimum number of repetitions we check the current
3150 // number first and skip the empty check if it's not enough.
3151 if (has_minimum) {
3152 int limit = data_.u_empty_match_check.repetition_limit;
3153 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3154 }
3155 // If the match is empty we bail out, otherwise we fall through
3156 // to the on-success continuation.
3157 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3158 trace->backtrack());
3159 assembler->Bind(&skip_empty_check);
3160 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003161 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003162 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003163 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003164 case POSITIVE_SUBMATCH_SUCCESS: {
3165 if (!trace->is_trivial()) {
3166 trace->Flush(compiler, this);
3167 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003168 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003169 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003170 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003171 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003172 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003173 int clear_register_count = data_.u_submatch.clear_register_count;
3174 if (clear_register_count == 0) {
3175 on_success()->Emit(compiler, trace);
3176 return;
3177 }
3178 int clear_registers_from = data_.u_submatch.clear_register_from;
3179 Label clear_registers_backtrack;
3180 Trace new_trace = *trace;
3181 new_trace.set_backtrack(&clear_registers_backtrack);
3182 on_success()->Emit(compiler, &new_trace);
3183
3184 assembler->Bind(&clear_registers_backtrack);
3185 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3186 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3187
3188 ASSERT(trace->backtrack() == NULL);
3189 assembler->Backtrack();
3190 return;
3191 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003192 default:
3193 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003194 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003195}
3196
3197
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003198void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003199 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003200 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003201 trace->Flush(compiler, this);
3202 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003203 }
3204
ager@chromium.org32912102009-01-16 10:38:43 +00003205 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003206 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003207 ASSERT(limit_result == CONTINUE);
3208
3209 RecursionCheck rc(compiler);
3210
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003211 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003212 if (compiler->ignore_case()) {
3213 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3214 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003215 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003216 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003217 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003218 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003219}
3220
3221
3222// -------------------------------------------------------------------
3223// Dot/dotty output
3224
3225
3226#ifdef DEBUG
3227
3228
3229class DotPrinter: public NodeVisitor {
3230 public:
3231 explicit DotPrinter(bool ignore_case)
3232 : ignore_case_(ignore_case),
3233 stream_(&alloc_) { }
3234 void PrintNode(const char* label, RegExpNode* node);
3235 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003236 void PrintAttributes(RegExpNode* from);
3237 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003238 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003239#define DECLARE_VISIT(Type) \
3240 virtual void Visit##Type(Type##Node* that);
3241FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3242#undef DECLARE_VISIT
3243 private:
3244 bool ignore_case_;
3245 HeapStringAllocator alloc_;
3246 StringStream stream_;
3247};
3248
3249
3250void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3251 stream()->Add("digraph G {\n graph [label=\"");
3252 for (int i = 0; label[i]; i++) {
3253 switch (label[i]) {
3254 case '\\':
3255 stream()->Add("\\\\");
3256 break;
3257 case '"':
3258 stream()->Add("\"");
3259 break;
3260 default:
3261 stream()->Put(label[i]);
3262 break;
3263 }
3264 }
3265 stream()->Add("\"];\n");
3266 Visit(node);
3267 stream()->Add("}\n");
3268 printf("%s", *(stream()->ToCString()));
3269}
3270
3271
3272void DotPrinter::Visit(RegExpNode* node) {
3273 if (node->info()->visited) return;
3274 node->info()->visited = true;
3275 node->Accept(this);
3276}
3277
3278
3279void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003280 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3281 Visit(on_failure);
3282}
3283
3284
3285class TableEntryBodyPrinter {
3286 public:
3287 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3288 : stream_(stream), choice_(choice) { }
3289 void Call(uc16 from, DispatchTable::Entry entry) {
3290 OutSet* out_set = entry.out_set();
3291 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3292 if (out_set->Get(i)) {
3293 stream()->Add(" n%p:s%io%i -> n%p;\n",
3294 choice(),
3295 from,
3296 i,
3297 choice()->alternatives()->at(i).node());
3298 }
3299 }
3300 }
3301 private:
3302 StringStream* stream() { return stream_; }
3303 ChoiceNode* choice() { return choice_; }
3304 StringStream* stream_;
3305 ChoiceNode* choice_;
3306};
3307
3308
3309class TableEntryHeaderPrinter {
3310 public:
3311 explicit TableEntryHeaderPrinter(StringStream* stream)
3312 : first_(true), stream_(stream) { }
3313 void Call(uc16 from, DispatchTable::Entry entry) {
3314 if (first_) {
3315 first_ = false;
3316 } else {
3317 stream()->Add("|");
3318 }
3319 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3320 OutSet* out_set = entry.out_set();
3321 int priority = 0;
3322 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3323 if (out_set->Get(i)) {
3324 if (priority > 0) stream()->Add("|");
3325 stream()->Add("<s%io%i> %i", from, i, priority);
3326 priority++;
3327 }
3328 }
3329 stream()->Add("}}");
3330 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00003331
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003332 private:
3333 bool first_;
3334 StringStream* stream() { return stream_; }
3335 StringStream* stream_;
3336};
3337
3338
3339class AttributePrinter {
3340 public:
3341 explicit AttributePrinter(DotPrinter* out)
3342 : out_(out), first_(true) { }
3343 void PrintSeparator() {
3344 if (first_) {
3345 first_ = false;
3346 } else {
3347 out_->stream()->Add("|");
3348 }
3349 }
3350 void PrintBit(const char* name, bool value) {
3351 if (!value) return;
3352 PrintSeparator();
3353 out_->stream()->Add("{%s}", name);
3354 }
3355 void PrintPositive(const char* name, int value) {
3356 if (value < 0) return;
3357 PrintSeparator();
3358 out_->stream()->Add("{%s|%x}", name, value);
3359 }
3360 private:
3361 DotPrinter* out_;
3362 bool first_;
3363};
3364
3365
3366void DotPrinter::PrintAttributes(RegExpNode* that) {
3367 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3368 "margin=0.1, fontsize=10, label=\"{",
3369 that);
3370 AttributePrinter printer(this);
3371 NodeInfo* info = that->info();
3372 printer.PrintBit("NI", info->follows_newline_interest);
3373 printer.PrintBit("WI", info->follows_word_interest);
3374 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003375 Label* label = that->label();
3376 if (label->is_bound())
3377 printer.PrintPositive("@", label->pos());
3378 stream()->Add("}\"];\n");
3379 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3380 "arrowhead=none];\n", that, that);
3381}
3382
3383
3384static const bool kPrintDispatchTable = false;
3385void DotPrinter::VisitChoice(ChoiceNode* that) {
3386 if (kPrintDispatchTable) {
3387 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3388 TableEntryHeaderPrinter header_printer(stream());
3389 that->GetTable(ignore_case_)->ForEach(&header_printer);
3390 stream()->Add("\"]\n", that);
3391 PrintAttributes(that);
3392 TableEntryBodyPrinter body_printer(stream(), that);
3393 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003394 } else {
3395 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3396 for (int i = 0; i < that->alternatives()->length(); i++) {
3397 GuardedAlternative alt = that->alternatives()->at(i);
3398 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3399 }
3400 }
3401 for (int i = 0; i < that->alternatives()->length(); i++) {
3402 GuardedAlternative alt = that->alternatives()->at(i);
3403 alt.node()->Accept(this);
3404 }
3405}
3406
3407
3408void DotPrinter::VisitText(TextNode* that) {
3409 stream()->Add(" n%p [label=\"", that);
3410 for (int i = 0; i < that->elements()->length(); i++) {
3411 if (i > 0) stream()->Add(" ");
3412 TextElement elm = that->elements()->at(i);
3413 switch (elm.type) {
3414 case TextElement::ATOM: {
3415 stream()->Add("'%w'", elm.data.u_atom->data());
3416 break;
3417 }
3418 case TextElement::CHAR_CLASS: {
3419 RegExpCharacterClass* node = elm.data.u_char_class;
3420 stream()->Add("[");
3421 if (node->is_negated())
3422 stream()->Add("^");
3423 for (int j = 0; j < node->ranges()->length(); j++) {
3424 CharacterRange range = node->ranges()->at(j);
3425 stream()->Add("%k-%k", range.from(), range.to());
3426 }
3427 stream()->Add("]");
3428 break;
3429 }
3430 default:
3431 UNREACHABLE();
3432 }
3433 }
3434 stream()->Add("\", shape=box, peripheries=2];\n");
3435 PrintAttributes(that);
3436 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3437 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003438}
3439
3440
3441void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3442 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3443 that,
3444 that->start_register(),
3445 that->end_register());
3446 PrintAttributes(that);
3447 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3448 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003449}
3450
3451
3452void DotPrinter::VisitEnd(EndNode* that) {
3453 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3454 PrintAttributes(that);
3455}
3456
3457
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003458void DotPrinter::VisitAssertion(AssertionNode* that) {
3459 stream()->Add(" n%p [", that);
3460 switch (that->type()) {
3461 case AssertionNode::AT_END:
3462 stream()->Add("label=\"$\", shape=septagon");
3463 break;
3464 case AssertionNode::AT_START:
3465 stream()->Add("label=\"^\", shape=septagon");
3466 break;
3467 case AssertionNode::AT_BOUNDARY:
3468 stream()->Add("label=\"\\b\", shape=septagon");
3469 break;
3470 case AssertionNode::AT_NON_BOUNDARY:
3471 stream()->Add("label=\"\\B\", shape=septagon");
3472 break;
3473 case AssertionNode::AFTER_NEWLINE:
3474 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3475 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003476 case AssertionNode::AFTER_WORD_CHARACTER:
3477 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3478 break;
3479 case AssertionNode::AFTER_NONWORD_CHARACTER:
3480 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3481 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003482 }
3483 stream()->Add("];\n");
3484 PrintAttributes(that);
3485 RegExpNode* successor = that->on_success();
3486 stream()->Add(" n%p -> n%p;\n", that, successor);
3487 Visit(successor);
3488}
3489
3490
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003491void DotPrinter::VisitAction(ActionNode* that) {
3492 stream()->Add(" n%p [", that);
3493 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003494 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003495 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3496 that->data_.u_store_register.reg,
3497 that->data_.u_store_register.value);
3498 break;
3499 case ActionNode::INCREMENT_REGISTER:
3500 stream()->Add("label=\"$%i++\", shape=octagon",
3501 that->data_.u_increment_register.reg);
3502 break;
3503 case ActionNode::STORE_POSITION:
3504 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3505 that->data_.u_position_register.reg);
3506 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003507 case ActionNode::BEGIN_SUBMATCH:
3508 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3509 that->data_.u_submatch.current_position_register);
3510 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003511 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003512 stream()->Add("label=\"escape\", shape=septagon");
3513 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003514 case ActionNode::EMPTY_MATCH_CHECK:
3515 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3516 that->data_.u_empty_match_check.start_register,
3517 that->data_.u_empty_match_check.repetition_register,
3518 that->data_.u_empty_match_check.repetition_limit);
3519 break;
3520 case ActionNode::CLEAR_CAPTURES: {
3521 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3522 that->data_.u_clear_captures.range_from,
3523 that->data_.u_clear_captures.range_to);
3524 break;
3525 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003526 }
3527 stream()->Add("];\n");
3528 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003529 RegExpNode* successor = that->on_success();
3530 stream()->Add(" n%p -> n%p;\n", that, successor);
3531 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003532}
3533
3534
3535class DispatchTableDumper {
3536 public:
3537 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3538 void Call(uc16 key, DispatchTable::Entry entry);
3539 StringStream* stream() { return stream_; }
3540 private:
3541 StringStream* stream_;
3542};
3543
3544
3545void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3546 stream()->Add("[%k-%k]: {", key, entry.to());
3547 OutSet* set = entry.out_set();
3548 bool first = true;
3549 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3550 if (set->Get(i)) {
3551 if (first) {
3552 first = false;
3553 } else {
3554 stream()->Add(", ");
3555 }
3556 stream()->Add("%i", i);
3557 }
3558 }
3559 stream()->Add("}\n");
3560}
3561
3562
3563void DispatchTable::Dump() {
3564 HeapStringAllocator alloc;
3565 StringStream stream(&alloc);
3566 DispatchTableDumper dumper(&stream);
3567 tree()->ForEach(&dumper);
3568 OS::PrintError("%s", *stream.ToCString());
3569}
3570
3571
3572void RegExpEngine::DotPrint(const char* label,
3573 RegExpNode* node,
3574 bool ignore_case) {
3575 DotPrinter printer(ignore_case);
3576 printer.PrintNode(label, node);
3577}
3578
3579
3580#endif // DEBUG
3581
3582
3583// -------------------------------------------------------------------
3584// Tree to graph conversion
3585
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003586static const int kSpaceRangeCount = 20;
3587static const int kSpaceRangeAsciiCount = 4;
3588static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3589 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3590 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3591
3592static const int kWordRangeCount = 8;
3593static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3594 '_', 'a', 'z' };
3595
3596static const int kDigitRangeCount = 2;
3597static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3598
3599static const int kLineTerminatorRangeCount = 6;
3600static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3601 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003602
3603RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003604 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003605 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3606 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003607 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003608}
3609
3610
3611RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003612 RegExpNode* on_success) {
3613 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003614}
3615
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003616static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3617 const uc16* special_class,
3618 int length) {
3619 ASSERT(ranges->length() != 0);
3620 ASSERT(length != 0);
3621 ASSERT(special_class[0] != 0);
3622 if (ranges->length() != (length >> 1) + 1) {
3623 return false;
3624 }
3625 CharacterRange range = ranges->at(0);
3626 if (range.from() != 0) {
3627 return false;
3628 }
3629 for (int i = 0; i < length; i += 2) {
3630 if (special_class[i] != (range.to() + 1)) {
3631 return false;
3632 }
3633 range = ranges->at((i >> 1) + 1);
3634 if (special_class[i+1] != range.from() - 1) {
3635 return false;
3636 }
3637 }
3638 if (range.to() != 0xffff) {
3639 return false;
3640 }
3641 return true;
3642}
3643
3644
3645static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3646 const uc16* special_class,
3647 int length) {
3648 if (ranges->length() * 2 != length) {
3649 return false;
3650 }
3651 for (int i = 0; i < length; i += 2) {
3652 CharacterRange range = ranges->at(i >> 1);
3653 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3654 return false;
3655 }
3656 }
3657 return true;
3658}
3659
3660
3661bool RegExpCharacterClass::is_standard() {
3662 // TODO(lrn): Remove need for this function, by not throwing away information
3663 // along the way.
3664 if (is_negated_) {
3665 return false;
3666 }
3667 if (set_.is_standard()) {
3668 return true;
3669 }
3670 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3671 set_.set_standard_set_type('s');
3672 return true;
3673 }
3674 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3675 set_.set_standard_set_type('S');
3676 return true;
3677 }
3678 if (CompareInverseRanges(set_.ranges(),
3679 kLineTerminatorRanges,
3680 kLineTerminatorRangeCount)) {
3681 set_.set_standard_set_type('.');
3682 return true;
3683 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003684 if (CompareRanges(set_.ranges(),
3685 kLineTerminatorRanges,
3686 kLineTerminatorRangeCount)) {
3687 set_.set_standard_set_type('n');
3688 return true;
3689 }
3690 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3691 set_.set_standard_set_type('w');
3692 return true;
3693 }
3694 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3695 set_.set_standard_set_type('W');
3696 return true;
3697 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003698 return false;
3699}
3700
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003701
3702RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003703 RegExpNode* on_success) {
3704 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003705}
3706
3707
3708RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003709 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003710 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3711 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003712 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003713 for (int i = 0; i < length; i++) {
3714 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003715 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003716 result->AddAlternative(alternative);
3717 }
3718 return result;
3719}
3720
3721
3722RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003723 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003724 return ToNode(min(),
3725 max(),
3726 is_greedy(),
3727 body(),
3728 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003729 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003730}
3731
3732
3733RegExpNode* RegExpQuantifier::ToNode(int min,
3734 int max,
3735 bool is_greedy,
3736 RegExpTree* body,
3737 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003738 RegExpNode* on_success,
3739 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003740 // x{f, t} becomes this:
3741 //
3742 // (r++)<-.
3743 // | `
3744 // | (x)
3745 // v ^
3746 // (r=0)-->(?)---/ [if r < t]
3747 // |
3748 // [if r >= f] \----> ...
3749 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003750
3751 // 15.10.2.5 RepeatMatcher algorithm.
3752 // The parser has already eliminated the case where max is 0. In the case
3753 // where max_match is zero the parser has removed the quantifier if min was
3754 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3755
3756 // If we know that we cannot match zero length then things are a little
3757 // simpler since we don't need to make the special zero length match check
3758 // from step 2.1. If the min and max are small we can unroll a little in
3759 // this case.
3760 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3761 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3762 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003763 bool body_can_be_empty = (body->min_match() == 0);
3764 int body_start_reg = RegExpCompiler::kNoRegister;
3765 Interval capture_registers = body->CaptureRegisters();
3766 bool needs_capture_clearing = !capture_registers.is_empty();
3767 if (body_can_be_empty) {
3768 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003769 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003770 // Only unroll if there are no captures and the body can't be
3771 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003772 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3773 int new_max = (max == kInfinity) ? max : max - min;
3774 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003775 RegExpNode* answer = ToNode(
3776 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003777 // Unroll the forced matches from 0 to min. This can cause chains of
3778 // TextNodes (which the parser does not generate). These should be
3779 // combined if it turns out they hinder good code generation.
3780 for (int i = 0; i < min; i++) {
3781 answer = body->ToNode(compiler, answer);
3782 }
3783 return answer;
3784 }
3785 if (max <= kMaxUnrolledMaxMatches) {
3786 ASSERT(min == 0);
3787 // Unroll the optional matches up to max.
3788 RegExpNode* answer = on_success;
3789 for (int i = 0; i < max; i++) {
3790 ChoiceNode* alternation = new ChoiceNode(2);
3791 if (is_greedy) {
3792 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3793 answer)));
3794 alternation->AddAlternative(GuardedAlternative(on_success));
3795 } else {
3796 alternation->AddAlternative(GuardedAlternative(on_success));
3797 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3798 answer)));
3799 }
3800 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003801 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003802 }
3803 return answer;
3804 }
3805 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003806 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003807 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003808 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003809 int reg_ctr = needs_counter
3810 ? compiler->AllocateRegister()
3811 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003812 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003813 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003814 RegExpNode* loop_return = needs_counter
3815 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3816 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003817 if (body_can_be_empty) {
3818 // If the body can be empty we need to check if it was and then
3819 // backtrack.
3820 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3821 reg_ctr,
3822 min,
3823 loop_return);
3824 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003825 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003826 if (body_can_be_empty) {
3827 // If the body can be empty we need to store the start position
3828 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003829 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003830 }
3831 if (needs_capture_clearing) {
3832 // Before entering the body of this loop we need to clear captures.
3833 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3834 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003835 GuardedAlternative body_alt(body_node);
3836 if (has_max) {
3837 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3838 body_alt.AddGuard(body_guard);
3839 }
3840 GuardedAlternative rest_alt(on_success);
3841 if (has_min) {
3842 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3843 rest_alt.AddGuard(rest_guard);
3844 }
3845 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003846 center->AddLoopAlternative(body_alt);
3847 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003848 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003849 center->AddContinueAlternative(rest_alt);
3850 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003851 }
3852 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003853 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003854 } else {
3855 return center;
3856 }
3857}
3858
3859
3860RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003861 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003862 NodeInfo info;
3863 switch (type()) {
3864 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003865 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003866 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003867 return AssertionNode::AtStart(on_success);
3868 case BOUNDARY:
3869 return AssertionNode::AtBoundary(on_success);
3870 case NON_BOUNDARY:
3871 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003872 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003873 return AssertionNode::AtEnd(on_success);
3874 case END_OF_LINE: {
3875 // Compile $ in multiline regexps as an alternation with a positive
3876 // lookahead in one side and an end-of-input on the other side.
3877 // We need two registers for the lookahead.
3878 int stack_pointer_register = compiler->AllocateRegister();
3879 int position_register = compiler->AllocateRegister();
3880 // The ChoiceNode to distinguish between a newline and end-of-input.
3881 ChoiceNode* result = new ChoiceNode(2);
3882 // Create a newline atom.
3883 ZoneList<CharacterRange>* newline_ranges =
3884 new ZoneList<CharacterRange>(3);
3885 CharacterRange::AddClassEscape('n', newline_ranges);
3886 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3887 TextNode* newline_matcher = new TextNode(
3888 newline_atom,
3889 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3890 position_register,
3891 0, // No captures inside.
3892 -1, // Ignored if no captures.
3893 on_success));
3894 // Create an end-of-input matcher.
3895 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3896 stack_pointer_register,
3897 position_register,
3898 newline_matcher);
3899 // Add the two alternatives to the ChoiceNode.
3900 GuardedAlternative eol_alternative(end_of_line);
3901 result->AddAlternative(eol_alternative);
3902 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3903 result->AddAlternative(end_alternative);
3904 return result;
3905 }
3906 default:
3907 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003908 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003909 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003910}
3911
3912
3913RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003914 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003915 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3916 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003917 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003918}
3919
3920
3921RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003922 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003923 return on_success;
3924}
3925
3926
3927RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003928 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003929 int stack_pointer_register = compiler->AllocateRegister();
3930 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003931
3932 const int registers_per_capture = 2;
3933 const int register_of_first_capture = 2;
3934 int register_count = capture_count_ * registers_per_capture;
3935 int register_start =
3936 register_of_first_capture + capture_from_ * registers_per_capture;
3937
ager@chromium.org8bb60582008-12-11 12:02:20 +00003938 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003939 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003940 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003941 stack_pointer_register,
3942 position_register,
3943 body()->ToNode(
3944 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003945 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3946 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003947 register_count,
3948 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003949 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003950 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003951 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003952 // We use a ChoiceNode for a negative lookahead because it has most of
3953 // the characteristics we need. It has the body of the lookahead as its
3954 // first alternative and the expression after the lookahead of the second
3955 // alternative. If the first alternative succeeds then the
3956 // NegativeSubmatchSuccess will unwind the stack including everything the
3957 // choice node set up and backtrack. If the first alternative fails then
3958 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003959 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3960 // ChoiceNode that knows to ignore the first exit when calculating quick
3961 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003962 GuardedAlternative body_alt(
3963 body()->ToNode(
3964 compiler,
3965 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003966 position_register,
3967 register_count,
3968 register_start)));
3969 ChoiceNode* choice_node =
3970 new NegativeLookaheadChoiceNode(body_alt,
3971 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003972 return ActionNode::BeginSubmatch(stack_pointer_register,
3973 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003974 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003975 }
3976}
3977
3978
3979RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003980 RegExpNode* on_success) {
3981 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003982}
3983
3984
3985RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3986 int index,
3987 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003988 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003989 int start_reg = RegExpCapture::StartRegister(index);
3990 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003991 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003992 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003993 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003994}
3995
3996
3997RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003998 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003999 ZoneList<RegExpTree*>* children = nodes();
4000 RegExpNode* current = on_success;
4001 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004002 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004003 }
4004 return current;
4005}
4006
4007
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004008static void AddClass(const uc16* elmv,
4009 int elmc,
4010 ZoneList<CharacterRange>* ranges) {
4011 for (int i = 0; i < elmc; i += 2) {
4012 ASSERT(elmv[i] <= elmv[i + 1]);
4013 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
4014 }
4015}
4016
4017
4018static void AddClassNegated(const uc16 *elmv,
4019 int elmc,
4020 ZoneList<CharacterRange>* ranges) {
4021 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00004022 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004023 uc16 last = 0x0000;
4024 for (int i = 0; i < elmc; i += 2) {
4025 ASSERT(last <= elmv[i] - 1);
4026 ASSERT(elmv[i] <= elmv[i + 1]);
4027 ranges->Add(CharacterRange(last, elmv[i] - 1));
4028 last = elmv[i + 1] + 1;
4029 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004030 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004031}
4032
4033
4034void CharacterRange::AddClassEscape(uc16 type,
4035 ZoneList<CharacterRange>* ranges) {
4036 switch (type) {
4037 case 's':
4038 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
4039 break;
4040 case 'S':
4041 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
4042 break;
4043 case 'w':
4044 AddClass(kWordRanges, kWordRangeCount, ranges);
4045 break;
4046 case 'W':
4047 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
4048 break;
4049 case 'd':
4050 AddClass(kDigitRanges, kDigitRangeCount, ranges);
4051 break;
4052 case 'D':
4053 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
4054 break;
4055 case '.':
4056 AddClassNegated(kLineTerminatorRanges,
4057 kLineTerminatorRangeCount,
4058 ranges);
4059 break;
4060 // This is not a character range as defined by the spec but a
4061 // convenient shorthand for a character class that matches any
4062 // character.
4063 case '*':
4064 ranges->Add(CharacterRange::Everything());
4065 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004066 // This is the set of characters matched by the $ and ^ symbols
4067 // in multiline mode.
4068 case 'n':
4069 AddClass(kLineTerminatorRanges,
4070 kLineTerminatorRangeCount,
4071 ranges);
4072 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004073 default:
4074 UNREACHABLE();
4075 }
4076}
4077
4078
4079Vector<const uc16> CharacterRange::GetWordBounds() {
4080 return Vector<const uc16>(kWordRanges, kWordRangeCount);
4081}
4082
4083
4084class CharacterRangeSplitter {
4085 public:
4086 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
4087 ZoneList<CharacterRange>** excluded)
4088 : included_(included),
4089 excluded_(excluded) { }
4090 void Call(uc16 from, DispatchTable::Entry entry);
4091
4092 static const int kInBase = 0;
4093 static const int kInOverlay = 1;
4094
4095 private:
4096 ZoneList<CharacterRange>** included_;
4097 ZoneList<CharacterRange>** excluded_;
4098};
4099
4100
4101void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
4102 if (!entry.out_set()->Get(kInBase)) return;
4103 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
4104 ? included_
4105 : excluded_;
4106 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
4107 (*target)->Add(CharacterRange(entry.from(), entry.to()));
4108}
4109
4110
4111void CharacterRange::Split(ZoneList<CharacterRange>* base,
4112 Vector<const uc16> overlay,
4113 ZoneList<CharacterRange>** included,
4114 ZoneList<CharacterRange>** excluded) {
4115 ASSERT_EQ(NULL, *included);
4116 ASSERT_EQ(NULL, *excluded);
4117 DispatchTable table;
4118 for (int i = 0; i < base->length(); i++)
4119 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
4120 for (int i = 0; i < overlay.length(); i += 2) {
4121 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
4122 CharacterRangeSplitter::kInOverlay);
4123 }
4124 CharacterRangeSplitter callback(included, excluded);
4125 table.ForEach(&callback);
4126}
4127
4128
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004129static void AddUncanonicals(Isolate* isolate,
4130 ZoneList<CharacterRange>* ranges,
ager@chromium.org38e4c712009-11-11 09:11:58 +00004131 int bottom,
4132 int top);
4133
4134
4135void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4136 bool is_ascii) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004137 Isolate* isolate = Isolate::Current();
ager@chromium.org38e4c712009-11-11 09:11:58 +00004138 uc16 bottom = from();
4139 uc16 top = to();
4140 if (is_ascii) {
4141 if (bottom > String::kMaxAsciiCharCode) return;
4142 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4143 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004144 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004145 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004146 // If this is a singleton we just expand the one character.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004147 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004148 for (int i = 0; i < length; i++) {
4149 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004150 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004151 ranges->Add(CharacterRange::Singleton(chars[i]));
4152 }
4153 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004154 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004155 // If this is a range we expand the characters block by block,
4156 // expanding contiguous subranges (blocks) one at a time.
4157 // The approach is as follows. For a given start character we
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004158 // look up the remainder of the block that contains it (represented
4159 // by the end point), for instance we find 'z' if the character
4160 // is 'c'. A block is characterized by the property
4161 // that all characters uncanonicalize in the same way, except that
4162 // each entry in the result is incremented by the distance from the first
4163 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
4164 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
4165 // Once we've found the end point we look up its uncanonicalization
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004166 // and produce a range for each element. For instance for [c-f]
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004167 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004168 // add a range if it is not already contained in the input, so [c-f]
4169 // will be skipped but [C-F] will be added. If this range is not
4170 // completely contained in a block we do this for all the blocks
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004171 // covered by the range (handling characters that is not in a block
4172 // as a "singleton block").
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004173 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004174 int pos = bottom;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004175 while (pos < top) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004176 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004177 uc16 block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004178 if (length == 0) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004179 block_end = pos;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004180 } else {
4181 ASSERT_EQ(1, length);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004182 block_end = range[0];
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004183 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004184 int end = (block_end > top) ? top : block_end;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004185 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004186 for (int i = 0; i < length; i++) {
4187 uc32 c = range[i];
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004188 uc16 range_from = c - (block_end - pos);
4189 uc16 range_to = c - (block_end - end);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004190 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004191 ranges->Add(CharacterRange(range_from, range_to));
4192 }
4193 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004194 pos = end + 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004195 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004196 }
4197}
4198
4199
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004200bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4201 ASSERT_NOT_NULL(ranges);
4202 int n = ranges->length();
4203 if (n <= 1) return true;
4204 int max = ranges->at(0).to();
4205 for (int i = 1; i < n; i++) {
4206 CharacterRange next_range = ranges->at(i);
4207 if (next_range.from() <= max + 1) return false;
4208 max = next_range.to();
4209 }
4210 return true;
4211}
4212
4213SetRelation CharacterRange::WordCharacterRelation(
4214 ZoneList<CharacterRange>* range) {
4215 ASSERT(IsCanonical(range));
4216 int i = 0; // Word character range index.
4217 int j = 0; // Argument range index.
4218 ASSERT_NE(0, kWordRangeCount);
4219 SetRelation result;
4220 if (range->length() == 0) {
4221 result.SetElementsInSecondSet();
4222 return result;
4223 }
4224 CharacterRange argument_range = range->at(0);
4225 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4226 while (i < kWordRangeCount && j < range->length()) {
4227 // Check the two ranges for the five cases:
4228 // - no overlap.
4229 // - partial overlap (there are elements in both ranges that isn't
4230 // in the other, and there are also elements that are in both).
4231 // - argument range entirely inside word range.
4232 // - word range entirely inside argument range.
4233 // - ranges are completely equal.
4234
4235 // First check for no overlap. The earlier range is not in the other set.
4236 if (argument_range.from() > word_range.to()) {
4237 // Ranges are disjoint. The earlier word range contains elements that
4238 // cannot be in the argument set.
4239 result.SetElementsInSecondSet();
4240 } else if (word_range.from() > argument_range.to()) {
4241 // Ranges are disjoint. The earlier argument range contains elements that
4242 // cannot be in the word set.
4243 result.SetElementsInFirstSet();
4244 } else if (word_range.from() <= argument_range.from() &&
4245 word_range.to() >= argument_range.from()) {
4246 result.SetElementsInBothSets();
4247 // argument range completely inside word range.
4248 if (word_range.from() < argument_range.from() ||
4249 word_range.to() > argument_range.from()) {
4250 result.SetElementsInSecondSet();
4251 }
4252 } else if (word_range.from() >= argument_range.from() &&
4253 word_range.to() <= argument_range.from()) {
4254 result.SetElementsInBothSets();
4255 result.SetElementsInFirstSet();
4256 } else {
4257 // There is overlap, and neither is a subrange of the other
4258 result.SetElementsInFirstSet();
4259 result.SetElementsInSecondSet();
4260 result.SetElementsInBothSets();
4261 }
4262 if (result.NonTrivialIntersection()) {
4263 // The result is as (im)precise as we can possibly make it.
4264 return result;
4265 }
4266 // Progress the range(s) with minimal to-character.
4267 uc16 word_to = word_range.to();
4268 uc16 argument_to = argument_range.to();
4269 if (argument_to <= word_to) {
4270 j++;
4271 if (j < range->length()) {
4272 argument_range = range->at(j);
4273 }
4274 }
4275 if (word_to <= argument_to) {
4276 i += 2;
4277 if (i < kWordRangeCount) {
4278 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4279 }
4280 }
4281 }
4282 // Check if anything wasn't compared in the loop.
4283 if (i < kWordRangeCount) {
4284 // word range contains something not in argument range.
4285 result.SetElementsInSecondSet();
4286 } else if (j < range->length()) {
4287 // Argument range contains something not in word range.
4288 result.SetElementsInFirstSet();
4289 }
4290
4291 return result;
4292}
4293
4294
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004295static void AddUncanonicals(Isolate* isolate,
4296 ZoneList<CharacterRange>* ranges,
ager@chromium.org38e4c712009-11-11 09:11:58 +00004297 int bottom,
4298 int top) {
4299 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4300 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4301 // this table is correct.
4302 // 0x0600 - 0x0fff
4303 // 0x1100 - 0x1cff
4304 // 0x2000 - 0x20ff
4305 // 0x2200 - 0x23ff
4306 // 0x2500 - 0x2bff
4307 // 0x2e00 - 0xa5ff
4308 // 0xa800 - 0xfaff
4309 // 0xfc00 - 0xfeff
4310 const int boundary_count = 18;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004311 int boundaries[] = {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004312 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4313 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4314
4315 // Special ASCII rule from spec can save us some work here.
4316 if (bottom == 0x80 && top == 0xffff) return;
4317
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004318 if (top <= boundaries[0]) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004319 CharacterRange range(bottom, top);
4320 range.AddCaseEquivalents(ranges, false);
4321 return;
4322 }
4323
4324 // Split up very large ranges. This helps remove ranges where there are no
4325 // case mappings.
4326 for (int i = 0; i < boundary_count; i++) {
4327 if (bottom < boundaries[i] && top >= boundaries[i]) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004328 AddUncanonicals(isolate, ranges, bottom, boundaries[i] - 1);
4329 AddUncanonicals(isolate, ranges, boundaries[i], top);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004330 return;
4331 }
4332 }
4333
4334 // If we are completely in a zone with no case mappings then we are done.
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004335 for (int i = 0; i < boundary_count; i += 2) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004336 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4337#ifdef DEBUG
4338 for (int j = bottom; j <= top; j++) {
4339 unsigned current_char = j;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004340 int length = isolate->jsregexp_uncanonicalize()->get(current_char,
4341 '\0', chars);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004342 for (int k = 0; k < length; k++) {
4343 ASSERT(chars[k] == current_char);
4344 }
4345 }
4346#endif
4347 return;
4348 }
4349 }
4350
4351 // Step through the range finding equivalent characters.
4352 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4353 for (int i = bottom; i <= top; i++) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004354 int length = isolate->jsregexp_uncanonicalize()->get(i, '\0', chars);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004355 for (int j = 0; j < length; j++) {
4356 uc32 chr = chars[j];
4357 if (chr != i && (chr < bottom || chr > top)) {
4358 characters->Add(chr);
4359 }
4360 }
4361 }
4362
4363 // Step through the equivalent characters finding simple ranges and
4364 // adding ranges to the character class.
4365 if (characters->length() > 0) {
4366 int new_from = characters->at(0);
4367 int new_to = new_from;
4368 for (int i = 1; i < characters->length(); i++) {
4369 int chr = characters->at(i);
4370 if (chr == new_to + 1) {
4371 new_to++;
4372 } else {
4373 if (new_to == new_from) {
4374 ranges->Add(CharacterRange::Singleton(new_from));
4375 } else {
4376 ranges->Add(CharacterRange(new_from, new_to));
4377 }
4378 new_from = new_to = chr;
4379 }
4380 }
4381 if (new_to == new_from) {
4382 ranges->Add(CharacterRange::Singleton(new_from));
4383 } else {
4384 ranges->Add(CharacterRange(new_from, new_to));
4385 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004386 }
4387}
4388
4389
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004390ZoneList<CharacterRange>* CharacterSet::ranges() {
4391 if (ranges_ == NULL) {
4392 ranges_ = new ZoneList<CharacterRange>(2);
4393 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4394 }
4395 return ranges_;
4396}
4397
4398
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004399// Move a number of elements in a zonelist to another position
4400// in the same list. Handles overlapping source and target areas.
4401static void MoveRanges(ZoneList<CharacterRange>* list,
4402 int from,
4403 int to,
4404 int count) {
4405 // Ranges are potentially overlapping.
4406 if (from < to) {
4407 for (int i = count - 1; i >= 0; i--) {
4408 list->at(to + i) = list->at(from + i);
4409 }
4410 } else {
4411 for (int i = 0; i < count; i++) {
4412 list->at(to + i) = list->at(from + i);
4413 }
4414 }
4415}
4416
4417
4418static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4419 int count,
4420 CharacterRange insert) {
4421 // Inserts a range into list[0..count[, which must be sorted
4422 // by from value and non-overlapping and non-adjacent, using at most
4423 // list[0..count] for the result. Returns the number of resulting
4424 // canonicalized ranges. Inserting a range may collapse existing ranges into
4425 // fewer ranges, so the return value can be anything in the range 1..count+1.
4426 uc16 from = insert.from();
4427 uc16 to = insert.to();
4428 int start_pos = 0;
4429 int end_pos = count;
4430 for (int i = count - 1; i >= 0; i--) {
4431 CharacterRange current = list->at(i);
4432 if (current.from() > to + 1) {
4433 end_pos = i;
4434 } else if (current.to() + 1 < from) {
4435 start_pos = i + 1;
4436 break;
4437 }
4438 }
4439
4440 // Inserted range overlaps, or is adjacent to, ranges at positions
4441 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4442 // not affected by the insertion.
4443 // If start_pos == end_pos, the range must be inserted before start_pos.
4444 // if start_pos < end_pos, the entire range from start_pos to end_pos
4445 // must be merged with the insert range.
4446
4447 if (start_pos == end_pos) {
4448 // Insert between existing ranges at position start_pos.
4449 if (start_pos < count) {
4450 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4451 }
4452 list->at(start_pos) = insert;
4453 return count + 1;
4454 }
4455 if (start_pos + 1 == end_pos) {
4456 // Replace single existing range at position start_pos.
4457 CharacterRange to_replace = list->at(start_pos);
4458 int new_from = Min(to_replace.from(), from);
4459 int new_to = Max(to_replace.to(), to);
4460 list->at(start_pos) = CharacterRange(new_from, new_to);
4461 return count;
4462 }
4463 // Replace a number of existing ranges from start_pos to end_pos - 1.
4464 // Move the remaining ranges down.
4465
4466 int new_from = Min(list->at(start_pos).from(), from);
4467 int new_to = Max(list->at(end_pos - 1).to(), to);
4468 if (end_pos < count) {
4469 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4470 }
4471 list->at(start_pos) = CharacterRange(new_from, new_to);
4472 return count - (end_pos - start_pos) + 1;
4473}
4474
4475
4476void CharacterSet::Canonicalize() {
4477 // Special/default classes are always considered canonical. The result
4478 // of calling ranges() will be sorted.
4479 if (ranges_ == NULL) return;
4480 CharacterRange::Canonicalize(ranges_);
4481}
4482
4483
4484void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4485 if (character_ranges->length() <= 1) return;
4486 // Check whether ranges are already canonical (increasing, non-overlapping,
4487 // non-adjacent).
4488 int n = character_ranges->length();
4489 int max = character_ranges->at(0).to();
4490 int i = 1;
4491 while (i < n) {
4492 CharacterRange current = character_ranges->at(i);
4493 if (current.from() <= max + 1) {
4494 break;
4495 }
4496 max = current.to();
4497 i++;
4498 }
4499 // Canonical until the i'th range. If that's all of them, we are done.
4500 if (i == n) return;
4501
4502 // The ranges at index i and forward are not canonicalized. Make them so by
4503 // doing the equivalent of insertion sort (inserting each into the previous
4504 // list, in order).
4505 // Notice that inserting a range can reduce the number of ranges in the
4506 // result due to combining of adjacent and overlapping ranges.
4507 int read = i; // Range to insert.
4508 int num_canonical = i; // Length of canonicalized part of list.
4509 do {
4510 num_canonical = InsertRangeInCanonicalList(character_ranges,
4511 num_canonical,
4512 character_ranges->at(read));
4513 read++;
4514 } while (read < n);
4515 character_ranges->Rewind(num_canonical);
4516
4517 ASSERT(CharacterRange::IsCanonical(character_ranges));
4518}
4519
4520
4521// Utility function for CharacterRange::Merge. Adds a range at the end of
4522// a canonicalized range list, if necessary merging the range with the last
4523// range of the list.
4524static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4525 if (set == NULL) return;
4526 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4527 int n = set->length();
4528 if (n > 0) {
4529 CharacterRange lastRange = set->at(n - 1);
4530 if (lastRange.to() == range.from() - 1) {
4531 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4532 return;
4533 }
4534 }
4535 set->Add(range);
4536}
4537
4538
4539static void AddRangeToSelectedSet(int selector,
4540 ZoneList<CharacterRange>* first_set,
4541 ZoneList<CharacterRange>* second_set,
4542 ZoneList<CharacterRange>* intersection_set,
4543 CharacterRange range) {
4544 switch (selector) {
4545 case kInsideFirst:
4546 AddRangeToSet(first_set, range);
4547 break;
4548 case kInsideSecond:
4549 AddRangeToSet(second_set, range);
4550 break;
4551 case kInsideBoth:
4552 AddRangeToSet(intersection_set, range);
4553 break;
4554 }
4555}
4556
4557
4558
4559void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4560 ZoneList<CharacterRange>* second_set,
4561 ZoneList<CharacterRange>* first_set_only_out,
4562 ZoneList<CharacterRange>* second_set_only_out,
4563 ZoneList<CharacterRange>* both_sets_out) {
4564 // Inputs are canonicalized.
4565 ASSERT(CharacterRange::IsCanonical(first_set));
4566 ASSERT(CharacterRange::IsCanonical(second_set));
4567 // Outputs are empty, if applicable.
4568 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4569 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4570 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4571
4572 // Merge sets by iterating through the lists in order of lowest "from" value,
4573 // and putting intervals into one of three sets.
4574
4575 if (first_set->length() == 0) {
4576 second_set_only_out->AddAll(*second_set);
4577 return;
4578 }
4579 if (second_set->length() == 0) {
4580 first_set_only_out->AddAll(*first_set);
4581 return;
4582 }
4583 // Indices into input lists.
4584 int i1 = 0;
4585 int i2 = 0;
4586 // Cache length of input lists.
4587 int n1 = first_set->length();
4588 int n2 = second_set->length();
4589 // Current range. May be invalid if state is kInsideNone.
4590 int from = 0;
4591 int to = -1;
4592 // Where current range comes from.
4593 int state = kInsideNone;
4594
4595 while (i1 < n1 || i2 < n2) {
4596 CharacterRange next_range;
4597 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004598 if (i2 == n2 ||
4599 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4600 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004601 next_range = first_set->at(i1++);
4602 range_source = kInsideFirst;
4603 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004604 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004605 next_range = second_set->at(i2++);
4606 range_source = kInsideSecond;
4607 }
4608 if (to < next_range.from()) {
4609 // Ranges disjoint: |current| |next|
4610 AddRangeToSelectedSet(state,
4611 first_set_only_out,
4612 second_set_only_out,
4613 both_sets_out,
4614 CharacterRange(from, to));
4615 from = next_range.from();
4616 to = next_range.to();
4617 state = range_source;
4618 } else {
4619 if (from < next_range.from()) {
4620 AddRangeToSelectedSet(state,
4621 first_set_only_out,
4622 second_set_only_out,
4623 both_sets_out,
4624 CharacterRange(from, next_range.from()-1));
4625 }
4626 if (to < next_range.to()) {
4627 // Ranges overlap: |current|
4628 // |next|
4629 AddRangeToSelectedSet(state | range_source,
4630 first_set_only_out,
4631 second_set_only_out,
4632 both_sets_out,
4633 CharacterRange(next_range.from(), to));
4634 from = to + 1;
4635 to = next_range.to();
4636 state = range_source;
4637 } else {
4638 // Range included: |current| , possibly ending at same character.
4639 // |next|
4640 AddRangeToSelectedSet(
4641 state | range_source,
4642 first_set_only_out,
4643 second_set_only_out,
4644 both_sets_out,
4645 CharacterRange(next_range.from(), next_range.to()));
4646 from = next_range.to() + 1;
4647 // If ranges end at same character, both ranges are consumed completely.
4648 if (next_range.to() == to) state = kInsideNone;
4649 }
4650 }
4651 }
4652 AddRangeToSelectedSet(state,
4653 first_set_only_out,
4654 second_set_only_out,
4655 both_sets_out,
4656 CharacterRange(from, to));
4657}
4658
4659
4660void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4661 ZoneList<CharacterRange>* negated_ranges) {
4662 ASSERT(CharacterRange::IsCanonical(ranges));
4663 ASSERT_EQ(0, negated_ranges->length());
4664 int range_count = ranges->length();
4665 uc16 from = 0;
4666 int i = 0;
4667 if (range_count > 0 && ranges->at(0).from() == 0) {
4668 from = ranges->at(0).to();
4669 i = 1;
4670 }
4671 while (i < range_count) {
4672 CharacterRange range = ranges->at(i);
4673 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4674 from = range.to();
4675 i++;
4676 }
4677 if (from < String::kMaxUC16CharCode) {
4678 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4679 }
4680}
4681
4682
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004683
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004684// -------------------------------------------------------------------
4685// Interest propagation
4686
4687
4688RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4689 for (int i = 0; i < siblings_.length(); i++) {
4690 RegExpNode* sibling = siblings_.Get(i);
4691 if (sibling->info()->Matches(info))
4692 return sibling;
4693 }
4694 return NULL;
4695}
4696
4697
4698RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4699 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004700 siblings_.Ensure(this);
4701 RegExpNode* result = TryGetSibling(info);
4702 if (result != NULL) return result;
4703 result = this->Clone();
4704 NodeInfo* new_info = result->info();
4705 new_info->ResetCompilationState();
4706 new_info->AddFromPreceding(info);
4707 AddSibling(result);
4708 *cloned = true;
4709 return result;
4710}
4711
4712
4713template <class C>
4714static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4715 NodeInfo full_info(*node->info());
4716 full_info.AddFromPreceding(info);
4717 bool cloned = false;
4718 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4719}
4720
4721
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004722// -------------------------------------------------------------------
4723// Splay tree
4724
4725
4726OutSet* OutSet::Extend(unsigned value) {
4727 if (Get(value))
4728 return this;
4729 if (successors() != NULL) {
4730 for (int i = 0; i < successors()->length(); i++) {
4731 OutSet* successor = successors()->at(i);
4732 if (successor->Get(value))
4733 return successor;
4734 }
4735 } else {
4736 successors_ = new ZoneList<OutSet*>(2);
4737 }
4738 OutSet* result = new OutSet(first_, remaining_);
4739 result->Set(value);
4740 successors()->Add(result);
4741 return result;
4742}
4743
4744
4745void OutSet::Set(unsigned value) {
4746 if (value < kFirstLimit) {
4747 first_ |= (1 << value);
4748 } else {
4749 if (remaining_ == NULL)
4750 remaining_ = new ZoneList<unsigned>(1);
4751 if (remaining_->is_empty() || !remaining_->Contains(value))
4752 remaining_->Add(value);
4753 }
4754}
4755
4756
4757bool OutSet::Get(unsigned value) {
4758 if (value < kFirstLimit) {
4759 return (first_ & (1 << value)) != 0;
4760 } else if (remaining_ == NULL) {
4761 return false;
4762 } else {
4763 return remaining_->Contains(value);
4764 }
4765}
4766
4767
4768const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4769const DispatchTable::Entry DispatchTable::Config::kNoValue;
4770
4771
4772void DispatchTable::AddRange(CharacterRange full_range, int value) {
4773 CharacterRange current = full_range;
4774 if (tree()->is_empty()) {
4775 // If this is the first range we just insert into the table.
4776 ZoneSplayTree<Config>::Locator loc;
4777 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4778 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4779 return;
4780 }
4781 // First see if there is a range to the left of this one that
4782 // overlaps.
4783 ZoneSplayTree<Config>::Locator loc;
4784 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4785 Entry* entry = &loc.value();
4786 // If we've found a range that overlaps with this one, and it
4787 // starts strictly to the left of this one, we have to fix it
4788 // because the following code only handles ranges that start on
4789 // or after the start point of the range we're adding.
4790 if (entry->from() < current.from() && entry->to() >= current.from()) {
4791 // Snap the overlapping range in half around the start point of
4792 // the range we're adding.
4793 CharacterRange left(entry->from(), current.from() - 1);
4794 CharacterRange right(current.from(), entry->to());
4795 // The left part of the overlapping range doesn't overlap.
4796 // Truncate the whole entry to be just the left part.
4797 entry->set_to(left.to());
4798 // The right part is the one that overlaps. We add this part
4799 // to the map and let the next step deal with merging it with
4800 // the range we're adding.
4801 ZoneSplayTree<Config>::Locator loc;
4802 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4803 loc.set_value(Entry(right.from(),
4804 right.to(),
4805 entry->out_set()));
4806 }
4807 }
4808 while (current.is_valid()) {
4809 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4810 (loc.value().from() <= current.to()) &&
4811 (loc.value().to() >= current.from())) {
4812 Entry* entry = &loc.value();
4813 // We have overlap. If there is space between the start point of
4814 // the range we're adding and where the overlapping range starts
4815 // then we have to add a range covering just that space.
4816 if (current.from() < entry->from()) {
4817 ZoneSplayTree<Config>::Locator ins;
4818 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4819 ins.set_value(Entry(current.from(),
4820 entry->from() - 1,
4821 empty()->Extend(value)));
4822 current.set_from(entry->from());
4823 }
4824 ASSERT_EQ(current.from(), entry->from());
4825 // If the overlapping range extends beyond the one we want to add
4826 // we have to snap the right part off and add it separately.
4827 if (entry->to() > current.to()) {
4828 ZoneSplayTree<Config>::Locator ins;
4829 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4830 ins.set_value(Entry(current.to() + 1,
4831 entry->to(),
4832 entry->out_set()));
4833 entry->set_to(current.to());
4834 }
4835 ASSERT(entry->to() <= current.to());
4836 // The overlapping range is now completely contained by the range
4837 // we're adding so we can just update it and move the start point
4838 // of the range we're adding just past it.
4839 entry->AddValue(value);
4840 // Bail out if the last interval ended at 0xFFFF since otherwise
4841 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004842 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004843 break;
4844 ASSERT(entry->to() + 1 > current.from());
4845 current.set_from(entry->to() + 1);
4846 } else {
4847 // There is no overlap so we can just add the range
4848 ZoneSplayTree<Config>::Locator ins;
4849 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4850 ins.set_value(Entry(current.from(),
4851 current.to(),
4852 empty()->Extend(value)));
4853 break;
4854 }
4855 }
4856}
4857
4858
4859OutSet* DispatchTable::Get(uc16 value) {
4860 ZoneSplayTree<Config>::Locator loc;
4861 if (!tree()->FindGreatestLessThan(value, &loc))
4862 return empty();
4863 Entry* entry = &loc.value();
4864 if (value <= entry->to())
4865 return entry->out_set();
4866 else
4867 return empty();
4868}
4869
4870
4871// -------------------------------------------------------------------
4872// Analysis
4873
4874
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004875void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004876 StackLimitCheck check(Isolate::Current());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004877 if (check.HasOverflowed()) {
4878 fail("Stack overflow");
4879 return;
4880 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004881 if (that->info()->been_analyzed || that->info()->being_analyzed)
4882 return;
4883 that->info()->being_analyzed = true;
4884 that->Accept(this);
4885 that->info()->being_analyzed = false;
4886 that->info()->been_analyzed = true;
4887}
4888
4889
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004890void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004891 // nothing to do
4892}
4893
4894
ager@chromium.org8bb60582008-12-11 12:02:20 +00004895void TextNode::CalculateOffsets() {
4896 int element_count = elements()->length();
4897 // Set up the offsets of the elements relative to the start. This is a fixed
4898 // quantity since a TextNode can only contain fixed-width things.
4899 int cp_offset = 0;
4900 for (int i = 0; i < element_count; i++) {
4901 TextElement& elm = elements()->at(i);
4902 elm.cp_offset = cp_offset;
4903 if (elm.type == TextElement::ATOM) {
4904 cp_offset += elm.data.u_atom->data().length();
4905 } else {
4906 cp_offset++;
4907 Vector<const uc16> quarks = elm.data.u_atom->data();
4908 }
4909 }
4910}
4911
4912
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004913void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004914 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004915 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004916 }
4917 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004918 if (!has_failed()) {
4919 that->CalculateOffsets();
4920 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004921}
4922
4923
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004924void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004925 RegExpNode* target = that->on_success();
4926 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004927 if (!has_failed()) {
4928 // If the next node is interested in what it follows then this node
4929 // has to be interested too so it can pass the information on.
4930 that->info()->AddFromFollowing(target->info());
4931 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004932}
4933
4934
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004935void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004936 NodeInfo* info = that->info();
4937 for (int i = 0; i < that->alternatives()->length(); i++) {
4938 RegExpNode* node = that->alternatives()->at(i).node();
4939 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004940 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004941 // Anything the following nodes need to know has to be known by
4942 // this node also, so it can pass it on.
4943 info->AddFromFollowing(node->info());
4944 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004945}
4946
4947
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004948void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4949 NodeInfo* info = that->info();
4950 for (int i = 0; i < that->alternatives()->length(); i++) {
4951 RegExpNode* node = that->alternatives()->at(i).node();
4952 if (node != that->loop_node()) {
4953 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004954 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004955 info->AddFromFollowing(node->info());
4956 }
4957 }
4958 // Check the loop last since it may need the value of this node
4959 // to get a correct result.
4960 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004961 if (!has_failed()) {
4962 info->AddFromFollowing(that->loop_node()->info());
4963 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004964}
4965
4966
4967void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004968 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004969}
4970
4971
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004972void Analysis::VisitAssertion(AssertionNode* that) {
4973 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004974 AssertionNode::AssertionNodeType type = that->type();
4975 if (type == AssertionNode::AT_BOUNDARY ||
4976 type == AssertionNode::AT_NON_BOUNDARY) {
4977 // Check if the following character is known to be a word character
4978 // or known to not be a word character.
4979 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4980
4981 CharacterRange::Canonicalize(following_chars);
4982
4983 SetRelation word_relation =
4984 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004985 if (word_relation.Disjoint()) {
4986 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004987 // Following character is definitely *not* a word character.
4988 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004989 AssertionNode::AFTER_WORD_CHARACTER :
4990 AssertionNode::AFTER_NONWORD_CHARACTER;
4991 that->set_type(type);
4992 } else if (word_relation.ContainedIn()) {
4993 // Following character is definitely a word character.
4994 type = (type == AssertionNode::AT_BOUNDARY) ?
4995 AssertionNode::AFTER_NONWORD_CHARACTER :
4996 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004997 that->set_type(type);
4998 }
4999 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005000}
5001
5002
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005003ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
5004 if (first_character_set_ == NULL) {
5005 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
5006 // If we can't find an exact solution within the budget, we
5007 // set the value to the set of every character, i.e., all characters
5008 // are possible.
5009 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
5010 all_set->Add(CharacterRange::Everything());
5011 first_character_set_ = all_set;
5012 }
5013 }
5014 return first_character_set_;
5015}
5016
5017
5018int RegExpNode::ComputeFirstCharacterSet(int budget) {
5019 // Default behavior is to not be able to determine the first character.
5020 return kComputeFirstCharacterSetFail;
5021}
5022
5023
5024int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
5025 budget--;
5026 if (budget >= 0) {
5027 // Find loop min-iteration. It's the value of the guarded choice node
5028 // with a GEQ guard, if any.
5029 int min_repetition = 0;
5030
5031 for (int i = 0; i <= 1; i++) {
5032 GuardedAlternative alternative = alternatives()->at(i);
5033 ZoneList<Guard*>* guards = alternative.guards();
5034 if (guards != NULL && guards->length() > 0) {
5035 Guard* guard = guards->at(0);
5036 if (guard->op() == Guard::GEQ) {
5037 min_repetition = guard->value();
5038 break;
5039 }
5040 }
5041 }
5042
5043 budget = loop_node()->ComputeFirstCharacterSet(budget);
5044 if (budget >= 0) {
5045 ZoneList<CharacterRange>* character_set =
5046 loop_node()->first_character_set();
5047 if (body_can_be_zero_length() || min_repetition == 0) {
5048 budget = continue_node()->ComputeFirstCharacterSet(budget);
5049 if (budget < 0) return budget;
5050 ZoneList<CharacterRange>* body_set =
5051 continue_node()->first_character_set();
5052 ZoneList<CharacterRange>* union_set =
5053 new ZoneList<CharacterRange>(Max(character_set->length(),
5054 body_set->length()));
5055 CharacterRange::Merge(character_set,
5056 body_set,
5057 union_set,
5058 union_set,
5059 union_set);
5060 character_set = union_set;
5061 }
5062 set_first_character_set(character_set);
5063 }
5064 }
5065 return budget;
5066}
5067
5068
5069int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
5070 budget--;
5071 if (budget >= 0) {
5072 GuardedAlternative successor = this->alternatives()->at(1);
5073 RegExpNode* successor_node = successor.node();
5074 budget = successor_node->ComputeFirstCharacterSet(budget);
5075 if (budget >= 0) {
5076 set_first_character_set(successor_node->first_character_set());
5077 }
5078 }
5079 return budget;
5080}
5081
5082
5083// The first character set of an EndNode is unknowable. Just use the
5084// default implementation that fails and returns all characters as possible.
5085
5086
5087int AssertionNode::ComputeFirstCharacterSet(int budget) {
5088 budget -= 1;
5089 if (budget >= 0) {
5090 switch (type_) {
5091 case AT_END: {
5092 set_first_character_set(new ZoneList<CharacterRange>(0));
5093 break;
5094 }
5095 case AT_START:
5096 case AT_BOUNDARY:
5097 case AT_NON_BOUNDARY:
5098 case AFTER_NEWLINE:
5099 case AFTER_NONWORD_CHARACTER:
5100 case AFTER_WORD_CHARACTER: {
5101 ASSERT_NOT_NULL(on_success());
5102 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005103 if (budget >= 0) {
5104 set_first_character_set(on_success()->first_character_set());
5105 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005106 break;
5107 }
5108 }
5109 }
5110 return budget;
5111}
5112
5113
5114int ActionNode::ComputeFirstCharacterSet(int budget) {
5115 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
5116 budget--;
5117 if (budget >= 0) {
5118 ASSERT_NOT_NULL(on_success());
5119 budget = on_success()->ComputeFirstCharacterSet(budget);
5120 if (budget >= 0) {
5121 set_first_character_set(on_success()->first_character_set());
5122 }
5123 }
5124 return budget;
5125}
5126
5127
5128int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5129 // We don't know anything about the first character of a backreference
5130 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005131 // The potential first characters are the first characters of the capture,
5132 // and the first characters of the on_success node, depending on whether the
5133 // capture can be empty and whether it is known to be participating or known
5134 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005135 return kComputeFirstCharacterSetFail;
5136}
5137
5138
5139int TextNode::ComputeFirstCharacterSet(int budget) {
5140 budget--;
5141 if (budget >= 0) {
5142 ASSERT_NE(0, elements()->length());
5143 TextElement text = elements()->at(0);
5144 if (text.type == TextElement::ATOM) {
5145 RegExpAtom* atom = text.data.u_atom;
5146 ASSERT_NE(0, atom->length());
5147 uc16 first_char = atom->data()[0];
5148 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5149 range->Add(CharacterRange(first_char, first_char));
5150 set_first_character_set(range);
5151 } else {
5152 ASSERT(text.type == TextElement::CHAR_CLASS);
5153 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005154 ZoneList<CharacterRange>* ranges = char_class->ranges();
5155 // TODO(lrn): Canonicalize ranges when they are created
5156 // instead of waiting until now.
5157 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005158 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005159 int length = ranges->length();
5160 int new_length = length + 1;
5161 if (length > 0) {
5162 if (ranges->at(0).from() == 0) new_length--;
5163 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5164 new_length--;
5165 }
5166 }
5167 ZoneList<CharacterRange>* negated_ranges =
5168 new ZoneList<CharacterRange>(new_length);
5169 CharacterRange::Negate(ranges, negated_ranges);
5170 set_first_character_set(negated_ranges);
5171 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005172 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005173 }
5174 }
5175 }
5176 return budget;
5177}
5178
5179
5180
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005181// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005182// Dispatch table construction
5183
5184
5185void DispatchTableConstructor::VisitEnd(EndNode* that) {
5186 AddRange(CharacterRange::Everything());
5187}
5188
5189
5190void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5191 node->set_being_calculated(true);
5192 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5193 for (int i = 0; i < alternatives->length(); i++) {
5194 set_choice_index(i);
5195 alternatives->at(i).node()->Accept(this);
5196 }
5197 node->set_being_calculated(false);
5198}
5199
5200
5201class AddDispatchRange {
5202 public:
5203 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5204 : constructor_(constructor) { }
5205 void Call(uc32 from, DispatchTable::Entry entry);
5206 private:
5207 DispatchTableConstructor* constructor_;
5208};
5209
5210
5211void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5212 CharacterRange range(from, entry.to());
5213 constructor_->AddRange(range);
5214}
5215
5216
5217void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5218 if (node->being_calculated())
5219 return;
5220 DispatchTable* table = node->GetTable(ignore_case_);
5221 AddDispatchRange adder(this);
5222 table->ForEach(&adder);
5223}
5224
5225
5226void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5227 // TODO(160): Find the node that we refer back to and propagate its start
5228 // set back to here. For now we just accept anything.
5229 AddRange(CharacterRange::Everything());
5230}
5231
5232
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005233void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5234 RegExpNode* target = that->on_success();
5235 target->Accept(this);
5236}
5237
5238
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005239static int CompareRangeByFrom(const CharacterRange* a,
5240 const CharacterRange* b) {
5241 return Compare<uc16>(a->from(), b->from());
5242}
5243
5244
5245void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5246 ranges->Sort(CompareRangeByFrom);
5247 uc16 last = 0;
5248 for (int i = 0; i < ranges->length(); i++) {
5249 CharacterRange range = ranges->at(i);
5250 if (last < range.from())
5251 AddRange(CharacterRange(last, range.from() - 1));
5252 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005253 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005254 return;
5255 } else {
5256 last = range.to() + 1;
5257 }
5258 }
5259 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005260 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005261}
5262
5263
5264void DispatchTableConstructor::VisitText(TextNode* that) {
5265 TextElement elm = that->elements()->at(0);
5266 switch (elm.type) {
5267 case TextElement::ATOM: {
5268 uc16 c = elm.data.u_atom->data()[0];
5269 AddRange(CharacterRange(c, c));
5270 break;
5271 }
5272 case TextElement::CHAR_CLASS: {
5273 RegExpCharacterClass* tree = elm.data.u_char_class;
5274 ZoneList<CharacterRange>* ranges = tree->ranges();
5275 if (tree->is_negated()) {
5276 AddInverse(ranges);
5277 } else {
5278 for (int i = 0; i < ranges->length(); i++)
5279 AddRange(ranges->at(i));
5280 }
5281 break;
5282 }
5283 default: {
5284 UNIMPLEMENTED();
5285 }
5286 }
5287}
5288
5289
5290void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005291 RegExpNode* target = that->on_success();
5292 target->Accept(this);
5293}
5294
5295
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005296RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5297 bool ignore_case,
5298 bool is_multiline,
5299 Handle<String> pattern,
5300 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005301 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005302 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005303 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005304 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005305 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005306 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005307 0,
5308 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005309 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005310 RegExpNode* node = captured_body;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005311 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
5312 bool is_start_anchored = data->tree->IsAnchoredAtStart();
5313 int max_length = data->tree->max_match();
5314 if (!is_start_anchored) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005315 // Add a .*? at the beginning, outside the body capture, unless
5316 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005317 RegExpNode* loop_node =
5318 RegExpQuantifier::ToNode(0,
5319 RegExpTree::kInfinity,
5320 false,
5321 new RegExpCharacterClass('*'),
5322 &compiler,
5323 captured_body,
5324 data->contains_anchor);
5325
5326 if (data->contains_anchor) {
5327 // Unroll loop once, to take care of the case that might start
5328 // at the start of input.
5329 ChoiceNode* first_step_node = new ChoiceNode(2);
5330 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5331 first_step_node->AddAlternative(GuardedAlternative(
5332 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5333 node = first_step_node;
5334 } else {
5335 node = loop_node;
5336 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005337 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005338 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005339 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005340 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005341 if (analysis.has_failed()) {
5342 const char* error_message = analysis.error_message();
5343 return CompilationResult(error_message);
5344 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005345
5346 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005347
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005348 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005349#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005350 // Native regexp implementation.
5351
5352 NativeRegExpMacroAssembler::Mode mode =
5353 is_ascii ? NativeRegExpMacroAssembler::ASCII
5354 : NativeRegExpMacroAssembler::UC16;
5355
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005356#if V8_TARGET_ARCH_IA32
5357 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5358#elif V8_TARGET_ARCH_X64
5359 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5360#elif V8_TARGET_ARCH_ARM
5361 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
lrn@chromium.org7516f052011-03-30 08:52:27 +00005362#elif V8_TARGET_ARCH_MIPS
5363 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005364#endif
5365
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005366#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005367 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005368 EmbeddedVector<byte, 1024> codes;
5369 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005370#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005371
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005372 // Inserted here, instead of in Assembler, because it depends on information
5373 // in the AST that isn't replicated in the Node structure.
5374 static const int kMaxBacksearchLimit = 1024;
5375 if (is_end_anchored &&
5376 !is_start_anchored &&
5377 max_length < kMaxBacksearchLimit) {
5378 macro_assembler.SetCurrentPositionFromEnd(max_length);
5379 }
5380
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005381 return compiler.Assemble(&macro_assembler,
5382 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005383 data->capture_count,
5384 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005385}
5386
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005387
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005388}} // namespace v8::internal