blob: d5f59eaa3ee03681e05f1102b9ea7662e09e3a4a [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
fschneider@chromium.org7979bbb2011-03-28 10:47:03 +0000504 if (IrregexpInterpreter::Match(isolate,
505 byte_codes,
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000506 subject,
507 register_vector,
508 index)) {
509 return RE_SUCCESS;
510 }
511 return RE_FAILURE;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000512#endif // V8_INTERPRETED_REGEXP
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000513}
514
515
ager@chromium.org41826e72009-03-30 13:30:57 +0000516Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000517 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000518 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000519 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000520 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000521
ager@chromium.org8bb60582008-12-11 12:02:20 +0000522 // Prepare space for the return values.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000523#ifdef V8_INTERPRETED_REGEXP
ager@chromium.org8bb60582008-12-11 12:02:20 +0000524#ifdef DEBUG
525 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000526 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000527 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
528 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
529 }
530#endif
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000531#endif
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000532 int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject);
533 if (required_registers < 0) {
534 // Compiling failed with an exception.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000535 ASSERT(Isolate::Current()->has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000536 return Handle<Object>::null();
537 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000538
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000539 OffsetsVector registers(required_registers);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000540
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000541 IrregexpResult res = RegExpImpl::IrregexpExecOnce(
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000542 jsregexp, subject, previous_index, Vector<int>(registers.vector(),
543 registers.length()));
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000544 if (res == RE_SUCCESS) {
545 int capture_register_count =
546 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
547 last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead);
548 AssertNoAllocation no_gc;
549 int* register_vector = registers.vector();
550 FixedArray* array = FixedArray::cast(last_match_info->elements());
551 for (int i = 0; i < capture_register_count; i += 2) {
552 SetCapture(array, i, register_vector[i]);
553 SetCapture(array, i + 1, register_vector[i + 1]);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000554 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000555 SetLastCaptureCount(array, capture_register_count);
556 SetLastSubject(array, *subject);
557 SetLastInput(array, *subject);
558 return last_match_info;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000559 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000560 if (res == RE_EXCEPTION) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000561 ASSERT(Isolate::Current()->has_pending_exception());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000562 return Handle<Object>::null();
563 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000564 ASSERT(res == RE_FAILURE);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000565 return Isolate::Current()->factory()->null_value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000566}
567
568
569// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000570// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000571//
572// The Irregexp regular expression engine is intended to be a complete
573// implementation of ECMAScript regular expressions. It generates either
574// bytecodes or native code.
575
576// The Irregexp regexp engine is structured in three steps.
577// 1) The parser generates an abstract syntax tree. See ast.cc.
578// 2) From the AST a node network is created. The nodes are all
579// subclasses of RegExpNode. The nodes represent states when
580// executing a regular expression. Several optimizations are
581// performed on the node network.
582// 3) From the nodes we generate either byte codes or native code
583// that can actually execute the regular expression (perform
584// the search). The code generation step is described in more
585// detail below.
586
587// Code generation.
588//
589// The nodes are divided into four main categories.
590// * Choice nodes
591// These represent places where the regular expression can
592// match in more than one way. For example on entry to an
593// alternation (foo|bar) or a repetition (*, +, ? or {}).
594// * Action nodes
595// These represent places where some action should be
596// performed. Examples include recording the current position
597// in the input string to a register (in order to implement
598// captures) or other actions on register for example in order
599// to implement the counters needed for {} repetitions.
600// * Matching nodes
601// These attempt to match some element part of the input string.
602// Examples of elements include character classes, plain strings
603// or back references.
604// * End nodes
605// These are used to implement the actions required on finding
606// a successful match or failing to find a match.
607//
608// The code generated (whether as byte codes or native code) maintains
609// some state as it runs. This consists of the following elements:
610//
611// * The capture registers. Used for string captures.
612// * Other registers. Used for counters etc.
613// * The current position.
614// * The stack of backtracking information. Used when a matching node
615// fails to find a match and needs to try an alternative.
616//
617// Conceptual regular expression execution model:
618//
619// There is a simple conceptual model of regular expression execution
620// which will be presented first. The actual code generated is a more
621// efficient simulation of the simple conceptual model:
622//
623// * Choice nodes are implemented as follows:
624// For each choice except the last {
625// push current position
626// push backtrack code location
627// <generate code to test for choice>
628// backtrack code location:
629// pop current position
630// }
631// <generate code to test for last choice>
632//
633// * Actions nodes are generated as follows
634// <push affected registers on backtrack stack>
635// <generate code to perform action>
636// push backtrack code location
637// <generate code to test for following nodes>
638// backtrack code location:
639// <pop affected registers to restore their state>
640// <pop backtrack location from stack and go to it>
641//
642// * Matching nodes are generated as follows:
643// if input string matches at current position
644// update current position
645// <generate code to test for following nodes>
646// else
647// <pop backtrack location from stack and go to it>
648//
649// Thus it can be seen that the current position is saved and restored
650// by the choice nodes, whereas the registers are saved and restored by
651// by the action nodes that manipulate them.
652//
653// The other interesting aspect of this model is that nodes are generated
654// at the point where they are needed by a recursive call to Emit(). If
655// the node has already been code generated then the Emit() call will
656// generate a jump to the previously generated code instead. In order to
657// limit recursion it is possible for the Emit() function to put the node
658// on a work list for later generation and instead generate a jump. The
659// destination of the jump is resolved later when the code is generated.
660//
661// Actual regular expression code generation.
662//
663// Code generation is actually more complicated than the above. In order
664// to improve the efficiency of the generated code some optimizations are
665// performed
666//
667// * Choice nodes have 1-character lookahead.
668// A choice node looks at the following character and eliminates some of
669// the choices immediately based on that character. This is not yet
670// implemented.
671// * Simple greedy loops store reduced backtracking information.
672// A quantifier like /.*foo/m will greedily match the whole input. It will
673// then need to backtrack to a point where it can match "foo". The naive
674// implementation of this would push each character position onto the
675// backtracking stack, then pop them off one by one. This would use space
676// proportional to the length of the input string. However since the "."
677// can only match in one way and always has a constant length (in this case
678// of 1) it suffices to store the current position on the top of the stack
679// once. Matching now becomes merely incrementing the current position and
680// backtracking becomes decrementing the current position and checking the
681// result against the stored current position. This is faster and saves
682// space.
683// * The current state is virtualized.
684// This is used to defer expensive operations until it is clear that they
685// are needed and to generate code for a node more than once, allowing
686// specialized an efficient versions of the code to be created. This is
687// explained in the section below.
688//
689// Execution state virtualization.
690//
691// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000692// manipulation in an object called the Trace. The Trace object can record a
693// current position offset, an optional backtrack code location on the top of
694// the virtualized backtrack stack and some register changes. When a node is
695// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000696// will emit code to bring the actual state into line with the virtual state.
697// Avoiding flushing the state can postpone some work (eg updates of capture
698// registers). Postponing work can save time when executing the regular
699// expression since it may be found that the work never has to be done as a
700// failure to match can occur. In addition it is much faster to jump to a
701// known backtrack code location than it is to pop an unknown backtrack
702// location from the stack and jump there.
703//
ager@chromium.org32912102009-01-16 10:38:43 +0000704// The virtual state found in the Trace affects code generation. For example
705// the virtual state contains the difference between the actual current
706// position and the virtual current position, and matching code needs to use
707// this offset to attempt a match in the correct location of the input
708// string. Therefore code generated for a non-trivial trace is specialized
709// to that trace. The code generator therefore has the ability to generate
710// code for each node several times. In order to limit the size of the
711// generated code there is an arbitrary limit on how many specialized sets of
712// code may be generated for a given node. If the limit is reached, the
713// trace is flushed and a generic version of the code for a node is emitted.
714// This is subsequently used for that node. The code emitted for non-generic
715// trace is not recorded in the node and so it cannot currently be reused in
716// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000717
718
719void RegExpTree::AppendToText(RegExpText* text) {
720 UNREACHABLE();
721}
722
723
724void RegExpAtom::AppendToText(RegExpText* text) {
725 text->AddElement(TextElement::Atom(this));
726}
727
728
729void RegExpCharacterClass::AppendToText(RegExpText* text) {
730 text->AddElement(TextElement::CharClass(this));
731}
732
733
734void RegExpText::AppendToText(RegExpText* text) {
735 for (int i = 0; i < elements()->length(); i++)
736 text->AddElement(elements()->at(i));
737}
738
739
740TextElement TextElement::Atom(RegExpAtom* atom) {
741 TextElement result = TextElement(ATOM);
742 result.data.u_atom = atom;
743 return result;
744}
745
746
747TextElement TextElement::CharClass(
748 RegExpCharacterClass* char_class) {
749 TextElement result = TextElement(CHAR_CLASS);
750 result.data.u_char_class = char_class;
751 return result;
752}
753
754
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000755int TextElement::length() {
756 if (type == ATOM) {
757 return data.u_atom->length();
758 } else {
759 ASSERT(type == CHAR_CLASS);
760 return 1;
761 }
762}
763
764
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000765DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
766 if (table_ == NULL) {
767 table_ = new DispatchTable();
768 DispatchTableConstructor cons(table_, ignore_case);
769 cons.BuildTable(this);
770 }
771 return table_;
772}
773
774
775class RegExpCompiler {
776 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000777 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000778
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000779 int AllocateRegister() {
780 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
781 reg_exp_too_big_ = true;
782 return next_register_;
783 }
784 return next_register_++;
785 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000786
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000787 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
788 RegExpNode* start,
789 int capture_count,
790 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000791
792 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
793
794 static const int kImplementationOffset = 0;
795 static const int kNumberOfRegistersOffset = 0;
796 static const int kCodeOffset = 1;
797
798 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
799 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000800
801 static const int kMaxRecursion = 100;
802 inline int recursion_depth() { return recursion_depth_; }
803 inline void IncrementRecursionDepth() { recursion_depth_++; }
804 inline void DecrementRecursionDepth() { recursion_depth_--; }
805
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000806 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
807
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000808 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000809 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000810
ager@chromium.org32912102009-01-16 10:38:43 +0000811 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000812 private:
813 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000814 int next_register_;
815 List<RegExpNode*>* work_list_;
816 int recursion_depth_;
817 RegExpMacroAssembler* macro_assembler_;
818 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000819 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000820 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000821};
822
823
824class RecursionCheck {
825 public:
826 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
827 compiler->IncrementRecursionDepth();
828 }
829 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
830 private:
831 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000832};
833
834
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000835static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
836 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000837}
838
839
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000840// Attempts to compile the regexp using an Irregexp code generator. Returns
841// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000842RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000843 : next_register_(2 * (capture_count + 1)),
844 work_list_(NULL),
845 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000846 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000847 ascii_(ascii),
848 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000849 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000850 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000851}
852
853
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000854RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000855 RegExpMacroAssembler* macro_assembler,
856 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000857 int capture_count,
858 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000859#ifdef DEBUG
860 if (FLAG_trace_regexp_assembler)
861 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
862 else
863#endif
864 macro_assembler_ = macro_assembler;
865 List <RegExpNode*> work_list(0);
866 work_list_ = &work_list;
867 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000868 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000869 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000870 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000871 macro_assembler_->Bind(&fail);
872 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000873 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000874 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000875 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000876 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
877
ager@chromium.org8bb60582008-12-11 12:02:20 +0000878 Handle<Object> code = macro_assembler_->GetCode(pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000879 work_list_ = NULL;
880#ifdef DEBUG
danno@chromium.org4d3fe4e2011-03-10 10:14:28 +0000881 if (FLAG_print_code) {
882 Handle<Code>::cast(code)->Disassemble(*pattern->ToCString());
883 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000884 if (FLAG_trace_regexp_assembler) {
885 delete macro_assembler_;
886 }
887#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000888 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000889}
890
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000891
ager@chromium.org32912102009-01-16 10:38:43 +0000892bool Trace::DeferredAction::Mentions(int that) {
893 if (type() == ActionNode::CLEAR_CAPTURES) {
894 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
895 return range.Contains(that);
896 } else {
897 return reg() == that;
898 }
899}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000900
ager@chromium.org32912102009-01-16 10:38:43 +0000901
902bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000903 for (DeferredAction* action = actions_;
904 action != NULL;
905 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000906 if (action->Mentions(reg))
907 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000908 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000909 return false;
910}
911
912
ager@chromium.org32912102009-01-16 10:38:43 +0000913bool Trace::GetStoredPosition(int reg, int* cp_offset) {
914 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000915 for (DeferredAction* action = actions_;
916 action != NULL;
917 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000918 if (action->Mentions(reg)) {
919 if (action->type() == ActionNode::STORE_POSITION) {
920 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
921 return true;
922 } else {
923 return false;
924 }
925 }
926 }
927 return false;
928}
929
930
931int Trace::FindAffectedRegisters(OutSet* affected_registers) {
932 int max_register = RegExpCompiler::kNoRegister;
933 for (DeferredAction* action = actions_;
934 action != NULL;
935 action = action->next()) {
936 if (action->type() == ActionNode::CLEAR_CAPTURES) {
937 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
938 for (int i = range.from(); i <= range.to(); i++)
939 affected_registers->Set(i);
940 if (range.to() > max_register) max_register = range.to();
941 } else {
942 affected_registers->Set(action->reg());
943 if (action->reg() > max_register) max_register = action->reg();
944 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000945 }
946 return max_register;
947}
948
949
ager@chromium.org32912102009-01-16 10:38:43 +0000950void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
951 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000952 OutSet& registers_to_pop,
953 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000954 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000955 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
956 else if (registers_to_clear.Get(reg)) {
957 int clear_to = reg;
958 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
959 reg--;
960 }
961 assembler->ClearRegisters(reg, clear_to);
962 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000963 }
964}
965
966
ager@chromium.org32912102009-01-16 10:38:43 +0000967void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
968 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000969 OutSet& affected_registers,
970 OutSet* registers_to_pop,
971 OutSet* registers_to_clear) {
972 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
973 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
974
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000975 // Count pushes performed to force a stack limit check occasionally.
976 int pushes = 0;
977
ager@chromium.org8bb60582008-12-11 12:02:20 +0000978 for (int reg = 0; reg <= max_register; reg++) {
979 if (!affected_registers.Get(reg)) {
980 continue;
981 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000982
983 // The chronologically first deferred action in the trace
984 // is used to infer the action needed to restore a register
985 // to its previous state (or not, if it's safe to ignore it).
986 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
987 DeferredActionUndoType undo_action = IGNORE;
988
ager@chromium.org8bb60582008-12-11 12:02:20 +0000989 int value = 0;
990 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000991 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000992 int store_position = -1;
993 // This is a little tricky because we are scanning the actions in reverse
994 // historical order (newest first).
995 for (DeferredAction* action = actions_;
996 action != NULL;
997 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000998 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000999 switch (action->type()) {
1000 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00001001 Trace::DeferredSetRegister* psr =
1002 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001003 if (!absolute) {
1004 value += psr->value();
1005 absolute = true;
1006 }
1007 // SET_REGISTER is currently only used for newly introduced loop
1008 // counters. They can have a significant previous value if they
1009 // occour in a loop. TODO(lrn): Propagate this information, so
1010 // we can set undo_action to IGNORE if we know there is no value to
1011 // restore.
1012 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001013 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001014 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001015 break;
1016 }
1017 case ActionNode::INCREMENT_REGISTER:
1018 if (!absolute) {
1019 value++;
1020 }
1021 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +00001022 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001023 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001024 break;
1025 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00001026 Trace::DeferredCapture* pc =
1027 static_cast<Trace::DeferredCapture*>(action);
1028 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001029 store_position = pc->cp_offset();
1030 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001031
1032 // For captures we know that stores and clears alternate.
1033 // Other register, are never cleared, and if the occur
1034 // inside a loop, they might be assigned more than once.
1035 if (reg <= 1) {
1036 // Registers zero and one, aka "capture zero", is
1037 // always set correctly if we succeed. There is no
1038 // need to undo a setting on backtrack, because we
1039 // will set it again or fail.
1040 undo_action = IGNORE;
1041 } else {
1042 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1043 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001044 ASSERT(!absolute);
1045 ASSERT_EQ(value, 0);
1046 break;
1047 }
ager@chromium.org32912102009-01-16 10:38:43 +00001048 case ActionNode::CLEAR_CAPTURES: {
1049 // Since we're scanning in reverse order, if we've already
1050 // set the position we have to ignore historically earlier
1051 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001052 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +00001053 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001054 }
1055 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +00001056 ASSERT(!absolute);
1057 ASSERT_EQ(value, 0);
1058 break;
1059 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001060 default:
1061 UNREACHABLE();
1062 break;
1063 }
1064 }
1065 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001066 // Prepare for the undo-action (e.g., push if it's going to be popped).
1067 if (undo_action == RESTORE) {
1068 pushes++;
1069 RegExpMacroAssembler::StackCheckFlag stack_check =
1070 RegExpMacroAssembler::kNoStackLimitCheck;
1071 if (pushes == push_limit) {
1072 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1073 pushes = 0;
1074 }
1075
1076 assembler->PushRegister(reg, stack_check);
1077 registers_to_pop->Set(reg);
1078 } else if (undo_action == CLEAR) {
1079 registers_to_clear->Set(reg);
1080 }
1081 // Perform the chronologically last action (or accumulated increment)
1082 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001083 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001084 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001085 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001086 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001087 } else if (absolute) {
1088 assembler->SetRegister(reg, value);
1089 } else if (value != 0) {
1090 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001091 }
1092 }
1093}
1094
1095
ager@chromium.org8bb60582008-12-11 12:02:20 +00001096// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001097// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001098// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001099void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001100 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001101
iposva@chromium.org245aa852009-02-10 00:49:54 +00001102 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001103
1104 if (actions_ == NULL && backtrack() == NULL) {
1105 // 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 +00001106 // a normal situation. We may also have to forget some information gained
1107 // through a quick check that was already performed.
1108 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001109 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001110 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001111 successor->Emit(compiler, &new_state);
1112 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001113 }
1114
1115 // Generate deferred actions here along with code to undo them again.
1116 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001117
ager@chromium.org381abbb2009-02-25 13:23:22 +00001118 if (backtrack() != NULL) {
1119 // Here we have a concrete backtrack location. These are set up by choice
1120 // nodes and so they indicate that we have a deferred save of the current
1121 // position which we may need to emit here.
1122 assembler->PushCurrentPosition();
1123 }
1124
ager@chromium.org8bb60582008-12-11 12:02:20 +00001125 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001126 OutSet registers_to_pop;
1127 OutSet registers_to_clear;
1128 PerformDeferredActions(assembler,
1129 max_register,
1130 affected_registers,
1131 &registers_to_pop,
1132 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001133 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001134 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001135 }
1136
1137 // Create a new trivial state and generate the node with that.
1138 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001139 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001140 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001141 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001142
1143 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001144 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001145 RestoreAffectedRegisters(assembler,
1146 max_register,
1147 registers_to_pop,
1148 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001149 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001150 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001151 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001152 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001153 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001154 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001155}
1156
1157
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001158void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001159 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001160
1161 // Omit flushing the trace. We discard the entire stack frame anyway.
1162
ager@chromium.org8bb60582008-12-11 12:02:20 +00001163 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001164 // We are completely independent of the trace, since we ignore it,
1165 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001166 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001167 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001168
1169 // Throw away everything on the backtrack stack since the start
1170 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001171 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1172 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001173 if (clear_capture_count_ > 0) {
1174 // Clear any captures that might have been performed during the success
1175 // of the body of the negative look-ahead.
1176 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1177 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1178 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001179 // Now that we have unwound the stack we find at the top of the stack the
1180 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001181 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001182}
1183
1184
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001185void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001186 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001187 trace->Flush(compiler, this);
1188 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001189 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001190 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001191 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001192 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001193 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001194 switch (action_) {
1195 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001196 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001197 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001198 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001199 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001200 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001201 case NEGATIVE_SUBMATCH_SUCCESS:
1202 // This case is handled in a different virtual method.
1203 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001204 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001205 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001206}
1207
1208
1209void GuardedAlternative::AddGuard(Guard* guard) {
1210 if (guards_ == NULL)
1211 guards_ = new ZoneList<Guard*>(1);
1212 guards_->Add(guard);
1213}
1214
1215
ager@chromium.org8bb60582008-12-11 12:02:20 +00001216ActionNode* ActionNode::SetRegister(int reg,
1217 int val,
1218 RegExpNode* on_success) {
1219 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001220 result->data_.u_store_register.reg = reg;
1221 result->data_.u_store_register.value = val;
1222 return result;
1223}
1224
1225
1226ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1227 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1228 result->data_.u_increment_register.reg = reg;
1229 return result;
1230}
1231
1232
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001233ActionNode* ActionNode::StorePosition(int reg,
1234 bool is_capture,
1235 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001236 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1237 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001238 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001239 return result;
1240}
1241
1242
ager@chromium.org32912102009-01-16 10:38:43 +00001243ActionNode* ActionNode::ClearCaptures(Interval range,
1244 RegExpNode* on_success) {
1245 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1246 result->data_.u_clear_captures.range_from = range.from();
1247 result->data_.u_clear_captures.range_to = range.to();
1248 return result;
1249}
1250
1251
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001252ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1253 int position_reg,
1254 RegExpNode* on_success) {
1255 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1256 result->data_.u_submatch.stack_pointer_register = stack_reg;
1257 result->data_.u_submatch.current_position_register = position_reg;
1258 return result;
1259}
1260
1261
ager@chromium.org8bb60582008-12-11 12:02:20 +00001262ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1263 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001264 int clear_register_count,
1265 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001266 RegExpNode* on_success) {
1267 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001268 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001269 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001270 result->data_.u_submatch.clear_register_count = clear_register_count;
1271 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001272 return result;
1273}
1274
1275
ager@chromium.org32912102009-01-16 10:38:43 +00001276ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1277 int repetition_register,
1278 int repetition_limit,
1279 RegExpNode* on_success) {
1280 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1281 result->data_.u_empty_match_check.start_register = start_register;
1282 result->data_.u_empty_match_check.repetition_register = repetition_register;
1283 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1284 return result;
1285}
1286
1287
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001288#define DEFINE_ACCEPT(Type) \
1289 void Type##Node::Accept(NodeVisitor* visitor) { \
1290 visitor->Visit##Type(this); \
1291 }
1292FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1293#undef DEFINE_ACCEPT
1294
1295
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001296void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1297 visitor->VisitLoopChoice(this);
1298}
1299
1300
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001301// -------------------------------------------------------------------
1302// Emit code.
1303
1304
1305void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1306 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001307 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001308 switch (guard->op()) {
1309 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001310 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001311 macro_assembler->IfRegisterGE(guard->reg(),
1312 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001313 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001314 break;
1315 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001316 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001317 macro_assembler->IfRegisterLT(guard->reg(),
1318 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001319 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001320 break;
1321 }
1322}
1323
1324
ager@chromium.org381abbb2009-02-25 13:23:22 +00001325// Returns the number of characters in the equivalence class, omitting those
1326// that cannot occur in the source string because it is ASCII.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001327static int GetCaseIndependentLetters(Isolate* isolate,
1328 uc16 character,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001329 bool ascii_subject,
1330 unibrow::uchar* letters) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001331 int length =
1332 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00001333 // Unibrow returns 0 or 1 for characters where case independence is
ager@chromium.org381abbb2009-02-25 13:23:22 +00001334 // trivial.
1335 if (length == 0) {
1336 letters[0] = character;
1337 length = 1;
1338 }
1339 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1340 return length;
1341 }
1342 // The standard requires that non-ASCII characters cannot have ASCII
1343 // character codes in their equivalence class.
1344 return 0;
1345}
1346
1347
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001348static inline bool EmitSimpleCharacter(Isolate* isolate,
1349 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001350 uc16 c,
1351 Label* on_failure,
1352 int cp_offset,
1353 bool check,
1354 bool preloaded) {
1355 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1356 bool bound_checked = false;
1357 if (!preloaded) {
1358 assembler->LoadCurrentCharacter(
1359 cp_offset,
1360 on_failure,
1361 check);
1362 bound_checked = true;
1363 }
1364 assembler->CheckNotCharacter(c, on_failure);
1365 return bound_checked;
1366}
1367
1368
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001369// Only emits non-letters (things that don't have case). Only used for case
1370// independent matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001371static inline bool EmitAtomNonLetter(Isolate* isolate,
1372 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001373 uc16 c,
1374 Label* on_failure,
1375 int cp_offset,
1376 bool check,
1377 bool preloaded) {
1378 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1379 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001380 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001381 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001382 if (length < 1) {
1383 // This can't match. Must be an ASCII subject and a non-ASCII character.
1384 // We do not need to do anything since the ASCII pass already handled this.
1385 return false; // Bounds not checked.
1386 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001387 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001388 // We handle the length > 1 case in a later pass.
1389 if (length == 1) {
1390 if (ascii && c > String::kMaxAsciiCharCodeU) {
1391 // Can't match - see above.
1392 return false; // Bounds not checked.
1393 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001394 if (!preloaded) {
1395 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1396 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001397 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001398 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001399 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001400 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001401}
1402
1403
1404static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001405 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001406 uc16 c1,
1407 uc16 c2,
1408 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001409 uc16 char_mask;
1410 if (ascii) {
1411 char_mask = String::kMaxAsciiCharCode;
1412 } else {
1413 char_mask = String::kMaxUC16CharCode;
1414 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001415 uc16 exor = c1 ^ c2;
1416 // Check whether exor has only one bit set.
1417 if (((exor - 1) & exor) == 0) {
1418 // If c1 and c2 differ only by one bit.
1419 // Ecma262UnCanonicalize always gives the highest number last.
1420 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001421 uc16 mask = char_mask ^ exor;
1422 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001423 return true;
1424 }
1425 ASSERT(c2 > c1);
1426 uc16 diff = c2 - c1;
1427 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1428 // If the characters differ by 2^n but don't differ by one bit then
1429 // subtract the difference from the found character, then do the or
1430 // trick. We avoid the theoretical case where negative numbers are
1431 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001432 uc16 mask = char_mask ^ diff;
1433 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1434 diff,
1435 mask,
1436 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001437 return true;
1438 }
1439 return false;
1440}
1441
1442
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001443typedef bool EmitCharacterFunction(Isolate* isolate,
1444 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001445 uc16 c,
1446 Label* on_failure,
1447 int cp_offset,
1448 bool check,
1449 bool preloaded);
1450
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001451// Only emits letters (things that have case). Only used for case independent
1452// matches.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001453static inline bool EmitAtomLetter(Isolate* isolate,
1454 RegExpCompiler* compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001455 uc16 c,
1456 Label* on_failure,
1457 int cp_offset,
1458 bool check,
1459 bool preloaded) {
1460 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1461 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001462 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001463 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001464 if (length <= 1) return false;
1465 // We may not need to check against the end of the input string
1466 // if this character lies before a character that matched.
1467 if (!preloaded) {
1468 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001469 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001470 Label ok;
1471 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1472 switch (length) {
1473 case 2: {
1474 if (ShortCutEmitCharacterPair(macro_assembler,
1475 ascii,
1476 chars[0],
1477 chars[1],
1478 on_failure)) {
1479 } else {
1480 macro_assembler->CheckCharacter(chars[0], &ok);
1481 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1482 macro_assembler->Bind(&ok);
1483 }
1484 break;
1485 }
1486 case 4:
1487 macro_assembler->CheckCharacter(chars[3], &ok);
1488 // Fall through!
1489 case 3:
1490 macro_assembler->CheckCharacter(chars[0], &ok);
1491 macro_assembler->CheckCharacter(chars[1], &ok);
1492 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1493 macro_assembler->Bind(&ok);
1494 break;
1495 default:
1496 UNREACHABLE();
1497 break;
1498 }
1499 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001500}
1501
1502
1503static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1504 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001505 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001506 Label* on_failure,
1507 int cp_offset,
1508 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001509 bool preloaded) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001510 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001511 int max_char;
1512 if (ascii) {
1513 max_char = String::kMaxAsciiCharCode;
1514 } else {
1515 max_char = String::kMaxUC16CharCode;
1516 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001517
1518 Label success;
1519
1520 Label* char_is_in_class =
1521 cc->is_negated() ? on_failure : &success;
1522
1523 int range_count = ranges->length();
1524
ager@chromium.org8bb60582008-12-11 12:02:20 +00001525 int last_valid_range = range_count - 1;
1526 while (last_valid_range >= 0) {
1527 CharacterRange& range = ranges->at(last_valid_range);
1528 if (range.from() <= max_char) {
1529 break;
1530 }
1531 last_valid_range--;
1532 }
1533
1534 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001535 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001536 // TODO(plesner): We can remove this when the node level does our
1537 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001538 macro_assembler->GoTo(on_failure);
1539 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001540 if (check_offset) {
1541 macro_assembler->CheckPosition(cp_offset, on_failure);
1542 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001543 return;
1544 }
1545
ager@chromium.org8bb60582008-12-11 12:02:20 +00001546 if (last_valid_range == 0 &&
1547 !cc->is_negated() &&
1548 ranges->at(0).IsEverything(max_char)) {
1549 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001550 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001551 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001552 }
1553 return;
1554 }
1555
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001556 if (!preloaded) {
1557 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001558 }
1559
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001560 if (cc->is_standard() &&
1561 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1562 on_failure)) {
1563 return;
1564 }
1565
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001566 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001567 CharacterRange& range = ranges->at(i);
1568 Label next_range;
1569 uc16 from = range.from();
1570 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001571 if (from > max_char) {
1572 continue;
1573 }
1574 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001575 if (to == from) {
1576 macro_assembler->CheckCharacter(to, char_is_in_class);
1577 } else {
1578 if (from != 0) {
1579 macro_assembler->CheckCharacterLT(from, &next_range);
1580 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001581 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001582 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1583 } else {
1584 macro_assembler->GoTo(char_is_in_class);
1585 }
1586 }
1587 macro_assembler->Bind(&next_range);
1588 }
1589
ager@chromium.org8bb60582008-12-11 12:02:20 +00001590 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001591 uc16 from = range.from();
1592 uc16 to = range.to();
1593
ager@chromium.org8bb60582008-12-11 12:02:20 +00001594 if (to > max_char) to = max_char;
1595 ASSERT(to >= from);
1596
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001597 if (to == from) {
1598 if (cc->is_negated()) {
1599 macro_assembler->CheckCharacter(to, on_failure);
1600 } else {
1601 macro_assembler->CheckNotCharacter(to, on_failure);
1602 }
1603 } else {
1604 if (from != 0) {
1605 if (cc->is_negated()) {
1606 macro_assembler->CheckCharacterLT(from, &success);
1607 } else {
1608 macro_assembler->CheckCharacterLT(from, on_failure);
1609 }
1610 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001611 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001612 if (cc->is_negated()) {
1613 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1614 } else {
1615 macro_assembler->CheckCharacterGT(to, on_failure);
1616 }
1617 } else {
1618 if (cc->is_negated()) {
1619 macro_assembler->GoTo(on_failure);
1620 }
1621 }
1622 }
1623 macro_assembler->Bind(&success);
1624}
1625
1626
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001627RegExpNode::~RegExpNode() {
1628}
1629
1630
ager@chromium.org8bb60582008-12-11 12:02:20 +00001631RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001632 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001633 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001634 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001635 return CONTINUE;
1636 }
1637
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001638 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001639 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001640 if (label_.is_bound()) {
1641 // We are being asked to generate a generic version, but that's already
1642 // been done so just go to it.
1643 macro_assembler->GoTo(&label_);
1644 return DONE;
1645 }
1646 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1647 // To avoid too deep recursion we push the node to the work queue and just
1648 // generate a goto here.
1649 compiler->AddWork(this);
1650 macro_assembler->GoTo(&label_);
1651 return DONE;
1652 }
1653 // Generate generic version of the node and bind the label for later use.
1654 macro_assembler->Bind(&label_);
1655 return CONTINUE;
1656 }
1657
1658 // We are being asked to make a non-generic version. Keep track of how many
1659 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001660 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001661 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001662 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001663 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1664 return CONTINUE;
1665 }
1666
ager@chromium.org32912102009-01-16 10:38:43 +00001667 // If we get here code has been generated for this node too many times or
1668 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001669 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001670 trace->Flush(compiler, this);
1671 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001672}
1673
1674
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001675int ActionNode::EatsAtLeast(int still_to_find,
1676 int recursion_depth,
1677 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001678 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1679 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001680 return on_success()->EatsAtLeast(still_to_find,
1681 recursion_depth + 1,
1682 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001683}
1684
1685
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001686int AssertionNode::EatsAtLeast(int still_to_find,
1687 int recursion_depth,
1688 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001689 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001690 // If we know we are not at the start and we are asked "how many characters
1691 // will you match if you succeed?" then we can answer anything since false
1692 // implies false. So lets just return the max answer (still_to_find) since
1693 // that won't prevent us from preloading a lot of characters for the other
1694 // branches in the node graph.
1695 if (type() == AT_START && not_at_start) return still_to_find;
1696 return on_success()->EatsAtLeast(still_to_find,
1697 recursion_depth + 1,
1698 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001699}
1700
1701
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001702int BackReferenceNode::EatsAtLeast(int still_to_find,
1703 int recursion_depth,
1704 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001705 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001706 return on_success()->EatsAtLeast(still_to_find,
1707 recursion_depth + 1,
1708 not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001709}
1710
1711
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001712int TextNode::EatsAtLeast(int still_to_find,
1713 int recursion_depth,
1714 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001715 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001716 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001717 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001718 // We are not at start after this node so we set the last argument to 'true'.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001719 return answer + on_success()->EatsAtLeast(still_to_find - answer,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001720 recursion_depth + 1,
1721 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001722}
1723
1724
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001725int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001726 int recursion_depth,
1727 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001728 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1729 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1730 // afterwards.
1731 RegExpNode* node = alternatives_->at(1).node();
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001732 return node->EatsAtLeast(still_to_find, recursion_depth + 1, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001733}
1734
1735
1736void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1737 QuickCheckDetails* details,
1738 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001739 int filled_in,
1740 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001741 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1742 // afterwards.
1743 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001744 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001745}
1746
1747
1748int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1749 int recursion_depth,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001750 RegExpNode* ignore_this_node,
1751 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001752 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1753 int min = 100;
1754 int choice_count = alternatives_->length();
1755 for (int i = 0; i < choice_count; i++) {
1756 RegExpNode* node = alternatives_->at(i).node();
1757 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001758 int node_eats_at_least = node->EatsAtLeast(still_to_find,
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001759 recursion_depth + 1,
1760 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001761 if (node_eats_at_least < min) min = node_eats_at_least;
1762 }
1763 return min;
1764}
1765
1766
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001767int LoopChoiceNode::EatsAtLeast(int still_to_find,
1768 int recursion_depth,
1769 bool not_at_start) {
1770 return EatsAtLeastHelper(still_to_find,
1771 recursion_depth,
1772 loop_node_,
1773 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001774}
1775
1776
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001777int ChoiceNode::EatsAtLeast(int still_to_find,
1778 int recursion_depth,
1779 bool not_at_start) {
1780 return EatsAtLeastHelper(still_to_find,
1781 recursion_depth,
1782 NULL,
1783 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001784}
1785
1786
1787// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1788static inline uint32_t SmearBitsRight(uint32_t v) {
1789 v |= v >> 1;
1790 v |= v >> 2;
1791 v |= v >> 4;
1792 v |= v >> 8;
1793 v |= v >> 16;
1794 return v;
1795}
1796
1797
1798bool QuickCheckDetails::Rationalize(bool asc) {
1799 bool found_useful_op = false;
1800 uint32_t char_mask;
1801 if (asc) {
1802 char_mask = String::kMaxAsciiCharCode;
1803 } else {
1804 char_mask = String::kMaxUC16CharCode;
1805 }
1806 mask_ = 0;
1807 value_ = 0;
1808 int char_shift = 0;
1809 for (int i = 0; i < characters_; i++) {
1810 Position* pos = &positions_[i];
1811 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1812 found_useful_op = true;
1813 }
1814 mask_ |= (pos->mask & char_mask) << char_shift;
1815 value_ |= (pos->value & char_mask) << char_shift;
1816 char_shift += asc ? 8 : 16;
1817 }
1818 return found_useful_op;
1819}
1820
1821
1822bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001823 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001824 bool preload_has_checked_bounds,
1825 Label* on_possible_success,
1826 QuickCheckDetails* details,
1827 bool fall_through_on_failure) {
1828 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001829 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1830 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001831 if (!details->Rationalize(compiler->ascii())) return false;
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001832 ASSERT(details->characters() == 1 ||
1833 compiler->macro_assembler()->CanReadUnaligned());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001834 uint32_t mask = details->mask();
1835 uint32_t value = details->value();
1836
1837 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1838
ager@chromium.org32912102009-01-16 10:38:43 +00001839 if (trace->characters_preloaded() != details->characters()) {
1840 assembler->LoadCurrentCharacter(trace->cp_offset(),
1841 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001842 !preload_has_checked_bounds,
1843 details->characters());
1844 }
1845
1846
1847 bool need_mask = true;
1848
1849 if (details->characters() == 1) {
1850 // If number of characters preloaded is 1 then we used a byte or 16 bit
1851 // load so the value is already masked down.
1852 uint32_t char_mask;
1853 if (compiler->ascii()) {
1854 char_mask = String::kMaxAsciiCharCode;
1855 } else {
1856 char_mask = String::kMaxUC16CharCode;
1857 }
1858 if ((mask & char_mask) == char_mask) need_mask = false;
1859 mask &= char_mask;
1860 } else {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001861 // For 2-character preloads in ASCII mode or 1-character preloads in
1862 // TWO_BYTE mode we also use a 16 bit load with zero extend.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001863 if (details->characters() == 2 && compiler->ascii()) {
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001864 if ((mask & 0x7f7f) == 0x7f7f) need_mask = false;
1865 } else if (details->characters() == 1 && !compiler->ascii()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001866 if ((mask & 0xffff) == 0xffff) need_mask = false;
1867 } else {
1868 if (mask == 0xffffffff) need_mask = false;
1869 }
1870 }
1871
1872 if (fall_through_on_failure) {
1873 if (need_mask) {
1874 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1875 } else {
1876 assembler->CheckCharacter(value, on_possible_success);
1877 }
1878 } else {
1879 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001880 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001881 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001882 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001883 }
1884 }
1885 return true;
1886}
1887
1888
1889// Here is the meat of GetQuickCheckDetails (see also the comment on the
1890// super-class in the .h file).
1891//
1892// We iterate along the text object, building up for each character a
1893// mask and value that can be used to test for a quick failure to match.
1894// The masks and values for the positions will be combined into a single
1895// machine word for the current character width in order to be used in
1896// generating a quick check.
1897void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1898 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001899 int characters_filled_in,
1900 bool not_at_start) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001901 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001902 ASSERT(characters_filled_in < details->characters());
1903 int characters = details->characters();
1904 int char_mask;
1905 int char_shift;
1906 if (compiler->ascii()) {
1907 char_mask = String::kMaxAsciiCharCode;
1908 char_shift = 8;
1909 } else {
1910 char_mask = String::kMaxUC16CharCode;
1911 char_shift = 16;
1912 }
1913 for (int k = 0; k < elms_->length(); k++) {
1914 TextElement elm = elms_->at(k);
1915 if (elm.type == TextElement::ATOM) {
1916 Vector<const uc16> quarks = elm.data.u_atom->data();
1917 for (int i = 0; i < characters && i < quarks.length(); i++) {
1918 QuickCheckDetails::Position* pos =
1919 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001920 uc16 c = quarks[i];
1921 if (c > char_mask) {
1922 // If we expect a non-ASCII character from an ASCII string,
1923 // there is no way we can match. Not even case independent
1924 // matching can turn an ASCII character into non-ASCII or
1925 // vice versa.
1926 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001927 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001928 return;
1929 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001930 if (compiler->ignore_case()) {
1931 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001932 int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
1933 chars);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001934 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1935 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001936 // This letter has no case equivalents, so it's nice and simple
1937 // and the mask-compare will determine definitely whether we have
1938 // a match at this character position.
1939 pos->mask = char_mask;
1940 pos->value = c;
1941 pos->determines_perfectly = true;
1942 } else {
1943 uint32_t common_bits = char_mask;
1944 uint32_t bits = chars[0];
1945 for (int j = 1; j < length; j++) {
1946 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1947 common_bits ^= differing_bits;
1948 bits &= common_bits;
1949 }
1950 // If length is 2 and common bits has only one zero in it then
1951 // our mask and compare instruction will determine definitely
1952 // whether we have a match at this character position. Otherwise
1953 // it can only be an approximate check.
1954 uint32_t one_zero = (common_bits | ~char_mask);
1955 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1956 pos->determines_perfectly = true;
1957 }
1958 pos->mask = common_bits;
1959 pos->value = bits;
1960 }
1961 } else {
1962 // Don't ignore case. Nice simple case where the mask-compare will
1963 // determine definitely whether we have a match at this character
1964 // position.
1965 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001966 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001967 pos->determines_perfectly = true;
1968 }
1969 characters_filled_in++;
1970 ASSERT(characters_filled_in <= details->characters());
1971 if (characters_filled_in == details->characters()) {
1972 return;
1973 }
1974 }
1975 } else {
1976 QuickCheckDetails::Position* pos =
1977 details->positions(characters_filled_in);
1978 RegExpCharacterClass* tree = elm.data.u_char_class;
1979 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001980 if (tree->is_negated()) {
1981 // A quick check uses multi-character mask and compare. There is no
1982 // useful way to incorporate a negative char class into this scheme
1983 // so we just conservatively create a mask and value that will always
1984 // succeed.
1985 pos->mask = 0;
1986 pos->value = 0;
1987 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001988 int first_range = 0;
1989 while (ranges->at(first_range).from() > char_mask) {
1990 first_range++;
1991 if (first_range == ranges->length()) {
1992 details->set_cannot_match();
1993 pos->determines_perfectly = false;
1994 return;
1995 }
1996 }
1997 CharacterRange range = ranges->at(first_range);
1998 uc16 from = range.from();
1999 uc16 to = range.to();
2000 if (to > char_mask) {
2001 to = char_mask;
2002 }
2003 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002004 // A mask and compare is only perfect if the differing bits form a
2005 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002006 if ((differing_bits & (differing_bits + 1)) == 0 &&
2007 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002008 pos->determines_perfectly = true;
2009 }
2010 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002011 uint32_t bits = (from & common_bits);
2012 for (int i = first_range + 1; i < ranges->length(); i++) {
2013 CharacterRange range = ranges->at(i);
2014 uc16 from = range.from();
2015 uc16 to = range.to();
2016 if (from > char_mask) continue;
2017 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002018 // Here we are combining more ranges into the mask and compare
2019 // value. With each new range the mask becomes more sparse and
2020 // so the chances of a false positive rise. A character class
2021 // with multiple ranges is assumed never to be equivalent to a
2022 // mask and compare operation.
2023 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002024 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002025 new_common_bits = ~SmearBitsRight(new_common_bits);
2026 common_bits &= new_common_bits;
2027 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002028 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002029 common_bits ^= differing_bits;
2030 bits &= common_bits;
2031 }
2032 pos->mask = common_bits;
2033 pos->value = bits;
2034 }
2035 characters_filled_in++;
2036 ASSERT(characters_filled_in <= details->characters());
2037 if (characters_filled_in == details->characters()) {
2038 return;
2039 }
2040 }
2041 }
2042 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00002043 on_success()-> GetQuickCheckDetails(details,
2044 compiler,
2045 characters_filled_in,
2046 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002047}
2048
2049
2050void QuickCheckDetails::Clear() {
2051 for (int i = 0; i < characters_; i++) {
2052 positions_[i].mask = 0;
2053 positions_[i].value = 0;
2054 positions_[i].determines_perfectly = false;
2055 }
2056 characters_ = 0;
2057}
2058
2059
2060void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002061 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002062 if (by >= characters_) {
2063 Clear();
2064 return;
2065 }
2066 for (int i = 0; i < characters_ - by; i++) {
2067 positions_[i] = positions_[by + i];
2068 }
2069 for (int i = characters_ - by; i < characters_; i++) {
2070 positions_[i].mask = 0;
2071 positions_[i].value = 0;
2072 positions_[i].determines_perfectly = false;
2073 }
2074 characters_ -= by;
2075 // We could change mask_ and value_ here but we would never advance unless
2076 // they had already been used in a check and they won't be used again because
2077 // it would gain us nothing. So there's no point.
2078}
2079
2080
2081void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2082 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002083 if (other->cannot_match_) {
2084 return;
2085 }
2086 if (cannot_match_) {
2087 *this = *other;
2088 return;
2089 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002090 for (int i = from_index; i < characters_; i++) {
2091 QuickCheckDetails::Position* pos = positions(i);
2092 QuickCheckDetails::Position* other_pos = other->positions(i);
2093 if (pos->mask != other_pos->mask ||
2094 pos->value != other_pos->value ||
2095 !other_pos->determines_perfectly) {
2096 // Our mask-compare operation will be approximate unless we have the
2097 // exact same operation on both sides of the alternation.
2098 pos->determines_perfectly = false;
2099 }
2100 pos->mask &= other_pos->mask;
2101 pos->value &= pos->mask;
2102 other_pos->value &= pos->mask;
2103 uc16 differing_bits = (pos->value ^ other_pos->value);
2104 pos->mask &= ~differing_bits;
2105 pos->value &= pos->mask;
2106 }
2107}
2108
2109
ager@chromium.org32912102009-01-16 10:38:43 +00002110class VisitMarker {
2111 public:
2112 explicit VisitMarker(NodeInfo* info) : info_(info) {
2113 ASSERT(!info->visited);
2114 info->visited = true;
2115 }
2116 ~VisitMarker() {
2117 info_->visited = false;
2118 }
2119 private:
2120 NodeInfo* info_;
2121};
2122
2123
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002124void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2125 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002126 int characters_filled_in,
2127 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002128 if (body_can_be_zero_length_ || info()->visited) return;
2129 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002130 return ChoiceNode::GetQuickCheckDetails(details,
2131 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002132 characters_filled_in,
2133 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002134}
2135
2136
2137void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2138 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002139 int characters_filled_in,
2140 bool not_at_start) {
2141 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002142 int choice_count = alternatives_->length();
2143 ASSERT(choice_count > 0);
2144 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2145 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002146 characters_filled_in,
2147 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002148 for (int i = 1; i < choice_count; i++) {
2149 QuickCheckDetails new_details(details->characters());
2150 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002151 node->GetQuickCheckDetails(&new_details, compiler,
2152 characters_filled_in,
2153 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002154 // Here we merge the quick match details of the two branches.
2155 details->Merge(&new_details, characters_filled_in);
2156 }
2157}
2158
2159
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002160// Check for [0-9A-Z_a-z].
2161static void EmitWordCheck(RegExpMacroAssembler* assembler,
2162 Label* word,
2163 Label* non_word,
2164 bool fall_through_on_word) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002165 if (assembler->CheckSpecialCharacterClass(
2166 fall_through_on_word ? 'w' : 'W',
2167 fall_through_on_word ? non_word : word)) {
2168 // Optimized implementation available.
2169 return;
2170 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002171 assembler->CheckCharacterGT('z', non_word);
2172 assembler->CheckCharacterLT('0', non_word);
2173 assembler->CheckCharacterGT('a' - 1, word);
2174 assembler->CheckCharacterLT('9' + 1, word);
2175 assembler->CheckCharacterLT('A', non_word);
2176 assembler->CheckCharacterLT('Z' + 1, word);
2177 if (fall_through_on_word) {
2178 assembler->CheckNotCharacter('_', non_word);
2179 } else {
2180 assembler->CheckCharacter('_', word);
2181 }
2182}
2183
2184
2185// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2186// that matches newline or the start of input).
2187static void EmitHat(RegExpCompiler* compiler,
2188 RegExpNode* on_success,
2189 Trace* trace) {
2190 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2191 // We will be loading the previous character into the current character
2192 // register.
2193 Trace new_trace(*trace);
2194 new_trace.InvalidateCurrentCharacter();
2195
2196 Label ok;
2197 if (new_trace.cp_offset() == 0) {
2198 // The start of input counts as a newline in this context, so skip to
2199 // ok if we are at the start.
2200 assembler->CheckAtStart(&ok);
2201 }
2202 // We already checked that we are not at the start of input so it must be
2203 // OK to load the previous character.
2204 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2205 new_trace.backtrack(),
2206 false);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002207 if (!assembler->CheckSpecialCharacterClass('n',
2208 new_trace.backtrack())) {
2209 // Newline means \n, \r, 0x2028 or 0x2029.
2210 if (!compiler->ascii()) {
2211 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2212 }
2213 assembler->CheckCharacter('\n', &ok);
2214 assembler->CheckNotCharacter('\r', new_trace.backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002215 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002216 assembler->Bind(&ok);
2217 on_success->Emit(compiler, &new_trace);
2218}
2219
2220
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002221// Emit the code to handle \b and \B (word-boundary or non-word-boundary)
2222// when we know whether the next character must be a word character or not.
2223static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type,
2224 RegExpCompiler* compiler,
2225 RegExpNode* on_success,
2226 Trace* trace) {
2227 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2228 Label done;
2229
2230 Trace new_trace(*trace);
2231
2232 bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER);
2233 Label* on_word = expect_word_character ? &done : new_trace.backtrack();
2234 Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done;
2235
2236 // Check whether previous character was a word character.
2237 switch (trace->at_start()) {
2238 case Trace::TRUE:
2239 if (expect_word_character) {
2240 assembler->GoTo(on_non_word);
2241 }
2242 break;
2243 case Trace::UNKNOWN:
2244 ASSERT_EQ(0, trace->cp_offset());
2245 assembler->CheckAtStart(on_non_word);
2246 // Fall through.
2247 case Trace::FALSE:
2248 int prev_char_offset = trace->cp_offset() - 1;
2249 assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1);
2250 EmitWordCheck(assembler, on_word, on_non_word, expect_word_character);
2251 // We may or may not have loaded the previous character.
2252 new_trace.InvalidateCurrentCharacter();
2253 }
2254
2255 assembler->Bind(&done);
2256
2257 on_success->Emit(compiler, &new_trace);
2258}
2259
2260
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002261// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2262static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2263 RegExpCompiler* compiler,
2264 RegExpNode* on_success,
2265 Trace* trace) {
2266 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2267 Label before_non_word;
2268 Label before_word;
2269 if (trace->characters_preloaded() != 1) {
2270 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2271 }
2272 // Fall through on non-word.
2273 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2274
2275 // We will be loading the previous character into the current character
2276 // register.
2277 Trace new_trace(*trace);
2278 new_trace.InvalidateCurrentCharacter();
2279
2280 Label ok;
2281 Label* boundary;
2282 Label* not_boundary;
2283 if (type == AssertionNode::AT_BOUNDARY) {
2284 boundary = &ok;
2285 not_boundary = new_trace.backtrack();
2286 } else {
2287 not_boundary = &ok;
2288 boundary = new_trace.backtrack();
2289 }
2290
2291 // Next character is not a word character.
2292 assembler->Bind(&before_non_word);
2293 if (new_trace.cp_offset() == 0) {
2294 // The start of input counts as a non-word character, so the question is
2295 // decided if we are at the start.
2296 assembler->CheckAtStart(not_boundary);
2297 }
2298 // We already checked that we are not at the start of input so it must be
2299 // OK to load the previous character.
2300 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2301 &ok, // Unused dummy label in this call.
2302 false);
2303 // Fall through on non-word.
2304 EmitWordCheck(assembler, boundary, not_boundary, false);
2305 assembler->GoTo(not_boundary);
2306
2307 // Next character is a word character.
2308 assembler->Bind(&before_word);
2309 if (new_trace.cp_offset() == 0) {
2310 // The start of input counts as a non-word character, so the question is
2311 // decided if we are at the start.
2312 assembler->CheckAtStart(boundary);
2313 }
2314 // We already checked that we are not at the start of input so it must be
2315 // OK to load the previous character.
2316 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2317 &ok, // Unused dummy label in this call.
2318 false);
2319 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2320 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2321
2322 assembler->Bind(&ok);
2323
2324 on_success->Emit(compiler, &new_trace);
2325}
2326
2327
iposva@chromium.org245aa852009-02-10 00:49:54 +00002328void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2329 RegExpCompiler* compiler,
2330 int filled_in,
2331 bool not_at_start) {
2332 if (type_ == AT_START && not_at_start) {
2333 details->set_cannot_match();
2334 return;
2335 }
2336 return on_success()->GetQuickCheckDetails(details,
2337 compiler,
2338 filled_in,
2339 not_at_start);
2340}
2341
2342
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002343void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2344 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2345 switch (type_) {
2346 case AT_END: {
2347 Label ok;
2348 assembler->CheckPosition(trace->cp_offset(), &ok);
2349 assembler->GoTo(trace->backtrack());
2350 assembler->Bind(&ok);
2351 break;
2352 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002353 case AT_START: {
2354 if (trace->at_start() == Trace::FALSE) {
2355 assembler->GoTo(trace->backtrack());
2356 return;
2357 }
2358 if (trace->at_start() == Trace::UNKNOWN) {
2359 assembler->CheckNotAtStart(trace->backtrack());
2360 Trace at_start_trace = *trace;
2361 at_start_trace.set_at_start(true);
2362 on_success()->Emit(compiler, &at_start_trace);
2363 return;
2364 }
2365 }
2366 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002367 case AFTER_NEWLINE:
2368 EmitHat(compiler, on_success(), trace);
2369 return;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002370 case AT_BOUNDARY:
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002371 case AT_NON_BOUNDARY: {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002372 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2373 return;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002374 }
2375 case AFTER_WORD_CHARACTER:
2376 case AFTER_NONWORD_CHARACTER: {
2377 EmitHalfBoundaryCheck(type_, compiler, on_success(), trace);
2378 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002379 }
2380 on_success()->Emit(compiler, trace);
2381}
2382
2383
ager@chromium.org381abbb2009-02-25 13:23:22 +00002384static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2385 if (quick_check == NULL) return false;
2386 if (offset >= quick_check->characters()) return false;
2387 return quick_check->positions(offset)->determines_perfectly;
2388}
2389
2390
2391static void UpdateBoundsCheck(int index, int* checked_up_to) {
2392 if (index > *checked_up_to) {
2393 *checked_up_to = index;
2394 }
2395}
2396
2397
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002398// We call this repeatedly to generate code for each pass over the text node.
2399// The passes are in increasing order of difficulty because we hope one
2400// of the first passes will fail in which case we are saved the work of the
2401// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2402// we will check the '%' in the first pass, the case independent 'a' in the
2403// second pass and the character class in the last pass.
2404//
2405// The passes are done from right to left, so for example to test for /bar/
2406// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2407// and then a 'b' with offset 0. This means we can avoid the end-of-input
2408// bounds check most of the time. In the example we only need to check for
2409// end-of-input when loading the putative 'r'.
2410//
2411// A slight complication involves the fact that the first character may already
2412// be fetched into a register by the previous node. In this case we want to
2413// do the test for that character first. We do this in separate passes. The
2414// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2415// pass has been performed then subsequent passes will have true in
2416// first_element_checked to indicate that that character does not need to be
2417// checked again.
2418//
ager@chromium.org32912102009-01-16 10:38:43 +00002419// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002420// contain an AlternativeGeneration object. In this AlternativeGeneration
2421// object we can see details of any quick check that was already passed in
2422// order to get to the code we are now generating. The quick check can involve
2423// loading characters, which means we do not need to recheck the bounds
2424// up to the limit the quick check already checked. In addition the quick
2425// check can have involved a mask and compare operation which may simplify
2426// or obviate the need for further checks at some character positions.
2427void TextNode::TextEmitPass(RegExpCompiler* compiler,
2428 TextEmitPassType pass,
2429 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002430 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002431 bool first_element_checked,
2432 int* checked_up_to) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002433 Isolate* isolate = Isolate::Current();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002434 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2435 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002436 Label* backtrack = trace->backtrack();
2437 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002438 int element_count = elms_->length();
2439 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2440 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002441 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002442 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002443 Vector<const uc16> quarks = elm.data.u_atom->data();
2444 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2445 if (first_element_checked && i == 0 && j == 0) continue;
2446 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2447 EmitCharacterFunction* emit_function = NULL;
2448 switch (pass) {
2449 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002450 ASSERT(ascii);
2451 if (quarks[j] > String::kMaxAsciiCharCode) {
2452 assembler->GoTo(backtrack);
2453 return;
2454 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002455 break;
2456 case NON_LETTER_CHARACTER_MATCH:
2457 emit_function = &EmitAtomNonLetter;
2458 break;
2459 case SIMPLE_CHARACTER_MATCH:
2460 emit_function = &EmitSimpleCharacter;
2461 break;
2462 case CASE_CHARACTER_MATCH:
2463 emit_function = &EmitAtomLetter;
2464 break;
2465 default:
2466 break;
2467 }
2468 if (emit_function != NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002469 bool bound_checked = emit_function(isolate,
2470 compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002471 quarks[j],
2472 backtrack,
2473 cp_offset + j,
2474 *checked_up_to < cp_offset + j,
2475 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002476 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002477 }
2478 }
2479 } else {
2480 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002481 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002482 if (first_element_checked && i == 0) continue;
2483 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002484 RegExpCharacterClass* cc = elm.data.u_char_class;
2485 EmitCharClass(assembler,
2486 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002487 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002488 backtrack,
2489 cp_offset,
2490 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002491 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002492 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002493 }
2494 }
2495 }
2496}
2497
2498
2499int TextNode::Length() {
2500 TextElement elm = elms_->last();
2501 ASSERT(elm.cp_offset >= 0);
2502 if (elm.type == TextElement::ATOM) {
2503 return elm.cp_offset + elm.data.u_atom->data().length();
2504 } else {
2505 return elm.cp_offset + 1;
2506 }
2507}
2508
2509
ager@chromium.org381abbb2009-02-25 13:23:22 +00002510bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2511 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2512 if (ignore_case) {
2513 return pass == SIMPLE_CHARACTER_MATCH;
2514 } else {
2515 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2516 }
2517}
2518
2519
ager@chromium.org8bb60582008-12-11 12:02:20 +00002520// This generates the code to match a text node. A text node can contain
2521// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002522// way) and character classes. For efficiency we do not do this in a single
2523// pass from left to right. Instead we pass over the text node several times,
2524// emitting code for some character positions every time. See the comment on
2525// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002526void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002527 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002528 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002529 ASSERT(limit_result == CONTINUE);
2530
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002531 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2532 compiler->SetRegExpTooBig();
2533 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002534 }
2535
2536 if (compiler->ascii()) {
2537 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002538 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002539 }
2540
2541 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002542 int bound_checked_to = trace->cp_offset() - 1;
2543 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002544
2545 // If a character is preloaded into the current character register then
2546 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002547 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002548 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2549 if (!SkipPass(pass, compiler->ignore_case())) {
2550 TextEmitPass(compiler,
2551 static_cast<TextEmitPassType>(pass),
2552 true,
2553 trace,
2554 false,
2555 &bound_checked_to);
2556 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002557 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002558 first_elt_done = true;
2559 }
2560
ager@chromium.org381abbb2009-02-25 13:23:22 +00002561 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2562 if (!SkipPass(pass, compiler->ignore_case())) {
2563 TextEmitPass(compiler,
2564 static_cast<TextEmitPassType>(pass),
2565 false,
2566 trace,
2567 first_elt_done,
2568 &bound_checked_to);
2569 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002570 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002571
ager@chromium.org32912102009-01-16 10:38:43 +00002572 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002573 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002574 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002575 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002576 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002577}
2578
2579
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002580void Trace::InvalidateCurrentCharacter() {
2581 characters_preloaded_ = 0;
2582}
2583
2584
2585void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002586 ASSERT(by > 0);
2587 // We don't have an instruction for shifting the current character register
2588 // down or for using a shifted value for anything so lets just forget that
2589 // we preloaded any characters into it.
2590 characters_preloaded_ = 0;
2591 // Adjust the offsets of the quick check performed information. This
2592 // information is used to find out what we already determined about the
2593 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002594 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002595 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002596 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2597 compiler->SetRegExpTooBig();
2598 cp_offset_ = 0;
2599 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002600 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002601}
2602
2603
ager@chromium.org38e4c712009-11-11 09:11:58 +00002604void TextNode::MakeCaseIndependent(bool is_ascii) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002605 int element_count = elms_->length();
2606 for (int i = 0; i < element_count; i++) {
2607 TextElement elm = elms_->at(i);
2608 if (elm.type == TextElement::CHAR_CLASS) {
2609 RegExpCharacterClass* cc = elm.data.u_char_class;
ager@chromium.org38e4c712009-11-11 09:11:58 +00002610 // None of the standard character classses is different in the case
2611 // independent case and it slows us down if we don't know that.
2612 if (cc->is_standard()) continue;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002613 ZoneList<CharacterRange>* ranges = cc->ranges();
2614 int range_count = ranges->length();
ager@chromium.org38e4c712009-11-11 09:11:58 +00002615 for (int j = 0; j < range_count; j++) {
2616 ranges->at(j).AddCaseEquivalents(ranges, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002617 }
2618 }
2619 }
2620}
2621
2622
ager@chromium.org8bb60582008-12-11 12:02:20 +00002623int TextNode::GreedyLoopTextLength() {
2624 TextElement elm = elms_->at(elms_->length() - 1);
2625 if (elm.type == TextElement::CHAR_CLASS) {
2626 return elm.cp_offset + 1;
2627 } else {
2628 return elm.cp_offset + elm.data.u_atom->data().length();
2629 }
2630}
2631
2632
2633// Finds the fixed match length of a sequence of nodes that goes from
2634// this alternative and back to this choice node. If there are variable
2635// length nodes or other complications in the way then return a sentinel
2636// value indicating that a greedy loop cannot be constructed.
2637int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2638 int length = 0;
2639 RegExpNode* node = alternative->node();
2640 // Later we will generate code for all these text nodes using recursion
2641 // so we have to limit the max number.
2642 int recursion_depth = 0;
2643 while (node != this) {
2644 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2645 return kNodeIsTooComplexForGreedyLoops;
2646 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002647 int node_length = node->GreedyLoopTextLength();
2648 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2649 return kNodeIsTooComplexForGreedyLoops;
2650 }
2651 length += node_length;
2652 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2653 node = seq_node->on_success();
2654 }
2655 return length;
2656}
2657
2658
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002659void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2660 ASSERT_EQ(loop_node_, NULL);
2661 AddAlternative(alt);
2662 loop_node_ = alt.node();
2663}
2664
2665
2666void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2667 ASSERT_EQ(continue_node_, NULL);
2668 AddAlternative(alt);
2669 continue_node_ = alt.node();
2670}
2671
2672
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002673void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002674 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002675 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002676 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2677 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2678 // Update the counter-based backtracking info on the stack. This is an
2679 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002680 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002681 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002682 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002683 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002684 }
ager@chromium.org32912102009-01-16 10:38:43 +00002685 ASSERT(trace->stop_node() == NULL);
2686 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002687 trace->Flush(compiler, this);
2688 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002689 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002690 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002691}
2692
2693
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002694int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
2695 bool not_at_start) {
2696 int preload_characters = EatsAtLeast(4, 0, not_at_start);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002697 if (compiler->macro_assembler()->CanReadUnaligned()) {
2698 bool ascii = compiler->ascii();
2699 if (ascii) {
2700 if (preload_characters > 4) preload_characters = 4;
2701 // We can't preload 3 characters because there is no machine instruction
2702 // to do that. We can't just load 4 because we could be reading
2703 // beyond the end of the string, which could cause a memory fault.
2704 if (preload_characters == 3) preload_characters = 2;
2705 } else {
2706 if (preload_characters > 2) preload_characters = 2;
2707 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002708 } else {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002709 if (preload_characters > 1) preload_characters = 1;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002710 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002711 return preload_characters;
2712}
2713
2714
2715// This class is used when generating the alternatives in a choice node. It
2716// records the way the alternative is being code generated.
2717class AlternativeGeneration: public Malloced {
2718 public:
2719 AlternativeGeneration()
2720 : possible_success(),
2721 expects_preload(false),
2722 after(),
2723 quick_check_details() { }
2724 Label possible_success;
2725 bool expects_preload;
2726 Label after;
2727 QuickCheckDetails quick_check_details;
2728};
2729
2730
2731// Creates a list of AlternativeGenerations. If the list has a reasonable
2732// size then it is on the stack, otherwise the excess is on the heap.
2733class AlternativeGenerationList {
2734 public:
2735 explicit AlternativeGenerationList(int count)
2736 : alt_gens_(count) {
2737 for (int i = 0; i < count && i < kAFew; i++) {
2738 alt_gens_.Add(a_few_alt_gens_ + i);
2739 }
2740 for (int i = kAFew; i < count; i++) {
2741 alt_gens_.Add(new AlternativeGeneration());
2742 }
2743 }
2744 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002745 for (int i = kAFew; i < alt_gens_.length(); i++) {
2746 delete alt_gens_[i];
2747 alt_gens_[i] = NULL;
2748 }
2749 }
2750
2751 AlternativeGeneration* at(int i) {
2752 return alt_gens_[i];
2753 }
2754 private:
2755 static const int kAFew = 10;
2756 ZoneList<AlternativeGeneration*> alt_gens_;
2757 AlternativeGeneration a_few_alt_gens_[kAFew];
2758};
2759
2760
2761/* Code generation for choice nodes.
2762 *
2763 * We generate quick checks that do a mask and compare to eliminate a
2764 * choice. If the quick check succeeds then it jumps to the continuation to
2765 * do slow checks and check subsequent nodes. If it fails (the common case)
2766 * it falls through to the next choice.
2767 *
2768 * Here is the desired flow graph. Nodes directly below each other imply
2769 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2770 * 3 doesn't have a quick check so we have to call the slow check.
2771 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2772 * regexp continuation is generated directly after the Sn node, up to the
2773 * next GoTo if we decide to reuse some already generated code. Some
2774 * nodes expect preload_characters to be preloaded into the current
2775 * character register. R nodes do this preloading. Vertices are marked
2776 * F for failures and S for success (possible success in the case of quick
2777 * nodes). L, V, < and > are used as arrow heads.
2778 *
2779 * ----------> R
2780 * |
2781 * V
2782 * Q1 -----> S1
2783 * | S /
2784 * F| /
2785 * | F/
2786 * | /
2787 * | R
2788 * | /
2789 * V L
2790 * Q2 -----> S2
2791 * | S /
2792 * F| /
2793 * | F/
2794 * | /
2795 * | R
2796 * | /
2797 * V L
2798 * S3
2799 * |
2800 * F|
2801 * |
2802 * R
2803 * |
2804 * backtrack V
2805 * <----------Q4
2806 * \ F |
2807 * \ |S
2808 * \ F V
2809 * \-----S4
2810 *
2811 * For greedy loops we reverse our expectation and expect to match rather
2812 * than fail. Therefore we want the loop code to look like this (U is the
2813 * unwind code that steps back in the greedy loop). The following alternatives
2814 * look the same as above.
2815 * _____
2816 * / \
2817 * V |
2818 * ----------> S1 |
2819 * /| |
2820 * / |S |
2821 * F/ \_____/
2822 * /
2823 * |<-----------
2824 * | \
2825 * V \
2826 * Q2 ---> S2 \
2827 * | S / |
2828 * F| / |
2829 * | F/ |
2830 * | / |
2831 * | R |
2832 * | / |
2833 * F VL |
2834 * <------U |
2835 * back |S |
2836 * \______________/
2837 */
2838
2839
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002840void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002841 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2842 int choice_count = alternatives_->length();
2843#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002844 for (int i = 0; i < choice_count - 1; i++) {
2845 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002846 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002847 int guard_count = (guards == NULL) ? 0 : guards->length();
2848 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002849 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002850 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002851 }
2852#endif
2853
ager@chromium.org32912102009-01-16 10:38:43 +00002854 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002855 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002856 ASSERT(limit_result == CONTINUE);
2857
ager@chromium.org381abbb2009-02-25 13:23:22 +00002858 int new_flush_budget = trace->flush_budget() / choice_count;
2859 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2860 trace->Flush(compiler, this);
2861 return;
2862 }
2863
ager@chromium.org8bb60582008-12-11 12:02:20 +00002864 RecursionCheck rc(compiler);
2865
ager@chromium.org32912102009-01-16 10:38:43 +00002866 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002867
2868 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2869 bool greedy_loop = false;
2870 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002871 Trace counter_backtrack_trace;
2872 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002873 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2874
ager@chromium.org8bb60582008-12-11 12:02:20 +00002875 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2876 // Here we have special handling for greedy loops containing only text nodes
2877 // and other simple nodes. These are handled by pushing the current
2878 // position on the stack and then incrementing the current position each
2879 // time around the switch. On backtrack we decrement the current position
2880 // and check it against the pushed value. This avoids pushing backtrack
2881 // information for each iteration of the loop, which could take up a lot of
2882 // space.
2883 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002884 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002885 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002886 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002887 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002888 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002889 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002890 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002891 Label loop_label;
2892 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002893 greedy_match_trace.set_stop_node(this);
2894 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002895 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002896 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002897 }
2898
2899 Label second_choice; // For use in greedy matches.
2900 macro_assembler->Bind(&second_choice);
2901
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002902 int first_normal_choice = greedy_loop ? 1 : 0;
2903
kasperl@chromium.orga5551262010-12-07 12:49:48 +00002904 int preload_characters =
2905 CalculatePreloadCharacters(compiler,
2906 current_trace->at_start() == Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002907 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002908 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002909 bool preload_has_checked_bounds = preload_is_current;
2910
2911 AlternativeGenerationList alt_gens(choice_count);
2912
ager@chromium.org8bb60582008-12-11 12:02:20 +00002913 // For now we just call all choices one after the other. The idea ultimately
2914 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002915 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002916 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002917 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002918 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002919 ZoneList<Guard*>* guards = alternative.guards();
2920 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002921 Trace new_trace(*current_trace);
2922 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002923 preload_characters :
2924 0);
2925 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002926 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002927 }
ager@chromium.org32912102009-01-16 10:38:43 +00002928 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002929 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002930 alt_gen->expects_preload = preload_is_current;
2931 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002932 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002933 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002934 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002935 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002936 preload_has_checked_bounds,
2937 &alt_gen->possible_success,
2938 &alt_gen->quick_check_details,
2939 i < choice_count - 1)) {
2940 // Quick check was generated for this choice.
2941 preload_is_current = true;
2942 preload_has_checked_bounds = true;
2943 // On the last choice in the ChoiceNode we generated the quick
2944 // check to fall through on possible success. So now we need to
2945 // generate the full check inline.
2946 if (i == choice_count - 1) {
2947 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002948 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2949 new_trace.set_characters_preloaded(preload_characters);
2950 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002951 generate_full_check_inline = true;
2952 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002953 } else if (alt_gen->quick_check_details.cannot_match()) {
2954 if (i == choice_count - 1 && !greedy_loop) {
2955 macro_assembler->GoTo(trace->backtrack());
2956 }
2957 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002958 } else {
2959 // No quick check was generated. Put the full code here.
2960 // If this is not the first choice then there could be slow checks from
2961 // previous cases that go here when they fail. There's no reason to
2962 // insist that they preload characters since the slow check we are about
2963 // to generate probably can't use it.
2964 if (i != first_normal_choice) {
2965 alt_gen->expects_preload = false;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002966 new_trace.InvalidateCurrentCharacter();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002967 }
2968 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002969 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002970 }
2971 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002972 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002973 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002974 if (new_trace.actions() != NULL) {
2975 new_trace.set_flush_budget(new_flush_budget);
2976 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002977 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002978 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002979 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002980 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002981 preload_is_current = false;
2982 }
2983 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002984 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002985 if (greedy_loop) {
2986 macro_assembler->Bind(&greedy_loop_label);
2987 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002988 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002989 // Otherwise try the second priority at an earlier position.
2990 macro_assembler->AdvanceCurrentPosition(-text_length);
2991 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002992 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002993
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002994 // At this point we need to generate slow checks for the alternatives where
2995 // the quick check was inlined. We can recognize these because the associated
2996 // label was bound.
2997 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2998 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002999 Trace new_trace(*current_trace);
3000 // If there are actions to be flushed we have to limit how many times
3001 // they are flushed. Take the budget of the parent trace and distribute
3002 // it fairly amongst the children.
3003 if (new_trace.actions() != NULL) {
3004 new_trace.set_flush_budget(new_flush_budget);
3005 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003006 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00003007 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003008 alternatives_->at(i),
3009 alt_gen,
3010 preload_characters,
3011 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003012 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003013}
3014
3015
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003016void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00003017 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003018 GuardedAlternative alternative,
3019 AlternativeGeneration* alt_gen,
3020 int preload_characters,
3021 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003022 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003023
3024 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3025 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00003026 Trace out_of_line_trace(*trace);
3027 out_of_line_trace.set_characters_preloaded(preload_characters);
3028 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003029 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003030 ZoneList<Guard*>* guards = alternative.guards();
3031 int guard_count = (guards == NULL) ? 0 : guards->length();
3032 if (next_expects_preload) {
3033 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00003034 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003035 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003036 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003037 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003038 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003039 macro_assembler->Bind(&reload_current_char);
3040 // Reload the current character, since the next quick check expects that.
3041 // We don't need to check bounds here because we only get into this
3042 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00003043 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003044 NULL,
3045 false,
3046 preload_characters);
3047 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003048 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00003049 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003050 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00003051 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003052 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003053 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003054 }
3055}
3056
3057
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003058void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003059 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003060 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003061 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003062 ASSERT(limit_result == CONTINUE);
3063
3064 RecursionCheck rc(compiler);
3065
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003066 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003067 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00003068 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003069 new_capture(data_.u_position_register.reg,
3070 data_.u_position_register.is_capture,
3071 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003072 Trace new_trace = *trace;
3073 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003074 on_success()->Emit(compiler, &new_trace);
3075 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003076 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003077 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003078 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003079 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00003080 Trace new_trace = *trace;
3081 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003082 on_success()->Emit(compiler, &new_trace);
3083 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003084 }
3085 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00003086 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00003087 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00003088 Trace new_trace = *trace;
3089 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003090 on_success()->Emit(compiler, &new_trace);
3091 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003092 }
3093 case CLEAR_CAPTURES: {
3094 Trace::DeferredClearCaptures
3095 new_capture(Interval(data_.u_clear_captures.range_from,
3096 data_.u_clear_captures.range_to));
3097 Trace new_trace = *trace;
3098 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003099 on_success()->Emit(compiler, &new_trace);
3100 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003101 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003102 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003103 if (!trace->is_trivial()) {
3104 trace->Flush(compiler, this);
3105 } else {
3106 assembler->WriteCurrentPositionToRegister(
3107 data_.u_submatch.current_position_register, 0);
3108 assembler->WriteStackPointerToRegister(
3109 data_.u_submatch.stack_pointer_register);
3110 on_success()->Emit(compiler, trace);
3111 }
3112 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003113 case EMPTY_MATCH_CHECK: {
3114 int start_pos_reg = data_.u_empty_match_check.start_register;
3115 int stored_pos = 0;
3116 int rep_reg = data_.u_empty_match_check.repetition_register;
3117 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
3118 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
3119 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
3120 // If we know we haven't advanced and there is no minimum we
3121 // can just backtrack immediately.
3122 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00003123 } else if (know_dist && stored_pos < trace->cp_offset()) {
3124 // If we know we've advanced we can generate the continuation
3125 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003126 on_success()->Emit(compiler, trace);
3127 } else if (!trace->is_trivial()) {
3128 trace->Flush(compiler, this);
3129 } else {
3130 Label skip_empty_check;
3131 // If we have a minimum number of repetitions we check the current
3132 // number first and skip the empty check if it's not enough.
3133 if (has_minimum) {
3134 int limit = data_.u_empty_match_check.repetition_limit;
3135 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
3136 }
3137 // If the match is empty we bail out, otherwise we fall through
3138 // to the on-success continuation.
3139 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
3140 trace->backtrack());
3141 assembler->Bind(&skip_empty_check);
3142 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00003143 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003144 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003145 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003146 case POSITIVE_SUBMATCH_SUCCESS: {
3147 if (!trace->is_trivial()) {
3148 trace->Flush(compiler, this);
3149 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003150 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003151 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00003152 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003153 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003154 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003155 int clear_register_count = data_.u_submatch.clear_register_count;
3156 if (clear_register_count == 0) {
3157 on_success()->Emit(compiler, trace);
3158 return;
3159 }
3160 int clear_registers_from = data_.u_submatch.clear_register_from;
3161 Label clear_registers_backtrack;
3162 Trace new_trace = *trace;
3163 new_trace.set_backtrack(&clear_registers_backtrack);
3164 on_success()->Emit(compiler, &new_trace);
3165
3166 assembler->Bind(&clear_registers_backtrack);
3167 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3168 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3169
3170 ASSERT(trace->backtrack() == NULL);
3171 assembler->Backtrack();
3172 return;
3173 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003174 default:
3175 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003176 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003177}
3178
3179
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003180void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003181 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003182 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003183 trace->Flush(compiler, this);
3184 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003185 }
3186
ager@chromium.org32912102009-01-16 10:38:43 +00003187 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003188 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003189 ASSERT(limit_result == CONTINUE);
3190
3191 RecursionCheck rc(compiler);
3192
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003193 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003194 if (compiler->ignore_case()) {
3195 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3196 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003197 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003198 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003199 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003200 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003201}
3202
3203
3204// -------------------------------------------------------------------
3205// Dot/dotty output
3206
3207
3208#ifdef DEBUG
3209
3210
3211class DotPrinter: public NodeVisitor {
3212 public:
3213 explicit DotPrinter(bool ignore_case)
3214 : ignore_case_(ignore_case),
3215 stream_(&alloc_) { }
3216 void PrintNode(const char* label, RegExpNode* node);
3217 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003218 void PrintAttributes(RegExpNode* from);
3219 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003220 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003221#define DECLARE_VISIT(Type) \
3222 virtual void Visit##Type(Type##Node* that);
3223FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3224#undef DECLARE_VISIT
3225 private:
3226 bool ignore_case_;
3227 HeapStringAllocator alloc_;
3228 StringStream stream_;
3229};
3230
3231
3232void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3233 stream()->Add("digraph G {\n graph [label=\"");
3234 for (int i = 0; label[i]; i++) {
3235 switch (label[i]) {
3236 case '\\':
3237 stream()->Add("\\\\");
3238 break;
3239 case '"':
3240 stream()->Add("\"");
3241 break;
3242 default:
3243 stream()->Put(label[i]);
3244 break;
3245 }
3246 }
3247 stream()->Add("\"];\n");
3248 Visit(node);
3249 stream()->Add("}\n");
3250 printf("%s", *(stream()->ToCString()));
3251}
3252
3253
3254void DotPrinter::Visit(RegExpNode* node) {
3255 if (node->info()->visited) return;
3256 node->info()->visited = true;
3257 node->Accept(this);
3258}
3259
3260
3261void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003262 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3263 Visit(on_failure);
3264}
3265
3266
3267class TableEntryBodyPrinter {
3268 public:
3269 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3270 : stream_(stream), choice_(choice) { }
3271 void Call(uc16 from, DispatchTable::Entry entry) {
3272 OutSet* out_set = entry.out_set();
3273 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3274 if (out_set->Get(i)) {
3275 stream()->Add(" n%p:s%io%i -> n%p;\n",
3276 choice(),
3277 from,
3278 i,
3279 choice()->alternatives()->at(i).node());
3280 }
3281 }
3282 }
3283 private:
3284 StringStream* stream() { return stream_; }
3285 ChoiceNode* choice() { return choice_; }
3286 StringStream* stream_;
3287 ChoiceNode* choice_;
3288};
3289
3290
3291class TableEntryHeaderPrinter {
3292 public:
3293 explicit TableEntryHeaderPrinter(StringStream* stream)
3294 : first_(true), stream_(stream) { }
3295 void Call(uc16 from, DispatchTable::Entry entry) {
3296 if (first_) {
3297 first_ = false;
3298 } else {
3299 stream()->Add("|");
3300 }
3301 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3302 OutSet* out_set = entry.out_set();
3303 int priority = 0;
3304 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3305 if (out_set->Get(i)) {
3306 if (priority > 0) stream()->Add("|");
3307 stream()->Add("<s%io%i> %i", from, i, priority);
3308 priority++;
3309 }
3310 }
3311 stream()->Add("}}");
3312 }
3313 private:
3314 bool first_;
3315 StringStream* stream() { return stream_; }
3316 StringStream* stream_;
3317};
3318
3319
3320class AttributePrinter {
3321 public:
3322 explicit AttributePrinter(DotPrinter* out)
3323 : out_(out), first_(true) { }
3324 void PrintSeparator() {
3325 if (first_) {
3326 first_ = false;
3327 } else {
3328 out_->stream()->Add("|");
3329 }
3330 }
3331 void PrintBit(const char* name, bool value) {
3332 if (!value) return;
3333 PrintSeparator();
3334 out_->stream()->Add("{%s}", name);
3335 }
3336 void PrintPositive(const char* name, int value) {
3337 if (value < 0) return;
3338 PrintSeparator();
3339 out_->stream()->Add("{%s|%x}", name, value);
3340 }
3341 private:
3342 DotPrinter* out_;
3343 bool first_;
3344};
3345
3346
3347void DotPrinter::PrintAttributes(RegExpNode* that) {
3348 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3349 "margin=0.1, fontsize=10, label=\"{",
3350 that);
3351 AttributePrinter printer(this);
3352 NodeInfo* info = that->info();
3353 printer.PrintBit("NI", info->follows_newline_interest);
3354 printer.PrintBit("WI", info->follows_word_interest);
3355 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003356 Label* label = that->label();
3357 if (label->is_bound())
3358 printer.PrintPositive("@", label->pos());
3359 stream()->Add("}\"];\n");
3360 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3361 "arrowhead=none];\n", that, that);
3362}
3363
3364
3365static const bool kPrintDispatchTable = false;
3366void DotPrinter::VisitChoice(ChoiceNode* that) {
3367 if (kPrintDispatchTable) {
3368 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3369 TableEntryHeaderPrinter header_printer(stream());
3370 that->GetTable(ignore_case_)->ForEach(&header_printer);
3371 stream()->Add("\"]\n", that);
3372 PrintAttributes(that);
3373 TableEntryBodyPrinter body_printer(stream(), that);
3374 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003375 } else {
3376 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3377 for (int i = 0; i < that->alternatives()->length(); i++) {
3378 GuardedAlternative alt = that->alternatives()->at(i);
3379 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3380 }
3381 }
3382 for (int i = 0; i < that->alternatives()->length(); i++) {
3383 GuardedAlternative alt = that->alternatives()->at(i);
3384 alt.node()->Accept(this);
3385 }
3386}
3387
3388
3389void DotPrinter::VisitText(TextNode* that) {
3390 stream()->Add(" n%p [label=\"", that);
3391 for (int i = 0; i < that->elements()->length(); i++) {
3392 if (i > 0) stream()->Add(" ");
3393 TextElement elm = that->elements()->at(i);
3394 switch (elm.type) {
3395 case TextElement::ATOM: {
3396 stream()->Add("'%w'", elm.data.u_atom->data());
3397 break;
3398 }
3399 case TextElement::CHAR_CLASS: {
3400 RegExpCharacterClass* node = elm.data.u_char_class;
3401 stream()->Add("[");
3402 if (node->is_negated())
3403 stream()->Add("^");
3404 for (int j = 0; j < node->ranges()->length(); j++) {
3405 CharacterRange range = node->ranges()->at(j);
3406 stream()->Add("%k-%k", range.from(), range.to());
3407 }
3408 stream()->Add("]");
3409 break;
3410 }
3411 default:
3412 UNREACHABLE();
3413 }
3414 }
3415 stream()->Add("\", shape=box, peripheries=2];\n");
3416 PrintAttributes(that);
3417 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3418 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003419}
3420
3421
3422void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3423 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3424 that,
3425 that->start_register(),
3426 that->end_register());
3427 PrintAttributes(that);
3428 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3429 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003430}
3431
3432
3433void DotPrinter::VisitEnd(EndNode* that) {
3434 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3435 PrintAttributes(that);
3436}
3437
3438
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003439void DotPrinter::VisitAssertion(AssertionNode* that) {
3440 stream()->Add(" n%p [", that);
3441 switch (that->type()) {
3442 case AssertionNode::AT_END:
3443 stream()->Add("label=\"$\", shape=septagon");
3444 break;
3445 case AssertionNode::AT_START:
3446 stream()->Add("label=\"^\", shape=septagon");
3447 break;
3448 case AssertionNode::AT_BOUNDARY:
3449 stream()->Add("label=\"\\b\", shape=septagon");
3450 break;
3451 case AssertionNode::AT_NON_BOUNDARY:
3452 stream()->Add("label=\"\\B\", shape=septagon");
3453 break;
3454 case AssertionNode::AFTER_NEWLINE:
3455 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3456 break;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003457 case AssertionNode::AFTER_WORD_CHARACTER:
3458 stream()->Add("label=\"(?<=\\w)\", shape=septagon");
3459 break;
3460 case AssertionNode::AFTER_NONWORD_CHARACTER:
3461 stream()->Add("label=\"(?<=\\W)\", shape=septagon");
3462 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003463 }
3464 stream()->Add("];\n");
3465 PrintAttributes(that);
3466 RegExpNode* successor = that->on_success();
3467 stream()->Add(" n%p -> n%p;\n", that, successor);
3468 Visit(successor);
3469}
3470
3471
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003472void DotPrinter::VisitAction(ActionNode* that) {
3473 stream()->Add(" n%p [", that);
3474 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003475 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003476 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3477 that->data_.u_store_register.reg,
3478 that->data_.u_store_register.value);
3479 break;
3480 case ActionNode::INCREMENT_REGISTER:
3481 stream()->Add("label=\"$%i++\", shape=octagon",
3482 that->data_.u_increment_register.reg);
3483 break;
3484 case ActionNode::STORE_POSITION:
3485 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3486 that->data_.u_position_register.reg);
3487 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003488 case ActionNode::BEGIN_SUBMATCH:
3489 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3490 that->data_.u_submatch.current_position_register);
3491 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003492 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003493 stream()->Add("label=\"escape\", shape=septagon");
3494 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003495 case ActionNode::EMPTY_MATCH_CHECK:
3496 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3497 that->data_.u_empty_match_check.start_register,
3498 that->data_.u_empty_match_check.repetition_register,
3499 that->data_.u_empty_match_check.repetition_limit);
3500 break;
3501 case ActionNode::CLEAR_CAPTURES: {
3502 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3503 that->data_.u_clear_captures.range_from,
3504 that->data_.u_clear_captures.range_to);
3505 break;
3506 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003507 }
3508 stream()->Add("];\n");
3509 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003510 RegExpNode* successor = that->on_success();
3511 stream()->Add(" n%p -> n%p;\n", that, successor);
3512 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003513}
3514
3515
3516class DispatchTableDumper {
3517 public:
3518 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3519 void Call(uc16 key, DispatchTable::Entry entry);
3520 StringStream* stream() { return stream_; }
3521 private:
3522 StringStream* stream_;
3523};
3524
3525
3526void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3527 stream()->Add("[%k-%k]: {", key, entry.to());
3528 OutSet* set = entry.out_set();
3529 bool first = true;
3530 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3531 if (set->Get(i)) {
3532 if (first) {
3533 first = false;
3534 } else {
3535 stream()->Add(", ");
3536 }
3537 stream()->Add("%i", i);
3538 }
3539 }
3540 stream()->Add("}\n");
3541}
3542
3543
3544void DispatchTable::Dump() {
3545 HeapStringAllocator alloc;
3546 StringStream stream(&alloc);
3547 DispatchTableDumper dumper(&stream);
3548 tree()->ForEach(&dumper);
3549 OS::PrintError("%s", *stream.ToCString());
3550}
3551
3552
3553void RegExpEngine::DotPrint(const char* label,
3554 RegExpNode* node,
3555 bool ignore_case) {
3556 DotPrinter printer(ignore_case);
3557 printer.PrintNode(label, node);
3558}
3559
3560
3561#endif // DEBUG
3562
3563
3564// -------------------------------------------------------------------
3565// Tree to graph conversion
3566
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003567static const int kSpaceRangeCount = 20;
3568static const int kSpaceRangeAsciiCount = 4;
3569static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3570 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3571 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3572
3573static const int kWordRangeCount = 8;
3574static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3575 '_', 'a', 'z' };
3576
3577static const int kDigitRangeCount = 2;
3578static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3579
3580static const int kLineTerminatorRangeCount = 6;
3581static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3582 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003583
3584RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003585 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003586 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3587 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003588 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003589}
3590
3591
3592RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003593 RegExpNode* on_success) {
3594 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003595}
3596
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003597static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3598 const uc16* special_class,
3599 int length) {
3600 ASSERT(ranges->length() != 0);
3601 ASSERT(length != 0);
3602 ASSERT(special_class[0] != 0);
3603 if (ranges->length() != (length >> 1) + 1) {
3604 return false;
3605 }
3606 CharacterRange range = ranges->at(0);
3607 if (range.from() != 0) {
3608 return false;
3609 }
3610 for (int i = 0; i < length; i += 2) {
3611 if (special_class[i] != (range.to() + 1)) {
3612 return false;
3613 }
3614 range = ranges->at((i >> 1) + 1);
3615 if (special_class[i+1] != range.from() - 1) {
3616 return false;
3617 }
3618 }
3619 if (range.to() != 0xffff) {
3620 return false;
3621 }
3622 return true;
3623}
3624
3625
3626static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3627 const uc16* special_class,
3628 int length) {
3629 if (ranges->length() * 2 != length) {
3630 return false;
3631 }
3632 for (int i = 0; i < length; i += 2) {
3633 CharacterRange range = ranges->at(i >> 1);
3634 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3635 return false;
3636 }
3637 }
3638 return true;
3639}
3640
3641
3642bool RegExpCharacterClass::is_standard() {
3643 // TODO(lrn): Remove need for this function, by not throwing away information
3644 // along the way.
3645 if (is_negated_) {
3646 return false;
3647 }
3648 if (set_.is_standard()) {
3649 return true;
3650 }
3651 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3652 set_.set_standard_set_type('s');
3653 return true;
3654 }
3655 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3656 set_.set_standard_set_type('S');
3657 return true;
3658 }
3659 if (CompareInverseRanges(set_.ranges(),
3660 kLineTerminatorRanges,
3661 kLineTerminatorRangeCount)) {
3662 set_.set_standard_set_type('.');
3663 return true;
3664 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003665 if (CompareRanges(set_.ranges(),
3666 kLineTerminatorRanges,
3667 kLineTerminatorRangeCount)) {
3668 set_.set_standard_set_type('n');
3669 return true;
3670 }
3671 if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3672 set_.set_standard_set_type('w');
3673 return true;
3674 }
3675 if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) {
3676 set_.set_standard_set_type('W');
3677 return true;
3678 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003679 return false;
3680}
3681
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003682
3683RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003684 RegExpNode* on_success) {
3685 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003686}
3687
3688
3689RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003690 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003691 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3692 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003693 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003694 for (int i = 0; i < length; i++) {
3695 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003696 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003697 result->AddAlternative(alternative);
3698 }
3699 return result;
3700}
3701
3702
3703RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003704 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003705 return ToNode(min(),
3706 max(),
3707 is_greedy(),
3708 body(),
3709 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003710 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003711}
3712
3713
3714RegExpNode* RegExpQuantifier::ToNode(int min,
3715 int max,
3716 bool is_greedy,
3717 RegExpTree* body,
3718 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003719 RegExpNode* on_success,
3720 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003721 // x{f, t} becomes this:
3722 //
3723 // (r++)<-.
3724 // | `
3725 // | (x)
3726 // v ^
3727 // (r=0)-->(?)---/ [if r < t]
3728 // |
3729 // [if r >= f] \----> ...
3730 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003731
3732 // 15.10.2.5 RepeatMatcher algorithm.
3733 // The parser has already eliminated the case where max is 0. In the case
3734 // where max_match is zero the parser has removed the quantifier if min was
3735 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3736
3737 // If we know that we cannot match zero length then things are a little
3738 // simpler since we don't need to make the special zero length match check
3739 // from step 2.1. If the min and max are small we can unroll a little in
3740 // this case.
3741 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3742 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3743 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003744 bool body_can_be_empty = (body->min_match() == 0);
3745 int body_start_reg = RegExpCompiler::kNoRegister;
3746 Interval capture_registers = body->CaptureRegisters();
3747 bool needs_capture_clearing = !capture_registers.is_empty();
3748 if (body_can_be_empty) {
3749 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003750 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003751 // Only unroll if there are no captures and the body can't be
3752 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003753 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3754 int new_max = (max == kInfinity) ? max : max - min;
3755 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003756 RegExpNode* answer = ToNode(
3757 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003758 // Unroll the forced matches from 0 to min. This can cause chains of
3759 // TextNodes (which the parser does not generate). These should be
3760 // combined if it turns out they hinder good code generation.
3761 for (int i = 0; i < min; i++) {
3762 answer = body->ToNode(compiler, answer);
3763 }
3764 return answer;
3765 }
3766 if (max <= kMaxUnrolledMaxMatches) {
3767 ASSERT(min == 0);
3768 // Unroll the optional matches up to max.
3769 RegExpNode* answer = on_success;
3770 for (int i = 0; i < max; i++) {
3771 ChoiceNode* alternation = new ChoiceNode(2);
3772 if (is_greedy) {
3773 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3774 answer)));
3775 alternation->AddAlternative(GuardedAlternative(on_success));
3776 } else {
3777 alternation->AddAlternative(GuardedAlternative(on_success));
3778 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3779 answer)));
3780 }
3781 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003782 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003783 }
3784 return answer;
3785 }
3786 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003787 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003788 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003789 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003790 int reg_ctr = needs_counter
3791 ? compiler->AllocateRegister()
3792 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003793 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003794 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003795 RegExpNode* loop_return = needs_counter
3796 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3797 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003798 if (body_can_be_empty) {
3799 // If the body can be empty we need to check if it was and then
3800 // backtrack.
3801 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3802 reg_ctr,
3803 min,
3804 loop_return);
3805 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003806 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003807 if (body_can_be_empty) {
3808 // If the body can be empty we need to store the start position
3809 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003810 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003811 }
3812 if (needs_capture_clearing) {
3813 // Before entering the body of this loop we need to clear captures.
3814 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3815 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003816 GuardedAlternative body_alt(body_node);
3817 if (has_max) {
3818 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3819 body_alt.AddGuard(body_guard);
3820 }
3821 GuardedAlternative rest_alt(on_success);
3822 if (has_min) {
3823 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3824 rest_alt.AddGuard(rest_guard);
3825 }
3826 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003827 center->AddLoopAlternative(body_alt);
3828 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003829 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003830 center->AddContinueAlternative(rest_alt);
3831 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003832 }
3833 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003834 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003835 } else {
3836 return center;
3837 }
3838}
3839
3840
3841RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003842 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003843 NodeInfo info;
3844 switch (type()) {
3845 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003846 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003847 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003848 return AssertionNode::AtStart(on_success);
3849 case BOUNDARY:
3850 return AssertionNode::AtBoundary(on_success);
3851 case NON_BOUNDARY:
3852 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003853 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003854 return AssertionNode::AtEnd(on_success);
3855 case END_OF_LINE: {
3856 // Compile $ in multiline regexps as an alternation with a positive
3857 // lookahead in one side and an end-of-input on the other side.
3858 // We need two registers for the lookahead.
3859 int stack_pointer_register = compiler->AllocateRegister();
3860 int position_register = compiler->AllocateRegister();
3861 // The ChoiceNode to distinguish between a newline and end-of-input.
3862 ChoiceNode* result = new ChoiceNode(2);
3863 // Create a newline atom.
3864 ZoneList<CharacterRange>* newline_ranges =
3865 new ZoneList<CharacterRange>(3);
3866 CharacterRange::AddClassEscape('n', newline_ranges);
3867 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3868 TextNode* newline_matcher = new TextNode(
3869 newline_atom,
3870 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3871 position_register,
3872 0, // No captures inside.
3873 -1, // Ignored if no captures.
3874 on_success));
3875 // Create an end-of-input matcher.
3876 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3877 stack_pointer_register,
3878 position_register,
3879 newline_matcher);
3880 // Add the two alternatives to the ChoiceNode.
3881 GuardedAlternative eol_alternative(end_of_line);
3882 result->AddAlternative(eol_alternative);
3883 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3884 result->AddAlternative(end_alternative);
3885 return result;
3886 }
3887 default:
3888 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003889 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003890 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003891}
3892
3893
3894RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003895 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003896 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3897 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003898 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003899}
3900
3901
3902RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003903 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003904 return on_success;
3905}
3906
3907
3908RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003909 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003910 int stack_pointer_register = compiler->AllocateRegister();
3911 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003912
3913 const int registers_per_capture = 2;
3914 const int register_of_first_capture = 2;
3915 int register_count = capture_count_ * registers_per_capture;
3916 int register_start =
3917 register_of_first_capture + capture_from_ * registers_per_capture;
3918
ager@chromium.org8bb60582008-12-11 12:02:20 +00003919 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003920 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003921 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003922 stack_pointer_register,
3923 position_register,
3924 body()->ToNode(
3925 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003926 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3927 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003928 register_count,
3929 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003930 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003931 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003932 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003933 // We use a ChoiceNode for a negative lookahead because it has most of
3934 // the characteristics we need. It has the body of the lookahead as its
3935 // first alternative and the expression after the lookahead of the second
3936 // alternative. If the first alternative succeeds then the
3937 // NegativeSubmatchSuccess will unwind the stack including everything the
3938 // choice node set up and backtrack. If the first alternative fails then
3939 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003940 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3941 // ChoiceNode that knows to ignore the first exit when calculating quick
3942 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003943 GuardedAlternative body_alt(
3944 body()->ToNode(
3945 compiler,
3946 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003947 position_register,
3948 register_count,
3949 register_start)));
3950 ChoiceNode* choice_node =
3951 new NegativeLookaheadChoiceNode(body_alt,
3952 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003953 return ActionNode::BeginSubmatch(stack_pointer_register,
3954 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003955 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003956 }
3957}
3958
3959
3960RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003961 RegExpNode* on_success) {
3962 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003963}
3964
3965
3966RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3967 int index,
3968 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003969 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003970 int start_reg = RegExpCapture::StartRegister(index);
3971 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003972 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003973 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003974 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003975}
3976
3977
3978RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003979 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003980 ZoneList<RegExpTree*>* children = nodes();
3981 RegExpNode* current = on_success;
3982 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003983 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003984 }
3985 return current;
3986}
3987
3988
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003989static void AddClass(const uc16* elmv,
3990 int elmc,
3991 ZoneList<CharacterRange>* ranges) {
3992 for (int i = 0; i < elmc; i += 2) {
3993 ASSERT(elmv[i] <= elmv[i + 1]);
3994 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3995 }
3996}
3997
3998
3999static void AddClassNegated(const uc16 *elmv,
4000 int elmc,
4001 ZoneList<CharacterRange>* ranges) {
4002 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00004003 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004004 uc16 last = 0x0000;
4005 for (int i = 0; i < elmc; i += 2) {
4006 ASSERT(last <= elmv[i] - 1);
4007 ASSERT(elmv[i] <= elmv[i + 1]);
4008 ranges->Add(CharacterRange(last, elmv[i] - 1));
4009 last = elmv[i + 1] + 1;
4010 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004011 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004012}
4013
4014
4015void CharacterRange::AddClassEscape(uc16 type,
4016 ZoneList<CharacterRange>* ranges) {
4017 switch (type) {
4018 case 's':
4019 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
4020 break;
4021 case 'S':
4022 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
4023 break;
4024 case 'w':
4025 AddClass(kWordRanges, kWordRangeCount, ranges);
4026 break;
4027 case 'W':
4028 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
4029 break;
4030 case 'd':
4031 AddClass(kDigitRanges, kDigitRangeCount, ranges);
4032 break;
4033 case 'D':
4034 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
4035 break;
4036 case '.':
4037 AddClassNegated(kLineTerminatorRanges,
4038 kLineTerminatorRangeCount,
4039 ranges);
4040 break;
4041 // This is not a character range as defined by the spec but a
4042 // convenient shorthand for a character class that matches any
4043 // character.
4044 case '*':
4045 ranges->Add(CharacterRange::Everything());
4046 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004047 // This is the set of characters matched by the $ and ^ symbols
4048 // in multiline mode.
4049 case 'n':
4050 AddClass(kLineTerminatorRanges,
4051 kLineTerminatorRangeCount,
4052 ranges);
4053 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004054 default:
4055 UNREACHABLE();
4056 }
4057}
4058
4059
4060Vector<const uc16> CharacterRange::GetWordBounds() {
4061 return Vector<const uc16>(kWordRanges, kWordRangeCount);
4062}
4063
4064
4065class CharacterRangeSplitter {
4066 public:
4067 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
4068 ZoneList<CharacterRange>** excluded)
4069 : included_(included),
4070 excluded_(excluded) { }
4071 void Call(uc16 from, DispatchTable::Entry entry);
4072
4073 static const int kInBase = 0;
4074 static const int kInOverlay = 1;
4075
4076 private:
4077 ZoneList<CharacterRange>** included_;
4078 ZoneList<CharacterRange>** excluded_;
4079};
4080
4081
4082void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
4083 if (!entry.out_set()->Get(kInBase)) return;
4084 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
4085 ? included_
4086 : excluded_;
4087 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
4088 (*target)->Add(CharacterRange(entry.from(), entry.to()));
4089}
4090
4091
4092void CharacterRange::Split(ZoneList<CharacterRange>* base,
4093 Vector<const uc16> overlay,
4094 ZoneList<CharacterRange>** included,
4095 ZoneList<CharacterRange>** excluded) {
4096 ASSERT_EQ(NULL, *included);
4097 ASSERT_EQ(NULL, *excluded);
4098 DispatchTable table;
4099 for (int i = 0; i < base->length(); i++)
4100 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
4101 for (int i = 0; i < overlay.length(); i += 2) {
4102 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
4103 CharacterRangeSplitter::kInOverlay);
4104 }
4105 CharacterRangeSplitter callback(included, excluded);
4106 table.ForEach(&callback);
4107}
4108
4109
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004110static void AddUncanonicals(Isolate* isolate,
4111 ZoneList<CharacterRange>* ranges,
ager@chromium.org38e4c712009-11-11 09:11:58 +00004112 int bottom,
4113 int top);
4114
4115
4116void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
4117 bool is_ascii) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004118 Isolate* isolate = Isolate::Current();
ager@chromium.org38e4c712009-11-11 09:11:58 +00004119 uc16 bottom = from();
4120 uc16 top = to();
4121 if (is_ascii) {
4122 if (bottom > String::kMaxAsciiCharCode) return;
4123 if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode;
4124 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004125 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004126 if (top == bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004127 // If this is a singleton we just expand the one character.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004128 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004129 for (int i = 0; i < length; i++) {
4130 uc32 chr = chars[i];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004131 if (chr != bottom) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004132 ranges->Add(CharacterRange::Singleton(chars[i]));
4133 }
4134 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004135 } else {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004136 // If this is a range we expand the characters block by block,
4137 // expanding contiguous subranges (blocks) one at a time.
4138 // The approach is as follows. For a given start character we
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004139 // look up the remainder of the block that contains it (represented
4140 // by the end point), for instance we find 'z' if the character
4141 // is 'c'. A block is characterized by the property
4142 // that all characters uncanonicalize in the same way, except that
4143 // each entry in the result is incremented by the distance from the first
4144 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
4145 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
4146 // Once we've found the end point we look up its uncanonicalization
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004147 // and produce a range for each element. For instance for [c-f]
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004148 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004149 // add a range if it is not already contained in the input, so [c-f]
4150 // will be skipped but [C-F] will be added. If this range is not
4151 // completely contained in a block we do this for all the blocks
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004152 // covered by the range (handling characters that is not in a block
4153 // as a "singleton block").
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004154 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org38e4c712009-11-11 09:11:58 +00004155 int pos = bottom;
ager@chromium.org38e4c712009-11-11 09:11:58 +00004156 while (pos < top) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004157 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004158 uc16 block_end;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004159 if (length == 0) {
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004160 block_end = pos;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004161 } else {
4162 ASSERT_EQ(1, length);
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004163 block_end = range[0];
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004164 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004165 int end = (block_end > top) ? top : block_end;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004166 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004167 for (int i = 0; i < length; i++) {
4168 uc32 c = range[i];
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004169 uc16 range_from = c - (block_end - pos);
4170 uc16 range_to = c - (block_end - end);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004171 if (!(bottom <= range_from && range_to <= top)) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004172 ranges->Add(CharacterRange(range_from, range_to));
4173 }
4174 }
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004175 pos = end + 1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004176 }
ager@chromium.org38e4c712009-11-11 09:11:58 +00004177 }
4178}
4179
4180
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004181bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
4182 ASSERT_NOT_NULL(ranges);
4183 int n = ranges->length();
4184 if (n <= 1) return true;
4185 int max = ranges->at(0).to();
4186 for (int i = 1; i < n; i++) {
4187 CharacterRange next_range = ranges->at(i);
4188 if (next_range.from() <= max + 1) return false;
4189 max = next_range.to();
4190 }
4191 return true;
4192}
4193
4194SetRelation CharacterRange::WordCharacterRelation(
4195 ZoneList<CharacterRange>* range) {
4196 ASSERT(IsCanonical(range));
4197 int i = 0; // Word character range index.
4198 int j = 0; // Argument range index.
4199 ASSERT_NE(0, kWordRangeCount);
4200 SetRelation result;
4201 if (range->length() == 0) {
4202 result.SetElementsInSecondSet();
4203 return result;
4204 }
4205 CharacterRange argument_range = range->at(0);
4206 CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]);
4207 while (i < kWordRangeCount && j < range->length()) {
4208 // Check the two ranges for the five cases:
4209 // - no overlap.
4210 // - partial overlap (there are elements in both ranges that isn't
4211 // in the other, and there are also elements that are in both).
4212 // - argument range entirely inside word range.
4213 // - word range entirely inside argument range.
4214 // - ranges are completely equal.
4215
4216 // First check for no overlap. The earlier range is not in the other set.
4217 if (argument_range.from() > word_range.to()) {
4218 // Ranges are disjoint. The earlier word range contains elements that
4219 // cannot be in the argument set.
4220 result.SetElementsInSecondSet();
4221 } else if (word_range.from() > argument_range.to()) {
4222 // Ranges are disjoint. The earlier argument range contains elements that
4223 // cannot be in the word set.
4224 result.SetElementsInFirstSet();
4225 } else if (word_range.from() <= argument_range.from() &&
4226 word_range.to() >= argument_range.from()) {
4227 result.SetElementsInBothSets();
4228 // argument range completely inside word range.
4229 if (word_range.from() < argument_range.from() ||
4230 word_range.to() > argument_range.from()) {
4231 result.SetElementsInSecondSet();
4232 }
4233 } else if (word_range.from() >= argument_range.from() &&
4234 word_range.to() <= argument_range.from()) {
4235 result.SetElementsInBothSets();
4236 result.SetElementsInFirstSet();
4237 } else {
4238 // There is overlap, and neither is a subrange of the other
4239 result.SetElementsInFirstSet();
4240 result.SetElementsInSecondSet();
4241 result.SetElementsInBothSets();
4242 }
4243 if (result.NonTrivialIntersection()) {
4244 // The result is as (im)precise as we can possibly make it.
4245 return result;
4246 }
4247 // Progress the range(s) with minimal to-character.
4248 uc16 word_to = word_range.to();
4249 uc16 argument_to = argument_range.to();
4250 if (argument_to <= word_to) {
4251 j++;
4252 if (j < range->length()) {
4253 argument_range = range->at(j);
4254 }
4255 }
4256 if (word_to <= argument_to) {
4257 i += 2;
4258 if (i < kWordRangeCount) {
4259 word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]);
4260 }
4261 }
4262 }
4263 // Check if anything wasn't compared in the loop.
4264 if (i < kWordRangeCount) {
4265 // word range contains something not in argument range.
4266 result.SetElementsInSecondSet();
4267 } else if (j < range->length()) {
4268 // Argument range contains something not in word range.
4269 result.SetElementsInFirstSet();
4270 }
4271
4272 return result;
4273}
4274
4275
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004276static void AddUncanonicals(Isolate* isolate,
4277 ZoneList<CharacterRange>* ranges,
ager@chromium.org38e4c712009-11-11 09:11:58 +00004278 int bottom,
4279 int top) {
4280 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
4281 // Zones with no case mappings. There is a DEBUG-mode loop to assert that
4282 // this table is correct.
4283 // 0x0600 - 0x0fff
4284 // 0x1100 - 0x1cff
4285 // 0x2000 - 0x20ff
4286 // 0x2200 - 0x23ff
4287 // 0x2500 - 0x2bff
4288 // 0x2e00 - 0xa5ff
4289 // 0xa800 - 0xfaff
4290 // 0xfc00 - 0xfeff
4291 const int boundary_count = 18;
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004292 int boundaries[] = {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004293 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500,
4294 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00};
4295
4296 // Special ASCII rule from spec can save us some work here.
4297 if (bottom == 0x80 && top == 0xffff) return;
4298
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004299 if (top <= boundaries[0]) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004300 CharacterRange range(bottom, top);
4301 range.AddCaseEquivalents(ranges, false);
4302 return;
4303 }
4304
4305 // Split up very large ranges. This helps remove ranges where there are no
4306 // case mappings.
4307 for (int i = 0; i < boundary_count; i++) {
4308 if (bottom < boundaries[i] && top >= boundaries[i]) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004309 AddUncanonicals(isolate, ranges, bottom, boundaries[i] - 1);
4310 AddUncanonicals(isolate, ranges, boundaries[i], top);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004311 return;
4312 }
4313 }
4314
4315 // If we are completely in a zone with no case mappings then we are done.
whesse@chromium.orge90029b2010-08-02 11:52:17 +00004316 for (int i = 0; i < boundary_count; i += 2) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004317 if (bottom >= boundaries[i] && top < boundaries[i + 1]) {
4318#ifdef DEBUG
4319 for (int j = bottom; j <= top; j++) {
4320 unsigned current_char = j;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004321 int length = isolate->jsregexp_uncanonicalize()->get(current_char,
4322 '\0', chars);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004323 for (int k = 0; k < length; k++) {
4324 ASSERT(chars[k] == current_char);
4325 }
4326 }
4327#endif
4328 return;
4329 }
4330 }
4331
4332 // Step through the range finding equivalent characters.
4333 ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100);
4334 for (int i = bottom; i <= top; i++) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004335 int length = isolate->jsregexp_uncanonicalize()->get(i, '\0', chars);
ager@chromium.org38e4c712009-11-11 09:11:58 +00004336 for (int j = 0; j < length; j++) {
4337 uc32 chr = chars[j];
4338 if (chr != i && (chr < bottom || chr > top)) {
4339 characters->Add(chr);
4340 }
4341 }
4342 }
4343
4344 // Step through the equivalent characters finding simple ranges and
4345 // adding ranges to the character class.
4346 if (characters->length() > 0) {
4347 int new_from = characters->at(0);
4348 int new_to = new_from;
4349 for (int i = 1; i < characters->length(); i++) {
4350 int chr = characters->at(i);
4351 if (chr == new_to + 1) {
4352 new_to++;
4353 } else {
4354 if (new_to == new_from) {
4355 ranges->Add(CharacterRange::Singleton(new_from));
4356 } else {
4357 ranges->Add(CharacterRange(new_from, new_to));
4358 }
4359 new_from = new_to = chr;
4360 }
4361 }
4362 if (new_to == new_from) {
4363 ranges->Add(CharacterRange::Singleton(new_from));
4364 } else {
4365 ranges->Add(CharacterRange(new_from, new_to));
4366 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004367 }
4368}
4369
4370
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004371ZoneList<CharacterRange>* CharacterSet::ranges() {
4372 if (ranges_ == NULL) {
4373 ranges_ = new ZoneList<CharacterRange>(2);
4374 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4375 }
4376 return ranges_;
4377}
4378
4379
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004380// Move a number of elements in a zonelist to another position
4381// in the same list. Handles overlapping source and target areas.
4382static void MoveRanges(ZoneList<CharacterRange>* list,
4383 int from,
4384 int to,
4385 int count) {
4386 // Ranges are potentially overlapping.
4387 if (from < to) {
4388 for (int i = count - 1; i >= 0; i--) {
4389 list->at(to + i) = list->at(from + i);
4390 }
4391 } else {
4392 for (int i = 0; i < count; i++) {
4393 list->at(to + i) = list->at(from + i);
4394 }
4395 }
4396}
4397
4398
4399static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
4400 int count,
4401 CharacterRange insert) {
4402 // Inserts a range into list[0..count[, which must be sorted
4403 // by from value and non-overlapping and non-adjacent, using at most
4404 // list[0..count] for the result. Returns the number of resulting
4405 // canonicalized ranges. Inserting a range may collapse existing ranges into
4406 // fewer ranges, so the return value can be anything in the range 1..count+1.
4407 uc16 from = insert.from();
4408 uc16 to = insert.to();
4409 int start_pos = 0;
4410 int end_pos = count;
4411 for (int i = count - 1; i >= 0; i--) {
4412 CharacterRange current = list->at(i);
4413 if (current.from() > to + 1) {
4414 end_pos = i;
4415 } else if (current.to() + 1 < from) {
4416 start_pos = i + 1;
4417 break;
4418 }
4419 }
4420
4421 // Inserted range overlaps, or is adjacent to, ranges at positions
4422 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
4423 // not affected by the insertion.
4424 // If start_pos == end_pos, the range must be inserted before start_pos.
4425 // if start_pos < end_pos, the entire range from start_pos to end_pos
4426 // must be merged with the insert range.
4427
4428 if (start_pos == end_pos) {
4429 // Insert between existing ranges at position start_pos.
4430 if (start_pos < count) {
4431 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
4432 }
4433 list->at(start_pos) = insert;
4434 return count + 1;
4435 }
4436 if (start_pos + 1 == end_pos) {
4437 // Replace single existing range at position start_pos.
4438 CharacterRange to_replace = list->at(start_pos);
4439 int new_from = Min(to_replace.from(), from);
4440 int new_to = Max(to_replace.to(), to);
4441 list->at(start_pos) = CharacterRange(new_from, new_to);
4442 return count;
4443 }
4444 // Replace a number of existing ranges from start_pos to end_pos - 1.
4445 // Move the remaining ranges down.
4446
4447 int new_from = Min(list->at(start_pos).from(), from);
4448 int new_to = Max(list->at(end_pos - 1).to(), to);
4449 if (end_pos < count) {
4450 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
4451 }
4452 list->at(start_pos) = CharacterRange(new_from, new_to);
4453 return count - (end_pos - start_pos) + 1;
4454}
4455
4456
4457void CharacterSet::Canonicalize() {
4458 // Special/default classes are always considered canonical. The result
4459 // of calling ranges() will be sorted.
4460 if (ranges_ == NULL) return;
4461 CharacterRange::Canonicalize(ranges_);
4462}
4463
4464
4465void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
4466 if (character_ranges->length() <= 1) return;
4467 // Check whether ranges are already canonical (increasing, non-overlapping,
4468 // non-adjacent).
4469 int n = character_ranges->length();
4470 int max = character_ranges->at(0).to();
4471 int i = 1;
4472 while (i < n) {
4473 CharacterRange current = character_ranges->at(i);
4474 if (current.from() <= max + 1) {
4475 break;
4476 }
4477 max = current.to();
4478 i++;
4479 }
4480 // Canonical until the i'th range. If that's all of them, we are done.
4481 if (i == n) return;
4482
4483 // The ranges at index i and forward are not canonicalized. Make them so by
4484 // doing the equivalent of insertion sort (inserting each into the previous
4485 // list, in order).
4486 // Notice that inserting a range can reduce the number of ranges in the
4487 // result due to combining of adjacent and overlapping ranges.
4488 int read = i; // Range to insert.
4489 int num_canonical = i; // Length of canonicalized part of list.
4490 do {
4491 num_canonical = InsertRangeInCanonicalList(character_ranges,
4492 num_canonical,
4493 character_ranges->at(read));
4494 read++;
4495 } while (read < n);
4496 character_ranges->Rewind(num_canonical);
4497
4498 ASSERT(CharacterRange::IsCanonical(character_ranges));
4499}
4500
4501
4502// Utility function for CharacterRange::Merge. Adds a range at the end of
4503// a canonicalized range list, if necessary merging the range with the last
4504// range of the list.
4505static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) {
4506 if (set == NULL) return;
4507 ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from());
4508 int n = set->length();
4509 if (n > 0) {
4510 CharacterRange lastRange = set->at(n - 1);
4511 if (lastRange.to() == range.from() - 1) {
4512 set->at(n - 1) = CharacterRange(lastRange.from(), range.to());
4513 return;
4514 }
4515 }
4516 set->Add(range);
4517}
4518
4519
4520static void AddRangeToSelectedSet(int selector,
4521 ZoneList<CharacterRange>* first_set,
4522 ZoneList<CharacterRange>* second_set,
4523 ZoneList<CharacterRange>* intersection_set,
4524 CharacterRange range) {
4525 switch (selector) {
4526 case kInsideFirst:
4527 AddRangeToSet(first_set, range);
4528 break;
4529 case kInsideSecond:
4530 AddRangeToSet(second_set, range);
4531 break;
4532 case kInsideBoth:
4533 AddRangeToSet(intersection_set, range);
4534 break;
4535 }
4536}
4537
4538
4539
4540void CharacterRange::Merge(ZoneList<CharacterRange>* first_set,
4541 ZoneList<CharacterRange>* second_set,
4542 ZoneList<CharacterRange>* first_set_only_out,
4543 ZoneList<CharacterRange>* second_set_only_out,
4544 ZoneList<CharacterRange>* both_sets_out) {
4545 // Inputs are canonicalized.
4546 ASSERT(CharacterRange::IsCanonical(first_set));
4547 ASSERT(CharacterRange::IsCanonical(second_set));
4548 // Outputs are empty, if applicable.
4549 ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0);
4550 ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0);
4551 ASSERT(both_sets_out == NULL || both_sets_out->length() == 0);
4552
4553 // Merge sets by iterating through the lists in order of lowest "from" value,
4554 // and putting intervals into one of three sets.
4555
4556 if (first_set->length() == 0) {
4557 second_set_only_out->AddAll(*second_set);
4558 return;
4559 }
4560 if (second_set->length() == 0) {
4561 first_set_only_out->AddAll(*first_set);
4562 return;
4563 }
4564 // Indices into input lists.
4565 int i1 = 0;
4566 int i2 = 0;
4567 // Cache length of input lists.
4568 int n1 = first_set->length();
4569 int n2 = second_set->length();
4570 // Current range. May be invalid if state is kInsideNone.
4571 int from = 0;
4572 int to = -1;
4573 // Where current range comes from.
4574 int state = kInsideNone;
4575
4576 while (i1 < n1 || i2 < n2) {
4577 CharacterRange next_range;
4578 int range_source;
ager@chromium.org64488672010-01-25 13:24:36 +00004579 if (i2 == n2 ||
4580 (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) {
4581 // Next smallest element is in first set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004582 next_range = first_set->at(i1++);
4583 range_source = kInsideFirst;
4584 } else {
ager@chromium.org64488672010-01-25 13:24:36 +00004585 // Next smallest element is in second set.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004586 next_range = second_set->at(i2++);
4587 range_source = kInsideSecond;
4588 }
4589 if (to < next_range.from()) {
4590 // Ranges disjoint: |current| |next|
4591 AddRangeToSelectedSet(state,
4592 first_set_only_out,
4593 second_set_only_out,
4594 both_sets_out,
4595 CharacterRange(from, to));
4596 from = next_range.from();
4597 to = next_range.to();
4598 state = range_source;
4599 } else {
4600 if (from < next_range.from()) {
4601 AddRangeToSelectedSet(state,
4602 first_set_only_out,
4603 second_set_only_out,
4604 both_sets_out,
4605 CharacterRange(from, next_range.from()-1));
4606 }
4607 if (to < next_range.to()) {
4608 // Ranges overlap: |current|
4609 // |next|
4610 AddRangeToSelectedSet(state | range_source,
4611 first_set_only_out,
4612 second_set_only_out,
4613 both_sets_out,
4614 CharacterRange(next_range.from(), to));
4615 from = to + 1;
4616 to = next_range.to();
4617 state = range_source;
4618 } else {
4619 // Range included: |current| , possibly ending at same character.
4620 // |next|
4621 AddRangeToSelectedSet(
4622 state | range_source,
4623 first_set_only_out,
4624 second_set_only_out,
4625 both_sets_out,
4626 CharacterRange(next_range.from(), next_range.to()));
4627 from = next_range.to() + 1;
4628 // If ranges end at same character, both ranges are consumed completely.
4629 if (next_range.to() == to) state = kInsideNone;
4630 }
4631 }
4632 }
4633 AddRangeToSelectedSet(state,
4634 first_set_only_out,
4635 second_set_only_out,
4636 both_sets_out,
4637 CharacterRange(from, to));
4638}
4639
4640
4641void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
4642 ZoneList<CharacterRange>* negated_ranges) {
4643 ASSERT(CharacterRange::IsCanonical(ranges));
4644 ASSERT_EQ(0, negated_ranges->length());
4645 int range_count = ranges->length();
4646 uc16 from = 0;
4647 int i = 0;
4648 if (range_count > 0 && ranges->at(0).from() == 0) {
4649 from = ranges->at(0).to();
4650 i = 1;
4651 }
4652 while (i < range_count) {
4653 CharacterRange range = ranges->at(i);
4654 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1));
4655 from = range.to();
4656 i++;
4657 }
4658 if (from < String::kMaxUC16CharCode) {
4659 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode));
4660 }
4661}
4662
4663
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004664
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004665// -------------------------------------------------------------------
4666// Interest propagation
4667
4668
4669RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4670 for (int i = 0; i < siblings_.length(); i++) {
4671 RegExpNode* sibling = siblings_.Get(i);
4672 if (sibling->info()->Matches(info))
4673 return sibling;
4674 }
4675 return NULL;
4676}
4677
4678
4679RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4680 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004681 siblings_.Ensure(this);
4682 RegExpNode* result = TryGetSibling(info);
4683 if (result != NULL) return result;
4684 result = this->Clone();
4685 NodeInfo* new_info = result->info();
4686 new_info->ResetCompilationState();
4687 new_info->AddFromPreceding(info);
4688 AddSibling(result);
4689 *cloned = true;
4690 return result;
4691}
4692
4693
4694template <class C>
4695static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4696 NodeInfo full_info(*node->info());
4697 full_info.AddFromPreceding(info);
4698 bool cloned = false;
4699 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4700}
4701
4702
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004703// -------------------------------------------------------------------
4704// Splay tree
4705
4706
4707OutSet* OutSet::Extend(unsigned value) {
4708 if (Get(value))
4709 return this;
4710 if (successors() != NULL) {
4711 for (int i = 0; i < successors()->length(); i++) {
4712 OutSet* successor = successors()->at(i);
4713 if (successor->Get(value))
4714 return successor;
4715 }
4716 } else {
4717 successors_ = new ZoneList<OutSet*>(2);
4718 }
4719 OutSet* result = new OutSet(first_, remaining_);
4720 result->Set(value);
4721 successors()->Add(result);
4722 return result;
4723}
4724
4725
4726void OutSet::Set(unsigned value) {
4727 if (value < kFirstLimit) {
4728 first_ |= (1 << value);
4729 } else {
4730 if (remaining_ == NULL)
4731 remaining_ = new ZoneList<unsigned>(1);
4732 if (remaining_->is_empty() || !remaining_->Contains(value))
4733 remaining_->Add(value);
4734 }
4735}
4736
4737
4738bool OutSet::Get(unsigned value) {
4739 if (value < kFirstLimit) {
4740 return (first_ & (1 << value)) != 0;
4741 } else if (remaining_ == NULL) {
4742 return false;
4743 } else {
4744 return remaining_->Contains(value);
4745 }
4746}
4747
4748
4749const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4750const DispatchTable::Entry DispatchTable::Config::kNoValue;
4751
4752
4753void DispatchTable::AddRange(CharacterRange full_range, int value) {
4754 CharacterRange current = full_range;
4755 if (tree()->is_empty()) {
4756 // If this is the first range we just insert into the table.
4757 ZoneSplayTree<Config>::Locator loc;
4758 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4759 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4760 return;
4761 }
4762 // First see if there is a range to the left of this one that
4763 // overlaps.
4764 ZoneSplayTree<Config>::Locator loc;
4765 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4766 Entry* entry = &loc.value();
4767 // If we've found a range that overlaps with this one, and it
4768 // starts strictly to the left of this one, we have to fix it
4769 // because the following code only handles ranges that start on
4770 // or after the start point of the range we're adding.
4771 if (entry->from() < current.from() && entry->to() >= current.from()) {
4772 // Snap the overlapping range in half around the start point of
4773 // the range we're adding.
4774 CharacterRange left(entry->from(), current.from() - 1);
4775 CharacterRange right(current.from(), entry->to());
4776 // The left part of the overlapping range doesn't overlap.
4777 // Truncate the whole entry to be just the left part.
4778 entry->set_to(left.to());
4779 // The right part is the one that overlaps. We add this part
4780 // to the map and let the next step deal with merging it with
4781 // the range we're adding.
4782 ZoneSplayTree<Config>::Locator loc;
4783 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4784 loc.set_value(Entry(right.from(),
4785 right.to(),
4786 entry->out_set()));
4787 }
4788 }
4789 while (current.is_valid()) {
4790 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4791 (loc.value().from() <= current.to()) &&
4792 (loc.value().to() >= current.from())) {
4793 Entry* entry = &loc.value();
4794 // We have overlap. If there is space between the start point of
4795 // the range we're adding and where the overlapping range starts
4796 // then we have to add a range covering just that space.
4797 if (current.from() < entry->from()) {
4798 ZoneSplayTree<Config>::Locator ins;
4799 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4800 ins.set_value(Entry(current.from(),
4801 entry->from() - 1,
4802 empty()->Extend(value)));
4803 current.set_from(entry->from());
4804 }
4805 ASSERT_EQ(current.from(), entry->from());
4806 // If the overlapping range extends beyond the one we want to add
4807 // we have to snap the right part off and add it separately.
4808 if (entry->to() > current.to()) {
4809 ZoneSplayTree<Config>::Locator ins;
4810 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4811 ins.set_value(Entry(current.to() + 1,
4812 entry->to(),
4813 entry->out_set()));
4814 entry->set_to(current.to());
4815 }
4816 ASSERT(entry->to() <= current.to());
4817 // The overlapping range is now completely contained by the range
4818 // we're adding so we can just update it and move the start point
4819 // of the range we're adding just past it.
4820 entry->AddValue(value);
4821 // Bail out if the last interval ended at 0xFFFF since otherwise
4822 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004823 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004824 break;
4825 ASSERT(entry->to() + 1 > current.from());
4826 current.set_from(entry->to() + 1);
4827 } else {
4828 // There is no overlap so we can just add the range
4829 ZoneSplayTree<Config>::Locator ins;
4830 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4831 ins.set_value(Entry(current.from(),
4832 current.to(),
4833 empty()->Extend(value)));
4834 break;
4835 }
4836 }
4837}
4838
4839
4840OutSet* DispatchTable::Get(uc16 value) {
4841 ZoneSplayTree<Config>::Locator loc;
4842 if (!tree()->FindGreatestLessThan(value, &loc))
4843 return empty();
4844 Entry* entry = &loc.value();
4845 if (value <= entry->to())
4846 return entry->out_set();
4847 else
4848 return empty();
4849}
4850
4851
4852// -------------------------------------------------------------------
4853// Analysis
4854
4855
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004856void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00004857 StackLimitCheck check(Isolate::Current());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004858 if (check.HasOverflowed()) {
4859 fail("Stack overflow");
4860 return;
4861 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004862 if (that->info()->been_analyzed || that->info()->being_analyzed)
4863 return;
4864 that->info()->being_analyzed = true;
4865 that->Accept(this);
4866 that->info()->being_analyzed = false;
4867 that->info()->been_analyzed = true;
4868}
4869
4870
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004871void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004872 // nothing to do
4873}
4874
4875
ager@chromium.org8bb60582008-12-11 12:02:20 +00004876void TextNode::CalculateOffsets() {
4877 int element_count = elements()->length();
4878 // Set up the offsets of the elements relative to the start. This is a fixed
4879 // quantity since a TextNode can only contain fixed-width things.
4880 int cp_offset = 0;
4881 for (int i = 0; i < element_count; i++) {
4882 TextElement& elm = elements()->at(i);
4883 elm.cp_offset = cp_offset;
4884 if (elm.type == TextElement::ATOM) {
4885 cp_offset += elm.data.u_atom->data().length();
4886 } else {
4887 cp_offset++;
4888 Vector<const uc16> quarks = elm.data.u_atom->data();
4889 }
4890 }
4891}
4892
4893
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004894void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004895 if (ignore_case_) {
ager@chromium.org38e4c712009-11-11 09:11:58 +00004896 that->MakeCaseIndependent(is_ascii_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004897 }
4898 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004899 if (!has_failed()) {
4900 that->CalculateOffsets();
4901 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004902}
4903
4904
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004905void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004906 RegExpNode* target = that->on_success();
4907 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004908 if (!has_failed()) {
4909 // If the next node is interested in what it follows then this node
4910 // has to be interested too so it can pass the information on.
4911 that->info()->AddFromFollowing(target->info());
4912 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004913}
4914
4915
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004916void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004917 NodeInfo* info = that->info();
4918 for (int i = 0; i < that->alternatives()->length(); i++) {
4919 RegExpNode* node = that->alternatives()->at(i).node();
4920 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004921 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004922 // Anything the following nodes need to know has to be known by
4923 // this node also, so it can pass it on.
4924 info->AddFromFollowing(node->info());
4925 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004926}
4927
4928
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004929void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4930 NodeInfo* info = that->info();
4931 for (int i = 0; i < that->alternatives()->length(); i++) {
4932 RegExpNode* node = that->alternatives()->at(i).node();
4933 if (node != that->loop_node()) {
4934 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004935 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004936 info->AddFromFollowing(node->info());
4937 }
4938 }
4939 // Check the loop last since it may need the value of this node
4940 // to get a correct result.
4941 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004942 if (!has_failed()) {
4943 info->AddFromFollowing(that->loop_node()->info());
4944 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004945}
4946
4947
4948void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004949 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004950}
4951
4952
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004953void Analysis::VisitAssertion(AssertionNode* that) {
4954 EnsureAnalyzed(that->on_success());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004955 AssertionNode::AssertionNodeType type = that->type();
4956 if (type == AssertionNode::AT_BOUNDARY ||
4957 type == AssertionNode::AT_NON_BOUNDARY) {
4958 // Check if the following character is known to be a word character
4959 // or known to not be a word character.
4960 ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet();
4961
4962 CharacterRange::Canonicalize(following_chars);
4963
4964 SetRelation word_relation =
4965 CharacterRange::WordCharacterRelation(following_chars);
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004966 if (word_relation.Disjoint()) {
4967 // Includes the case where following_chars is empty (e.g., end-of-input).
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004968 // Following character is definitely *not* a word character.
4969 type = (type == AssertionNode::AT_BOUNDARY) ?
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00004970 AssertionNode::AFTER_WORD_CHARACTER :
4971 AssertionNode::AFTER_NONWORD_CHARACTER;
4972 that->set_type(type);
4973 } else if (word_relation.ContainedIn()) {
4974 // Following character is definitely a word character.
4975 type = (type == AssertionNode::AT_BOUNDARY) ?
4976 AssertionNode::AFTER_NONWORD_CHARACTER :
4977 AssertionNode::AFTER_WORD_CHARACTER;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004978 that->set_type(type);
4979 }
4980 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004981}
4982
4983
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00004984ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() {
4985 if (first_character_set_ == NULL) {
4986 if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) {
4987 // If we can't find an exact solution within the budget, we
4988 // set the value to the set of every character, i.e., all characters
4989 // are possible.
4990 ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1);
4991 all_set->Add(CharacterRange::Everything());
4992 first_character_set_ = all_set;
4993 }
4994 }
4995 return first_character_set_;
4996}
4997
4998
4999int RegExpNode::ComputeFirstCharacterSet(int budget) {
5000 // Default behavior is to not be able to determine the first character.
5001 return kComputeFirstCharacterSetFail;
5002}
5003
5004
5005int LoopChoiceNode::ComputeFirstCharacterSet(int budget) {
5006 budget--;
5007 if (budget >= 0) {
5008 // Find loop min-iteration. It's the value of the guarded choice node
5009 // with a GEQ guard, if any.
5010 int min_repetition = 0;
5011
5012 for (int i = 0; i <= 1; i++) {
5013 GuardedAlternative alternative = alternatives()->at(i);
5014 ZoneList<Guard*>* guards = alternative.guards();
5015 if (guards != NULL && guards->length() > 0) {
5016 Guard* guard = guards->at(0);
5017 if (guard->op() == Guard::GEQ) {
5018 min_repetition = guard->value();
5019 break;
5020 }
5021 }
5022 }
5023
5024 budget = loop_node()->ComputeFirstCharacterSet(budget);
5025 if (budget >= 0) {
5026 ZoneList<CharacterRange>* character_set =
5027 loop_node()->first_character_set();
5028 if (body_can_be_zero_length() || min_repetition == 0) {
5029 budget = continue_node()->ComputeFirstCharacterSet(budget);
5030 if (budget < 0) return budget;
5031 ZoneList<CharacterRange>* body_set =
5032 continue_node()->first_character_set();
5033 ZoneList<CharacterRange>* union_set =
5034 new ZoneList<CharacterRange>(Max(character_set->length(),
5035 body_set->length()));
5036 CharacterRange::Merge(character_set,
5037 body_set,
5038 union_set,
5039 union_set,
5040 union_set);
5041 character_set = union_set;
5042 }
5043 set_first_character_set(character_set);
5044 }
5045 }
5046 return budget;
5047}
5048
5049
5050int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) {
5051 budget--;
5052 if (budget >= 0) {
5053 GuardedAlternative successor = this->alternatives()->at(1);
5054 RegExpNode* successor_node = successor.node();
5055 budget = successor_node->ComputeFirstCharacterSet(budget);
5056 if (budget >= 0) {
5057 set_first_character_set(successor_node->first_character_set());
5058 }
5059 }
5060 return budget;
5061}
5062
5063
5064// The first character set of an EndNode is unknowable. Just use the
5065// default implementation that fails and returns all characters as possible.
5066
5067
5068int AssertionNode::ComputeFirstCharacterSet(int budget) {
5069 budget -= 1;
5070 if (budget >= 0) {
5071 switch (type_) {
5072 case AT_END: {
5073 set_first_character_set(new ZoneList<CharacterRange>(0));
5074 break;
5075 }
5076 case AT_START:
5077 case AT_BOUNDARY:
5078 case AT_NON_BOUNDARY:
5079 case AFTER_NEWLINE:
5080 case AFTER_NONWORD_CHARACTER:
5081 case AFTER_WORD_CHARACTER: {
5082 ASSERT_NOT_NULL(on_success());
5083 budget = on_success()->ComputeFirstCharacterSet(budget);
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005084 if (budget >= 0) {
5085 set_first_character_set(on_success()->first_character_set());
5086 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005087 break;
5088 }
5089 }
5090 }
5091 return budget;
5092}
5093
5094
5095int ActionNode::ComputeFirstCharacterSet(int budget) {
5096 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail;
5097 budget--;
5098 if (budget >= 0) {
5099 ASSERT_NOT_NULL(on_success());
5100 budget = on_success()->ComputeFirstCharacterSet(budget);
5101 if (budget >= 0) {
5102 set_first_character_set(on_success()->first_character_set());
5103 }
5104 }
5105 return budget;
5106}
5107
5108
5109int BackReferenceNode::ComputeFirstCharacterSet(int budget) {
5110 // We don't know anything about the first character of a backreference
5111 // at this point.
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005112 // The potential first characters are the first characters of the capture,
5113 // and the first characters of the on_success node, depending on whether the
5114 // capture can be empty and whether it is known to be participating or known
5115 // not to be.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005116 return kComputeFirstCharacterSetFail;
5117}
5118
5119
5120int TextNode::ComputeFirstCharacterSet(int budget) {
5121 budget--;
5122 if (budget >= 0) {
5123 ASSERT_NE(0, elements()->length());
5124 TextElement text = elements()->at(0);
5125 if (text.type == TextElement::ATOM) {
5126 RegExpAtom* atom = text.data.u_atom;
5127 ASSERT_NE(0, atom->length());
5128 uc16 first_char = atom->data()[0];
5129 ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1);
5130 range->Add(CharacterRange(first_char, first_char));
5131 set_first_character_set(range);
5132 } else {
5133 ASSERT(text.type == TextElement::CHAR_CLASS);
5134 RegExpCharacterClass* char_class = text.data.u_char_class;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005135 ZoneList<CharacterRange>* ranges = char_class->ranges();
5136 // TODO(lrn): Canonicalize ranges when they are created
5137 // instead of waiting until now.
5138 CharacterRange::Canonicalize(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005139 if (char_class->is_negated()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005140 int length = ranges->length();
5141 int new_length = length + 1;
5142 if (length > 0) {
5143 if (ranges->at(0).from() == 0) new_length--;
5144 if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) {
5145 new_length--;
5146 }
5147 }
5148 ZoneList<CharacterRange>* negated_ranges =
5149 new ZoneList<CharacterRange>(new_length);
5150 CharacterRange::Negate(ranges, negated_ranges);
5151 set_first_character_set(negated_ranges);
5152 } else {
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00005153 set_first_character_set(ranges);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005154 }
5155 }
5156 }
5157 return budget;
5158}
5159
5160
5161
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005162// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005163// Dispatch table construction
5164
5165
5166void DispatchTableConstructor::VisitEnd(EndNode* that) {
5167 AddRange(CharacterRange::Everything());
5168}
5169
5170
5171void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5172 node->set_being_calculated(true);
5173 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5174 for (int i = 0; i < alternatives->length(); i++) {
5175 set_choice_index(i);
5176 alternatives->at(i).node()->Accept(this);
5177 }
5178 node->set_being_calculated(false);
5179}
5180
5181
5182class AddDispatchRange {
5183 public:
5184 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5185 : constructor_(constructor) { }
5186 void Call(uc32 from, DispatchTable::Entry entry);
5187 private:
5188 DispatchTableConstructor* constructor_;
5189};
5190
5191
5192void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5193 CharacterRange range(from, entry.to());
5194 constructor_->AddRange(range);
5195}
5196
5197
5198void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5199 if (node->being_calculated())
5200 return;
5201 DispatchTable* table = node->GetTable(ignore_case_);
5202 AddDispatchRange adder(this);
5203 table->ForEach(&adder);
5204}
5205
5206
5207void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5208 // TODO(160): Find the node that we refer back to and propagate its start
5209 // set back to here. For now we just accept anything.
5210 AddRange(CharacterRange::Everything());
5211}
5212
5213
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005214void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5215 RegExpNode* target = that->on_success();
5216 target->Accept(this);
5217}
5218
5219
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005220static int CompareRangeByFrom(const CharacterRange* a,
5221 const CharacterRange* b) {
5222 return Compare<uc16>(a->from(), b->from());
5223}
5224
5225
5226void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5227 ranges->Sort(CompareRangeByFrom);
5228 uc16 last = 0;
5229 for (int i = 0; i < ranges->length(); i++) {
5230 CharacterRange range = ranges->at(i);
5231 if (last < range.from())
5232 AddRange(CharacterRange(last, range.from() - 1));
5233 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005234 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005235 return;
5236 } else {
5237 last = range.to() + 1;
5238 }
5239 }
5240 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005241 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005242}
5243
5244
5245void DispatchTableConstructor::VisitText(TextNode* that) {
5246 TextElement elm = that->elements()->at(0);
5247 switch (elm.type) {
5248 case TextElement::ATOM: {
5249 uc16 c = elm.data.u_atom->data()[0];
5250 AddRange(CharacterRange(c, c));
5251 break;
5252 }
5253 case TextElement::CHAR_CLASS: {
5254 RegExpCharacterClass* tree = elm.data.u_char_class;
5255 ZoneList<CharacterRange>* ranges = tree->ranges();
5256 if (tree->is_negated()) {
5257 AddInverse(ranges);
5258 } else {
5259 for (int i = 0; i < ranges->length(); i++)
5260 AddRange(ranges->at(i));
5261 }
5262 break;
5263 }
5264 default: {
5265 UNIMPLEMENTED();
5266 }
5267 }
5268}
5269
5270
5271void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00005272 RegExpNode* target = that->on_success();
5273 target->Accept(this);
5274}
5275
5276
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005277RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
5278 bool ignore_case,
5279 bool is_multiline,
5280 Handle<String> pattern,
5281 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005282 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00005283 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005284 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00005285 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005286 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00005287 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005288 0,
5289 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005290 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005291 RegExpNode* node = captured_body;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005292 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
5293 bool is_start_anchored = data->tree->IsAnchoredAtStart();
5294 int max_length = data->tree->max_match();
5295 if (!is_start_anchored) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005296 // Add a .*? at the beginning, outside the body capture, unless
5297 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00005298 RegExpNode* loop_node =
5299 RegExpQuantifier::ToNode(0,
5300 RegExpTree::kInfinity,
5301 false,
5302 new RegExpCharacterClass('*'),
5303 &compiler,
5304 captured_body,
5305 data->contains_anchor);
5306
5307 if (data->contains_anchor) {
5308 // Unroll loop once, to take care of the case that might start
5309 // at the start of input.
5310 ChoiceNode* first_step_node = new ChoiceNode(2);
5311 first_step_node->AddAlternative(GuardedAlternative(captured_body));
5312 first_step_node->AddAlternative(GuardedAlternative(
5313 new TextNode(new RegExpCharacterClass('*'), loop_node)));
5314 node = first_step_node;
5315 } else {
5316 node = loop_node;
5317 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00005318 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00005319 data->node = node;
ager@chromium.org38e4c712009-11-11 09:11:58 +00005320 Analysis analysis(ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005321 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00005322 if (analysis.has_failed()) {
5323 const char* error_message = analysis.error_message();
5324 return CompilationResult(error_message);
5325 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005326
5327 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00005328
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005329 // Create the correct assembler for the architecture.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005330#ifndef V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005331 // Native regexp implementation.
5332
5333 NativeRegExpMacroAssembler::Mode mode =
5334 is_ascii ? NativeRegExpMacroAssembler::ASCII
5335 : NativeRegExpMacroAssembler::UC16;
5336
ager@chromium.org18ad94b2009-09-02 08:22:29 +00005337#if V8_TARGET_ARCH_IA32
5338 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2);
5339#elif V8_TARGET_ARCH_X64
5340 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2);
5341#elif V8_TARGET_ARCH_ARM
5342 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005343#endif
5344
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005345#else // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005346 // Interpreted regexp implementation.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005347 EmbeddedVector<byte, 1024> codes;
5348 RegExpMacroAssemblerIrregexp macro_assembler(codes);
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00005349#endif // V8_INTERPRETED_REGEXP
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00005350
whesse@chromium.org4a5224e2010-10-20 12:37:07 +00005351 // Inserted here, instead of in Assembler, because it depends on information
5352 // in the AST that isn't replicated in the Node structure.
5353 static const int kMaxBacksearchLimit = 1024;
5354 if (is_end_anchored &&
5355 !is_start_anchored &&
5356 max_length < kMaxBacksearchLimit) {
5357 macro_assembler.SetCurrentPositionFromEnd(max_length);
5358 }
5359
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005360 return compiler.Assemble(&macro_assembler,
5361 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00005362 data->capture_count,
5363 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00005364}
5365
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00005366
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00005367}} // namespace v8::internal