blob: 2db8ddff9fde0a716ac28fe31e000fea386a0162 [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"
kasperl@chromium.org2abc4502009-07-02 07:00:29 +000053#else
54#error Unsupported target architecture.
ager@chromium.orga74f0da2008-12-03 16:05:52 +000055#endif
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000056#endif
ager@chromium.orga74f0da2008-12-03 16:05:52 +000057
58#include "interpreter-irregexp.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000059
ager@chromium.orga74f0da2008-12-03 16:05:52 +000060
kasperl@chromium.org71affb52009-05-26 05:44:31 +000061namespace v8 {
62namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000064Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
65 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000066 Handle<String> flags,
67 bool* has_pending_exception) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000068 // Call the construct code with 2 arguments.
69 Object** argv[2] = { Handle<Object>::cast(pattern).location(),
70 Handle<Object>::cast(flags).location() };
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000071 return Execution::New(constructor, 2, argv, has_pending_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000072}
73
74
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000075static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
76 int flags = JSRegExp::NONE;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000077 for (int i = 0; i < str->length(); i++) {
78 switch (str->Get(i)) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000079 case 'i':
80 flags |= JSRegExp::IGNORE_CASE;
81 break;
82 case 'g':
83 flags |= JSRegExp::GLOBAL;
84 break;
85 case 'm':
86 flags |= JSRegExp::MULTILINE;
87 break;
88 }
89 }
90 return JSRegExp::Flags(flags);
91}
92
93
ager@chromium.orga74f0da2008-12-03 16:05:52 +000094static inline void ThrowRegExpException(Handle<JSRegExp> re,
95 Handle<String> pattern,
96 Handle<String> error_text,
97 const char* message) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000098 Isolate* isolate = re->GetIsolate();
99 Factory* factory = isolate->factory();
100 Handle<FixedArray> elements = factory->NewFixedArray(2);
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000101 elements->set(0, *pattern);
102 elements->set(1, *error_text);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000103 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
104 Handle<Object> regexp_err = factory->NewSyntaxError(message, array);
105 isolate->Throw(*regexp_err);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000106}
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000107
108
ager@chromium.org8bb60582008-12-11 12:02:20 +0000109// Generic RegExp methods. Dispatches to implementation specific methods.
110
111
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000112Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
113 Handle<String> pattern,
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000114 Handle<String> flag_str) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000115 Isolate* isolate = re->GetIsolate();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000116 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000117 CompilationCache* compilation_cache = isolate->compilation_cache();
118 Handle<FixedArray> cached = compilation_cache->LookupRegExp(pattern, flags);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000119 bool in_cache = !cached.is_null();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000120 LOG(isolate, RegExpCompileEvent(re, in_cache));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000121
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000122 Handle<Object> result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000123 if (in_cache) {
124 re->set_data(*cached);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000125 return re;
126 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000127 pattern = FlattenGetString(pattern);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000128 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000129 PostponeInterruptsScope postpone(isolate);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000130 RegExpCompileData parse_result;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000131 FlatStringReader reader(isolate, pattern);
fschneider@chromium.orge03fb642010-11-01 12:34:09 +0000132 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
133 &parse_result)) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000134 // Throw an exception if we fail to parse the pattern.
135 ThrowRegExpException(re,
136 pattern,
137 parse_result.error,
138 "malformed_regexp");
139 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000140 }
141
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000142 if (parse_result.simple && !flags.is_ignore_case()) {
143 // Parse-tree is a single atom that is equal to the pattern.
144 AtomCompile(re, pattern, flags, pattern);
145 } else if (parse_result.tree->IsAtom() &&
146 !flags.is_ignore_case() &&
147 parse_result.capture_count == 0) {
148 RegExpAtom* atom = parse_result.tree->AsAtom();
149 Vector<const uc16> atom_pattern = atom->data();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000150 Handle<String> atom_string =
151 isolate->factory()->NewStringFromTwoByte(atom_pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000152 AtomCompile(re, pattern, flags, atom_string);
153 } else {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000154 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000155 }
156 ASSERT(re->data()->IsFixedArray());
157 // Compilation succeeded so the data is set on the regexp
158 // and we can store it in the cache.
159 Handle<FixedArray> data(FixedArray::cast(re->data()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000160 compilation_cache->PutRegExp(pattern, flags, data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000161
162 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000163}
164
165
166Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
167 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000168 int index,
169 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000170 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000171 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000172 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000173 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000174 Handle<Object> result =
175 IrregexpExec(regexp, subject, index, last_match_info);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000176 ASSERT(!result.is_null() || Isolate::Current()->has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000177 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000178 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000179 default:
180 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000181 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000182 }
183}
184
185
ager@chromium.org8bb60582008-12-11 12:02:20 +0000186// RegExp Atom implementation: Simple string search using indexOf.
187
188
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000189void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
190 Handle<String> pattern,
191 JSRegExp::Flags flags,
192 Handle<String> match_pattern) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000193 re->GetIsolate()->factory()->SetRegExpAtomData(re,
194 JSRegExp::ATOM,
195 pattern,
196 flags,
197 match_pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000198}
199
200
201static void SetAtomLastCapture(FixedArray* array,
202 String* subject,
203 int from,
204 int to) {
205 NoHandleAllocation no_handles;
206 RegExpImpl::SetLastCaptureCount(array, 2);
207 RegExpImpl::SetLastSubject(array, subject);
208 RegExpImpl::SetLastInput(array, subject);
209 RegExpImpl::SetCapture(array, 0, from);
210 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000211}
212
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000213 /* template <typename SubjectChar>, typename PatternChar>
214static int ReStringMatch(Vector<const SubjectChar> sub_vector,
215 Vector<const PatternChar> pat_vector,
216 int start_index) {
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000217
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000218 int pattern_length = pat_vector.length();
219 if (pattern_length == 0) return start_index;
220
221 int subject_length = sub_vector.length();
222 if (start_index + pattern_length > subject_length) return -1;
223 return SearchString(sub_vector, pat_vector, start_index);
224}
225 */
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000226Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
227 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000228 int index,
229 Handle<JSArray> last_match_info) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000230 Isolate* isolate = re->GetIsolate();
231
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000232 ASSERT(0 <= index);
233 ASSERT(index <= subject->length());
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000234
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000235 if (!subject->IsFlat()) FlattenString(subject);
236 AssertNoAllocation no_heap_allocation; // ensure vectors stay valid
237 // Extract flattened substrings of cons strings before determining asciiness.
238 String* seq_sub = *subject;
239 if (seq_sub->IsConsString()) seq_sub = ConsString::cast(seq_sub)->first();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000240
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000241 String* needle = String::cast(re->DataAt(JSRegExp::kAtomPatternIndex));
242 int needle_len = needle->length();
243
244 if (needle_len != 0) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000245 if (index + needle_len > subject->length())
246 return isolate->factory()->null_value();
247
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000248 // dispatch on type of strings
249 index = (needle->IsAsciiRepresentation()
250 ? (seq_sub->IsAsciiRepresentation()
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000251 ? SearchString(isolate,
252 seq_sub->ToAsciiVector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000253 needle->ToAsciiVector(),
254 index)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000255 : SearchString(isolate,
256 seq_sub->ToUC16Vector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000257 needle->ToAsciiVector(),
258 index))
259 : (seq_sub->IsAsciiRepresentation()
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000260 ? SearchString(isolate,
261 seq_sub->ToAsciiVector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000262 needle->ToUC16Vector(),
263 index)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000264 : SearchString(isolate,
265 seq_sub->ToUC16Vector(),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000266 needle->ToUC16Vector(),
267 index)));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000268 if (index == -1) return FACTORY->null_value();
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000269 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000270 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000271
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000272 {
273 NoHandleAllocation no_handles;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000274 FixedArray* array = FixedArray::cast(last_match_info->elements());
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000275 SetAtomLastCapture(array, *subject, index, index + needle_len);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000276 }
277 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000278}
279
280
ager@chromium.org8bb60582008-12-11 12:02:20 +0000281// Irregexp implementation.
282
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000283// Ensures that the regexp object contains a compiled version of the
284// source for either ASCII or non-ASCII strings.
285// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000286// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000287// If compilation fails, an exception is thrown and this function
288// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000289bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000290 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000291#ifdef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000292 if (compiled_code->IsByteArray()) return true;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000293#else // V8_INTERPRETED_REGEXP (RegExp native code)
294 if (compiled_code->IsCode()) return true;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000295#endif
296 return CompileIrregexp(re, is_ascii);
297}
ager@chromium.org8bb60582008-12-11 12:02:20 +0000298
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000299
300bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000301 // Compile the RegExp.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000302 Isolate* isolate = re->GetIsolate();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000303 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000304 PostponeInterruptsScope postpone(isolate);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000305 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
306 if (entry->IsJSObject()) {
307 // If it's a JSObject, a previous compilation failed and threw this object.
308 // Re-throw the object without trying again.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000309 isolate->Throw(entry);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000310 return false;
311 }
312 ASSERT(entry->IsTheHole());
ager@chromium.org8bb60582008-12-11 12:02:20 +0000313
314 JSRegExp::Flags flags = re->GetFlags();
315
316 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000317 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000318 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000319 }
320
321 RegExpCompileData compile_data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000322 FlatStringReader reader(isolate, pattern);
fschneider@chromium.orge03fb642010-11-01 12:34:09 +0000323 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
324 &compile_data)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000325 // Throw an exception if we fail to parse the pattern.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000326 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000327 ThrowRegExpException(re,
328 pattern,
329 compile_data.error,
330 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000331 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000332 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000333 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000334 RegExpEngine::Compile(&compile_data,
335 flags.is_ignore_case(),
336 flags.is_multiline(),
337 pattern,
338 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000339 if (result.error_message != NULL) {
340 // Unable to compile regexp.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000341 Factory* factory = isolate->factory();
342 Handle<FixedArray> elements = factory->NewFixedArray(2);
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000343 elements->set(0, *pattern);
344 Handle<String> error_message =
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000345 factory->NewStringFromUtf8(CStrVector(result.error_message));
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000346 elements->set(1, *error_message);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000347 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000348 Handle<Object> regexp_err =
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000349 factory->NewSyntaxError("malformed_regexp", array);
350 isolate->Throw(*regexp_err);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000351 re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000352 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000353 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000354
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000355 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
356 data->set(JSRegExp::code_index(is_ascii), result.code);
357 int register_max = IrregexpMaxRegisterCount(*data);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000358 if (result.num_registers > register_max) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000359 SetIrregexpMaxRegisterCount(*data, result.num_registers);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000360 }
361
362 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000363}
364
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000365
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000366int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
367 return Smi::cast(
368 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000369}
370
371
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000372void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
373 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000374}
375
376
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000377int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
378 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000379}
380
381
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000382int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
383 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000384}
385
386
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000387ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000388 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000389}
390
391
392Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000393 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000394}
395
396
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000397void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
398 Handle<String> pattern,
399 JSRegExp::Flags flags,
400 int capture_count) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000401 // Initialize compiled code entries to null.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000402 re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
403 JSRegExp::IRREGEXP,
404 pattern,
405 flags,
406 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000407}
408
409
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000410int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
411 Handle<String> subject) {
412 if (!subject->IsFlat()) {
413 FlattenString(subject);
414 }
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000415 // Check the asciiness of the underlying storage.
416 bool is_ascii;
417 {
418 AssertNoAllocation no_gc;
419 String* sequential_string = *subject;
420 if (subject->IsConsString()) {
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000421 sequential_string = ConsString::cast(*subject)->first();
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000422 }
423 is_ascii = sequential_string->IsAsciiRepresentation();
424 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000425 if (!EnsureCompiledIrregexp(regexp, is_ascii)) {
426 return -1;
427 }
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000428#ifdef V8_INTERPRETED_REGEXP
429 // Byte-code regexp needs space allocated for all its registers.
430 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data()));
431#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000432 // Native regexp only needs room to output captures. Registers are handled
433 // internally.
434 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000435#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000436}
437
438
erik.corry@gmail.com145eff52010-08-23 11:36:18 +0000439RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(
440 Handle<JSRegExp> regexp,
441 Handle<String> subject,
442 int index,
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000443 Vector<int> output) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000444 Isolate* isolate = regexp->GetIsolate();
445
446 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000447
448 ASSERT(index >= 0);
449 ASSERT(index <= subject->length());
450 ASSERT(subject->IsFlat());
451
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000452 // A flat ASCII string might have a two-byte first part.
453 if (subject->IsConsString()) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000454 subject = Handle<String>(ConsString::cast(*subject)->first(), isolate);
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000455 }
456
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000457#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000458 ASSERT(output.length() >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000459 do {
460 bool is_ascii = subject->IsAsciiRepresentation();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000461 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000462 NativeRegExpMacroAssembler::Result res =
463 NativeRegExpMacroAssembler::Match(code,
464 subject,
465 output.start(),
466 output.length(),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000467 index,
468 isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000469 if (res != NativeRegExpMacroAssembler::RETRY) {
470 ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION ||
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000471 isolate->has_pending_exception());
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000472 STATIC_ASSERT(
473 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
474 STATIC_ASSERT(
475 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
476 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
477 == RE_EXCEPTION);
478 return static_cast<IrregexpResult>(res);
479 }
480 // If result is RETRY, the string has changed representation, and we
481 // must restart from scratch.
482 // In this case, it means we must make sure we are prepared to handle
lrn@chromium.org32d961d2010-06-30 09:09:34 +0000483 // the, potentially, different subject (the string can switch between
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000484 // being internal and external, and even between being ASCII and UC16,
485 // but the characters are always the same).
486 IrregexpPrepare(regexp, subject);
487 } while (true);
488 UNREACHABLE();
489 return RE_EXCEPTION;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000490#else // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000491
492 ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp));
493 bool is_ascii = subject->IsAsciiRepresentation();
494 // We must have done EnsureCompiledIrregexp, so we can get the number of
495 // registers.
496 int* register_vector = output.start();
497 int number_of_capture_registers =
498 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
499 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
500 register_vector[i] = -1;
501 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000502 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii), isolate);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000503
504 if (IrregexpInterpreter::Match(byte_codes,
505 subject,
506 register_vector,
507 index)) {
508 return RE_SUCCESS;
509 }
510 return RE_FAILURE;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000511#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000512}
513
514
ager@chromium.org41826e72009-03-30 13:30:57 +0000515Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000516 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000517 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000518 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000519 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000520
ager@chromium.org8bb60582008-12-11 12:02:20 +0000521 // Prepare space for the return values.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000522#ifdef V8_INTERPRETED_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000523#ifdef DEBUG
524 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000525 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000526 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
527 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
528 }
529#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000530#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000531 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
532 if (required_registers < 0) {
533 // Compiling failed with an exception.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000534 ASSERT(Isolate::Current()->has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000535 return Handle<Object>::null();
536 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000537
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000538 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000539
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000540 IrregexpResult res = RegExpImpl::IrregexpExecOnce(
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000541 jsregexp, subject, previous_index, Vector<int>(registers.vector(),
542 registers.length()));
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000543 if (res == RE_SUCCESS) {
544 int capture_register_count =
545 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
546 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
547 AssertNoAllocation no_gc;
548 int* register_vector = registers.vector();
549 FixedArray* array = FixedArray::cast(last_match_info->elements());
550 for (int i = 0; i < capture_register_count; i += 2) {
551 SetCapture(array, i, register_vector[i]);
552 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000553 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000554 SetLastCaptureCount(array, capture_register_count);
555 SetLastSubject(array, *subject);
556 SetLastInput(array, *subject);
557 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000558 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000559 if (res == RE_EXCEPTION) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000560 ASSERT(Isolate::Current()->has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000561 return Handle<Object>::null();
562 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000563 ASSERT(res == RE_FAILURE);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000564 return Isolate::Current()->factory()->null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000565}
566
567
568// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000569// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000570//
571// The Irregexp regular expression engine is intended to be a complete
572// implementation of ECMAScript regular expressions. It generates either
573// bytecodes or native code.
574
575// The Irregexp regexp engine is structured in three steps.
576// 1) The parser generates an abstract syntax tree. See ast.cc.
577// 2) From the AST a node network is created. The nodes are all
578// subclasses of RegExpNode. The nodes represent states when
579// executing a regular expression. Several optimizations are
580// performed on the node network.
581// 3) From the nodes we generate either byte codes or native code
582// that can actually execute the regular expression (perform
583// the search). The code generation step is described in more
584// detail below.
585
586// Code generation.
587//
588// The nodes are divided into four main categories.
589// * Choice nodes
590// These represent places where the regular expression can
591// match in more than one way. For example on entry to an
592// alternation (foo|bar) or a repetition (*, +, ? or {}).
593// * Action nodes
594// These represent places where some action should be
595// performed. Examples include recording the current position
596// in the input string to a register (in order to implement
597// captures) or other actions on register for example in order
598// to implement the counters needed for {} repetitions.
599// * Matching nodes
600// These attempt to match some element part of the input string.
601// Examples of elements include character classes, plain strings
602// or back references.
603// * End nodes
604// These are used to implement the actions required on finding
605// a successful match or failing to find a match.
606//
607// The code generated (whether as byte codes or native code) maintains
608// some state as it runs. This consists of the following elements:
609//
610// * The capture registers. Used for string captures.
611// * Other registers. Used for counters etc.
612// * The current position.
613// * The stack of backtracking information. Used when a matching node
614// fails to find a match and needs to try an alternative.
615//
616// Conceptual regular expression execution model:
617//
618// There is a simple conceptual model of regular expression execution
619// which will be presented first. The actual code generated is a more
620// efficient simulation of the simple conceptual model:
621//
622// * Choice nodes are implemented as follows:
623// For each choice except the last {
624// push current position
625// push backtrack code location
626// <generate code to test for choice>
627// backtrack code location:
628// pop current position
629// }
630// <generate code to test for last choice>
631//
632// * Actions nodes are generated as follows
633// <push affected registers on backtrack stack>
634// <generate code to perform action>
635// push backtrack code location
636// <generate code to test for following nodes>
637// backtrack code location:
638// <pop affected registers to restore their state>
639// <pop backtrack location from stack and go to it>
640//
641// * Matching nodes are generated as follows:
642// if input string matches at current position
643// update current position
644// <generate code to test for following nodes>
645// else
646// <pop backtrack location from stack and go to it>
647//
648// Thus it can be seen that the current position is saved and restored
649// by the choice nodes, whereas the registers are saved and restored by
650// by the action nodes that manipulate them.
651//
652// The other interesting aspect of this model is that nodes are generated
653// at the point where they are needed by a recursive call to Emit(). If
654// the node has already been code generated then the Emit() call will
655// generate a jump to the previously generated code instead. In order to
656// limit recursion it is possible for the Emit() function to put the node
657// on a work list for later generation and instead generate a jump. The
658// destination of the jump is resolved later when the code is generated.
659//
660// Actual regular expression code generation.
661//
662// Code generation is actually more complicated than the above. In order
663// to improve the efficiency of the generated code some optimizations are
664// performed
665//
666// * Choice nodes have 1-character lookahead.
667// A choice node looks at the following character and eliminates some of
668// the choices immediately based on that character. This is not yet
669// implemented.
670// * Simple greedy loops store reduced backtracking information.
671// A quantifier like /.*foo/m will greedily match the whole input. It will
672// then need to backtrack to a point where it can match "foo". The naive
673// implementation of this would push each character position onto the
674// backtracking stack, then pop them off one by one. This would use space
675// proportional to the length of the input string. However since the "."
676// can only match in one way and always has a constant length (in this case
677// of 1) it suffices to store the current position on the top of the stack
678// once. Matching now becomes merely incrementing the current position and
679// backtracking becomes decrementing the current position and checking the
680// result against the stored current position. This is faster and saves
681// space.
682// * The current state is virtualized.
683// This is used to defer expensive operations until it is clear that they
684// are needed and to generate code for a node more than once, allowing
685// specialized an efficient versions of the code to be created. This is
686// explained in the section below.
687//
688// Execution state virtualization.
689//
690// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000691// manipulation in an object called the Trace. The Trace object can record a
692// current position offset, an optional backtrack code location on the top of
693// the virtualized backtrack stack and some register changes. When a node is
694// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000695// will emit code to bring the actual state into line with the virtual state.
696// Avoiding flushing the state can postpone some work (eg updates of capture
697// registers). Postponing work can save time when executing the regular
698// expression since it may be found that the work never has to be done as a
699// failure to match can occur. In addition it is much faster to jump to a
700// known backtrack code location than it is to pop an unknown backtrack
701// location from the stack and jump there.
702//
ager@chromium.org32912102009-01-16 10:38:43 +0000703// The virtual state found in the Trace affects code generation. For example
704// the virtual state contains the difference between the actual current
705// position and the virtual current position, and matching code needs to use
706// this offset to attempt a match in the correct location of the input
707// string. Therefore code generated for a non-trivial trace is specialized
708// to that trace. The code generator therefore has the ability to generate
709// code for each node several times. In order to limit the size of the
710// generated code there is an arbitrary limit on how many specialized sets of
711// code may be generated for a given node. If the limit is reached, the
712// trace is flushed and a generic version of the code for a node is emitted.
713// This is subsequently used for that node. The code emitted for non-generic
714// trace is not recorded in the node and so it cannot currently be reused in
715// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000716
717
718void RegExpTree::AppendToText(RegExpText* text) {
719 UNREACHABLE();
720}
721
722
723void RegExpAtom::AppendToText(RegExpText* text) {
724 text->AddElement(TextElement::Atom(this));
725}
726
727
728void RegExpCharacterClass::AppendToText(RegExpText* text) {
729 text->AddElement(TextElement::CharClass(this));
730}
731
732
733void RegExpText::AppendToText(RegExpText* text) {
734 for (int i = 0; i < elements()->length(); i++)
735 text->AddElement(elements()->at(i));
736}
737
738
739TextElement TextElement::Atom(RegExpAtom* atom) {
740 TextElement result = TextElement(ATOM);
741 result.data.u_atom = atom;
742 return result;
743}
744
745
746TextElement TextElement::CharClass(
747 RegExpCharacterClass* char_class) {
748 TextElement result = TextElement(CHAR_CLASS);
749 result.data.u_char_class = char_class;
750 return result;
751}
752
753
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000754int TextElement::length() {
755 if (type == ATOM) {
756 return data.u_atom->length();
757 } else {
758 ASSERT(type == CHAR_CLASS);
759 return 1;
760 }
761}
762
763
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000764DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
765 if (table_ == NULL) {
766 table_ = new DispatchTable();
767 DispatchTableConstructor cons(table_, ignore_case);
768 cons.BuildTable(this);
769 }
770 return table_;
771}
772
773
774class RegExpCompiler {
775 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000776 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000777
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000778 int AllocateRegister() {
779 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
780 reg_exp_too_big_ = true;
781 return next_register_;
782 }
783 return next_register_++;
784 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000785
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000786 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
787 RegExpNode* start,
788 int capture_count,
789 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000790
791 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
792
793 static const int kImplementationOffset = 0;
794 static const int kNumberOfRegistersOffset = 0;
795 static const int kCodeOffset = 1;
796
797 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
798 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000799
800 static const int kMaxRecursion = 100;
801 inline int recursion_depth() { return recursion_depth_; }
802 inline void IncrementRecursionDepth() { recursion_depth_++; }
803 inline void DecrementRecursionDepth() { recursion_depth_--; }
804
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000805 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
806
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000807 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000808 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000809
ager@chromium.org32912102009-01-16 10:38:43 +0000810 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000811 private:
812 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000813 int next_register_;
814 List<RegExpNode*>* work_list_;
815 int recursion_depth_;
816 RegExpMacroAssembler* macro_assembler_;
817 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000818 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000819 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000820};
821
822
823class RecursionCheck {
824 public:
825 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
826 compiler->IncrementRecursionDepth();
827 }
828 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
829 private:
830 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000831};
832
833
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000834static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
835 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000836}
837
838
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000839// Attempts to compile the regexp using an Irregexp code generator. Returns
840// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000841RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000842 : next_register_(2 * (capture_count + 1)),
843 work_list_(NULL),
844 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000845 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000846 ascii_(ascii),
847 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000848 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000849 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000850}
851
852
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000853RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000854 RegExpMacroAssembler* macro_assembler,
855 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000856 int capture_count,
857 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000858#ifdef DEBUG
859 if (FLAG_trace_regexp_assembler)
860 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
861 else
862#endif
863 macro_assembler_ = macro_assembler;
864 List <RegExpNode*> work_list(0);
865 work_list_ = &work_list;
866 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000867 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000868 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000869 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000870 macro_assembler_->Bind(&fail);
871 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000872 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000873 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000874 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000875 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
876
ager@chromium.org8bb60582008-12-11 12:02:20 +0000877 Handle<Object> code = macro_assembler_->GetCode(pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000878 work_list_ = NULL;
879#ifdef DEBUG
danno@chromium.org4d3fe4e2011-03-10 10:14:28 +0000880 if (FLAG_print_code) {
881 Handle<Code>::cast(code)->Disassemble(*pattern->ToCString());
882 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000883 if (FLAG_trace_regexp_assembler) {
884 delete macro_assembler_;
885 }
886#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000887 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000888}
889
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000890
ager@chromium.org32912102009-01-16 10:38:43 +0000891bool Trace::DeferredAction::Mentions(int that) {
892 if (type() == ActionNode::CLEAR_CAPTURES) {
893 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
894 return range.Contains(that);
895 } else {
896 return reg() == that;
897 }
898}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000899
ager@chromium.org32912102009-01-16 10:38:43 +0000900
901bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000902 for (DeferredAction* action = actions_;
903 action != NULL;
904 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000905 if (action->Mentions(reg))
906 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000907 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000908 return false;
909}
910
911
ager@chromium.org32912102009-01-16 10:38:43 +0000912bool Trace::GetStoredPosition(int reg, int* cp_offset) {
913 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000914 for (DeferredAction* action = actions_;
915 action != NULL;
916 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000917 if (action->Mentions(reg)) {
918 if (action->type() == ActionNode::STORE_POSITION) {
919 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
920 return true;
921 } else {
922 return false;
923 }
924 }
925 }
926 return false;
927}
928
929
930int Trace::FindAffectedRegisters(OutSet* affected_registers) {
931 int max_register = RegExpCompiler::kNoRegister;
932 for (DeferredAction* action = actions_;
933 action != NULL;
934 action = action->next()) {
935 if (action->type() == ActionNode::CLEAR_CAPTURES) {
936 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
937 for (int i = range.from(); i <= range.to(); i++)
938 affected_registers->Set(i);
939 if (range.to() > max_register) max_register = range.to();
940 } else {
941 affected_registers->Set(action->reg());
942 if (action->reg() > max_register) max_register = action->reg();
943 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000944 }
945 return max_register;
946}
947
948
ager@chromium.org32912102009-01-16 10:38:43 +0000949void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
950 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000951 OutSet& registers_to_pop,
952 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000953 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000954 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
955 else if (registers_to_clear.Get(reg)) {
956 int clear_to = reg;
957 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
958 reg--;
959 }
960 assembler->ClearRegisters(reg, clear_to);
961 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000962 }
963}
964
965
ager@chromium.org32912102009-01-16 10:38:43 +0000966void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
967 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000968 OutSet& affected_registers,
969 OutSet* registers_to_pop,
970 OutSet* registers_to_clear) {
971 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
972 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
973
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000974 // Count pushes performed to force a stack limit check occasionally.
975 int pushes = 0;
976
ager@chromium.org8bb60582008-12-11 12:02:20 +0000977 for (int reg = 0; reg <= max_register; reg++) {
978 if (!affected_registers.Get(reg)) {
979 continue;
980 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000981
982 // The chronologically first deferred action in the trace
983 // is used to infer the action needed to restore a register
984 // to its previous state (or not, if it's safe to ignore it).
985 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
986 DeferredActionUndoType undo_action = IGNORE;
987
ager@chromium.org8bb60582008-12-11 12:02:20 +0000988 int value = 0;
989 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000990 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000991 int store_position = -1;
992 // This is a little tricky because we are scanning the actions in reverse
993 // historical order (newest first).
994 for (DeferredAction* action = actions_;
995 action != NULL;
996 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000997 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000998 switch (action->type()) {
999 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00001000 Trace::DeferredSetRegister* psr =
1001 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001002 if (!absolute) {
1003 value += psr->value();
1004 absolute = true;
1005 }
1006 // SET_REGISTER is currently only used for newly introduced loop
1007 // counters. They can have a significant previous value if they
1008 // occour in a loop. TODO(lrn): Propagate this information, so
1009 // we can set undo_action to IGNORE if we know there is no value to
1010 // restore.
1011 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001012 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001013 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001014 break;
1015 }
1016 case ActionNode::INCREMENT_REGISTER:
1017 if (!absolute) {
1018 value++;
1019 }
1020 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001021 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001022 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001023 break;
1024 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00001025 Trace::DeferredCapture* pc =
1026 static_cast<Trace::DeferredCapture*>(action);
1027 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001028 store_position = pc->cp_offset();
1029 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001030
1031 // For captures we know that stores and clears alternate.
1032 // Other register, are never cleared, and if the occur
1033 // inside a loop, they might be assigned more than once.
1034 if (reg <= 1) {
1035 // Registers zero and one, aka "capture zero", is
1036 // always set correctly if we succeed. There is no
1037 // need to undo a setting on backtrack, because we
1038 // will set it again or fail.
1039 undo_action = IGNORE;
1040 } else {
1041 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1042 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001043 ASSERT(!absolute);
1044 ASSERT_EQ(value, 0);
1045 break;
1046 }
ager@chromium.org32912102009-01-16 10:38:43 +00001047 case ActionNode::CLEAR_CAPTURES: {
1048 // Since we're scanning in reverse order, if we've already
1049 // set the position we have to ignore historically earlier
1050 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001051 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +00001052 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001053 }
1054 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +00001055 ASSERT(!absolute);
1056 ASSERT_EQ(value, 0);
1057 break;
1058 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001059 default:
1060 UNREACHABLE();
1061 break;
1062 }
1063 }
1064 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001065 // Prepare for the undo-action (e.g., push if it's going to be popped).
1066 if (undo_action == RESTORE) {
1067 pushes++;
1068 RegExpMacroAssembler::StackCheckFlag stack_check =
1069 RegExpMacroAssembler::kNoStackLimitCheck;
1070 if (pushes == push_limit) {
1071 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1072 pushes = 0;
1073 }
1074
1075 assembler->PushRegister(reg, stack_check);
1076 registers_to_pop->Set(reg);
1077 } else if (undo_action == CLEAR) {
1078 registers_to_clear->Set(reg);
1079 }
1080 // Perform the chronologically last action (or accumulated increment)
1081 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001082 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001083 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001084 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001085 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001086 } else if (absolute) {
1087 assembler->SetRegister(reg, value);
1088 } else if (value != 0) {
1089 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001090 }
1091 }
1092}
1093
1094
ager@chromium.org8bb60582008-12-11 12:02:20 +00001095// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001096// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001097// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001098void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001099 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001100
iposva@chromium.org245aa852009-02-10 00:49:54 +00001101 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001102
1103 if (actions_ == NULL && backtrack() == NULL) {
1104 // 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 +00001105 // a normal situation. We may also have to forget some information gained
1106 // through a quick check that was already performed.
1107 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001108 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001109 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001110 successor->Emit(compiler, &new_state);
1111 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001112 }
1113
1114 // Generate deferred actions here along with code to undo them again.
1115 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001116
ager@chromium.org381abbb2009-02-25 13:23:22 +00001117 if (backtrack() != NULL) {
1118 // Here we have a concrete backtrack location. These are set up by choice
1119 // nodes and so they indicate that we have a deferred save of the current
1120 // position which we may need to emit here.
1121 assembler->PushCurrentPosition();
1122 }
1123
ager@chromium.org8bb60582008-12-11 12:02:20 +00001124 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001125 OutSet registers_to_pop;
1126 OutSet registers_to_clear;
1127 PerformDeferredActions(assembler,
1128 max_register,
1129 affected_registers,
1130 &registers_to_pop,
1131 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001132 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001133 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001134 }
1135
1136 // Create a new trivial state and generate the node with that.
1137 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001138 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001139 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001140 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001141
1142 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001143 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001144 RestoreAffectedRegisters(assembler,
1145 max_register,
1146 registers_to_pop,
1147 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001148 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001149 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001150 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001151 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001152 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001153 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001154}
1155
1156
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001157void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001158 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001159
1160 // Omit flushing the trace. We discard the entire stack frame anyway.
1161
ager@chromium.org8bb60582008-12-11 12:02:20 +00001162 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001163 // We are completely independent of the trace, since we ignore it,
1164 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001165 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001166 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001167
1168 // Throw away everything on the backtrack stack since the start
1169 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001170 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1171 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001172 if (clear_capture_count_ > 0) {
1173 // Clear any captures that might have been performed during the success
1174 // of the body of the negative look-ahead.
1175 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1176 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1177 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001178 // Now that we have unwound the stack we find at the top of the stack the
1179 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001180 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001181}
1182
1183
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001184void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001185 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001186 trace->Flush(compiler, this);
1187 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001188 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001189 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001190 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001191 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001192 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001193 switch (action_) {
1194 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001195 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001196 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001197 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001198 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001199 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001200 case NEGATIVE_SUBMATCH_SUCCESS:
1201 // This case is handled in a different virtual method.
1202 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001203 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001204 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001205}
1206
1207
1208void GuardedAlternative::AddGuard(Guard* guard) {
1209 if (guards_ == NULL)
1210 guards_ = new ZoneList<Guard*>(1);
1211 guards_->Add(guard);
1212}
1213
1214
ager@chromium.org8bb60582008-12-11 12:02:20 +00001215ActionNode* ActionNode::SetRegister(int reg,
1216 int val,
1217 RegExpNode* on_success) {
1218 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001219 result->data_.u_store_register.reg = reg;
1220 result->data_.u_store_register.value = val;
1221 return result;
1222}
1223
1224
1225ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1226 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1227 result->data_.u_increment_register.reg = reg;
1228 return result;
1229}
1230
1231
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001232ActionNode* ActionNode::StorePosition(int reg,
1233 bool is_capture,
1234 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001235 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1236 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001237 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001238 return result;
1239}
1240
1241
ager@chromium.org32912102009-01-16 10:38:43 +00001242ActionNode* ActionNode::ClearCaptures(Interval range,
1243 RegExpNode* on_success) {
1244 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1245 result->data_.u_clear_captures.range_from = range.from();
1246 result->data_.u_clear_captures.range_to = range.to();
1247 return result;
1248}
1249
1250
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001251ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1252 int position_reg,
1253 RegExpNode* on_success) {
1254 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1255 result->data_.u_submatch.stack_pointer_register = stack_reg;
1256 result->data_.u_submatch.current_position_register = position_reg;
1257 return result;
1258}
1259
1260
ager@chromium.org8bb60582008-12-11 12:02:20 +00001261ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1262 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001263 int clear_register_count,
1264 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001265 RegExpNode* on_success) {
1266 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001267 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001268 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001269 result->data_.u_submatch.clear_register_count = clear_register_count;
1270 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001271 return result;
1272}
1273
1274
ager@chromium.org32912102009-01-16 10:38:43 +00001275ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1276 int repetition_register,
1277 int repetition_limit,
1278 RegExpNode* on_success) {
1279 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1280 result->data_.u_empty_match_check.start_register = start_register;
1281 result->data_.u_empty_match_check.repetition_register = repetition_register;
1282 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1283 return result;
1284}
1285
1286
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001287#define DEFINE_ACCEPT(Type) \
1288 void Type##Node::Accept(NodeVisitor* visitor) { \
1289 visitor->Visit##Type(this); \
1290 }
1291FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1292#undef DEFINE_ACCEPT
1293
1294
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001295void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1296 visitor->VisitLoopChoice(this);
1297}
1298
1299
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001300// -------------------------------------------------------------------
1301// Emit code.
1302
1303
1304void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1305 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001306 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001307 switch (guard->op()) {
1308 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001309 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001310 macro_assembler->IfRegisterGE(guard->reg(),
1311 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001312 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001313 break;
1314 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001315 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001316 macro_assembler->IfRegisterLT(guard->reg(),
1317 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001318 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001319 break;
1320 }
1321}
1322
1323
ager@chromium.org381abbb2009-02-25 13:23:22 +00001324// Returns the number of characters in the equivalence class, omitting those
1325// that cannot occur in the source string because it is ASCII.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001326static int GetCaseIndependentLetters(Isolate* isolate,
1327 uc16 character,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001328 bool ascii_subject,
1329 unibrow::uchar* letters) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001330 int length =
1331 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00001332 // Unibrow returns 0 or 1 for characters where case independence is
ager@chromium.org381abbb2009-02-25 13:23:22 +00001333 // trivial.
1334 if (length == 0) {
1335 letters[0] = character;
1336 length = 1;
1337 }
1338 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1339 return length;
1340 }
1341 // The standard requires that non-ASCII characters cannot have ASCII
1342 // character codes in their equivalence class.
1343 return 0;
1344}
1345
1346
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001347static inline bool EmitSimpleCharacter(Isolate* isolate,
1348 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001349 uc16 c,
1350 Label* on_failure,
1351 int cp_offset,
1352 bool check,
1353 bool preloaded) {
1354 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1355 bool bound_checked = false;
1356 if (!preloaded) {
1357 assembler->LoadCurrentCharacter(
1358 cp_offset,
1359 on_failure,
1360 check);
1361 bound_checked = true;
1362 }
1363 assembler->CheckNotCharacter(c, on_failure);
1364 return bound_checked;
1365}
1366
1367
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001368// Only emits non-letters (things that don't have case). Only used for case
1369// independent matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001370static inline bool EmitAtomNonLetter(Isolate* isolate,
1371 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001372 uc16 c,
1373 Label* on_failure,
1374 int cp_offset,
1375 bool check,
1376 bool preloaded) {
1377 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1378 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001379 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001380 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001381 if (length < 1) {
1382 // This can't match. Must be an ASCII subject and a non-ASCII character.
1383 // We do not need to do anything since the ASCII pass already handled this.
1384 return false; // Bounds not checked.
1385 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001386 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001387 // We handle the length > 1 case in a later pass.
1388 if (length == 1) {
1389 if (ascii && c > String::kMaxAsciiCharCodeU) {
1390 // Can't match - see above.
1391 return false; // Bounds not checked.
1392 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001393 if (!preloaded) {
1394 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1395 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001396 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001397 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001398 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001399 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001400}
1401
1402
1403static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001404 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001405 uc16 c1,
1406 uc16 c2,
1407 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001408 uc16 char_mask;
1409 if (ascii) {
1410 char_mask = String::kMaxAsciiCharCode;
1411 } else {
1412 char_mask = String::kMaxUC16CharCode;
1413 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001414 uc16 exor = c1 ^ c2;
1415 // Check whether exor has only one bit set.
1416 if (((exor - 1) & exor) == 0) {
1417 // If c1 and c2 differ only by one bit.
1418 // Ecma262UnCanonicalize always gives the highest number last.
1419 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001420 uc16 mask = char_mask ^ exor;
1421 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001422 return true;
1423 }
1424 ASSERT(c2 > c1);
1425 uc16 diff = c2 - c1;
1426 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1427 // If the characters differ by 2^n but don't differ by one bit then
1428 // subtract the difference from the found character, then do the or
1429 // trick. We avoid the theoretical case where negative numbers are
1430 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001431 uc16 mask = char_mask ^ diff;
1432 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1433 diff,
1434 mask,
1435 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001436 return true;
1437 }
1438 return false;
1439}
1440
1441
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001442typedef bool EmitCharacterFunction(Isolate* isolate,
1443 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001444 uc16 c,
1445 Label* on_failure,
1446 int cp_offset,
1447 bool check,
1448 bool preloaded);
1449
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001450// Only emits letters (things that have case). Only used for case independent
1451// matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001452static inline bool EmitAtomLetter(Isolate* isolate,
1453 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001454 uc16 c,
1455 Label* on_failure,
1456 int cp_offset,
1457 bool check,
1458 bool preloaded) {
1459 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1460 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001461 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001462 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001463 if (length <= 1) return false;
1464 // We may not need to check against the end of the input string
1465 // if this character lies before a character that matched.
1466 if (!preloaded) {
1467 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001468 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001469 Label ok;
1470 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1471 switch (length) {
1472 case 2: {
1473 if (ShortCutEmitCharacterPair(macro_assembler,
1474 ascii,
1475 chars[0],
1476 chars[1],
1477 on_failure)) {
1478 } else {
1479 macro_assembler->CheckCharacter(chars[0], &ok);
1480 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1481 macro_assembler->Bind(&ok);
1482 }
1483 break;
1484 }
1485 case 4:
1486 macro_assembler->CheckCharacter(chars[3], &ok);
1487 // Fall through!
1488 case 3:
1489 macro_assembler->CheckCharacter(chars[0], &ok);
1490 macro_assembler->CheckCharacter(chars[1], &ok);
1491 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1492 macro_assembler->Bind(&ok);
1493 break;
1494 default:
1495 UNREACHABLE();
1496 break;
1497 }
1498 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001499}
1500
1501
1502static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1503 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001504 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001505 Label* on_failure,
1506 int cp_offset,
1507 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001508 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001509 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001510 int max_char;
1511 if (ascii) {
1512 max_char = String::kMaxAsciiCharCode;
1513 } else {
1514 max_char = String::kMaxUC16CharCode;
1515 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001516
1517 Label success;
1518
1519 Label* char_is_in_class =
1520 cc->is_negated() ? on_failure : &success;
1521
1522 int range_count = ranges->length();
1523
ager@chromium.org8bb60582008-12-11 12:02:20 +00001524 int last_valid_range = range_count - 1;
1525 while (last_valid_range >= 0) {
1526 CharacterRange& range = ranges->at(last_valid_range);
1527 if (range.from() <= max_char) {
1528 break;
1529 }
1530 last_valid_range--;
1531 }
1532
1533 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001534 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001535 // TODO(plesner): We can remove this when the node level does our
1536 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001537 macro_assembler->GoTo(on_failure);
1538 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001539 if (check_offset) {
1540 macro_assembler->CheckPosition(cp_offset, on_failure);
1541 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001542 return;
1543 }
1544
ager@chromium.org8bb60582008-12-11 12:02:20 +00001545 if (last_valid_range == 0 &&
1546 !cc->is_negated() &&
1547 ranges->at(0).IsEverything(max_char)) {
1548 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001549 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001550 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001551 }
1552 return;
1553 }
1554
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001555 if (!preloaded) {
1556 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001557 }
1558
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001559 if (cc->is_standard() &&
1560 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1561 on_failure)) {
1562 return;
1563 }
1564
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001565 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001566 CharacterRange& range = ranges->at(i);
1567 Label next_range;
1568 uc16 from = range.from();
1569 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001570 if (from > max_char) {
1571 continue;
1572 }
1573 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001574 if (to == from) {
1575 macro_assembler->CheckCharacter(to, char_is_in_class);
1576 } else {
1577 if (from != 0) {
1578 macro_assembler->CheckCharacterLT(from, &next_range);
1579 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001580 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001581 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1582 } else {
1583 macro_assembler->GoTo(char_is_in_class);
1584 }
1585 }
1586 macro_assembler->Bind(&next_range);
1587 }
1588
ager@chromium.org8bb60582008-12-11 12:02:20 +00001589 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001590 uc16 from = range.from();
1591 uc16 to = range.to();
1592
ager@chromium.org8bb60582008-12-11 12:02:20 +00001593 if (to > max_char) to = max_char;
1594 ASSERT(to >= from);
1595
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001596 if (to == from) {
1597 if (cc->is_negated()) {
1598 macro_assembler->CheckCharacter(to, on_failure);
1599 } else {
1600 macro_assembler->CheckNotCharacter(to, on_failure);
1601 }
1602 } else {
1603 if (from != 0) {
1604 if (cc->is_negated()) {
1605 macro_assembler->CheckCharacterLT(from, &success);
1606 } else {
1607 macro_assembler->CheckCharacterLT(from, on_failure);
1608 }
1609 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001610 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001611 if (cc->is_negated()) {
1612 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1613 } else {
1614 macro_assembler->CheckCharacterGT(to, on_failure);
1615 }
1616 } else {
1617 if (cc->is_negated()) {
1618 macro_assembler->GoTo(on_failure);
1619 }
1620 }
1621 }
1622 macro_assembler->Bind(&success);
1623}
1624
1625
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001626RegExpNode::~RegExpNode() {
1627}
1628
1629
ager@chromium.org8bb60582008-12-11 12:02:20 +00001630RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001631 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001632 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001633 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001634 return CONTINUE;
1635 }
1636
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001637 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001638 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001639 if (label_.is_bound()) {
1640 // We are being asked to generate a generic version, but that's already
1641 // been done so just go to it.
1642 macro_assembler->GoTo(&label_);
1643 return DONE;
1644 }
1645 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1646 // To avoid too deep recursion we push the node to the work queue and just
1647 // generate a goto here.
1648 compiler->AddWork(this);
1649 macro_assembler->GoTo(&label_);
1650 return DONE;
1651 }
1652 // Generate generic version of the node and bind the label for later use.
1653 macro_assembler->Bind(&label_);
1654 return CONTINUE;
1655 }
1656
1657 // We are being asked to make a non-generic version. Keep track of how many
1658 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001659 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001660 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001661 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001662 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1663 return CONTINUE;
1664 }
1665
ager@chromium.org32912102009-01-16 10:38:43 +00001666 // If we get here code has been generated for this node too many times or
1667 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001668 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001669 trace->Flush(compiler, this);
1670 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001671}
1672
1673
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001674int ActionNode::EatsAtLeast(int still_to_find,
1675 int recursion_depth,
1676 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001677 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1678 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001679 return on_success()->EatsAtLeast(still_to_find,
1680 recursion_depth + 1,
1681 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001682}
1683
1684
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001685int AssertionNode::EatsAtLeast(int still_to_find,
1686 int recursion_depth,
1687 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001688 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001689 // If we know we are not at the start and we are asked "how many characters
1690 // will you match if you succeed?" then we can answer anything since false
1691 // implies false. So lets just return the max answer (still_to_find) since
1692 // that won't prevent us from preloading a lot of characters for the other
1693 // branches in the node graph.
1694 if (type() == AT_START && not_at_start) return still_to_find;
1695 return on_success()->EatsAtLeast(still_to_find,
1696 recursion_depth + 1,
1697 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001698}
1699
1700
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001701int BackReferenceNode::EatsAtLeast(int still_to_find,
1702 int recursion_depth,
1703 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001704 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001705 return on_success()->EatsAtLeast(still_to_find,
1706 recursion_depth + 1,
1707 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001708}
1709
1710
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001711int TextNode::EatsAtLeast(int still_to_find,
1712 int recursion_depth,
1713 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001714 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001715 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001716 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001717 // We are not at start after this node so we set the last argument to 'true'.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001718 return answer + on_success()->EatsAtLeast(still_to_find - answer,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001719 recursion_depth + 1,
1720 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001721}
1722
1723
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001724int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001725 int recursion_depth,
1726 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001727 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1728 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1729 // afterwards.
1730 RegExpNode* node = alternatives_->at(1).node();
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001731 return node->EatsAtLeast(still_to_find, recursion_depth + 1, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001732}
1733
1734
1735void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1736 QuickCheckDetails* details,
1737 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001738 int filled_in,
1739 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001740 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1741 // afterwards.
1742 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001743 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001744}
1745
1746
1747int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1748 int recursion_depth,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001749 RegExpNode* ignore_this_node,
1750 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001751 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1752 int min = 100;
1753 int choice_count = alternatives_->length();
1754 for (int i = 0; i < choice_count; i++) {
1755 RegExpNode* node = alternatives_->at(i).node();
1756 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001757 int node_eats_at_least = node->EatsAtLeast(still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001758 recursion_depth + 1,
1759 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001760 if (node_eats_at_least < min) min = node_eats_at_least;
1761 }
1762 return min;
1763}
1764
1765
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001766int LoopChoiceNode::EatsAtLeast(int still_to_find,
1767 int recursion_depth,
1768 bool not_at_start) {
1769 return EatsAtLeastHelper(still_to_find,
1770 recursion_depth,
1771 loop_node_,
1772 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001773}
1774
1775
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001776int ChoiceNode::EatsAtLeast(int still_to_find,
1777 int recursion_depth,
1778 bool not_at_start) {
1779 return EatsAtLeastHelper(still_to_find,
1780 recursion_depth,
1781 NULL,
1782 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001783}
1784
1785
1786// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1787static inline uint32_t SmearBitsRight(uint32_t v) {
1788 v |= v >> 1;
1789 v |= v >> 2;
1790 v |= v >> 4;
1791 v |= v >> 8;
1792 v |= v >> 16;
1793 return v;
1794}
1795
1796
1797bool QuickCheckDetails::Rationalize(bool asc) {
1798 bool found_useful_op = false;
1799 uint32_t char_mask;
1800 if (asc) {
1801 char_mask = String::kMaxAsciiCharCode;
1802 } else {
1803 char_mask = String::kMaxUC16CharCode;
1804 }
1805 mask_ = 0;
1806 value_ = 0;
1807 int char_shift = 0;
1808 for (int i = 0; i < characters_; i++) {
1809 Position* pos = &positions_[i];
1810 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1811 found_useful_op = true;
1812 }
1813 mask_ |= (pos->mask & char_mask) << char_shift;
1814 value_ |= (pos->value & char_mask) << char_shift;
1815 char_shift += asc ? 8 : 16;
1816 }
1817 return found_useful_op;
1818}
1819
1820
1821bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001822 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001823 bool preload_has_checked_bounds,
1824 Label* on_possible_success,
1825 QuickCheckDetails* details,
1826 bool fall_through_on_failure) {
1827 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001828 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1829 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001830 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001831 ASSERT(details->characters() == 1 ||
1832 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001833 uint32_t mask = details->mask();
1834 uint32_t value = details->value();
1835
1836 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1837
ager@chromium.org32912102009-01-16 10:38:43 +00001838 if (trace->characters_preloaded() != details->characters()) {
1839 assembler->LoadCurrentCharacter(trace->cp_offset(),
1840 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001841 !preload_has_checked_bounds,
1842 details->characters());
1843 }
1844
1845
1846 bool need_mask = true;
1847
1848 if (details->characters() == 1) {
1849 // If number of characters preloaded is 1 then we used a byte or 16 bit
1850 // load so the value is already masked down.
1851 uint32_t char_mask;
1852 if (compiler->ascii()) {
1853 char_mask = String::kMaxAsciiCharCode;
1854 } else {
1855 char_mask = String::kMaxUC16CharCode;
1856 }
1857 if ((mask & char_mask) == char_mask) need_mask = false;
1858 mask &= char_mask;
1859 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001860 // For 2-character preloads in ASCII mode or 1-character preloads in
1861 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001862 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001863 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1864 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001865 if ((mask & 0xffff) == 0xffff) need_mask = false;
1866 } else {
1867 if (mask == 0xffffffff) need_mask = false;
1868 }
1869 }
1870
1871 if (fall_through_on_failure) {
1872 if (need_mask) {
1873 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1874 } else {
1875 assembler->CheckCharacter(value, on_possible_success);
1876 }
1877 } else {
1878 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001879 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001880 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001881 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001882 }
1883 }
1884 return true;
1885}
1886
1887
1888// Here is the meat of GetQuickCheckDetails (see also the comment on the
1889// super-class in the .h file).
1890//
1891// We iterate along the text object, building up for each character a
1892// mask and value that can be used to test for a quick failure to match.
1893// The masks and values for the positions will be combined into a single
1894// machine word for the current character width in order to be used in
1895// generating a quick check.
1896void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1897 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001898 int characters_filled_in,
1899 bool not_at_start) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001900 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001901 ASSERT(characters_filled_in < details->characters());
1902 int characters = details->characters();
1903 int char_mask;
1904 int char_shift;
1905 if (compiler->ascii()) {
1906 char_mask = String::kMaxAsciiCharCode;
1907 char_shift = 8;
1908 } else {
1909 char_mask = String::kMaxUC16CharCode;
1910 char_shift = 16;
1911 }
1912 for (int k = 0; k < elms_->length(); k++) {
1913 TextElement elm = elms_->at(k);
1914 if (elm.type == TextElement::ATOM) {
1915 Vector<const uc16> quarks = elm.data.u_atom->data();
1916 for (int i = 0; i < characters && i < quarks.length(); i++) {
1917 QuickCheckDetails::Position* pos =
1918 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001919 uc16 c = quarks[i];
1920 if (c > char_mask) {
1921 // If we expect a non-ASCII character from an ASCII string,
1922 // there is no way we can match. Not even case independent
1923 // matching can turn an ASCII character into non-ASCII or
1924 // vice versa.
1925 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001926 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001927 return;
1928 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001929 if (compiler->ignore_case()) {
1930 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001931 int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
1932 chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001933 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1934 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001935 // This letter has no case equivalents, so it's nice and simple
1936 // and the mask-compare will determine definitely whether we have
1937 // a match at this character position.
1938 pos->mask = char_mask;
1939 pos->value = c;
1940 pos->determines_perfectly = true;
1941 } else {
1942 uint32_t common_bits = char_mask;
1943 uint32_t bits = chars[0];
1944 for (int j = 1; j < length; j++) {
1945 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1946 common_bits ^= differing_bits;
1947 bits &= common_bits;
1948 }
1949 // If length is 2 and common bits has only one zero in it then
1950 // our mask and compare instruction will determine definitely
1951 // whether we have a match at this character position. Otherwise
1952 // it can only be an approximate check.
1953 uint32_t one_zero = (common_bits | ~char_mask);
1954 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1955 pos->determines_perfectly = true;
1956 }
1957 pos->mask = common_bits;
1958 pos->value = bits;
1959 }
1960 } else {
1961 // Don't ignore case. Nice simple case where the mask-compare will
1962 // determine definitely whether we have a match at this character
1963 // position.
1964 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001965 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001966 pos->determines_perfectly = true;
1967 }
1968 characters_filled_in++;
1969 ASSERT(characters_filled_in <= details->characters());
1970 if (characters_filled_in == details->characters()) {
1971 return;
1972 }
1973 }
1974 } else {
1975 QuickCheckDetails::Position* pos =
1976 details->positions(characters_filled_in);
1977 RegExpCharacterClass* tree = elm.data.u_char_class;
1978 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001979 if (tree->is_negated()) {
1980 // A quick check uses multi-character mask and compare. There is no
1981 // useful way to incorporate a negative char class into this scheme
1982 // so we just conservatively create a mask and value that will always
1983 // succeed.
1984 pos->mask = 0;
1985 pos->value = 0;
1986 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001987 int first_range = 0;
1988 while (ranges->at(first_range).from() > char_mask) {
1989 first_range++;
1990 if (first_range == ranges->length()) {
1991 details->set_cannot_match();
1992 pos->determines_perfectly = false;
1993 return;
1994 }
1995 }
1996 CharacterRange range = ranges->at(first_range);
1997 uc16 from = range.from();
1998 uc16 to = range.to();
1999 if (to > char_mask) {
2000 to = char_mask;
2001 }
2002 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002003 // A mask and compare is only perfect if the differing bits form a
2004 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002005 if ((differing_bits & (differing_bits + 1)) == 0 &&
2006 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002007 pos->determines_perfectly = true;
2008 }
2009 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002010 uint32_t bits = (from & common_bits);
2011 for (int i = first_range + 1; i < ranges->length(); i++) {
2012 CharacterRange range = ranges->at(i);
2013 uc16 from = range.from();
2014 uc16 to = range.to();
2015 if (from > char_mask) continue;
2016 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002017 // Here we are combining more ranges into the mask and compare
2018 // value. With each new range the mask becomes more sparse and
2019 // so the chances of a false positive rise. A character class
2020 // with multiple ranges is assumed never to be equivalent to a
2021 // mask and compare operation.
2022 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002023 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002024 new_common_bits = ~SmearBitsRight(new_common_bits);
2025 common_bits &= new_common_bits;
2026 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002027 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002028 common_bits ^= differing_bits;
2029 bits &= common_bits;
2030 }
2031 pos->mask = common_bits;
2032 pos->value = bits;
2033 }
2034 characters_filled_in++;
2035 ASSERT(characters_filled_in <= details->characters());
2036 if (characters_filled_in == details->characters()) {
2037 return;
2038 }
2039 }
2040 }
2041 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00002042 on_success()-> GetQuickCheckDetails(details,
2043 compiler,
2044 characters_filled_in,
2045 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002046}
2047
2048
2049void QuickCheckDetails::Clear() {
2050 for (int i = 0; i < characters_; i++) {
2051 positions_[i].mask = 0;
2052 positions_[i].value = 0;
2053 positions_[i].determines_perfectly = false;
2054 }
2055 characters_ = 0;
2056}
2057
2058
2059void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002060 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002061 if (by >= characters_) {
2062 Clear();
2063 return;
2064 }
2065 for (int i = 0; i < characters_ - by; i++) {
2066 positions_[i] = positions_[by + i];
2067 }
2068 for (int i = characters_ - by; i < characters_; i++) {
2069 positions_[i].mask = 0;
2070 positions_[i].value = 0;
2071 positions_[i].determines_perfectly = false;
2072 }
2073 characters_ -= by;
2074 // We could change mask_ and value_ here but we would never advance unless
2075 // they had already been used in a check and they won't be used again because
2076 // it would gain us nothing. So there's no point.
2077}
2078
2079
2080void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2081 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002082 if (other->cannot_match_) {
2083 return;
2084 }
2085 if (cannot_match_) {
2086 *this = *other;
2087 return;
2088 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002089 for (int i = from_index; i < characters_; i++) {
2090 QuickCheckDetails::Position* pos = positions(i);
2091 QuickCheckDetails::Position* other_pos = other->positions(i);
2092 if (pos->mask != other_pos->mask ||
2093 pos->value != other_pos->value ||
2094 !other_pos->determines_perfectly) {
2095 // Our mask-compare operation will be approximate unless we have the
2096 // exact same operation on both sides of the alternation.
2097 pos->determines_perfectly = false;
2098 }
2099 pos->mask &= other_pos->mask;
2100 pos->value &= pos->mask;
2101 other_pos->value &= pos->mask;
2102 uc16 differing_bits = (pos->value ^ other_pos->value);
2103 pos->mask &= ~differing_bits;
2104 pos->value &= pos->mask;
2105 }
2106}
2107
2108
ager@chromium.org32912102009-01-16 10:38:43 +00002109class VisitMarker {
2110 public:
2111 explicit VisitMarker(NodeInfo* info) : info_(info) {
2112 ASSERT(!info->visited);
2113 info->visited = true;
2114 }
2115 ~VisitMarker() {
2116 info_->visited = false;
2117 }
2118 private:
2119 NodeInfo* info_;
2120};
2121
2122
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002123void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2124 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002125 int characters_filled_in,
2126 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002127 if (body_can_be_zero_length_ || info()->visited) return;
2128 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002129 return ChoiceNode::GetQuickCheckDetails(details,
2130 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002131 characters_filled_in,
2132 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002133}
2134
2135
2136void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2137 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002138 int characters_filled_in,
2139 bool not_at_start) {
2140 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002141 int choice_count = alternatives_->length();
2142 ASSERT(choice_count > 0);
2143 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2144 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002145 characters_filled_in,
2146 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002147 for (int i = 1; i < choice_count; i++) {
2148 QuickCheckDetails new_details(details->characters());
2149 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002150 node->GetQuickCheckDetails(&new_details, compiler,
2151 characters_filled_in,
2152 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002153 // Here we merge the quick match details of the two branches.
2154 details->Merge(&new_details, characters_filled_in);
2155 }
2156}
2157
2158
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002159// Check for [0-9A-Z_a-z].
2160static void EmitWordCheck(RegExpMacroAssembler* assembler,
2161 Label* word,
2162 Label* non_word,
2163 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002164 if (assembler->CheckSpecialCharacterClass(
2165 fall_through_on_word ? 'w' : 'W',
2166 fall_through_on_word ? non_word : word)) {
2167 // Optimized implementation available.
2168 return;
2169 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002170 assembler->CheckCharacterGT('z', non_word);
2171 assembler->CheckCharacterLT('0', non_word);
2172 assembler->CheckCharacterGT('a' - 1, word);
2173 assembler->CheckCharacterLT('9' + 1, word);
2174 assembler->CheckCharacterLT('A', non_word);
2175 assembler->CheckCharacterLT('Z' + 1, word);
2176 if (fall_through_on_word) {
2177 assembler->CheckNotCharacter('_', non_word);
2178 } else {
2179 assembler->CheckCharacter('_', word);
2180 }
2181}
2182
2183
2184// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2185// that matches newline or the start of input).
2186static void EmitHat(RegExpCompiler* compiler,
2187 RegExpNode* on_success,
2188 Trace* trace) {
2189 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2190 // We will be loading the previous character into the current character
2191 // register.
2192 Trace new_trace(*trace);
2193 new_trace.InvalidateCurrentCharacter();
2194
2195 Label ok;
2196 if (new_trace.cp_offset() == 0) {
2197 // The start of input counts as a newline in this context, so skip to
2198 // ok if we are at the start.
2199 assembler->CheckAtStart(&ok);
2200 }
2201 // We already checked that we are not at the start of input so it must be
2202 // OK to load the previous character.
2203 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2204 new_trace.backtrack(),
2205 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002206 if (!assembler->CheckSpecialCharacterClass('n',
2207 new_trace.backtrack())) {
2208 // Newline means \n, \r, 0x2028 or 0x2029.
2209 if (!compiler->ascii()) {
2210 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2211 }
2212 assembler->CheckCharacter('\n', &ok);
2213 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002214 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002215 assembler->Bind(&ok);
2216 on_success->Emit(compiler, &new_trace);
2217}
2218
2219
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002220// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2221// when we know whether the next character must be a word character or not.
2222static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2223 RegExpCompiler* compiler,
2224 RegExpNode* on_success,
2225 Trace* trace) {
2226 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2227 Label done;
2228
2229 Trace new_trace(*trace);
2230
2231 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2232 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2233 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2234
2235 // Check whether previous character was a word character.
2236 switch (trace->at_start()) {
2237 case Trace::TRUE:
2238 if (expect_word_character) {
2239 assembler->GoTo(on_non_word);
2240 }
2241 break;
2242 case Trace::UNKNOWN:
2243 ASSERT_EQ(0, trace->cp_offset());
2244 assembler->CheckAtStart(on_non_word);
2245 // Fall through.
2246 case Trace::FALSE:
2247 int prev_char_offset = trace->cp_offset() - 1;
2248 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2249 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2250 // We may or may not have loaded the previous character.
2251 new_trace.InvalidateCurrentCharacter();
2252 }
2253
2254 assembler->Bind(&done);
2255
2256 on_success->Emit(compiler, &new_trace);
2257}
2258
2259
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002260// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2261static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2262 RegExpCompiler* compiler,
2263 RegExpNode* on_success,
2264 Trace* trace) {
2265 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2266 Label before_non_word;
2267 Label before_word;
2268 if (trace->characters_preloaded() != 1) {
2269 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2270 }
2271 // Fall through on non-word.
2272 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2273
2274 // We will be loading the previous character into the current character
2275 // register.
2276 Trace new_trace(*trace);
2277 new_trace.InvalidateCurrentCharacter();
2278
2279 Label ok;
2280 Label* boundary;
2281 Label* not_boundary;
2282 if (type == AssertionNode::AT_BOUNDARY) {
2283 boundary = &ok;
2284 not_boundary = new_trace.backtrack();
2285 } else {
2286 not_boundary = &ok;
2287 boundary = new_trace.backtrack();
2288 }
2289
2290 // Next character is not a word character.
2291 assembler->Bind(&before_non_word);
2292 if (new_trace.cp_offset() == 0) {
2293 // The start of input counts as a non-word character, so the question is
2294 // decided if we are at the start.
2295 assembler->CheckAtStart(not_boundary);
2296 }
2297 // We already checked that we are not at the start of input so it must be
2298 // OK to load the previous character.
2299 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2300 &ok, // Unused dummy label in this call.
2301 false);
2302 // Fall through on non-word.
2303 EmitWordCheck(assembler, boundary, not_boundary, false);
2304 assembler->GoTo(not_boundary);
2305
2306 // Next character is a word character.
2307 assembler->Bind(&before_word);
2308 if (new_trace.cp_offset() == 0) {
2309 // The start of input counts as a non-word character, so the question is
2310 // decided if we are at the start.
2311 assembler->CheckAtStart(boundary);
2312 }
2313 // We already checked that we are not at the start of input so it must be
2314 // OK to load the previous character.
2315 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2316 &ok, // Unused dummy label in this call.
2317 false);
2318 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2319 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2320
2321 assembler->Bind(&ok);
2322
2323 on_success->Emit(compiler, &new_trace);
2324}
2325
2326
iposva@chromium.org245aa852009-02-10 00:49:54 +00002327void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2328 RegExpCompiler* compiler,
2329 int filled_in,
2330 bool not_at_start) {
2331 if (type_ == AT_START && not_at_start) {
2332 details->set_cannot_match();
2333 return;
2334 }
2335 return on_success()->GetQuickCheckDetails(details,
2336 compiler,
2337 filled_in,
2338 not_at_start);
2339}
2340
2341
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002342void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2343 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2344 switch (type_) {
2345 case AT_END: {
2346 Label ok;
2347 assembler->CheckPosition(trace->cp_offset(), &ok);
2348 assembler->GoTo(trace->backtrack());
2349 assembler->Bind(&ok);
2350 break;
2351 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002352 case AT_START: {
2353 if (trace->at_start() == Trace::FALSE) {
2354 assembler->GoTo(trace->backtrack());
2355 return;
2356 }
2357 if (trace->at_start() == Trace::UNKNOWN) {
2358 assembler->CheckNotAtStart(trace->backtrack());
2359 Trace at_start_trace = *trace;
2360 at_start_trace.set_at_start(true);
2361 on_success()->Emit(compiler, &at_start_trace);
2362 return;
2363 }
2364 }
2365 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002366 case AFTER_NEWLINE:
2367 EmitHat(compiler, on_success(), trace);
2368 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002369 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002370 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002371 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2372 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002373 }
2374 case AFTER_WORD_CHARACTER:
2375 case AFTER_NONWORD_CHARACTER: {
2376 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2377 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002378 }
2379 on_success()->Emit(compiler, trace);
2380}
2381
2382
ager@chromium.org381abbb2009-02-25 13:23:22 +00002383static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2384 if (quick_check == NULL) return false;
2385 if (offset >= quick_check->characters()) return false;
2386 return quick_check->positions(offset)->determines_perfectly;
2387}
2388
2389
2390static void UpdateBoundsCheck(int index, int* checked_up_to) {
2391 if (index > *checked_up_to) {
2392 *checked_up_to = index;
2393 }
2394}
2395
2396
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002397// We call this repeatedly to generate code for each pass over the text node.
2398// The passes are in increasing order of difficulty because we hope one
2399// of the first passes will fail in which case we are saved the work of the
2400// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2401// we will check the '%' in the first pass, the case independent 'a' in the
2402// second pass and the character class in the last pass.
2403//
2404// The passes are done from right to left, so for example to test for /bar/
2405// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2406// and then a 'b' with offset 0. This means we can avoid the end-of-input
2407// bounds check most of the time. In the example we only need to check for
2408// end-of-input when loading the putative 'r'.
2409//
2410// A slight complication involves the fact that the first character may already
2411// be fetched into a register by the previous node. In this case we want to
2412// do the test for that character first. We do this in separate passes. The
2413// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2414// pass has been performed then subsequent passes will have true in
2415// first_element_checked to indicate that that character does not need to be
2416// checked again.
2417//
ager@chromium.org32912102009-01-16 10:38:43 +00002418// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002419// contain an AlternativeGeneration object. In this AlternativeGeneration
2420// object we can see details of any quick check that was already passed in
2421// order to get to the code we are now generating. The quick check can involve
2422// loading characters, which means we do not need to recheck the bounds
2423// up to the limit the quick check already checked. In addition the quick
2424// check can have involved a mask and compare operation which may simplify
2425// or obviate the need for further checks at some character positions.
2426void TextNode::TextEmitPass(RegExpCompiler* compiler,
2427 TextEmitPassType pass,
2428 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002429 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002430 bool first_element_checked,
2431 int* checked_up_to) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002432 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002433 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2434 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002435 Label* backtrack = trace->backtrack();
2436 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002437 int element_count = elms_->length();
2438 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2439 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002440 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002441 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002442 Vector<const uc16> quarks = elm.data.u_atom->data();
2443 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2444 if (first_element_checked && i == 0 && j == 0) continue;
2445 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2446 EmitCharacterFunction* emit_function = NULL;
2447 switch (pass) {
2448 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002449 ASSERT(ascii);
2450 if (quarks[j] > String::kMaxAsciiCharCode) {
2451 assembler->GoTo(backtrack);
2452 return;
2453 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002454 break;
2455 case NON_LETTER_CHARACTER_MATCH:
2456 emit_function = &EmitAtomNonLetter;
2457 break;
2458 case SIMPLE_CHARACTER_MATCH:
2459 emit_function = &EmitSimpleCharacter;
2460 break;
2461 case CASE_CHARACTER_MATCH:
2462 emit_function = &EmitAtomLetter;
2463 break;
2464 default:
2465 break;
2466 }
2467 if (emit_function != NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002468 bool bound_checked = emit_function(isolate,
2469 compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002470 quarks[j],
2471 backtrack,
2472 cp_offset + j,
2473 *checked_up_to < cp_offset + j,
2474 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002475 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002476 }
2477 }
2478 } else {
2479 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002480 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002481 if (first_element_checked && i == 0) continue;
2482 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002483 RegExpCharacterClass* cc = elm.data.u_char_class;
2484 EmitCharClass(assembler,
2485 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002486 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002487 backtrack,
2488 cp_offset,
2489 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002490 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002491 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002492 }
2493 }
2494 }
2495}
2496
2497
2498int TextNode::Length() {
2499 TextElement elm = elms_->last();
2500 ASSERT(elm.cp_offset >= 0);
2501 if (elm.type == TextElement::ATOM) {
2502 return elm.cp_offset + elm.data.u_atom->data().length();
2503 } else {
2504 return elm.cp_offset + 1;
2505 }
2506}
2507
2508
ager@chromium.org381abbb2009-02-25 13:23:22 +00002509bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2510 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2511 if (ignore_case) {
2512 return pass == SIMPLE_CHARACTER_MATCH;
2513 } else {
2514 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2515 }
2516}
2517
2518
ager@chromium.org8bb60582008-12-11 12:02:20 +00002519// This generates the code to match a text node. A text node can contain
2520// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002521// way) and character classes. For efficiency we do not do this in a single
2522// pass from left to right. Instead we pass over the text node several times,
2523// emitting code for some character positions every time. See the comment on
2524// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002525void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002526 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002527 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002528 ASSERT(limit_result == CONTINUE);
2529
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002530 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2531 compiler->SetRegExpTooBig();
2532 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002533 }
2534
2535 if (compiler->ascii()) {
2536 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002537 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002538 }
2539
2540 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002541 int bound_checked_to = trace->cp_offset() - 1;
2542 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002543
2544 // If a character is preloaded into the current character register then
2545 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002546 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002547 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2548 if (!SkipPass(pass, compiler->ignore_case())) {
2549 TextEmitPass(compiler,
2550 static_cast<TextEmitPassType>(pass),
2551 true,
2552 trace,
2553 false,
2554 &bound_checked_to);
2555 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002556 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002557 first_elt_done = true;
2558 }
2559
ager@chromium.org381abbb2009-02-25 13:23:22 +00002560 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2561 if (!SkipPass(pass, compiler->ignore_case())) {
2562 TextEmitPass(compiler,
2563 static_cast<TextEmitPassType>(pass),
2564 false,
2565 trace,
2566 first_elt_done,
2567 &bound_checked_to);
2568 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002569 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002570
ager@chromium.org32912102009-01-16 10:38:43 +00002571 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002572 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002573 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002574 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002575 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002576}
2577
2578
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002579void Trace::InvalidateCurrentCharacter() {
2580 characters_preloaded_ = 0;
2581}
2582
2583
2584void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002585 ASSERT(by > 0);
2586 // We don't have an instruction for shifting the current character register
2587 // down or for using a shifted value for anything so lets just forget that
2588 // we preloaded any characters into it.
2589 characters_preloaded_ = 0;
2590 // Adjust the offsets of the quick check performed information. This
2591 // information is used to find out what we already determined about the
2592 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002593 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002594 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002595 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2596 compiler->SetRegExpTooBig();
2597 cp_offset_ = 0;
2598 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002599 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002600}
2601
2602
ager@chromium.org38e4c712009-11-11 09:11:58 +00002603void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002604 int element_count = elms_->length();
2605 for (int i = 0; i < element_count; i++) {
2606 TextElement elm = elms_->at(i);
2607 if (elm.type == TextElement::CHAR_CLASS) {
2608 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002609 // None of the standard character classses is different in the case
2610 // independent case and it slows us down if we don't know that.
2611 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002612 ZoneList<CharacterRange>* ranges = cc->ranges();
2613 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002614 for (int j = 0; j < range_count; j++) {
2615 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002616 }
2617 }
2618 }
2619}
2620
2621
ager@chromium.org8bb60582008-12-11 12:02:20 +00002622int TextNode::GreedyLoopTextLength() {
2623 TextElement elm = elms_->at(elms_->length() - 1);
2624 if (elm.type == TextElement::CHAR_CLASS) {
2625 return elm.cp_offset + 1;
2626 } else {
2627 return elm.cp_offset + elm.data.u_atom->data().length();
2628 }
2629}
2630
2631
2632// Finds the fixed match length of a sequence of nodes that goes from
2633// this alternative and back to this choice node. If there are variable
2634// length nodes or other complications in the way then return a sentinel
2635// value indicating that a greedy loop cannot be constructed.
2636int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2637 int length = 0;
2638 RegExpNode* node = alternative->node();
2639 // Later we will generate code for all these text nodes using recursion
2640 // so we have to limit the max number.
2641 int recursion_depth = 0;
2642 while (node != this) {
2643 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2644 return kNodeIsTooComplexForGreedyLoops;
2645 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002646 int node_length = node->GreedyLoopTextLength();
2647 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2648 return kNodeIsTooComplexForGreedyLoops;
2649 }
2650 length += node_length;
2651 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2652 node = seq_node->on_success();
2653 }
2654 return length;
2655}
2656
2657
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002658void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2659 ASSERT_EQ(loop_node_, NULL);
2660 AddAlternative(alt);
2661 loop_node_ = alt.node();
2662}
2663
2664
2665void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2666 ASSERT_EQ(continue_node_, NULL);
2667 AddAlternative(alt);
2668 continue_node_ = alt.node();
2669}
2670
2671
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002672void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002673 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002674 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002675 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2676 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2677 // Update the counter-based backtracking info on the stack. This is an
2678 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002679 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002680 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002681 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002682 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002683 }
ager@chromium.org32912102009-01-16 10:38:43 +00002684 ASSERT(trace->stop_node() == NULL);
2685 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002686 trace->Flush(compiler, this);
2687 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002688 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002689 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002690}
2691
2692
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002693int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
2694 bool not_at_start) {
2695 int preload_characters = EatsAtLeast(4, 0, not_at_start);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002696 if (compiler->macro_assembler()->CanReadUnaligned()) {
2697 bool ascii = compiler->ascii();
2698 if (ascii) {
2699 if (preload_characters > 4) preload_characters = 4;
2700 // We can't preload 3 characters because there is no machine instruction
2701 // to do that. We can't just load 4 because we could be reading
2702 // beyond the end of the string, which could cause a memory fault.
2703 if (preload_characters == 3) preload_characters = 2;
2704 } else {
2705 if (preload_characters > 2) preload_characters = 2;
2706 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002707 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002708 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002709 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002710 return preload_characters;
2711}
2712
2713
2714// This class is used when generating the alternatives in a choice node. It
2715// records the way the alternative is being code generated.
2716class AlternativeGeneration: public Malloced {
2717 public:
2718 AlternativeGeneration()
2719 : possible_success(),
2720 expects_preload(false),
2721 after(),
2722 quick_check_details() { }
2723 Label possible_success;
2724 bool expects_preload;
2725 Label after;
2726 QuickCheckDetails quick_check_details;
2727};
2728
2729
2730// Creates a list of AlternativeGenerations. If the list has a reasonable
2731// size then it is on the stack, otherwise the excess is on the heap.
2732class AlternativeGenerationList {
2733 public:
2734 explicit AlternativeGenerationList(int count)
2735 : alt_gens_(count) {
2736 for (int i = 0; i < count && i < kAFew; i++) {
2737 alt_gens_.Add(a_few_alt_gens_ + i);
2738 }
2739 for (int i = kAFew; i < count; i++) {
2740 alt_gens_.Add(new AlternativeGeneration());
2741 }
2742 }
2743 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002744 for (int i = kAFew; i < alt_gens_.length(); i++) {
2745 delete alt_gens_[i];
2746 alt_gens_[i] = NULL;
2747 }
2748 }
2749
2750 AlternativeGeneration* at(int i) {
2751 return alt_gens_[i];
2752 }
2753 private:
2754 static const int kAFew = 10;
2755 ZoneList<AlternativeGeneration*> alt_gens_;
2756 AlternativeGeneration a_few_alt_gens_[kAFew];
2757};
2758
2759
2760/* Code generation for choice nodes.
2761 *
2762 * We generate quick checks that do a mask and compare to eliminate a
2763 * choice. If the quick check succeeds then it jumps to the continuation to
2764 * do slow checks and check subsequent nodes. If it fails (the common case)
2765 * it falls through to the next choice.
2766 *
2767 * Here is the desired flow graph. Nodes directly below each other imply
2768 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2769 * 3 doesn't have a quick check so we have to call the slow check.
2770 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2771 * regexp continuation is generated directly after the Sn node, up to the
2772 * next GoTo if we decide to reuse some already generated code. Some
2773 * nodes expect preload_characters to be preloaded into the current
2774 * character register. R nodes do this preloading. Vertices are marked
2775 * F for failures and S for success (possible success in the case of quick
2776 * nodes). L, V, < and > are used as arrow heads.
2777 *
2778 * ----------> R
2779 * |
2780 * V
2781 * Q1 -----> S1
2782 * | S /
2783 * F| /
2784 * | F/
2785 * | /
2786 * | R
2787 * | /
2788 * V L
2789 * Q2 -----> S2
2790 * | S /
2791 * F| /
2792 * | F/
2793 * | /
2794 * | R
2795 * | /
2796 * V L
2797 * S3
2798 * |
2799 * F|
2800 * |
2801 * R
2802 * |
2803 * backtrack V
2804 * <----------Q4
2805 * \ F |
2806 * \ |S
2807 * \ F V
2808 * \-----S4
2809 *
2810 * For greedy loops we reverse our expectation and expect to match rather
2811 * than fail. Therefore we want the loop code to look like this (U is the
2812 * unwind code that steps back in the greedy loop). The following alternatives
2813 * look the same as above.
2814 * _____
2815 * / \
2816 * V |
2817 * ----------> S1 |
2818 * /| |
2819 * / |S |
2820 * F/ \_____/
2821 * /
2822 * |<-----------
2823 * | \
2824 * V \
2825 * Q2 ---> S2 \
2826 * | S / |
2827 * F| / |
2828 * | F/ |
2829 * | / |
2830 * | R |
2831 * | / |
2832 * F VL |
2833 * <------U |
2834 * back |S |
2835 * \______________/
2836 */
2837
2838
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002839void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002840 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2841 int choice_count = alternatives_->length();
2842#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002843 for (int i = 0; i < choice_count - 1; i++) {
2844 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002845 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002846 int guard_count = (guards == NULL) ? 0 : guards->length();
2847 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002848 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002849 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002850 }
2851#endif
2852
ager@chromium.org32912102009-01-16 10:38:43 +00002853 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002854 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002855 ASSERT(limit_result == CONTINUE);
2856
ager@chromium.org381abbb2009-02-25 13:23:22 +00002857 int new_flush_budget = trace->flush_budget() / choice_count;
2858 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2859 trace->Flush(compiler, this);
2860 return;
2861 }
2862
ager@chromium.org8bb60582008-12-11 12:02:20 +00002863 RecursionCheck rc(compiler);
2864
ager@chromium.org32912102009-01-16 10:38:43 +00002865 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002866
2867 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2868 bool greedy_loop = false;
2869 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002870 Trace counter_backtrack_trace;
2871 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002872 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2873
ager@chromium.org8bb60582008-12-11 12:02:20 +00002874 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2875 // Here we have special handling for greedy loops containing only text nodes
2876 // and other simple nodes. These are handled by pushing the current
2877 // position on the stack and then incrementing the current position each
2878 // time around the switch. On backtrack we decrement the current position
2879 // and check it against the pushed value. This avoids pushing backtrack
2880 // information for each iteration of the loop, which could take up a lot of
2881 // space.
2882 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002883 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002884 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002885 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002886 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002887 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002888 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002889 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002890 Label loop_label;
2891 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002892 greedy_match_trace.set_stop_node(this);
2893 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002894 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002895 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002896 }
2897
2898 Label second_choice; // For use in greedy matches.
2899 macro_assembler->Bind(&second_choice);
2900
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002901 int first_normal_choice = greedy_loop ? 1 : 0;
2902
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002903 int preload_characters =
2904 CalculatePreloadCharacters(compiler,
2905 current_trace->at_start() == Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002906 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002907 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002908 bool preload_has_checked_bounds = preload_is_current;
2909
2910 AlternativeGenerationList alt_gens(choice_count);
2911
ager@chromium.org8bb60582008-12-11 12:02:20 +00002912 // For now we just call all choices one after the other. The idea ultimately
2913 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002914 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002915 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002916 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002917 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002918 ZoneList<Guard*>* guards = alternative.guards();
2919 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002920 Trace new_trace(*current_trace);
2921 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002922 preload_characters :
2923 0);
2924 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002925 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002926 }
ager@chromium.org32912102009-01-16 10:38:43 +00002927 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002928 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002929 alt_gen->expects_preload = preload_is_current;
2930 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002931 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002932 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002933 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002934 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002935 preload_has_checked_bounds,
2936 &alt_gen->possible_success,
2937 &alt_gen->quick_check_details,
2938 i < choice_count - 1)) {
2939 // Quick check was generated for this choice.
2940 preload_is_current = true;
2941 preload_has_checked_bounds = true;
2942 // On the last choice in the ChoiceNode we generated the quick
2943 // check to fall through on possible success. So now we need to
2944 // generate the full check inline.
2945 if (i == choice_count - 1) {
2946 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002947 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2948 new_trace.set_characters_preloaded(preload_characters);
2949 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002950 generate_full_check_inline = true;
2951 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002952 } else if (alt_gen->quick_check_details.cannot_match()) {
2953 if (i == choice_count - 1 && !greedy_loop) {
2954 macro_assembler->GoTo(trace->backtrack());
2955 }
2956 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002957 } else {
2958 // No quick check was generated. Put the full code here.
2959 // If this is not the first choice then there could be slow checks from
2960 // previous cases that go here when they fail. There's no reason to
2961 // insist that they preload characters since the slow check we are about
2962 // to generate probably can't use it.
2963 if (i != first_normal_choice) {
2964 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002965 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002966 }
2967 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002968 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002969 }
2970 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002971 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002972 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002973 if (new_trace.actions() != NULL) {
2974 new_trace.set_flush_budget(new_flush_budget);
2975 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002976 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002977 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002978 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002979 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002980 preload_is_current = false;
2981 }
2982 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002983 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002984 if (greedy_loop) {
2985 macro_assembler->Bind(&greedy_loop_label);
2986 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002987 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002988 // Otherwise try the second priority at an earlier position.
2989 macro_assembler->AdvanceCurrentPosition(-text_length);
2990 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002991 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002992
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002993 // At this point we need to generate slow checks for the alternatives where
2994 // the quick check was inlined. We can recognize these because the associated
2995 // label was bound.
2996 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2997 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002998 Trace new_trace(*current_trace);
2999 // If there are actions to be flushed we have to limit how many times
3000 // they are flushed. Take the budget of the parent trace and distribute
3001 // it fairly amongst the children.
3002 if (new_trace.actions() != NULL) {
3003 new_trace.set_flush_budget(new_flush_budget);
3004 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003005 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00003006 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003007 alternatives_->at(i),
3008 alt_gen,
3009 preload_characters,
3010 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003011 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003012}
3013
3014
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003015void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00003016 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003017 GuardedAlternative alternative,
3018 AlternativeGeneration* alt_gen,
3019 int preload_characters,
3020 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003021 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003022
3023 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3024 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00003025 Trace out_of_line_trace(*trace);
3026 out_of_line_trace.set_characters_preloaded(preload_characters);
3027 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003028 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003029 ZoneList<Guard*>* guards = alternative.guards();
3030 int guard_count = (guards == NULL) ? 0 : guards->length();
3031 if (next_expects_preload) {
3032 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00003033 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003034 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003035 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003036 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003037 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003038 macro_assembler->Bind(&reload_current_char);
3039 // Reload the current character, since the next quick check expects that.
3040 // We don't need to check bounds here because we only get into this
3041 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00003042 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003043 NULL,
3044 false,
3045 preload_characters);
3046 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003047 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00003048 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003049 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003050 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003051 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003052 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003053 }
3054}
3055
3056
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003057void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003058 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003059 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003060 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003061 ASSERT(limit_result == CONTINUE);
3062
3063 RecursionCheck rc(compiler);
3064
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003065 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003066 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00003067 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003068 new_capture(data_.u_position_register.reg,
3069 data_.u_position_register.is_capture,
3070 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003071 Trace new_trace = *trace;
3072 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003073 on_success()->Emit(compiler, &new_trace);
3074 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003075 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003076 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003077 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003078 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00003079 Trace new_trace = *trace;
3080 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003081 on_success()->Emit(compiler, &new_trace);
3082 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003083 }
3084 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003085 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003086 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00003087 Trace new_trace = *trace;
3088 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003089 on_success()->Emit(compiler, &new_trace);
3090 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003091 }
3092 case CLEAR_CAPTURES: {
3093 Trace::DeferredClearCaptures
3094 new_capture(Interval(data_.u_clear_captures.range_from,
3095 data_.u_clear_captures.range_to));
3096 Trace new_trace = *trace;
3097 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003098 on_success()->Emit(compiler, &new_trace);
3099 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003100 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003101 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003102 if (!trace->is_trivial()) {
3103 trace->Flush(compiler, this);
3104 } else {
3105 assembler->WriteCurrentPositionToRegister(
3106 data_.u_submatch.current_position_register, 0);
3107 assembler->WriteStackPointerToRegister(
3108 data_.u_submatch.stack_pointer_register);
3109 on_success()->Emit(compiler, trace);
3110 }
3111 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003112 case EMPTY_MATCH_CHECK: {
3113 int start_pos_reg = data_.u_empty_match_check.start_register;
3114 int stored_pos = 0;
3115 int rep_reg = data_.u_empty_match_check.repetition_register;
3116 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3117 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3118 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3119 // If we know we haven't advanced and there is no minimum we
3120 // can just backtrack immediately.
3121 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003122 } else if (know_dist && stored_pos < trace->cp_offset()) {
3123 // If we know we've advanced we can generate the continuation
3124 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003125 on_success()->Emit(compiler, trace);
3126 } else if (!trace->is_trivial()) {
3127 trace->Flush(compiler, this);
3128 } else {
3129 Label skip_empty_check;
3130 // If we have a minimum number of repetitions we check the current
3131 // number first and skip the empty check if it's not enough.
3132 if (has_minimum) {
3133 int limit = data_.u_empty_match_check.repetition_limit;
3134 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3135 }
3136 // If the match is empty we bail out, otherwise we fall through
3137 // to the on-success continuation.
3138 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3139 trace->backtrack());
3140 assembler->Bind(&skip_empty_check);
3141 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003142 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003143 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003144 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003145 case POSITIVE_SUBMATCH_SUCCESS: {
3146 if (!trace->is_trivial()) {
3147 trace->Flush(compiler, this);
3148 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003149 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003150 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003151 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003152 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003153 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003154 int clear_register_count = data_.u_submatch.clear_register_count;
3155 if (clear_register_count == 0) {
3156 on_success()->Emit(compiler, trace);
3157 return;
3158 }
3159 int clear_registers_from = data_.u_submatch.clear_register_from;
3160 Label clear_registers_backtrack;
3161 Trace new_trace = *trace;
3162 new_trace.set_backtrack(&clear_registers_backtrack);
3163 on_success()->Emit(compiler, &new_trace);
3164
3165 assembler->Bind(&clear_registers_backtrack);
3166 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3167 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3168
3169 ASSERT(trace->backtrack() == NULL);
3170 assembler->Backtrack();
3171 return;
3172 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003173 default:
3174 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003175 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003176}
3177
3178
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003179void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003180 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003181 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003182 trace->Flush(compiler, this);
3183 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003184 }
3185
ager@chromium.org32912102009-01-16 10:38:43 +00003186 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003187 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003188 ASSERT(limit_result == CONTINUE);
3189
3190 RecursionCheck rc(compiler);
3191
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003192 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003193 if (compiler->ignore_case()) {
3194 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3195 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003196 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003197 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003198 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003199 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003200}
3201
3202
3203// -------------------------------------------------------------------
3204// Dot/dotty output
3205
3206
3207#ifdef DEBUG
3208
3209
3210class DotPrinter: public NodeVisitor {
3211 public:
3212 explicit DotPrinter(bool ignore_case)
3213 : ignore_case_(ignore_case),
3214 stream_(&alloc_) { }
3215 void PrintNode(const char* label, RegExpNode* node);
3216 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003217 void PrintAttributes(RegExpNode* from);
3218 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003219 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003220#define DECLARE_VISIT(Type) \
3221 virtual void Visit##Type(Type##Node* that);
3222FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3223#undef DECLARE_VISIT
3224 private:
3225 bool ignore_case_;
3226 HeapStringAllocator alloc_;
3227 StringStream stream_;
3228};
3229
3230
3231void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3232 stream()->Add("digraph G {\n graph [label=\"");
3233 for (int i = 0; label[i]; i++) {
3234 switch (label[i]) {
3235 case '\\':
3236 stream()->Add("\\\\");
3237 break;
3238 case '"':
3239 stream()->Add("\"");
3240 break;
3241 default:
3242 stream()->Put(label[i]);
3243 break;
3244 }
3245 }
3246 stream()->Add("\"];\n");
3247 Visit(node);
3248 stream()->Add("}\n");
3249 printf("%s", *(stream()->ToCString()));
3250}
3251
3252
3253void DotPrinter::Visit(RegExpNode* node) {
3254 if (node->info()->visited) return;
3255 node->info()->visited = true;
3256 node->Accept(this);
3257}
3258
3259
3260void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003261 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3262 Visit(on_failure);
3263}
3264
3265
3266class TableEntryBodyPrinter {
3267 public:
3268 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3269 : stream_(stream), choice_(choice) { }
3270 void Call(uc16 from, DispatchTable::Entry entry) {
3271 OutSet* out_set = entry.out_set();
3272 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3273 if (out_set->Get(i)) {
3274 stream()->Add(" n%p:s%io%i -> n%p;\n",
3275 choice(),
3276 from,
3277 i,
3278 choice()->alternatives()->at(i).node());
3279 }
3280 }
3281 }
3282 private:
3283 StringStream* stream() { return stream_; }
3284 ChoiceNode* choice() { return choice_; }
3285 StringStream* stream_;
3286 ChoiceNode* choice_;
3287};
3288
3289
3290class TableEntryHeaderPrinter {
3291 public:
3292 explicit TableEntryHeaderPrinter(StringStream* stream)
3293 : first_(true), stream_(stream) { }
3294 void Call(uc16 from, DispatchTable::Entry entry) {
3295 if (first_) {
3296 first_ = false;
3297 } else {
3298 stream()->Add("|");
3299 }
3300 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3301 OutSet* out_set = entry.out_set();
3302 int priority = 0;
3303 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3304 if (out_set->Get(i)) {
3305 if (priority > 0) stream()->Add("|");
3306 stream()->Add("<s%io%i> %i", from, i, priority);
3307 priority++;
3308 }
3309 }
3310 stream()->Add("}}");
3311 }
3312 private:
3313 bool first_;
3314 StringStream* stream() { return stream_; }
3315 StringStream* stream_;
3316};
3317
3318
3319class AttributePrinter {
3320 public:
3321 explicit AttributePrinter(DotPrinter* out)
3322 : out_(out), first_(true) { }
3323 void PrintSeparator() {
3324 if (first_) {
3325 first_ = false;
3326 } else {
3327 out_->stream()->Add("|");
3328 }
3329 }
3330 void PrintBit(const char* name, bool value) {
3331 if (!value) return;
3332 PrintSeparator();
3333 out_->stream()->Add("{%s}", name);
3334 }
3335 void PrintPositive(const char* name, int value) {
3336 if (value < 0) return;
3337 PrintSeparator();
3338 out_->stream()->Add("{%s|%x}", name, value);
3339 }
3340 private:
3341 DotPrinter* out_;
3342 bool first_;
3343};
3344
3345
3346void DotPrinter::PrintAttributes(RegExpNode* that) {
3347 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3348 "margin=0.1, fontsize=10, label=\"{",
3349 that);
3350 AttributePrinter printer(this);
3351 NodeInfo* info = that->info();
3352 printer.PrintBit("NI", info->follows_newline_interest);
3353 printer.PrintBit("WI", info->follows_word_interest);
3354 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003355 Label* label = that->label();
3356 if (label->is_bound())
3357 printer.PrintPositive("@", label->pos());
3358 stream()->Add("}\"];\n");
3359 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3360 "arrowhead=none];\n", that, that);
3361}
3362
3363
3364static const bool kPrintDispatchTable = false;
3365void DotPrinter::VisitChoice(ChoiceNode* that) {
3366 if (kPrintDispatchTable) {
3367 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3368 TableEntryHeaderPrinter header_printer(stream());
3369 that->GetTable(ignore_case_)->ForEach(&header_printer);
3370 stream()->Add("\"]\n", that);
3371 PrintAttributes(that);
3372 TableEntryBodyPrinter body_printer(stream(), that);
3373 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003374 } else {
3375 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3376 for (int i = 0; i < that->alternatives()->length(); i++) {
3377 GuardedAlternative alt = that->alternatives()->at(i);
3378 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3379 }
3380 }
3381 for (int i = 0; i < that->alternatives()->length(); i++) {
3382 GuardedAlternative alt = that->alternatives()->at(i);
3383 alt.node()->Accept(this);
3384 }
3385}
3386
3387
3388void DotPrinter::VisitText(TextNode* that) {
3389 stream()->Add(" n%p [label=\"", that);
3390 for (int i = 0; i < that->elements()->length(); i++) {
3391 if (i > 0) stream()->Add(" ");
3392 TextElement elm = that->elements()->at(i);
3393 switch (elm.type) {
3394 case TextElement::ATOM: {
3395 stream()->Add("'%w'", elm.data.u_atom->data());
3396 break;
3397 }
3398 case TextElement::CHAR_CLASS: {
3399 RegExpCharacterClass* node = elm.data.u_char_class;
3400 stream()->Add("[");
3401 if (node->is_negated())
3402 stream()->Add("^");
3403 for (int j = 0; j < node->ranges()->length(); j++) {
3404 CharacterRange range = node->ranges()->at(j);
3405 stream()->Add("%k-%k", range.from(), range.to());
3406 }
3407 stream()->Add("]");
3408 break;
3409 }
3410 default:
3411 UNREACHABLE();
3412 }
3413 }
3414 stream()->Add("\", shape=box, peripheries=2];\n");
3415 PrintAttributes(that);
3416 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3417 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003418}
3419
3420
3421void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3422 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3423 that,
3424 that->start_register(),
3425 that->end_register());
3426 PrintAttributes(that);
3427 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3428 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003429}
3430
3431
3432void DotPrinter::VisitEnd(EndNode* that) {
3433 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3434 PrintAttributes(that);
3435}
3436
3437
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003438void DotPrinter::VisitAssertion(AssertionNode* that) {
3439 stream()->Add(" n%p [", that);
3440 switch (that->type()) {
3441 case AssertionNode::AT_END:
3442 stream()->Add("label=\"$\", shape=septagon");
3443 break;
3444 case AssertionNode::AT_START:
3445 stream()->Add("label=\"^\", shape=septagon");
3446 break;
3447 case AssertionNode::AT_BOUNDARY:
3448 stream()->Add("label=\"\\b\", shape=septagon");
3449 break;
3450 case AssertionNode::AT_NON_BOUNDARY:
3451 stream()->Add("label=\"\\B\", shape=septagon");
3452 break;
3453 case AssertionNode::AFTER_NEWLINE:
3454 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3455 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003456 case AssertionNode::AFTER_WORD_CHARACTER:
3457 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3458 break;
3459 case AssertionNode::AFTER_NONWORD_CHARACTER:
3460 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3461 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003462 }
3463 stream()->Add("];\n");
3464 PrintAttributes(that);
3465 RegExpNode* successor = that->on_success();
3466 stream()->Add(" n%p -> n%p;\n", that, successor);
3467 Visit(successor);
3468}
3469
3470
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003471void DotPrinter::VisitAction(ActionNode* that) {
3472 stream()->Add(" n%p [", that);
3473 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003474 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003475 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3476 that->data_.u_store_register.reg,
3477 that->data_.u_store_register.value);
3478 break;
3479 case ActionNode::INCREMENT_REGISTER:
3480 stream()->Add("label=\"$%i++\", shape=octagon",
3481 that->data_.u_increment_register.reg);
3482 break;
3483 case ActionNode::STORE_POSITION:
3484 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3485 that->data_.u_position_register.reg);
3486 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003487 case ActionNode::BEGIN_SUBMATCH:
3488 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3489 that->data_.u_submatch.current_position_register);
3490 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003491 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003492 stream()->Add("label=\"escape\", shape=septagon");
3493 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003494 case ActionNode::EMPTY_MATCH_CHECK:
3495 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3496 that->data_.u_empty_match_check.start_register,
3497 that->data_.u_empty_match_check.repetition_register,
3498 that->data_.u_empty_match_check.repetition_limit);
3499 break;
3500 case ActionNode::CLEAR_CAPTURES: {
3501 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3502 that->data_.u_clear_captures.range_from,
3503 that->data_.u_clear_captures.range_to);
3504 break;
3505 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003506 }
3507 stream()->Add("];\n");
3508 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003509 RegExpNode* successor = that->on_success();
3510 stream()->Add(" n%p -> n%p;\n", that, successor);
3511 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003512}
3513
3514
3515class DispatchTableDumper {
3516 public:
3517 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3518 void Call(uc16 key, DispatchTable::Entry entry);
3519 StringStream* stream() { return stream_; }
3520 private:
3521 StringStream* stream_;
3522};
3523
3524
3525void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3526 stream()->Add("[%k-%k]: {", key, entry.to());
3527 OutSet* set = entry.out_set();
3528 bool first = true;
3529 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3530 if (set->Get(i)) {
3531 if (first) {
3532 first = false;
3533 } else {
3534 stream()->Add(", ");
3535 }
3536 stream()->Add("%i", i);
3537 }
3538 }
3539 stream()->Add("}\n");
3540}
3541
3542
3543void DispatchTable::Dump() {
3544 HeapStringAllocator alloc;
3545 StringStream stream(&alloc);
3546 DispatchTableDumper dumper(&stream);
3547 tree()->ForEach(&dumper);
3548 OS::PrintError("%s", *stream.ToCString());
3549}
3550
3551
3552void RegExpEngine::DotPrint(const char* label,
3553 RegExpNode* node,
3554 bool ignore_case) {
3555 DotPrinter printer(ignore_case);
3556 printer.PrintNode(label, node);
3557}
3558
3559
3560#endif // DEBUG
3561
3562
3563// -------------------------------------------------------------------
3564// Tree to graph conversion
3565
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003566static const int kSpaceRangeCount = 20;
3567static const int kSpaceRangeAsciiCount = 4;
3568static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3569 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3570 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3571
3572static const int kWordRangeCount = 8;
3573static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3574 '_', 'a', 'z' };
3575
3576static const int kDigitRangeCount = 2;
3577static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3578
3579static const int kLineTerminatorRangeCount = 6;
3580static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3581 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003582
3583RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003584 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003585 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3586 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003587 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003588}
3589
3590
3591RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003592 RegExpNode* on_success) {
3593 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003594}
3595
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003596static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3597 const uc16* special_class,
3598 int length) {
3599 ASSERT(ranges->length() != 0);
3600 ASSERT(length != 0);
3601 ASSERT(special_class[0] != 0);
3602 if (ranges->length() != (length >> 1) + 1) {
3603 return false;
3604 }
3605 CharacterRange range = ranges->at(0);
3606 if (range.from() != 0) {
3607 return false;
3608 }
3609 for (int i = 0; i < length; i += 2) {
3610 if (special_class[i] != (range.to() + 1)) {
3611 return false;
3612 }
3613 range = ranges->at((i >> 1) + 1);
3614 if (special_class[i+1] != range.from() - 1) {
3615 return false;
3616 }
3617 }
3618 if (range.to() != 0xffff) {
3619 return false;
3620 }
3621 return true;
3622}
3623
3624
3625static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3626 const uc16* special_class,
3627 int length) {
3628 if (ranges->length() * 2 != length) {
3629 return false;
3630 }
3631 for (int i = 0; i < length; i += 2) {
3632 CharacterRange range = ranges->at(i >> 1);
3633 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3634 return false;
3635 }
3636 }
3637 return true;
3638}
3639
3640
3641bool RegExpCharacterClass::is_standard() {
3642 // TODO(lrn): Remove need for this function, by not throwing away information
3643 // along the way.
3644 if (is_negated_) {
3645 return false;
3646 }
3647 if (set_.is_standard()) {
3648 return true;
3649 }
3650 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3651 set_.set_standard_set_type('s');
3652 return true;
3653 }
3654 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3655 set_.set_standard_set_type('S');
3656 return true;
3657 }
3658 if (CompareInverseRanges(set_.ranges(),
3659 kLineTerminatorRanges,
3660 kLineTerminatorRangeCount)) {
3661 set_.set_standard_set_type('.');
3662 return true;
3663 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003664 if (CompareRanges(set_.ranges(),
3665 kLineTerminatorRanges,
3666 kLineTerminatorRangeCount)) {
3667 set_.set_standard_set_type('n');
3668 return true;
3669 }
3670 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3671 set_.set_standard_set_type('w');
3672 return true;
3673 }
3674 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3675 set_.set_standard_set_type('W');
3676 return true;
3677 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003678 return false;
3679}
3680
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003681
3682RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003683 RegExpNode* on_success) {
3684 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003685}
3686
3687
3688RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003689 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003690 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3691 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003692 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003693 for (int i = 0; i < length; i++) {
3694 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003695 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003696 result->AddAlternative(alternative);
3697 }
3698 return result;
3699}
3700
3701
3702RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003703 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003704 return ToNode(min(),
3705 max(),
3706 is_greedy(),
3707 body(),
3708 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003709 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003710}
3711
3712
3713RegExpNode* RegExpQuantifier::ToNode(int min,
3714 int max,
3715 bool is_greedy,
3716 RegExpTree* body,
3717 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003718 RegExpNode* on_success,
3719 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003720 // x{f, t} becomes this:
3721 //
3722 // (r++)<-.
3723 // | `
3724 // | (x)
3725 // v ^
3726 // (r=0)-->(?)---/ [if r < t]
3727 // |
3728 // [if r >= f] \----> ...
3729 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003730
3731 // 15.10.2.5 RepeatMatcher algorithm.
3732 // The parser has already eliminated the case where max is 0. In the case
3733 // where max_match is zero the parser has removed the quantifier if min was
3734 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3735
3736 // If we know that we cannot match zero length then things are a little
3737 // simpler since we don't need to make the special zero length match check
3738 // from step 2.1. If the min and max are small we can unroll a little in
3739 // this case.
3740 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3741 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3742 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003743 bool body_can_be_empty = (body->min_match() == 0);
3744 int body_start_reg = RegExpCompiler::kNoRegister;
3745 Interval capture_registers = body->CaptureRegisters();
3746 bool needs_capture_clearing = !capture_registers.is_empty();
3747 if (body_can_be_empty) {
3748 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003749 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003750 // Only unroll if there are no captures and the body can't be
3751 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003752 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3753 int new_max = (max == kInfinity) ? max : max - min;
3754 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003755 RegExpNode* answer = ToNode(
3756 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003757 // Unroll the forced matches from 0 to min. This can cause chains of
3758 // TextNodes (which the parser does not generate). These should be
3759 // combined if it turns out they hinder good code generation.
3760 for (int i = 0; i < min; i++) {
3761 answer = body->ToNode(compiler, answer);
3762 }
3763 return answer;
3764 }
3765 if (max <= kMaxUnrolledMaxMatches) {
3766 ASSERT(min == 0);
3767 // Unroll the optional matches up to max.
3768 RegExpNode* answer = on_success;
3769 for (int i = 0; i < max; i++) {
3770 ChoiceNode* alternation = new ChoiceNode(2);
3771 if (is_greedy) {
3772 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3773 answer)));
3774 alternation->AddAlternative(GuardedAlternative(on_success));
3775 } else {
3776 alternation->AddAlternative(GuardedAlternative(on_success));
3777 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3778 answer)));
3779 }
3780 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003781 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003782 }
3783 return answer;
3784 }
3785 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003786 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003787 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003788 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003789 int reg_ctr = needs_counter
3790 ? compiler->AllocateRegister()
3791 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003792 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003793 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003794 RegExpNode* loop_return = needs_counter
3795 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3796 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003797 if (body_can_be_empty) {
3798 // If the body can be empty we need to check if it was and then
3799 // backtrack.
3800 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3801 reg_ctr,
3802 min,
3803 loop_return);
3804 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003805 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003806 if (body_can_be_empty) {
3807 // If the body can be empty we need to store the start position
3808 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003809 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003810 }
3811 if (needs_capture_clearing) {
3812 // Before entering the body of this loop we need to clear captures.
3813 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3814 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003815 GuardedAlternative body_alt(body_node);
3816 if (has_max) {
3817 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3818 body_alt.AddGuard(body_guard);
3819 }
3820 GuardedAlternative rest_alt(on_success);
3821 if (has_min) {
3822 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3823 rest_alt.AddGuard(rest_guard);
3824 }
3825 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003826 center->AddLoopAlternative(body_alt);
3827 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003828 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003829 center->AddContinueAlternative(rest_alt);
3830 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003831 }
3832 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003833 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003834 } else {
3835 return center;
3836 }
3837}
3838
3839
3840RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003841 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003842 NodeInfo info;
3843 switch (type()) {
3844 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003845 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003846 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003847 return AssertionNode::AtStart(on_success);
3848 case BOUNDARY:
3849 return AssertionNode::AtBoundary(on_success);
3850 case NON_BOUNDARY:
3851 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003852 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003853 return AssertionNode::AtEnd(on_success);
3854 case END_OF_LINE: {
3855 // Compile $ in multiline regexps as an alternation with a positive
3856 // lookahead in one side and an end-of-input on the other side.
3857 // We need two registers for the lookahead.
3858 int stack_pointer_register = compiler->AllocateRegister();
3859 int position_register = compiler->AllocateRegister();
3860 // The ChoiceNode to distinguish between a newline and end-of-input.
3861 ChoiceNode* result = new ChoiceNode(2);
3862 // Create a newline atom.
3863 ZoneList<CharacterRange>* newline_ranges =
3864 new ZoneList<CharacterRange>(3);
3865 CharacterRange::AddClassEscape('n', newline_ranges);
3866 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3867 TextNode* newline_matcher = new TextNode(
3868 newline_atom,
3869 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3870 position_register,
3871 0, // No captures inside.
3872 -1, // Ignored if no captures.
3873 on_success));
3874 // Create an end-of-input matcher.
3875 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3876 stack_pointer_register,
3877 position_register,
3878 newline_matcher);
3879 // Add the two alternatives to the ChoiceNode.
3880 GuardedAlternative eol_alternative(end_of_line);
3881 result->AddAlternative(eol_alternative);
3882 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3883 result->AddAlternative(end_alternative);
3884 return result;
3885 }
3886 default:
3887 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003888 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003889 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003890}
3891
3892
3893RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003894 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003895 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3896 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003897 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003898}
3899
3900
3901RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003902 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003903 return on_success;
3904}
3905
3906
3907RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003908 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003909 int stack_pointer_register = compiler->AllocateRegister();
3910 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003911
3912 const int registers_per_capture = 2;
3913 const int register_of_first_capture = 2;
3914 int register_count = capture_count_ * registers_per_capture;
3915 int register_start =
3916 register_of_first_capture + capture_from_ * registers_per_capture;
3917
ager@chromium.org8bb60582008-12-11 12:02:20 +00003918 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003919 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003920 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003921 stack_pointer_register,
3922 position_register,
3923 body()->ToNode(
3924 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003925 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3926 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003927 register_count,
3928 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003929 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003930 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003931 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003932 // We use a ChoiceNode for a negative lookahead because it has most of
3933 // the characteristics we need. It has the body of the lookahead as its
3934 // first alternative and the expression after the lookahead of the second
3935 // alternative. If the first alternative succeeds then the
3936 // NegativeSubmatchSuccess will unwind the stack including everything the
3937 // choice node set up and backtrack. If the first alternative fails then
3938 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003939 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3940 // ChoiceNode that knows to ignore the first exit when calculating quick
3941 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003942 GuardedAlternative body_alt(
3943 body()->ToNode(
3944 compiler,
3945 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003946 position_register,
3947 register_count,
3948 register_start)));
3949 ChoiceNode* choice_node =
3950 new NegativeLookaheadChoiceNode(body_alt,
3951 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003952 return ActionNode::BeginSubmatch(stack_pointer_register,
3953 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003954 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003955 }
3956}
3957
3958
3959RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003960 RegExpNode* on_success) {
3961 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003962}
3963
3964
3965RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3966 int index,
3967 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003968 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003969 int start_reg = RegExpCapture::StartRegister(index);
3970 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003971 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003972 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003973 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003974}
3975
3976
3977RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003978 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003979 ZoneList<RegExpTree*>* children = nodes();
3980 RegExpNode* current = on_success;
3981 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003982 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003983 }
3984 return current;
3985}
3986
3987
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003988static void AddClass(const uc16* elmv,
3989 int elmc,
3990 ZoneList<CharacterRange>* ranges) {
3991 for (int i = 0; i < elmc; i += 2) {
3992 ASSERT(elmv[i] <= elmv[i + 1]);
3993 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3994 }
3995}
3996
3997
3998static void AddClassNegated(const uc16 *elmv,
3999 int elmc,
4000 ZoneList<CharacterRange>* ranges) {
4001 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00004002 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004003 uc16 last = 0x0000;
4004 for (int i = 0; i < elmc; i += 2) {
4005 ASSERT(last <= elmv[i] - 1);
4006 ASSERT(elmv[i] <= elmv[i + 1]);
4007 ranges->Add(CharacterRange(last, elmv[i] - 1));
4008 last = elmv[i + 1] + 1;
4009 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004010 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004011}
4012
4013
4014void CharacterRange::AddClassEscape(uc16 type,
4015 ZoneList<CharacterRange>* ranges) {
4016 switch (type) {
4017 case 's':
4018 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
4019 break;
4020 case 'S':
4021 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
4022 break;
4023 case 'w':
4024 AddClass(kWordRanges, kWordRangeCount, ranges);
4025 break;
4026 case 'W':
4027 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
4028 break;
4029 case 'd':
4030 AddClass(kDigitRanges, kDigitRangeCount, ranges);
4031 break;
4032 case 'D':
4033 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
4034 break;
4035 case '.':
4036 AddClassNegated(kLineTerminatorRanges,
4037 kLineTerminatorRangeCount,
4038 ranges);
4039 break;
4040 // This is not a character range as defined by the spec but a
4041 // convenient shorthand for a character class that matches any
4042 // character.
4043 case '*':
4044 ranges->Add(CharacterRange::Everything());
4045 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004046 // This is the set of characters matched by the $ and ^ symbols
4047 // in multiline mode.
4048 case 'n':
4049 AddClass(kLineTerminatorRanges,
4050 kLineTerminatorRangeCount,
4051 ranges);
4052 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004053 default:
4054 UNREACHABLE();
4055 }
4056}
4057
4058
4059Vector<const uc16> CharacterRange::GetWordBounds() {
4060 return Vector<const uc16>(kWordRanges, kWordRangeCount);
4061}
4062
4063
4064class CharacterRangeSplitter {
4065 public:
4066 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
4067 ZoneList<CharacterRange>** excluded)
4068 : included_(included),
4069 excluded_(excluded) { }
4070 void Call(uc16 from, DispatchTable::Entry entry);
4071
4072 static const int kInBase = 0;
4073 static const int kInOverlay = 1;
4074
4075 private:
4076 ZoneList<CharacterRange>** included_;
4077 ZoneList<CharacterRange>** excluded_;
4078};
4079
4080
4081void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
4082 if (!entry.out_set()->Get(kInBase)) return;
4083 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
4084 ? included_
4085 : excluded_;
4086 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
4087 (*target)->Add(CharacterRange(entry.from(), entry.to()));
4088}
4089
4090
4091void CharacterRange::Split(ZoneList<CharacterRange>* base,
4092 Vector<const uc16> overlay,
4093 ZoneList<CharacterRange>** included,
4094 ZoneList<CharacterRange>** excluded) {
4095 ASSERT_EQ(NULL, *included);
4096 ASSERT_EQ(NULL, *excluded);
4097 DispatchTable table;
4098 for (int i = 0; i < base->length(); i++)
4099 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
4100 for (int i = 0; i < overlay.length(); i += 2) {
4101 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
4102 CharacterRangeSplitter::kInOverlay);
4103 }
4104 CharacterRangeSplitter callback(included, excluded);
4105 table.ForEach(&callback);
4106}
4107
4108
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004109static void AddUncanonicals(Isolate* isolate,
4110 ZoneList<CharacterRange>* ranges,
ager@chromium.org38e4c712009-11-11 09:11:58 +00004111 int bottom,
4112 int top);
4113
4114
4115void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4116 bool is_ascii) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004117 Isolate* isolate = Isolate::Current();
ager@chromium.org38e4c712009-11-11 09:11:58 +00004118 uc16 bottom = from();
4119 uc16 top = to();
4120 if (is_ascii) {
4121 if (bottom > String::kMaxAsciiCharCode) return;
4122 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4123 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004124 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004125 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004126 // If this is a singleton we just expand the one character.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004127 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004128 for (int i = 0; i < length; i++) {
4129 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004130 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004131 ranges->Add(CharacterRange::Singleton(chars[i]));
4132 }
4133 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004134 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004135 // If this is a range we expand the characters block by block,
4136 // expanding contiguous subranges (blocks) one at a time.
4137 // The approach is as follows. For a given start character we
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004138 // look up the remainder of the block that contains it (represented
4139 // by the end point), for instance we find 'z' if the character
4140 // is 'c'. A block is characterized by the property
4141 // that all characters uncanonicalize in the same way, except that
4142 // each entry in the result is incremented by the distance from the first
4143 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
4144 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
4145 // Once we've found the end point we look up its uncanonicalization
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004146 // and produce a range for each element. For instance for [c-f]
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004147 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004148 // add a range if it is not already contained in the input, so [c-f]
4149 // will be skipped but [C-F] will be added. If this range is not
4150 // completely contained in a block we do this for all the blocks
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004151 // covered by the range (handling characters that is not in a block
4152 // as a "singleton block").
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004153 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004154 int pos = bottom;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004155 while (pos < top) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004156 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004157 uc16 block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004158 if (length == 0) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004159 block_end = pos;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004160 } else {
4161 ASSERT_EQ(1, length);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004162 block_end = range[0];
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004163 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004164 int end = (block_end > top) ? top : block_end;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004165 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004166 for (int i = 0; i < length; i++) {
4167 uc32 c = range[i];
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004168 uc16 range_from = c - (block_end - pos);
4169 uc16 range_to = c - (block_end - end);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004170 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004171 ranges->Add(CharacterRange(range_from, range_to));
4172 }
4173 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004174 pos = end + 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004175 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004176 }
4177}
4178
4179
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004180bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4181 ASSERT_NOT_NULL(ranges);
4182 int n = ranges->length();
4183 if (n <= 1) return true;
4184 int max = ranges->at(0).to();
4185 for (int i = 1; i < n; i++) {
4186 CharacterRange next_range = ranges->at(i);
4187 if (next_range.from() <= max + 1) return false;
4188 max = next_range.to();
4189 }
4190 return true;
4191}
4192
4193SetRelation CharacterRange::WordCharacterRelation(
4194 ZoneList<CharacterRange>* range) {
4195 ASSERT(IsCanonical(range));
4196 int i = 0; // Word character range index.
4197 int j = 0; // Argument range index.
4198 ASSERT_NE(0, kWordRangeCount);
4199 SetRelation result;
4200 if (range->length() == 0) {
4201 result.SetElementsInSecondSet();
4202 return result;
4203 }
4204 CharacterRange argument_range = range->at(0);
4205 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4206 while (i < kWordRangeCount && j < range->length()) {
4207 // Check the two ranges for the five cases:
4208 // - no overlap.
4209 // - partial overlap (there are elements in both ranges that isn't
4210 // in the other, and there are also elements that are in both).
4211 // - argument range entirely inside word range.
4212 // - word range entirely inside argument range.
4213 // - ranges are completely equal.
4214
4215 // First check for no overlap. The earlier range is not in the other set.
4216 if (argument_range.from() > word_range.to()) {
4217 // Ranges are disjoint. The earlier word range contains elements that
4218 // cannot be in the argument set.
4219 result.SetElementsInSecondSet();
4220 } else if (word_range.from() > argument_range.to()) {
4221 // Ranges are disjoint. The earlier argument range contains elements that
4222 // cannot be in the word set.
4223 result.SetElementsInFirstSet();
4224 } else if (word_range.from() <= argument_range.from() &&
4225 word_range.to() >= argument_range.from()) {
4226 result.SetElementsInBothSets();
4227 // argument range completely inside word range.
4228 if (word_range.from() < argument_range.from() ||
4229 word_range.to() > argument_range.from()) {
4230 result.SetElementsInSecondSet();
4231 }
4232 } else if (word_range.from() >= argument_range.from() &&
4233 word_range.to() <= argument_range.from()) {
4234 result.SetElementsInBothSets();
4235 result.SetElementsInFirstSet();
4236 } else {
4237 // There is overlap, and neither is a subrange of the other
4238 result.SetElementsInFirstSet();
4239 result.SetElementsInSecondSet();
4240 result.SetElementsInBothSets();
4241 }
4242 if (result.NonTrivialIntersection()) {
4243 // The result is as (im)precise as we can possibly make it.
4244 return result;
4245 }
4246 // Progress the range(s) with minimal to-character.
4247 uc16 word_to = word_range.to();
4248 uc16 argument_to = argument_range.to();
4249 if (argument_to <= word_to) {
4250 j++;
4251 if (j < range->length()) {
4252 argument_range = range->at(j);
4253 }
4254 }
4255 if (word_to <= argument_to) {
4256 i += 2;
4257 if (i < kWordRangeCount) {
4258 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4259 }
4260 }
4261 }
4262 // Check if anything wasn't compared in the loop.
4263 if (i < kWordRangeCount) {
4264 // word range contains something not in argument range.
4265 result.SetElementsInSecondSet();
4266 } else if (j < range->length()) {
4267 // Argument range contains something not in word range.
4268 result.SetElementsInFirstSet();
4269 }
4270
4271 return result;
4272}
4273
4274
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004275static void AddUncanonicals(Isolate* isolate,
4276 ZoneList<CharacterRange>* ranges,
ager@chromium.org38e4c712009-11-11 09:11:58 +00004277 int bottom,
4278 int top) {
4279 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4280 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4281 // this table is correct.
4282 // 0x0600 - 0x0fff
4283 // 0x1100 - 0x1cff
4284 // 0x2000 - 0x20ff
4285 // 0x2200 - 0x23ff
4286 // 0x2500 - 0x2bff
4287 // 0x2e00 - 0xa5ff
4288 // 0xa800 - 0xfaff
4289 // 0xfc00 - 0xfeff
4290 const int boundary_count = 18;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004291 int boundaries[] = {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004292 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4293 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4294
4295 // Special ASCII rule from spec can save us some work here.
4296 if (bottom == 0x80 && top == 0xffff) return;
4297
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004298 if (top <= boundaries[0]) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004299 CharacterRange range(bottom, top);
4300 range.AddCaseEquivalents(ranges, false);
4301 return;
4302 }
4303
4304 // Split up very large ranges. This helps remove ranges where there are no
4305 // case mappings.
4306 for (int i = 0; i < boundary_count; i++) {
4307 if (bottom < boundaries[i] && top >= boundaries[i]) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004308 AddUncanonicals(isolate, ranges, bottom, boundaries[i] - 1);
4309 AddUncanonicals(isolate, ranges, boundaries[i], top);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004310 return;
4311 }
4312 }
4313
4314 // If we are completely in a zone with no case mappings then we are done.
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004315 for (int i = 0; i < boundary_count; i += 2) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004316 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4317#ifdef DEBUG
4318 for (int j = bottom; j <= top; j++) {
4319 unsigned current_char = j;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004320 int length = isolate->jsregexp_uncanonicalize()->get(current_char,
4321 '\0', chars);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004322 for (int k = 0; k < length; k++) {
4323 ASSERT(chars[k] == current_char);
4324 }
4325 }
4326#endif
4327 return;
4328 }
4329 }
4330
4331 // Step through the range finding equivalent characters.
4332 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4333 for (int i = bottom; i <= top; i++) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004334 int length = isolate->jsregexp_uncanonicalize()->get(i, '\0', chars);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004335 for (int j = 0; j < length; j++) {
4336 uc32 chr = chars[j];
4337 if (chr != i && (chr < bottom || chr > top)) {
4338 characters->Add(chr);
4339 }
4340 }
4341 }
4342
4343 // Step through the equivalent characters finding simple ranges and
4344 // adding ranges to the character class.
4345 if (characters->length() > 0) {
4346 int new_from = characters->at(0);
4347 int new_to = new_from;
4348 for (int i = 1; i < characters->length(); i++) {
4349 int chr = characters->at(i);
4350 if (chr == new_to + 1) {
4351 new_to++;
4352 } else {
4353 if (new_to == new_from) {
4354 ranges->Add(CharacterRange::Singleton(new_from));
4355 } else {
4356 ranges->Add(CharacterRange(new_from, new_to));
4357 }
4358 new_from = new_to = chr;
4359 }
4360 }
4361 if (new_to == new_from) {
4362 ranges->Add(CharacterRange::Singleton(new_from));
4363 } else {
4364 ranges->Add(CharacterRange(new_from, new_to));
4365 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004366 }
4367}
4368
4369
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004370ZoneList<CharacterRange>* CharacterSet::ranges() {
4371 if (ranges_ == NULL) {
4372 ranges_ = new ZoneList<CharacterRange>(2);
4373 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4374 }
4375 return ranges_;
4376}
4377
4378
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004379// Move a number of elements in a zonelist to another position
4380// in the same list. Handles overlapping source and target areas.
4381static void MoveRanges(ZoneList<CharacterRange>* list,
4382 int from,
4383 int to,
4384 int count) {
4385 // Ranges are potentially overlapping.
4386 if (from < to) {
4387 for (int i = count - 1; i >= 0; i--) {
4388 list->at(to + i) = list->at(from + i);
4389 }
4390 } else {
4391 for (int i = 0; i < count; i++) {
4392 list->at(to + i) = list->at(from + i);
4393 }
4394 }
4395}
4396
4397
4398static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4399 int count,
4400 CharacterRange insert) {
4401 // Inserts a range into list[0..count[, which must be sorted
4402 // by from value and non-overlapping and non-adjacent, using at most
4403 // list[0..count] for the result. Returns the number of resulting
4404 // canonicalized ranges. Inserting a range may collapse existing ranges into
4405 // fewer ranges, so the return value can be anything in the range 1..count+1.
4406 uc16 from = insert.from();
4407 uc16 to = insert.to();
4408 int start_pos = 0;
4409 int end_pos = count;
4410 for (int i = count - 1; i >= 0; i--) {
4411 CharacterRange current = list->at(i);
4412 if (current.from() > to + 1) {
4413 end_pos = i;
4414 } else if (current.to() + 1 < from) {
4415 start_pos = i + 1;
4416 break;
4417 }
4418 }
4419
4420 // Inserted range overlaps, or is adjacent to, ranges at positions
4421 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4422 // not affected by the insertion.
4423 // If start_pos == end_pos, the range must be inserted before start_pos.
4424 // if start_pos < end_pos, the entire range from start_pos to end_pos
4425 // must be merged with the insert range.
4426
4427 if (start_pos == end_pos) {
4428 // Insert between existing ranges at position start_pos.
4429 if (start_pos < count) {
4430 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4431 }
4432 list->at(start_pos) = insert;
4433 return count + 1;
4434 }
4435 if (start_pos + 1 == end_pos) {
4436 // Replace single existing range at position start_pos.
4437 CharacterRange to_replace = list->at(start_pos);
4438 int new_from = Min(to_replace.from(), from);
4439 int new_to = Max(to_replace.to(), to);
4440 list->at(start_pos) = CharacterRange(new_from, new_to);
4441 return count;
4442 }
4443 // Replace a number of existing ranges from start_pos to end_pos - 1.
4444 // Move the remaining ranges down.
4445
4446 int new_from = Min(list->at(start_pos).from(), from);
4447 int new_to = Max(list->at(end_pos - 1).to(), to);
4448 if (end_pos < count) {
4449 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4450 }
4451 list->at(start_pos) = CharacterRange(new_from, new_to);
4452 return count - (end_pos - start_pos) + 1;
4453}
4454
4455
4456void CharacterSet::Canonicalize() {
4457 // Special/default classes are always considered canonical. The result
4458 // of calling ranges() will be sorted.
4459 if (ranges_ == NULL) return;
4460 CharacterRange::Canonicalize(ranges_);
4461}
4462
4463
4464void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4465 if (character_ranges->length() <= 1) return;
4466 // Check whether ranges are already canonical (increasing, non-overlapping,
4467 // non-adjacent).
4468 int n = character_ranges->length();
4469 int max = character_ranges->at(0).to();
4470 int i = 1;
4471 while (i < n) {
4472 CharacterRange current = character_ranges->at(i);
4473 if (current.from() <= max + 1) {
4474 break;
4475 }
4476 max = current.to();
4477 i++;
4478 }
4479 // Canonical until the i'th range. If that's all of them, we are done.
4480 if (i == n) return;
4481
4482 // The ranges at index i and forward are not canonicalized. Make them so by
4483 // doing the equivalent of insertion sort (inserting each into the previous
4484 // list, in order).
4485 // Notice that inserting a range can reduce the number of ranges in the
4486 // result due to combining of adjacent and overlapping ranges.
4487 int read = i; // Range to insert.
4488 int num_canonical = i; // Length of canonicalized part of list.
4489 do {
4490 num_canonical = InsertRangeInCanonicalList(character_ranges,
4491 num_canonical,
4492 character_ranges->at(read));
4493 read++;
4494 } while (read < n);
4495 character_ranges->Rewind(num_canonical);
4496
4497 ASSERT(CharacterRange::IsCanonical(character_ranges));
4498}
4499
4500
4501// Utility function for CharacterRange::Merge. Adds a range at the end of
4502// a canonicalized range list, if necessary merging the range with the last
4503// range of the list.
4504static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4505 if (set == NULL) return;
4506 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4507 int n = set->length();
4508 if (n > 0) {
4509 CharacterRange lastRange = set->at(n - 1);
4510 if (lastRange.to() == range.from() - 1) {
4511 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4512 return;
4513 }
4514 }
4515 set->Add(range);
4516}
4517
4518
4519static void AddRangeToSelectedSet(int selector,
4520 ZoneList<CharacterRange>* first_set,
4521 ZoneList<CharacterRange>* second_set,
4522 ZoneList<CharacterRange>* intersection_set,
4523 CharacterRange range) {
4524 switch (selector) {
4525 case kInsideFirst:
4526 AddRangeToSet(first_set, range);
4527 break;
4528 case kInsideSecond:
4529 AddRangeToSet(second_set, range);
4530 break;
4531 case kInsideBoth:
4532 AddRangeToSet(intersection_set, range);
4533 break;
4534 }
4535}
4536
4537
4538
4539void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4540 ZoneList<CharacterRange>* second_set,
4541 ZoneList<CharacterRange>* first_set_only_out,
4542 ZoneList<CharacterRange>* second_set_only_out,
4543 ZoneList<CharacterRange>* both_sets_out) {
4544 // Inputs are canonicalized.
4545 ASSERT(CharacterRange::IsCanonical(first_set));
4546 ASSERT(CharacterRange::IsCanonical(second_set));
4547 // Outputs are empty, if applicable.
4548 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4549 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4550 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4551
4552 // Merge sets by iterating through the lists in order of lowest "from" value,
4553 // and putting intervals into one of three sets.
4554
4555 if (first_set->length() == 0) {
4556 second_set_only_out->AddAll(*second_set);
4557 return;
4558 }
4559 if (second_set->length() == 0) {
4560 first_set_only_out->AddAll(*first_set);
4561 return;
4562 }
4563 // Indices into input lists.
4564 int i1 = 0;
4565 int i2 = 0;
4566 // Cache length of input lists.
4567 int n1 = first_set->length();
4568 int n2 = second_set->length();
4569 // Current range. May be invalid if state is kInsideNone.
4570 int from = 0;
4571 int to = -1;
4572 // Where current range comes from.
4573 int state = kInsideNone;
4574
4575 while (i1 < n1 || i2 < n2) {
4576 CharacterRange next_range;
4577 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004578 if (i2 == n2 ||
4579 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4580 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004581 next_range = first_set->at(i1++);
4582 range_source = kInsideFirst;
4583 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004584 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004585 next_range = second_set->at(i2++);
4586 range_source = kInsideSecond;
4587 }
4588 if (to < next_range.from()) {
4589 // Ranges disjoint: |current| |next|
4590 AddRangeToSelectedSet(state,
4591 first_set_only_out,
4592 second_set_only_out,
4593 both_sets_out,
4594 CharacterRange(from, to));
4595 from = next_range.from();
4596 to = next_range.to();
4597 state = range_source;
4598 } else {
4599 if (from < next_range.from()) {
4600 AddRangeToSelectedSet(state,
4601 first_set_only_out,
4602 second_set_only_out,
4603 both_sets_out,
4604 CharacterRange(from, next_range.from()-1));
4605 }
4606 if (to < next_range.to()) {
4607 // Ranges overlap: |current|
4608 // |next|
4609 AddRangeToSelectedSet(state | range_source,
4610 first_set_only_out,
4611 second_set_only_out,
4612 both_sets_out,
4613 CharacterRange(next_range.from(), to));
4614 from = to + 1;
4615 to = next_range.to();
4616 state = range_source;
4617 } else {
4618 // Range included: |current| , possibly ending at same character.
4619 // |next|
4620 AddRangeToSelectedSet(
4621 state | range_source,
4622 first_set_only_out,
4623 second_set_only_out,
4624 both_sets_out,
4625 CharacterRange(next_range.from(), next_range.to()));
4626 from = next_range.to() + 1;
4627 // If ranges end at same character, both ranges are consumed completely.
4628 if (next_range.to() == to) state = kInsideNone;
4629 }
4630 }
4631 }
4632 AddRangeToSelectedSet(state,
4633 first_set_only_out,
4634 second_set_only_out,
4635 both_sets_out,
4636 CharacterRange(from, to));
4637}
4638
4639
4640void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4641 ZoneList<CharacterRange>* negated_ranges) {
4642 ASSERT(CharacterRange::IsCanonical(ranges));
4643 ASSERT_EQ(0, negated_ranges->length());
4644 int range_count = ranges->length();
4645 uc16 from = 0;
4646 int i = 0;
4647 if (range_count > 0 && ranges->at(0).from() == 0) {
4648 from = ranges->at(0).to();
4649 i = 1;
4650 }
4651 while (i < range_count) {
4652 CharacterRange range = ranges->at(i);
4653 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4654 from = range.to();
4655 i++;
4656 }
4657 if (from < String::kMaxUC16CharCode) {
4658 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4659 }
4660}
4661
4662
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004663
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004664// -------------------------------------------------------------------
4665// Interest propagation
4666
4667
4668RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4669 for (int i = 0; i < siblings_.length(); i++) {
4670 RegExpNode* sibling = siblings_.Get(i);
4671 if (sibling->info()->Matches(info))
4672 return sibling;
4673 }
4674 return NULL;
4675}
4676
4677
4678RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4679 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004680 siblings_.Ensure(this);
4681 RegExpNode* result = TryGetSibling(info);
4682 if (result != NULL) return result;
4683 result = this->Clone();
4684 NodeInfo* new_info = result->info();
4685 new_info->ResetCompilationState();
4686 new_info->AddFromPreceding(info);
4687 AddSibling(result);
4688 *cloned = true;
4689 return result;
4690}
4691
4692
4693template <class C>
4694static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4695 NodeInfo full_info(*node->info());
4696 full_info.AddFromPreceding(info);
4697 bool cloned = false;
4698 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4699}
4700
4701
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004702// -------------------------------------------------------------------
4703// Splay tree
4704
4705
4706OutSet* OutSet::Extend(unsigned value) {
4707 if (Get(value))
4708 return this;
4709 if (successors() != NULL) {
4710 for (int i = 0; i < successors()->length(); i++) {
4711 OutSet* successor = successors()->at(i);
4712 if (successor->Get(value))
4713 return successor;
4714 }
4715 } else {
4716 successors_ = new ZoneList<OutSet*>(2);
4717 }
4718 OutSet* result = new OutSet(first_, remaining_);
4719 result->Set(value);
4720 successors()->Add(result);
4721 return result;
4722}
4723
4724
4725void OutSet::Set(unsigned value) {
4726 if (value < kFirstLimit) {
4727 first_ |= (1 << value);
4728 } else {
4729 if (remaining_ == NULL)
4730 remaining_ = new ZoneList<unsigned>(1);
4731 if (remaining_->is_empty() || !remaining_->Contains(value))
4732 remaining_->Add(value);
4733 }
4734}
4735
4736
4737bool OutSet::Get(unsigned value) {
4738 if (value < kFirstLimit) {
4739 return (first_ & (1 << value)) != 0;
4740 } else if (remaining_ == NULL) {
4741 return false;
4742 } else {
4743 return remaining_->Contains(value);
4744 }
4745}
4746
4747
4748const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4749const DispatchTable::Entry DispatchTable::Config::kNoValue;
4750
4751
4752void DispatchTable::AddRange(CharacterRange full_range, int value) {
4753 CharacterRange current = full_range;
4754 if (tree()->is_empty()) {
4755 // If this is the first range we just insert into the table.
4756 ZoneSplayTree<Config>::Locator loc;
4757 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4758 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4759 return;
4760 }
4761 // First see if there is a range to the left of this one that
4762 // overlaps.
4763 ZoneSplayTree<Config>::Locator loc;
4764 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4765 Entry* entry = &loc.value();
4766 // If we've found a range that overlaps with this one, and it
4767 // starts strictly to the left of this one, we have to fix it
4768 // because the following code only handles ranges that start on
4769 // or after the start point of the range we're adding.
4770 if (entry->from() < current.from() && entry->to() >= current.from()) {
4771 // Snap the overlapping range in half around the start point of
4772 // the range we're adding.
4773 CharacterRange left(entry->from(), current.from() - 1);
4774 CharacterRange right(current.from(), entry->to());
4775 // The left part of the overlapping range doesn't overlap.
4776 // Truncate the whole entry to be just the left part.
4777 entry->set_to(left.to());
4778 // The right part is the one that overlaps. We add this part
4779 // to the map and let the next step deal with merging it with
4780 // the range we're adding.
4781 ZoneSplayTree<Config>::Locator loc;
4782 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4783 loc.set_value(Entry(right.from(),
4784 right.to(),
4785 entry->out_set()));
4786 }
4787 }
4788 while (current.is_valid()) {
4789 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4790 (loc.value().from() <= current.to()) &&
4791 (loc.value().to() >= current.from())) {
4792 Entry* entry = &loc.value();
4793 // We have overlap. If there is space between the start point of
4794 // the range we're adding and where the overlapping range starts
4795 // then we have to add a range covering just that space.
4796 if (current.from() < entry->from()) {
4797 ZoneSplayTree<Config>::Locator ins;
4798 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4799 ins.set_value(Entry(current.from(),
4800 entry->from() - 1,
4801 empty()->Extend(value)));
4802 current.set_from(entry->from());
4803 }
4804 ASSERT_EQ(current.from(), entry->from());
4805 // If the overlapping range extends beyond the one we want to add
4806 // we have to snap the right part off and add it separately.
4807 if (entry->to() > current.to()) {
4808 ZoneSplayTree<Config>::Locator ins;
4809 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4810 ins.set_value(Entry(current.to() + 1,
4811 entry->to(),
4812 entry->out_set()));
4813 entry->set_to(current.to());
4814 }
4815 ASSERT(entry->to() <= current.to());
4816 // The overlapping range is now completely contained by the range
4817 // we're adding so we can just update it and move the start point
4818 // of the range we're adding just past it.
4819 entry->AddValue(value);
4820 // Bail out if the last interval ended at 0xFFFF since otherwise
4821 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004822 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004823 break;
4824 ASSERT(entry->to() + 1 > current.from());
4825 current.set_from(entry->to() + 1);
4826 } else {
4827 // There is no overlap so we can just add the range
4828 ZoneSplayTree<Config>::Locator ins;
4829 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4830 ins.set_value(Entry(current.from(),
4831 current.to(),
4832 empty()->Extend(value)));
4833 break;
4834 }
4835 }
4836}
4837
4838
4839OutSet* DispatchTable::Get(uc16 value) {
4840 ZoneSplayTree<Config>::Locator loc;
4841 if (!tree()->FindGreatestLessThan(value, &loc))
4842 return empty();
4843 Entry* entry = &loc.value();
4844 if (value <= entry->to())
4845 return entry->out_set();
4846 else
4847 return empty();
4848}
4849
4850
4851// -------------------------------------------------------------------
4852// Analysis
4853
4854
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004855void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004856 StackLimitCheck check(Isolate::Current());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004857 if (check.HasOverflowed()) {
4858 fail("Stack overflow");
4859 return;
4860 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004861 if (that->info()->been_analyzed || that->info()->being_analyzed)
4862 return;
4863 that->info()->being_analyzed = true;
4864 that->Accept(this);
4865 that->info()->being_analyzed = false;
4866 that->info()->been_analyzed = true;
4867}
4868
4869
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004870void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004871 // nothing to do
4872}
4873
4874
ager@chromium.org8bb60582008-12-11 12:02:20 +00004875void TextNode::CalculateOffsets() {
4876 int element_count = elements()->length();
4877 // Set up the offsets of the elements relative to the start. This is a fixed
4878 // quantity since a TextNode can only contain fixed-width things.
4879 int cp_offset = 0;
4880 for (int i = 0; i < element_count; i++) {
4881 TextElement& elm = elements()->at(i);
4882 elm.cp_offset = cp_offset;
4883 if (elm.type == TextElement::ATOM) {
4884 cp_offset += elm.data.u_atom->data().length();
4885 } else {
4886 cp_offset++;
4887 Vector<const uc16> quarks = elm.data.u_atom->data();
4888 }
4889 }
4890}
4891
4892
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004893void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004894 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004895 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004896 }
4897 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004898 if (!has_failed()) {
4899 that->CalculateOffsets();
4900 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004901}
4902
4903
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004904void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004905 RegExpNode* target = that->on_success();
4906 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004907 if (!has_failed()) {
4908 // If the next node is interested in what it follows then this node
4909 // has to be interested too so it can pass the information on.
4910 that->info()->AddFromFollowing(target->info());
4911 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004912}
4913
4914
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004915void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004916 NodeInfo* info = that->info();
4917 for (int i = 0; i < that->alternatives()->length(); i++) {
4918 RegExpNode* node = that->alternatives()->at(i).node();
4919 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004920 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004921 // Anything the following nodes need to know has to be known by
4922 // this node also, so it can pass it on.
4923 info->AddFromFollowing(node->info());
4924 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004925}
4926
4927
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004928void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4929 NodeInfo* info = that->info();
4930 for (int i = 0; i < that->alternatives()->length(); i++) {
4931 RegExpNode* node = that->alternatives()->at(i).node();
4932 if (node != that->loop_node()) {
4933 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004934 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004935 info->AddFromFollowing(node->info());
4936 }
4937 }
4938 // Check the loop last since it may need the value of this node
4939 // to get a correct result.
4940 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004941 if (!has_failed()) {
4942 info->AddFromFollowing(that->loop_node()->info());
4943 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004944}
4945
4946
4947void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004948 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004949}
4950
4951
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004952void Analysis::VisitAssertion(AssertionNode* that) {
4953 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004954 AssertionNode::AssertionNodeType type = that->type();
4955 if (type == AssertionNode::AT_BOUNDARY ||
4956 type == AssertionNode::AT_NON_BOUNDARY) {
4957 // Check if the following character is known to be a word character
4958 // or known to not be a word character.
4959 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4960
4961 CharacterRange::Canonicalize(following_chars);
4962
4963 SetRelation word_relation =
4964 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004965 if (word_relation.Disjoint()) {
4966 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004967 // Following character is definitely *not* a word character.
4968 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004969 AssertionNode::AFTER_WORD_CHARACTER :
4970 AssertionNode::AFTER_NONWORD_CHARACTER;
4971 that->set_type(type);
4972 } else if (word_relation.ContainedIn()) {
4973 // Following character is definitely a word character.
4974 type = (type == AssertionNode::AT_BOUNDARY) ?
4975 AssertionNode::AFTER_NONWORD_CHARACTER :
4976 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004977 that->set_type(type);
4978 }
4979 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004980}
4981
4982
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004983ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4984 if (first_character_set_ == NULL) {
4985 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4986 // If we can't find an exact solution within the budget, we
4987 // set the value to the set of every character, i.e., all characters
4988 // are possible.
4989 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4990 all_set->Add(CharacterRange::Everything());
4991 first_character_set_ = all_set;
4992 }
4993 }
4994 return first_character_set_;
4995}
4996
4997
4998int RegExpNode::ComputeFirstCharacterSet(int budget) {
4999 // Default behavior is to not be able to determine the first character.
5000 return kComputeFirstCharacterSetFail;
5001}
5002
5003
5004int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
5005 budget--;
5006 if (budget >= 0) {
5007 // Find loop min-iteration. It's the value of the guarded choice node
5008 // with a GEQ guard, if any.
5009 int min_repetition = 0;
5010
5011 for (int i = 0; i <= 1; i++) {
5012 GuardedAlternative alternative = alternatives()->at(i);
5013 ZoneList<Guard*>* guards = alternative.guards();
5014 if (guards != NULL && guards->length() > 0) {
5015 Guard* guard = guards->at(0);
5016 if (guard->op() == Guard::GEQ) {
5017 min_repetition = guard->value();
5018 break;
5019 }
5020 }
5021 }
5022
5023 budget = loop_node()->ComputeFirstCharacterSet(budget);
5024 if (budget >= 0) {
5025 ZoneList<CharacterRange>* character_set =
5026 loop_node()->first_character_set();
5027 if (body_can_be_zero_length() || min_repetition == 0) {
5028 budget = continue_node()->ComputeFirstCharacterSet(budget);
5029 if (budget < 0) return budget;
5030 ZoneList<CharacterRange>* body_set =
5031 continue_node()->first_character_set();
5032 ZoneList<CharacterRange>* union_set =
5033 new ZoneList<CharacterRange>(Max(character_set->length(),
5034 body_set->length()));
5035 CharacterRange::Merge(character_set,
5036 body_set,
5037 union_set,
5038 union_set,
5039 union_set);
5040 character_set = union_set;
5041 }
5042 set_first_character_set(character_set);
5043 }
5044 }
5045 return budget;
5046}
5047
5048
5049int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
5050 budget--;
5051 if (budget >= 0) {
5052 GuardedAlternative successor = this->alternatives()->at(1);
5053 RegExpNode* successor_node = successor.node();
5054 budget = successor_node->ComputeFirstCharacterSet(budget);
5055 if (budget >= 0) {
5056 set_first_character_set(successor_node->first_character_set());
5057 }
5058 }
5059 return budget;
5060}
5061
5062
5063// The first character set of an EndNode is unknowable. Just use the
5064// default implementation that fails and returns all characters as possible.
5065
5066
5067int AssertionNode::ComputeFirstCharacterSet(int budget) {
5068 budget -= 1;
5069 if (budget >= 0) {
5070 switch (type_) {
5071 case AT_END: {
5072 set_first_character_set(new ZoneList<CharacterRange>(0));
5073 break;
5074 }
5075 case AT_START:
5076 case AT_BOUNDARY:
5077 case AT_NON_BOUNDARY:
5078 case AFTER_NEWLINE:
5079 case AFTER_NONWORD_CHARACTER:
5080 case AFTER_WORD_CHARACTER: {
5081 ASSERT_NOT_NULL(on_success());
5082 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005083 if (budget >= 0) {
5084 set_first_character_set(on_success()->first_character_set());
5085 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005086 break;
5087 }
5088 }
5089 }
5090 return budget;
5091}
5092
5093
5094int ActionNode::ComputeFirstCharacterSet(int budget) {
5095 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
5096 budget--;
5097 if (budget >= 0) {
5098 ASSERT_NOT_NULL(on_success());
5099 budget = on_success()->ComputeFirstCharacterSet(budget);
5100 if (budget >= 0) {
5101 set_first_character_set(on_success()->first_character_set());
5102 }
5103 }
5104 return budget;
5105}
5106
5107
5108int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5109 // We don't know anything about the first character of a backreference
5110 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005111 // The potential first characters are the first characters of the capture,
5112 // and the first characters of the on_success node, depending on whether the
5113 // capture can be empty and whether it is known to be participating or known
5114 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005115 return kComputeFirstCharacterSetFail;
5116}
5117
5118
5119int TextNode::ComputeFirstCharacterSet(int budget) {
5120 budget--;
5121 if (budget >= 0) {
5122 ASSERT_NE(0, elements()->length());
5123 TextElement text = elements()->at(0);
5124 if (text.type == TextElement::ATOM) {
5125 RegExpAtom* atom = text.data.u_atom;
5126 ASSERT_NE(0, atom->length());
5127 uc16 first_char = atom->data()[0];
5128 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5129 range->Add(CharacterRange(first_char, first_char));
5130 set_first_character_set(range);
5131 } else {
5132 ASSERT(text.type == TextElement::CHAR_CLASS);
5133 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005134 ZoneList<CharacterRange>* ranges = char_class->ranges();
5135 // TODO(lrn): Canonicalize ranges when they are created
5136 // instead of waiting until now.
5137 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005138 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005139 int length = ranges->length();
5140 int new_length = length + 1;
5141 if (length > 0) {
5142 if (ranges->at(0).from() == 0) new_length--;
5143 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5144 new_length--;
5145 }
5146 }
5147 ZoneList<CharacterRange>* negated_ranges =
5148 new ZoneList<CharacterRange>(new_length);
5149 CharacterRange::Negate(ranges, negated_ranges);
5150 set_first_character_set(negated_ranges);
5151 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005152 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005153 }
5154 }
5155 }
5156 return budget;
5157}
5158
5159
5160
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005161// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005162// Dispatch table construction
5163
5164
5165void DispatchTableConstructor::VisitEnd(EndNode* that) {
5166 AddRange(CharacterRange::Everything());
5167}
5168
5169
5170void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5171 node->set_being_calculated(true);
5172 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5173 for (int i = 0; i < alternatives->length(); i++) {
5174 set_choice_index(i);
5175 alternatives->at(i).node()->Accept(this);
5176 }
5177 node->set_being_calculated(false);
5178}
5179
5180
5181class AddDispatchRange {
5182 public:
5183 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5184 : constructor_(constructor) { }
5185 void Call(uc32 from, DispatchTable::Entry entry);
5186 private:
5187 DispatchTableConstructor* constructor_;
5188};
5189
5190
5191void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5192 CharacterRange range(from, entry.to());
5193 constructor_->AddRange(range);
5194}
5195
5196
5197void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5198 if (node->being_calculated())
5199 return;
5200 DispatchTable* table = node->GetTable(ignore_case_);
5201 AddDispatchRange adder(this);
5202 table->ForEach(&adder);
5203}
5204
5205
5206void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5207 // TODO(160): Find the node that we refer back to and propagate its start
5208 // set back to here. For now we just accept anything.
5209 AddRange(CharacterRange::Everything());
5210}
5211
5212
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005213void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5214 RegExpNode* target = that->on_success();
5215 target->Accept(this);
5216}
5217
5218
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005219static int CompareRangeByFrom(const CharacterRange* a,
5220 const CharacterRange* b) {
5221 return Compare<uc16>(a->from(), b->from());
5222}
5223
5224
5225void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5226 ranges->Sort(CompareRangeByFrom);
5227 uc16 last = 0;
5228 for (int i = 0; i < ranges->length(); i++) {
5229 CharacterRange range = ranges->at(i);
5230 if (last < range.from())
5231 AddRange(CharacterRange(last, range.from() - 1));
5232 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005233 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005234 return;
5235 } else {
5236 last = range.to() + 1;
5237 }
5238 }
5239 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005240 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005241}
5242
5243
5244void DispatchTableConstructor::VisitText(TextNode* that) {
5245 TextElement elm = that->elements()->at(0);
5246 switch (elm.type) {
5247 case TextElement::ATOM: {
5248 uc16 c = elm.data.u_atom->data()[0];
5249 AddRange(CharacterRange(c, c));
5250 break;
5251 }
5252 case TextElement::CHAR_CLASS: {
5253 RegExpCharacterClass* tree = elm.data.u_char_class;
5254 ZoneList<CharacterRange>* ranges = tree->ranges();
5255 if (tree->is_negated()) {
5256 AddInverse(ranges);
5257 } else {
5258 for (int i = 0; i < ranges->length(); i++)
5259 AddRange(ranges->at(i));
5260 }
5261 break;
5262 }
5263 default: {
5264 UNIMPLEMENTED();
5265 }
5266 }
5267}
5268
5269
5270void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005271 RegExpNode* target = that->on_success();
5272 target->Accept(this);
5273}
5274
5275
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005276RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5277 bool ignore_case,
5278 bool is_multiline,
5279 Handle<String> pattern,
5280 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005281 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005282 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005283 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005284 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005285 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005286 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005287 0,
5288 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005289 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005290 RegExpNode* node = captured_body;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005291 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
5292 bool is_start_anchored = data->tree->IsAnchoredAtStart();
5293 int max_length = data->tree->max_match();
5294 if (!is_start_anchored) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005295 // Add a .*? at the beginning, outside the body capture, unless
5296 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005297 RegExpNode* loop_node =
5298 RegExpQuantifier::ToNode(0,
5299 RegExpTree::kInfinity,
5300 false,
5301 new RegExpCharacterClass('*'),
5302 &compiler,
5303 captured_body,
5304 data->contains_anchor);
5305
5306 if (data->contains_anchor) {
5307 // Unroll loop once, to take care of the case that might start
5308 // at the start of input.
5309 ChoiceNode* first_step_node = new ChoiceNode(2);
5310 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5311 first_step_node->AddAlternative(GuardedAlternative(
5312 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5313 node = first_step_node;
5314 } else {
5315 node = loop_node;
5316 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005317 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005318 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005319 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005320 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005321 if (analysis.has_failed()) {
5322 const char* error_message = analysis.error_message();
5323 return CompilationResult(error_message);
5324 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005325
5326 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005327
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005328 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005329#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005330 // Native regexp implementation.
5331
5332 NativeRegExpMacroAssembler::Mode mode =
5333 is_ascii ? NativeRegExpMacroAssembler::ASCII
5334 : NativeRegExpMacroAssembler::UC16;
5335
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005336#if V8_TARGET_ARCH_IA32
5337 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5338#elif V8_TARGET_ARCH_X64
5339 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5340#elif V8_TARGET_ARCH_ARM
5341 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005342#endif
5343
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005344#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005345 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005346 EmbeddedVector<byte, 1024> codes;
5347 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005348#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005349
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005350 // Inserted here, instead of in Assembler, because it depends on information
5351 // in the AST that isn't replicated in the Node structure.
5352 static const int kMaxBacksearchLimit = 1024;
5353 if (is_end_anchored &&
5354 !is_start_anchored &&
5355 max_length < kMaxBacksearchLimit) {
5356 macro_assembler.SetCurrentPositionFromEnd(max_length);
5357 }
5358
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005359 return compiler.Assemble(&macro_assembler,
5360 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005361 data->capture_count,
5362 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005363}
5364
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005365
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005366}} // namespace v8::internal