blob: 879f671a9f058ac077ac1b6dd6ab02f9c2361973 [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"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000034#include "jsregexp-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "platform.h"
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000036#include "runtime.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "top.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
kasperl@chromium.org71affb52009-05-26 05:44:31 +000046#if V8_TARGET_ARCH_IA32
ager@chromium.org3a37e9b2009-04-27 09:26:21 +000047#include "ia32/macro-assembler-ia32.h"
48#include "ia32/regexp-macro-assembler-ia32.h"
ager@chromium.org9085a012009-05-11 19:22:57 +000049#elif V8_TARGET_ARCH_X64
50#include "x64/macro-assembler-x64.h"
51#include "x64/regexp-macro-assembler-x64.h"
52#elif V8_TARGET_ARCH_ARM
53#include "arm/regexp-macro-assembler-arm.h"
kasperl@chromium.org2abc4502009-07-02 07:00:29 +000054#else
55#error Unsupported target architecture.
ager@chromium.orga74f0da2008-12-03 16:05:52 +000056#endif
57
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
64
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000065Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
66 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067 Handle<String> flags,
68 bool* has_pending_exception) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000069 // Ensure that the constructor function has been loaded.
70 if (!constructor->IsLoaded()) {
71 LoadLazy(constructor, has_pending_exception);
ager@chromium.orga74f0da2008-12-03 16:05:52 +000072 if (*has_pending_exception) return Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073 }
74 // Call the construct code with 2 arguments.
75 Object** argv[2] = { Handle<Object>::cast(pattern).location(),
76 Handle<Object>::cast(flags).location() };
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000077 return Execution::New(constructor, 2, argv, has_pending_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000078}
79
80
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000081static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
82 int flags = JSRegExp::NONE;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000083 for (int i = 0; i < str->length(); i++) {
84 switch (str->Get(i)) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000085 case 'i':
86 flags |= JSRegExp::IGNORE_CASE;
87 break;
88 case 'g':
89 flags |= JSRegExp::GLOBAL;
90 break;
91 case 'm':
92 flags |= JSRegExp::MULTILINE;
93 break;
94 }
95 }
96 return JSRegExp::Flags(flags);
97}
98
99
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000100static inline void ThrowRegExpException(Handle<JSRegExp> re,
101 Handle<String> pattern,
102 Handle<String> error_text,
103 const char* message) {
104 Handle<JSArray> array = Factory::NewJSArray(2);
105 SetElement(array, 0, pattern);
106 SetElement(array, 1, error_text);
107 Handle<Object> regexp_err = Factory::NewSyntaxError(message, array);
108 Top::Throw(*regexp_err);
109}
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000110
111
ager@chromium.org8bb60582008-12-11 12:02:20 +0000112// Generic RegExp methods. Dispatches to implementation specific methods.
113
114
115class OffsetsVector {
116 public:
117 inline OffsetsVector(int num_registers)
118 : offsets_vector_length_(num_registers) {
119 if (offsets_vector_length_ > kStaticOffsetsVectorSize) {
120 vector_ = NewArray<int>(offsets_vector_length_);
121 } else {
122 vector_ = static_offsets_vector_;
123 }
124 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000125 inline ~OffsetsVector() {
126 if (offsets_vector_length_ > kStaticOffsetsVectorSize) {
127 DeleteArray(vector_);
128 vector_ = NULL;
129 }
130 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000131 inline int* vector() { return vector_; }
132 inline int length() { return offsets_vector_length_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000133
134 private:
135 int* vector_;
136 int offsets_vector_length_;
137 static const int kStaticOffsetsVectorSize = 50;
138 static int static_offsets_vector_[kStaticOffsetsVectorSize];
139};
140
141
142int OffsetsVector::static_offsets_vector_[
143 OffsetsVector::kStaticOffsetsVectorSize];
144
145
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000146Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
147 Handle<String> pattern,
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000148 Handle<String> flag_str) {
149 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
150 Handle<FixedArray> cached = CompilationCache::LookupRegExp(pattern, flags);
151 bool in_cache = !cached.is_null();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000152 LOG(RegExpCompileEvent(re, in_cache));
153
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000154 Handle<Object> result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000155 if (in_cache) {
156 re->set_data(*cached);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000157 return re;
158 }
159 FlattenString(pattern);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000160 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000161 RegExpCompileData parse_result;
162 FlatStringReader reader(pattern);
163 if (!ParseRegExp(&reader, flags.is_multiline(), &parse_result)) {
164 // Throw an exception if we fail to parse the pattern.
165 ThrowRegExpException(re,
166 pattern,
167 parse_result.error,
168 "malformed_regexp");
169 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000170 }
171
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000172 if (parse_result.simple && !flags.is_ignore_case()) {
173 // Parse-tree is a single atom that is equal to the pattern.
174 AtomCompile(re, pattern, flags, pattern);
175 } else if (parse_result.tree->IsAtom() &&
176 !flags.is_ignore_case() &&
177 parse_result.capture_count == 0) {
178 RegExpAtom* atom = parse_result.tree->AsAtom();
179 Vector<const uc16> atom_pattern = atom->data();
180 Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern);
181 AtomCompile(re, pattern, flags, atom_string);
182 } else {
183 IrregexpPrepare(re, pattern, flags, parse_result.capture_count);
184 }
185 ASSERT(re->data()->IsFixedArray());
186 // Compilation succeeded so the data is set on the regexp
187 // and we can store it in the cache.
188 Handle<FixedArray> data(FixedArray::cast(re->data()));
189 CompilationCache::PutRegExp(pattern, flags, data);
190
191 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000192}
193
194
195Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
196 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000197 int index,
198 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000199 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000200 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000201 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000202 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000203 Handle<Object> result =
204 IrregexpExec(regexp, subject, index, last_match_info);
ager@chromium.org6f10e412009-02-13 10:11:16 +0000205 ASSERT(!result.is_null() || Top::has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000206 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000207 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000208 default:
209 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000210 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000211 }
212}
213
214
ager@chromium.org8bb60582008-12-11 12:02:20 +0000215// RegExp Atom implementation: Simple string search using indexOf.
216
217
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000218void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
219 Handle<String> pattern,
220 JSRegExp::Flags flags,
221 Handle<String> match_pattern) {
222 Factory::SetRegExpAtomData(re,
223 JSRegExp::ATOM,
224 pattern,
225 flags,
226 match_pattern);
227}
228
229
230static void SetAtomLastCapture(FixedArray* array,
231 String* subject,
232 int from,
233 int to) {
234 NoHandleAllocation no_handles;
235 RegExpImpl::SetLastCaptureCount(array, 2);
236 RegExpImpl::SetLastSubject(array, subject);
237 RegExpImpl::SetLastInput(array, subject);
238 RegExpImpl::SetCapture(array, 0, from);
239 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000240}
241
242
243Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
244 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000245 int index,
246 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000247 Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex)));
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000248
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000249 uint32_t start_index = index;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000250
ager@chromium.org7c537e22008-10-16 08:43:32 +0000251 int value = Runtime::StringMatch(subject, needle, start_index);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000252 if (value == -1) return Factory::null_value();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000253 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000254
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000255 {
256 NoHandleAllocation no_handles;
257 FixedArray* array = last_match_info->elements();
258 SetAtomLastCapture(array, *subject, value, value + needle->length());
259 }
260 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000261}
262
263
ager@chromium.org8bb60582008-12-11 12:02:20 +0000264// Irregexp implementation.
265
266
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000267// Ensures that the regexp object contains a compiled version of the
268// source for either ASCII or non-ASCII strings.
269// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000270// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000271// If compilation fails, an exception is thrown and this function
272// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000273bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000274 int index;
275 if (is_ascii) {
276 index = JSRegExp::kIrregexpASCIICodeIndex;
277 } else {
278 index = JSRegExp::kIrregexpUC16CodeIndex;
279 }
280 Object* entry = re->DataAt(index);
281 if (!entry->IsTheHole()) {
282 // A value has already been compiled.
283 if (entry->IsJSObject()) {
284 // If it's a JS value, it's an error.
285 Top::Throw(entry);
286 return false;
287 }
288 return true;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000289 }
290
291 // Compile the RegExp.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000292 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000293
294 JSRegExp::Flags flags = re->GetFlags();
295
296 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000297 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000298 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000299 }
300
301 RegExpCompileData compile_data;
302 FlatStringReader reader(pattern);
303 if (!ParseRegExp(&reader, flags.is_multiline(), &compile_data)) {
304 // Throw an exception if we fail to parse the pattern.
305 // THIS SHOULD NOT HAPPEN. We already parsed it successfully once.
306 ThrowRegExpException(re,
307 pattern,
308 compile_data.error,
309 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000310 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000311 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000312 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000313 RegExpEngine::Compile(&compile_data,
314 flags.is_ignore_case(),
315 flags.is_multiline(),
316 pattern,
317 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000318 if (result.error_message != NULL) {
319 // Unable to compile regexp.
320 Handle<JSArray> array = Factory::NewJSArray(2);
321 SetElement(array, 0, pattern);
322 SetElement(array,
323 1,
324 Factory::NewStringFromUtf8(CStrVector(result.error_message)));
325 Handle<Object> regexp_err =
326 Factory::NewSyntaxError("malformed_regexp", array);
327 Top::Throw(*regexp_err);
328 re->SetDataAt(index, *regexp_err);
329 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000330 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000331
332 NoHandleAllocation no_handles;
333
334 FixedArray* data = FixedArray::cast(re->data());
335 data->set(index, result.code);
336 int register_max = IrregexpMaxRegisterCount(data);
337 if (result.num_registers > register_max) {
338 SetIrregexpMaxRegisterCount(data, result.num_registers);
339 }
340
341 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000342}
343
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000344
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000345int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
346 return Smi::cast(
347 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000348}
349
350
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000351void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
352 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000353}
354
355
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000356int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
357 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000358}
359
360
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000361int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
362 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000363}
364
365
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000366ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
367 int index;
368 if (is_ascii) {
369 index = JSRegExp::kIrregexpASCIICodeIndex;
370 } else {
371 index = JSRegExp::kIrregexpUC16CodeIndex;
372 }
373 return ByteArray::cast(re->get(index));
374}
375
376
377Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
378 int index;
379 if (is_ascii) {
380 index = JSRegExp::kIrregexpASCIICodeIndex;
381 } else {
382 index = JSRegExp::kIrregexpUC16CodeIndex;
383 }
384 return Code::cast(re->get(index));
385}
386
387
388void RegExpImpl::IrregexpPrepare(Handle<JSRegExp> re,
389 Handle<String> pattern,
390 JSRegExp::Flags flags,
391 int capture_count) {
392 // Initialize compiled code entries to null.
393 Factory::SetRegExpIrregexpData(re,
394 JSRegExp::IRREGEXP,
395 pattern,
396 flags,
397 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000398}
399
400
ager@chromium.org41826e72009-03-30 13:30:57 +0000401Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000402 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000403 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000404 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000405 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000406
ager@chromium.org8bb60582008-12-11 12:02:20 +0000407 // Prepare space for the return values.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000408 int number_of_capture_registers =
ager@chromium.org41826e72009-03-30 13:30:57 +0000409 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000410
ager@chromium.org8bb60582008-12-11 12:02:20 +0000411#ifdef DEBUG
412 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000413 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000414 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
415 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
416 }
417#endif
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000418
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000419 if (!subject->IsFlat()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000420 FlattenString(subject);
421 }
422
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000423 last_match_info->EnsureSize(number_of_capture_registers + kLastMatchOverhead);
424
ager@chromium.org8bb60582008-12-11 12:02:20 +0000425 bool rc;
ager@chromium.org3e875802009-06-29 08:26:34 +0000426 // We have to initialize this with something to make gcc happy but we can't
427 // initialize it with its real value until after the GC-causing things are
428 // over.
429 FixedArray* array = NULL;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000430
ager@chromium.org41826e72009-03-30 13:30:57 +0000431 // Dispatch to the correct RegExp implementation.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000432 Handle<String> original_subject = subject;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000433 Handle<FixedArray> regexp(FixedArray::cast(jsregexp->data()));
434 if (UseNativeRegexp()) {
ager@chromium.org9085a012009-05-11 19:22:57 +0000435#if V8_TARGET_ARCH_IA32
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000436 OffsetsVector captures(number_of_capture_registers);
437 int* captures_vector = captures.vector();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000438 RegExpMacroAssemblerIA32::Result res;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000439 do {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000440 bool is_ascii = subject->IsAsciiRepresentation();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000441 if (!EnsureCompiledIrregexp(jsregexp, is_ascii)) {
442 return Handle<Object>::null();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000443 }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000444 Handle<Code> code(RegExpImpl::IrregexpNativeCode(*regexp, is_ascii));
445 res = RegExpMacroAssemblerIA32::Match(code,
446 subject,
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000447 captures_vector,
448 captures.length(),
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000449 previous_index);
450 // If result is RETRY, the string have changed representation, and we
451 // must restart from scratch.
452 } while (res == RegExpMacroAssemblerIA32::RETRY);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000453 if (res == RegExpMacroAssemblerIA32::EXCEPTION) {
454 ASSERT(Top::has_pending_exception());
455 return Handle<Object>::null();
456 }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000457 ASSERT(res == RegExpMacroAssemblerIA32::SUCCESS
458 || res == RegExpMacroAssemblerIA32::FAILURE);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000459
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000460 rc = (res == RegExpMacroAssemblerIA32::SUCCESS);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000461 if (!rc) return Factory::null_value();
462
463 array = last_match_info->elements();
464 ASSERT(array->length() >= number_of_capture_registers + kLastMatchOverhead);
465 // The captures come in (start, end+1) pairs.
466 for (int i = 0; i < number_of_capture_registers; i += 2) {
467 SetCapture(array, i, captures_vector[i]);
468 SetCapture(array, i + 1, captures_vector[i + 1]);
469 }
470#else // !V8_TARGET_ARCH_IA32
ager@chromium.org9085a012009-05-11 19:22:57 +0000471 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000472#endif
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000473 } else {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000474 bool is_ascii = subject->IsAsciiRepresentation();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000475 if (!EnsureCompiledIrregexp(jsregexp, is_ascii)) {
476 return Handle<Object>::null();
477 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000478 // Now that we have done EnsureCompiledIrregexp we can get the number of
479 // registers.
480 int number_of_registers =
481 IrregexpNumberOfRegisters(FixedArray::cast(jsregexp->data()));
482 OffsetsVector registers(number_of_registers);
483 int* register_vector = registers.vector();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000484 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000485 register_vector[i] = -1;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000486 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000487 Handle<ByteArray> byte_codes(IrregexpByteCode(*regexp, is_ascii));
ager@chromium.org8bb60582008-12-11 12:02:20 +0000488
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000489 rc = IrregexpInterpreter::Match(byte_codes,
490 subject,
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000491 register_vector,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000492 previous_index);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000493 if (!rc) return Factory::null_value();
494
495 array = last_match_info->elements();
496 ASSERT(array->length() >= number_of_capture_registers + kLastMatchOverhead);
497 // The captures come in (start, end+1) pairs.
498 for (int i = 0; i < number_of_capture_registers; i += 2) {
499 SetCapture(array, i, register_vector[i]);
500 SetCapture(array, i + 1, register_vector[i + 1]);
501 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000502 }
503
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000504 SetLastCaptureCount(array, number_of_capture_registers);
505 SetLastSubject(array, *original_subject);
506 SetLastInput(array, *original_subject);
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000507
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000508 return last_match_info;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000509}
510
511
512// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000513// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000514//
515// The Irregexp regular expression engine is intended to be a complete
516// implementation of ECMAScript regular expressions. It generates either
517// bytecodes or native code.
518
519// The Irregexp regexp engine is structured in three steps.
520// 1) The parser generates an abstract syntax tree. See ast.cc.
521// 2) From the AST a node network is created. The nodes are all
522// subclasses of RegExpNode. The nodes represent states when
523// executing a regular expression. Several optimizations are
524// performed on the node network.
525// 3) From the nodes we generate either byte codes or native code
526// that can actually execute the regular expression (perform
527// the search). The code generation step is described in more
528// detail below.
529
530// Code generation.
531//
532// The nodes are divided into four main categories.
533// * Choice nodes
534// These represent places where the regular expression can
535// match in more than one way. For example on entry to an
536// alternation (foo|bar) or a repetition (*, +, ? or {}).
537// * Action nodes
538// These represent places where some action should be
539// performed. Examples include recording the current position
540// in the input string to a register (in order to implement
541// captures) or other actions on register for example in order
542// to implement the counters needed for {} repetitions.
543// * Matching nodes
544// These attempt to match some element part of the input string.
545// Examples of elements include character classes, plain strings
546// or back references.
547// * End nodes
548// These are used to implement the actions required on finding
549// a successful match or failing to find a match.
550//
551// The code generated (whether as byte codes or native code) maintains
552// some state as it runs. This consists of the following elements:
553//
554// * The capture registers. Used for string captures.
555// * Other registers. Used for counters etc.
556// * The current position.
557// * The stack of backtracking information. Used when a matching node
558// fails to find a match and needs to try an alternative.
559//
560// Conceptual regular expression execution model:
561//
562// There is a simple conceptual model of regular expression execution
563// which will be presented first. The actual code generated is a more
564// efficient simulation of the simple conceptual model:
565//
566// * Choice nodes are implemented as follows:
567// For each choice except the last {
568// push current position
569// push backtrack code location
570// <generate code to test for choice>
571// backtrack code location:
572// pop current position
573// }
574// <generate code to test for last choice>
575//
576// * Actions nodes are generated as follows
577// <push affected registers on backtrack stack>
578// <generate code to perform action>
579// push backtrack code location
580// <generate code to test for following nodes>
581// backtrack code location:
582// <pop affected registers to restore their state>
583// <pop backtrack location from stack and go to it>
584//
585// * Matching nodes are generated as follows:
586// if input string matches at current position
587// update current position
588// <generate code to test for following nodes>
589// else
590// <pop backtrack location from stack and go to it>
591//
592// Thus it can be seen that the current position is saved and restored
593// by the choice nodes, whereas the registers are saved and restored by
594// by the action nodes that manipulate them.
595//
596// The other interesting aspect of this model is that nodes are generated
597// at the point where they are needed by a recursive call to Emit(). If
598// the node has already been code generated then the Emit() call will
599// generate a jump to the previously generated code instead. In order to
600// limit recursion it is possible for the Emit() function to put the node
601// on a work list for later generation and instead generate a jump. The
602// destination of the jump is resolved later when the code is generated.
603//
604// Actual regular expression code generation.
605//
606// Code generation is actually more complicated than the above. In order
607// to improve the efficiency of the generated code some optimizations are
608// performed
609//
610// * Choice nodes have 1-character lookahead.
611// A choice node looks at the following character and eliminates some of
612// the choices immediately based on that character. This is not yet
613// implemented.
614// * Simple greedy loops store reduced backtracking information.
615// A quantifier like /.*foo/m will greedily match the whole input. It will
616// then need to backtrack to a point where it can match "foo". The naive
617// implementation of this would push each character position onto the
618// backtracking stack, then pop them off one by one. This would use space
619// proportional to the length of the input string. However since the "."
620// can only match in one way and always has a constant length (in this case
621// of 1) it suffices to store the current position on the top of the stack
622// once. Matching now becomes merely incrementing the current position and
623// backtracking becomes decrementing the current position and checking the
624// result against the stored current position. This is faster and saves
625// space.
626// * The current state is virtualized.
627// This is used to defer expensive operations until it is clear that they
628// are needed and to generate code for a node more than once, allowing
629// specialized an efficient versions of the code to be created. This is
630// explained in the section below.
631//
632// Execution state virtualization.
633//
634// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000635// manipulation in an object called the Trace. The Trace object can record a
636// current position offset, an optional backtrack code location on the top of
637// the virtualized backtrack stack and some register changes. When a node is
638// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000639// will emit code to bring the actual state into line with the virtual state.
640// Avoiding flushing the state can postpone some work (eg updates of capture
641// registers). Postponing work can save time when executing the regular
642// expression since it may be found that the work never has to be done as a
643// failure to match can occur. In addition it is much faster to jump to a
644// known backtrack code location than it is to pop an unknown backtrack
645// location from the stack and jump there.
646//
ager@chromium.org32912102009-01-16 10:38:43 +0000647// The virtual state found in the Trace affects code generation. For example
648// the virtual state contains the difference between the actual current
649// position and the virtual current position, and matching code needs to use
650// this offset to attempt a match in the correct location of the input
651// string. Therefore code generated for a non-trivial trace is specialized
652// to that trace. The code generator therefore has the ability to generate
653// code for each node several times. In order to limit the size of the
654// generated code there is an arbitrary limit on how many specialized sets of
655// code may be generated for a given node. If the limit is reached, the
656// trace is flushed and a generic version of the code for a node is emitted.
657// This is subsequently used for that node. The code emitted for non-generic
658// trace is not recorded in the node and so it cannot currently be reused in
659// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000660
661
662void RegExpTree::AppendToText(RegExpText* text) {
663 UNREACHABLE();
664}
665
666
667void RegExpAtom::AppendToText(RegExpText* text) {
668 text->AddElement(TextElement::Atom(this));
669}
670
671
672void RegExpCharacterClass::AppendToText(RegExpText* text) {
673 text->AddElement(TextElement::CharClass(this));
674}
675
676
677void RegExpText::AppendToText(RegExpText* text) {
678 for (int i = 0; i < elements()->length(); i++)
679 text->AddElement(elements()->at(i));
680}
681
682
683TextElement TextElement::Atom(RegExpAtom* atom) {
684 TextElement result = TextElement(ATOM);
685 result.data.u_atom = atom;
686 return result;
687}
688
689
690TextElement TextElement::CharClass(
691 RegExpCharacterClass* char_class) {
692 TextElement result = TextElement(CHAR_CLASS);
693 result.data.u_char_class = char_class;
694 return result;
695}
696
697
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000698int TextElement::length() {
699 if (type == ATOM) {
700 return data.u_atom->length();
701 } else {
702 ASSERT(type == CHAR_CLASS);
703 return 1;
704 }
705}
706
707
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000708DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
709 if (table_ == NULL) {
710 table_ = new DispatchTable();
711 DispatchTableConstructor cons(table_, ignore_case);
712 cons.BuildTable(this);
713 }
714 return table_;
715}
716
717
718class RegExpCompiler {
719 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000720 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000721
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000722 int AllocateRegister() {
723 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
724 reg_exp_too_big_ = true;
725 return next_register_;
726 }
727 return next_register_++;
728 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000729
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000730 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
731 RegExpNode* start,
732 int capture_count,
733 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000734
735 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
736
737 static const int kImplementationOffset = 0;
738 static const int kNumberOfRegistersOffset = 0;
739 static const int kCodeOffset = 1;
740
741 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
742 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000743
744 static const int kMaxRecursion = 100;
745 inline int recursion_depth() { return recursion_depth_; }
746 inline void IncrementRecursionDepth() { recursion_depth_++; }
747 inline void DecrementRecursionDepth() { recursion_depth_--; }
748
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000749 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
750
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000751 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000752 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000753
ager@chromium.org32912102009-01-16 10:38:43 +0000754 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000755 private:
756 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000757 int next_register_;
758 List<RegExpNode*>* work_list_;
759 int recursion_depth_;
760 RegExpMacroAssembler* macro_assembler_;
761 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000762 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000763 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000764};
765
766
767class RecursionCheck {
768 public:
769 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
770 compiler->IncrementRecursionDepth();
771 }
772 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
773 private:
774 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000775};
776
777
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000778static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
779 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000780}
781
782
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000783// Attempts to compile the regexp using an Irregexp code generator. Returns
784// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000785RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000786 : next_register_(2 * (capture_count + 1)),
787 work_list_(NULL),
788 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000789 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000790 ascii_(ascii),
791 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000792 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000793 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000794}
795
796
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000797RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000798 RegExpMacroAssembler* macro_assembler,
799 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000800 int capture_count,
801 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000802#ifdef DEBUG
803 if (FLAG_trace_regexp_assembler)
804 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
805 else
806#endif
807 macro_assembler_ = macro_assembler;
808 List <RegExpNode*> work_list(0);
809 work_list_ = &work_list;
810 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000811 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000812 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000813 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000814 macro_assembler_->Bind(&fail);
815 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000816 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000817 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000818 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000819 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
820
ager@chromium.org8bb60582008-12-11 12:02:20 +0000821 Handle<Object> code = macro_assembler_->GetCode(pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000822
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000823 work_list_ = NULL;
824#ifdef DEBUG
825 if (FLAG_trace_regexp_assembler) {
826 delete macro_assembler_;
827 }
828#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000829 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000830}
831
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000832
ager@chromium.org32912102009-01-16 10:38:43 +0000833bool Trace::DeferredAction::Mentions(int that) {
834 if (type() == ActionNode::CLEAR_CAPTURES) {
835 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
836 return range.Contains(that);
837 } else {
838 return reg() == that;
839 }
840}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000841
ager@chromium.org32912102009-01-16 10:38:43 +0000842
843bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000844 for (DeferredAction* action = actions_;
845 action != NULL;
846 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000847 if (action->Mentions(reg))
848 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000849 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000850 return false;
851}
852
853
ager@chromium.org32912102009-01-16 10:38:43 +0000854bool Trace::GetStoredPosition(int reg, int* cp_offset) {
855 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000856 for (DeferredAction* action = actions_;
857 action != NULL;
858 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000859 if (action->Mentions(reg)) {
860 if (action->type() == ActionNode::STORE_POSITION) {
861 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
862 return true;
863 } else {
864 return false;
865 }
866 }
867 }
868 return false;
869}
870
871
872int Trace::FindAffectedRegisters(OutSet* affected_registers) {
873 int max_register = RegExpCompiler::kNoRegister;
874 for (DeferredAction* action = actions_;
875 action != NULL;
876 action = action->next()) {
877 if (action->type() == ActionNode::CLEAR_CAPTURES) {
878 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
879 for (int i = range.from(); i <= range.to(); i++)
880 affected_registers->Set(i);
881 if (range.to() > max_register) max_register = range.to();
882 } else {
883 affected_registers->Set(action->reg());
884 if (action->reg() > max_register) max_register = action->reg();
885 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000886 }
887 return max_register;
888}
889
890
ager@chromium.org32912102009-01-16 10:38:43 +0000891void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
892 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000893 OutSet& registers_to_pop,
894 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000895 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000896 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
897 else if (registers_to_clear.Get(reg)) {
898 int clear_to = reg;
899 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
900 reg--;
901 }
902 assembler->ClearRegisters(reg, clear_to);
903 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000904 }
905}
906
907
ager@chromium.org32912102009-01-16 10:38:43 +0000908void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
909 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000910 OutSet& affected_registers,
911 OutSet* registers_to_pop,
912 OutSet* registers_to_clear) {
913 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
914 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
915
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000916 // Count pushes performed to force a stack limit check occasionally.
917 int pushes = 0;
918
ager@chromium.org8bb60582008-12-11 12:02:20 +0000919 for (int reg = 0; reg <= max_register; reg++) {
920 if (!affected_registers.Get(reg)) {
921 continue;
922 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000923
924 // The chronologically first deferred action in the trace
925 // is used to infer the action needed to restore a register
926 // to its previous state (or not, if it's safe to ignore it).
927 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
928 DeferredActionUndoType undo_action = IGNORE;
929
ager@chromium.org8bb60582008-12-11 12:02:20 +0000930 int value = 0;
931 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000932 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000933 int store_position = -1;
934 // This is a little tricky because we are scanning the actions in reverse
935 // historical order (newest first).
936 for (DeferredAction* action = actions_;
937 action != NULL;
938 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000939 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000940 switch (action->type()) {
941 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +0000942 Trace::DeferredSetRegister* psr =
943 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000944 if (!absolute) {
945 value += psr->value();
946 absolute = true;
947 }
948 // SET_REGISTER is currently only used for newly introduced loop
949 // counters. They can have a significant previous value if they
950 // occour in a loop. TODO(lrn): Propagate this information, so
951 // we can set undo_action to IGNORE if we know there is no value to
952 // restore.
953 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000954 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000955 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000956 break;
957 }
958 case ActionNode::INCREMENT_REGISTER:
959 if (!absolute) {
960 value++;
961 }
962 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000963 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000964 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000965 break;
966 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +0000967 Trace::DeferredCapture* pc =
968 static_cast<Trace::DeferredCapture*>(action);
969 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000970 store_position = pc->cp_offset();
971 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000972
973 // For captures we know that stores and clears alternate.
974 // Other register, are never cleared, and if the occur
975 // inside a loop, they might be assigned more than once.
976 if (reg <= 1) {
977 // Registers zero and one, aka "capture zero", is
978 // always set correctly if we succeed. There is no
979 // need to undo a setting on backtrack, because we
980 // will set it again or fail.
981 undo_action = IGNORE;
982 } else {
983 undo_action = pc->is_capture() ? CLEAR : RESTORE;
984 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000985 ASSERT(!absolute);
986 ASSERT_EQ(value, 0);
987 break;
988 }
ager@chromium.org32912102009-01-16 10:38:43 +0000989 case ActionNode::CLEAR_CAPTURES: {
990 // Since we're scanning in reverse order, if we've already
991 // set the position we have to ignore historically earlier
992 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000993 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +0000994 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000995 }
996 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +0000997 ASSERT(!absolute);
998 ASSERT_EQ(value, 0);
999 break;
1000 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001001 default:
1002 UNREACHABLE();
1003 break;
1004 }
1005 }
1006 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001007 // Prepare for the undo-action (e.g., push if it's going to be popped).
1008 if (undo_action == RESTORE) {
1009 pushes++;
1010 RegExpMacroAssembler::StackCheckFlag stack_check =
1011 RegExpMacroAssembler::kNoStackLimitCheck;
1012 if (pushes == push_limit) {
1013 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1014 pushes = 0;
1015 }
1016
1017 assembler->PushRegister(reg, stack_check);
1018 registers_to_pop->Set(reg);
1019 } else if (undo_action == CLEAR) {
1020 registers_to_clear->Set(reg);
1021 }
1022 // Perform the chronologically last action (or accumulated increment)
1023 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001024 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001025 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001026 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001027 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001028 } else if (absolute) {
1029 assembler->SetRegister(reg, value);
1030 } else if (value != 0) {
1031 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001032 }
1033 }
1034}
1035
1036
ager@chromium.org8bb60582008-12-11 12:02:20 +00001037// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001038// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001039// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001040void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001041 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001042
iposva@chromium.org245aa852009-02-10 00:49:54 +00001043 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001044
1045 if (actions_ == NULL && backtrack() == NULL) {
1046 // 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 +00001047 // a normal situation. We may also have to forget some information gained
1048 // through a quick check that was already performed.
1049 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001050 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001051 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001052 successor->Emit(compiler, &new_state);
1053 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001054 }
1055
1056 // Generate deferred actions here along with code to undo them again.
1057 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001058
ager@chromium.org381abbb2009-02-25 13:23:22 +00001059 if (backtrack() != NULL) {
1060 // Here we have a concrete backtrack location. These are set up by choice
1061 // nodes and so they indicate that we have a deferred save of the current
1062 // position which we may need to emit here.
1063 assembler->PushCurrentPosition();
1064 }
1065
ager@chromium.org8bb60582008-12-11 12:02:20 +00001066 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001067 OutSet registers_to_pop;
1068 OutSet registers_to_clear;
1069 PerformDeferredActions(assembler,
1070 max_register,
1071 affected_registers,
1072 &registers_to_pop,
1073 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001074 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001075 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001076 }
1077
1078 // Create a new trivial state and generate the node with that.
1079 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001080 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001081 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001082 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001083
1084 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001085 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001086 RestoreAffectedRegisters(assembler,
1087 max_register,
1088 registers_to_pop,
1089 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001090 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001091 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001092 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001093 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001094 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001095 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001096}
1097
1098
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001099void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001100 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001101
1102 // Omit flushing the trace. We discard the entire stack frame anyway.
1103
ager@chromium.org8bb60582008-12-11 12:02:20 +00001104 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001105 // We are completely independent of the trace, since we ignore it,
1106 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001107 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001108 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001109
1110 // Throw away everything on the backtrack stack since the start
1111 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001112 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1113 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001114 if (clear_capture_count_ > 0) {
1115 // Clear any captures that might have been performed during the success
1116 // of the body of the negative look-ahead.
1117 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1118 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1119 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001120 // Now that we have unwound the stack we find at the top of the stack the
1121 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001122 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001123}
1124
1125
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001126void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001127 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001128 trace->Flush(compiler, this);
1129 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001130 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001131 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001132 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001133 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001134 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001135 switch (action_) {
1136 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001137 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001138 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001139 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001140 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001141 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001142 case NEGATIVE_SUBMATCH_SUCCESS:
1143 // This case is handled in a different virtual method.
1144 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001145 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001146 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001147}
1148
1149
1150void GuardedAlternative::AddGuard(Guard* guard) {
1151 if (guards_ == NULL)
1152 guards_ = new ZoneList<Guard*>(1);
1153 guards_->Add(guard);
1154}
1155
1156
ager@chromium.org8bb60582008-12-11 12:02:20 +00001157ActionNode* ActionNode::SetRegister(int reg,
1158 int val,
1159 RegExpNode* on_success) {
1160 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001161 result->data_.u_store_register.reg = reg;
1162 result->data_.u_store_register.value = val;
1163 return result;
1164}
1165
1166
1167ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1168 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1169 result->data_.u_increment_register.reg = reg;
1170 return result;
1171}
1172
1173
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001174ActionNode* ActionNode::StorePosition(int reg,
1175 bool is_capture,
1176 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001177 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1178 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001179 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001180 return result;
1181}
1182
1183
ager@chromium.org32912102009-01-16 10:38:43 +00001184ActionNode* ActionNode::ClearCaptures(Interval range,
1185 RegExpNode* on_success) {
1186 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1187 result->data_.u_clear_captures.range_from = range.from();
1188 result->data_.u_clear_captures.range_to = range.to();
1189 return result;
1190}
1191
1192
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001193ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1194 int position_reg,
1195 RegExpNode* on_success) {
1196 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1197 result->data_.u_submatch.stack_pointer_register = stack_reg;
1198 result->data_.u_submatch.current_position_register = position_reg;
1199 return result;
1200}
1201
1202
ager@chromium.org8bb60582008-12-11 12:02:20 +00001203ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1204 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001205 int clear_register_count,
1206 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001207 RegExpNode* on_success) {
1208 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001209 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001210 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001211 result->data_.u_submatch.clear_register_count = clear_register_count;
1212 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001213 return result;
1214}
1215
1216
ager@chromium.org32912102009-01-16 10:38:43 +00001217ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1218 int repetition_register,
1219 int repetition_limit,
1220 RegExpNode* on_success) {
1221 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1222 result->data_.u_empty_match_check.start_register = start_register;
1223 result->data_.u_empty_match_check.repetition_register = repetition_register;
1224 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1225 return result;
1226}
1227
1228
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001229#define DEFINE_ACCEPT(Type) \
1230 void Type##Node::Accept(NodeVisitor* visitor) { \
1231 visitor->Visit##Type(this); \
1232 }
1233FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1234#undef DEFINE_ACCEPT
1235
1236
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001237void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1238 visitor->VisitLoopChoice(this);
1239}
1240
1241
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001242// -------------------------------------------------------------------
1243// Emit code.
1244
1245
1246void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1247 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001248 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001249 switch (guard->op()) {
1250 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001251 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001252 macro_assembler->IfRegisterGE(guard->reg(),
1253 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001254 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001255 break;
1256 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001257 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001258 macro_assembler->IfRegisterLT(guard->reg(),
1259 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001260 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001261 break;
1262 }
1263}
1264
1265
1266static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1267static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1268
1269
ager@chromium.org381abbb2009-02-25 13:23:22 +00001270// Returns the number of characters in the equivalence class, omitting those
1271// that cannot occur in the source string because it is ASCII.
1272static int GetCaseIndependentLetters(uc16 character,
1273 bool ascii_subject,
1274 unibrow::uchar* letters) {
1275 int length = uncanonicalize.get(character, '\0', letters);
1276 // Unibrow returns 0 or 1 for characters where case independependence is
1277 // trivial.
1278 if (length == 0) {
1279 letters[0] = character;
1280 length = 1;
1281 }
1282 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1283 return length;
1284 }
1285 // The standard requires that non-ASCII characters cannot have ASCII
1286 // character codes in their equivalence class.
1287 return 0;
1288}
1289
1290
1291static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1292 uc16 c,
1293 Label* on_failure,
1294 int cp_offset,
1295 bool check,
1296 bool preloaded) {
1297 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1298 bool bound_checked = false;
1299 if (!preloaded) {
1300 assembler->LoadCurrentCharacter(
1301 cp_offset,
1302 on_failure,
1303 check);
1304 bound_checked = true;
1305 }
1306 assembler->CheckNotCharacter(c, on_failure);
1307 return bound_checked;
1308}
1309
1310
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001311// Only emits non-letters (things that don't have case). Only used for case
1312// independent matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001313static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1314 uc16 c,
1315 Label* on_failure,
1316 int cp_offset,
1317 bool check,
1318 bool preloaded) {
1319 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1320 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001321 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001322 int length = GetCaseIndependentLetters(c, ascii, chars);
1323 if (length < 1) {
1324 // This can't match. Must be an ASCII subject and a non-ASCII character.
1325 // We do not need to do anything since the ASCII pass already handled this.
1326 return false; // Bounds not checked.
1327 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001328 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001329 // We handle the length > 1 case in a later pass.
1330 if (length == 1) {
1331 if (ascii && c > String::kMaxAsciiCharCodeU) {
1332 // Can't match - see above.
1333 return false; // Bounds not checked.
1334 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001335 if (!preloaded) {
1336 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1337 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001338 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001339 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001340 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001341 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001342}
1343
1344
1345static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001346 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001347 uc16 c1,
1348 uc16 c2,
1349 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001350 uc16 char_mask;
1351 if (ascii) {
1352 char_mask = String::kMaxAsciiCharCode;
1353 } else {
1354 char_mask = String::kMaxUC16CharCode;
1355 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001356 uc16 exor = c1 ^ c2;
1357 // Check whether exor has only one bit set.
1358 if (((exor - 1) & exor) == 0) {
1359 // If c1 and c2 differ only by one bit.
1360 // Ecma262UnCanonicalize always gives the highest number last.
1361 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001362 uc16 mask = char_mask ^ exor;
1363 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001364 return true;
1365 }
1366 ASSERT(c2 > c1);
1367 uc16 diff = c2 - c1;
1368 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1369 // If the characters differ by 2^n but don't differ by one bit then
1370 // subtract the difference from the found character, then do the or
1371 // trick. We avoid the theoretical case where negative numbers are
1372 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001373 uc16 mask = char_mask ^ diff;
1374 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1375 diff,
1376 mask,
1377 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001378 return true;
1379 }
1380 return false;
1381}
1382
1383
ager@chromium.org381abbb2009-02-25 13:23:22 +00001384typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1385 uc16 c,
1386 Label* on_failure,
1387 int cp_offset,
1388 bool check,
1389 bool preloaded);
1390
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001391// Only emits letters (things that have case). Only used for case independent
1392// matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001393static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1394 uc16 c,
1395 Label* on_failure,
1396 int cp_offset,
1397 bool check,
1398 bool preloaded) {
1399 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1400 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001401 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001402 int length = GetCaseIndependentLetters(c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001403 if (length <= 1) return false;
1404 // We may not need to check against the end of the input string
1405 // if this character lies before a character that matched.
1406 if (!preloaded) {
1407 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001408 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001409 Label ok;
1410 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1411 switch (length) {
1412 case 2: {
1413 if (ShortCutEmitCharacterPair(macro_assembler,
1414 ascii,
1415 chars[0],
1416 chars[1],
1417 on_failure)) {
1418 } else {
1419 macro_assembler->CheckCharacter(chars[0], &ok);
1420 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1421 macro_assembler->Bind(&ok);
1422 }
1423 break;
1424 }
1425 case 4:
1426 macro_assembler->CheckCharacter(chars[3], &ok);
1427 // Fall through!
1428 case 3:
1429 macro_assembler->CheckCharacter(chars[0], &ok);
1430 macro_assembler->CheckCharacter(chars[1], &ok);
1431 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1432 macro_assembler->Bind(&ok);
1433 break;
1434 default:
1435 UNREACHABLE();
1436 break;
1437 }
1438 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001439}
1440
1441
1442static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1443 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001444 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001445 Label* on_failure,
1446 int cp_offset,
1447 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001448 bool preloaded) {
1449 if (cc->is_standard() &&
1450 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1451 cp_offset,
1452 check_offset,
1453 on_failure)) {
1454 return;
1455 }
1456
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001457 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001458 int max_char;
1459 if (ascii) {
1460 max_char = String::kMaxAsciiCharCode;
1461 } else {
1462 max_char = String::kMaxUC16CharCode;
1463 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001464
1465 Label success;
1466
1467 Label* char_is_in_class =
1468 cc->is_negated() ? on_failure : &success;
1469
1470 int range_count = ranges->length();
1471
ager@chromium.org8bb60582008-12-11 12:02:20 +00001472 int last_valid_range = range_count - 1;
1473 while (last_valid_range >= 0) {
1474 CharacterRange& range = ranges->at(last_valid_range);
1475 if (range.from() <= max_char) {
1476 break;
1477 }
1478 last_valid_range--;
1479 }
1480
1481 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001482 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001483 // TODO(plesner): We can remove this when the node level does our
1484 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001485 macro_assembler->GoTo(on_failure);
1486 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001487 if (check_offset) {
1488 macro_assembler->CheckPosition(cp_offset, on_failure);
1489 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001490 return;
1491 }
1492
ager@chromium.org8bb60582008-12-11 12:02:20 +00001493 if (last_valid_range == 0 &&
1494 !cc->is_negated() &&
1495 ranges->at(0).IsEverything(max_char)) {
1496 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001497 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001498 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001499 }
1500 return;
1501 }
1502
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001503 if (!preloaded) {
1504 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001505 }
1506
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001507 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001508 CharacterRange& range = ranges->at(i);
1509 Label next_range;
1510 uc16 from = range.from();
1511 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001512 if (from > max_char) {
1513 continue;
1514 }
1515 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001516 if (to == from) {
1517 macro_assembler->CheckCharacter(to, char_is_in_class);
1518 } else {
1519 if (from != 0) {
1520 macro_assembler->CheckCharacterLT(from, &next_range);
1521 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001522 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001523 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1524 } else {
1525 macro_assembler->GoTo(char_is_in_class);
1526 }
1527 }
1528 macro_assembler->Bind(&next_range);
1529 }
1530
ager@chromium.org8bb60582008-12-11 12:02:20 +00001531 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001532 uc16 from = range.from();
1533 uc16 to = range.to();
1534
ager@chromium.org8bb60582008-12-11 12:02:20 +00001535 if (to > max_char) to = max_char;
1536 ASSERT(to >= from);
1537
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001538 if (to == from) {
1539 if (cc->is_negated()) {
1540 macro_assembler->CheckCharacter(to, on_failure);
1541 } else {
1542 macro_assembler->CheckNotCharacter(to, on_failure);
1543 }
1544 } else {
1545 if (from != 0) {
1546 if (cc->is_negated()) {
1547 macro_assembler->CheckCharacterLT(from, &success);
1548 } else {
1549 macro_assembler->CheckCharacterLT(from, on_failure);
1550 }
1551 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001552 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001553 if (cc->is_negated()) {
1554 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1555 } else {
1556 macro_assembler->CheckCharacterGT(to, on_failure);
1557 }
1558 } else {
1559 if (cc->is_negated()) {
1560 macro_assembler->GoTo(on_failure);
1561 }
1562 }
1563 }
1564 macro_assembler->Bind(&success);
1565}
1566
1567
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001568RegExpNode::~RegExpNode() {
1569}
1570
1571
ager@chromium.org8bb60582008-12-11 12:02:20 +00001572RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001573 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001574 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001575 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001576 return CONTINUE;
1577 }
1578
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001579 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001580 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001581 if (label_.is_bound()) {
1582 // We are being asked to generate a generic version, but that's already
1583 // been done so just go to it.
1584 macro_assembler->GoTo(&label_);
1585 return DONE;
1586 }
1587 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1588 // To avoid too deep recursion we push the node to the work queue and just
1589 // generate a goto here.
1590 compiler->AddWork(this);
1591 macro_assembler->GoTo(&label_);
1592 return DONE;
1593 }
1594 // Generate generic version of the node and bind the label for later use.
1595 macro_assembler->Bind(&label_);
1596 return CONTINUE;
1597 }
1598
1599 // We are being asked to make a non-generic version. Keep track of how many
1600 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001601 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001602 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001603 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001604 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1605 return CONTINUE;
1606 }
1607
ager@chromium.org32912102009-01-16 10:38:43 +00001608 // If we get here code has been generated for this node too many times or
1609 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001610 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001611 trace->Flush(compiler, this);
1612 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001613}
1614
1615
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001616int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001617 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1618 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001619 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001620}
1621
1622
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001623int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1624 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1625 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1626}
1627
1628
1629int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1630 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1631 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1632}
1633
1634
1635int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001636 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001637 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001638 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001639 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1640 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001641}
1642
1643
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001644int NegativeLookaheadChoiceNode:: EatsAtLeast(int still_to_find,
1645 int recursion_depth) {
1646 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1647 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1648 // afterwards.
1649 RegExpNode* node = alternatives_->at(1).node();
1650 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1651}
1652
1653
1654void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1655 QuickCheckDetails* details,
1656 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001657 int filled_in,
1658 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001659 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1660 // afterwards.
1661 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001662 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001663}
1664
1665
1666int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1667 int recursion_depth,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001668 RegExpNode* ignore_this_node) {
1669 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1670 int min = 100;
1671 int choice_count = alternatives_->length();
1672 for (int i = 0; i < choice_count; i++) {
1673 RegExpNode* node = alternatives_->at(i).node();
1674 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001675 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1676 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001677 if (node_eats_at_least < min) min = node_eats_at_least;
1678 }
1679 return min;
1680}
1681
1682
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001683int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1684 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001685}
1686
1687
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001688int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1689 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001690}
1691
1692
1693// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1694static inline uint32_t SmearBitsRight(uint32_t v) {
1695 v |= v >> 1;
1696 v |= v >> 2;
1697 v |= v >> 4;
1698 v |= v >> 8;
1699 v |= v >> 16;
1700 return v;
1701}
1702
1703
1704bool QuickCheckDetails::Rationalize(bool asc) {
1705 bool found_useful_op = false;
1706 uint32_t char_mask;
1707 if (asc) {
1708 char_mask = String::kMaxAsciiCharCode;
1709 } else {
1710 char_mask = String::kMaxUC16CharCode;
1711 }
1712 mask_ = 0;
1713 value_ = 0;
1714 int char_shift = 0;
1715 for (int i = 0; i < characters_; i++) {
1716 Position* pos = &positions_[i];
1717 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1718 found_useful_op = true;
1719 }
1720 mask_ |= (pos->mask & char_mask) << char_shift;
1721 value_ |= (pos->value & char_mask) << char_shift;
1722 char_shift += asc ? 8 : 16;
1723 }
1724 return found_useful_op;
1725}
1726
1727
1728bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001729 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001730 bool preload_has_checked_bounds,
1731 Label* on_possible_success,
1732 QuickCheckDetails* details,
1733 bool fall_through_on_failure) {
1734 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001735 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1736 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001737 if (!details->Rationalize(compiler->ascii())) return false;
1738 uint32_t mask = details->mask();
1739 uint32_t value = details->value();
1740
1741 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1742
ager@chromium.org32912102009-01-16 10:38:43 +00001743 if (trace->characters_preloaded() != details->characters()) {
1744 assembler->LoadCurrentCharacter(trace->cp_offset(),
1745 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001746 !preload_has_checked_bounds,
1747 details->characters());
1748 }
1749
1750
1751 bool need_mask = true;
1752
1753 if (details->characters() == 1) {
1754 // If number of characters preloaded is 1 then we used a byte or 16 bit
1755 // load so the value is already masked down.
1756 uint32_t char_mask;
1757 if (compiler->ascii()) {
1758 char_mask = String::kMaxAsciiCharCode;
1759 } else {
1760 char_mask = String::kMaxUC16CharCode;
1761 }
1762 if ((mask & char_mask) == char_mask) need_mask = false;
1763 mask &= char_mask;
1764 } else {
1765 // For 2-character preloads in ASCII mode we also use a 16 bit load with
1766 // zero extend.
1767 if (details->characters() == 2 && compiler->ascii()) {
1768 if ((mask & 0xffff) == 0xffff) need_mask = false;
1769 } else {
1770 if (mask == 0xffffffff) need_mask = false;
1771 }
1772 }
1773
1774 if (fall_through_on_failure) {
1775 if (need_mask) {
1776 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1777 } else {
1778 assembler->CheckCharacter(value, on_possible_success);
1779 }
1780 } else {
1781 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001782 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001783 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001784 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001785 }
1786 }
1787 return true;
1788}
1789
1790
1791// Here is the meat of GetQuickCheckDetails (see also the comment on the
1792// super-class in the .h file).
1793//
1794// We iterate along the text object, building up for each character a
1795// mask and value that can be used to test for a quick failure to match.
1796// The masks and values for the positions will be combined into a single
1797// machine word for the current character width in order to be used in
1798// generating a quick check.
1799void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1800 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001801 int characters_filled_in,
1802 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001803 ASSERT(characters_filled_in < details->characters());
1804 int characters = details->characters();
1805 int char_mask;
1806 int char_shift;
1807 if (compiler->ascii()) {
1808 char_mask = String::kMaxAsciiCharCode;
1809 char_shift = 8;
1810 } else {
1811 char_mask = String::kMaxUC16CharCode;
1812 char_shift = 16;
1813 }
1814 for (int k = 0; k < elms_->length(); k++) {
1815 TextElement elm = elms_->at(k);
1816 if (elm.type == TextElement::ATOM) {
1817 Vector<const uc16> quarks = elm.data.u_atom->data();
1818 for (int i = 0; i < characters && i < quarks.length(); i++) {
1819 QuickCheckDetails::Position* pos =
1820 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001821 uc16 c = quarks[i];
1822 if (c > char_mask) {
1823 // If we expect a non-ASCII character from an ASCII string,
1824 // there is no way we can match. Not even case independent
1825 // matching can turn an ASCII character into non-ASCII or
1826 // vice versa.
1827 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001828 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001829 return;
1830 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001831 if (compiler->ignore_case()) {
1832 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001833 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1834 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1835 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001836 // This letter has no case equivalents, so it's nice and simple
1837 // and the mask-compare will determine definitely whether we have
1838 // a match at this character position.
1839 pos->mask = char_mask;
1840 pos->value = c;
1841 pos->determines_perfectly = true;
1842 } else {
1843 uint32_t common_bits = char_mask;
1844 uint32_t bits = chars[0];
1845 for (int j = 1; j < length; j++) {
1846 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1847 common_bits ^= differing_bits;
1848 bits &= common_bits;
1849 }
1850 // If length is 2 and common bits has only one zero in it then
1851 // our mask and compare instruction will determine definitely
1852 // whether we have a match at this character position. Otherwise
1853 // it can only be an approximate check.
1854 uint32_t one_zero = (common_bits | ~char_mask);
1855 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1856 pos->determines_perfectly = true;
1857 }
1858 pos->mask = common_bits;
1859 pos->value = bits;
1860 }
1861 } else {
1862 // Don't ignore case. Nice simple case where the mask-compare will
1863 // determine definitely whether we have a match at this character
1864 // position.
1865 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001866 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001867 pos->determines_perfectly = true;
1868 }
1869 characters_filled_in++;
1870 ASSERT(characters_filled_in <= details->characters());
1871 if (characters_filled_in == details->characters()) {
1872 return;
1873 }
1874 }
1875 } else {
1876 QuickCheckDetails::Position* pos =
1877 details->positions(characters_filled_in);
1878 RegExpCharacterClass* tree = elm.data.u_char_class;
1879 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001880 if (tree->is_negated()) {
1881 // A quick check uses multi-character mask and compare. There is no
1882 // useful way to incorporate a negative char class into this scheme
1883 // so we just conservatively create a mask and value that will always
1884 // succeed.
1885 pos->mask = 0;
1886 pos->value = 0;
1887 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001888 int first_range = 0;
1889 while (ranges->at(first_range).from() > char_mask) {
1890 first_range++;
1891 if (first_range == ranges->length()) {
1892 details->set_cannot_match();
1893 pos->determines_perfectly = false;
1894 return;
1895 }
1896 }
1897 CharacterRange range = ranges->at(first_range);
1898 uc16 from = range.from();
1899 uc16 to = range.to();
1900 if (to > char_mask) {
1901 to = char_mask;
1902 }
1903 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001904 // A mask and compare is only perfect if the differing bits form a
1905 // number like 00011111 with one single block of trailing 1s.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001906 if ((differing_bits & (differing_bits + 1)) == 0 &&
1907 from + differing_bits == to) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001908 pos->determines_perfectly = true;
1909 }
1910 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001911 uint32_t bits = (from & common_bits);
1912 for (int i = first_range + 1; i < ranges->length(); i++) {
1913 CharacterRange range = ranges->at(i);
1914 uc16 from = range.from();
1915 uc16 to = range.to();
1916 if (from > char_mask) continue;
1917 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001918 // Here we are combining more ranges into the mask and compare
1919 // value. With each new range the mask becomes more sparse and
1920 // so the chances of a false positive rise. A character class
1921 // with multiple ranges is assumed never to be equivalent to a
1922 // mask and compare operation.
1923 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001924 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001925 new_common_bits = ~SmearBitsRight(new_common_bits);
1926 common_bits &= new_common_bits;
1927 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001928 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001929 common_bits ^= differing_bits;
1930 bits &= common_bits;
1931 }
1932 pos->mask = common_bits;
1933 pos->value = bits;
1934 }
1935 characters_filled_in++;
1936 ASSERT(characters_filled_in <= details->characters());
1937 if (characters_filled_in == details->characters()) {
1938 return;
1939 }
1940 }
1941 }
1942 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00001943 on_success()-> GetQuickCheckDetails(details,
1944 compiler,
1945 characters_filled_in,
1946 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001947}
1948
1949
1950void QuickCheckDetails::Clear() {
1951 for (int i = 0; i < characters_; i++) {
1952 positions_[i].mask = 0;
1953 positions_[i].value = 0;
1954 positions_[i].determines_perfectly = false;
1955 }
1956 characters_ = 0;
1957}
1958
1959
1960void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001961 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001962 if (by >= characters_) {
1963 Clear();
1964 return;
1965 }
1966 for (int i = 0; i < characters_ - by; i++) {
1967 positions_[i] = positions_[by + i];
1968 }
1969 for (int i = characters_ - by; i < characters_; i++) {
1970 positions_[i].mask = 0;
1971 positions_[i].value = 0;
1972 positions_[i].determines_perfectly = false;
1973 }
1974 characters_ -= by;
1975 // We could change mask_ and value_ here but we would never advance unless
1976 // they had already been used in a check and they won't be used again because
1977 // it would gain us nothing. So there's no point.
1978}
1979
1980
1981void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1982 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001983 if (other->cannot_match_) {
1984 return;
1985 }
1986 if (cannot_match_) {
1987 *this = *other;
1988 return;
1989 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001990 for (int i = from_index; i < characters_; i++) {
1991 QuickCheckDetails::Position* pos = positions(i);
1992 QuickCheckDetails::Position* other_pos = other->positions(i);
1993 if (pos->mask != other_pos->mask ||
1994 pos->value != other_pos->value ||
1995 !other_pos->determines_perfectly) {
1996 // Our mask-compare operation will be approximate unless we have the
1997 // exact same operation on both sides of the alternation.
1998 pos->determines_perfectly = false;
1999 }
2000 pos->mask &= other_pos->mask;
2001 pos->value &= pos->mask;
2002 other_pos->value &= pos->mask;
2003 uc16 differing_bits = (pos->value ^ other_pos->value);
2004 pos->mask &= ~differing_bits;
2005 pos->value &= pos->mask;
2006 }
2007}
2008
2009
ager@chromium.org32912102009-01-16 10:38:43 +00002010class VisitMarker {
2011 public:
2012 explicit VisitMarker(NodeInfo* info) : info_(info) {
2013 ASSERT(!info->visited);
2014 info->visited = true;
2015 }
2016 ~VisitMarker() {
2017 info_->visited = false;
2018 }
2019 private:
2020 NodeInfo* info_;
2021};
2022
2023
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002024void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2025 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002026 int characters_filled_in,
2027 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002028 if (body_can_be_zero_length_ || info()->visited) return;
2029 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002030 return ChoiceNode::GetQuickCheckDetails(details,
2031 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002032 characters_filled_in,
2033 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002034}
2035
2036
2037void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2038 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002039 int characters_filled_in,
2040 bool not_at_start) {
2041 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002042 int choice_count = alternatives_->length();
2043 ASSERT(choice_count > 0);
2044 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2045 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002046 characters_filled_in,
2047 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002048 for (int i = 1; i < choice_count; i++) {
2049 QuickCheckDetails new_details(details->characters());
2050 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002051 node->GetQuickCheckDetails(&new_details, compiler,
2052 characters_filled_in,
2053 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002054 // Here we merge the quick match details of the two branches.
2055 details->Merge(&new_details, characters_filled_in);
2056 }
2057}
2058
2059
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002060// Check for [0-9A-Z_a-z].
2061static void EmitWordCheck(RegExpMacroAssembler* assembler,
2062 Label* word,
2063 Label* non_word,
2064 bool fall_through_on_word) {
2065 assembler->CheckCharacterGT('z', non_word);
2066 assembler->CheckCharacterLT('0', non_word);
2067 assembler->CheckCharacterGT('a' - 1, word);
2068 assembler->CheckCharacterLT('9' + 1, word);
2069 assembler->CheckCharacterLT('A', non_word);
2070 assembler->CheckCharacterLT('Z' + 1, word);
2071 if (fall_through_on_word) {
2072 assembler->CheckNotCharacter('_', non_word);
2073 } else {
2074 assembler->CheckCharacter('_', word);
2075 }
2076}
2077
2078
2079// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2080// that matches newline or the start of input).
2081static void EmitHat(RegExpCompiler* compiler,
2082 RegExpNode* on_success,
2083 Trace* trace) {
2084 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2085 // We will be loading the previous character into the current character
2086 // register.
2087 Trace new_trace(*trace);
2088 new_trace.InvalidateCurrentCharacter();
2089
2090 Label ok;
2091 if (new_trace.cp_offset() == 0) {
2092 // The start of input counts as a newline in this context, so skip to
2093 // ok if we are at the start.
2094 assembler->CheckAtStart(&ok);
2095 }
2096 // We already checked that we are not at the start of input so it must be
2097 // OK to load the previous character.
2098 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2099 new_trace.backtrack(),
2100 false);
2101 // Newline means \n, \r, 0x2028 or 0x2029.
2102 if (!compiler->ascii()) {
2103 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2104 }
2105 assembler->CheckCharacter('\n', &ok);
2106 assembler->CheckNotCharacter('\r', new_trace.backtrack());
2107 assembler->Bind(&ok);
2108 on_success->Emit(compiler, &new_trace);
2109}
2110
2111
2112// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2113static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2114 RegExpCompiler* compiler,
2115 RegExpNode* on_success,
2116 Trace* trace) {
2117 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2118 Label before_non_word;
2119 Label before_word;
2120 if (trace->characters_preloaded() != 1) {
2121 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2122 }
2123 // Fall through on non-word.
2124 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2125
2126 // We will be loading the previous character into the current character
2127 // register.
2128 Trace new_trace(*trace);
2129 new_trace.InvalidateCurrentCharacter();
2130
2131 Label ok;
2132 Label* boundary;
2133 Label* not_boundary;
2134 if (type == AssertionNode::AT_BOUNDARY) {
2135 boundary = &ok;
2136 not_boundary = new_trace.backtrack();
2137 } else {
2138 not_boundary = &ok;
2139 boundary = new_trace.backtrack();
2140 }
2141
2142 // Next character is not a word character.
2143 assembler->Bind(&before_non_word);
2144 if (new_trace.cp_offset() == 0) {
2145 // The start of input counts as a non-word character, so the question is
2146 // decided if we are at the start.
2147 assembler->CheckAtStart(not_boundary);
2148 }
2149 // We already checked that we are not at the start of input so it must be
2150 // OK to load the previous character.
2151 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2152 &ok, // Unused dummy label in this call.
2153 false);
2154 // Fall through on non-word.
2155 EmitWordCheck(assembler, boundary, not_boundary, false);
2156 assembler->GoTo(not_boundary);
2157
2158 // Next character is a word character.
2159 assembler->Bind(&before_word);
2160 if (new_trace.cp_offset() == 0) {
2161 // The start of input counts as a non-word character, so the question is
2162 // decided if we are at the start.
2163 assembler->CheckAtStart(boundary);
2164 }
2165 // We already checked that we are not at the start of input so it must be
2166 // OK to load the previous character.
2167 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2168 &ok, // Unused dummy label in this call.
2169 false);
2170 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2171 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2172
2173 assembler->Bind(&ok);
2174
2175 on_success->Emit(compiler, &new_trace);
2176}
2177
2178
iposva@chromium.org245aa852009-02-10 00:49:54 +00002179void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2180 RegExpCompiler* compiler,
2181 int filled_in,
2182 bool not_at_start) {
2183 if (type_ == AT_START && not_at_start) {
2184 details->set_cannot_match();
2185 return;
2186 }
2187 return on_success()->GetQuickCheckDetails(details,
2188 compiler,
2189 filled_in,
2190 not_at_start);
2191}
2192
2193
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002194void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2195 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2196 switch (type_) {
2197 case AT_END: {
2198 Label ok;
2199 assembler->CheckPosition(trace->cp_offset(), &ok);
2200 assembler->GoTo(trace->backtrack());
2201 assembler->Bind(&ok);
2202 break;
2203 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002204 case AT_START: {
2205 if (trace->at_start() == Trace::FALSE) {
2206 assembler->GoTo(trace->backtrack());
2207 return;
2208 }
2209 if (trace->at_start() == Trace::UNKNOWN) {
2210 assembler->CheckNotAtStart(trace->backtrack());
2211 Trace at_start_trace = *trace;
2212 at_start_trace.set_at_start(true);
2213 on_success()->Emit(compiler, &at_start_trace);
2214 return;
2215 }
2216 }
2217 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002218 case AFTER_NEWLINE:
2219 EmitHat(compiler, on_success(), trace);
2220 return;
2221 case AT_NON_BOUNDARY:
2222 case AT_BOUNDARY:
2223 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2224 return;
2225 }
2226 on_success()->Emit(compiler, trace);
2227}
2228
2229
ager@chromium.org381abbb2009-02-25 13:23:22 +00002230static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2231 if (quick_check == NULL) return false;
2232 if (offset >= quick_check->characters()) return false;
2233 return quick_check->positions(offset)->determines_perfectly;
2234}
2235
2236
2237static void UpdateBoundsCheck(int index, int* checked_up_to) {
2238 if (index > *checked_up_to) {
2239 *checked_up_to = index;
2240 }
2241}
2242
2243
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002244// We call this repeatedly to generate code for each pass over the text node.
2245// The passes are in increasing order of difficulty because we hope one
2246// of the first passes will fail in which case we are saved the work of the
2247// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2248// we will check the '%' in the first pass, the case independent 'a' in the
2249// second pass and the character class in the last pass.
2250//
2251// The passes are done from right to left, so for example to test for /bar/
2252// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2253// and then a 'b' with offset 0. This means we can avoid the end-of-input
2254// bounds check most of the time. In the example we only need to check for
2255// end-of-input when loading the putative 'r'.
2256//
2257// A slight complication involves the fact that the first character may already
2258// be fetched into a register by the previous node. In this case we want to
2259// do the test for that character first. We do this in separate passes. The
2260// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2261// pass has been performed then subsequent passes will have true in
2262// first_element_checked to indicate that that character does not need to be
2263// checked again.
2264//
ager@chromium.org32912102009-01-16 10:38:43 +00002265// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002266// contain an AlternativeGeneration object. In this AlternativeGeneration
2267// object we can see details of any quick check that was already passed in
2268// order to get to the code we are now generating. The quick check can involve
2269// loading characters, which means we do not need to recheck the bounds
2270// up to the limit the quick check already checked. In addition the quick
2271// check can have involved a mask and compare operation which may simplify
2272// or obviate the need for further checks at some character positions.
2273void TextNode::TextEmitPass(RegExpCompiler* compiler,
2274 TextEmitPassType pass,
2275 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002276 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002277 bool first_element_checked,
2278 int* checked_up_to) {
2279 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2280 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002281 Label* backtrack = trace->backtrack();
2282 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002283 int element_count = elms_->length();
2284 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2285 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002286 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002287 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002288 Vector<const uc16> quarks = elm.data.u_atom->data();
2289 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2290 if (first_element_checked && i == 0 && j == 0) continue;
2291 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2292 EmitCharacterFunction* emit_function = NULL;
2293 switch (pass) {
2294 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002295 ASSERT(ascii);
2296 if (quarks[j] > String::kMaxAsciiCharCode) {
2297 assembler->GoTo(backtrack);
2298 return;
2299 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002300 break;
2301 case NON_LETTER_CHARACTER_MATCH:
2302 emit_function = &EmitAtomNonLetter;
2303 break;
2304 case SIMPLE_CHARACTER_MATCH:
2305 emit_function = &EmitSimpleCharacter;
2306 break;
2307 case CASE_CHARACTER_MATCH:
2308 emit_function = &EmitAtomLetter;
2309 break;
2310 default:
2311 break;
2312 }
2313 if (emit_function != NULL) {
2314 bool bound_checked = emit_function(compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002315 quarks[j],
2316 backtrack,
2317 cp_offset + j,
2318 *checked_up_to < cp_offset + j,
2319 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002320 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002321 }
2322 }
2323 } else {
2324 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002325 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002326 if (first_element_checked && i == 0) continue;
2327 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002328 RegExpCharacterClass* cc = elm.data.u_char_class;
2329 EmitCharClass(assembler,
2330 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002331 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002332 backtrack,
2333 cp_offset,
2334 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002335 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002336 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002337 }
2338 }
2339 }
2340}
2341
2342
2343int TextNode::Length() {
2344 TextElement elm = elms_->last();
2345 ASSERT(elm.cp_offset >= 0);
2346 if (elm.type == TextElement::ATOM) {
2347 return elm.cp_offset + elm.data.u_atom->data().length();
2348 } else {
2349 return elm.cp_offset + 1;
2350 }
2351}
2352
2353
ager@chromium.org381abbb2009-02-25 13:23:22 +00002354bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2355 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2356 if (ignore_case) {
2357 return pass == SIMPLE_CHARACTER_MATCH;
2358 } else {
2359 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2360 }
2361}
2362
2363
ager@chromium.org8bb60582008-12-11 12:02:20 +00002364// This generates the code to match a text node. A text node can contain
2365// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002366// way) and character classes. For efficiency we do not do this in a single
2367// pass from left to right. Instead we pass over the text node several times,
2368// emitting code for some character positions every time. See the comment on
2369// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002370void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002371 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002372 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002373 ASSERT(limit_result == CONTINUE);
2374
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002375 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2376 compiler->SetRegExpTooBig();
2377 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002378 }
2379
2380 if (compiler->ascii()) {
2381 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002382 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002383 }
2384
2385 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002386 int bound_checked_to = trace->cp_offset() - 1;
2387 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002388
2389 // If a character is preloaded into the current character register then
2390 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002391 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002392 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2393 if (!SkipPass(pass, compiler->ignore_case())) {
2394 TextEmitPass(compiler,
2395 static_cast<TextEmitPassType>(pass),
2396 true,
2397 trace,
2398 false,
2399 &bound_checked_to);
2400 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002401 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002402 first_elt_done = true;
2403 }
2404
ager@chromium.org381abbb2009-02-25 13:23:22 +00002405 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2406 if (!SkipPass(pass, compiler->ignore_case())) {
2407 TextEmitPass(compiler,
2408 static_cast<TextEmitPassType>(pass),
2409 false,
2410 trace,
2411 first_elt_done,
2412 &bound_checked_to);
2413 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002414 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002415
ager@chromium.org32912102009-01-16 10:38:43 +00002416 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002417 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002418 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002419 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002420 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002421}
2422
2423
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002424void Trace::InvalidateCurrentCharacter() {
2425 characters_preloaded_ = 0;
2426}
2427
2428
2429void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002430 ASSERT(by > 0);
2431 // We don't have an instruction for shifting the current character register
2432 // down or for using a shifted value for anything so lets just forget that
2433 // we preloaded any characters into it.
2434 characters_preloaded_ = 0;
2435 // Adjust the offsets of the quick check performed information. This
2436 // information is used to find out what we already determined about the
2437 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002438 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002439 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002440 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2441 compiler->SetRegExpTooBig();
2442 cp_offset_ = 0;
2443 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002444 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002445}
2446
2447
2448void TextNode::MakeCaseIndependent() {
2449 int element_count = elms_->length();
2450 for (int i = 0; i < element_count; i++) {
2451 TextElement elm = elms_->at(i);
2452 if (elm.type == TextElement::CHAR_CLASS) {
2453 RegExpCharacterClass* cc = elm.data.u_char_class;
2454 ZoneList<CharacterRange>* ranges = cc->ranges();
2455 int range_count = ranges->length();
2456 for (int i = 0; i < range_count; i++) {
2457 ranges->at(i).AddCaseEquivalents(ranges);
2458 }
2459 }
2460 }
2461}
2462
2463
ager@chromium.org8bb60582008-12-11 12:02:20 +00002464int TextNode::GreedyLoopTextLength() {
2465 TextElement elm = elms_->at(elms_->length() - 1);
2466 if (elm.type == TextElement::CHAR_CLASS) {
2467 return elm.cp_offset + 1;
2468 } else {
2469 return elm.cp_offset + elm.data.u_atom->data().length();
2470 }
2471}
2472
2473
2474// Finds the fixed match length of a sequence of nodes that goes from
2475// this alternative and back to this choice node. If there are variable
2476// length nodes or other complications in the way then return a sentinel
2477// value indicating that a greedy loop cannot be constructed.
2478int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2479 int length = 0;
2480 RegExpNode* node = alternative->node();
2481 // Later we will generate code for all these text nodes using recursion
2482 // so we have to limit the max number.
2483 int recursion_depth = 0;
2484 while (node != this) {
2485 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2486 return kNodeIsTooComplexForGreedyLoops;
2487 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002488 int node_length = node->GreedyLoopTextLength();
2489 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2490 return kNodeIsTooComplexForGreedyLoops;
2491 }
2492 length += node_length;
2493 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2494 node = seq_node->on_success();
2495 }
2496 return length;
2497}
2498
2499
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002500void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2501 ASSERT_EQ(loop_node_, NULL);
2502 AddAlternative(alt);
2503 loop_node_ = alt.node();
2504}
2505
2506
2507void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2508 ASSERT_EQ(continue_node_, NULL);
2509 AddAlternative(alt);
2510 continue_node_ = alt.node();
2511}
2512
2513
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002514void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002515 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002516 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002517 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2518 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2519 // Update the counter-based backtracking info on the stack. This is an
2520 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002521 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002522 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002523 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002524 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002525 }
ager@chromium.org32912102009-01-16 10:38:43 +00002526 ASSERT(trace->stop_node() == NULL);
2527 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002528 trace->Flush(compiler, this);
2529 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002530 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002531 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002532}
2533
2534
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002535int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002536 int preload_characters = EatsAtLeast(4, 0);
ager@chromium.org9085a012009-05-11 19:22:57 +00002537#ifdef V8_HOST_CAN_READ_UNALIGNED
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002538 bool ascii = compiler->ascii();
2539 if (ascii) {
2540 if (preload_characters > 4) preload_characters = 4;
2541 // We can't preload 3 characters because there is no machine instruction
2542 // to do that. We can't just load 4 because we could be reading
2543 // beyond the end of the string, which could cause a memory fault.
2544 if (preload_characters == 3) preload_characters = 2;
2545 } else {
2546 if (preload_characters > 2) preload_characters = 2;
2547 }
2548#else
2549 if (preload_characters > 1) preload_characters = 1;
2550#endif
2551 return preload_characters;
2552}
2553
2554
2555// This class is used when generating the alternatives in a choice node. It
2556// records the way the alternative is being code generated.
2557class AlternativeGeneration: public Malloced {
2558 public:
2559 AlternativeGeneration()
2560 : possible_success(),
2561 expects_preload(false),
2562 after(),
2563 quick_check_details() { }
2564 Label possible_success;
2565 bool expects_preload;
2566 Label after;
2567 QuickCheckDetails quick_check_details;
2568};
2569
2570
2571// Creates a list of AlternativeGenerations. If the list has a reasonable
2572// size then it is on the stack, otherwise the excess is on the heap.
2573class AlternativeGenerationList {
2574 public:
2575 explicit AlternativeGenerationList(int count)
2576 : alt_gens_(count) {
2577 for (int i = 0; i < count && i < kAFew; i++) {
2578 alt_gens_.Add(a_few_alt_gens_ + i);
2579 }
2580 for (int i = kAFew; i < count; i++) {
2581 alt_gens_.Add(new AlternativeGeneration());
2582 }
2583 }
2584 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002585 for (int i = kAFew; i < alt_gens_.length(); i++) {
2586 delete alt_gens_[i];
2587 alt_gens_[i] = NULL;
2588 }
2589 }
2590
2591 AlternativeGeneration* at(int i) {
2592 return alt_gens_[i];
2593 }
2594 private:
2595 static const int kAFew = 10;
2596 ZoneList<AlternativeGeneration*> alt_gens_;
2597 AlternativeGeneration a_few_alt_gens_[kAFew];
2598};
2599
2600
2601/* Code generation for choice nodes.
2602 *
2603 * We generate quick checks that do a mask and compare to eliminate a
2604 * choice. If the quick check succeeds then it jumps to the continuation to
2605 * do slow checks and check subsequent nodes. If it fails (the common case)
2606 * it falls through to the next choice.
2607 *
2608 * Here is the desired flow graph. Nodes directly below each other imply
2609 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2610 * 3 doesn't have a quick check so we have to call the slow check.
2611 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2612 * regexp continuation is generated directly after the Sn node, up to the
2613 * next GoTo if we decide to reuse some already generated code. Some
2614 * nodes expect preload_characters to be preloaded into the current
2615 * character register. R nodes do this preloading. Vertices are marked
2616 * F for failures and S for success (possible success in the case of quick
2617 * nodes). L, V, < and > are used as arrow heads.
2618 *
2619 * ----------> R
2620 * |
2621 * V
2622 * Q1 -----> S1
2623 * | S /
2624 * F| /
2625 * | F/
2626 * | /
2627 * | R
2628 * | /
2629 * V L
2630 * Q2 -----> S2
2631 * | S /
2632 * F| /
2633 * | F/
2634 * | /
2635 * | R
2636 * | /
2637 * V L
2638 * S3
2639 * |
2640 * F|
2641 * |
2642 * R
2643 * |
2644 * backtrack V
2645 * <----------Q4
2646 * \ F |
2647 * \ |S
2648 * \ F V
2649 * \-----S4
2650 *
2651 * For greedy loops we reverse our expectation and expect to match rather
2652 * than fail. Therefore we want the loop code to look like this (U is the
2653 * unwind code that steps back in the greedy loop). The following alternatives
2654 * look the same as above.
2655 * _____
2656 * / \
2657 * V |
2658 * ----------> S1 |
2659 * /| |
2660 * / |S |
2661 * F/ \_____/
2662 * /
2663 * |<-----------
2664 * | \
2665 * V \
2666 * Q2 ---> S2 \
2667 * | S / |
2668 * F| / |
2669 * | F/ |
2670 * | / |
2671 * | R |
2672 * | / |
2673 * F VL |
2674 * <------U |
2675 * back |S |
2676 * \______________/
2677 */
2678
2679
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002680void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002681 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2682 int choice_count = alternatives_->length();
2683#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002684 for (int i = 0; i < choice_count - 1; i++) {
2685 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002686 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002687 int guard_count = (guards == NULL) ? 0 : guards->length();
2688 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002689 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002690 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002691 }
2692#endif
2693
ager@chromium.org32912102009-01-16 10:38:43 +00002694 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002695 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002696 ASSERT(limit_result == CONTINUE);
2697
ager@chromium.org381abbb2009-02-25 13:23:22 +00002698 int new_flush_budget = trace->flush_budget() / choice_count;
2699 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2700 trace->Flush(compiler, this);
2701 return;
2702 }
2703
ager@chromium.org8bb60582008-12-11 12:02:20 +00002704 RecursionCheck rc(compiler);
2705
ager@chromium.org32912102009-01-16 10:38:43 +00002706 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002707
2708 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2709 bool greedy_loop = false;
2710 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002711 Trace counter_backtrack_trace;
2712 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002713 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2714
ager@chromium.org8bb60582008-12-11 12:02:20 +00002715 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2716 // Here we have special handling for greedy loops containing only text nodes
2717 // and other simple nodes. These are handled by pushing the current
2718 // position on the stack and then incrementing the current position each
2719 // time around the switch. On backtrack we decrement the current position
2720 // and check it against the pushed value. This avoids pushing backtrack
2721 // information for each iteration of the loop, which could take up a lot of
2722 // space.
2723 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002724 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002725 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002726 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002727 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002728 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002729 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002730 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002731 Label loop_label;
2732 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002733 greedy_match_trace.set_stop_node(this);
2734 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002735 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002736 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002737 }
2738
2739 Label second_choice; // For use in greedy matches.
2740 macro_assembler->Bind(&second_choice);
2741
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002742 int first_normal_choice = greedy_loop ? 1 : 0;
2743
2744 int preload_characters = CalculatePreloadCharacters(compiler);
2745 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002746 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002747 bool preload_has_checked_bounds = preload_is_current;
2748
2749 AlternativeGenerationList alt_gens(choice_count);
2750
ager@chromium.org8bb60582008-12-11 12:02:20 +00002751 // For now we just call all choices one after the other. The idea ultimately
2752 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002753 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002754 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002755 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002756 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002757 ZoneList<Guard*>* guards = alternative.guards();
2758 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002759 Trace new_trace(*current_trace);
2760 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002761 preload_characters :
2762 0);
2763 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002764 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002765 }
ager@chromium.org32912102009-01-16 10:38:43 +00002766 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002767 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002768 alt_gen->expects_preload = preload_is_current;
2769 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002770 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002771 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002772 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002773 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002774 preload_has_checked_bounds,
2775 &alt_gen->possible_success,
2776 &alt_gen->quick_check_details,
2777 i < choice_count - 1)) {
2778 // Quick check was generated for this choice.
2779 preload_is_current = true;
2780 preload_has_checked_bounds = true;
2781 // On the last choice in the ChoiceNode we generated the quick
2782 // check to fall through on possible success. So now we need to
2783 // generate the full check inline.
2784 if (i == choice_count - 1) {
2785 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002786 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2787 new_trace.set_characters_preloaded(preload_characters);
2788 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002789 generate_full_check_inline = true;
2790 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002791 } else if (alt_gen->quick_check_details.cannot_match()) {
2792 if (i == choice_count - 1 && !greedy_loop) {
2793 macro_assembler->GoTo(trace->backtrack());
2794 }
2795 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002796 } else {
2797 // No quick check was generated. Put the full code here.
2798 // If this is not the first choice then there could be slow checks from
2799 // previous cases that go here when they fail. There's no reason to
2800 // insist that they preload characters since the slow check we are about
2801 // to generate probably can't use it.
2802 if (i != first_normal_choice) {
2803 alt_gen->expects_preload = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002804 new_trace.set_characters_preloaded(0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002805 }
2806 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002807 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002808 }
2809 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002810 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002811 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002812 if (new_trace.actions() != NULL) {
2813 new_trace.set_flush_budget(new_flush_budget);
2814 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002815 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002816 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002817 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002818 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002819 preload_is_current = false;
2820 }
2821 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002822 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002823 if (greedy_loop) {
2824 macro_assembler->Bind(&greedy_loop_label);
2825 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002826 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002827 // Otherwise try the second priority at an earlier position.
2828 macro_assembler->AdvanceCurrentPosition(-text_length);
2829 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002830 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002831
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002832 // At this point we need to generate slow checks for the alternatives where
2833 // the quick check was inlined. We can recognize these because the associated
2834 // label was bound.
2835 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2836 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002837 Trace new_trace(*current_trace);
2838 // If there are actions to be flushed we have to limit how many times
2839 // they are flushed. Take the budget of the parent trace and distribute
2840 // it fairly amongst the children.
2841 if (new_trace.actions() != NULL) {
2842 new_trace.set_flush_budget(new_flush_budget);
2843 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002844 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002845 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002846 alternatives_->at(i),
2847 alt_gen,
2848 preload_characters,
2849 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002850 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002851}
2852
2853
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002854void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002855 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002856 GuardedAlternative alternative,
2857 AlternativeGeneration* alt_gen,
2858 int preload_characters,
2859 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002860 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002861
2862 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2863 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002864 Trace out_of_line_trace(*trace);
2865 out_of_line_trace.set_characters_preloaded(preload_characters);
2866 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002867 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002868 ZoneList<Guard*>* guards = alternative.guards();
2869 int guard_count = (guards == NULL) ? 0 : guards->length();
2870 if (next_expects_preload) {
2871 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00002872 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002873 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002874 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002875 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002876 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002877 macro_assembler->Bind(&reload_current_char);
2878 // Reload the current character, since the next quick check expects that.
2879 // We don't need to check bounds here because we only get into this
2880 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00002881 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002882 NULL,
2883 false,
2884 preload_characters);
2885 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002886 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00002887 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002888 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002889 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002890 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002891 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002892 }
2893}
2894
2895
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002896void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002897 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002898 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002899 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002900 ASSERT(limit_result == CONTINUE);
2901
2902 RecursionCheck rc(compiler);
2903
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002904 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002905 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00002906 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002907 new_capture(data_.u_position_register.reg,
2908 data_.u_position_register.is_capture,
2909 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002910 Trace new_trace = *trace;
2911 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002912 on_success()->Emit(compiler, &new_trace);
2913 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002914 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002915 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002916 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002917 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00002918 Trace new_trace = *trace;
2919 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002920 on_success()->Emit(compiler, &new_trace);
2921 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002922 }
2923 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002924 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002925 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00002926 Trace new_trace = *trace;
2927 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002928 on_success()->Emit(compiler, &new_trace);
2929 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002930 }
2931 case CLEAR_CAPTURES: {
2932 Trace::DeferredClearCaptures
2933 new_capture(Interval(data_.u_clear_captures.range_from,
2934 data_.u_clear_captures.range_to));
2935 Trace new_trace = *trace;
2936 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002937 on_success()->Emit(compiler, &new_trace);
2938 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002939 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002940 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002941 if (!trace->is_trivial()) {
2942 trace->Flush(compiler, this);
2943 } else {
2944 assembler->WriteCurrentPositionToRegister(
2945 data_.u_submatch.current_position_register, 0);
2946 assembler->WriteStackPointerToRegister(
2947 data_.u_submatch.stack_pointer_register);
2948 on_success()->Emit(compiler, trace);
2949 }
2950 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002951 case EMPTY_MATCH_CHECK: {
2952 int start_pos_reg = data_.u_empty_match_check.start_register;
2953 int stored_pos = 0;
2954 int rep_reg = data_.u_empty_match_check.repetition_register;
2955 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
2956 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
2957 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
2958 // If we know we haven't advanced and there is no minimum we
2959 // can just backtrack immediately.
2960 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00002961 } else if (know_dist && stored_pos < trace->cp_offset()) {
2962 // If we know we've advanced we can generate the continuation
2963 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002964 on_success()->Emit(compiler, trace);
2965 } else if (!trace->is_trivial()) {
2966 trace->Flush(compiler, this);
2967 } else {
2968 Label skip_empty_check;
2969 // If we have a minimum number of repetitions we check the current
2970 // number first and skip the empty check if it's not enough.
2971 if (has_minimum) {
2972 int limit = data_.u_empty_match_check.repetition_limit;
2973 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
2974 }
2975 // If the match is empty we bail out, otherwise we fall through
2976 // to the on-success continuation.
2977 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
2978 trace->backtrack());
2979 assembler->Bind(&skip_empty_check);
2980 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002981 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002982 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002983 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002984 case POSITIVE_SUBMATCH_SUCCESS: {
2985 if (!trace->is_trivial()) {
2986 trace->Flush(compiler, this);
2987 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002988 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002989 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00002990 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002991 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002992 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002993 int clear_register_count = data_.u_submatch.clear_register_count;
2994 if (clear_register_count == 0) {
2995 on_success()->Emit(compiler, trace);
2996 return;
2997 }
2998 int clear_registers_from = data_.u_submatch.clear_register_from;
2999 Label clear_registers_backtrack;
3000 Trace new_trace = *trace;
3001 new_trace.set_backtrack(&clear_registers_backtrack);
3002 on_success()->Emit(compiler, &new_trace);
3003
3004 assembler->Bind(&clear_registers_backtrack);
3005 int clear_registers_to = clear_registers_from + clear_register_count - 1;
3006 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
3007
3008 ASSERT(trace->backtrack() == NULL);
3009 assembler->Backtrack();
3010 return;
3011 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003012 default:
3013 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003014 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003015}
3016
3017
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003018void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003019 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00003020 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003021 trace->Flush(compiler, this);
3022 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003023 }
3024
ager@chromium.org32912102009-01-16 10:38:43 +00003025 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003026 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003027 ASSERT(limit_result == CONTINUE);
3028
3029 RecursionCheck rc(compiler);
3030
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003031 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003032 if (compiler->ignore_case()) {
3033 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3034 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003035 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003036 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003037 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003038 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003039}
3040
3041
3042// -------------------------------------------------------------------
3043// Dot/dotty output
3044
3045
3046#ifdef DEBUG
3047
3048
3049class DotPrinter: public NodeVisitor {
3050 public:
3051 explicit DotPrinter(bool ignore_case)
3052 : ignore_case_(ignore_case),
3053 stream_(&alloc_) { }
3054 void PrintNode(const char* label, RegExpNode* node);
3055 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003056 void PrintAttributes(RegExpNode* from);
3057 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003058 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003059#define DECLARE_VISIT(Type) \
3060 virtual void Visit##Type(Type##Node* that);
3061FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3062#undef DECLARE_VISIT
3063 private:
3064 bool ignore_case_;
3065 HeapStringAllocator alloc_;
3066 StringStream stream_;
3067};
3068
3069
3070void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3071 stream()->Add("digraph G {\n graph [label=\"");
3072 for (int i = 0; label[i]; i++) {
3073 switch (label[i]) {
3074 case '\\':
3075 stream()->Add("\\\\");
3076 break;
3077 case '"':
3078 stream()->Add("\"");
3079 break;
3080 default:
3081 stream()->Put(label[i]);
3082 break;
3083 }
3084 }
3085 stream()->Add("\"];\n");
3086 Visit(node);
3087 stream()->Add("}\n");
3088 printf("%s", *(stream()->ToCString()));
3089}
3090
3091
3092void DotPrinter::Visit(RegExpNode* node) {
3093 if (node->info()->visited) return;
3094 node->info()->visited = true;
3095 node->Accept(this);
3096}
3097
3098
3099void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003100 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3101 Visit(on_failure);
3102}
3103
3104
3105class TableEntryBodyPrinter {
3106 public:
3107 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3108 : stream_(stream), choice_(choice) { }
3109 void Call(uc16 from, DispatchTable::Entry entry) {
3110 OutSet* out_set = entry.out_set();
3111 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3112 if (out_set->Get(i)) {
3113 stream()->Add(" n%p:s%io%i -> n%p;\n",
3114 choice(),
3115 from,
3116 i,
3117 choice()->alternatives()->at(i).node());
3118 }
3119 }
3120 }
3121 private:
3122 StringStream* stream() { return stream_; }
3123 ChoiceNode* choice() { return choice_; }
3124 StringStream* stream_;
3125 ChoiceNode* choice_;
3126};
3127
3128
3129class TableEntryHeaderPrinter {
3130 public:
3131 explicit TableEntryHeaderPrinter(StringStream* stream)
3132 : first_(true), stream_(stream) { }
3133 void Call(uc16 from, DispatchTable::Entry entry) {
3134 if (first_) {
3135 first_ = false;
3136 } else {
3137 stream()->Add("|");
3138 }
3139 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3140 OutSet* out_set = entry.out_set();
3141 int priority = 0;
3142 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3143 if (out_set->Get(i)) {
3144 if (priority > 0) stream()->Add("|");
3145 stream()->Add("<s%io%i> %i", from, i, priority);
3146 priority++;
3147 }
3148 }
3149 stream()->Add("}}");
3150 }
3151 private:
3152 bool first_;
3153 StringStream* stream() { return stream_; }
3154 StringStream* stream_;
3155};
3156
3157
3158class AttributePrinter {
3159 public:
3160 explicit AttributePrinter(DotPrinter* out)
3161 : out_(out), first_(true) { }
3162 void PrintSeparator() {
3163 if (first_) {
3164 first_ = false;
3165 } else {
3166 out_->stream()->Add("|");
3167 }
3168 }
3169 void PrintBit(const char* name, bool value) {
3170 if (!value) return;
3171 PrintSeparator();
3172 out_->stream()->Add("{%s}", name);
3173 }
3174 void PrintPositive(const char* name, int value) {
3175 if (value < 0) return;
3176 PrintSeparator();
3177 out_->stream()->Add("{%s|%x}", name, value);
3178 }
3179 private:
3180 DotPrinter* out_;
3181 bool first_;
3182};
3183
3184
3185void DotPrinter::PrintAttributes(RegExpNode* that) {
3186 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3187 "margin=0.1, fontsize=10, label=\"{",
3188 that);
3189 AttributePrinter printer(this);
3190 NodeInfo* info = that->info();
3191 printer.PrintBit("NI", info->follows_newline_interest);
3192 printer.PrintBit("WI", info->follows_word_interest);
3193 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003194 Label* label = that->label();
3195 if (label->is_bound())
3196 printer.PrintPositive("@", label->pos());
3197 stream()->Add("}\"];\n");
3198 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3199 "arrowhead=none];\n", that, that);
3200}
3201
3202
3203static const bool kPrintDispatchTable = false;
3204void DotPrinter::VisitChoice(ChoiceNode* that) {
3205 if (kPrintDispatchTable) {
3206 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3207 TableEntryHeaderPrinter header_printer(stream());
3208 that->GetTable(ignore_case_)->ForEach(&header_printer);
3209 stream()->Add("\"]\n", that);
3210 PrintAttributes(that);
3211 TableEntryBodyPrinter body_printer(stream(), that);
3212 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003213 } else {
3214 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3215 for (int i = 0; i < that->alternatives()->length(); i++) {
3216 GuardedAlternative alt = that->alternatives()->at(i);
3217 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3218 }
3219 }
3220 for (int i = 0; i < that->alternatives()->length(); i++) {
3221 GuardedAlternative alt = that->alternatives()->at(i);
3222 alt.node()->Accept(this);
3223 }
3224}
3225
3226
3227void DotPrinter::VisitText(TextNode* that) {
3228 stream()->Add(" n%p [label=\"", that);
3229 for (int i = 0; i < that->elements()->length(); i++) {
3230 if (i > 0) stream()->Add(" ");
3231 TextElement elm = that->elements()->at(i);
3232 switch (elm.type) {
3233 case TextElement::ATOM: {
3234 stream()->Add("'%w'", elm.data.u_atom->data());
3235 break;
3236 }
3237 case TextElement::CHAR_CLASS: {
3238 RegExpCharacterClass* node = elm.data.u_char_class;
3239 stream()->Add("[");
3240 if (node->is_negated())
3241 stream()->Add("^");
3242 for (int j = 0; j < node->ranges()->length(); j++) {
3243 CharacterRange range = node->ranges()->at(j);
3244 stream()->Add("%k-%k", range.from(), range.to());
3245 }
3246 stream()->Add("]");
3247 break;
3248 }
3249 default:
3250 UNREACHABLE();
3251 }
3252 }
3253 stream()->Add("\", shape=box, peripheries=2];\n");
3254 PrintAttributes(that);
3255 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3256 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003257}
3258
3259
3260void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3261 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3262 that,
3263 that->start_register(),
3264 that->end_register());
3265 PrintAttributes(that);
3266 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3267 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003268}
3269
3270
3271void DotPrinter::VisitEnd(EndNode* that) {
3272 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3273 PrintAttributes(that);
3274}
3275
3276
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003277void DotPrinter::VisitAssertion(AssertionNode* that) {
3278 stream()->Add(" n%p [", that);
3279 switch (that->type()) {
3280 case AssertionNode::AT_END:
3281 stream()->Add("label=\"$\", shape=septagon");
3282 break;
3283 case AssertionNode::AT_START:
3284 stream()->Add("label=\"^\", shape=septagon");
3285 break;
3286 case AssertionNode::AT_BOUNDARY:
3287 stream()->Add("label=\"\\b\", shape=septagon");
3288 break;
3289 case AssertionNode::AT_NON_BOUNDARY:
3290 stream()->Add("label=\"\\B\", shape=septagon");
3291 break;
3292 case AssertionNode::AFTER_NEWLINE:
3293 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3294 break;
3295 }
3296 stream()->Add("];\n");
3297 PrintAttributes(that);
3298 RegExpNode* successor = that->on_success();
3299 stream()->Add(" n%p -> n%p;\n", that, successor);
3300 Visit(successor);
3301}
3302
3303
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003304void DotPrinter::VisitAction(ActionNode* that) {
3305 stream()->Add(" n%p [", that);
3306 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003307 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003308 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3309 that->data_.u_store_register.reg,
3310 that->data_.u_store_register.value);
3311 break;
3312 case ActionNode::INCREMENT_REGISTER:
3313 stream()->Add("label=\"$%i++\", shape=octagon",
3314 that->data_.u_increment_register.reg);
3315 break;
3316 case ActionNode::STORE_POSITION:
3317 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3318 that->data_.u_position_register.reg);
3319 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003320 case ActionNode::BEGIN_SUBMATCH:
3321 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3322 that->data_.u_submatch.current_position_register);
3323 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003324 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003325 stream()->Add("label=\"escape\", shape=septagon");
3326 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003327 case ActionNode::EMPTY_MATCH_CHECK:
3328 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3329 that->data_.u_empty_match_check.start_register,
3330 that->data_.u_empty_match_check.repetition_register,
3331 that->data_.u_empty_match_check.repetition_limit);
3332 break;
3333 case ActionNode::CLEAR_CAPTURES: {
3334 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3335 that->data_.u_clear_captures.range_from,
3336 that->data_.u_clear_captures.range_to);
3337 break;
3338 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003339 }
3340 stream()->Add("];\n");
3341 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003342 RegExpNode* successor = that->on_success();
3343 stream()->Add(" n%p -> n%p;\n", that, successor);
3344 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003345}
3346
3347
3348class DispatchTableDumper {
3349 public:
3350 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3351 void Call(uc16 key, DispatchTable::Entry entry);
3352 StringStream* stream() { return stream_; }
3353 private:
3354 StringStream* stream_;
3355};
3356
3357
3358void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3359 stream()->Add("[%k-%k]: {", key, entry.to());
3360 OutSet* set = entry.out_set();
3361 bool first = true;
3362 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3363 if (set->Get(i)) {
3364 if (first) {
3365 first = false;
3366 } else {
3367 stream()->Add(", ");
3368 }
3369 stream()->Add("%i", i);
3370 }
3371 }
3372 stream()->Add("}\n");
3373}
3374
3375
3376void DispatchTable::Dump() {
3377 HeapStringAllocator alloc;
3378 StringStream stream(&alloc);
3379 DispatchTableDumper dumper(&stream);
3380 tree()->ForEach(&dumper);
3381 OS::PrintError("%s", *stream.ToCString());
3382}
3383
3384
3385void RegExpEngine::DotPrint(const char* label,
3386 RegExpNode* node,
3387 bool ignore_case) {
3388 DotPrinter printer(ignore_case);
3389 printer.PrintNode(label, node);
3390}
3391
3392
3393#endif // DEBUG
3394
3395
3396// -------------------------------------------------------------------
3397// Tree to graph conversion
3398
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003399static const int kSpaceRangeCount = 20;
3400static const int kSpaceRangeAsciiCount = 4;
3401static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3402 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3403 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3404
3405static const int kWordRangeCount = 8;
3406static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3407 '_', 'a', 'z' };
3408
3409static const int kDigitRangeCount = 2;
3410static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3411
3412static const int kLineTerminatorRangeCount = 6;
3413static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3414 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003415
3416RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003417 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003418 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3419 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003420 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003421}
3422
3423
3424RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003425 RegExpNode* on_success) {
3426 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003427}
3428
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003429static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3430 const uc16* special_class,
3431 int length) {
3432 ASSERT(ranges->length() != 0);
3433 ASSERT(length != 0);
3434 ASSERT(special_class[0] != 0);
3435 if (ranges->length() != (length >> 1) + 1) {
3436 return false;
3437 }
3438 CharacterRange range = ranges->at(0);
3439 if (range.from() != 0) {
3440 return false;
3441 }
3442 for (int i = 0; i < length; i += 2) {
3443 if (special_class[i] != (range.to() + 1)) {
3444 return false;
3445 }
3446 range = ranges->at((i >> 1) + 1);
3447 if (special_class[i+1] != range.from() - 1) {
3448 return false;
3449 }
3450 }
3451 if (range.to() != 0xffff) {
3452 return false;
3453 }
3454 return true;
3455}
3456
3457
3458static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3459 const uc16* special_class,
3460 int length) {
3461 if (ranges->length() * 2 != length) {
3462 return false;
3463 }
3464 for (int i = 0; i < length; i += 2) {
3465 CharacterRange range = ranges->at(i >> 1);
3466 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3467 return false;
3468 }
3469 }
3470 return true;
3471}
3472
3473
3474bool RegExpCharacterClass::is_standard() {
3475 // TODO(lrn): Remove need for this function, by not throwing away information
3476 // along the way.
3477 if (is_negated_) {
3478 return false;
3479 }
3480 if (set_.is_standard()) {
3481 return true;
3482 }
3483 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3484 set_.set_standard_set_type('s');
3485 return true;
3486 }
3487 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3488 set_.set_standard_set_type('S');
3489 return true;
3490 }
3491 if (CompareInverseRanges(set_.ranges(),
3492 kLineTerminatorRanges,
3493 kLineTerminatorRangeCount)) {
3494 set_.set_standard_set_type('.');
3495 return true;
3496 }
3497 return false;
3498}
3499
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003500
3501RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003502 RegExpNode* on_success) {
3503 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003504}
3505
3506
3507RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003508 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003509 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3510 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003511 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003512 for (int i = 0; i < length; i++) {
3513 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003514 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003515 result->AddAlternative(alternative);
3516 }
3517 return result;
3518}
3519
3520
3521RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003522 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003523 return ToNode(min(),
3524 max(),
3525 is_greedy(),
3526 body(),
3527 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003528 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003529}
3530
3531
3532RegExpNode* RegExpQuantifier::ToNode(int min,
3533 int max,
3534 bool is_greedy,
3535 RegExpTree* body,
3536 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003537 RegExpNode* on_success,
3538 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003539 // x{f, t} becomes this:
3540 //
3541 // (r++)<-.
3542 // | `
3543 // | (x)
3544 // v ^
3545 // (r=0)-->(?)---/ [if r < t]
3546 // |
3547 // [if r >= f] \----> ...
3548 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003549
3550 // 15.10.2.5 RepeatMatcher algorithm.
3551 // The parser has already eliminated the case where max is 0. In the case
3552 // where max_match is zero the parser has removed the quantifier if min was
3553 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3554
3555 // If we know that we cannot match zero length then things are a little
3556 // simpler since we don't need to make the special zero length match check
3557 // from step 2.1. If the min and max are small we can unroll a little in
3558 // this case.
3559 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3560 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3561 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003562 bool body_can_be_empty = (body->min_match() == 0);
3563 int body_start_reg = RegExpCompiler::kNoRegister;
3564 Interval capture_registers = body->CaptureRegisters();
3565 bool needs_capture_clearing = !capture_registers.is_empty();
3566 if (body_can_be_empty) {
3567 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003568 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003569 // Only unroll if there are no captures and the body can't be
3570 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003571 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3572 int new_max = (max == kInfinity) ? max : max - min;
3573 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003574 RegExpNode* answer = ToNode(
3575 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003576 // Unroll the forced matches from 0 to min. This can cause chains of
3577 // TextNodes (which the parser does not generate). These should be
3578 // combined if it turns out they hinder good code generation.
3579 for (int i = 0; i < min; i++) {
3580 answer = body->ToNode(compiler, answer);
3581 }
3582 return answer;
3583 }
3584 if (max <= kMaxUnrolledMaxMatches) {
3585 ASSERT(min == 0);
3586 // Unroll the optional matches up to max.
3587 RegExpNode* answer = on_success;
3588 for (int i = 0; i < max; i++) {
3589 ChoiceNode* alternation = new ChoiceNode(2);
3590 if (is_greedy) {
3591 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3592 answer)));
3593 alternation->AddAlternative(GuardedAlternative(on_success));
3594 } else {
3595 alternation->AddAlternative(GuardedAlternative(on_success));
3596 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3597 answer)));
3598 }
3599 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003600 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003601 }
3602 return answer;
3603 }
3604 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003605 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003606 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003607 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003608 int reg_ctr = needs_counter
3609 ? compiler->AllocateRegister()
3610 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003611 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003612 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003613 RegExpNode* loop_return = needs_counter
3614 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3615 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003616 if (body_can_be_empty) {
3617 // If the body can be empty we need to check if it was and then
3618 // backtrack.
3619 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3620 reg_ctr,
3621 min,
3622 loop_return);
3623 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003624 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003625 if (body_can_be_empty) {
3626 // If the body can be empty we need to store the start position
3627 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003628 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003629 }
3630 if (needs_capture_clearing) {
3631 // Before entering the body of this loop we need to clear captures.
3632 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3633 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003634 GuardedAlternative body_alt(body_node);
3635 if (has_max) {
3636 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3637 body_alt.AddGuard(body_guard);
3638 }
3639 GuardedAlternative rest_alt(on_success);
3640 if (has_min) {
3641 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3642 rest_alt.AddGuard(rest_guard);
3643 }
3644 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003645 center->AddLoopAlternative(body_alt);
3646 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003647 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003648 center->AddContinueAlternative(rest_alt);
3649 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003650 }
3651 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003652 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003653 } else {
3654 return center;
3655 }
3656}
3657
3658
3659RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003660 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003661 NodeInfo info;
3662 switch (type()) {
3663 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003664 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003665 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003666 return AssertionNode::AtStart(on_success);
3667 case BOUNDARY:
3668 return AssertionNode::AtBoundary(on_success);
3669 case NON_BOUNDARY:
3670 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003671 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003672 return AssertionNode::AtEnd(on_success);
3673 case END_OF_LINE: {
3674 // Compile $ in multiline regexps as an alternation with a positive
3675 // lookahead in one side and an end-of-input on the other side.
3676 // We need two registers for the lookahead.
3677 int stack_pointer_register = compiler->AllocateRegister();
3678 int position_register = compiler->AllocateRegister();
3679 // The ChoiceNode to distinguish between a newline and end-of-input.
3680 ChoiceNode* result = new ChoiceNode(2);
3681 // Create a newline atom.
3682 ZoneList<CharacterRange>* newline_ranges =
3683 new ZoneList<CharacterRange>(3);
3684 CharacterRange::AddClassEscape('n', newline_ranges);
3685 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3686 TextNode* newline_matcher = new TextNode(
3687 newline_atom,
3688 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3689 position_register,
3690 0, // No captures inside.
3691 -1, // Ignored if no captures.
3692 on_success));
3693 // Create an end-of-input matcher.
3694 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3695 stack_pointer_register,
3696 position_register,
3697 newline_matcher);
3698 // Add the two alternatives to the ChoiceNode.
3699 GuardedAlternative eol_alternative(end_of_line);
3700 result->AddAlternative(eol_alternative);
3701 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3702 result->AddAlternative(end_alternative);
3703 return result;
3704 }
3705 default:
3706 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003707 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003708 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003709}
3710
3711
3712RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003713 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003714 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3715 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003716 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003717}
3718
3719
3720RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003721 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003722 return on_success;
3723}
3724
3725
3726RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003727 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003728 int stack_pointer_register = compiler->AllocateRegister();
3729 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003730
3731 const int registers_per_capture = 2;
3732 const int register_of_first_capture = 2;
3733 int register_count = capture_count_ * registers_per_capture;
3734 int register_start =
3735 register_of_first_capture + capture_from_ * registers_per_capture;
3736
ager@chromium.org8bb60582008-12-11 12:02:20 +00003737 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003738 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003739 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003740 stack_pointer_register,
3741 position_register,
3742 body()->ToNode(
3743 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003744 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3745 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003746 register_count,
3747 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003748 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003749 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003750 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003751 // We use a ChoiceNode for a negative lookahead because it has most of
3752 // the characteristics we need. It has the body of the lookahead as its
3753 // first alternative and the expression after the lookahead of the second
3754 // alternative. If the first alternative succeeds then the
3755 // NegativeSubmatchSuccess will unwind the stack including everything the
3756 // choice node set up and backtrack. If the first alternative fails then
3757 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003758 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3759 // ChoiceNode that knows to ignore the first exit when calculating quick
3760 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003761 GuardedAlternative body_alt(
3762 body()->ToNode(
3763 compiler,
3764 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003765 position_register,
3766 register_count,
3767 register_start)));
3768 ChoiceNode* choice_node =
3769 new NegativeLookaheadChoiceNode(body_alt,
3770 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003771 return ActionNode::BeginSubmatch(stack_pointer_register,
3772 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003773 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003774 }
3775}
3776
3777
3778RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003779 RegExpNode* on_success) {
3780 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003781}
3782
3783
3784RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3785 int index,
3786 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003787 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003788 int start_reg = RegExpCapture::StartRegister(index);
3789 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003790 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003791 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003792 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003793}
3794
3795
3796RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003797 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003798 ZoneList<RegExpTree*>* children = nodes();
3799 RegExpNode* current = on_success;
3800 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003801 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003802 }
3803 return current;
3804}
3805
3806
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003807static void AddClass(const uc16* elmv,
3808 int elmc,
3809 ZoneList<CharacterRange>* ranges) {
3810 for (int i = 0; i < elmc; i += 2) {
3811 ASSERT(elmv[i] <= elmv[i + 1]);
3812 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3813 }
3814}
3815
3816
3817static void AddClassNegated(const uc16 *elmv,
3818 int elmc,
3819 ZoneList<CharacterRange>* ranges) {
3820 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003821 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003822 uc16 last = 0x0000;
3823 for (int i = 0; i < elmc; i += 2) {
3824 ASSERT(last <= elmv[i] - 1);
3825 ASSERT(elmv[i] <= elmv[i + 1]);
3826 ranges->Add(CharacterRange(last, elmv[i] - 1));
3827 last = elmv[i + 1] + 1;
3828 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003829 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003830}
3831
3832
3833void CharacterRange::AddClassEscape(uc16 type,
3834 ZoneList<CharacterRange>* ranges) {
3835 switch (type) {
3836 case 's':
3837 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3838 break;
3839 case 'S':
3840 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3841 break;
3842 case 'w':
3843 AddClass(kWordRanges, kWordRangeCount, ranges);
3844 break;
3845 case 'W':
3846 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3847 break;
3848 case 'd':
3849 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3850 break;
3851 case 'D':
3852 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3853 break;
3854 case '.':
3855 AddClassNegated(kLineTerminatorRanges,
3856 kLineTerminatorRangeCount,
3857 ranges);
3858 break;
3859 // This is not a character range as defined by the spec but a
3860 // convenient shorthand for a character class that matches any
3861 // character.
3862 case '*':
3863 ranges->Add(CharacterRange::Everything());
3864 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003865 // This is the set of characters matched by the $ and ^ symbols
3866 // in multiline mode.
3867 case 'n':
3868 AddClass(kLineTerminatorRanges,
3869 kLineTerminatorRangeCount,
3870 ranges);
3871 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003872 default:
3873 UNREACHABLE();
3874 }
3875}
3876
3877
3878Vector<const uc16> CharacterRange::GetWordBounds() {
3879 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3880}
3881
3882
3883class CharacterRangeSplitter {
3884 public:
3885 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3886 ZoneList<CharacterRange>** excluded)
3887 : included_(included),
3888 excluded_(excluded) { }
3889 void Call(uc16 from, DispatchTable::Entry entry);
3890
3891 static const int kInBase = 0;
3892 static const int kInOverlay = 1;
3893
3894 private:
3895 ZoneList<CharacterRange>** included_;
3896 ZoneList<CharacterRange>** excluded_;
3897};
3898
3899
3900void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3901 if (!entry.out_set()->Get(kInBase)) return;
3902 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3903 ? included_
3904 : excluded_;
3905 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3906 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3907}
3908
3909
3910void CharacterRange::Split(ZoneList<CharacterRange>* base,
3911 Vector<const uc16> overlay,
3912 ZoneList<CharacterRange>** included,
3913 ZoneList<CharacterRange>** excluded) {
3914 ASSERT_EQ(NULL, *included);
3915 ASSERT_EQ(NULL, *excluded);
3916 DispatchTable table;
3917 for (int i = 0; i < base->length(); i++)
3918 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3919 for (int i = 0; i < overlay.length(); i += 2) {
3920 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
3921 CharacterRangeSplitter::kInOverlay);
3922 }
3923 CharacterRangeSplitter callback(included, excluded);
3924 table.ForEach(&callback);
3925}
3926
3927
3928void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges) {
3929 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
3930 if (IsSingleton()) {
3931 // If this is a singleton we just expand the one character.
3932 int length = uncanonicalize.get(from(), '\0', chars);
3933 for (int i = 0; i < length; i++) {
3934 uc32 chr = chars[i];
3935 if (chr != from()) {
3936 ranges->Add(CharacterRange::Singleton(chars[i]));
3937 }
3938 }
3939 } else if (from() <= kRangeCanonicalizeMax &&
3940 to() <= kRangeCanonicalizeMax) {
3941 // If this is a range we expand the characters block by block,
3942 // expanding contiguous subranges (blocks) one at a time.
3943 // The approach is as follows. For a given start character we
3944 // look up the block that contains it, for instance 'a' if the
3945 // start character is 'c'. A block is characterized by the property
3946 // that all characters uncanonicalize in the same way as the first
3947 // element, except that each entry in the result is incremented
3948 // by the distance from the first element. So a-z is a block
3949 // because 'a' uncanonicalizes to ['a', 'A'] and the k'th letter
3950 // uncanonicalizes to ['a' + k, 'A' + k].
3951 // Once we've found the start point we look up its uncanonicalization
3952 // and produce a range for each element. For instance for [c-f]
3953 // we look up ['a', 'A'] and produce [c-f] and [C-F]. We then only
3954 // add a range if it is not already contained in the input, so [c-f]
3955 // will be skipped but [C-F] will be added. If this range is not
3956 // completely contained in a block we do this for all the blocks
3957 // covered by the range.
3958 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
3959 // First, look up the block that contains the 'from' character.
3960 int length = canonrange.get(from(), '\0', range);
3961 if (length == 0) {
3962 range[0] = from();
3963 } else {
3964 ASSERT_EQ(1, length);
3965 }
3966 int pos = from();
3967 // The start of the current block. Note that except for the first
3968 // iteration 'start' is always equal to 'pos'.
3969 int start;
3970 // If it is not the start point of a block the entry contains the
3971 // offset of the character from the start point.
3972 if ((range[0] & kStartMarker) == 0) {
3973 start = pos - range[0];
3974 } else {
3975 start = pos;
3976 }
3977 // Then we add the ranges on at a time, incrementing the current
3978 // position to be after the last block each time. The position
3979 // always points to the start of a block.
3980 while (pos < to()) {
3981 length = canonrange.get(start, '\0', range);
3982 if (length == 0) {
3983 range[0] = start;
3984 } else {
3985 ASSERT_EQ(1, length);
3986 }
3987 ASSERT((range[0] & kStartMarker) != 0);
3988 // The start point of a block contains the distance to the end
3989 // of the range.
3990 int block_end = start + (range[0] & kPayloadMask) - 1;
3991 int end = (block_end > to()) ? to() : block_end;
3992 length = uncanonicalize.get(start, '\0', range);
3993 for (int i = 0; i < length; i++) {
3994 uc32 c = range[i];
3995 uc16 range_from = c + (pos - start);
3996 uc16 range_to = c + (end - start);
3997 if (!(from() <= range_from && range_to <= to())) {
3998 ranges->Add(CharacterRange(range_from, range_to));
3999 }
4000 }
4001 start = pos = block_end + 1;
4002 }
4003 } else {
4004 // TODO(plesner) when we've fixed the 2^11 bug in unibrow.
4005 }
4006}
4007
4008
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004009ZoneList<CharacterRange>* CharacterSet::ranges() {
4010 if (ranges_ == NULL) {
4011 ranges_ = new ZoneList<CharacterRange>(2);
4012 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
4013 }
4014 return ranges_;
4015}
4016
4017
4018
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004019// -------------------------------------------------------------------
4020// Interest propagation
4021
4022
4023RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4024 for (int i = 0; i < siblings_.length(); i++) {
4025 RegExpNode* sibling = siblings_.Get(i);
4026 if (sibling->info()->Matches(info))
4027 return sibling;
4028 }
4029 return NULL;
4030}
4031
4032
4033RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4034 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004035 siblings_.Ensure(this);
4036 RegExpNode* result = TryGetSibling(info);
4037 if (result != NULL) return result;
4038 result = this->Clone();
4039 NodeInfo* new_info = result->info();
4040 new_info->ResetCompilationState();
4041 new_info->AddFromPreceding(info);
4042 AddSibling(result);
4043 *cloned = true;
4044 return result;
4045}
4046
4047
4048template <class C>
4049static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4050 NodeInfo full_info(*node->info());
4051 full_info.AddFromPreceding(info);
4052 bool cloned = false;
4053 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4054}
4055
4056
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004057// -------------------------------------------------------------------
4058// Splay tree
4059
4060
4061OutSet* OutSet::Extend(unsigned value) {
4062 if (Get(value))
4063 return this;
4064 if (successors() != NULL) {
4065 for (int i = 0; i < successors()->length(); i++) {
4066 OutSet* successor = successors()->at(i);
4067 if (successor->Get(value))
4068 return successor;
4069 }
4070 } else {
4071 successors_ = new ZoneList<OutSet*>(2);
4072 }
4073 OutSet* result = new OutSet(first_, remaining_);
4074 result->Set(value);
4075 successors()->Add(result);
4076 return result;
4077}
4078
4079
4080void OutSet::Set(unsigned value) {
4081 if (value < kFirstLimit) {
4082 first_ |= (1 << value);
4083 } else {
4084 if (remaining_ == NULL)
4085 remaining_ = new ZoneList<unsigned>(1);
4086 if (remaining_->is_empty() || !remaining_->Contains(value))
4087 remaining_->Add(value);
4088 }
4089}
4090
4091
4092bool OutSet::Get(unsigned value) {
4093 if (value < kFirstLimit) {
4094 return (first_ & (1 << value)) != 0;
4095 } else if (remaining_ == NULL) {
4096 return false;
4097 } else {
4098 return remaining_->Contains(value);
4099 }
4100}
4101
4102
4103const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4104const DispatchTable::Entry DispatchTable::Config::kNoValue;
4105
4106
4107void DispatchTable::AddRange(CharacterRange full_range, int value) {
4108 CharacterRange current = full_range;
4109 if (tree()->is_empty()) {
4110 // If this is the first range we just insert into the table.
4111 ZoneSplayTree<Config>::Locator loc;
4112 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4113 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4114 return;
4115 }
4116 // First see if there is a range to the left of this one that
4117 // overlaps.
4118 ZoneSplayTree<Config>::Locator loc;
4119 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4120 Entry* entry = &loc.value();
4121 // If we've found a range that overlaps with this one, and it
4122 // starts strictly to the left of this one, we have to fix it
4123 // because the following code only handles ranges that start on
4124 // or after the start point of the range we're adding.
4125 if (entry->from() < current.from() && entry->to() >= current.from()) {
4126 // Snap the overlapping range in half around the start point of
4127 // the range we're adding.
4128 CharacterRange left(entry->from(), current.from() - 1);
4129 CharacterRange right(current.from(), entry->to());
4130 // The left part of the overlapping range doesn't overlap.
4131 // Truncate the whole entry to be just the left part.
4132 entry->set_to(left.to());
4133 // The right part is the one that overlaps. We add this part
4134 // to the map and let the next step deal with merging it with
4135 // the range we're adding.
4136 ZoneSplayTree<Config>::Locator loc;
4137 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4138 loc.set_value(Entry(right.from(),
4139 right.to(),
4140 entry->out_set()));
4141 }
4142 }
4143 while (current.is_valid()) {
4144 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4145 (loc.value().from() <= current.to()) &&
4146 (loc.value().to() >= current.from())) {
4147 Entry* entry = &loc.value();
4148 // We have overlap. If there is space between the start point of
4149 // the range we're adding and where the overlapping range starts
4150 // then we have to add a range covering just that space.
4151 if (current.from() < entry->from()) {
4152 ZoneSplayTree<Config>::Locator ins;
4153 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4154 ins.set_value(Entry(current.from(),
4155 entry->from() - 1,
4156 empty()->Extend(value)));
4157 current.set_from(entry->from());
4158 }
4159 ASSERT_EQ(current.from(), entry->from());
4160 // If the overlapping range extends beyond the one we want to add
4161 // we have to snap the right part off and add it separately.
4162 if (entry->to() > current.to()) {
4163 ZoneSplayTree<Config>::Locator ins;
4164 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4165 ins.set_value(Entry(current.to() + 1,
4166 entry->to(),
4167 entry->out_set()));
4168 entry->set_to(current.to());
4169 }
4170 ASSERT(entry->to() <= current.to());
4171 // The overlapping range is now completely contained by the range
4172 // we're adding so we can just update it and move the start point
4173 // of the range we're adding just past it.
4174 entry->AddValue(value);
4175 // Bail out if the last interval ended at 0xFFFF since otherwise
4176 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004177 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004178 break;
4179 ASSERT(entry->to() + 1 > current.from());
4180 current.set_from(entry->to() + 1);
4181 } else {
4182 // There is no overlap so we can just add the range
4183 ZoneSplayTree<Config>::Locator ins;
4184 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4185 ins.set_value(Entry(current.from(),
4186 current.to(),
4187 empty()->Extend(value)));
4188 break;
4189 }
4190 }
4191}
4192
4193
4194OutSet* DispatchTable::Get(uc16 value) {
4195 ZoneSplayTree<Config>::Locator loc;
4196 if (!tree()->FindGreatestLessThan(value, &loc))
4197 return empty();
4198 Entry* entry = &loc.value();
4199 if (value <= entry->to())
4200 return entry->out_set();
4201 else
4202 return empty();
4203}
4204
4205
4206// -------------------------------------------------------------------
4207// Analysis
4208
4209
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004210void Analysis::EnsureAnalyzed(RegExpNode* that) {
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004211 StackLimitCheck check;
4212 if (check.HasOverflowed()) {
4213 fail("Stack overflow");
4214 return;
4215 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004216 if (that->info()->been_analyzed || that->info()->being_analyzed)
4217 return;
4218 that->info()->being_analyzed = true;
4219 that->Accept(this);
4220 that->info()->being_analyzed = false;
4221 that->info()->been_analyzed = true;
4222}
4223
4224
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004225void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004226 // nothing to do
4227}
4228
4229
ager@chromium.org8bb60582008-12-11 12:02:20 +00004230void TextNode::CalculateOffsets() {
4231 int element_count = elements()->length();
4232 // Set up the offsets of the elements relative to the start. This is a fixed
4233 // quantity since a TextNode can only contain fixed-width things.
4234 int cp_offset = 0;
4235 for (int i = 0; i < element_count; i++) {
4236 TextElement& elm = elements()->at(i);
4237 elm.cp_offset = cp_offset;
4238 if (elm.type == TextElement::ATOM) {
4239 cp_offset += elm.data.u_atom->data().length();
4240 } else {
4241 cp_offset++;
4242 Vector<const uc16> quarks = elm.data.u_atom->data();
4243 }
4244 }
4245}
4246
4247
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004248void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004249 if (ignore_case_) {
4250 that->MakeCaseIndependent();
4251 }
4252 EnsureAnalyzed(that->on_success());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004253 if (!has_failed()) {
4254 that->CalculateOffsets();
4255 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004256}
4257
4258
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004259void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004260 RegExpNode* target = that->on_success();
4261 EnsureAnalyzed(target);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004262 if (!has_failed()) {
4263 // If the next node is interested in what it follows then this node
4264 // has to be interested too so it can pass the information on.
4265 that->info()->AddFromFollowing(target->info());
4266 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004267}
4268
4269
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004270void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004271 NodeInfo* info = that->info();
4272 for (int i = 0; i < that->alternatives()->length(); i++) {
4273 RegExpNode* node = that->alternatives()->at(i).node();
4274 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004275 if (has_failed()) return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004276 // Anything the following nodes need to know has to be known by
4277 // this node also, so it can pass it on.
4278 info->AddFromFollowing(node->info());
4279 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004280}
4281
4282
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004283void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4284 NodeInfo* info = that->info();
4285 for (int i = 0; i < that->alternatives()->length(); i++) {
4286 RegExpNode* node = that->alternatives()->at(i).node();
4287 if (node != that->loop_node()) {
4288 EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004289 if (has_failed()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004290 info->AddFromFollowing(node->info());
4291 }
4292 }
4293 // Check the loop last since it may need the value of this node
4294 // to get a correct result.
4295 EnsureAnalyzed(that->loop_node());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004296 if (!has_failed()) {
4297 info->AddFromFollowing(that->loop_node()->info());
4298 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004299}
4300
4301
4302void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004303 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004304}
4305
4306
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004307void Analysis::VisitAssertion(AssertionNode* that) {
4308 EnsureAnalyzed(that->on_success());
4309}
4310
4311
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004312// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004313// Dispatch table construction
4314
4315
4316void DispatchTableConstructor::VisitEnd(EndNode* that) {
4317 AddRange(CharacterRange::Everything());
4318}
4319
4320
4321void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
4322 node->set_being_calculated(true);
4323 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
4324 for (int i = 0; i < alternatives->length(); i++) {
4325 set_choice_index(i);
4326 alternatives->at(i).node()->Accept(this);
4327 }
4328 node->set_being_calculated(false);
4329}
4330
4331
4332class AddDispatchRange {
4333 public:
4334 explicit AddDispatchRange(DispatchTableConstructor* constructor)
4335 : constructor_(constructor) { }
4336 void Call(uc32 from, DispatchTable::Entry entry);
4337 private:
4338 DispatchTableConstructor* constructor_;
4339};
4340
4341
4342void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
4343 CharacterRange range(from, entry.to());
4344 constructor_->AddRange(range);
4345}
4346
4347
4348void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
4349 if (node->being_calculated())
4350 return;
4351 DispatchTable* table = node->GetTable(ignore_case_);
4352 AddDispatchRange adder(this);
4353 table->ForEach(&adder);
4354}
4355
4356
4357void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
4358 // TODO(160): Find the node that we refer back to and propagate its start
4359 // set back to here. For now we just accept anything.
4360 AddRange(CharacterRange::Everything());
4361}
4362
4363
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004364void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
4365 RegExpNode* target = that->on_success();
4366 target->Accept(this);
4367}
4368
4369
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004370
4371static int CompareRangeByFrom(const CharacterRange* a,
4372 const CharacterRange* b) {
4373 return Compare<uc16>(a->from(), b->from());
4374}
4375
4376
4377void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
4378 ranges->Sort(CompareRangeByFrom);
4379 uc16 last = 0;
4380 for (int i = 0; i < ranges->length(); i++) {
4381 CharacterRange range = ranges->at(i);
4382 if (last < range.from())
4383 AddRange(CharacterRange(last, range.from() - 1));
4384 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004385 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004386 return;
4387 } else {
4388 last = range.to() + 1;
4389 }
4390 }
4391 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004392 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004393}
4394
4395
4396void DispatchTableConstructor::VisitText(TextNode* that) {
4397 TextElement elm = that->elements()->at(0);
4398 switch (elm.type) {
4399 case TextElement::ATOM: {
4400 uc16 c = elm.data.u_atom->data()[0];
4401 AddRange(CharacterRange(c, c));
4402 break;
4403 }
4404 case TextElement::CHAR_CLASS: {
4405 RegExpCharacterClass* tree = elm.data.u_char_class;
4406 ZoneList<CharacterRange>* ranges = tree->ranges();
4407 if (tree->is_negated()) {
4408 AddInverse(ranges);
4409 } else {
4410 for (int i = 0; i < ranges->length(); i++)
4411 AddRange(ranges->at(i));
4412 }
4413 break;
4414 }
4415 default: {
4416 UNIMPLEMENTED();
4417 }
4418 }
4419}
4420
4421
4422void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004423 RegExpNode* target = that->on_success();
4424 target->Accept(this);
4425}
4426
4427
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00004428RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
4429 bool ignore_case,
4430 bool is_multiline,
4431 Handle<String> pattern,
4432 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004433 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00004434 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004435 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004436 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004437 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004438 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004439 0,
4440 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004441 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004442 RegExpNode* node = captured_body;
4443 if (!data->tree->IsAnchored()) {
4444 // Add a .*? at the beginning, outside the body capture, unless
4445 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00004446 RegExpNode* loop_node =
4447 RegExpQuantifier::ToNode(0,
4448 RegExpTree::kInfinity,
4449 false,
4450 new RegExpCharacterClass('*'),
4451 &compiler,
4452 captured_body,
4453 data->contains_anchor);
4454
4455 if (data->contains_anchor) {
4456 // Unroll loop once, to take care of the case that might start
4457 // at the start of input.
4458 ChoiceNode* first_step_node = new ChoiceNode(2);
4459 first_step_node->AddAlternative(GuardedAlternative(captured_body));
4460 first_step_node->AddAlternative(GuardedAlternative(
4461 new TextNode(new RegExpCharacterClass('*'), loop_node)));
4462 node = first_step_node;
4463 } else {
4464 node = loop_node;
4465 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004466 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004467 data->node = node;
4468 Analysis analysis(ignore_case);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004469 analysis.EnsureAnalyzed(node);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00004470 if (analysis.has_failed()) {
4471 const char* error_message = analysis.error_message();
4472 return CompilationResult(error_message);
4473 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004474
4475 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00004476
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00004477 if (RegExpImpl::UseNativeRegexp()) {
ager@chromium.org9085a012009-05-11 19:22:57 +00004478#ifdef V8_TARGET_ARCH_ARM
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00004479 UNREACHABLE();
ager@chromium.org5ec48922009-05-05 07:25:34 +00004480#endif
ager@chromium.org9085a012009-05-11 19:22:57 +00004481#ifdef V8_TARGET_ARCH_X64
ager@chromium.org5ec48922009-05-05 07:25:34 +00004482 UNREACHABLE();
4483#endif
ager@chromium.org9085a012009-05-11 19:22:57 +00004484#ifdef V8_TARGET_ARCH_IA32
ager@chromium.org8bb60582008-12-11 12:02:20 +00004485 RegExpMacroAssemblerIA32::Mode mode;
4486 if (is_ascii) {
4487 mode = RegExpMacroAssemblerIA32::ASCII;
4488 } else {
4489 mode = RegExpMacroAssemblerIA32::UC16;
4490 }
4491 RegExpMacroAssemblerIA32 macro_assembler(mode,
4492 (data->capture_count + 1) * 2);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004493 return compiler.Assemble(&macro_assembler,
4494 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004495 data->capture_count,
4496 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004497#endif
4498 }
4499 EmbeddedVector<byte, 1024> codes;
4500 RegExpMacroAssemblerIrregexp macro_assembler(codes);
4501 return compiler.Assemble(&macro_assembler,
4502 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004503 data->capture_count,
4504 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004505}
4506
4507
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004508}} // namespace v8::internal