blob: 89d11eb4e25e38abd56142125806a1ccfe1882f2 [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"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000031#include "execution.h"
32#include "factory.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000033#include "jsregexp-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000034#include "platform.h"
kasperl@chromium.org41044eb2008-10-06 08:24:46 +000035#include "runtime.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036#include "top.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000037#include "compilation-cache.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000038#include "string-stream.h"
39#include "parser.h"
40#include "regexp-macro-assembler.h"
41#include "regexp-macro-assembler-tracer.h"
42#include "regexp-macro-assembler-irregexp.h"
ager@chromium.org32912102009-01-16 10:38:43 +000043#include "regexp-stack.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000044
45#ifdef ARM
ager@chromium.org3a37e9b2009-04-27 09:26:21 +000046#include "arm/regexp-macro-assembler-arm.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000047#else // IA32
ager@chromium.org3a37e9b2009-04-27 09:26:21 +000048#include "ia32/macro-assembler-ia32.h"
49#include "ia32/regexp-macro-assembler-ia32.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000050#endif
51
52#include "interpreter-irregexp.h"
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000053
ager@chromium.orga74f0da2008-12-03 16:05:52 +000054
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000055namespace v8 { namespace internal {
56
57
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000058Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor,
59 Handle<String> pattern,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000060 Handle<String> flags,
61 bool* has_pending_exception) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000062 // Ensure that the constructor function has been loaded.
63 if (!constructor->IsLoaded()) {
64 LoadLazy(constructor, has_pending_exception);
ager@chromium.orga74f0da2008-12-03 16:05:52 +000065 if (*has_pending_exception) return Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000066 }
67 // Call the construct code with 2 arguments.
68 Object** argv[2] = { Handle<Object>::cast(pattern).location(),
69 Handle<Object>::cast(flags).location() };
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000070 return Execution::New(constructor, 2, argv, has_pending_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000071}
72
73
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000074static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
75 int flags = JSRegExp::NONE;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000076 for (int i = 0; i < str->length(); i++) {
77 switch (str->Get(i)) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +000078 case 'i':
79 flags |= JSRegExp::IGNORE_CASE;
80 break;
81 case 'g':
82 flags |= JSRegExp::GLOBAL;
83 break;
84 case 'm':
85 flags |= JSRegExp::MULTILINE;
86 break;
87 }
88 }
89 return JSRegExp::Flags(flags);
90}
91
92
ager@chromium.orga74f0da2008-12-03 16:05:52 +000093static inline void ThrowRegExpException(Handle<JSRegExp> re,
94 Handle<String> pattern,
95 Handle<String> error_text,
96 const char* message) {
97 Handle<JSArray> array = Factory::NewJSArray(2);
98 SetElement(array, 0, pattern);
99 SetElement(array, 1, error_text);
100 Handle<Object> regexp_err = Factory::NewSyntaxError(message, array);
101 Top::Throw(*regexp_err);
102}
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000103
104
ager@chromium.org8bb60582008-12-11 12:02:20 +0000105// Generic RegExp methods. Dispatches to implementation specific methods.
106
107
108class OffsetsVector {
109 public:
110 inline OffsetsVector(int num_registers)
111 : offsets_vector_length_(num_registers) {
112 if (offsets_vector_length_ > kStaticOffsetsVectorSize) {
113 vector_ = NewArray<int>(offsets_vector_length_);
114 } else {
115 vector_ = static_offsets_vector_;
116 }
117 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000118 inline ~OffsetsVector() {
119 if (offsets_vector_length_ > kStaticOffsetsVectorSize) {
120 DeleteArray(vector_);
121 vector_ = NULL;
122 }
123 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000124 inline int* vector() { return vector_; }
125 inline int length() { return offsets_vector_length_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000126
127 private:
128 int* vector_;
129 int offsets_vector_length_;
130 static const int kStaticOffsetsVectorSize = 50;
131 static int static_offsets_vector_[kStaticOffsetsVectorSize];
132};
133
134
135int OffsetsVector::static_offsets_vector_[
136 OffsetsVector::kStaticOffsetsVectorSize];
137
138
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000139Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
140 Handle<String> pattern,
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000141 Handle<String> flag_str) {
142 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
143 Handle<FixedArray> cached = CompilationCache::LookupRegExp(pattern, flags);
144 bool in_cache = !cached.is_null();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000145 LOG(RegExpCompileEvent(re, in_cache));
146
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000147 Handle<Object> result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000148 if (in_cache) {
149 re->set_data(*cached);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000150 return re;
151 }
152 FlattenString(pattern);
153 ZoneScope zone_scope(DELETE_ON_EXIT);
154 RegExpCompileData parse_result;
155 FlatStringReader reader(pattern);
156 if (!ParseRegExp(&reader, flags.is_multiline(), &parse_result)) {
157 // Throw an exception if we fail to parse the pattern.
158 ThrowRegExpException(re,
159 pattern,
160 parse_result.error,
161 "malformed_regexp");
162 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000163 }
164
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000165 if (parse_result.simple && !flags.is_ignore_case()) {
166 // Parse-tree is a single atom that is equal to the pattern.
167 AtomCompile(re, pattern, flags, pattern);
168 } else if (parse_result.tree->IsAtom() &&
169 !flags.is_ignore_case() &&
170 parse_result.capture_count == 0) {
171 RegExpAtom* atom = parse_result.tree->AsAtom();
172 Vector<const uc16> atom_pattern = atom->data();
173 Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern);
174 AtomCompile(re, pattern, flags, atom_string);
175 } else {
176 IrregexpPrepare(re, pattern, flags, parse_result.capture_count);
177 }
178 ASSERT(re->data()->IsFixedArray());
179 // Compilation succeeded so the data is set on the regexp
180 // and we can store it in the cache.
181 Handle<FixedArray> data(FixedArray::cast(re->data()));
182 CompilationCache::PutRegExp(pattern, flags, data);
183
184 return re;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000185}
186
187
188Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
189 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000190 int index,
191 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000192 switch (regexp->TypeTag()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000193 case JSRegExp::ATOM:
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000194 return AtomExec(regexp, subject, index, last_match_info);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000195 case JSRegExp::IRREGEXP: {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000196 Handle<Object> result =
197 IrregexpExec(regexp, subject, index, last_match_info);
ager@chromium.org6f10e412009-02-13 10:11:16 +0000198 ASSERT(!result.is_null() || Top::has_pending_exception());
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000199 return result;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000200 }
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000201 default:
202 UNREACHABLE();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000203 return Handle<Object>::null();
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000204 }
205}
206
207
ager@chromium.org8bb60582008-12-11 12:02:20 +0000208// RegExp Atom implementation: Simple string search using indexOf.
209
210
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000211void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
212 Handle<String> pattern,
213 JSRegExp::Flags flags,
214 Handle<String> match_pattern) {
215 Factory::SetRegExpAtomData(re,
216 JSRegExp::ATOM,
217 pattern,
218 flags,
219 match_pattern);
220}
221
222
223static void SetAtomLastCapture(FixedArray* array,
224 String* subject,
225 int from,
226 int to) {
227 NoHandleAllocation no_handles;
228 RegExpImpl::SetLastCaptureCount(array, 2);
229 RegExpImpl::SetLastSubject(array, subject);
230 RegExpImpl::SetLastInput(array, subject);
231 RegExpImpl::SetCapture(array, 0, from);
232 RegExpImpl::SetCapture(array, 1, to);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000233}
234
235
236Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
237 Handle<String> subject,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000238 int index,
239 Handle<JSArray> last_match_info) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +0000240 Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex)));
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000241
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000242 uint32_t start_index = index;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000243
ager@chromium.org7c537e22008-10-16 08:43:32 +0000244 int value = Runtime::StringMatch(subject, needle, start_index);
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000245 if (value == -1) return Factory::null_value();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000246 ASSERT(last_match_info->HasFastElements());
ager@chromium.org7c537e22008-10-16 08:43:32 +0000247
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000248 {
249 NoHandleAllocation no_handles;
250 FixedArray* array = last_match_info->elements();
251 SetAtomLastCapture(array, *subject, value, value + needle->length());
252 }
253 return last_match_info;
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000254}
255
256
ager@chromium.org8bb60582008-12-11 12:02:20 +0000257// Irregexp implementation.
258
259
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000260// Ensures that the regexp object contains a compiled version of the
261// source for either ASCII or non-ASCII strings.
262// If the compiled version doesn't already exist, it is compiled
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000263// from the source pattern.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000264// If compilation fails, an exception is thrown and this function
265// returns false.
ager@chromium.org41826e72009-03-30 13:30:57 +0000266bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000267 int index;
268 if (is_ascii) {
269 index = JSRegExp::kIrregexpASCIICodeIndex;
270 } else {
271 index = JSRegExp::kIrregexpUC16CodeIndex;
272 }
273 Object* entry = re->DataAt(index);
274 if (!entry->IsTheHole()) {
275 // A value has already been compiled.
276 if (entry->IsJSObject()) {
277 // If it's a JS value, it's an error.
278 Top::Throw(entry);
279 return false;
280 }
281 return true;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000282 }
283
284 // Compile the RegExp.
285 ZoneScope zone_scope(DELETE_ON_EXIT);
286
287 JSRegExp::Flags flags = re->GetFlags();
288
289 Handle<String> pattern(re->Pattern());
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000290 if (!pattern->IsFlat()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000291 FlattenString(pattern);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000292 }
293
294 RegExpCompileData compile_data;
295 FlatStringReader reader(pattern);
296 if (!ParseRegExp(&reader, flags.is_multiline(), &compile_data)) {
297 // Throw an exception if we fail to parse the pattern.
298 // THIS SHOULD NOT HAPPEN. We already parsed it successfully once.
299 ThrowRegExpException(re,
300 pattern,
301 compile_data.error,
302 "malformed_regexp");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000303 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000304 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000305 RegExpEngine::CompilationResult result =
ager@chromium.org8bb60582008-12-11 12:02:20 +0000306 RegExpEngine::Compile(&compile_data,
307 flags.is_ignore_case(),
308 flags.is_multiline(),
309 pattern,
310 is_ascii);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000311 if (result.error_message != NULL) {
312 // Unable to compile regexp.
313 Handle<JSArray> array = Factory::NewJSArray(2);
314 SetElement(array, 0, pattern);
315 SetElement(array,
316 1,
317 Factory::NewStringFromUtf8(CStrVector(result.error_message)));
318 Handle<Object> regexp_err =
319 Factory::NewSyntaxError("malformed_regexp", array);
320 Top::Throw(*regexp_err);
321 re->SetDataAt(index, *regexp_err);
322 return false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000323 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000324
325 NoHandleAllocation no_handles;
326
327 FixedArray* data = FixedArray::cast(re->data());
328 data->set(index, result.code);
329 int register_max = IrregexpMaxRegisterCount(data);
330 if (result.num_registers > register_max) {
331 SetIrregexpMaxRegisterCount(data, result.num_registers);
332 }
333
334 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000335}
336
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000337
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000338int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
339 return Smi::cast(
340 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000341}
342
343
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000344void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
345 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000346}
347
348
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000349int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
350 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000351}
352
353
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000354int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
355 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000356}
357
358
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000359ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
360 int index;
361 if (is_ascii) {
362 index = JSRegExp::kIrregexpASCIICodeIndex;
363 } else {
364 index = JSRegExp::kIrregexpUC16CodeIndex;
365 }
366 return ByteArray::cast(re->get(index));
367}
368
369
370Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
371 int index;
372 if (is_ascii) {
373 index = JSRegExp::kIrregexpASCIICodeIndex;
374 } else {
375 index = JSRegExp::kIrregexpUC16CodeIndex;
376 }
377 return Code::cast(re->get(index));
378}
379
380
381void RegExpImpl::IrregexpPrepare(Handle<JSRegExp> re,
382 Handle<String> pattern,
383 JSRegExp::Flags flags,
384 int capture_count) {
385 // Initialize compiled code entries to null.
386 Factory::SetRegExpIrregexpData(re,
387 JSRegExp::IRREGEXP,
388 pattern,
389 flags,
390 capture_count);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000391}
392
393
ager@chromium.org41826e72009-03-30 13:30:57 +0000394Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000395 Handle<String> subject,
ager@chromium.org41826e72009-03-30 13:30:57 +0000396 int previous_index,
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000397 Handle<JSArray> last_match_info) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000398 ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000399
ager@chromium.org8bb60582008-12-11 12:02:20 +0000400 // Prepare space for the return values.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000401 int number_of_capture_registers =
ager@chromium.org41826e72009-03-30 13:30:57 +0000402 (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000403 OffsetsVector offsets(number_of_capture_registers);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000404
ager@chromium.org8bb60582008-12-11 12:02:20 +0000405#ifdef DEBUG
406 if (FLAG_trace_regexp_bytecodes) {
ager@chromium.org41826e72009-03-30 13:30:57 +0000407 String* pattern = jsregexp->Pattern();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000408 PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
409 PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
410 }
411#endif
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000412
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000413 if (!subject->IsFlat()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000414 FlattenString(subject);
415 }
416
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000417 last_match_info->EnsureSize(number_of_capture_registers + kLastMatchOverhead);
418
ager@chromium.org41826e72009-03-30 13:30:57 +0000419 int* offsets_vector = offsets.vector();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000420 bool rc;
421
ager@chromium.org41826e72009-03-30 13:30:57 +0000422 // Dispatch to the correct RegExp implementation.
423
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000424 Handle<String> original_subject = subject;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000425 Handle<FixedArray> regexp(FixedArray::cast(jsregexp->data()));
426 if (UseNativeRegexp()) {
427#ifdef ARM
428 UNREACHABLE();
429#else
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000430 RegExpMacroAssemblerIA32::Result res;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000431 do {
432 bool is_ascii = StringShape(*subject).IsAsciiRepresentation();
433 if (!EnsureCompiledIrregexp(jsregexp, is_ascii)) {
434 return Handle<Object>::null();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000435 }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000436 Handle<Code> code(RegExpImpl::IrregexpNativeCode(*regexp, is_ascii));
437 res = RegExpMacroAssemblerIA32::Match(code,
438 subject,
439 offsets_vector,
ager@chromium.org41826e72009-03-30 13:30:57 +0000440 offsets.length(),
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000441 previous_index);
442 // If result is RETRY, the string have changed representation, and we
443 // must restart from scratch.
444 } while (res == RegExpMacroAssemblerIA32::RETRY);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000445 if (res == RegExpMacroAssemblerIA32::EXCEPTION) {
446 ASSERT(Top::has_pending_exception());
447 return Handle<Object>::null();
448 }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000449 ASSERT(res == RegExpMacroAssemblerIA32::SUCCESS
450 || res == RegExpMacroAssemblerIA32::FAILURE);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000451
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000452 rc = (res == RegExpMacroAssemblerIA32::SUCCESS);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000453#endif
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000454 } else {
455 bool is_ascii = StringShape(*subject).IsAsciiRepresentation();
456 if (!EnsureCompiledIrregexp(jsregexp, is_ascii)) {
457 return Handle<Object>::null();
458 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000459 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
460 offsets_vector[i] = -1;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000461 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000462 Handle<ByteArray> byte_codes(IrregexpByteCode(*regexp, is_ascii));
ager@chromium.org8bb60582008-12-11 12:02:20 +0000463
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000464 rc = IrregexpInterpreter::Match(byte_codes,
465 subject,
466 offsets_vector,
467 previous_index);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000468 }
469
ager@chromium.org41826e72009-03-30 13:30:57 +0000470 // Handle results from RegExp implementation.
471
ager@chromium.org8bb60582008-12-11 12:02:20 +0000472 if (!rc) {
473 return Factory::null_value();
474 }
475
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000476 FixedArray* array = last_match_info->elements();
477 ASSERT(array->length() >= number_of_capture_registers + kLastMatchOverhead);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000478 // The captures come in (start, end+1) pairs.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000479 SetLastCaptureCount(array, number_of_capture_registers);
480 SetLastSubject(array, *original_subject);
481 SetLastInput(array, *original_subject);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000482 for (int i = 0; i < number_of_capture_registers; i+=2) {
483 SetCapture(array, i, offsets_vector[i]);
484 SetCapture(array, i + 1, offsets_vector[i + 1]);
485 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000486 return last_match_info;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000487}
488
489
490// -------------------------------------------------------------------
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000491// Implementation of the Irregexp regular expression engine.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000492//
493// The Irregexp regular expression engine is intended to be a complete
494// implementation of ECMAScript regular expressions. It generates either
495// bytecodes or native code.
496
497// The Irregexp regexp engine is structured in three steps.
498// 1) The parser generates an abstract syntax tree. See ast.cc.
499// 2) From the AST a node network is created. The nodes are all
500// subclasses of RegExpNode. The nodes represent states when
501// executing a regular expression. Several optimizations are
502// performed on the node network.
503// 3) From the nodes we generate either byte codes or native code
504// that can actually execute the regular expression (perform
505// the search). The code generation step is described in more
506// detail below.
507
508// Code generation.
509//
510// The nodes are divided into four main categories.
511// * Choice nodes
512// These represent places where the regular expression can
513// match in more than one way. For example on entry to an
514// alternation (foo|bar) or a repetition (*, +, ? or {}).
515// * Action nodes
516// These represent places where some action should be
517// performed. Examples include recording the current position
518// in the input string to a register (in order to implement
519// captures) or other actions on register for example in order
520// to implement the counters needed for {} repetitions.
521// * Matching nodes
522// These attempt to match some element part of the input string.
523// Examples of elements include character classes, plain strings
524// or back references.
525// * End nodes
526// These are used to implement the actions required on finding
527// a successful match or failing to find a match.
528//
529// The code generated (whether as byte codes or native code) maintains
530// some state as it runs. This consists of the following elements:
531//
532// * The capture registers. Used for string captures.
533// * Other registers. Used for counters etc.
534// * The current position.
535// * The stack of backtracking information. Used when a matching node
536// fails to find a match and needs to try an alternative.
537//
538// Conceptual regular expression execution model:
539//
540// There is a simple conceptual model of regular expression execution
541// which will be presented first. The actual code generated is a more
542// efficient simulation of the simple conceptual model:
543//
544// * Choice nodes are implemented as follows:
545// For each choice except the last {
546// push current position
547// push backtrack code location
548// <generate code to test for choice>
549// backtrack code location:
550// pop current position
551// }
552// <generate code to test for last choice>
553//
554// * Actions nodes are generated as follows
555// <push affected registers on backtrack stack>
556// <generate code to perform action>
557// push backtrack code location
558// <generate code to test for following nodes>
559// backtrack code location:
560// <pop affected registers to restore their state>
561// <pop backtrack location from stack and go to it>
562//
563// * Matching nodes are generated as follows:
564// if input string matches at current position
565// update current position
566// <generate code to test for following nodes>
567// else
568// <pop backtrack location from stack and go to it>
569//
570// Thus it can be seen that the current position is saved and restored
571// by the choice nodes, whereas the registers are saved and restored by
572// by the action nodes that manipulate them.
573//
574// The other interesting aspect of this model is that nodes are generated
575// at the point where they are needed by a recursive call to Emit(). If
576// the node has already been code generated then the Emit() call will
577// generate a jump to the previously generated code instead. In order to
578// limit recursion it is possible for the Emit() function to put the node
579// on a work list for later generation and instead generate a jump. The
580// destination of the jump is resolved later when the code is generated.
581//
582// Actual regular expression code generation.
583//
584// Code generation is actually more complicated than the above. In order
585// to improve the efficiency of the generated code some optimizations are
586// performed
587//
588// * Choice nodes have 1-character lookahead.
589// A choice node looks at the following character and eliminates some of
590// the choices immediately based on that character. This is not yet
591// implemented.
592// * Simple greedy loops store reduced backtracking information.
593// A quantifier like /.*foo/m will greedily match the whole input. It will
594// then need to backtrack to a point where it can match "foo". The naive
595// implementation of this would push each character position onto the
596// backtracking stack, then pop them off one by one. This would use space
597// proportional to the length of the input string. However since the "."
598// can only match in one way and always has a constant length (in this case
599// of 1) it suffices to store the current position on the top of the stack
600// once. Matching now becomes merely incrementing the current position and
601// backtracking becomes decrementing the current position and checking the
602// result against the stored current position. This is faster and saves
603// space.
604// * The current state is virtualized.
605// This is used to defer expensive operations until it is clear that they
606// are needed and to generate code for a node more than once, allowing
607// specialized an efficient versions of the code to be created. This is
608// explained in the section below.
609//
610// Execution state virtualization.
611//
612// Instead of emitting code, nodes that manipulate the state can record their
ager@chromium.org32912102009-01-16 10:38:43 +0000613// manipulation in an object called the Trace. The Trace object can record a
614// current position offset, an optional backtrack code location on the top of
615// the virtualized backtrack stack and some register changes. When a node is
616// to be emitted it can flush the Trace or update it. Flushing the Trace
ager@chromium.org8bb60582008-12-11 12:02:20 +0000617// will emit code to bring the actual state into line with the virtual state.
618// Avoiding flushing the state can postpone some work (eg updates of capture
619// registers). Postponing work can save time when executing the regular
620// expression since it may be found that the work never has to be done as a
621// failure to match can occur. In addition it is much faster to jump to a
622// known backtrack code location than it is to pop an unknown backtrack
623// location from the stack and jump there.
624//
ager@chromium.org32912102009-01-16 10:38:43 +0000625// The virtual state found in the Trace affects code generation. For example
626// the virtual state contains the difference between the actual current
627// position and the virtual current position, and matching code needs to use
628// this offset to attempt a match in the correct location of the input
629// string. Therefore code generated for a non-trivial trace is specialized
630// to that trace. The code generator therefore has the ability to generate
631// code for each node several times. In order to limit the size of the
632// generated code there is an arbitrary limit on how many specialized sets of
633// code may be generated for a given node. If the limit is reached, the
634// trace is flushed and a generic version of the code for a node is emitted.
635// This is subsequently used for that node. The code emitted for non-generic
636// trace is not recorded in the node and so it cannot currently be reused in
637// the event that code generation is requested for an identical trace.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000638
639
640void RegExpTree::AppendToText(RegExpText* text) {
641 UNREACHABLE();
642}
643
644
645void RegExpAtom::AppendToText(RegExpText* text) {
646 text->AddElement(TextElement::Atom(this));
647}
648
649
650void RegExpCharacterClass::AppendToText(RegExpText* text) {
651 text->AddElement(TextElement::CharClass(this));
652}
653
654
655void RegExpText::AppendToText(RegExpText* text) {
656 for (int i = 0; i < elements()->length(); i++)
657 text->AddElement(elements()->at(i));
658}
659
660
661TextElement TextElement::Atom(RegExpAtom* atom) {
662 TextElement result = TextElement(ATOM);
663 result.data.u_atom = atom;
664 return result;
665}
666
667
668TextElement TextElement::CharClass(
669 RegExpCharacterClass* char_class) {
670 TextElement result = TextElement(CHAR_CLASS);
671 result.data.u_char_class = char_class;
672 return result;
673}
674
675
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +0000676int TextElement::length() {
677 if (type == ATOM) {
678 return data.u_atom->length();
679 } else {
680 ASSERT(type == CHAR_CLASS);
681 return 1;
682 }
683}
684
685
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000686DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
687 if (table_ == NULL) {
688 table_ = new DispatchTable();
689 DispatchTableConstructor cons(table_, ignore_case);
690 cons.BuildTable(this);
691 }
692 return table_;
693}
694
695
696class RegExpCompiler {
697 public:
ager@chromium.org8bb60582008-12-11 12:02:20 +0000698 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000699
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000700 int AllocateRegister() {
701 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
702 reg_exp_too_big_ = true;
703 return next_register_;
704 }
705 return next_register_++;
706 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000707
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000708 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
709 RegExpNode* start,
710 int capture_count,
711 Handle<String> pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000712
713 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
714
715 static const int kImplementationOffset = 0;
716 static const int kNumberOfRegistersOffset = 0;
717 static const int kCodeOffset = 1;
718
719 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
720 EndNode* accept() { return accept_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000721
722 static const int kMaxRecursion = 100;
723 inline int recursion_depth() { return recursion_depth_; }
724 inline void IncrementRecursionDepth() { recursion_depth_++; }
725 inline void DecrementRecursionDepth() { recursion_depth_--; }
726
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000727 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
728
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000729 inline bool ignore_case() { return ignore_case_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000730 inline bool ascii() { return ascii_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000731
ager@chromium.org32912102009-01-16 10:38:43 +0000732 static const int kNoRegister = -1;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000733 private:
734 EndNode* accept_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000735 int next_register_;
736 List<RegExpNode*>* work_list_;
737 int recursion_depth_;
738 RegExpMacroAssembler* macro_assembler_;
739 bool ignore_case_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000740 bool ascii_;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000741 bool reg_exp_too_big_;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000742};
743
744
745class RecursionCheck {
746 public:
747 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
748 compiler->IncrementRecursionDepth();
749 }
750 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
751 private:
752 RegExpCompiler* compiler_;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000753};
754
755
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000756static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
757 return RegExpEngine::CompilationResult("RegExp too big");
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000758}
759
760
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000761// Attempts to compile the regexp using an Irregexp code generator. Returns
762// a fixed array or a null handle depending on whether it succeeded.
ager@chromium.org8bb60582008-12-11 12:02:20 +0000763RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000764 : next_register_(2 * (capture_count + 1)),
765 work_list_(NULL),
766 recursion_depth_(0),
ager@chromium.org8bb60582008-12-11 12:02:20 +0000767 ignore_case_(ignore_case),
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000768 ascii_(ascii),
769 reg_exp_too_big_(false) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000770 accept_ = new EndNode(EndNode::ACCEPT);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000771 ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000772}
773
774
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000775RegExpEngine::CompilationResult RegExpCompiler::Assemble(
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000776 RegExpMacroAssembler* macro_assembler,
777 RegExpNode* start,
ager@chromium.org8bb60582008-12-11 12:02:20 +0000778 int capture_count,
779 Handle<String> pattern) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000780#ifdef DEBUG
781 if (FLAG_trace_regexp_assembler)
782 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
783 else
784#endif
785 macro_assembler_ = macro_assembler;
786 List <RegExpNode*> work_list(0);
787 work_list_ = &work_list;
788 Label fail;
iposva@chromium.org245aa852009-02-10 00:49:54 +0000789 macro_assembler_->PushBacktrack(&fail);
ager@chromium.org32912102009-01-16 10:38:43 +0000790 Trace new_trace;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000791 start->Emit(this, &new_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000792 macro_assembler_->Bind(&fail);
793 macro_assembler_->Fail();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000794 while (!work_list.is_empty()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000795 work_list.RemoveLast()->Emit(this, &new_trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000796 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000797 if (reg_exp_too_big_) return IrregexpRegExpTooBig();
798
ager@chromium.org8bb60582008-12-11 12:02:20 +0000799 Handle<Object> code = macro_assembler_->GetCode(pattern);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000800
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000801 work_list_ = NULL;
802#ifdef DEBUG
803 if (FLAG_trace_regexp_assembler) {
804 delete macro_assembler_;
805 }
806#endif
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000807 return RegExpEngine::CompilationResult(*code, next_register_);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000808}
809
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000810
ager@chromium.org32912102009-01-16 10:38:43 +0000811bool Trace::DeferredAction::Mentions(int that) {
812 if (type() == ActionNode::CLEAR_CAPTURES) {
813 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
814 return range.Contains(that);
815 } else {
816 return reg() == that;
817 }
818}
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000819
ager@chromium.org32912102009-01-16 10:38:43 +0000820
821bool Trace::mentions_reg(int reg) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000822 for (DeferredAction* action = actions_;
823 action != NULL;
824 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000825 if (action->Mentions(reg))
826 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000827 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000828 return false;
829}
830
831
ager@chromium.org32912102009-01-16 10:38:43 +0000832bool Trace::GetStoredPosition(int reg, int* cp_offset) {
833 ASSERT_EQ(0, *cp_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000834 for (DeferredAction* action = actions_;
835 action != NULL;
836 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000837 if (action->Mentions(reg)) {
838 if (action->type() == ActionNode::STORE_POSITION) {
839 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
840 return true;
841 } else {
842 return false;
843 }
844 }
845 }
846 return false;
847}
848
849
850int Trace::FindAffectedRegisters(OutSet* affected_registers) {
851 int max_register = RegExpCompiler::kNoRegister;
852 for (DeferredAction* action = actions_;
853 action != NULL;
854 action = action->next()) {
855 if (action->type() == ActionNode::CLEAR_CAPTURES) {
856 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
857 for (int i = range.from(); i <= range.to(); i++)
858 affected_registers->Set(i);
859 if (range.to() > max_register) max_register = range.to();
860 } else {
861 affected_registers->Set(action->reg());
862 if (action->reg() > max_register) max_register = action->reg();
863 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000864 }
865 return max_register;
866}
867
868
ager@chromium.org32912102009-01-16 10:38:43 +0000869void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
870 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000871 OutSet& registers_to_pop,
872 OutSet& registers_to_clear) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000873 for (int reg = max_register; reg >= 0; reg--) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000874 if (registers_to_pop.Get(reg)) assembler->PopRegister(reg);
875 else if (registers_to_clear.Get(reg)) {
876 int clear_to = reg;
877 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
878 reg--;
879 }
880 assembler->ClearRegisters(reg, clear_to);
881 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000882 }
883}
884
885
ager@chromium.org32912102009-01-16 10:38:43 +0000886void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
887 int max_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000888 OutSet& affected_registers,
889 OutSet* registers_to_pop,
890 OutSet* registers_to_clear) {
891 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
892 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
893
ager@chromium.org8bb60582008-12-11 12:02:20 +0000894 for (int reg = 0; reg <= max_register; reg++) {
895 if (!affected_registers.Get(reg)) {
896 continue;
897 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000898 // Count pushes performed to force a stack limit check occasionally.
899 int pushes = 0;
900
901 // The chronologically first deferred action in the trace
902 // is used to infer the action needed to restore a register
903 // to its previous state (or not, if it's safe to ignore it).
904 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
905 DeferredActionUndoType undo_action = IGNORE;
906
ager@chromium.org8bb60582008-12-11 12:02:20 +0000907 int value = 0;
908 bool absolute = false;
ager@chromium.org32912102009-01-16 10:38:43 +0000909 bool clear = false;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000910 int store_position = -1;
911 // This is a little tricky because we are scanning the actions in reverse
912 // historical order (newest first).
913 for (DeferredAction* action = actions_;
914 action != NULL;
915 action = action->next()) {
ager@chromium.org32912102009-01-16 10:38:43 +0000916 if (action->Mentions(reg)) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000917 switch (action->type()) {
918 case ActionNode::SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +0000919 Trace::DeferredSetRegister* psr =
920 static_cast<Trace::DeferredSetRegister*>(action);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000921 if (!absolute) {
922 value += psr->value();
923 absolute = true;
924 }
925 // SET_REGISTER is currently only used for newly introduced loop
926 // counters. They can have a significant previous value if they
927 // occour in a loop. TODO(lrn): Propagate this information, so
928 // we can set undo_action to IGNORE if we know there is no value to
929 // restore.
930 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000931 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000932 ASSERT(!clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +0000933 break;
934 }
935 case ActionNode::INCREMENT_REGISTER:
936 if (!absolute) {
937 value++;
938 }
939 ASSERT_EQ(store_position, -1);
ager@chromium.org32912102009-01-16 10:38:43 +0000940 ASSERT(!clear);
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000941 undo_action = RESTORE;
ager@chromium.org8bb60582008-12-11 12:02:20 +0000942 break;
943 case ActionNode::STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +0000944 Trace::DeferredCapture* pc =
945 static_cast<Trace::DeferredCapture*>(action);
946 if (!clear && store_position == -1) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000947 store_position = pc->cp_offset();
948 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000949
950 // For captures we know that stores and clears alternate.
951 // Other register, are never cleared, and if the occur
952 // inside a loop, they might be assigned more than once.
953 if (reg <= 1) {
954 // Registers zero and one, aka "capture zero", is
955 // always set correctly if we succeed. There is no
956 // need to undo a setting on backtrack, because we
957 // will set it again or fail.
958 undo_action = IGNORE;
959 } else {
960 undo_action = pc->is_capture() ? CLEAR : RESTORE;
961 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000962 ASSERT(!absolute);
963 ASSERT_EQ(value, 0);
964 break;
965 }
ager@chromium.org32912102009-01-16 10:38:43 +0000966 case ActionNode::CLEAR_CAPTURES: {
967 // Since we're scanning in reverse order, if we've already
968 // set the position we have to ignore historically earlier
969 // clearing operations.
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000970 if (store_position == -1) {
ager@chromium.org32912102009-01-16 10:38:43 +0000971 clear = true;
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000972 }
973 undo_action = RESTORE;
ager@chromium.org32912102009-01-16 10:38:43 +0000974 ASSERT(!absolute);
975 ASSERT_EQ(value, 0);
976 break;
977 }
ager@chromium.org8bb60582008-12-11 12:02:20 +0000978 default:
979 UNREACHABLE();
980 break;
981 }
982 }
983 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +0000984 // Prepare for the undo-action (e.g., push if it's going to be popped).
985 if (undo_action == RESTORE) {
986 pushes++;
987 RegExpMacroAssembler::StackCheckFlag stack_check =
988 RegExpMacroAssembler::kNoStackLimitCheck;
989 if (pushes == push_limit) {
990 stack_check = RegExpMacroAssembler::kCheckStackLimit;
991 pushes = 0;
992 }
993
994 assembler->PushRegister(reg, stack_check);
995 registers_to_pop->Set(reg);
996 } else if (undo_action == CLEAR) {
997 registers_to_clear->Set(reg);
998 }
999 // Perform the chronologically last action (or accumulated increment)
1000 // for the register.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001001 if (store_position != -1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001002 assembler->WriteCurrentPositionToRegister(reg, store_position);
ager@chromium.org32912102009-01-16 10:38:43 +00001003 } else if (clear) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001004 assembler->ClearRegisters(reg, reg);
ager@chromium.org32912102009-01-16 10:38:43 +00001005 } else if (absolute) {
1006 assembler->SetRegister(reg, value);
1007 } else if (value != 0) {
1008 assembler->AdvanceRegister(reg, value);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001009 }
1010 }
1011}
1012
1013
ager@chromium.org8bb60582008-12-11 12:02:20 +00001014// This is called as we come into a loop choice node and some other tricky
ager@chromium.org32912102009-01-16 10:38:43 +00001015// nodes. It normalizes the state of the code generator to ensure we can
ager@chromium.org8bb60582008-12-11 12:02:20 +00001016// generate generic code.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001017void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001018 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001019
iposva@chromium.org245aa852009-02-10 00:49:54 +00001020 ASSERT(!is_trivial());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001021
1022 if (actions_ == NULL && backtrack() == NULL) {
1023 // 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 +00001024 // a normal situation. We may also have to forget some information gained
1025 // through a quick check that was already performed.
1026 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001027 // Create a new trivial state and generate the node with that.
ager@chromium.org32912102009-01-16 10:38:43 +00001028 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001029 successor->Emit(compiler, &new_state);
1030 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001031 }
1032
1033 // Generate deferred actions here along with code to undo them again.
1034 OutSet affected_registers;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001035
ager@chromium.org381abbb2009-02-25 13:23:22 +00001036 if (backtrack() != NULL) {
1037 // Here we have a concrete backtrack location. These are set up by choice
1038 // nodes and so they indicate that we have a deferred save of the current
1039 // position which we may need to emit here.
1040 assembler->PushCurrentPosition();
1041 }
1042
ager@chromium.org8bb60582008-12-11 12:02:20 +00001043 int max_register = FindAffectedRegisters(&affected_registers);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001044 OutSet registers_to_pop;
1045 OutSet registers_to_clear;
1046 PerformDeferredActions(assembler,
1047 max_register,
1048 affected_registers,
1049 &registers_to_pop,
1050 &registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001051 if (cp_offset_ != 0) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001052 assembler->AdvanceCurrentPosition(cp_offset_);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001053 }
1054
1055 // Create a new trivial state and generate the node with that.
1056 Label undo;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001057 assembler->PushBacktrack(&undo);
ager@chromium.org32912102009-01-16 10:38:43 +00001058 Trace new_state;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001059 successor->Emit(compiler, &new_state);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001060
1061 // On backtrack we need to restore state.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001062 assembler->Bind(&undo);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001063 RestoreAffectedRegisters(assembler,
1064 max_register,
1065 registers_to_pop,
1066 registers_to_clear);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001067 if (backtrack() == NULL) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001068 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001069 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001070 assembler->PopCurrentPosition();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001071 assembler->GoTo(backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001072 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001073}
1074
1075
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001076void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001077 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001078
1079 // Omit flushing the trace. We discard the entire stack frame anyway.
1080
ager@chromium.org8bb60582008-12-11 12:02:20 +00001081 if (!label()->is_bound()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001082 // We are completely independent of the trace, since we ignore it,
1083 // so this code can be used as the generic version.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001084 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001085 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001086
1087 // Throw away everything on the backtrack stack since the start
1088 // of the negative submatch and restore the character position.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001089 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1090 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001091 if (clear_capture_count_ > 0) {
1092 // Clear any captures that might have been performed during the success
1093 // of the body of the negative look-ahead.
1094 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1095 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1096 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001097 // Now that we have unwound the stack we find at the top of the stack the
1098 // backtrack that the BeginSubmatch node got.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001099 assembler->Backtrack();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001100}
1101
1102
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001103void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00001104 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001105 trace->Flush(compiler, this);
1106 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001107 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001108 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001109 if (!label()->is_bound()) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001110 assembler->Bind(label());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001111 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001112 switch (action_) {
1113 case ACCEPT:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001114 assembler->Succeed();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001115 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001116 case BACKTRACK:
ager@chromium.org32912102009-01-16 10:38:43 +00001117 assembler->GoTo(trace->backtrack());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001118 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001119 case NEGATIVE_SUBMATCH_SUCCESS:
1120 // This case is handled in a different virtual method.
1121 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001122 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001123 UNIMPLEMENTED();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001124}
1125
1126
1127void GuardedAlternative::AddGuard(Guard* guard) {
1128 if (guards_ == NULL)
1129 guards_ = new ZoneList<Guard*>(1);
1130 guards_->Add(guard);
1131}
1132
1133
ager@chromium.org8bb60582008-12-11 12:02:20 +00001134ActionNode* ActionNode::SetRegister(int reg,
1135 int val,
1136 RegExpNode* on_success) {
1137 ActionNode* result = new ActionNode(SET_REGISTER, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001138 result->data_.u_store_register.reg = reg;
1139 result->data_.u_store_register.value = val;
1140 return result;
1141}
1142
1143
1144ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1145 ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success);
1146 result->data_.u_increment_register.reg = reg;
1147 return result;
1148}
1149
1150
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001151ActionNode* ActionNode::StorePosition(int reg,
1152 bool is_capture,
1153 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001154 ActionNode* result = new ActionNode(STORE_POSITION, on_success);
1155 result->data_.u_position_register.reg = reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001156 result->data_.u_position_register.is_capture = is_capture;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001157 return result;
1158}
1159
1160
ager@chromium.org32912102009-01-16 10:38:43 +00001161ActionNode* ActionNode::ClearCaptures(Interval range,
1162 RegExpNode* on_success) {
1163 ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success);
1164 result->data_.u_clear_captures.range_from = range.from();
1165 result->data_.u_clear_captures.range_to = range.to();
1166 return result;
1167}
1168
1169
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001170ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1171 int position_reg,
1172 RegExpNode* on_success) {
1173 ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success);
1174 result->data_.u_submatch.stack_pointer_register = stack_reg;
1175 result->data_.u_submatch.current_position_register = position_reg;
1176 return result;
1177}
1178
1179
ager@chromium.org8bb60582008-12-11 12:02:20 +00001180ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1181 int position_reg,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001182 int clear_register_count,
1183 int clear_register_from,
ager@chromium.org8bb60582008-12-11 12:02:20 +00001184 RegExpNode* on_success) {
1185 ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001186 result->data_.u_submatch.stack_pointer_register = stack_reg;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001187 result->data_.u_submatch.current_position_register = position_reg;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001188 result->data_.u_submatch.clear_register_count = clear_register_count;
1189 result->data_.u_submatch.clear_register_from = clear_register_from;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001190 return result;
1191}
1192
1193
ager@chromium.org32912102009-01-16 10:38:43 +00001194ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1195 int repetition_register,
1196 int repetition_limit,
1197 RegExpNode* on_success) {
1198 ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success);
1199 result->data_.u_empty_match_check.start_register = start_register;
1200 result->data_.u_empty_match_check.repetition_register = repetition_register;
1201 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1202 return result;
1203}
1204
1205
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001206#define DEFINE_ACCEPT(Type) \
1207 void Type##Node::Accept(NodeVisitor* visitor) { \
1208 visitor->Visit##Type(this); \
1209 }
1210FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1211#undef DEFINE_ACCEPT
1212
1213
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001214void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1215 visitor->VisitLoopChoice(this);
1216}
1217
1218
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001219// -------------------------------------------------------------------
1220// Emit code.
1221
1222
1223void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1224 Guard* guard,
ager@chromium.org32912102009-01-16 10:38:43 +00001225 Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001226 switch (guard->op()) {
1227 case Guard::LT:
ager@chromium.org32912102009-01-16 10:38:43 +00001228 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001229 macro_assembler->IfRegisterGE(guard->reg(),
1230 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001231 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001232 break;
1233 case Guard::GEQ:
ager@chromium.org32912102009-01-16 10:38:43 +00001234 ASSERT(!trace->mentions_reg(guard->reg()));
ager@chromium.org8bb60582008-12-11 12:02:20 +00001235 macro_assembler->IfRegisterLT(guard->reg(),
1236 guard->value(),
ager@chromium.org32912102009-01-16 10:38:43 +00001237 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001238 break;
1239 }
1240}
1241
1242
1243static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
1244static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
1245
1246
ager@chromium.org381abbb2009-02-25 13:23:22 +00001247// Returns the number of characters in the equivalence class, omitting those
1248// that cannot occur in the source string because it is ASCII.
1249static int GetCaseIndependentLetters(uc16 character,
1250 bool ascii_subject,
1251 unibrow::uchar* letters) {
1252 int length = uncanonicalize.get(character, '\0', letters);
1253 // Unibrow returns 0 or 1 for characters where case independependence is
1254 // trivial.
1255 if (length == 0) {
1256 letters[0] = character;
1257 length = 1;
1258 }
1259 if (!ascii_subject || character <= String::kMaxAsciiCharCode) {
1260 return length;
1261 }
1262 // The standard requires that non-ASCII characters cannot have ASCII
1263 // character codes in their equivalence class.
1264 return 0;
1265}
1266
1267
1268static inline bool EmitSimpleCharacter(RegExpCompiler* compiler,
1269 uc16 c,
1270 Label* on_failure,
1271 int cp_offset,
1272 bool check,
1273 bool preloaded) {
1274 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1275 bool bound_checked = false;
1276 if (!preloaded) {
1277 assembler->LoadCurrentCharacter(
1278 cp_offset,
1279 on_failure,
1280 check);
1281 bound_checked = true;
1282 }
1283 assembler->CheckNotCharacter(c, on_failure);
1284 return bound_checked;
1285}
1286
1287
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001288// Only emits non-letters (things that don't have case). Only used for case
1289// independent matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001290static inline bool EmitAtomNonLetter(RegExpCompiler* compiler,
1291 uc16 c,
1292 Label* on_failure,
1293 int cp_offset,
1294 bool check,
1295 bool preloaded) {
1296 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1297 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001298 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001299 int length = GetCaseIndependentLetters(c, ascii, chars);
1300 if (length < 1) {
1301 // This can't match. Must be an ASCII subject and a non-ASCII character.
1302 // We do not need to do anything since the ASCII pass already handled this.
1303 return false; // Bounds not checked.
1304 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001305 bool checked = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001306 // We handle the length > 1 case in a later pass.
1307 if (length == 1) {
1308 if (ascii && c > String::kMaxAsciiCharCodeU) {
1309 // Can't match - see above.
1310 return false; // Bounds not checked.
1311 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001312 if (!preloaded) {
1313 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1314 checked = check;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001315 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001316 macro_assembler->CheckNotCharacter(c, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001317 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001318 return checked;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001319}
1320
1321
1322static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001323 bool ascii,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001324 uc16 c1,
1325 uc16 c2,
1326 Label* on_failure) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001327 uc16 char_mask;
1328 if (ascii) {
1329 char_mask = String::kMaxAsciiCharCode;
1330 } else {
1331 char_mask = String::kMaxUC16CharCode;
1332 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001333 uc16 exor = c1 ^ c2;
1334 // Check whether exor has only one bit set.
1335 if (((exor - 1) & exor) == 0) {
1336 // If c1 and c2 differ only by one bit.
1337 // Ecma262UnCanonicalize always gives the highest number last.
1338 ASSERT(c2 > c1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001339 uc16 mask = char_mask ^ exor;
1340 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001341 return true;
1342 }
1343 ASSERT(c2 > c1);
1344 uc16 diff = c2 - c1;
1345 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1346 // If the characters differ by 2^n but don't differ by one bit then
1347 // subtract the difference from the found character, then do the or
1348 // trick. We avoid the theoretical case where negative numbers are
1349 // involved in order to simplify code generation.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001350 uc16 mask = char_mask ^ diff;
1351 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1352 diff,
1353 mask,
1354 on_failure);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001355 return true;
1356 }
1357 return false;
1358}
1359
1360
ager@chromium.org381abbb2009-02-25 13:23:22 +00001361typedef bool EmitCharacterFunction(RegExpCompiler* compiler,
1362 uc16 c,
1363 Label* on_failure,
1364 int cp_offset,
1365 bool check,
1366 bool preloaded);
1367
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001368// Only emits letters (things that have case). Only used for case independent
1369// matches.
ager@chromium.org381abbb2009-02-25 13:23:22 +00001370static inline bool EmitAtomLetter(RegExpCompiler* compiler,
1371 uc16 c,
1372 Label* on_failure,
1373 int cp_offset,
1374 bool check,
1375 bool preloaded) {
1376 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1377 bool ascii = compiler->ascii();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001378 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001379 int length = GetCaseIndependentLetters(c, ascii, chars);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001380 if (length <= 1) return false;
1381 // We may not need to check against the end of the input string
1382 // if this character lies before a character that matched.
1383 if (!preloaded) {
1384 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001385 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001386 Label ok;
1387 ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1388 switch (length) {
1389 case 2: {
1390 if (ShortCutEmitCharacterPair(macro_assembler,
1391 ascii,
1392 chars[0],
1393 chars[1],
1394 on_failure)) {
1395 } else {
1396 macro_assembler->CheckCharacter(chars[0], &ok);
1397 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1398 macro_assembler->Bind(&ok);
1399 }
1400 break;
1401 }
1402 case 4:
1403 macro_assembler->CheckCharacter(chars[3], &ok);
1404 // Fall through!
1405 case 3:
1406 macro_assembler->CheckCharacter(chars[0], &ok);
1407 macro_assembler->CheckCharacter(chars[1], &ok);
1408 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1409 macro_assembler->Bind(&ok);
1410 break;
1411 default:
1412 UNREACHABLE();
1413 break;
1414 }
1415 return true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001416}
1417
1418
1419static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
1420 RegExpCharacterClass* cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001421 bool ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00001422 Label* on_failure,
1423 int cp_offset,
1424 bool check_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001425 bool preloaded) {
1426 if (cc->is_standard() &&
1427 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
1428 cp_offset,
1429 check_offset,
1430 on_failure)) {
1431 return;
1432 }
1433
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001434 ZoneList<CharacterRange>* ranges = cc->ranges();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001435 int max_char;
1436 if (ascii) {
1437 max_char = String::kMaxAsciiCharCode;
1438 } else {
1439 max_char = String::kMaxUC16CharCode;
1440 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001441
1442 Label success;
1443
1444 Label* char_is_in_class =
1445 cc->is_negated() ? on_failure : &success;
1446
1447 int range_count = ranges->length();
1448
ager@chromium.org8bb60582008-12-11 12:02:20 +00001449 int last_valid_range = range_count - 1;
1450 while (last_valid_range >= 0) {
1451 CharacterRange& range = ranges->at(last_valid_range);
1452 if (range.from() <= max_char) {
1453 break;
1454 }
1455 last_valid_range--;
1456 }
1457
1458 if (last_valid_range < 0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001459 if (!cc->is_negated()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001460 // TODO(plesner): We can remove this when the node level does our
1461 // ASCII optimizations for us.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001462 macro_assembler->GoTo(on_failure);
1463 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001464 if (check_offset) {
1465 macro_assembler->CheckPosition(cp_offset, on_failure);
1466 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001467 return;
1468 }
1469
ager@chromium.org8bb60582008-12-11 12:02:20 +00001470 if (last_valid_range == 0 &&
1471 !cc->is_negated() &&
1472 ranges->at(0).IsEverything(max_char)) {
1473 // This is a common case hit by non-anchored expressions.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001474 if (check_offset) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001475 macro_assembler->CheckPosition(cp_offset, on_failure);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001476 }
1477 return;
1478 }
1479
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001480 if (!preloaded) {
1481 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
ager@chromium.org8bb60582008-12-11 12:02:20 +00001482 }
1483
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001484 for (int i = 0; i < last_valid_range; i++) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001485 CharacterRange& range = ranges->at(i);
1486 Label next_range;
1487 uc16 from = range.from();
1488 uc16 to = range.to();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001489 if (from > max_char) {
1490 continue;
1491 }
1492 if (to > max_char) to = max_char;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001493 if (to == from) {
1494 macro_assembler->CheckCharacter(to, char_is_in_class);
1495 } else {
1496 if (from != 0) {
1497 macro_assembler->CheckCharacterLT(from, &next_range);
1498 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001499 if (to != max_char) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001500 macro_assembler->CheckCharacterLT(to + 1, char_is_in_class);
1501 } else {
1502 macro_assembler->GoTo(char_is_in_class);
1503 }
1504 }
1505 macro_assembler->Bind(&next_range);
1506 }
1507
ager@chromium.org8bb60582008-12-11 12:02:20 +00001508 CharacterRange& range = ranges->at(last_valid_range);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001509 uc16 from = range.from();
1510 uc16 to = range.to();
1511
ager@chromium.org8bb60582008-12-11 12:02:20 +00001512 if (to > max_char) to = max_char;
1513 ASSERT(to >= from);
1514
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001515 if (to == from) {
1516 if (cc->is_negated()) {
1517 macro_assembler->CheckCharacter(to, on_failure);
1518 } else {
1519 macro_assembler->CheckNotCharacter(to, on_failure);
1520 }
1521 } else {
1522 if (from != 0) {
1523 if (cc->is_negated()) {
1524 macro_assembler->CheckCharacterLT(from, &success);
1525 } else {
1526 macro_assembler->CheckCharacterLT(from, on_failure);
1527 }
1528 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001529 if (to != String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001530 if (cc->is_negated()) {
1531 macro_assembler->CheckCharacterLT(to + 1, on_failure);
1532 } else {
1533 macro_assembler->CheckCharacterGT(to, on_failure);
1534 }
1535 } else {
1536 if (cc->is_negated()) {
1537 macro_assembler->GoTo(on_failure);
1538 }
1539 }
1540 }
1541 macro_assembler->Bind(&success);
1542}
1543
1544
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001545RegExpNode::~RegExpNode() {
1546}
1547
1548
ager@chromium.org8bb60582008-12-11 12:02:20 +00001549RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001550 Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001551 // If we are generating a greedy loop then don't stop and don't reuse code.
ager@chromium.org32912102009-01-16 10:38:43 +00001552 if (trace->stop_node() != NULL) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001553 return CONTINUE;
1554 }
1555
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001556 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00001557 if (trace->is_trivial()) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001558 if (label_.is_bound()) {
1559 // We are being asked to generate a generic version, but that's already
1560 // been done so just go to it.
1561 macro_assembler->GoTo(&label_);
1562 return DONE;
1563 }
1564 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
1565 // To avoid too deep recursion we push the node to the work queue and just
1566 // generate a goto here.
1567 compiler->AddWork(this);
1568 macro_assembler->GoTo(&label_);
1569 return DONE;
1570 }
1571 // Generate generic version of the node and bind the label for later use.
1572 macro_assembler->Bind(&label_);
1573 return CONTINUE;
1574 }
1575
1576 // We are being asked to make a non-generic version. Keep track of how many
1577 // non-generic versions we generate so as not to overdo it.
ager@chromium.org32912102009-01-16 10:38:43 +00001578 trace_count_++;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001579 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00001580 trace_count_ < kMaxCopiesCodeGenerated &&
ager@chromium.org8bb60582008-12-11 12:02:20 +00001581 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
1582 return CONTINUE;
1583 }
1584
ager@chromium.org32912102009-01-16 10:38:43 +00001585 // If we get here code has been generated for this node too many times or
1586 // recursion is too deep. Time to switch to a generic version. The code for
ager@chromium.org8bb60582008-12-11 12:02:20 +00001587 // generic versions above can handle deep recursion properly.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001588 trace->Flush(compiler, this);
1589 return DONE;
ager@chromium.org8bb60582008-12-11 12:02:20 +00001590}
1591
1592
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001593int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001594 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1595 if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001596 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001597}
1598
1599
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001600int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1601 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1602 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1603}
1604
1605
1606int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1607 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1608 return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1);
1609}
1610
1611
1612int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001613 int answer = Length();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001614 if (answer >= still_to_find) return answer;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001615 if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001616 return answer + on_success()->EatsAtLeast(still_to_find - answer,
1617 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001618}
1619
1620
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001621int NegativeLookaheadChoiceNode:: EatsAtLeast(int still_to_find,
1622 int recursion_depth) {
1623 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1624 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1625 // afterwards.
1626 RegExpNode* node = alternatives_->at(1).node();
1627 return node->EatsAtLeast(still_to_find, recursion_depth + 1);
1628}
1629
1630
1631void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
1632 QuickCheckDetails* details,
1633 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001634 int filled_in,
1635 bool not_at_start) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001636 // Alternative 0 is the negative lookahead, alternative 1 is what comes
1637 // afterwards.
1638 RegExpNode* node = alternatives_->at(1).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001639 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001640}
1641
1642
1643int ChoiceNode::EatsAtLeastHelper(int still_to_find,
1644 int recursion_depth,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001645 RegExpNode* ignore_this_node) {
1646 if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0;
1647 int min = 100;
1648 int choice_count = alternatives_->length();
1649 for (int i = 0; i < choice_count; i++) {
1650 RegExpNode* node = alternatives_->at(i).node();
1651 if (node == ignore_this_node) continue;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001652 int node_eats_at_least = node->EatsAtLeast(still_to_find,
1653 recursion_depth + 1);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001654 if (node_eats_at_least < min) min = node_eats_at_least;
1655 }
1656 return min;
1657}
1658
1659
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001660int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1661 return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001662}
1663
1664
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001665int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) {
1666 return EatsAtLeastHelper(still_to_find, recursion_depth, NULL);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001667}
1668
1669
1670// Takes the left-most 1-bit and smears it out, setting all bits to its right.
1671static inline uint32_t SmearBitsRight(uint32_t v) {
1672 v |= v >> 1;
1673 v |= v >> 2;
1674 v |= v >> 4;
1675 v |= v >> 8;
1676 v |= v >> 16;
1677 return v;
1678}
1679
1680
1681bool QuickCheckDetails::Rationalize(bool asc) {
1682 bool found_useful_op = false;
1683 uint32_t char_mask;
1684 if (asc) {
1685 char_mask = String::kMaxAsciiCharCode;
1686 } else {
1687 char_mask = String::kMaxUC16CharCode;
1688 }
1689 mask_ = 0;
1690 value_ = 0;
1691 int char_shift = 0;
1692 for (int i = 0; i < characters_; i++) {
1693 Position* pos = &positions_[i];
1694 if ((pos->mask & String::kMaxAsciiCharCode) != 0) {
1695 found_useful_op = true;
1696 }
1697 mask_ |= (pos->mask & char_mask) << char_shift;
1698 value_ |= (pos->value & char_mask) << char_shift;
1699 char_shift += asc ? 8 : 16;
1700 }
1701 return found_useful_op;
1702}
1703
1704
1705bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00001706 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001707 bool preload_has_checked_bounds,
1708 Label* on_possible_success,
1709 QuickCheckDetails* details,
1710 bool fall_through_on_failure) {
1711 if (details->characters() == 0) return false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001712 GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
1713 if (details->cannot_match()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001714 if (!details->Rationalize(compiler->ascii())) return false;
1715 uint32_t mask = details->mask();
1716 uint32_t value = details->value();
1717
1718 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1719
ager@chromium.org32912102009-01-16 10:38:43 +00001720 if (trace->characters_preloaded() != details->characters()) {
1721 assembler->LoadCurrentCharacter(trace->cp_offset(),
1722 trace->backtrack(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001723 !preload_has_checked_bounds,
1724 details->characters());
1725 }
1726
1727
1728 bool need_mask = true;
1729
1730 if (details->characters() == 1) {
1731 // If number of characters preloaded is 1 then we used a byte or 16 bit
1732 // load so the value is already masked down.
1733 uint32_t char_mask;
1734 if (compiler->ascii()) {
1735 char_mask = String::kMaxAsciiCharCode;
1736 } else {
1737 char_mask = String::kMaxUC16CharCode;
1738 }
1739 if ((mask & char_mask) == char_mask) need_mask = false;
1740 mask &= char_mask;
1741 } else {
1742 // For 2-character preloads in ASCII mode we also use a 16 bit load with
1743 // zero extend.
1744 if (details->characters() == 2 && compiler->ascii()) {
1745 if ((mask & 0xffff) == 0xffff) need_mask = false;
1746 } else {
1747 if (mask == 0xffffffff) need_mask = false;
1748 }
1749 }
1750
1751 if (fall_through_on_failure) {
1752 if (need_mask) {
1753 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
1754 } else {
1755 assembler->CheckCharacter(value, on_possible_success);
1756 }
1757 } else {
1758 if (need_mask) {
ager@chromium.org32912102009-01-16 10:38:43 +00001759 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001760 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00001761 assembler->CheckNotCharacter(value, trace->backtrack());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001762 }
1763 }
1764 return true;
1765}
1766
1767
1768// Here is the meat of GetQuickCheckDetails (see also the comment on the
1769// super-class in the .h file).
1770//
1771// We iterate along the text object, building up for each character a
1772// mask and value that can be used to test for a quick failure to match.
1773// The masks and values for the positions will be combined into a single
1774// machine word for the current character width in order to be used in
1775// generating a quick check.
1776void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
1777 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001778 int characters_filled_in,
1779 bool not_at_start) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001780 ASSERT(characters_filled_in < details->characters());
1781 int characters = details->characters();
1782 int char_mask;
1783 int char_shift;
1784 if (compiler->ascii()) {
1785 char_mask = String::kMaxAsciiCharCode;
1786 char_shift = 8;
1787 } else {
1788 char_mask = String::kMaxUC16CharCode;
1789 char_shift = 16;
1790 }
1791 for (int k = 0; k < elms_->length(); k++) {
1792 TextElement elm = elms_->at(k);
1793 if (elm.type == TextElement::ATOM) {
1794 Vector<const uc16> quarks = elm.data.u_atom->data();
1795 for (int i = 0; i < characters && i < quarks.length(); i++) {
1796 QuickCheckDetails::Position* pos =
1797 details->positions(characters_filled_in);
ager@chromium.org6f10e412009-02-13 10:11:16 +00001798 uc16 c = quarks[i];
1799 if (c > char_mask) {
1800 // If we expect a non-ASCII character from an ASCII string,
1801 // there is no way we can match. Not even case independent
1802 // matching can turn an ASCII character into non-ASCII or
1803 // vice versa.
1804 details->set_cannot_match();
ager@chromium.org381abbb2009-02-25 13:23:22 +00001805 pos->determines_perfectly = false;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001806 return;
1807 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001808 if (compiler->ignore_case()) {
1809 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
ager@chromium.org381abbb2009-02-25 13:23:22 +00001810 int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
1811 ASSERT(length != 0); // Can only happen if c > char_mask (see above).
1812 if (length == 1) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001813 // This letter has no case equivalents, so it's nice and simple
1814 // and the mask-compare will determine definitely whether we have
1815 // a match at this character position.
1816 pos->mask = char_mask;
1817 pos->value = c;
1818 pos->determines_perfectly = true;
1819 } else {
1820 uint32_t common_bits = char_mask;
1821 uint32_t bits = chars[0];
1822 for (int j = 1; j < length; j++) {
1823 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
1824 common_bits ^= differing_bits;
1825 bits &= common_bits;
1826 }
1827 // If length is 2 and common bits has only one zero in it then
1828 // our mask and compare instruction will determine definitely
1829 // whether we have a match at this character position. Otherwise
1830 // it can only be an approximate check.
1831 uint32_t one_zero = (common_bits | ~char_mask);
1832 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
1833 pos->determines_perfectly = true;
1834 }
1835 pos->mask = common_bits;
1836 pos->value = bits;
1837 }
1838 } else {
1839 // Don't ignore case. Nice simple case where the mask-compare will
1840 // determine definitely whether we have a match at this character
1841 // position.
1842 pos->mask = char_mask;
ager@chromium.org6f10e412009-02-13 10:11:16 +00001843 pos->value = c;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001844 pos->determines_perfectly = true;
1845 }
1846 characters_filled_in++;
1847 ASSERT(characters_filled_in <= details->characters());
1848 if (characters_filled_in == details->characters()) {
1849 return;
1850 }
1851 }
1852 } else {
1853 QuickCheckDetails::Position* pos =
1854 details->positions(characters_filled_in);
1855 RegExpCharacterClass* tree = elm.data.u_char_class;
1856 ZoneList<CharacterRange>* ranges = tree->ranges();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001857 if (tree->is_negated()) {
1858 // A quick check uses multi-character mask and compare. There is no
1859 // useful way to incorporate a negative char class into this scheme
1860 // so we just conservatively create a mask and value that will always
1861 // succeed.
1862 pos->mask = 0;
1863 pos->value = 0;
1864 } else {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001865 int first_range = 0;
1866 while (ranges->at(first_range).from() > char_mask) {
1867 first_range++;
1868 if (first_range == ranges->length()) {
1869 details->set_cannot_match();
1870 pos->determines_perfectly = false;
1871 return;
1872 }
1873 }
1874 CharacterRange range = ranges->at(first_range);
1875 uc16 from = range.from();
1876 uc16 to = range.to();
1877 if (to > char_mask) {
1878 to = char_mask;
1879 }
1880 uint32_t differing_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001881 // A mask and compare is only perfect if the differing bits form a
1882 // number like 00011111 with one single block of trailing 1s.
1883 if ((differing_bits & (differing_bits + 1)) == 0) {
1884 pos->determines_perfectly = true;
1885 }
1886 uint32_t common_bits = ~SmearBitsRight(differing_bits);
ager@chromium.org381abbb2009-02-25 13:23:22 +00001887 uint32_t bits = (from & common_bits);
1888 for (int i = first_range + 1; i < ranges->length(); i++) {
1889 CharacterRange range = ranges->at(i);
1890 uc16 from = range.from();
1891 uc16 to = range.to();
1892 if (from > char_mask) continue;
1893 if (to > char_mask) to = char_mask;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001894 // Here we are combining more ranges into the mask and compare
1895 // value. With each new range the mask becomes more sparse and
1896 // so the chances of a false positive rise. A character class
1897 // with multiple ranges is assumed never to be equivalent to a
1898 // mask and compare operation.
1899 pos->determines_perfectly = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001900 uint32_t new_common_bits = (from ^ to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001901 new_common_bits = ~SmearBitsRight(new_common_bits);
1902 common_bits &= new_common_bits;
1903 bits &= new_common_bits;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001904 uint32_t differing_bits = (from & common_bits) ^ bits;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001905 common_bits ^= differing_bits;
1906 bits &= common_bits;
1907 }
1908 pos->mask = common_bits;
1909 pos->value = bits;
1910 }
1911 characters_filled_in++;
1912 ASSERT(characters_filled_in <= details->characters());
1913 if (characters_filled_in == details->characters()) {
1914 return;
1915 }
1916 }
1917 }
1918 ASSERT(characters_filled_in != details->characters());
iposva@chromium.org245aa852009-02-10 00:49:54 +00001919 on_success()-> GetQuickCheckDetails(details,
1920 compiler,
1921 characters_filled_in,
1922 true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001923}
1924
1925
1926void QuickCheckDetails::Clear() {
1927 for (int i = 0; i < characters_; i++) {
1928 positions_[i].mask = 0;
1929 positions_[i].value = 0;
1930 positions_[i].determines_perfectly = false;
1931 }
1932 characters_ = 0;
1933}
1934
1935
1936void QuickCheckDetails::Advance(int by, bool ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001937 ASSERT(by >= 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001938 if (by >= characters_) {
1939 Clear();
1940 return;
1941 }
1942 for (int i = 0; i < characters_ - by; i++) {
1943 positions_[i] = positions_[by + i];
1944 }
1945 for (int i = characters_ - by; i < characters_; i++) {
1946 positions_[i].mask = 0;
1947 positions_[i].value = 0;
1948 positions_[i].determines_perfectly = false;
1949 }
1950 characters_ -= by;
1951 // We could change mask_ and value_ here but we would never advance unless
1952 // they had already been used in a check and they won't be used again because
1953 // it would gain us nothing. So there's no point.
1954}
1955
1956
1957void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
1958 ASSERT(characters_ == other->characters_);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001959 if (other->cannot_match_) {
1960 return;
1961 }
1962 if (cannot_match_) {
1963 *this = *other;
1964 return;
1965 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001966 for (int i = from_index; i < characters_; i++) {
1967 QuickCheckDetails::Position* pos = positions(i);
1968 QuickCheckDetails::Position* other_pos = other->positions(i);
1969 if (pos->mask != other_pos->mask ||
1970 pos->value != other_pos->value ||
1971 !other_pos->determines_perfectly) {
1972 // Our mask-compare operation will be approximate unless we have the
1973 // exact same operation on both sides of the alternation.
1974 pos->determines_perfectly = false;
1975 }
1976 pos->mask &= other_pos->mask;
1977 pos->value &= pos->mask;
1978 other_pos->value &= pos->mask;
1979 uc16 differing_bits = (pos->value ^ other_pos->value);
1980 pos->mask &= ~differing_bits;
1981 pos->value &= pos->mask;
1982 }
1983}
1984
1985
ager@chromium.org32912102009-01-16 10:38:43 +00001986class VisitMarker {
1987 public:
1988 explicit VisitMarker(NodeInfo* info) : info_(info) {
1989 ASSERT(!info->visited);
1990 info->visited = true;
1991 }
1992 ~VisitMarker() {
1993 info_->visited = false;
1994 }
1995 private:
1996 NodeInfo* info_;
1997};
1998
1999
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002000void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2001 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002002 int characters_filled_in,
2003 bool not_at_start) {
ager@chromium.org32912102009-01-16 10:38:43 +00002004 if (body_can_be_zero_length_ || info()->visited) return;
2005 VisitMarker marker(info());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002006 return ChoiceNode::GetQuickCheckDetails(details,
2007 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002008 characters_filled_in,
2009 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002010}
2011
2012
2013void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2014 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002015 int characters_filled_in,
2016 bool not_at_start) {
2017 not_at_start = (not_at_start || not_at_start_);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002018 int choice_count = alternatives_->length();
2019 ASSERT(choice_count > 0);
2020 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2021 compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002022 characters_filled_in,
2023 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002024 for (int i = 1; i < choice_count; i++) {
2025 QuickCheckDetails new_details(details->characters());
2026 RegExpNode* node = alternatives_->at(i).node();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002027 node->GetQuickCheckDetails(&new_details, compiler,
2028 characters_filled_in,
2029 not_at_start);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002030 // Here we merge the quick match details of the two branches.
2031 details->Merge(&new_details, characters_filled_in);
2032 }
2033}
2034
2035
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002036// Check for [0-9A-Z_a-z].
2037static void EmitWordCheck(RegExpMacroAssembler* assembler,
2038 Label* word,
2039 Label* non_word,
2040 bool fall_through_on_word) {
2041 assembler->CheckCharacterGT('z', non_word);
2042 assembler->CheckCharacterLT('0', non_word);
2043 assembler->CheckCharacterGT('a' - 1, word);
2044 assembler->CheckCharacterLT('9' + 1, word);
2045 assembler->CheckCharacterLT('A', non_word);
2046 assembler->CheckCharacterLT('Z' + 1, word);
2047 if (fall_through_on_word) {
2048 assembler->CheckNotCharacter('_', non_word);
2049 } else {
2050 assembler->CheckCharacter('_', word);
2051 }
2052}
2053
2054
2055// Emit the code to check for a ^ in multiline mode (1-character lookbehind
2056// that matches newline or the start of input).
2057static void EmitHat(RegExpCompiler* compiler,
2058 RegExpNode* on_success,
2059 Trace* trace) {
2060 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2061 // We will be loading the previous character into the current character
2062 // register.
2063 Trace new_trace(*trace);
2064 new_trace.InvalidateCurrentCharacter();
2065
2066 Label ok;
2067 if (new_trace.cp_offset() == 0) {
2068 // The start of input counts as a newline in this context, so skip to
2069 // ok if we are at the start.
2070 assembler->CheckAtStart(&ok);
2071 }
2072 // We already checked that we are not at the start of input so it must be
2073 // OK to load the previous character.
2074 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
2075 new_trace.backtrack(),
2076 false);
2077 // Newline means \n, \r, 0x2028 or 0x2029.
2078 if (!compiler->ascii()) {
2079 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
2080 }
2081 assembler->CheckCharacter('\n', &ok);
2082 assembler->CheckNotCharacter('\r', new_trace.backtrack());
2083 assembler->Bind(&ok);
2084 on_success->Emit(compiler, &new_trace);
2085}
2086
2087
2088// Emit the code to handle \b and \B (word-boundary or non-word-boundary).
2089static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type,
2090 RegExpCompiler* compiler,
2091 RegExpNode* on_success,
2092 Trace* trace) {
2093 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2094 Label before_non_word;
2095 Label before_word;
2096 if (trace->characters_preloaded() != 1) {
2097 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
2098 }
2099 // Fall through on non-word.
2100 EmitWordCheck(assembler, &before_word, &before_non_word, false);
2101
2102 // We will be loading the previous character into the current character
2103 // register.
2104 Trace new_trace(*trace);
2105 new_trace.InvalidateCurrentCharacter();
2106
2107 Label ok;
2108 Label* boundary;
2109 Label* not_boundary;
2110 if (type == AssertionNode::AT_BOUNDARY) {
2111 boundary = &ok;
2112 not_boundary = new_trace.backtrack();
2113 } else {
2114 not_boundary = &ok;
2115 boundary = new_trace.backtrack();
2116 }
2117
2118 // Next character is not a word character.
2119 assembler->Bind(&before_non_word);
2120 if (new_trace.cp_offset() == 0) {
2121 // The start of input counts as a non-word character, so the question is
2122 // decided if we are at the start.
2123 assembler->CheckAtStart(not_boundary);
2124 }
2125 // We already checked that we are not at the start of input so it must be
2126 // OK to load the previous character.
2127 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2128 &ok, // Unused dummy label in this call.
2129 false);
2130 // Fall through on non-word.
2131 EmitWordCheck(assembler, boundary, not_boundary, false);
2132 assembler->GoTo(not_boundary);
2133
2134 // Next character is a word character.
2135 assembler->Bind(&before_word);
2136 if (new_trace.cp_offset() == 0) {
2137 // The start of input counts as a non-word character, so the question is
2138 // decided if we are at the start.
2139 assembler->CheckAtStart(boundary);
2140 }
2141 // We already checked that we are not at the start of input so it must be
2142 // OK to load the previous character.
2143 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1,
2144 &ok, // Unused dummy label in this call.
2145 false);
2146 bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY);
2147 EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word);
2148
2149 assembler->Bind(&ok);
2150
2151 on_success->Emit(compiler, &new_trace);
2152}
2153
2154
iposva@chromium.org245aa852009-02-10 00:49:54 +00002155void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
2156 RegExpCompiler* compiler,
2157 int filled_in,
2158 bool not_at_start) {
2159 if (type_ == AT_START && not_at_start) {
2160 details->set_cannot_match();
2161 return;
2162 }
2163 return on_success()->GetQuickCheckDetails(details,
2164 compiler,
2165 filled_in,
2166 not_at_start);
2167}
2168
2169
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002170void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
2171 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2172 switch (type_) {
2173 case AT_END: {
2174 Label ok;
2175 assembler->CheckPosition(trace->cp_offset(), &ok);
2176 assembler->GoTo(trace->backtrack());
2177 assembler->Bind(&ok);
2178 break;
2179 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002180 case AT_START: {
2181 if (trace->at_start() == Trace::FALSE) {
2182 assembler->GoTo(trace->backtrack());
2183 return;
2184 }
2185 if (trace->at_start() == Trace::UNKNOWN) {
2186 assembler->CheckNotAtStart(trace->backtrack());
2187 Trace at_start_trace = *trace;
2188 at_start_trace.set_at_start(true);
2189 on_success()->Emit(compiler, &at_start_trace);
2190 return;
2191 }
2192 }
2193 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002194 case AFTER_NEWLINE:
2195 EmitHat(compiler, on_success(), trace);
2196 return;
2197 case AT_NON_BOUNDARY:
2198 case AT_BOUNDARY:
2199 EmitBoundaryCheck(type_, compiler, on_success(), trace);
2200 return;
2201 }
2202 on_success()->Emit(compiler, trace);
2203}
2204
2205
ager@chromium.org381abbb2009-02-25 13:23:22 +00002206static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
2207 if (quick_check == NULL) return false;
2208 if (offset >= quick_check->characters()) return false;
2209 return quick_check->positions(offset)->determines_perfectly;
2210}
2211
2212
2213static void UpdateBoundsCheck(int index, int* checked_up_to) {
2214 if (index > *checked_up_to) {
2215 *checked_up_to = index;
2216 }
2217}
2218
2219
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002220// We call this repeatedly to generate code for each pass over the text node.
2221// The passes are in increasing order of difficulty because we hope one
2222// of the first passes will fail in which case we are saved the work of the
2223// later passes. for example for the case independent regexp /%[asdfghjkl]a/
2224// we will check the '%' in the first pass, the case independent 'a' in the
2225// second pass and the character class in the last pass.
2226//
2227// The passes are done from right to left, so for example to test for /bar/
2228// we will first test for an 'r' with offset 2, then an 'a' with offset 1
2229// and then a 'b' with offset 0. This means we can avoid the end-of-input
2230// bounds check most of the time. In the example we only need to check for
2231// end-of-input when loading the putative 'r'.
2232//
2233// A slight complication involves the fact that the first character may already
2234// be fetched into a register by the previous node. In this case we want to
2235// do the test for that character first. We do this in separate passes. The
2236// 'preloaded' argument indicates that we are doing such a 'pass'. If such a
2237// pass has been performed then subsequent passes will have true in
2238// first_element_checked to indicate that that character does not need to be
2239// checked again.
2240//
ager@chromium.org32912102009-01-16 10:38:43 +00002241// In addition to all this we are passed a Trace, which can
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002242// contain an AlternativeGeneration object. In this AlternativeGeneration
2243// object we can see details of any quick check that was already passed in
2244// order to get to the code we are now generating. The quick check can involve
2245// loading characters, which means we do not need to recheck the bounds
2246// up to the limit the quick check already checked. In addition the quick
2247// check can have involved a mask and compare operation which may simplify
2248// or obviate the need for further checks at some character positions.
2249void TextNode::TextEmitPass(RegExpCompiler* compiler,
2250 TextEmitPassType pass,
2251 bool preloaded,
ager@chromium.org32912102009-01-16 10:38:43 +00002252 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002253 bool first_element_checked,
2254 int* checked_up_to) {
2255 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2256 bool ascii = compiler->ascii();
ager@chromium.org32912102009-01-16 10:38:43 +00002257 Label* backtrack = trace->backtrack();
2258 QuickCheckDetails* quick_check = trace->quick_check_performed();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002259 int element_count = elms_->length();
2260 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
2261 TextElement elm = elms_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002262 int cp_offset = trace->cp_offset() + elm.cp_offset;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002263 if (elm.type == TextElement::ATOM) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002264 Vector<const uc16> quarks = elm.data.u_atom->data();
2265 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
2266 if (first_element_checked && i == 0 && j == 0) continue;
2267 if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue;
2268 EmitCharacterFunction* emit_function = NULL;
2269 switch (pass) {
2270 case NON_ASCII_MATCH:
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002271 ASSERT(ascii);
2272 if (quarks[j] > String::kMaxAsciiCharCode) {
2273 assembler->GoTo(backtrack);
2274 return;
2275 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002276 break;
2277 case NON_LETTER_CHARACTER_MATCH:
2278 emit_function = &EmitAtomNonLetter;
2279 break;
2280 case SIMPLE_CHARACTER_MATCH:
2281 emit_function = &EmitSimpleCharacter;
2282 break;
2283 case CASE_CHARACTER_MATCH:
2284 emit_function = &EmitAtomLetter;
2285 break;
2286 default:
2287 break;
2288 }
2289 if (emit_function != NULL) {
2290 bool bound_checked = emit_function(compiler,
ager@chromium.org6f10e412009-02-13 10:11:16 +00002291 quarks[j],
2292 backtrack,
2293 cp_offset + j,
2294 *checked_up_to < cp_offset + j,
2295 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002296 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002297 }
2298 }
2299 } else {
2300 ASSERT_EQ(elm.type, TextElement::CHAR_CLASS);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002301 if (pass == CHARACTER_CLASS_MATCH) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002302 if (first_element_checked && i == 0) continue;
2303 if (DeterminedAlready(quick_check, elm.cp_offset)) continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002304 RegExpCharacterClass* cc = elm.data.u_char_class;
2305 EmitCharClass(assembler,
2306 cc,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002307 ascii,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002308 backtrack,
2309 cp_offset,
2310 *checked_up_to < cp_offset,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002311 preloaded);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002312 UpdateBoundsCheck(cp_offset, checked_up_to);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002313 }
2314 }
2315 }
2316}
2317
2318
2319int TextNode::Length() {
2320 TextElement elm = elms_->last();
2321 ASSERT(elm.cp_offset >= 0);
2322 if (elm.type == TextElement::ATOM) {
2323 return elm.cp_offset + elm.data.u_atom->data().length();
2324 } else {
2325 return elm.cp_offset + 1;
2326 }
2327}
2328
2329
ager@chromium.org381abbb2009-02-25 13:23:22 +00002330bool TextNode::SkipPass(int int_pass, bool ignore_case) {
2331 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
2332 if (ignore_case) {
2333 return pass == SIMPLE_CHARACTER_MATCH;
2334 } else {
2335 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
2336 }
2337}
2338
2339
ager@chromium.org8bb60582008-12-11 12:02:20 +00002340// This generates the code to match a text node. A text node can contain
2341// straight character sequences (possibly to be matched in a case-independent
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002342// way) and character classes. For efficiency we do not do this in a single
2343// pass from left to right. Instead we pass over the text node several times,
2344// emitting code for some character positions every time. See the comment on
2345// TextEmitPass for details.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002346void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org32912102009-01-16 10:38:43 +00002347 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002348 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002349 ASSERT(limit_result == CONTINUE);
2350
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002351 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
2352 compiler->SetRegExpTooBig();
2353 return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002354 }
2355
2356 if (compiler->ascii()) {
2357 int dummy = 0;
ager@chromium.org32912102009-01-16 10:38:43 +00002358 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002359 }
2360
2361 bool first_elt_done = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002362 int bound_checked_to = trace->cp_offset() - 1;
2363 bound_checked_to += trace->bound_checked_up_to();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002364
2365 // If a character is preloaded into the current character register then
2366 // check that now.
ager@chromium.org32912102009-01-16 10:38:43 +00002367 if (trace->characters_preloaded() == 1) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002368 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2369 if (!SkipPass(pass, compiler->ignore_case())) {
2370 TextEmitPass(compiler,
2371 static_cast<TextEmitPassType>(pass),
2372 true,
2373 trace,
2374 false,
2375 &bound_checked_to);
2376 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002377 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002378 first_elt_done = true;
2379 }
2380
ager@chromium.org381abbb2009-02-25 13:23:22 +00002381 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
2382 if (!SkipPass(pass, compiler->ignore_case())) {
2383 TextEmitPass(compiler,
2384 static_cast<TextEmitPassType>(pass),
2385 false,
2386 trace,
2387 first_elt_done,
2388 &bound_checked_to);
2389 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002390 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002391
ager@chromium.org32912102009-01-16 10:38:43 +00002392 Trace successor_trace(*trace);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002393 successor_trace.set_at_start(false);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002394 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002395 RecursionCheck rc(compiler);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002396 on_success()->Emit(compiler, &successor_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002397}
2398
2399
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002400void Trace::InvalidateCurrentCharacter() {
2401 characters_preloaded_ = 0;
2402}
2403
2404
2405void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002406 ASSERT(by > 0);
2407 // We don't have an instruction for shifting the current character register
2408 // down or for using a shifted value for anything so lets just forget that
2409 // we preloaded any characters into it.
2410 characters_preloaded_ = 0;
2411 // Adjust the offsets of the quick check performed information. This
2412 // information is used to find out what we already determined about the
2413 // characters by means of mask and compare.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002414 quick_check_performed_.Advance(by, compiler->ascii());
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002415 cp_offset_ += by;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002416 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
2417 compiler->SetRegExpTooBig();
2418 cp_offset_ = 0;
2419 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002420 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002421}
2422
2423
2424void TextNode::MakeCaseIndependent() {
2425 int element_count = elms_->length();
2426 for (int i = 0; i < element_count; i++) {
2427 TextElement elm = elms_->at(i);
2428 if (elm.type == TextElement::CHAR_CLASS) {
2429 RegExpCharacterClass* cc = elm.data.u_char_class;
2430 ZoneList<CharacterRange>* ranges = cc->ranges();
2431 int range_count = ranges->length();
2432 for (int i = 0; i < range_count; i++) {
2433 ranges->at(i).AddCaseEquivalents(ranges);
2434 }
2435 }
2436 }
2437}
2438
2439
ager@chromium.org8bb60582008-12-11 12:02:20 +00002440int TextNode::GreedyLoopTextLength() {
2441 TextElement elm = elms_->at(elms_->length() - 1);
2442 if (elm.type == TextElement::CHAR_CLASS) {
2443 return elm.cp_offset + 1;
2444 } else {
2445 return elm.cp_offset + elm.data.u_atom->data().length();
2446 }
2447}
2448
2449
2450// Finds the fixed match length of a sequence of nodes that goes from
2451// this alternative and back to this choice node. If there are variable
2452// length nodes or other complications in the way then return a sentinel
2453// value indicating that a greedy loop cannot be constructed.
2454int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) {
2455 int length = 0;
2456 RegExpNode* node = alternative->node();
2457 // Later we will generate code for all these text nodes using recursion
2458 // so we have to limit the max number.
2459 int recursion_depth = 0;
2460 while (node != this) {
2461 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
2462 return kNodeIsTooComplexForGreedyLoops;
2463 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002464 int node_length = node->GreedyLoopTextLength();
2465 if (node_length == kNodeIsTooComplexForGreedyLoops) {
2466 return kNodeIsTooComplexForGreedyLoops;
2467 }
2468 length += node_length;
2469 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
2470 node = seq_node->on_success();
2471 }
2472 return length;
2473}
2474
2475
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002476void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
2477 ASSERT_EQ(loop_node_, NULL);
2478 AddAlternative(alt);
2479 loop_node_ = alt.node();
2480}
2481
2482
2483void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
2484 ASSERT_EQ(continue_node_, NULL);
2485 AddAlternative(alt);
2486 continue_node_ = alt.node();
2487}
2488
2489
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002490void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002491 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002492 if (trace->stop_node() == this) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002493 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2494 ASSERT(text_length != kNodeIsTooComplexForGreedyLoops);
2495 // Update the counter-based backtracking info on the stack. This is an
2496 // optimization for greedy loops (see below).
ager@chromium.org32912102009-01-16 10:38:43 +00002497 ASSERT(trace->cp_offset() == text_length);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002498 macro_assembler->AdvanceCurrentPosition(text_length);
ager@chromium.org32912102009-01-16 10:38:43 +00002499 macro_assembler->GoTo(trace->loop_label());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002500 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002501 }
ager@chromium.org32912102009-01-16 10:38:43 +00002502 ASSERT(trace->stop_node() == NULL);
2503 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002504 trace->Flush(compiler, this);
2505 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002506 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002507 ChoiceNode::Emit(compiler, trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002508}
2509
2510
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002511int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002512 int preload_characters = EatsAtLeast(4, 0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002513#ifdef CAN_READ_UNALIGNED
2514 bool ascii = compiler->ascii();
2515 if (ascii) {
2516 if (preload_characters > 4) preload_characters = 4;
2517 // We can't preload 3 characters because there is no machine instruction
2518 // to do that. We can't just load 4 because we could be reading
2519 // beyond the end of the string, which could cause a memory fault.
2520 if (preload_characters == 3) preload_characters = 2;
2521 } else {
2522 if (preload_characters > 2) preload_characters = 2;
2523 }
2524#else
2525 if (preload_characters > 1) preload_characters = 1;
2526#endif
2527 return preload_characters;
2528}
2529
2530
2531// This class is used when generating the alternatives in a choice node. It
2532// records the way the alternative is being code generated.
2533class AlternativeGeneration: public Malloced {
2534 public:
2535 AlternativeGeneration()
2536 : possible_success(),
2537 expects_preload(false),
2538 after(),
2539 quick_check_details() { }
2540 Label possible_success;
2541 bool expects_preload;
2542 Label after;
2543 QuickCheckDetails quick_check_details;
2544};
2545
2546
2547// Creates a list of AlternativeGenerations. If the list has a reasonable
2548// size then it is on the stack, otherwise the excess is on the heap.
2549class AlternativeGenerationList {
2550 public:
2551 explicit AlternativeGenerationList(int count)
2552 : alt_gens_(count) {
2553 for (int i = 0; i < count && i < kAFew; i++) {
2554 alt_gens_.Add(a_few_alt_gens_ + i);
2555 }
2556 for (int i = kAFew; i < count; i++) {
2557 alt_gens_.Add(new AlternativeGeneration());
2558 }
2559 }
2560 ~AlternativeGenerationList() {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002561 for (int i = kAFew; i < alt_gens_.length(); i++) {
2562 delete alt_gens_[i];
2563 alt_gens_[i] = NULL;
2564 }
2565 }
2566
2567 AlternativeGeneration* at(int i) {
2568 return alt_gens_[i];
2569 }
2570 private:
2571 static const int kAFew = 10;
2572 ZoneList<AlternativeGeneration*> alt_gens_;
2573 AlternativeGeneration a_few_alt_gens_[kAFew];
2574};
2575
2576
2577/* Code generation for choice nodes.
2578 *
2579 * We generate quick checks that do a mask and compare to eliminate a
2580 * choice. If the quick check succeeds then it jumps to the continuation to
2581 * do slow checks and check subsequent nodes. If it fails (the common case)
2582 * it falls through to the next choice.
2583 *
2584 * Here is the desired flow graph. Nodes directly below each other imply
2585 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
2586 * 3 doesn't have a quick check so we have to call the slow check.
2587 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
2588 * regexp continuation is generated directly after the Sn node, up to the
2589 * next GoTo if we decide to reuse some already generated code. Some
2590 * nodes expect preload_characters to be preloaded into the current
2591 * character register. R nodes do this preloading. Vertices are marked
2592 * F for failures and S for success (possible success in the case of quick
2593 * nodes). L, V, < and > are used as arrow heads.
2594 *
2595 * ----------> R
2596 * |
2597 * V
2598 * Q1 -----> S1
2599 * | S /
2600 * F| /
2601 * | F/
2602 * | /
2603 * | R
2604 * | /
2605 * V L
2606 * Q2 -----> S2
2607 * | S /
2608 * F| /
2609 * | F/
2610 * | /
2611 * | R
2612 * | /
2613 * V L
2614 * S3
2615 * |
2616 * F|
2617 * |
2618 * R
2619 * |
2620 * backtrack V
2621 * <----------Q4
2622 * \ F |
2623 * \ |S
2624 * \ F V
2625 * \-----S4
2626 *
2627 * For greedy loops we reverse our expectation and expect to match rather
2628 * than fail. Therefore we want the loop code to look like this (U is the
2629 * unwind code that steps back in the greedy loop). The following alternatives
2630 * look the same as above.
2631 * _____
2632 * / \
2633 * V |
2634 * ----------> S1 |
2635 * /| |
2636 * / |S |
2637 * F/ \_____/
2638 * /
2639 * |<-----------
2640 * | \
2641 * V \
2642 * Q2 ---> S2 \
2643 * | S / |
2644 * F| / |
2645 * | F/ |
2646 * | / |
2647 * | R |
2648 * | / |
2649 * F VL |
2650 * <------U |
2651 * back |S |
2652 * \______________/
2653 */
2654
2655
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002656void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002657 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2658 int choice_count = alternatives_->length();
2659#ifdef DEBUG
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002660 for (int i = 0; i < choice_count - 1; i++) {
2661 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002662 ZoneList<Guard*>* guards = alternative.guards();
ager@chromium.org8bb60582008-12-11 12:02:20 +00002663 int guard_count = (guards == NULL) ? 0 : guards->length();
2664 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002665 ASSERT(!trace->mentions_reg(guards->at(j)->reg()));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002666 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002667 }
2668#endif
2669
ager@chromium.org32912102009-01-16 10:38:43 +00002670 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002671 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002672 ASSERT(limit_result == CONTINUE);
2673
ager@chromium.org381abbb2009-02-25 13:23:22 +00002674 int new_flush_budget = trace->flush_budget() / choice_count;
2675 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
2676 trace->Flush(compiler, this);
2677 return;
2678 }
2679
ager@chromium.org8bb60582008-12-11 12:02:20 +00002680 RecursionCheck rc(compiler);
2681
ager@chromium.org32912102009-01-16 10:38:43 +00002682 Trace* current_trace = trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002683
2684 int text_length = GreedyLoopTextLength(&(alternatives_->at(0)));
2685 bool greedy_loop = false;
2686 Label greedy_loop_label;
ager@chromium.org32912102009-01-16 10:38:43 +00002687 Trace counter_backtrack_trace;
2688 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002689 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
2690
ager@chromium.org8bb60582008-12-11 12:02:20 +00002691 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
2692 // Here we have special handling for greedy loops containing only text nodes
2693 // and other simple nodes. These are handled by pushing the current
2694 // position on the stack and then incrementing the current position each
2695 // time around the switch. On backtrack we decrement the current position
2696 // and check it against the pushed value. This avoids pushing backtrack
2697 // information for each iteration of the loop, which could take up a lot of
2698 // space.
2699 greedy_loop = true;
ager@chromium.org32912102009-01-16 10:38:43 +00002700 ASSERT(trace->stop_node() == NULL);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002701 macro_assembler->PushCurrentPosition();
ager@chromium.org32912102009-01-16 10:38:43 +00002702 current_trace = &counter_backtrack_trace;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002703 Label greedy_match_failed;
ager@chromium.org32912102009-01-16 10:38:43 +00002704 Trace greedy_match_trace;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002705 if (not_at_start()) greedy_match_trace.set_at_start(false);
ager@chromium.org32912102009-01-16 10:38:43 +00002706 greedy_match_trace.set_backtrack(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002707 Label loop_label;
2708 macro_assembler->Bind(&loop_label);
ager@chromium.org32912102009-01-16 10:38:43 +00002709 greedy_match_trace.set_stop_node(this);
2710 greedy_match_trace.set_loop_label(&loop_label);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002711 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002712 macro_assembler->Bind(&greedy_match_failed);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002713 }
2714
2715 Label second_choice; // For use in greedy matches.
2716 macro_assembler->Bind(&second_choice);
2717
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002718 int first_normal_choice = greedy_loop ? 1 : 0;
2719
2720 int preload_characters = CalculatePreloadCharacters(compiler);
2721 bool preload_is_current =
ager@chromium.org32912102009-01-16 10:38:43 +00002722 (current_trace->characters_preloaded() == preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002723 bool preload_has_checked_bounds = preload_is_current;
2724
2725 AlternativeGenerationList alt_gens(choice_count);
2726
ager@chromium.org8bb60582008-12-11 12:02:20 +00002727 // For now we just call all choices one after the other. The idea ultimately
2728 // is to use the Dispatch table to try only the relevant ones.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002729 for (int i = first_normal_choice; i < choice_count; i++) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00002730 GuardedAlternative alternative = alternatives_->at(i);
ager@chromium.org32912102009-01-16 10:38:43 +00002731 AlternativeGeneration* alt_gen = alt_gens.at(i);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002732 alt_gen->quick_check_details.set_characters(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002733 ZoneList<Guard*>* guards = alternative.guards();
2734 int guard_count = (guards == NULL) ? 0 : guards->length();
ager@chromium.org32912102009-01-16 10:38:43 +00002735 Trace new_trace(*current_trace);
2736 new_trace.set_characters_preloaded(preload_is_current ?
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002737 preload_characters :
2738 0);
2739 if (preload_has_checked_bounds) {
ager@chromium.org32912102009-01-16 10:38:43 +00002740 new_trace.set_bound_checked_up_to(preload_characters);
ager@chromium.org8bb60582008-12-11 12:02:20 +00002741 }
ager@chromium.org32912102009-01-16 10:38:43 +00002742 new_trace.quick_check_performed()->Clear();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002743 if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002744 alt_gen->expects_preload = preload_is_current;
2745 bool generate_full_check_inline = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002746 if (FLAG_regexp_optimization &&
iposva@chromium.org245aa852009-02-10 00:49:54 +00002747 try_to_emit_quick_check_for_alternative(i) &&
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002748 alternative.node()->EmitQuickCheck(compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002749 &new_trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002750 preload_has_checked_bounds,
2751 &alt_gen->possible_success,
2752 &alt_gen->quick_check_details,
2753 i < choice_count - 1)) {
2754 // Quick check was generated for this choice.
2755 preload_is_current = true;
2756 preload_has_checked_bounds = true;
2757 // On the last choice in the ChoiceNode we generated the quick
2758 // check to fall through on possible success. So now we need to
2759 // generate the full check inline.
2760 if (i == choice_count - 1) {
2761 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002762 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
2763 new_trace.set_characters_preloaded(preload_characters);
2764 new_trace.set_bound_checked_up_to(preload_characters);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002765 generate_full_check_inline = true;
2766 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002767 } else if (alt_gen->quick_check_details.cannot_match()) {
2768 if (i == choice_count - 1 && !greedy_loop) {
2769 macro_assembler->GoTo(trace->backtrack());
2770 }
2771 continue;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002772 } else {
2773 // No quick check was generated. Put the full code here.
2774 // If this is not the first choice then there could be slow checks from
2775 // previous cases that go here when they fail. There's no reason to
2776 // insist that they preload characters since the slow check we are about
2777 // to generate probably can't use it.
2778 if (i != first_normal_choice) {
2779 alt_gen->expects_preload = false;
ager@chromium.org32912102009-01-16 10:38:43 +00002780 new_trace.set_characters_preloaded(0);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002781 }
2782 if (i < choice_count - 1) {
ager@chromium.org32912102009-01-16 10:38:43 +00002783 new_trace.set_backtrack(&alt_gen->after);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002784 }
2785 generate_full_check_inline = true;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002786 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002787 if (generate_full_check_inline) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002788 if (new_trace.actions() != NULL) {
2789 new_trace.set_flush_budget(new_flush_budget);
2790 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002791 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002792 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002793 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002794 alternative.node()->Emit(compiler, &new_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002795 preload_is_current = false;
2796 }
2797 macro_assembler->Bind(&alt_gen->after);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002798 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002799 if (greedy_loop) {
2800 macro_assembler->Bind(&greedy_loop_label);
2801 // If we have unwound to the bottom then backtrack.
ager@chromium.org32912102009-01-16 10:38:43 +00002802 macro_assembler->CheckGreedyLoop(trace->backtrack());
ager@chromium.org8bb60582008-12-11 12:02:20 +00002803 // Otherwise try the second priority at an earlier position.
2804 macro_assembler->AdvanceCurrentPosition(-text_length);
2805 macro_assembler->GoTo(&second_choice);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002806 }
ager@chromium.org381abbb2009-02-25 13:23:22 +00002807
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002808 // At this point we need to generate slow checks for the alternatives where
2809 // the quick check was inlined. We can recognize these because the associated
2810 // label was bound.
2811 for (int i = first_normal_choice; i < choice_count - 1; i++) {
2812 AlternativeGeneration* alt_gen = alt_gens.at(i);
ager@chromium.org381abbb2009-02-25 13:23:22 +00002813 Trace new_trace(*current_trace);
2814 // If there are actions to be flushed we have to limit how many times
2815 // they are flushed. Take the budget of the parent trace and distribute
2816 // it fairly amongst the children.
2817 if (new_trace.actions() != NULL) {
2818 new_trace.set_flush_budget(new_flush_budget);
2819 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002820 EmitOutOfLineContinuation(compiler,
ager@chromium.org381abbb2009-02-25 13:23:22 +00002821 &new_trace,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002822 alternatives_->at(i),
2823 alt_gen,
2824 preload_characters,
2825 alt_gens.at(i + 1)->expects_preload);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002826 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002827}
2828
2829
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002830void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
ager@chromium.org32912102009-01-16 10:38:43 +00002831 Trace* trace,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002832 GuardedAlternative alternative,
2833 AlternativeGeneration* alt_gen,
2834 int preload_characters,
2835 bool next_expects_preload) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002836 if (!alt_gen->possible_success.is_linked()) return;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002837
2838 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2839 macro_assembler->Bind(&alt_gen->possible_success);
ager@chromium.org32912102009-01-16 10:38:43 +00002840 Trace out_of_line_trace(*trace);
2841 out_of_line_trace.set_characters_preloaded(preload_characters);
2842 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
iposva@chromium.org245aa852009-02-10 00:49:54 +00002843 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002844 ZoneList<Guard*>* guards = alternative.guards();
2845 int guard_count = (guards == NULL) ? 0 : guards->length();
2846 if (next_expects_preload) {
2847 Label reload_current_char;
ager@chromium.org32912102009-01-16 10:38:43 +00002848 out_of_line_trace.set_backtrack(&reload_current_char);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002849 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002850 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002851 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002852 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002853 macro_assembler->Bind(&reload_current_char);
2854 // Reload the current character, since the next quick check expects that.
2855 // We don't need to check bounds here because we only get into this
2856 // code through a quick check which already did the checked load.
ager@chromium.org32912102009-01-16 10:38:43 +00002857 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002858 NULL,
2859 false,
2860 preload_characters);
2861 macro_assembler->GoTo(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002862 } else {
ager@chromium.org32912102009-01-16 10:38:43 +00002863 out_of_line_trace.set_backtrack(&(alt_gen->after));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002864 for (int j = 0; j < guard_count; j++) {
ager@chromium.org32912102009-01-16 10:38:43 +00002865 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002866 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002867 alternative.node()->Emit(compiler, &out_of_line_trace);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002868 }
2869}
2870
2871
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002872void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002873 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002874 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002875 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002876 ASSERT(limit_result == CONTINUE);
2877
2878 RecursionCheck rc(compiler);
2879
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002880 switch (type_) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002881 case STORE_POSITION: {
ager@chromium.org32912102009-01-16 10:38:43 +00002882 Trace::DeferredCapture
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002883 new_capture(data_.u_position_register.reg,
2884 data_.u_position_register.is_capture,
2885 trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002886 Trace new_trace = *trace;
2887 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002888 on_success()->Emit(compiler, &new_trace);
2889 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002890 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00002891 case INCREMENT_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002892 Trace::DeferredIncrementRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002893 new_increment(data_.u_increment_register.reg);
ager@chromium.org32912102009-01-16 10:38:43 +00002894 Trace new_trace = *trace;
2895 new_trace.add_action(&new_increment);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002896 on_success()->Emit(compiler, &new_trace);
2897 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002898 }
2899 case SET_REGISTER: {
ager@chromium.org32912102009-01-16 10:38:43 +00002900 Trace::DeferredSetRegister
ager@chromium.org8bb60582008-12-11 12:02:20 +00002901 new_set(data_.u_store_register.reg, data_.u_store_register.value);
ager@chromium.org32912102009-01-16 10:38:43 +00002902 Trace new_trace = *trace;
2903 new_trace.add_action(&new_set);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002904 on_success()->Emit(compiler, &new_trace);
2905 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002906 }
2907 case CLEAR_CAPTURES: {
2908 Trace::DeferredClearCaptures
2909 new_capture(Interval(data_.u_clear_captures.range_from,
2910 data_.u_clear_captures.range_to));
2911 Trace new_trace = *trace;
2912 new_trace.add_action(&new_capture);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002913 on_success()->Emit(compiler, &new_trace);
2914 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002915 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002916 case BEGIN_SUBMATCH:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002917 if (!trace->is_trivial()) {
2918 trace->Flush(compiler, this);
2919 } else {
2920 assembler->WriteCurrentPositionToRegister(
2921 data_.u_submatch.current_position_register, 0);
2922 assembler->WriteStackPointerToRegister(
2923 data_.u_submatch.stack_pointer_register);
2924 on_success()->Emit(compiler, trace);
2925 }
2926 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002927 case EMPTY_MATCH_CHECK: {
2928 int start_pos_reg = data_.u_empty_match_check.start_register;
2929 int stored_pos = 0;
2930 int rep_reg = data_.u_empty_match_check.repetition_register;
2931 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
2932 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
2933 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
2934 // If we know we haven't advanced and there is no minimum we
2935 // can just backtrack immediately.
2936 assembler->GoTo(trace->backtrack());
ager@chromium.org32912102009-01-16 10:38:43 +00002937 } else if (know_dist && stored_pos < trace->cp_offset()) {
2938 // If we know we've advanced we can generate the continuation
2939 // immediately.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002940 on_success()->Emit(compiler, trace);
2941 } else if (!trace->is_trivial()) {
2942 trace->Flush(compiler, this);
2943 } else {
2944 Label skip_empty_check;
2945 // If we have a minimum number of repetitions we check the current
2946 // number first and skip the empty check if it's not enough.
2947 if (has_minimum) {
2948 int limit = data_.u_empty_match_check.repetition_limit;
2949 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
2950 }
2951 // If the match is empty we bail out, otherwise we fall through
2952 // to the on-success continuation.
2953 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
2954 trace->backtrack());
2955 assembler->Bind(&skip_empty_check);
2956 on_success()->Emit(compiler, trace);
ager@chromium.org32912102009-01-16 10:38:43 +00002957 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002958 break;
ager@chromium.org32912102009-01-16 10:38:43 +00002959 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002960 case POSITIVE_SUBMATCH_SUCCESS: {
2961 if (!trace->is_trivial()) {
2962 trace->Flush(compiler, this);
2963 return;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002964 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002965 assembler->ReadCurrentPositionFromRegister(
ager@chromium.org8bb60582008-12-11 12:02:20 +00002966 data_.u_submatch.current_position_register);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002967 assembler->ReadStackPointerFromRegister(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002968 data_.u_submatch.stack_pointer_register);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002969 int clear_register_count = data_.u_submatch.clear_register_count;
2970 if (clear_register_count == 0) {
2971 on_success()->Emit(compiler, trace);
2972 return;
2973 }
2974 int clear_registers_from = data_.u_submatch.clear_register_from;
2975 Label clear_registers_backtrack;
2976 Trace new_trace = *trace;
2977 new_trace.set_backtrack(&clear_registers_backtrack);
2978 on_success()->Emit(compiler, &new_trace);
2979
2980 assembler->Bind(&clear_registers_backtrack);
2981 int clear_registers_to = clear_registers_from + clear_register_count - 1;
2982 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
2983
2984 ASSERT(trace->backtrack() == NULL);
2985 assembler->Backtrack();
2986 return;
2987 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002988 default:
2989 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002990 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002991}
2992
2993
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002994void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002995 RegExpMacroAssembler* assembler = compiler->macro_assembler();
ager@chromium.org32912102009-01-16 10:38:43 +00002996 if (!trace->is_trivial()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002997 trace->Flush(compiler, this);
2998 return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00002999 }
3000
ager@chromium.org32912102009-01-16 10:38:43 +00003001 LimitResult limit_result = LimitVersions(compiler, trace);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003002 if (limit_result == DONE) return;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003003 ASSERT(limit_result == CONTINUE);
3004
3005 RecursionCheck rc(compiler);
3006
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003007 ASSERT_EQ(start_reg_ + 1, end_reg_);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003008 if (compiler->ignore_case()) {
3009 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
3010 trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003011 } else {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003012 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003013 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003014 on_success()->Emit(compiler, trace);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003015}
3016
3017
3018// -------------------------------------------------------------------
3019// Dot/dotty output
3020
3021
3022#ifdef DEBUG
3023
3024
3025class DotPrinter: public NodeVisitor {
3026 public:
3027 explicit DotPrinter(bool ignore_case)
3028 : ignore_case_(ignore_case),
3029 stream_(&alloc_) { }
3030 void PrintNode(const char* label, RegExpNode* node);
3031 void Visit(RegExpNode* node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003032 void PrintAttributes(RegExpNode* from);
3033 StringStream* stream() { return &stream_; }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003034 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003035#define DECLARE_VISIT(Type) \
3036 virtual void Visit##Type(Type##Node* that);
3037FOR_EACH_NODE_TYPE(DECLARE_VISIT)
3038#undef DECLARE_VISIT
3039 private:
3040 bool ignore_case_;
3041 HeapStringAllocator alloc_;
3042 StringStream stream_;
3043};
3044
3045
3046void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
3047 stream()->Add("digraph G {\n graph [label=\"");
3048 for (int i = 0; label[i]; i++) {
3049 switch (label[i]) {
3050 case '\\':
3051 stream()->Add("\\\\");
3052 break;
3053 case '"':
3054 stream()->Add("\"");
3055 break;
3056 default:
3057 stream()->Put(label[i]);
3058 break;
3059 }
3060 }
3061 stream()->Add("\"];\n");
3062 Visit(node);
3063 stream()->Add("}\n");
3064 printf("%s", *(stream()->ToCString()));
3065}
3066
3067
3068void DotPrinter::Visit(RegExpNode* node) {
3069 if (node->info()->visited) return;
3070 node->info()->visited = true;
3071 node->Accept(this);
3072}
3073
3074
3075void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003076 stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
3077 Visit(on_failure);
3078}
3079
3080
3081class TableEntryBodyPrinter {
3082 public:
3083 TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice)
3084 : stream_(stream), choice_(choice) { }
3085 void Call(uc16 from, DispatchTable::Entry entry) {
3086 OutSet* out_set = entry.out_set();
3087 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3088 if (out_set->Get(i)) {
3089 stream()->Add(" n%p:s%io%i -> n%p;\n",
3090 choice(),
3091 from,
3092 i,
3093 choice()->alternatives()->at(i).node());
3094 }
3095 }
3096 }
3097 private:
3098 StringStream* stream() { return stream_; }
3099 ChoiceNode* choice() { return choice_; }
3100 StringStream* stream_;
3101 ChoiceNode* choice_;
3102};
3103
3104
3105class TableEntryHeaderPrinter {
3106 public:
3107 explicit TableEntryHeaderPrinter(StringStream* stream)
3108 : first_(true), stream_(stream) { }
3109 void Call(uc16 from, DispatchTable::Entry entry) {
3110 if (first_) {
3111 first_ = false;
3112 } else {
3113 stream()->Add("|");
3114 }
3115 stream()->Add("{\\%k-\\%k|{", from, entry.to());
3116 OutSet* out_set = entry.out_set();
3117 int priority = 0;
3118 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3119 if (out_set->Get(i)) {
3120 if (priority > 0) stream()->Add("|");
3121 stream()->Add("<s%io%i> %i", from, i, priority);
3122 priority++;
3123 }
3124 }
3125 stream()->Add("}}");
3126 }
3127 private:
3128 bool first_;
3129 StringStream* stream() { return stream_; }
3130 StringStream* stream_;
3131};
3132
3133
3134class AttributePrinter {
3135 public:
3136 explicit AttributePrinter(DotPrinter* out)
3137 : out_(out), first_(true) { }
3138 void PrintSeparator() {
3139 if (first_) {
3140 first_ = false;
3141 } else {
3142 out_->stream()->Add("|");
3143 }
3144 }
3145 void PrintBit(const char* name, bool value) {
3146 if (!value) return;
3147 PrintSeparator();
3148 out_->stream()->Add("{%s}", name);
3149 }
3150 void PrintPositive(const char* name, int value) {
3151 if (value < 0) return;
3152 PrintSeparator();
3153 out_->stream()->Add("{%s|%x}", name, value);
3154 }
3155 private:
3156 DotPrinter* out_;
3157 bool first_;
3158};
3159
3160
3161void DotPrinter::PrintAttributes(RegExpNode* that) {
3162 stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, "
3163 "margin=0.1, fontsize=10, label=\"{",
3164 that);
3165 AttributePrinter printer(this);
3166 NodeInfo* info = that->info();
3167 printer.PrintBit("NI", info->follows_newline_interest);
3168 printer.PrintBit("WI", info->follows_word_interest);
3169 printer.PrintBit("SI", info->follows_start_interest);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003170 Label* label = that->label();
3171 if (label->is_bound())
3172 printer.PrintPositive("@", label->pos());
3173 stream()->Add("}\"];\n");
3174 stream()->Add(" a%p -> n%p [style=dashed, color=grey, "
3175 "arrowhead=none];\n", that, that);
3176}
3177
3178
3179static const bool kPrintDispatchTable = false;
3180void DotPrinter::VisitChoice(ChoiceNode* that) {
3181 if (kPrintDispatchTable) {
3182 stream()->Add(" n%p [shape=Mrecord, label=\"", that);
3183 TableEntryHeaderPrinter header_printer(stream());
3184 that->GetTable(ignore_case_)->ForEach(&header_printer);
3185 stream()->Add("\"]\n", that);
3186 PrintAttributes(that);
3187 TableEntryBodyPrinter body_printer(stream(), that);
3188 that->GetTable(ignore_case_)->ForEach(&body_printer);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003189 } else {
3190 stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that);
3191 for (int i = 0; i < that->alternatives()->length(); i++) {
3192 GuardedAlternative alt = that->alternatives()->at(i);
3193 stream()->Add(" n%p -> n%p;\n", that, alt.node());
3194 }
3195 }
3196 for (int i = 0; i < that->alternatives()->length(); i++) {
3197 GuardedAlternative alt = that->alternatives()->at(i);
3198 alt.node()->Accept(this);
3199 }
3200}
3201
3202
3203void DotPrinter::VisitText(TextNode* that) {
3204 stream()->Add(" n%p [label=\"", that);
3205 for (int i = 0; i < that->elements()->length(); i++) {
3206 if (i > 0) stream()->Add(" ");
3207 TextElement elm = that->elements()->at(i);
3208 switch (elm.type) {
3209 case TextElement::ATOM: {
3210 stream()->Add("'%w'", elm.data.u_atom->data());
3211 break;
3212 }
3213 case TextElement::CHAR_CLASS: {
3214 RegExpCharacterClass* node = elm.data.u_char_class;
3215 stream()->Add("[");
3216 if (node->is_negated())
3217 stream()->Add("^");
3218 for (int j = 0; j < node->ranges()->length(); j++) {
3219 CharacterRange range = node->ranges()->at(j);
3220 stream()->Add("%k-%k", range.from(), range.to());
3221 }
3222 stream()->Add("]");
3223 break;
3224 }
3225 default:
3226 UNREACHABLE();
3227 }
3228 }
3229 stream()->Add("\", shape=box, peripheries=2];\n");
3230 PrintAttributes(that);
3231 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3232 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003233}
3234
3235
3236void DotPrinter::VisitBackReference(BackReferenceNode* that) {
3237 stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n",
3238 that,
3239 that->start_register(),
3240 that->end_register());
3241 PrintAttributes(that);
3242 stream()->Add(" n%p -> n%p;\n", that, that->on_success());
3243 Visit(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003244}
3245
3246
3247void DotPrinter::VisitEnd(EndNode* that) {
3248 stream()->Add(" n%p [style=bold, shape=point];\n", that);
3249 PrintAttributes(that);
3250}
3251
3252
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003253void DotPrinter::VisitAssertion(AssertionNode* that) {
3254 stream()->Add(" n%p [", that);
3255 switch (that->type()) {
3256 case AssertionNode::AT_END:
3257 stream()->Add("label=\"$\", shape=septagon");
3258 break;
3259 case AssertionNode::AT_START:
3260 stream()->Add("label=\"^\", shape=septagon");
3261 break;
3262 case AssertionNode::AT_BOUNDARY:
3263 stream()->Add("label=\"\\b\", shape=septagon");
3264 break;
3265 case AssertionNode::AT_NON_BOUNDARY:
3266 stream()->Add("label=\"\\B\", shape=septagon");
3267 break;
3268 case AssertionNode::AFTER_NEWLINE:
3269 stream()->Add("label=\"(?<=\\n)\", shape=septagon");
3270 break;
3271 }
3272 stream()->Add("];\n");
3273 PrintAttributes(that);
3274 RegExpNode* successor = that->on_success();
3275 stream()->Add(" n%p -> n%p;\n", that, successor);
3276 Visit(successor);
3277}
3278
3279
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003280void DotPrinter::VisitAction(ActionNode* that) {
3281 stream()->Add(" n%p [", that);
3282 switch (that->type_) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003283 case ActionNode::SET_REGISTER:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003284 stream()->Add("label=\"$%i:=%i\", shape=octagon",
3285 that->data_.u_store_register.reg,
3286 that->data_.u_store_register.value);
3287 break;
3288 case ActionNode::INCREMENT_REGISTER:
3289 stream()->Add("label=\"$%i++\", shape=octagon",
3290 that->data_.u_increment_register.reg);
3291 break;
3292 case ActionNode::STORE_POSITION:
3293 stream()->Add("label=\"$%i:=$pos\", shape=octagon",
3294 that->data_.u_position_register.reg);
3295 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003296 case ActionNode::BEGIN_SUBMATCH:
3297 stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
3298 that->data_.u_submatch.current_position_register);
3299 break;
ager@chromium.org8bb60582008-12-11 12:02:20 +00003300 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003301 stream()->Add("label=\"escape\", shape=septagon");
3302 break;
ager@chromium.org32912102009-01-16 10:38:43 +00003303 case ActionNode::EMPTY_MATCH_CHECK:
3304 stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon",
3305 that->data_.u_empty_match_check.start_register,
3306 that->data_.u_empty_match_check.repetition_register,
3307 that->data_.u_empty_match_check.repetition_limit);
3308 break;
3309 case ActionNode::CLEAR_CAPTURES: {
3310 stream()->Add("label=\"clear $%i to $%i\", shape=septagon",
3311 that->data_.u_clear_captures.range_from,
3312 that->data_.u_clear_captures.range_to);
3313 break;
3314 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003315 }
3316 stream()->Add("];\n");
3317 PrintAttributes(that);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003318 RegExpNode* successor = that->on_success();
3319 stream()->Add(" n%p -> n%p;\n", that, successor);
3320 Visit(successor);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003321}
3322
3323
3324class DispatchTableDumper {
3325 public:
3326 explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { }
3327 void Call(uc16 key, DispatchTable::Entry entry);
3328 StringStream* stream() { return stream_; }
3329 private:
3330 StringStream* stream_;
3331};
3332
3333
3334void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
3335 stream()->Add("[%k-%k]: {", key, entry.to());
3336 OutSet* set = entry.out_set();
3337 bool first = true;
3338 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
3339 if (set->Get(i)) {
3340 if (first) {
3341 first = false;
3342 } else {
3343 stream()->Add(", ");
3344 }
3345 stream()->Add("%i", i);
3346 }
3347 }
3348 stream()->Add("}\n");
3349}
3350
3351
3352void DispatchTable::Dump() {
3353 HeapStringAllocator alloc;
3354 StringStream stream(&alloc);
3355 DispatchTableDumper dumper(&stream);
3356 tree()->ForEach(&dumper);
3357 OS::PrintError("%s", *stream.ToCString());
3358}
3359
3360
3361void RegExpEngine::DotPrint(const char* label,
3362 RegExpNode* node,
3363 bool ignore_case) {
3364 DotPrinter printer(ignore_case);
3365 printer.PrintNode(label, node);
3366}
3367
3368
3369#endif // DEBUG
3370
3371
3372// -------------------------------------------------------------------
3373// Tree to graph conversion
3374
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003375static const int kSpaceRangeCount = 20;
3376static const int kSpaceRangeAsciiCount = 4;
3377static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020,
3378 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A,
3379 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 };
3380
3381static const int kWordRangeCount = 8;
3382static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_',
3383 '_', 'a', 'z' };
3384
3385static const int kDigitRangeCount = 2;
3386static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' };
3387
3388static const int kLineTerminatorRangeCount = 6;
3389static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A,
3390 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 };
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003391
3392RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003393 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003394 ZoneList<TextElement>* elms = new ZoneList<TextElement>(1);
3395 elms->Add(TextElement::Atom(this));
ager@chromium.org8bb60582008-12-11 12:02:20 +00003396 return new TextNode(elms, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003397}
3398
3399
3400RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003401 RegExpNode* on_success) {
3402 return new TextNode(elements(), on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003403}
3404
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003405static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
3406 const uc16* special_class,
3407 int length) {
3408 ASSERT(ranges->length() != 0);
3409 ASSERT(length != 0);
3410 ASSERT(special_class[0] != 0);
3411 if (ranges->length() != (length >> 1) + 1) {
3412 return false;
3413 }
3414 CharacterRange range = ranges->at(0);
3415 if (range.from() != 0) {
3416 return false;
3417 }
3418 for (int i = 0; i < length; i += 2) {
3419 if (special_class[i] != (range.to() + 1)) {
3420 return false;
3421 }
3422 range = ranges->at((i >> 1) + 1);
3423 if (special_class[i+1] != range.from() - 1) {
3424 return false;
3425 }
3426 }
3427 if (range.to() != 0xffff) {
3428 return false;
3429 }
3430 return true;
3431}
3432
3433
3434static bool CompareRanges(ZoneList<CharacterRange>* ranges,
3435 const uc16* special_class,
3436 int length) {
3437 if (ranges->length() * 2 != length) {
3438 return false;
3439 }
3440 for (int i = 0; i < length; i += 2) {
3441 CharacterRange range = ranges->at(i >> 1);
3442 if (range.from() != special_class[i] || range.to() != special_class[i+1]) {
3443 return false;
3444 }
3445 }
3446 return true;
3447}
3448
3449
3450bool RegExpCharacterClass::is_standard() {
3451 // TODO(lrn): Remove need for this function, by not throwing away information
3452 // along the way.
3453 if (is_negated_) {
3454 return false;
3455 }
3456 if (set_.is_standard()) {
3457 return true;
3458 }
3459 if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3460 set_.set_standard_set_type('s');
3461 return true;
3462 }
3463 if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) {
3464 set_.set_standard_set_type('S');
3465 return true;
3466 }
3467 if (CompareInverseRanges(set_.ranges(),
3468 kLineTerminatorRanges,
3469 kLineTerminatorRangeCount)) {
3470 set_.set_standard_set_type('.');
3471 return true;
3472 }
3473 return false;
3474}
3475
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003476
3477RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003478 RegExpNode* on_success) {
3479 return new TextNode(this, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003480}
3481
3482
3483RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003484 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003485 ZoneList<RegExpTree*>* alternatives = this->alternatives();
3486 int length = alternatives->length();
ager@chromium.org8bb60582008-12-11 12:02:20 +00003487 ChoiceNode* result = new ChoiceNode(length);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003488 for (int i = 0; i < length; i++) {
3489 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003490 on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003491 result->AddAlternative(alternative);
3492 }
3493 return result;
3494}
3495
3496
3497RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003498 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003499 return ToNode(min(),
3500 max(),
3501 is_greedy(),
3502 body(),
3503 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003504 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003505}
3506
3507
3508RegExpNode* RegExpQuantifier::ToNode(int min,
3509 int max,
3510 bool is_greedy,
3511 RegExpTree* body,
3512 RegExpCompiler* compiler,
iposva@chromium.org245aa852009-02-10 00:49:54 +00003513 RegExpNode* on_success,
3514 bool not_at_start) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003515 // x{f, t} becomes this:
3516 //
3517 // (r++)<-.
3518 // | `
3519 // | (x)
3520 // v ^
3521 // (r=0)-->(?)---/ [if r < t]
3522 // |
3523 // [if r >= f] \----> ...
3524 //
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003525
3526 // 15.10.2.5 RepeatMatcher algorithm.
3527 // The parser has already eliminated the case where max is 0. In the case
3528 // where max_match is zero the parser has removed the quantifier if min was
3529 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
3530
3531 // If we know that we cannot match zero length then things are a little
3532 // simpler since we don't need to make the special zero length match check
3533 // from step 2.1. If the min and max are small we can unroll a little in
3534 // this case.
3535 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
3536 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
3537 if (max == 0) return on_success; // This can happen due to recursion.
ager@chromium.org32912102009-01-16 10:38:43 +00003538 bool body_can_be_empty = (body->min_match() == 0);
3539 int body_start_reg = RegExpCompiler::kNoRegister;
3540 Interval capture_registers = body->CaptureRegisters();
3541 bool needs_capture_clearing = !capture_registers.is_empty();
3542 if (body_can_be_empty) {
3543 body_start_reg = compiler->AllocateRegister();
ager@chromium.org381abbb2009-02-25 13:23:22 +00003544 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
ager@chromium.org32912102009-01-16 10:38:43 +00003545 // Only unroll if there are no captures and the body can't be
3546 // empty.
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003547 if (min > 0 && min <= kMaxUnrolledMinMatches) {
3548 int new_max = (max == kInfinity) ? max : max - min;
3549 // Recurse once to get the loop or optional matches after the fixed ones.
iposva@chromium.org245aa852009-02-10 00:49:54 +00003550 RegExpNode* answer = ToNode(
3551 0, new_max, is_greedy, body, compiler, on_success, true);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003552 // Unroll the forced matches from 0 to min. This can cause chains of
3553 // TextNodes (which the parser does not generate). These should be
3554 // combined if it turns out they hinder good code generation.
3555 for (int i = 0; i < min; i++) {
3556 answer = body->ToNode(compiler, answer);
3557 }
3558 return answer;
3559 }
3560 if (max <= kMaxUnrolledMaxMatches) {
3561 ASSERT(min == 0);
3562 // Unroll the optional matches up to max.
3563 RegExpNode* answer = on_success;
3564 for (int i = 0; i < max; i++) {
3565 ChoiceNode* alternation = new ChoiceNode(2);
3566 if (is_greedy) {
3567 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3568 answer)));
3569 alternation->AddAlternative(GuardedAlternative(on_success));
3570 } else {
3571 alternation->AddAlternative(GuardedAlternative(on_success));
3572 alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler,
3573 answer)));
3574 }
3575 answer = alternation;
iposva@chromium.org245aa852009-02-10 00:49:54 +00003576 if (not_at_start) alternation->set_not_at_start();
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003577 }
3578 return answer;
3579 }
3580 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003581 bool has_min = min > 0;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003582 bool has_max = max < RegExpTree::kInfinity;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003583 bool needs_counter = has_min || has_max;
ager@chromium.org32912102009-01-16 10:38:43 +00003584 int reg_ctr = needs_counter
3585 ? compiler->AllocateRegister()
3586 : RegExpCompiler::kNoRegister;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003587 LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0);
iposva@chromium.org245aa852009-02-10 00:49:54 +00003588 if (not_at_start) center->set_not_at_start();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003589 RegExpNode* loop_return = needs_counter
3590 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
3591 : static_cast<RegExpNode*>(center);
ager@chromium.org32912102009-01-16 10:38:43 +00003592 if (body_can_be_empty) {
3593 // If the body can be empty we need to check if it was and then
3594 // backtrack.
3595 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
3596 reg_ctr,
3597 min,
3598 loop_return);
3599 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003600 RegExpNode* body_node = body->ToNode(compiler, loop_return);
ager@chromium.org32912102009-01-16 10:38:43 +00003601 if (body_can_be_empty) {
3602 // If the body can be empty we need to store the start position
3603 // so we can bail out if it was empty.
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003604 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
ager@chromium.org32912102009-01-16 10:38:43 +00003605 }
3606 if (needs_capture_clearing) {
3607 // Before entering the body of this loop we need to clear captures.
3608 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
3609 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003610 GuardedAlternative body_alt(body_node);
3611 if (has_max) {
3612 Guard* body_guard = new Guard(reg_ctr, Guard::LT, max);
3613 body_alt.AddGuard(body_guard);
3614 }
3615 GuardedAlternative rest_alt(on_success);
3616 if (has_min) {
3617 Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min);
3618 rest_alt.AddGuard(rest_guard);
3619 }
3620 if (is_greedy) {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003621 center->AddLoopAlternative(body_alt);
3622 center->AddContinueAlternative(rest_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003623 } else {
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003624 center->AddContinueAlternative(rest_alt);
3625 center->AddLoopAlternative(body_alt);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003626 }
3627 if (needs_counter) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003628 return ActionNode::SetRegister(reg_ctr, 0, center);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003629 } else {
3630 return center;
3631 }
3632}
3633
3634
3635RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003636 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003637 NodeInfo info;
3638 switch (type()) {
3639 case START_OF_LINE:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003640 return AssertionNode::AfterNewline(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003641 case START_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003642 return AssertionNode::AtStart(on_success);
3643 case BOUNDARY:
3644 return AssertionNode::AtBoundary(on_success);
3645 case NON_BOUNDARY:
3646 return AssertionNode::AtNonBoundary(on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003647 case END_OF_INPUT:
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003648 return AssertionNode::AtEnd(on_success);
3649 case END_OF_LINE: {
3650 // Compile $ in multiline regexps as an alternation with a positive
3651 // lookahead in one side and an end-of-input on the other side.
3652 // We need two registers for the lookahead.
3653 int stack_pointer_register = compiler->AllocateRegister();
3654 int position_register = compiler->AllocateRegister();
3655 // The ChoiceNode to distinguish between a newline and end-of-input.
3656 ChoiceNode* result = new ChoiceNode(2);
3657 // Create a newline atom.
3658 ZoneList<CharacterRange>* newline_ranges =
3659 new ZoneList<CharacterRange>(3);
3660 CharacterRange::AddClassEscape('n', newline_ranges);
3661 RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n');
3662 TextNode* newline_matcher = new TextNode(
3663 newline_atom,
3664 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3665 position_register,
3666 0, // No captures inside.
3667 -1, // Ignored if no captures.
3668 on_success));
3669 // Create an end-of-input matcher.
3670 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
3671 stack_pointer_register,
3672 position_register,
3673 newline_matcher);
3674 // Add the two alternatives to the ChoiceNode.
3675 GuardedAlternative eol_alternative(end_of_line);
3676 result->AddAlternative(eol_alternative);
3677 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
3678 result->AddAlternative(end_alternative);
3679 return result;
3680 }
3681 default:
3682 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003683 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003684 return on_success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003685}
3686
3687
3688RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003689 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003690 return new BackReferenceNode(RegExpCapture::StartRegister(index()),
3691 RegExpCapture::EndRegister(index()),
ager@chromium.org8bb60582008-12-11 12:02:20 +00003692 on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003693}
3694
3695
3696RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003697 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003698 return on_success;
3699}
3700
3701
3702RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003703 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003704 int stack_pointer_register = compiler->AllocateRegister();
3705 int position_register = compiler->AllocateRegister();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003706
3707 const int registers_per_capture = 2;
3708 const int register_of_first_capture = 2;
3709 int register_count = capture_count_ * registers_per_capture;
3710 int register_start =
3711 register_of_first_capture + capture_from_ * registers_per_capture;
3712
ager@chromium.org8bb60582008-12-11 12:02:20 +00003713 RegExpNode* success;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003714 if (is_positive()) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003715 RegExpNode* node = ActionNode::BeginSubmatch(
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003716 stack_pointer_register,
3717 position_register,
3718 body()->ToNode(
3719 compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003720 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
3721 position_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003722 register_count,
3723 register_start,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003724 on_success)));
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003725 return node;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003726 } else {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003727 // We use a ChoiceNode for a negative lookahead because it has most of
3728 // the characteristics we need. It has the body of the lookahead as its
3729 // first alternative and the expression after the lookahead of the second
3730 // alternative. If the first alternative succeeds then the
3731 // NegativeSubmatchSuccess will unwind the stack including everything the
3732 // choice node set up and backtrack. If the first alternative fails then
3733 // the second alternative is tried, which is exactly the desired result
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003734 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
3735 // ChoiceNode that knows to ignore the first exit when calculating quick
3736 // checks.
ager@chromium.org8bb60582008-12-11 12:02:20 +00003737 GuardedAlternative body_alt(
3738 body()->ToNode(
3739 compiler,
3740 success = new NegativeSubmatchSuccess(stack_pointer_register,
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003741 position_register,
3742 register_count,
3743 register_start)));
3744 ChoiceNode* choice_node =
3745 new NegativeLookaheadChoiceNode(body_alt,
3746 GuardedAlternative(on_success));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003747 return ActionNode::BeginSubmatch(stack_pointer_register,
3748 position_register,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003749 choice_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003750 }
3751}
3752
3753
3754RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003755 RegExpNode* on_success) {
3756 return ToNode(body(), index(), compiler, on_success);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003757}
3758
3759
3760RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
3761 int index,
3762 RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003763 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003764 int start_reg = RegExpCapture::StartRegister(index);
3765 int end_reg = RegExpCapture::EndRegister(index);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003766 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003767 RegExpNode* body_node = body->ToNode(compiler, store_end);
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003768 return ActionNode::StorePosition(start_reg, true, body_node);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003769}
3770
3771
3772RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00003773 RegExpNode* on_success) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003774 ZoneList<RegExpTree*>* children = nodes();
3775 RegExpNode* current = on_success;
3776 for (int i = children->length() - 1; i >= 0; i--) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00003777 current = children->at(i)->ToNode(compiler, current);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003778 }
3779 return current;
3780}
3781
3782
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003783static void AddClass(const uc16* elmv,
3784 int elmc,
3785 ZoneList<CharacterRange>* ranges) {
3786 for (int i = 0; i < elmc; i += 2) {
3787 ASSERT(elmv[i] <= elmv[i + 1]);
3788 ranges->Add(CharacterRange(elmv[i], elmv[i + 1]));
3789 }
3790}
3791
3792
3793static void AddClassNegated(const uc16 *elmv,
3794 int elmc,
3795 ZoneList<CharacterRange>* ranges) {
3796 ASSERT(elmv[0] != 0x0000);
ager@chromium.org8bb60582008-12-11 12:02:20 +00003797 ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003798 uc16 last = 0x0000;
3799 for (int i = 0; i < elmc; i += 2) {
3800 ASSERT(last <= elmv[i] - 1);
3801 ASSERT(elmv[i] <= elmv[i + 1]);
3802 ranges->Add(CharacterRange(last, elmv[i] - 1));
3803 last = elmv[i + 1] + 1;
3804 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00003805 ranges->Add(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003806}
3807
3808
3809void CharacterRange::AddClassEscape(uc16 type,
3810 ZoneList<CharacterRange>* ranges) {
3811 switch (type) {
3812 case 's':
3813 AddClass(kSpaceRanges, kSpaceRangeCount, ranges);
3814 break;
3815 case 'S':
3816 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges);
3817 break;
3818 case 'w':
3819 AddClass(kWordRanges, kWordRangeCount, ranges);
3820 break;
3821 case 'W':
3822 AddClassNegated(kWordRanges, kWordRangeCount, ranges);
3823 break;
3824 case 'd':
3825 AddClass(kDigitRanges, kDigitRangeCount, ranges);
3826 break;
3827 case 'D':
3828 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges);
3829 break;
3830 case '.':
3831 AddClassNegated(kLineTerminatorRanges,
3832 kLineTerminatorRangeCount,
3833 ranges);
3834 break;
3835 // This is not a character range as defined by the spec but a
3836 // convenient shorthand for a character class that matches any
3837 // character.
3838 case '*':
3839 ranges->Add(CharacterRange::Everything());
3840 break;
ager@chromium.orgddb913d2009-01-27 10:01:48 +00003841 // This is the set of characters matched by the $ and ^ symbols
3842 // in multiline mode.
3843 case 'n':
3844 AddClass(kLineTerminatorRanges,
3845 kLineTerminatorRangeCount,
3846 ranges);
3847 break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003848 default:
3849 UNREACHABLE();
3850 }
3851}
3852
3853
3854Vector<const uc16> CharacterRange::GetWordBounds() {
3855 return Vector<const uc16>(kWordRanges, kWordRangeCount);
3856}
3857
3858
3859class CharacterRangeSplitter {
3860 public:
3861 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
3862 ZoneList<CharacterRange>** excluded)
3863 : included_(included),
3864 excluded_(excluded) { }
3865 void Call(uc16 from, DispatchTable::Entry entry);
3866
3867 static const int kInBase = 0;
3868 static const int kInOverlay = 1;
3869
3870 private:
3871 ZoneList<CharacterRange>** included_;
3872 ZoneList<CharacterRange>** excluded_;
3873};
3874
3875
3876void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
3877 if (!entry.out_set()->Get(kInBase)) return;
3878 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
3879 ? included_
3880 : excluded_;
3881 if (*target == NULL) *target = new ZoneList<CharacterRange>(2);
3882 (*target)->Add(CharacterRange(entry.from(), entry.to()));
3883}
3884
3885
3886void CharacterRange::Split(ZoneList<CharacterRange>* base,
3887 Vector<const uc16> overlay,
3888 ZoneList<CharacterRange>** included,
3889 ZoneList<CharacterRange>** excluded) {
3890 ASSERT_EQ(NULL, *included);
3891 ASSERT_EQ(NULL, *excluded);
3892 DispatchTable table;
3893 for (int i = 0; i < base->length(); i++)
3894 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase);
3895 for (int i = 0; i < overlay.length(); i += 2) {
3896 table.AddRange(CharacterRange(overlay[i], overlay[i+1]),
3897 CharacterRangeSplitter::kInOverlay);
3898 }
3899 CharacterRangeSplitter callback(included, excluded);
3900 table.ForEach(&callback);
3901}
3902
3903
3904void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges) {
3905 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
3906 if (IsSingleton()) {
3907 // If this is a singleton we just expand the one character.
3908 int length = uncanonicalize.get(from(), '\0', chars);
3909 for (int i = 0; i < length; i++) {
3910 uc32 chr = chars[i];
3911 if (chr != from()) {
3912 ranges->Add(CharacterRange::Singleton(chars[i]));
3913 }
3914 }
3915 } else if (from() <= kRangeCanonicalizeMax &&
3916 to() <= kRangeCanonicalizeMax) {
3917 // If this is a range we expand the characters block by block,
3918 // expanding contiguous subranges (blocks) one at a time.
3919 // The approach is as follows. For a given start character we
3920 // look up the block that contains it, for instance 'a' if the
3921 // start character is 'c'. A block is characterized by the property
3922 // that all characters uncanonicalize in the same way as the first
3923 // element, except that each entry in the result is incremented
3924 // by the distance from the first element. So a-z is a block
3925 // because 'a' uncanonicalizes to ['a', 'A'] and the k'th letter
3926 // uncanonicalizes to ['a' + k, 'A' + k].
3927 // Once we've found the start point we look up its uncanonicalization
3928 // and produce a range for each element. For instance for [c-f]
3929 // we look up ['a', 'A'] and produce [c-f] and [C-F]. We then only
3930 // add a range if it is not already contained in the input, so [c-f]
3931 // will be skipped but [C-F] will be added. If this range is not
3932 // completely contained in a block we do this for all the blocks
3933 // covered by the range.
3934 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
3935 // First, look up the block that contains the 'from' character.
3936 int length = canonrange.get(from(), '\0', range);
3937 if (length == 0) {
3938 range[0] = from();
3939 } else {
3940 ASSERT_EQ(1, length);
3941 }
3942 int pos = from();
3943 // The start of the current block. Note that except for the first
3944 // iteration 'start' is always equal to 'pos'.
3945 int start;
3946 // If it is not the start point of a block the entry contains the
3947 // offset of the character from the start point.
3948 if ((range[0] & kStartMarker) == 0) {
3949 start = pos - range[0];
3950 } else {
3951 start = pos;
3952 }
3953 // Then we add the ranges on at a time, incrementing the current
3954 // position to be after the last block each time. The position
3955 // always points to the start of a block.
3956 while (pos < to()) {
3957 length = canonrange.get(start, '\0', range);
3958 if (length == 0) {
3959 range[0] = start;
3960 } else {
3961 ASSERT_EQ(1, length);
3962 }
3963 ASSERT((range[0] & kStartMarker) != 0);
3964 // The start point of a block contains the distance to the end
3965 // of the range.
3966 int block_end = start + (range[0] & kPayloadMask) - 1;
3967 int end = (block_end > to()) ? to() : block_end;
3968 length = uncanonicalize.get(start, '\0', range);
3969 for (int i = 0; i < length; i++) {
3970 uc32 c = range[i];
3971 uc16 range_from = c + (pos - start);
3972 uc16 range_to = c + (end - start);
3973 if (!(from() <= range_from && range_to <= to())) {
3974 ranges->Add(CharacterRange(range_from, range_to));
3975 }
3976 }
3977 start = pos = block_end + 1;
3978 }
3979 } else {
3980 // TODO(plesner) when we've fixed the 2^11 bug in unibrow.
3981 }
3982}
3983
3984
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003985ZoneList<CharacterRange>* CharacterSet::ranges() {
3986 if (ranges_ == NULL) {
3987 ranges_ = new ZoneList<CharacterRange>(2);
3988 CharacterRange::AddClassEscape(standard_set_type_, ranges_);
3989 }
3990 return ranges_;
3991}
3992
3993
3994
ager@chromium.orga74f0da2008-12-03 16:05:52 +00003995// -------------------------------------------------------------------
3996// Interest propagation
3997
3998
3999RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) {
4000 for (int i = 0; i < siblings_.length(); i++) {
4001 RegExpNode* sibling = siblings_.Get(i);
4002 if (sibling->info()->Matches(info))
4003 return sibling;
4004 }
4005 return NULL;
4006}
4007
4008
4009RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
4010 ASSERT_EQ(false, *cloned);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004011 siblings_.Ensure(this);
4012 RegExpNode* result = TryGetSibling(info);
4013 if (result != NULL) return result;
4014 result = this->Clone();
4015 NodeInfo* new_info = result->info();
4016 new_info->ResetCompilationState();
4017 new_info->AddFromPreceding(info);
4018 AddSibling(result);
4019 *cloned = true;
4020 return result;
4021}
4022
4023
4024template <class C>
4025static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) {
4026 NodeInfo full_info(*node->info());
4027 full_info.AddFromPreceding(info);
4028 bool cloned = false;
4029 return RegExpNode::EnsureSibling(node, &full_info, &cloned);
4030}
4031
4032
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004033// -------------------------------------------------------------------
4034// Splay tree
4035
4036
4037OutSet* OutSet::Extend(unsigned value) {
4038 if (Get(value))
4039 return this;
4040 if (successors() != NULL) {
4041 for (int i = 0; i < successors()->length(); i++) {
4042 OutSet* successor = successors()->at(i);
4043 if (successor->Get(value))
4044 return successor;
4045 }
4046 } else {
4047 successors_ = new ZoneList<OutSet*>(2);
4048 }
4049 OutSet* result = new OutSet(first_, remaining_);
4050 result->Set(value);
4051 successors()->Add(result);
4052 return result;
4053}
4054
4055
4056void OutSet::Set(unsigned value) {
4057 if (value < kFirstLimit) {
4058 first_ |= (1 << value);
4059 } else {
4060 if (remaining_ == NULL)
4061 remaining_ = new ZoneList<unsigned>(1);
4062 if (remaining_->is_empty() || !remaining_->Contains(value))
4063 remaining_->Add(value);
4064 }
4065}
4066
4067
4068bool OutSet::Get(unsigned value) {
4069 if (value < kFirstLimit) {
4070 return (first_ & (1 << value)) != 0;
4071 } else if (remaining_ == NULL) {
4072 return false;
4073 } else {
4074 return remaining_->Contains(value);
4075 }
4076}
4077
4078
4079const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
4080const DispatchTable::Entry DispatchTable::Config::kNoValue;
4081
4082
4083void DispatchTable::AddRange(CharacterRange full_range, int value) {
4084 CharacterRange current = full_range;
4085 if (tree()->is_empty()) {
4086 // If this is the first range we just insert into the table.
4087 ZoneSplayTree<Config>::Locator loc;
4088 ASSERT_RESULT(tree()->Insert(current.from(), &loc));
4089 loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value)));
4090 return;
4091 }
4092 // First see if there is a range to the left of this one that
4093 // overlaps.
4094 ZoneSplayTree<Config>::Locator loc;
4095 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
4096 Entry* entry = &loc.value();
4097 // If we've found a range that overlaps with this one, and it
4098 // starts strictly to the left of this one, we have to fix it
4099 // because the following code only handles ranges that start on
4100 // or after the start point of the range we're adding.
4101 if (entry->from() < current.from() && entry->to() >= current.from()) {
4102 // Snap the overlapping range in half around the start point of
4103 // the range we're adding.
4104 CharacterRange left(entry->from(), current.from() - 1);
4105 CharacterRange right(current.from(), entry->to());
4106 // The left part of the overlapping range doesn't overlap.
4107 // Truncate the whole entry to be just the left part.
4108 entry->set_to(left.to());
4109 // The right part is the one that overlaps. We add this part
4110 // to the map and let the next step deal with merging it with
4111 // the range we're adding.
4112 ZoneSplayTree<Config>::Locator loc;
4113 ASSERT_RESULT(tree()->Insert(right.from(), &loc));
4114 loc.set_value(Entry(right.from(),
4115 right.to(),
4116 entry->out_set()));
4117 }
4118 }
4119 while (current.is_valid()) {
4120 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
4121 (loc.value().from() <= current.to()) &&
4122 (loc.value().to() >= current.from())) {
4123 Entry* entry = &loc.value();
4124 // We have overlap. If there is space between the start point of
4125 // the range we're adding and where the overlapping range starts
4126 // then we have to add a range covering just that space.
4127 if (current.from() < entry->from()) {
4128 ZoneSplayTree<Config>::Locator ins;
4129 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4130 ins.set_value(Entry(current.from(),
4131 entry->from() - 1,
4132 empty()->Extend(value)));
4133 current.set_from(entry->from());
4134 }
4135 ASSERT_EQ(current.from(), entry->from());
4136 // If the overlapping range extends beyond the one we want to add
4137 // we have to snap the right part off and add it separately.
4138 if (entry->to() > current.to()) {
4139 ZoneSplayTree<Config>::Locator ins;
4140 ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins));
4141 ins.set_value(Entry(current.to() + 1,
4142 entry->to(),
4143 entry->out_set()));
4144 entry->set_to(current.to());
4145 }
4146 ASSERT(entry->to() <= current.to());
4147 // The overlapping range is now completely contained by the range
4148 // we're adding so we can just update it and move the start point
4149 // of the range we're adding just past it.
4150 entry->AddValue(value);
4151 // Bail out if the last interval ended at 0xFFFF since otherwise
4152 // adding 1 will wrap around to 0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004153 if (entry->to() == String::kMaxUC16CharCode)
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004154 break;
4155 ASSERT(entry->to() + 1 > current.from());
4156 current.set_from(entry->to() + 1);
4157 } else {
4158 // There is no overlap so we can just add the range
4159 ZoneSplayTree<Config>::Locator ins;
4160 ASSERT_RESULT(tree()->Insert(current.from(), &ins));
4161 ins.set_value(Entry(current.from(),
4162 current.to(),
4163 empty()->Extend(value)));
4164 break;
4165 }
4166 }
4167}
4168
4169
4170OutSet* DispatchTable::Get(uc16 value) {
4171 ZoneSplayTree<Config>::Locator loc;
4172 if (!tree()->FindGreatestLessThan(value, &loc))
4173 return empty();
4174 Entry* entry = &loc.value();
4175 if (value <= entry->to())
4176 return entry->out_set();
4177 else
4178 return empty();
4179}
4180
4181
4182// -------------------------------------------------------------------
4183// Analysis
4184
4185
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004186void Analysis::EnsureAnalyzed(RegExpNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004187 if (that->info()->been_analyzed || that->info()->being_analyzed)
4188 return;
4189 that->info()->being_analyzed = true;
4190 that->Accept(this);
4191 that->info()->being_analyzed = false;
4192 that->info()->been_analyzed = true;
4193}
4194
4195
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004196void Analysis::VisitEnd(EndNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004197 // nothing to do
4198}
4199
4200
ager@chromium.org8bb60582008-12-11 12:02:20 +00004201void TextNode::CalculateOffsets() {
4202 int element_count = elements()->length();
4203 // Set up the offsets of the elements relative to the start. This is a fixed
4204 // quantity since a TextNode can only contain fixed-width things.
4205 int cp_offset = 0;
4206 for (int i = 0; i < element_count; i++) {
4207 TextElement& elm = elements()->at(i);
4208 elm.cp_offset = cp_offset;
4209 if (elm.type == TextElement::ATOM) {
4210 cp_offset += elm.data.u_atom->data().length();
4211 } else {
4212 cp_offset++;
4213 Vector<const uc16> quarks = elm.data.u_atom->data();
4214 }
4215 }
4216}
4217
4218
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004219void Analysis::VisitText(TextNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004220 if (ignore_case_) {
4221 that->MakeCaseIndependent();
4222 }
4223 EnsureAnalyzed(that->on_success());
ager@chromium.org8bb60582008-12-11 12:02:20 +00004224 that->CalculateOffsets();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004225}
4226
4227
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004228void Analysis::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004229 RegExpNode* target = that->on_success();
4230 EnsureAnalyzed(target);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004231 // If the next node is interested in what it follows then this node
4232 // has to be interested too so it can pass the information on.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004233 that->info()->AddFromFollowing(target->info());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004234}
4235
4236
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004237void Analysis::VisitChoice(ChoiceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004238 NodeInfo* info = that->info();
4239 for (int i = 0; i < that->alternatives()->length(); i++) {
4240 RegExpNode* node = that->alternatives()->at(i).node();
4241 EnsureAnalyzed(node);
4242 // Anything the following nodes need to know has to be known by
4243 // this node also, so it can pass it on.
4244 info->AddFromFollowing(node->info());
4245 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004246}
4247
4248
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004249void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
4250 NodeInfo* info = that->info();
4251 for (int i = 0; i < that->alternatives()->length(); i++) {
4252 RegExpNode* node = that->alternatives()->at(i).node();
4253 if (node != that->loop_node()) {
4254 EnsureAnalyzed(node);
4255 info->AddFromFollowing(node->info());
4256 }
4257 }
4258 // Check the loop last since it may need the value of this node
4259 // to get a correct result.
4260 EnsureAnalyzed(that->loop_node());
4261 info->AddFromFollowing(that->loop_node()->info());
4262}
4263
4264
4265void Analysis::VisitBackReference(BackReferenceNode* that) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004266 EnsureAnalyzed(that->on_success());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004267}
4268
4269
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004270void Analysis::VisitAssertion(AssertionNode* that) {
4271 EnsureAnalyzed(that->on_success());
4272}
4273
4274
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004275// -------------------------------------------------------------------
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004276// Dispatch table construction
4277
4278
4279void DispatchTableConstructor::VisitEnd(EndNode* that) {
4280 AddRange(CharacterRange::Everything());
4281}
4282
4283
4284void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
4285 node->set_being_calculated(true);
4286 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
4287 for (int i = 0; i < alternatives->length(); i++) {
4288 set_choice_index(i);
4289 alternatives->at(i).node()->Accept(this);
4290 }
4291 node->set_being_calculated(false);
4292}
4293
4294
4295class AddDispatchRange {
4296 public:
4297 explicit AddDispatchRange(DispatchTableConstructor* constructor)
4298 : constructor_(constructor) { }
4299 void Call(uc32 from, DispatchTable::Entry entry);
4300 private:
4301 DispatchTableConstructor* constructor_;
4302};
4303
4304
4305void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
4306 CharacterRange range(from, entry.to());
4307 constructor_->AddRange(range);
4308}
4309
4310
4311void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
4312 if (node->being_calculated())
4313 return;
4314 DispatchTable* table = node->GetTable(ignore_case_);
4315 AddDispatchRange adder(this);
4316 table->ForEach(&adder);
4317}
4318
4319
4320void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
4321 // TODO(160): Find the node that we refer back to and propagate its start
4322 // set back to here. For now we just accept anything.
4323 AddRange(CharacterRange::Everything());
4324}
4325
4326
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004327void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
4328 RegExpNode* target = that->on_success();
4329 target->Accept(this);
4330}
4331
4332
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004333
4334static int CompareRangeByFrom(const CharacterRange* a,
4335 const CharacterRange* b) {
4336 return Compare<uc16>(a->from(), b->from());
4337}
4338
4339
4340void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
4341 ranges->Sort(CompareRangeByFrom);
4342 uc16 last = 0;
4343 for (int i = 0; i < ranges->length(); i++) {
4344 CharacterRange range = ranges->at(i);
4345 if (last < range.from())
4346 AddRange(CharacterRange(last, range.from() - 1));
4347 if (range.to() >= last) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004348 if (range.to() == String::kMaxUC16CharCode) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004349 return;
4350 } else {
4351 last = range.to() + 1;
4352 }
4353 }
4354 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004355 AddRange(CharacterRange(last, String::kMaxUC16CharCode));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004356}
4357
4358
4359void DispatchTableConstructor::VisitText(TextNode* that) {
4360 TextElement elm = that->elements()->at(0);
4361 switch (elm.type) {
4362 case TextElement::ATOM: {
4363 uc16 c = elm.data.u_atom->data()[0];
4364 AddRange(CharacterRange(c, c));
4365 break;
4366 }
4367 case TextElement::CHAR_CLASS: {
4368 RegExpCharacterClass* tree = elm.data.u_char_class;
4369 ZoneList<CharacterRange>* ranges = tree->ranges();
4370 if (tree->is_negated()) {
4371 AddInverse(ranges);
4372 } else {
4373 for (int i = 0; i < ranges->length(); i++)
4374 AddRange(ranges->at(i));
4375 }
4376 break;
4377 }
4378 default: {
4379 UNIMPLEMENTED();
4380 }
4381 }
4382}
4383
4384
4385void DispatchTableConstructor::VisitAction(ActionNode* that) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00004386 RegExpNode* target = that->on_success();
4387 target->Accept(this);
4388}
4389
4390
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00004391RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data,
4392 bool ignore_case,
4393 bool is_multiline,
4394 Handle<String> pattern,
4395 bool is_ascii) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004396 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00004397 return IrregexpRegExpTooBig();
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004398 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00004399 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004400 // Wrap the body of the regexp in capture #0.
ager@chromium.org8bb60582008-12-11 12:02:20 +00004401 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004402 0,
4403 &compiler,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004404 compiler.accept());
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004405 RegExpNode* node = captured_body;
4406 if (!data->tree->IsAnchored()) {
4407 // Add a .*? at the beginning, outside the body capture, unless
4408 // this expression is anchored at the beginning.
iposva@chromium.org245aa852009-02-10 00:49:54 +00004409 RegExpNode* loop_node =
4410 RegExpQuantifier::ToNode(0,
4411 RegExpTree::kInfinity,
4412 false,
4413 new RegExpCharacterClass('*'),
4414 &compiler,
4415 captured_body,
4416 data->contains_anchor);
4417
4418 if (data->contains_anchor) {
4419 // Unroll loop once, to take care of the case that might start
4420 // at the start of input.
4421 ChoiceNode* first_step_node = new ChoiceNode(2);
4422 first_step_node->AddAlternative(GuardedAlternative(captured_body));
4423 first_step_node->AddAlternative(GuardedAlternative(
4424 new TextNode(new RegExpCharacterClass('*'), loop_node)));
4425 node = first_step_node;
4426 } else {
4427 node = loop_node;
4428 }
ager@chromium.orgddb913d2009-01-27 10:01:48 +00004429 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00004430 data->node = node;
4431 Analysis analysis(ignore_case);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004432 analysis.EnsureAnalyzed(node);
4433
4434 NodeInfo info = *node->info();
ager@chromium.org8bb60582008-12-11 12:02:20 +00004435
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00004436 if (RegExpImpl::UseNativeRegexp()) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004437#ifdef ARM
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00004438 UNREACHABLE();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004439#else // IA32
ager@chromium.org8bb60582008-12-11 12:02:20 +00004440 RegExpMacroAssemblerIA32::Mode mode;
4441 if (is_ascii) {
4442 mode = RegExpMacroAssemblerIA32::ASCII;
4443 } else {
4444 mode = RegExpMacroAssemblerIA32::UC16;
4445 }
4446 RegExpMacroAssemblerIA32 macro_assembler(mode,
4447 (data->capture_count + 1) * 2);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004448 return compiler.Assemble(&macro_assembler,
4449 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004450 data->capture_count,
4451 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004452#endif
4453 }
4454 EmbeddedVector<byte, 1024> codes;
4455 RegExpMacroAssemblerIrregexp macro_assembler(codes);
4456 return compiler.Assemble(&macro_assembler,
4457 node,
ager@chromium.org8bb60582008-12-11 12:02:20 +00004458 data->capture_count,
4459 pattern);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00004460}
4461
4462
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004463}} // namespace v8::internal