The data contained in this repository can be downloaded to your computer using one of several clients.
Please see the documentation of your version control software client for more information.
Please select the desired protocol below to get the URL.
This URL has Read-Only access.
main_repo / deps / v8 / src / jsregexp.cc @ 40c0f755
History | View | Annotate | Download (152 KB)
1 |
// Copyright 2006-2009 the V8 project authors. All rights reserved.
|
---|---|
2 |
// 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 |
|
30 |
#include "ast.h" |
31 |
#include "execution.h" |
32 |
#include "factory.h" |
33 |
#include "jsregexp-inl.h" |
34 |
#include "platform.h" |
35 |
#include "runtime.h" |
36 |
#include "top.h" |
37 |
#include "compilation-cache.h" |
38 |
#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" |
43 |
#include "regexp-stack.h" |
44 |
|
45 |
#ifdef ARM
|
46 |
#include "regexp-macro-assembler-arm.h" |
47 |
#else // IA32 |
48 |
#include "macro-assembler-ia32.h" |
49 |
#include "regexp-macro-assembler-ia32.h" |
50 |
#endif
|
51 |
|
52 |
#include "interpreter-irregexp.h" |
53 |
|
54 |
|
55 |
namespace v8 { namespace internal { |
56 |
|
57 |
|
58 |
Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor, |
59 |
Handle<String> pattern, |
60 |
Handle<String> flags, |
61 |
bool* has_pending_exception) {
|
62 |
// Ensure that the constructor function has been loaded.
|
63 |
if (!constructor->IsLoaded()) {
|
64 |
LoadLazy(constructor, has_pending_exception); |
65 |
if (*has_pending_exception) return Handle<Object>(); |
66 |
} |
67 |
// Call the construct code with 2 arguments.
|
68 |
Object** argv[2] = { Handle<Object>::cast(pattern).location(),
|
69 |
Handle<Object>::cast(flags).location() }; |
70 |
return Execution::New(constructor, 2, argv, has_pending_exception); |
71 |
} |
72 |
|
73 |
|
74 |
static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
|
75 |
int flags = JSRegExp::NONE;
|
76 |
for (int i = 0; i < str->length(); i++) { |
77 |
switch (str->Get(i)) {
|
78 |
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 |
|
93 |
static 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 |
} |
103 |
|
104 |
|
105 |
// Generic RegExp methods. Dispatches to implementation specific methods.
|
106 |
|
107 |
|
108 |
class 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 |
} |
118 |
inline ~OffsetsVector() {
|
119 |
if (offsets_vector_length_ > kStaticOffsetsVectorSize) {
|
120 |
DeleteArray(vector_); |
121 |
vector_ = NULL;
|
122 |
} |
123 |
} |
124 |
inline int* vector() { return vector_; } |
125 |
inline int length() { return offsets_vector_length_; } |
126 |
|
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 |
|
135 |
int OffsetsVector::static_offsets_vector_[
|
136 |
OffsetsVector::kStaticOffsetsVectorSize]; |
137 |
|
138 |
|
139 |
Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re, |
140 |
Handle<String> pattern, |
141 |
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();
|
145 |
LOG(RegExpCompileEvent(re, in_cache)); |
146 |
|
147 |
Handle<Object> result; |
148 |
if (in_cache) {
|
149 |
re->set_data(*cached); |
150 |
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();
|
163 |
} |
164 |
|
165 |
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;
|
185 |
} |
186 |
|
187 |
|
188 |
Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp, |
189 |
Handle<String> subject, |
190 |
int index,
|
191 |
Handle<JSArray> last_match_info) { |
192 |
switch (regexp->TypeTag()) {
|
193 |
case JSRegExp::ATOM:
|
194 |
return AtomExec(regexp, subject, index, last_match_info);
|
195 |
case JSRegExp::IRREGEXP: {
|
196 |
Handle<Object> result = |
197 |
IrregexpExec(regexp, subject, index, last_match_info); |
198 |
ASSERT(!result.is_null() || Top::has_pending_exception()); |
199 |
return result;
|
200 |
} |
201 |
default:
|
202 |
UNREACHABLE(); |
203 |
return Handle<Object>::null();
|
204 |
} |
205 |
} |
206 |
|
207 |
|
208 |
// RegExp Atom implementation: Simple string search using indexOf.
|
209 |
|
210 |
|
211 |
void 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 |
|
223 |
static 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);
|
233 |
} |
234 |
|
235 |
|
236 |
Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re, |
237 |
Handle<String> subject, |
238 |
int index,
|
239 |
Handle<JSArray> last_match_info) { |
240 |
Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex))); |
241 |
|
242 |
uint32_t start_index = index; |
243 |
|
244 |
int value = Runtime::StringMatch(subject, needle, start_index);
|
245 |
if (value == -1) return Factory::null_value(); |
246 |
ASSERT(last_match_info->HasFastElements()); |
247 |
|
248 |
{ |
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;
|
254 |
} |
255 |
|
256 |
|
257 |
// Irregexp implementation.
|
258 |
|
259 |
|
260 |
// 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
|
263 |
// from the source pattern.
|
264 |
// If compilation fails, an exception is thrown and this function
|
265 |
// returns false.
|
266 |
bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) { |
267 |
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; |
282 |
} |
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()); |
290 |
if (!pattern->IsFlat()) {
|
291 |
FlattenString(pattern); |
292 |
} |
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");
|
303 |
return false; |
304 |
} |
305 |
RegExpEngine::CompilationResult result = |
306 |
RegExpEngine::Compile(&compile_data, |
307 |
flags.is_ignore_case(), |
308 |
flags.is_multiline(), |
309 |
pattern, |
310 |
is_ascii); |
311 |
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; |
323 |
} |
324 |
|
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; |
335 |
} |
336 |
|
337 |
|
338 |
int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
|
339 |
return Smi::cast(
|
340 |
re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value(); |
341 |
} |
342 |
|
343 |
|
344 |
void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) { |
345 |
re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value)); |
346 |
} |
347 |
|
348 |
|
349 |
int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
|
350 |
return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
|
351 |
} |
352 |
|
353 |
|
354 |
int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
|
355 |
return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
|
356 |
} |
357 |
|
358 |
|
359 |
ByteArray* 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 |
|
370 |
Code* 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 |
|
381 |
void 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); |
391 |
} |
392 |
|
393 |
|
394 |
Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp, |
395 |
Handle<String> subject, |
396 |
int previous_index,
|
397 |
Handle<JSArray> last_match_info) { |
398 |
ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP); |
399 |
|
400 |
// Prepare space for the return values.
|
401 |
int number_of_capture_registers =
|
402 |
(IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2; |
403 |
OffsetsVector offsets(number_of_capture_registers); |
404 |
|
405 |
#ifdef DEBUG
|
406 |
if (FLAG_trace_regexp_bytecodes) {
|
407 |
String* pattern = jsregexp->Pattern(); |
408 |
PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString()));
|
409 |
PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString()));
|
410 |
} |
411 |
#endif
|
412 |
|
413 |
if (!subject->IsFlat()) {
|
414 |
FlattenString(subject); |
415 |
} |
416 |
|
417 |
last_match_info->EnsureSize(number_of_capture_registers + kLastMatchOverhead); |
418 |
|
419 |
int* offsets_vector = offsets.vector();
|
420 |
bool rc;
|
421 |
|
422 |
// Dispatch to the correct RegExp implementation.
|
423 |
|
424 |
Handle<String> original_subject = subject; |
425 |
Handle<FixedArray> regexp(FixedArray::cast(jsregexp->data())); |
426 |
if (UseNativeRegexp()) {
|
427 |
#ifdef ARM
|
428 |
UNREACHABLE(); |
429 |
#else
|
430 |
RegExpMacroAssemblerIA32::Result res; |
431 |
do {
|
432 |
bool is_ascii = StringShape(*subject).IsAsciiRepresentation();
|
433 |
if (!EnsureCompiledIrregexp(jsregexp, is_ascii)) {
|
434 |
return Handle<Object>::null();
|
435 |
} |
436 |
Handle<Code> code(RegExpImpl::IrregexpNativeCode(*regexp, is_ascii)); |
437 |
res = RegExpMacroAssemblerIA32::Match(code, |
438 |
subject, |
439 |
offsets_vector, |
440 |
offsets.length(), |
441 |
previous_index); |
442 |
// If result is RETRY, the string have changed representation, and we
|
443 |
// must restart from scratch.
|
444 |
} while (res == RegExpMacroAssemblerIA32::RETRY);
|
445 |
if (res == RegExpMacroAssemblerIA32::EXCEPTION) {
|
446 |
ASSERT(Top::has_pending_exception()); |
447 |
return Handle<Object>::null();
|
448 |
} |
449 |
ASSERT(res == RegExpMacroAssemblerIA32::SUCCESS |
450 |
|| res == RegExpMacroAssemblerIA32::FAILURE); |
451 |
|
452 |
rc = (res == RegExpMacroAssemblerIA32::SUCCESS); |
453 |
#endif
|
454 |
} else {
|
455 |
bool is_ascii = StringShape(*subject).IsAsciiRepresentation();
|
456 |
if (!EnsureCompiledIrregexp(jsregexp, is_ascii)) {
|
457 |
return Handle<Object>::null();
|
458 |
} |
459 |
for (int i = number_of_capture_registers - 1; i >= 0; i--) { |
460 |
offsets_vector[i] = -1;
|
461 |
} |
462 |
Handle<ByteArray> byte_codes(IrregexpByteCode(*regexp, is_ascii)); |
463 |
|
464 |
rc = IrregexpInterpreter::Match(byte_codes, |
465 |
subject, |
466 |
offsets_vector, |
467 |
previous_index); |
468 |
} |
469 |
|
470 |
// Handle results from RegExp implementation.
|
471 |
|
472 |
if (!rc) {
|
473 |
return Factory::null_value();
|
474 |
} |
475 |
|
476 |
FixedArray* array = last_match_info->elements(); |
477 |
ASSERT(array->length() >= number_of_capture_registers + kLastMatchOverhead); |
478 |
// The captures come in (start, end+1) pairs.
|
479 |
SetLastCaptureCount(array, number_of_capture_registers); |
480 |
SetLastSubject(array, *original_subject); |
481 |
SetLastInput(array, *original_subject); |
482 |
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 |
} |
486 |
return last_match_info;
|
487 |
} |
488 |
|
489 |
|
490 |
// -------------------------------------------------------------------
|
491 |
// Implementation of the Irregexp regular expression engine.
|
492 |
//
|
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
|
613 |
// 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
|
617 |
// 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 |
//
|
625 |
// 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.
|
638 |
|
639 |
|
640 |
void RegExpTree::AppendToText(RegExpText* text) {
|
641 |
UNREACHABLE(); |
642 |
} |
643 |
|
644 |
|
645 |
void RegExpAtom::AppendToText(RegExpText* text) {
|
646 |
text->AddElement(TextElement::Atom(this));
|
647 |
} |
648 |
|
649 |
|
650 |
void RegExpCharacterClass::AppendToText(RegExpText* text) {
|
651 |
text->AddElement(TextElement::CharClass(this));
|
652 |
} |
653 |
|
654 |
|
655 |
void RegExpText::AppendToText(RegExpText* text) {
|
656 |
for (int i = 0; i < elements()->length(); i++) |
657 |
text->AddElement(elements()->at(i)); |
658 |
} |
659 |
|
660 |
|
661 |
TextElement TextElement::Atom(RegExpAtom* atom) { |
662 |
TextElement result = TextElement(ATOM); |
663 |
result.data.u_atom = atom; |
664 |
return result;
|
665 |
} |
666 |
|
667 |
|
668 |
TextElement 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 |
|
676 |
int 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 |
|
686 |
DispatchTable* 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 |
|
696 |
class RegExpCompiler { |
697 |
public:
|
698 |
RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii); |
699 |
|
700 |
int AllocateRegister() {
|
701 |
if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
|
702 |
reg_exp_too_big_ = true;
|
703 |
return next_register_;
|
704 |
} |
705 |
return next_register_++;
|
706 |
} |
707 |
|
708 |
RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler, |
709 |
RegExpNode* start, |
710 |
int capture_count,
|
711 |
Handle<String> pattern); |
712 |
|
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_; }
|
721 |
|
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 |
|
727 |
void SetRegExpTooBig() { reg_exp_too_big_ = true; } |
728 |
|
729 |
inline bool ignore_case() { return ignore_case_; } |
730 |
inline bool ascii() { return ascii_; } |
731 |
|
732 |
static const int kNoRegister = -1; |
733 |
private:
|
734 |
EndNode* accept_; |
735 |
int next_register_;
|
736 |
List<RegExpNode*>* work_list_; |
737 |
int recursion_depth_;
|
738 |
RegExpMacroAssembler* macro_assembler_; |
739 |
bool ignore_case_;
|
740 |
bool ascii_;
|
741 |
bool reg_exp_too_big_;
|
742 |
}; |
743 |
|
744 |
|
745 |
class RecursionCheck { |
746 |
public:
|
747 |
explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
|
748 |
compiler->IncrementRecursionDepth(); |
749 |
} |
750 |
~RecursionCheck() { compiler_->DecrementRecursionDepth(); } |
751 |
private:
|
752 |
RegExpCompiler* compiler_; |
753 |
}; |
754 |
|
755 |
|
756 |
static RegExpEngine::CompilationResult IrregexpRegExpTooBig() {
|
757 |
return RegExpEngine::CompilationResult("RegExp too big"); |
758 |
} |
759 |
|
760 |
|
761 |
// Attempts to compile the regexp using an Irregexp code generator. Returns
|
762 |
// a fixed array or a null handle depending on whether it succeeded.
|
763 |
RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii) |
764 |
: next_register_(2 * (capture_count + 1)), |
765 |
work_list_(NULL),
|
766 |
recursion_depth_(0),
|
767 |
ignore_case_(ignore_case), |
768 |
ascii_(ascii), |
769 |
reg_exp_too_big_(false) {
|
770 |
accept_ = new EndNode(EndNode::ACCEPT);
|
771 |
ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
|
772 |
} |
773 |
|
774 |
|
775 |
RegExpEngine::CompilationResult RegExpCompiler::Assemble( |
776 |
RegExpMacroAssembler* macro_assembler, |
777 |
RegExpNode* start, |
778 |
int capture_count,
|
779 |
Handle<String> pattern) { |
780 |
#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; |
789 |
macro_assembler_->PushBacktrack(&fail); |
790 |
Trace new_trace; |
791 |
start->Emit(this, &new_trace);
|
792 |
macro_assembler_->Bind(&fail); |
793 |
macro_assembler_->Fail(); |
794 |
while (!work_list.is_empty()) {
|
795 |
work_list.RemoveLast()->Emit(this, &new_trace);
|
796 |
} |
797 |
if (reg_exp_too_big_) return IrregexpRegExpTooBig(); |
798 |
|
799 |
Handle<Object> code = macro_assembler_->GetCode(pattern); |
800 |
|
801 |
work_list_ = NULL;
|
802 |
#ifdef DEBUG
|
803 |
if (FLAG_trace_regexp_assembler) {
|
804 |
delete macro_assembler_;
|
805 |
} |
806 |
#endif
|
807 |
return RegExpEngine::CompilationResult(*code, next_register_);
|
808 |
} |
809 |
|
810 |
|
811 |
bool 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 |
} |
819 |
|
820 |
|
821 |
bool Trace::mentions_reg(int reg) { |
822 |
for (DeferredAction* action = actions_;
|
823 |
action != NULL;
|
824 |
action = action->next()) { |
825 |
if (action->Mentions(reg))
|
826 |
return true; |
827 |
} |
828 |
return false; |
829 |
} |
830 |
|
831 |
|
832 |
bool Trace::GetStoredPosition(int reg, int* cp_offset) { |
833 |
ASSERT_EQ(0, *cp_offset);
|
834 |
for (DeferredAction* action = actions_;
|
835 |
action != NULL;
|
836 |
action = action->next()) { |
837 |
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 |
|
850 |
int 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 |
} |
864 |
} |
865 |
return max_register;
|
866 |
} |
867 |
|
868 |
|
869 |
void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
|
870 |
int max_register,
|
871 |
OutSet& registers_to_pop, |
872 |
OutSet& registers_to_clear) { |
873 |
for (int reg = max_register; reg >= 0; reg--) { |
874 |
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 |
} |
882 |
} |
883 |
} |
884 |
|
885 |
|
886 |
void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
|
887 |
int max_register,
|
888 |
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 |
|
894 |
for (int reg = 0; reg <= max_register; reg++) { |
895 |
if (!affected_registers.Get(reg)) {
|
896 |
continue;
|
897 |
} |
898 |
// 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 |
|
907 |
int value = 0; |
908 |
bool absolute = false; |
909 |
bool clear = false; |
910 |
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()) { |
916 |
if (action->Mentions(reg)) {
|
917 |
switch (action->type()) {
|
918 |
case ActionNode::SET_REGISTER: {
|
919 |
Trace::DeferredSetRegister* psr = |
920 |
static_cast<Trace::DeferredSetRegister*>(action);
|
921 |
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; |
931 |
ASSERT_EQ(store_position, -1);
|
932 |
ASSERT(!clear); |
933 |
break;
|
934 |
} |
935 |
case ActionNode::INCREMENT_REGISTER:
|
936 |
if (!absolute) {
|
937 |
value++; |
938 |
} |
939 |
ASSERT_EQ(store_position, -1);
|
940 |
ASSERT(!clear); |
941 |
undo_action = RESTORE; |
942 |
break;
|
943 |
case ActionNode::STORE_POSITION: {
|
944 |
Trace::DeferredCapture* pc = |
945 |
static_cast<Trace::DeferredCapture*>(action);
|
946 |
if (!clear && store_position == -1) { |
947 |
store_position = pc->cp_offset(); |
948 |
} |
949 |
|
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 |
} |
962 |
ASSERT(!absolute); |
963 |
ASSERT_EQ(value, 0);
|
964 |
break;
|
965 |
} |
966 |
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.
|
970 |
if (store_position == -1) { |
971 |
clear = true;
|
972 |
} |
973 |
undo_action = RESTORE; |
974 |
ASSERT(!absolute); |
975 |
ASSERT_EQ(value, 0);
|
976 |
break;
|
977 |
} |
978 |
default:
|
979 |
UNREACHABLE(); |
980 |
break;
|
981 |
} |
982 |
} |
983 |
} |
984 |
// 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.
|
1001 |
if (store_position != -1) { |
1002 |
assembler->WriteCurrentPositionToRegister(reg, store_position); |
1003 |
} else if (clear) { |
1004 |
assembler->ClearRegisters(reg, reg); |
1005 |
} else if (absolute) { |
1006 |
assembler->SetRegister(reg, value); |
1007 |
} else if (value != 0) { |
1008 |
assembler->AdvanceRegister(reg, value); |
1009 |
} |
1010 |
} |
1011 |
} |
1012 |
|
1013 |
|
1014 |
// This is called as we come into a loop choice node and some other tricky
|
1015 |
// nodes. It normalizes the state of the code generator to ensure we can
|
1016 |
// generate generic code.
|
1017 |
void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
|
1018 |
RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
1019 |
|
1020 |
ASSERT(!is_trivial()); |
1021 |
|
1022 |
if (actions_ == NULL && backtrack() == NULL) { |
1023 |
// Here we just have some deferred cp advances to fix and we are back to
|
1024 |
// 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_); |
1027 |
// Create a new trivial state and generate the node with that.
|
1028 |
Trace new_state; |
1029 |
successor->Emit(compiler, &new_state); |
1030 |
return;
|
1031 |
} |
1032 |
|
1033 |
// Generate deferred actions here along with code to undo them again.
|
1034 |
OutSet affected_registers; |
1035 |
|
1036 |
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 |
|
1043 |
int max_register = FindAffectedRegisters(&affected_registers);
|
1044 |
OutSet registers_to_pop; |
1045 |
OutSet registers_to_clear; |
1046 |
PerformDeferredActions(assembler, |
1047 |
max_register, |
1048 |
affected_registers, |
1049 |
®isters_to_pop, |
1050 |
®isters_to_clear); |
1051 |
if (cp_offset_ != 0) { |
1052 |
assembler->AdvanceCurrentPosition(cp_offset_); |
1053 |
} |
1054 |
|
1055 |
// Create a new trivial state and generate the node with that.
|
1056 |
Label undo; |
1057 |
assembler->PushBacktrack(&undo); |
1058 |
Trace new_state; |
1059 |
successor->Emit(compiler, &new_state); |
1060 |
|
1061 |
// On backtrack we need to restore state.
|
1062 |
assembler->Bind(&undo); |
1063 |
RestoreAffectedRegisters(assembler, |
1064 |
max_register, |
1065 |
registers_to_pop, |
1066 |
registers_to_clear); |
1067 |
if (backtrack() == NULL) { |
1068 |
assembler->Backtrack(); |
1069 |
} else {
|
1070 |
assembler->PopCurrentPosition(); |
1071 |
assembler->GoTo(backtrack()); |
1072 |
} |
1073 |
} |
1074 |
|
1075 |
|
1076 |
void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
|
1077 |
RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
1078 |
|
1079 |
// Omit flushing the trace. We discard the entire stack frame anyway.
|
1080 |
|
1081 |
if (!label()->is_bound()) {
|
1082 |
// We are completely independent of the trace, since we ignore it,
|
1083 |
// so this code can be used as the generic version.
|
1084 |
assembler->Bind(label()); |
1085 |
} |
1086 |
|
1087 |
// Throw away everything on the backtrack stack since the start
|
1088 |
// of the negative submatch and restore the character position.
|
1089 |
assembler->ReadCurrentPositionFromRegister(current_position_register_); |
1090 |
assembler->ReadStackPointerFromRegister(stack_pointer_register_); |
1091 |
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 |
} |
1097 |
// Now that we have unwound the stack we find at the top of the stack the
|
1098 |
// backtrack that the BeginSubmatch node got.
|
1099 |
assembler->Backtrack(); |
1100 |
} |
1101 |
|
1102 |
|
1103 |
void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
|
1104 |
if (!trace->is_trivial()) {
|
1105 |
trace->Flush(compiler, this);
|
1106 |
return;
|
1107 |
} |
1108 |
RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
1109 |
if (!label()->is_bound()) {
|
1110 |
assembler->Bind(label()); |
1111 |
} |
1112 |
switch (action_) {
|
1113 |
case ACCEPT:
|
1114 |
assembler->Succeed(); |
1115 |
return;
|
1116 |
case BACKTRACK:
|
1117 |
assembler->GoTo(trace->backtrack()); |
1118 |
return;
|
1119 |
case NEGATIVE_SUBMATCH_SUCCESS:
|
1120 |
// This case is handled in a different virtual method.
|
1121 |
UNREACHABLE(); |
1122 |
} |
1123 |
UNIMPLEMENTED(); |
1124 |
} |
1125 |
|
1126 |
|
1127 |
void GuardedAlternative::AddGuard(Guard* guard) {
|
1128 |
if (guards_ == NULL) |
1129 |
guards_ = new ZoneList<Guard*>(1); |
1130 |
guards_->Add(guard); |
1131 |
} |
1132 |
|
1133 |
|
1134 |
ActionNode* ActionNode::SetRegister(int reg,
|
1135 |
int val,
|
1136 |
RegExpNode* on_success) { |
1137 |
ActionNode* result = new ActionNode(SET_REGISTER, on_success);
|
1138 |
result->data_.u_store_register.reg = reg; |
1139 |
result->data_.u_store_register.value = val; |
1140 |
return result;
|
1141 |
} |
1142 |
|
1143 |
|
1144 |
ActionNode* 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 |
|
1151 |
ActionNode* ActionNode::StorePosition(int reg,
|
1152 |
bool is_capture,
|
1153 |
RegExpNode* on_success) { |
1154 |
ActionNode* result = new ActionNode(STORE_POSITION, on_success);
|
1155 |
result->data_.u_position_register.reg = reg; |
1156 |
result->data_.u_position_register.is_capture = is_capture; |
1157 |
return result;
|
1158 |
} |
1159 |
|
1160 |
|
1161 |
ActionNode* 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 |
|
1170 |
ActionNode* 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 |
|
1180 |
ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
|
1181 |
int position_reg,
|
1182 |
int clear_register_count,
|
1183 |
int clear_register_from,
|
1184 |
RegExpNode* on_success) { |
1185 |
ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
|
1186 |
result->data_.u_submatch.stack_pointer_register = stack_reg; |
1187 |
result->data_.u_submatch.current_position_register = position_reg; |
1188 |
result->data_.u_submatch.clear_register_count = clear_register_count; |
1189 |
result->data_.u_submatch.clear_register_from = clear_register_from; |
1190 |
return result;
|
1191 |
} |
1192 |
|
1193 |
|
1194 |
ActionNode* 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 |
|
1206 |
#define DEFINE_ACCEPT(Type) \
|
1207 |
void Type##Node::Accept(NodeVisitor* visitor) { \ |
1208 |
visitor->Visit##Type(this); \ |
1209 |
} |
1210 |
FOR_EACH_NODE_TYPE(DEFINE_ACCEPT) |
1211 |
#undef DEFINE_ACCEPT
|
1212 |
|
1213 |
|
1214 |
void LoopChoiceNode::Accept(NodeVisitor* visitor) {
|
1215 |
visitor->VisitLoopChoice(this);
|
1216 |
} |
1217 |
|
1218 |
|
1219 |
// -------------------------------------------------------------------
|
1220 |
// Emit code.
|
1221 |
|
1222 |
|
1223 |
void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
|
1224 |
Guard* guard, |
1225 |
Trace* trace) { |
1226 |
switch (guard->op()) {
|
1227 |
case Guard::LT:
|
1228 |
ASSERT(!trace->mentions_reg(guard->reg())); |
1229 |
macro_assembler->IfRegisterGE(guard->reg(), |
1230 |
guard->value(), |
1231 |
trace->backtrack()); |
1232 |
break;
|
1233 |
case Guard::GEQ:
|
1234 |
ASSERT(!trace->mentions_reg(guard->reg())); |
1235 |
macro_assembler->IfRegisterLT(guard->reg(), |
1236 |
guard->value(), |
1237 |
trace->backtrack()); |
1238 |
break;
|
1239 |
} |
1240 |
} |
1241 |
|
1242 |
|
1243 |
static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize;
|
1244 |
static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange;
|
1245 |
|
1246 |
|
1247 |
// Returns the number of characters in the equivalence class, omitting those
|
1248 |
// that cannot occur in the source string because it is ASCII.
|
1249 |
static 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 |
|
1268 |
static 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 |
|
1288 |
// Only emits non-letters (things that don't have case). Only used for case
|
1289 |
// independent matches.
|
1290 |
static 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();
|
1298 |
unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
1299 |
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 |
} |
1305 |
bool checked = false; |
1306 |
// 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 |
} |
1312 |
if (!preloaded) {
|
1313 |
macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check); |
1314 |
checked = check; |
1315 |
} |
1316 |
macro_assembler->CheckNotCharacter(c, on_failure); |
1317 |
} |
1318 |
return checked;
|
1319 |
} |
1320 |
|
1321 |
|
1322 |
static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler, |
1323 |
bool ascii,
|
1324 |
uc16 c1, |
1325 |
uc16 c2, |
1326 |
Label* on_failure) { |
1327 |
uc16 char_mask; |
1328 |
if (ascii) {
|
1329 |
char_mask = String::kMaxAsciiCharCode; |
1330 |
} else {
|
1331 |
char_mask = String::kMaxUC16CharCode; |
1332 |
} |
1333 |
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); |
1339 |
uc16 mask = char_mask ^ exor; |
1340 |
macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure); |
1341 |
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.
|
1350 |
uc16 mask = char_mask ^ diff; |
1351 |
macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff, |
1352 |
diff, |
1353 |
mask, |
1354 |
on_failure); |
1355 |
return true; |
1356 |
} |
1357 |
return false; |
1358 |
} |
1359 |
|
1360 |
|
1361 |
typedef bool EmitCharacterFunction(RegExpCompiler* compiler, |
1362 |
uc16 c, |
1363 |
Label* on_failure, |
1364 |
int cp_offset,
|
1365 |
bool check,
|
1366 |
bool preloaded);
|
1367 |
|
1368 |
// Only emits letters (things that have case). Only used for case independent
|
1369 |
// matches.
|
1370 |
static 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();
|
1378 |
unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
1379 |
int length = GetCaseIndependentLetters(c, ascii, chars);
|
1380 |
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); |
1385 |
} |
1386 |
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; |
1416 |
} |
1417 |
|
1418 |
|
1419 |
static void EmitCharClass(RegExpMacroAssembler* macro_assembler, |
1420 |
RegExpCharacterClass* cc, |
1421 |
bool ascii,
|
1422 |
Label* on_failure, |
1423 |
int cp_offset,
|
1424 |
bool check_offset,
|
1425 |
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 |
|
1434 |
ZoneList<CharacterRange>* ranges = cc->ranges(); |
1435 |
int max_char;
|
1436 |
if (ascii) {
|
1437 |
max_char = String::kMaxAsciiCharCode; |
1438 |
} else {
|
1439 |
max_char = String::kMaxUC16CharCode; |
1440 |
} |
1441 |
|
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 |
|
1449 |
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) { |
1459 |
if (!cc->is_negated()) {
|
1460 |
// TODO(plesner): We can remove this when the node level does our
|
1461 |
// ASCII optimizations for us.
|
1462 |
macro_assembler->GoTo(on_failure); |
1463 |
} |
1464 |
if (check_offset) {
|
1465 |
macro_assembler->CheckPosition(cp_offset, on_failure); |
1466 |
} |
1467 |
return;
|
1468 |
} |
1469 |
|
1470 |
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.
|
1474 |
if (check_offset) {
|
1475 |
macro_assembler->CheckPosition(cp_offset, on_failure); |
1476 |
} |
1477 |
return;
|
1478 |
} |
1479 |
|
1480 |
if (!preloaded) {
|
1481 |
macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset); |
1482 |
} |
1483 |
|
1484 |
for (int i = 0; i < last_valid_range; i++) { |
1485 |
CharacterRange& range = ranges->at(i); |
1486 |
Label next_range; |
1487 |
uc16 from = range.from(); |
1488 |
uc16 to = range.to(); |
1489 |
if (from > max_char) {
|
1490 |
continue;
|
1491 |
} |
1492 |
if (to > max_char) to = max_char;
|
1493 |
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 |
} |
1499 |
if (to != max_char) {
|
1500 |
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 |
|
1508 |
CharacterRange& range = ranges->at(last_valid_range); |
1509 |
uc16 from = range.from(); |
1510 |
uc16 to = range.to(); |
1511 |
|
1512 |
if (to > max_char) to = max_char;
|
1513 |
ASSERT(to >= from); |
1514 |
|
1515 |
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 |
} |
1529 |
if (to != String::kMaxUC16CharCode) {
|
1530 |
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 |
|
1545 |
RegExpNode::~RegExpNode() { |
1546 |
} |
1547 |
|
1548 |
|
1549 |
RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler, |
1550 |
Trace* trace) { |
1551 |
// If we are generating a greedy loop then don't stop and don't reuse code.
|
1552 |
if (trace->stop_node() != NULL) { |
1553 |
return CONTINUE;
|
1554 |
} |
1555 |
|
1556 |
RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
1557 |
if (trace->is_trivial()) {
|
1558 |
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.
|
1578 |
trace_count_++; |
1579 |
if (FLAG_regexp_optimization &&
|
1580 |
trace_count_ < kMaxCopiesCodeGenerated && |
1581 |
compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) { |
1582 |
return CONTINUE;
|
1583 |
} |
1584 |
|
1585 |
// 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
|
1587 |
// generic versions above can handle deep recursion properly.
|
1588 |
trace->Flush(compiler, this);
|
1589 |
return DONE;
|
1590 |
} |
1591 |
|
1592 |
|
1593 |
int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
1594 |
if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0; |
1595 |
if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input! |
1596 |
return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1); |
1597 |
} |
1598 |
|
1599 |
|
1600 |
int 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 |
|
1606 |
int 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 |
|
1612 |
int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
1613 |
int answer = Length();
|
1614 |
if (answer >= still_to_find) return answer; |
1615 |
if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer; |
1616 |
return answer + on_success()->EatsAtLeast(still_to_find - answer,
|
1617 |
recursion_depth + 1);
|
1618 |
} |
1619 |
|
1620 |
|
1621 |
int 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 |
|
1631 |
void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
|
1632 |
QuickCheckDetails* details, |
1633 |
RegExpCompiler* compiler, |
1634 |
int filled_in,
|
1635 |
bool not_at_start) {
|
1636 |
// Alternative 0 is the negative lookahead, alternative 1 is what comes
|
1637 |
// afterwards.
|
1638 |
RegExpNode* node = alternatives_->at(1).node();
|
1639 |
return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
|
1640 |
} |
1641 |
|
1642 |
|
1643 |
int ChoiceNode::EatsAtLeastHelper(int still_to_find, |
1644 |
int recursion_depth,
|
1645 |
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; |
1652 |
int node_eats_at_least = node->EatsAtLeast(still_to_find,
|
1653 |
recursion_depth + 1);
|
1654 |
if (node_eats_at_least < min) min = node_eats_at_least;
|
1655 |
} |
1656 |
return min;
|
1657 |
} |
1658 |
|
1659 |
|
1660 |
int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
1661 |
return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_);
|
1662 |
} |
1663 |
|
1664 |
|
1665 |
int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
1666 |
return EatsAtLeastHelper(still_to_find, recursion_depth, NULL); |
1667 |
} |
1668 |
|
1669 |
|
1670 |
// Takes the left-most 1-bit and smears it out, setting all bits to its right.
|
1671 |
static 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 |
|
1681 |
bool 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 |
|
1705 |
bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
|
1706 |
Trace* trace, |
1707 |
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; |
1712 |
GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE);
|
1713 |
if (details->cannot_match()) return false; |
1714 |
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 |
|
1720 |
if (trace->characters_preloaded() != details->characters()) {
|
1721 |
assembler->LoadCurrentCharacter(trace->cp_offset(), |
1722 |
trace->backtrack(), |
1723 |
!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) {
|
1759 |
assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack()); |
1760 |
} else {
|
1761 |
assembler->CheckNotCharacter(value, trace->backtrack()); |
1762 |
} |
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.
|
1776 |
void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
|
1777 |
RegExpCompiler* compiler, |
1778 |
int characters_filled_in,
|
1779 |
bool not_at_start) {
|
1780 |
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); |
1798 |
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(); |
1805 |
pos->determines_perfectly = false;
|
1806 |
return;
|
1807 |
} |
1808 |
if (compiler->ignore_case()) {
|
1809 |
unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
1810 |
int length = GetCaseIndependentLetters(c, compiler->ascii(), chars);
|
1811 |
ASSERT(length != 0); // Can only happen if c > char_mask (see above). |
1812 |
if (length == 1) { |
1813 |
// 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; |
1843 |
pos->value = c; |
1844 |
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(); |
1857 |
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 {
|
1865 |
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); |
1881 |
// 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); |
1887 |
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;
|
1894 |
// 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;
|
1900 |
uint32_t new_common_bits = (from ^ to); |
1901 |
new_common_bits = ~SmearBitsRight(new_common_bits); |
1902 |
common_bits &= new_common_bits; |
1903 |
bits &= new_common_bits; |
1904 |
uint32_t differing_bits = (from & common_bits) ^ bits; |
1905 |
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()); |
1919 |
on_success()-> GetQuickCheckDetails(details, |
1920 |
compiler, |
1921 |
characters_filled_in, |
1922 |
true);
|
1923 |
} |
1924 |
|
1925 |
|
1926 |
void 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 |
|
1936 |
void QuickCheckDetails::Advance(int by, bool ascii) { |
1937 |
ASSERT(by >= 0);
|
1938 |
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 |
|
1957 |
void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) { |
1958 |
ASSERT(characters_ == other->characters_); |
1959 |
if (other->cannot_match_) {
|
1960 |
return;
|
1961 |
} |
1962 |
if (cannot_match_) {
|
1963 |
*this = *other;
|
1964 |
return;
|
1965 |
} |
1966 |
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 |
|
1986 |
class 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 |
|
2000 |
void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
|
2001 |
RegExpCompiler* compiler, |
2002 |
int characters_filled_in,
|
2003 |
bool not_at_start) {
|
2004 |
if (body_can_be_zero_length_ || info()->visited) return; |
2005 |
VisitMarker marker(info()); |
2006 |
return ChoiceNode::GetQuickCheckDetails(details,
|
2007 |
compiler, |
2008 |
characters_filled_in, |
2009 |
not_at_start); |
2010 |
} |
2011 |
|
2012 |
|
2013 |
void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
|
2014 |
RegExpCompiler* compiler, |
2015 |
int characters_filled_in,
|
2016 |
bool not_at_start) {
|
2017 |
not_at_start = (not_at_start || not_at_start_); |
2018 |
int choice_count = alternatives_->length();
|
2019 |
ASSERT(choice_count > 0);
|
2020 |
alternatives_->at(0).node()->GetQuickCheckDetails(details,
|
2021 |
compiler, |
2022 |
characters_filled_in, |
2023 |
not_at_start); |
2024 |
for (int i = 1; i < choice_count; i++) { |
2025 |
QuickCheckDetails new_details(details->characters()); |
2026 |
RegExpNode* node = alternatives_->at(i).node(); |
2027 |
node->GetQuickCheckDetails(&new_details, compiler, |
2028 |
characters_filled_in, |
2029 |
not_at_start); |
2030 |
// Here we merge the quick match details of the two branches.
|
2031 |
details->Merge(&new_details, characters_filled_in); |
2032 |
} |
2033 |
} |
2034 |
|
2035 |
|
2036 |
// Check for [0-9A-Z_a-z].
|
2037 |
static 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).
|
2057 |
static 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).
|
2089 |
static 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 |
|
2155 |
void 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 |
|
2170 |
void 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 |
} |
2180 |
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;
|
2194 |
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 |
|
2206 |
static 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 |
|
2213 |
static void UpdateBoundsCheck(int index, int* checked_up_to) { |
2214 |
if (index > *checked_up_to) {
|
2215 |
*checked_up_to = index; |
2216 |
} |
2217 |
} |
2218 |
|
2219 |
|
2220 |
// 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 |
//
|
2241 |
// In addition to all this we are passed a Trace, which can
|
2242 |
// 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.
|
2249 |
void TextNode::TextEmitPass(RegExpCompiler* compiler,
|
2250 |
TextEmitPassType pass, |
2251 |
bool preloaded,
|
2252 |
Trace* trace, |
2253 |
bool first_element_checked,
|
2254 |
int* checked_up_to) {
|
2255 |
RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
2256 |
bool ascii = compiler->ascii();
|
2257 |
Label* backtrack = trace->backtrack(); |
2258 |
QuickCheckDetails* quick_check = trace->quick_check_performed(); |
2259 |
int element_count = elms_->length();
|
2260 |
for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) { |
2261 |
TextElement elm = elms_->at(i); |
2262 |
int cp_offset = trace->cp_offset() + elm.cp_offset;
|
2263 |
if (elm.type == TextElement::ATOM) {
|
2264 |
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:
|
2271 |
ASSERT(ascii); |
2272 |
if (quarks[j] > String::kMaxAsciiCharCode) {
|
2273 |
assembler->GoTo(backtrack); |
2274 |
return;
|
2275 |
} |
2276 |
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,
|
2291 |
quarks[j], |
2292 |
backtrack, |
2293 |
cp_offset + j, |
2294 |
*checked_up_to < cp_offset + j, |
2295 |
preloaded); |
2296 |
if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
|
2297 |
} |
2298 |
} |
2299 |
} else {
|
2300 |
ASSERT_EQ(elm.type, TextElement::CHAR_CLASS); |
2301 |
if (pass == CHARACTER_CLASS_MATCH) {
|
2302 |
if (first_element_checked && i == 0) continue; |
2303 |
if (DeterminedAlready(quick_check, elm.cp_offset)) continue; |
2304 |
RegExpCharacterClass* cc = elm.data.u_char_class; |
2305 |
EmitCharClass(assembler, |
2306 |
cc, |
2307 |
ascii, |
2308 |
backtrack, |
2309 |
cp_offset, |
2310 |
*checked_up_to < cp_offset, |
2311 |
preloaded); |
2312 |
UpdateBoundsCheck(cp_offset, checked_up_to); |
2313 |
} |
2314 |
} |
2315 |
} |
2316 |
} |
2317 |
|
2318 |
|
2319 |
int 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 |
|
2330 |
bool 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 |
|
2340 |
// 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
|
2342 |
// 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.
|
2346 |
void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
|
2347 |
LimitResult limit_result = LimitVersions(compiler, trace); |
2348 |
if (limit_result == DONE) return; |
2349 |
ASSERT(limit_result == CONTINUE); |
2350 |
|
2351 |
if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
|
2352 |
compiler->SetRegExpTooBig(); |
2353 |
return;
|
2354 |
} |
2355 |
|
2356 |
if (compiler->ascii()) {
|
2357 |
int dummy = 0; |
2358 |
TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy); |
2359 |
} |
2360 |
|
2361 |
bool first_elt_done = false; |
2362 |
int bound_checked_to = trace->cp_offset() - 1; |
2363 |
bound_checked_to += trace->bound_checked_up_to(); |
2364 |
|
2365 |
// If a character is preloaded into the current character register then
|
2366 |
// check that now.
|
2367 |
if (trace->characters_preloaded() == 1) { |
2368 |
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 |
} |
2377 |
} |
2378 |
first_elt_done = true;
|
2379 |
} |
2380 |
|
2381 |
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 |
} |
2390 |
} |
2391 |
|
2392 |
Trace successor_trace(*trace); |
2393 |
successor_trace.set_at_start(false);
|
2394 |
successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler); |
2395 |
RecursionCheck rc(compiler); |
2396 |
on_success()->Emit(compiler, &successor_trace); |
2397 |
} |
2398 |
|
2399 |
|
2400 |
void Trace::InvalidateCurrentCharacter() {
|
2401 |
characters_preloaded_ = 0;
|
2402 |
} |
2403 |
|
2404 |
|
2405 |
void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) { |
2406 |
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.
|
2414 |
quick_check_performed_.Advance(by, compiler->ascii()); |
2415 |
cp_offset_ += by; |
2416 |
if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
|
2417 |
compiler->SetRegExpTooBig(); |
2418 |
cp_offset_ = 0;
|
2419 |
} |
2420 |
bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
|
2421 |
} |
2422 |
|
2423 |
|
2424 |
void 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 |
|
2440 |
int 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.
|
2454 |
int 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 |
} |
2464 |
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 |
|
2476 |
void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
|
2477 |
ASSERT_EQ(loop_node_, NULL);
|
2478 |
AddAlternative(alt); |
2479 |
loop_node_ = alt.node(); |
2480 |
} |
2481 |
|
2482 |
|
2483 |
void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
|
2484 |
ASSERT_EQ(continue_node_, NULL);
|
2485 |
AddAlternative(alt); |
2486 |
continue_node_ = alt.node(); |
2487 |
} |
2488 |
|
2489 |
|
2490 |
void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
|
2491 |
RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
2492 |
if (trace->stop_node() == this) { |
2493 |
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).
|
2497 |
ASSERT(trace->cp_offset() == text_length); |
2498 |
macro_assembler->AdvanceCurrentPosition(text_length); |
2499 |
macro_assembler->GoTo(trace->loop_label()); |
2500 |
return;
|
2501 |
} |
2502 |
ASSERT(trace->stop_node() == NULL);
|
2503 |
if (!trace->is_trivial()) {
|
2504 |
trace->Flush(compiler, this);
|
2505 |
return;
|
2506 |
} |
2507 |
ChoiceNode::Emit(compiler, trace); |
2508 |
} |
2509 |
|
2510 |
|
2511 |
int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) {
|
2512 |
int preload_characters = EatsAtLeast(4, 0); |
2513 |
#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.
|
2533 |
class 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.
|
2549 |
class 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() { |
2561 |
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 |
|
2656 |
void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
|
2657 |
RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
2658 |
int choice_count = alternatives_->length();
|
2659 |
#ifdef DEBUG
|
2660 |
for (int i = 0; i < choice_count - 1; i++) { |
2661 |
GuardedAlternative alternative = alternatives_->at(i); |
2662 |
ZoneList<Guard*>* guards = alternative.guards(); |
2663 |
int guard_count = (guards == NULL) ? 0 : guards->length(); |
2664 |
for (int j = 0; j < guard_count; j++) { |
2665 |
ASSERT(!trace->mentions_reg(guards->at(j)->reg())); |
2666 |
} |
2667 |
} |
2668 |
#endif
|
2669 |
|
2670 |
LimitResult limit_result = LimitVersions(compiler, trace); |
2671 |
if (limit_result == DONE) return; |
2672 |
ASSERT(limit_result == CONTINUE); |
2673 |
|
2674 |
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 |
|
2680 |
RecursionCheck rc(compiler); |
2681 |
|
2682 |
Trace* current_trace = trace; |
2683 |
|
2684 |
int text_length = GreedyLoopTextLength(&(alternatives_->at(0))); |
2685 |
bool greedy_loop = false; |
2686 |
Label greedy_loop_label; |
2687 |
Trace counter_backtrack_trace; |
2688 |
counter_backtrack_trace.set_backtrack(&greedy_loop_label); |
2689 |
if (not_at_start()) counter_backtrack_trace.set_at_start(false); |
2690 |
|
2691 |
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;
|
2700 |
ASSERT(trace->stop_node() == NULL);
|
2701 |
macro_assembler->PushCurrentPosition(); |
2702 |
current_trace = &counter_backtrack_trace; |
2703 |
Label greedy_match_failed; |
2704 |
Trace greedy_match_trace; |
2705 |
if (not_at_start()) greedy_match_trace.set_at_start(false); |
2706 |
greedy_match_trace.set_backtrack(&greedy_match_failed); |
2707 |
Label loop_label; |
2708 |
macro_assembler->Bind(&loop_label); |
2709 |
greedy_match_trace.set_stop_node(this);
|
2710 |
greedy_match_trace.set_loop_label(&loop_label); |
2711 |
alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
|
2712 |
macro_assembler->Bind(&greedy_match_failed); |
2713 |
} |
2714 |
|
2715 |
Label second_choice; // For use in greedy matches.
|
2716 |
macro_assembler->Bind(&second_choice); |
2717 |
|
2718 |
int first_normal_choice = greedy_loop ? 1 : 0; |
2719 |
|
2720 |
int preload_characters = CalculatePreloadCharacters(compiler);
|
2721 |
bool preload_is_current =
|
2722 |
(current_trace->characters_preloaded() == preload_characters); |
2723 |
bool preload_has_checked_bounds = preload_is_current;
|
2724 |
|
2725 |
AlternativeGenerationList alt_gens(choice_count); |
2726 |
|
2727 |
// 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.
|
2729 |
for (int i = first_normal_choice; i < choice_count; i++) { |
2730 |
GuardedAlternative alternative = alternatives_->at(i); |
2731 |
AlternativeGeneration* alt_gen = alt_gens.at(i); |
2732 |
alt_gen->quick_check_details.set_characters(preload_characters); |
2733 |
ZoneList<Guard*>* guards = alternative.guards(); |
2734 |
int guard_count = (guards == NULL) ? 0 : guards->length(); |
2735 |
Trace new_trace(*current_trace); |
2736 |
new_trace.set_characters_preloaded(preload_is_current ? |
2737 |
preload_characters : |
2738 |
0);
|
2739 |
if (preload_has_checked_bounds) {
|
2740 |
new_trace.set_bound_checked_up_to(preload_characters); |
2741 |
} |
2742 |
new_trace.quick_check_performed()->Clear(); |
2743 |
if (not_at_start_) new_trace.set_at_start(Trace::FALSE);
|
2744 |
alt_gen->expects_preload = preload_is_current; |
2745 |
bool generate_full_check_inline = false; |
2746 |
if (FLAG_regexp_optimization &&
|
2747 |
try_to_emit_quick_check_for_alternative(i) && |
2748 |
alternative.node()->EmitQuickCheck(compiler, |
2749 |
&new_trace, |
2750 |
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); |
2762 |
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); |
2765 |
generate_full_check_inline = true;
|
2766 |
} |
2767 |
} 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;
|
2772 |
} 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;
|
2780 |
new_trace.set_characters_preloaded(0);
|
2781 |
} |
2782 |
if (i < choice_count - 1) { |
2783 |
new_trace.set_backtrack(&alt_gen->after); |
2784 |
} |
2785 |
generate_full_check_inline = true;
|
2786 |
} |
2787 |
if (generate_full_check_inline) {
|
2788 |
if (new_trace.actions() != NULL) { |
2789 |
new_trace.set_flush_budget(new_flush_budget); |
2790 |
} |
2791 |
for (int j = 0; j < guard_count; j++) { |
2792 |
GenerateGuard(macro_assembler, guards->at(j), &new_trace); |
2793 |
} |
2794 |
alternative.node()->Emit(compiler, &new_trace); |
2795 |
preload_is_current = false;
|
2796 |
} |
2797 |
macro_assembler->Bind(&alt_gen->after); |
2798 |
} |
2799 |
if (greedy_loop) {
|
2800 |
macro_assembler->Bind(&greedy_loop_label); |
2801 |
// If we have unwound to the bottom then backtrack.
|
2802 |
macro_assembler->CheckGreedyLoop(trace->backtrack()); |
2803 |
// Otherwise try the second priority at an earlier position.
|
2804 |
macro_assembler->AdvanceCurrentPosition(-text_length); |
2805 |
macro_assembler->GoTo(&second_choice); |
2806 |
} |
2807 |
|
2808 |
// 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); |
2813 |
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 |
} |
2820 |
EmitOutOfLineContinuation(compiler, |
2821 |
&new_trace, |
2822 |
alternatives_->at(i), |
2823 |
alt_gen, |
2824 |
preload_characters, |
2825 |
alt_gens.at(i + 1)->expects_preload);
|
2826 |
} |
2827 |
} |
2828 |
|
2829 |
|
2830 |
void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
|
2831 |
Trace* trace, |
2832 |
GuardedAlternative alternative, |
2833 |
AlternativeGeneration* alt_gen, |
2834 |
int preload_characters,
|
2835 |
bool next_expects_preload) {
|
2836 |
if (!alt_gen->possible_success.is_linked()) return; |
2837 |
|
2838 |
RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
2839 |
macro_assembler->Bind(&alt_gen->possible_success); |
2840 |
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); |
2843 |
if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE);
|
2844 |
ZoneList<Guard*>* guards = alternative.guards(); |
2845 |
int guard_count = (guards == NULL) ? 0 : guards->length(); |
2846 |
if (next_expects_preload) {
|
2847 |
Label reload_current_char; |
2848 |
out_of_line_trace.set_backtrack(&reload_current_char); |
2849 |
for (int j = 0; j < guard_count; j++) { |
2850 |
GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace); |
2851 |
} |
2852 |
alternative.node()->Emit(compiler, &out_of_line_trace); |
2853 |
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.
|
2857 |
macro_assembler->LoadCurrentCharacter(trace->cp_offset(), |
2858 |
NULL,
|
2859 |
false,
|
2860 |
preload_characters); |
2861 |
macro_assembler->GoTo(&(alt_gen->after)); |
2862 |
} else {
|
2863 |
out_of_line_trace.set_backtrack(&(alt_gen->after)); |
2864 |
for (int j = 0; j < guard_count; j++) { |
2865 |
GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace); |
2866 |
} |
2867 |
alternative.node()->Emit(compiler, &out_of_line_trace); |
2868 |
} |
2869 |
} |
2870 |
|
2871 |
|
2872 |
void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
|
2873 |
RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
2874 |
LimitResult limit_result = LimitVersions(compiler, trace); |
2875 |
if (limit_result == DONE) return; |
2876 |
ASSERT(limit_result == CONTINUE); |
2877 |
|
2878 |
RecursionCheck rc(compiler); |
2879 |
|
2880 |
switch (type_) {
|
2881 |
case STORE_POSITION: {
|
2882 |
Trace::DeferredCapture |
2883 |
new_capture(data_.u_position_register.reg, |
2884 |
data_.u_position_register.is_capture, |
2885 |
trace); |
2886 |
Trace new_trace = *trace; |
2887 |
new_trace.add_action(&new_capture); |
2888 |
on_success()->Emit(compiler, &new_trace); |
2889 |
break;
|
2890 |
} |
2891 |
case INCREMENT_REGISTER: {
|
2892 |
Trace::DeferredIncrementRegister |
2893 |
new_increment(data_.u_increment_register.reg); |
2894 |
Trace new_trace = *trace; |
2895 |
new_trace.add_action(&new_increment); |
2896 |
on_success()->Emit(compiler, &new_trace); |
2897 |
break;
|
2898 |
} |
2899 |
case SET_REGISTER: {
|
2900 |
Trace::DeferredSetRegister |
2901 |
new_set(data_.u_store_register.reg, data_.u_store_register.value); |
2902 |
Trace new_trace = *trace; |
2903 |
new_trace.add_action(&new_set); |
2904 |
on_success()->Emit(compiler, &new_trace); |
2905 |
break;
|
2906 |
} |
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); |
2913 |
on_success()->Emit(compiler, &new_trace); |
2914 |
break;
|
2915 |
} |
2916 |
case BEGIN_SUBMATCH:
|
2917 |
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;
|
2927 |
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()); |
2937 |
} else if (know_dist && stored_pos < trace->cp_offset()) { |
2938 |
// If we know we've advanced we can generate the continuation
|
2939 |
// immediately.
|
2940 |
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); |
2957 |
} |
2958 |
break;
|
2959 |
} |
2960 |
case POSITIVE_SUBMATCH_SUCCESS: {
|
2961 |
if (!trace->is_trivial()) {
|
2962 |
trace->Flush(compiler, this);
|
2963 |
return;
|
2964 |
} |
2965 |
assembler->ReadCurrentPositionFromRegister( |
2966 |
data_.u_submatch.current_position_register); |
2967 |
assembler->ReadStackPointerFromRegister( |
2968 |
data_.u_submatch.stack_pointer_register); |
2969 |
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 |
} |
2988 |
default:
|
2989 |
UNREACHABLE(); |
2990 |
} |
2991 |
} |
2992 |
|
2993 |
|
2994 |
void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
|
2995 |
RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
2996 |
if (!trace->is_trivial()) {
|
2997 |
trace->Flush(compiler, this);
|
2998 |
return;
|
2999 |
} |
3000 |
|
3001 |
LimitResult limit_result = LimitVersions(compiler, trace); |
3002 |
if (limit_result == DONE) return; |
3003 |
ASSERT(limit_result == CONTINUE); |
3004 |
|
3005 |
RecursionCheck rc(compiler); |
3006 |
|
3007 |
ASSERT_EQ(start_reg_ + 1, end_reg_);
|
3008 |
if (compiler->ignore_case()) {
|
3009 |
assembler->CheckNotBackReferenceIgnoreCase(start_reg_, |
3010 |
trace->backtrack()); |
3011 |
} else {
|
3012 |
assembler->CheckNotBackReference(start_reg_, trace->backtrack()); |
3013 |
} |
3014 |
on_success()->Emit(compiler, trace); |
3015 |
} |
3016 |
|
3017 |
|
3018 |
// -------------------------------------------------------------------
|
3019 |
// Dot/dotty output
|
3020 |
|
3021 |
|
3022 |
#ifdef DEBUG
|
3023 |
|
3024 |
|
3025 |
class 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);
|
3032 |
void PrintAttributes(RegExpNode* from);
|
3033 |
StringStream* stream() { return &stream_; }
|
3034 |
void PrintOnFailure(RegExpNode* from, RegExpNode* to);
|
3035 |
#define DECLARE_VISIT(Type) \
|
3036 |
virtual void Visit##Type(Type##Node* that); |
3037 |
FOR_EACH_NODE_TYPE(DECLARE_VISIT) |
3038 |
#undef DECLARE_VISIT
|
3039 |
private:
|
3040 |
bool ignore_case_;
|
3041 |
HeapStringAllocator alloc_; |
3042 |
StringStream stream_; |
3043 |
}; |
3044 |
|
3045 |
|
3046 |
void 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 |
|
3068 |
void DotPrinter::Visit(RegExpNode* node) {
|
3069 |
if (node->info()->visited) return; |
3070 |
node->info()->visited = true;
|
3071 |
node->Accept(this);
|
3072 |
} |
3073 |
|
3074 |
|
3075 |
void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
|
3076 |
stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure);
|
3077 |
Visit(on_failure); |
3078 |
} |
3079 |
|
3080 |
|
3081 |
class 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 |
|
3105 |
class 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 |
|
3134 |
class 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 |
|
3161 |
void 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);
|
3170 |
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 |
|
3179 |
static const bool kPrintDispatchTable = false; |
3180 |
void 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); |
3189 |
} 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 |
|
3203 |
void 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()); |
3233 |
} |
3234 |
|
3235 |
|
3236 |
void 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()); |
3244 |
} |
3245 |
|
3246 |
|
3247 |
void DotPrinter::VisitEnd(EndNode* that) {
|
3248 |
stream()->Add(" n%p [style=bold, shape=point];\n", that);
|
3249 |
PrintAttributes(that); |
3250 |
} |
3251 |
|
3252 |
|
3253 |
void 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 |
|
3280 |
void DotPrinter::VisitAction(ActionNode* that) {
|
3281 |
stream()->Add(" n%p [", that);
|
3282 |
switch (that->type_) {
|
3283 |
case ActionNode::SET_REGISTER:
|
3284 |
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;
|
3296 |
case ActionNode::BEGIN_SUBMATCH:
|
3297 |
stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon",
|
3298 |
that->data_.u_submatch.current_position_register); |
3299 |
break;
|
3300 |
case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
|
3301 |
stream()->Add("label=\"escape\", shape=septagon");
|
3302 |
break;
|
3303 |
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 |
} |
3315 |
} |
3316 |
stream()->Add("];\n");
|
3317 |
PrintAttributes(that); |
3318 |
RegExpNode* successor = that->on_success(); |
3319 |
stream()->Add(" n%p -> n%p;\n", that, successor);
|
3320 |
Visit(successor); |
3321 |
} |
3322 |
|
3323 |
|
3324 |
class 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 |
|
3334 |
void 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 |
|
3352 |
void 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 |
|
3361 |
void 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 |
|
3375 |
static const int kSpaceRangeCount = 20; |
3376 |
static const int kSpaceRangeAsciiCount = 4; |
3377 |
static 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 |
|
3381 |
static const int kWordRangeCount = 8; |
3382 |
static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_', |
3383 |
'_', 'a', 'z' }; |
3384 |
|
3385 |
static const int kDigitRangeCount = 2; |
3386 |
static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' }; |
3387 |
|
3388 |
static const int kLineTerminatorRangeCount = 6; |
3389 |
static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A, |
3390 |
0x000A, 0x000D, 0x000D, 0x2028, 0x2029 }; |
3391 |
|
3392 |
RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler, |
3393 |
RegExpNode* on_success) { |
3394 |
ZoneList<TextElement>* elms = new ZoneList<TextElement>(1); |
3395 |
elms->Add(TextElement::Atom(this));
|
3396 |
return new TextNode(elms, on_success); |
3397 |
} |
3398 |
|
3399 |
|
3400 |
RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler, |
3401 |
RegExpNode* on_success) { |
3402 |
return new TextNode(elements(), on_success); |
3403 |
} |
3404 |
|
3405 |
static 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 |
|
3434 |
static 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 |
|
3450 |
bool 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 |
|
3476 |
|
3477 |
RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler, |
3478 |
RegExpNode* on_success) { |
3479 |
return new TextNode(this, on_success); |
3480 |
} |
3481 |
|
3482 |
|
3483 |
RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler, |
3484 |
RegExpNode* on_success) { |
3485 |
ZoneList<RegExpTree*>* alternatives = this->alternatives();
|
3486 |
int length = alternatives->length();
|
3487 |
ChoiceNode* result = new ChoiceNode(length);
|
3488 |
for (int i = 0; i < length; i++) { |
3489 |
GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler, |
3490 |
on_success)); |
3491 |
result->AddAlternative(alternative); |
3492 |
} |
3493 |
return result;
|
3494 |
} |
3495 |
|
3496 |
|
3497 |
RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler, |
3498 |
RegExpNode* on_success) { |
3499 |
return ToNode(min(),
|
3500 |
max(), |
3501 |
is_greedy(), |
3502 |
body(), |
3503 |
compiler, |
3504 |
on_success); |
3505 |
} |
3506 |
|
3507 |
|
3508 |
RegExpNode* RegExpQuantifier::ToNode(int min,
|
3509 |
int max,
|
3510 |
bool is_greedy,
|
3511 |
RegExpTree* body, |
3512 |
RegExpCompiler* compiler, |
3513 |
RegExpNode* on_success, |
3514 |
bool not_at_start) {
|
3515 |
// 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 |
//
|
3525 |
|
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. |
3538 |
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(); |
3544 |
} else if (FLAG_regexp_optimization && !needs_capture_clearing) { |
3545 |
// Only unroll if there are no captures and the body can't be
|
3546 |
// empty.
|
3547 |
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.
|
3550 |
RegExpNode* answer = ToNode( |
3551 |
0, new_max, is_greedy, body, compiler, on_success, true); |
3552 |
// 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; |
3576 |
if (not_at_start) alternation->set_not_at_start();
|
3577 |
} |
3578 |
return answer;
|
3579 |
} |
3580 |
} |
3581 |
bool has_min = min > 0; |
3582 |
bool has_max = max < RegExpTree::kInfinity;
|
3583 |
bool needs_counter = has_min || has_max;
|
3584 |
int reg_ctr = needs_counter
|
3585 |
? compiler->AllocateRegister() |
3586 |
: RegExpCompiler::kNoRegister; |
3587 |
LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0); |
3588 |
if (not_at_start) center->set_not_at_start();
|
3589 |
RegExpNode* loop_return = needs_counter |
3590 |
? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
|
3591 |
: static_cast<RegExpNode*>(center);
|
3592 |
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 |
} |
3600 |
RegExpNode* body_node = body->ToNode(compiler, loop_return); |
3601 |
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.
|
3604 |
body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
|
3605 |
} |
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 |
} |
3610 |
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) {
|
3621 |
center->AddLoopAlternative(body_alt); |
3622 |
center->AddContinueAlternative(rest_alt); |
3623 |
} else {
|
3624 |
center->AddContinueAlternative(rest_alt); |
3625 |
center->AddLoopAlternative(body_alt); |
3626 |
} |
3627 |
if (needs_counter) {
|
3628 |
return ActionNode::SetRegister(reg_ctr, 0, center); |
3629 |
} else {
|
3630 |
return center;
|
3631 |
} |
3632 |
} |
3633 |
|
3634 |
|
3635 |
RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler, |
3636 |
RegExpNode* on_success) { |
3637 |
NodeInfo info; |
3638 |
switch (type()) {
|
3639 |
case START_OF_LINE:
|
3640 |
return AssertionNode::AfterNewline(on_success);
|
3641 |
case START_OF_INPUT:
|
3642 |
return AssertionNode::AtStart(on_success);
|
3643 |
case BOUNDARY:
|
3644 |
return AssertionNode::AtBoundary(on_success);
|
3645 |
case NON_BOUNDARY:
|
3646 |
return AssertionNode::AtNonBoundary(on_success);
|
3647 |
case END_OF_INPUT:
|
3648 |
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(); |
3683 |
} |
3684 |
return on_success;
|
3685 |
} |
3686 |
|
3687 |
|
3688 |
RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler, |
3689 |
RegExpNode* on_success) { |
3690 |
return new BackReferenceNode(RegExpCapture::StartRegister(index()), |
3691 |
RegExpCapture::EndRegister(index()), |
3692 |
on_success); |
3693 |
} |
3694 |
|
3695 |
|
3696 |
RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler, |
3697 |
RegExpNode* on_success) { |
3698 |
return on_success;
|
3699 |
} |
3700 |
|
3701 |
|
3702 |
RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler, |
3703 |
RegExpNode* on_success) { |
3704 |
int stack_pointer_register = compiler->AllocateRegister();
|
3705 |
int position_register = compiler->AllocateRegister();
|
3706 |
|
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 |
|
3713 |
RegExpNode* success; |
3714 |
if (is_positive()) {
|
3715 |
RegExpNode* node = ActionNode::BeginSubmatch( |
3716 |
stack_pointer_register, |
3717 |
position_register, |
3718 |
body()->ToNode( |
3719 |
compiler, |
3720 |
ActionNode::PositiveSubmatchSuccess(stack_pointer_register, |
3721 |
position_register, |
3722 |
register_count, |
3723 |
register_start, |
3724 |
on_success))); |
3725 |
return node;
|
3726 |
} else {
|
3727 |
// 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
|
3734 |
// for a negative lookahead. The NegativeLookaheadChoiceNode is a special
|
3735 |
// ChoiceNode that knows to ignore the first exit when calculating quick
|
3736 |
// checks.
|
3737 |
GuardedAlternative body_alt( |
3738 |
body()->ToNode( |
3739 |
compiler, |
3740 |
success = new NegativeSubmatchSuccess(stack_pointer_register,
|
3741 |
position_register, |
3742 |
register_count, |
3743 |
register_start))); |
3744 |
ChoiceNode* choice_node = |
3745 |
new NegativeLookaheadChoiceNode(body_alt,
|
3746 |
GuardedAlternative(on_success)); |
3747 |
return ActionNode::BeginSubmatch(stack_pointer_register,
|
3748 |
position_register, |
3749 |
choice_node); |
3750 |
} |
3751 |
} |
3752 |
|
3753 |
|
3754 |
RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler, |
3755 |
RegExpNode* on_success) { |
3756 |
return ToNode(body(), index(), compiler, on_success);
|
3757 |
} |
3758 |
|
3759 |
|
3760 |
RegExpNode* RegExpCapture::ToNode(RegExpTree* body, |
3761 |
int index,
|
3762 |
RegExpCompiler* compiler, |
3763 |
RegExpNode* on_success) { |
3764 |
int start_reg = RegExpCapture::StartRegister(index);
|
3765 |
int end_reg = RegExpCapture::EndRegister(index);
|
3766 |
RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
|
3767 |
RegExpNode* body_node = body->ToNode(compiler, store_end); |
3768 |
return ActionNode::StorePosition(start_reg, true, body_node); |
3769 |
} |
3770 |
|
3771 |
|
3772 |
RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler, |
3773 |
RegExpNode* on_success) { |
3774 |
ZoneList<RegExpTree*>* children = nodes(); |
3775 |
RegExpNode* current = on_success; |
3776 |
for (int i = children->length() - 1; i >= 0; i--) { |
3777 |
current = children->at(i)->ToNode(compiler, current); |
3778 |
} |
3779 |
return current;
|
3780 |
} |
3781 |
|
3782 |
|
3783 |
static 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 |
|
3793 |
static void AddClassNegated(const uc16 *elmv, |
3794 |
int elmc,
|
3795 |
ZoneList<CharacterRange>* ranges) { |
3796 |
ASSERT(elmv[0] != 0x0000); |
3797 |
ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode);
|
3798 |
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 |
} |
3805 |
ranges->Add(CharacterRange(last, String::kMaxUC16CharCode)); |
3806 |
} |
3807 |
|
3808 |
|
3809 |
void 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;
|
3841 |
// 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;
|
3848 |
default:
|
3849 |
UNREACHABLE(); |
3850 |
} |
3851 |
} |
3852 |
|
3853 |
|
3854 |
Vector<const uc16> CharacterRange::GetWordBounds() {
|
3855 |
return Vector<const uc16>(kWordRanges, kWordRangeCount); |
3856 |
} |
3857 |
|
3858 |
|
3859 |
class 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 |
|
3876 |
void 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 |
|
3886 |
void 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 |
|
3904 |
void 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 |
|
3985 |
ZoneList<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 |
|
3995 |
// -------------------------------------------------------------------
|
3996 |
// Interest propagation
|
3997 |
|
3998 |
|
3999 |
RegExpNode* 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 |
|
4009 |
RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) {
|
4010 |
ASSERT_EQ(false, *cloned);
|
4011 |
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 |
|
4024 |
template <class C> |
4025 |
static 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 |
|
4033 |
// -------------------------------------------------------------------
|
4034 |
// Splay tree
|
4035 |
|
4036 |
|
4037 |
OutSet* 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 |
|
4056 |
void 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 |
|
4068 |
bool 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 |
|
4079 |
const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
|
4080 |
const DispatchTable::Entry DispatchTable::Config::kNoValue;
|
4081 |
|
4082 |
|
4083 |
void 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.
|
4153 |
if (entry->to() == String::kMaxUC16CharCode)
|
4154 |
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 |
|
4170 |
OutSet* 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 |
|
4186 |
void Analysis::EnsureAnalyzed(RegExpNode* that) {
|
4187 |
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 |
|
4196 |
void Analysis::VisitEnd(EndNode* that) {
|
4197 |
// nothing to do
|
4198 |
} |
4199 |
|
4200 |
|
4201 |
void 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 |
|
4219 |
void Analysis::VisitText(TextNode* that) {
|
4220 |
if (ignore_case_) {
|
4221 |
that->MakeCaseIndependent(); |
4222 |
} |
4223 |
EnsureAnalyzed(that->on_success()); |
4224 |
that->CalculateOffsets(); |
4225 |
} |
4226 |
|
4227 |
|
4228 |
void Analysis::VisitAction(ActionNode* that) {
|
4229 |
RegExpNode* target = that->on_success(); |
4230 |
EnsureAnalyzed(target); |
4231 |
// 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.
|
4233 |
that->info()->AddFromFollowing(target->info()); |
4234 |
} |
4235 |
|
4236 |
|
4237 |
void Analysis::VisitChoice(ChoiceNode* that) {
|
4238 |
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 |
} |
4246 |
} |
4247 |
|
4248 |
|
4249 |
void 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 |
|
4265 |
void Analysis::VisitBackReference(BackReferenceNode* that) {
|
4266 |
EnsureAnalyzed(that->on_success()); |
4267 |
} |
4268 |
|
4269 |
|
4270 |
void Analysis::VisitAssertion(AssertionNode* that) {
|
4271 |
EnsureAnalyzed(that->on_success()); |
4272 |
} |
4273 |
|
4274 |
|
4275 |
// -------------------------------------------------------------------
|
4276 |
// Dispatch table construction
|
4277 |
|
4278 |
|
4279 |
void DispatchTableConstructor::VisitEnd(EndNode* that) {
|
4280 |
AddRange(CharacterRange::Everything()); |
4281 |
} |
4282 |
|
4283 |
|
4284 |
void 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 |
|
4295 |
class 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 |
|
4305 |
void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
|
4306 |
CharacterRange range(from, entry.to()); |
4307 |
constructor_->AddRange(range); |
4308 |
} |
4309 |
|
4310 |
|
4311 |
void 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 |
|
4320 |
void 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 |
|
4327 |
void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
|
4328 |
RegExpNode* target = that->on_success(); |
4329 |
target->Accept(this);
|
4330 |
} |
4331 |
|
4332 |
|
4333 |
|
4334 |
static int CompareRangeByFrom(const CharacterRange* a, |
4335 |
const CharacterRange* b) {
|
4336 |
return Compare<uc16>(a->from(), b->from());
|
4337 |
} |
4338 |
|
4339 |
|
4340 |
void 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) {
|
4348 |
if (range.to() == String::kMaxUC16CharCode) {
|
4349 |
return;
|
4350 |
} else {
|
4351 |
last = range.to() + 1;
|
4352 |
} |
4353 |
} |
4354 |
} |
4355 |
AddRange(CharacterRange(last, String::kMaxUC16CharCode)); |
4356 |
} |
4357 |
|
4358 |
|
4359 |
void 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 |
|
4385 |
void DispatchTableConstructor::VisitAction(ActionNode* that) {
|
4386 |
RegExpNode* target = that->on_success(); |
4387 |
target->Accept(this);
|
4388 |
} |
4389 |
|
4390 |
|
4391 |
RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data, |
4392 |
bool ignore_case,
|
4393 |
bool is_multiline,
|
4394 |
Handle<String> pattern, |
4395 |
bool is_ascii) {
|
4396 |
if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) { |
4397 |
return IrregexpRegExpTooBig();
|
4398 |
} |
4399 |
RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii); |
4400 |
// Wrap the body of the regexp in capture #0.
|
4401 |
RegExpNode* captured_body = RegExpCapture::ToNode(data->tree, |
4402 |
0,
|
4403 |
&compiler, |
4404 |
compiler.accept()); |
4405 |
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.
|
4409 |
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 |
} |
4429 |
} |
4430 |
data->node = node; |
4431 |
Analysis analysis(ignore_case); |
4432 |
analysis.EnsureAnalyzed(node); |
4433 |
|
4434 |
NodeInfo info = *node->info(); |
4435 |
|
4436 |
if (RegExpImpl::UseNativeRegexp()) {
|
4437 |
#ifdef ARM
|
4438 |
UNREACHABLE(); |
4439 |
#else // IA32 |
4440 |
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); |
4448 |
return compiler.Assemble(¯o_assembler,
|
4449 |
node, |
4450 |
data->capture_count, |
4451 |
pattern); |
4452 |
#endif
|
4453 |
} |
4454 |
EmbeddedVector<byte, 1024> codes;
|
4455 |
RegExpMacroAssemblerIrregexp macro_assembler(codes); |
4456 |
return compiler.Assemble(¯o_assembler,
|
4457 |
node, |
4458 |
data->capture_count, |
4459 |
pattern); |
4460 |
} |
4461 |
|
4462 |
|
4463 |
}} // namespace v8::internal
|