Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 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 "compiler.h" |
| 32 | #include "execution.h" |
| 33 | #include "factory.h" |
| 34 | #include "jsregexp.h" |
| 35 | #include "platform.h" |
| 36 | #include "runtime.h" |
| 37 | #include "top.h" |
| 38 | #include "compilation-cache.h" |
| 39 | #include "string-stream.h" |
| 40 | #include "parser.h" |
| 41 | #include "regexp-macro-assembler.h" |
| 42 | #include "regexp-macro-assembler-tracer.h" |
| 43 | #include "regexp-macro-assembler-irregexp.h" |
| 44 | #include "regexp-stack.h" |
| 45 | |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 46 | #ifndef V8_INTERPRETED_REGEXP |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 47 | #if V8_TARGET_ARCH_IA32 |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 48 | #include "ia32/regexp-macro-assembler-ia32.h" |
| 49 | #elif V8_TARGET_ARCH_X64 |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 50 | #include "x64/regexp-macro-assembler-x64.h" |
| 51 | #elif V8_TARGET_ARCH_ARM |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 52 | #include "arm/regexp-macro-assembler-arm.h" |
| 53 | #else |
| 54 | #error Unsupported target architecture. |
| 55 | #endif |
| 56 | #endif |
| 57 | |
| 58 | #include "interpreter-irregexp.h" |
| 59 | |
| 60 | |
| 61 | namespace v8 { |
| 62 | namespace internal { |
| 63 | |
| 64 | |
| 65 | Handle<Object> RegExpImpl::CreateRegExpLiteral(Handle<JSFunction> constructor, |
| 66 | Handle<String> pattern, |
| 67 | Handle<String> flags, |
| 68 | bool* has_pending_exception) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 69 | // Call the construct code with 2 arguments. |
| 70 | Object** argv[2] = { Handle<Object>::cast(pattern).location(), |
| 71 | Handle<Object>::cast(flags).location() }; |
| 72 | return Execution::New(constructor, 2, argv, has_pending_exception); |
| 73 | } |
| 74 | |
| 75 | |
| 76 | static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) { |
| 77 | int flags = JSRegExp::NONE; |
| 78 | for (int i = 0; i < str->length(); i++) { |
| 79 | switch (str->Get(i)) { |
| 80 | case 'i': |
| 81 | flags |= JSRegExp::IGNORE_CASE; |
| 82 | break; |
| 83 | case 'g': |
| 84 | flags |= JSRegExp::GLOBAL; |
| 85 | break; |
| 86 | case 'm': |
| 87 | flags |= JSRegExp::MULTILINE; |
| 88 | break; |
| 89 | } |
| 90 | } |
| 91 | return JSRegExp::Flags(flags); |
| 92 | } |
| 93 | |
| 94 | |
| 95 | static inline void ThrowRegExpException(Handle<JSRegExp> re, |
| 96 | Handle<String> pattern, |
| 97 | Handle<String> error_text, |
| 98 | const char* message) { |
| 99 | Handle<JSArray> array = Factory::NewJSArray(2); |
| 100 | SetElement(array, 0, pattern); |
| 101 | SetElement(array, 1, error_text); |
| 102 | Handle<Object> regexp_err = Factory::NewSyntaxError(message, array); |
| 103 | Top::Throw(*regexp_err); |
| 104 | } |
| 105 | |
| 106 | |
| 107 | // Generic RegExp methods. Dispatches to implementation specific methods. |
| 108 | |
| 109 | |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 110 | Handle<Object> RegExpImpl::Compile(Handle<JSRegExp> re, |
| 111 | Handle<String> pattern, |
| 112 | Handle<String> flag_str) { |
| 113 | JSRegExp::Flags flags = RegExpFlagsFromString(flag_str); |
| 114 | Handle<FixedArray> cached = CompilationCache::LookupRegExp(pattern, flags); |
| 115 | bool in_cache = !cached.is_null(); |
| 116 | LOG(RegExpCompileEvent(re, in_cache)); |
| 117 | |
| 118 | Handle<Object> result; |
| 119 | if (in_cache) { |
| 120 | re->set_data(*cached); |
| 121 | return re; |
| 122 | } |
| 123 | FlattenString(pattern); |
| 124 | CompilationZoneScope zone_scope(DELETE_ON_EXIT); |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 125 | PostponeInterruptsScope postpone; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 126 | RegExpCompileData parse_result; |
| 127 | FlatStringReader reader(pattern); |
| 128 | if (!ParseRegExp(&reader, flags.is_multiline(), &parse_result)) { |
| 129 | // Throw an exception if we fail to parse the pattern. |
| 130 | ThrowRegExpException(re, |
| 131 | pattern, |
| 132 | parse_result.error, |
| 133 | "malformed_regexp"); |
| 134 | return Handle<Object>::null(); |
| 135 | } |
| 136 | |
| 137 | if (parse_result.simple && !flags.is_ignore_case()) { |
| 138 | // Parse-tree is a single atom that is equal to the pattern. |
| 139 | AtomCompile(re, pattern, flags, pattern); |
| 140 | } else if (parse_result.tree->IsAtom() && |
| 141 | !flags.is_ignore_case() && |
| 142 | parse_result.capture_count == 0) { |
| 143 | RegExpAtom* atom = parse_result.tree->AsAtom(); |
| 144 | Vector<const uc16> atom_pattern = atom->data(); |
| 145 | Handle<String> atom_string = Factory::NewStringFromTwoByte(atom_pattern); |
| 146 | AtomCompile(re, pattern, flags, atom_string); |
| 147 | } else { |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 148 | IrregexpInitialize(re, pattern, flags, parse_result.capture_count); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 149 | } |
| 150 | ASSERT(re->data()->IsFixedArray()); |
| 151 | // Compilation succeeded so the data is set on the regexp |
| 152 | // and we can store it in the cache. |
| 153 | Handle<FixedArray> data(FixedArray::cast(re->data())); |
| 154 | CompilationCache::PutRegExp(pattern, flags, data); |
| 155 | |
| 156 | return re; |
| 157 | } |
| 158 | |
| 159 | |
| 160 | Handle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp, |
| 161 | Handle<String> subject, |
| 162 | int index, |
| 163 | Handle<JSArray> last_match_info) { |
| 164 | switch (regexp->TypeTag()) { |
| 165 | case JSRegExp::ATOM: |
| 166 | return AtomExec(regexp, subject, index, last_match_info); |
| 167 | case JSRegExp::IRREGEXP: { |
| 168 | Handle<Object> result = |
| 169 | IrregexpExec(regexp, subject, index, last_match_info); |
| 170 | ASSERT(!result.is_null() || Top::has_pending_exception()); |
| 171 | return result; |
| 172 | } |
| 173 | default: |
| 174 | UNREACHABLE(); |
| 175 | return Handle<Object>::null(); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | |
| 180 | // RegExp Atom implementation: Simple string search using indexOf. |
| 181 | |
| 182 | |
| 183 | void RegExpImpl::AtomCompile(Handle<JSRegExp> re, |
| 184 | Handle<String> pattern, |
| 185 | JSRegExp::Flags flags, |
| 186 | Handle<String> match_pattern) { |
| 187 | Factory::SetRegExpAtomData(re, |
| 188 | JSRegExp::ATOM, |
| 189 | pattern, |
| 190 | flags, |
| 191 | match_pattern); |
| 192 | } |
| 193 | |
| 194 | |
| 195 | static void SetAtomLastCapture(FixedArray* array, |
| 196 | String* subject, |
| 197 | int from, |
| 198 | int to) { |
| 199 | NoHandleAllocation no_handles; |
| 200 | RegExpImpl::SetLastCaptureCount(array, 2); |
| 201 | RegExpImpl::SetLastSubject(array, subject); |
| 202 | RegExpImpl::SetLastInput(array, subject); |
| 203 | RegExpImpl::SetCapture(array, 0, from); |
| 204 | RegExpImpl::SetCapture(array, 1, to); |
| 205 | } |
| 206 | |
| 207 | |
| 208 | Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re, |
| 209 | Handle<String> subject, |
| 210 | int index, |
| 211 | Handle<JSArray> last_match_info) { |
| 212 | Handle<String> needle(String::cast(re->DataAt(JSRegExp::kAtomPatternIndex))); |
| 213 | |
| 214 | uint32_t start_index = index; |
| 215 | |
| 216 | int value = Runtime::StringMatch(subject, needle, start_index); |
| 217 | if (value == -1) return Factory::null_value(); |
| 218 | ASSERT(last_match_info->HasFastElements()); |
| 219 | |
| 220 | { |
| 221 | NoHandleAllocation no_handles; |
| 222 | FixedArray* array = FixedArray::cast(last_match_info->elements()); |
| 223 | SetAtomLastCapture(array, *subject, value, value + needle->length()); |
| 224 | } |
| 225 | return last_match_info; |
| 226 | } |
| 227 | |
| 228 | |
| 229 | // Irregexp implementation. |
| 230 | |
| 231 | // Ensures that the regexp object contains a compiled version of the |
| 232 | // source for either ASCII or non-ASCII strings. |
| 233 | // If the compiled version doesn't already exist, it is compiled |
| 234 | // from the source pattern. |
| 235 | // If compilation fails, an exception is thrown and this function |
| 236 | // returns false. |
| 237 | bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re, bool is_ascii) { |
| 238 | Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii)); |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 239 | #ifdef V8_INTERPRETED_REGEXP |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 240 | if (compiled_code->IsByteArray()) return true; |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 241 | #else // V8_INTERPRETED_REGEXP (RegExp native code) |
| 242 | if (compiled_code->IsCode()) return true; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 243 | #endif |
| 244 | return CompileIrregexp(re, is_ascii); |
| 245 | } |
| 246 | |
| 247 | |
| 248 | bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re, bool is_ascii) { |
| 249 | // Compile the RegExp. |
| 250 | CompilationZoneScope zone_scope(DELETE_ON_EXIT); |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 251 | PostponeInterruptsScope postpone; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 252 | Object* entry = re->DataAt(JSRegExp::code_index(is_ascii)); |
| 253 | if (entry->IsJSObject()) { |
| 254 | // If it's a JSObject, a previous compilation failed and threw this object. |
| 255 | // Re-throw the object without trying again. |
| 256 | Top::Throw(entry); |
| 257 | return false; |
| 258 | } |
| 259 | ASSERT(entry->IsTheHole()); |
| 260 | |
| 261 | JSRegExp::Flags flags = re->GetFlags(); |
| 262 | |
| 263 | Handle<String> pattern(re->Pattern()); |
| 264 | if (!pattern->IsFlat()) { |
| 265 | FlattenString(pattern); |
| 266 | } |
| 267 | |
| 268 | RegExpCompileData compile_data; |
| 269 | FlatStringReader reader(pattern); |
| 270 | if (!ParseRegExp(&reader, flags.is_multiline(), &compile_data)) { |
| 271 | // Throw an exception if we fail to parse the pattern. |
| 272 | // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once. |
| 273 | ThrowRegExpException(re, |
| 274 | pattern, |
| 275 | compile_data.error, |
| 276 | "malformed_regexp"); |
| 277 | return false; |
| 278 | } |
| 279 | RegExpEngine::CompilationResult result = |
| 280 | RegExpEngine::Compile(&compile_data, |
| 281 | flags.is_ignore_case(), |
| 282 | flags.is_multiline(), |
| 283 | pattern, |
| 284 | is_ascii); |
| 285 | if (result.error_message != NULL) { |
| 286 | // Unable to compile regexp. |
| 287 | Handle<JSArray> array = Factory::NewJSArray(2); |
| 288 | SetElement(array, 0, pattern); |
| 289 | SetElement(array, |
| 290 | 1, |
| 291 | Factory::NewStringFromUtf8(CStrVector(result.error_message))); |
| 292 | Handle<Object> regexp_err = |
| 293 | Factory::NewSyntaxError("malformed_regexp", array); |
| 294 | Top::Throw(*regexp_err); |
| 295 | re->SetDataAt(JSRegExp::code_index(is_ascii), *regexp_err); |
| 296 | return false; |
| 297 | } |
| 298 | |
| 299 | Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data())); |
| 300 | data->set(JSRegExp::code_index(is_ascii), result.code); |
| 301 | int register_max = IrregexpMaxRegisterCount(*data); |
| 302 | if (result.num_registers > register_max) { |
| 303 | SetIrregexpMaxRegisterCount(*data, result.num_registers); |
| 304 | } |
| 305 | |
| 306 | return true; |
| 307 | } |
| 308 | |
| 309 | |
| 310 | int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) { |
| 311 | return Smi::cast( |
| 312 | re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value(); |
| 313 | } |
| 314 | |
| 315 | |
| 316 | void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) { |
| 317 | re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value)); |
| 318 | } |
| 319 | |
| 320 | |
| 321 | int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) { |
| 322 | return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value(); |
| 323 | } |
| 324 | |
| 325 | |
| 326 | int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) { |
| 327 | return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value(); |
| 328 | } |
| 329 | |
| 330 | |
| 331 | ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) { |
| 332 | return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii))); |
| 333 | } |
| 334 | |
| 335 | |
| 336 | Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) { |
| 337 | return Code::cast(re->get(JSRegExp::code_index(is_ascii))); |
| 338 | } |
| 339 | |
| 340 | |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 341 | void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re, |
| 342 | Handle<String> pattern, |
| 343 | JSRegExp::Flags flags, |
| 344 | int capture_count) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 345 | // Initialize compiled code entries to null. |
| 346 | Factory::SetRegExpIrregexpData(re, |
| 347 | JSRegExp::IRREGEXP, |
| 348 | pattern, |
| 349 | flags, |
| 350 | capture_count); |
| 351 | } |
| 352 | |
| 353 | |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 354 | int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp, |
| 355 | Handle<String> subject) { |
| 356 | if (!subject->IsFlat()) { |
| 357 | FlattenString(subject); |
| 358 | } |
Steve Block | 8defd9f | 2010-07-08 12:39:36 +0100 | [diff] [blame] | 359 | // Check the asciiness of the underlying storage. |
| 360 | bool is_ascii; |
| 361 | { |
| 362 | AssertNoAllocation no_gc; |
| 363 | String* sequential_string = *subject; |
| 364 | if (subject->IsConsString()) { |
| 365 | sequential_string = ConsString::cast(*subject)->first(); |
| 366 | } |
| 367 | is_ascii = sequential_string->IsAsciiRepresentation(); |
| 368 | } |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 369 | if (!EnsureCompiledIrregexp(regexp, is_ascii)) { |
| 370 | return -1; |
| 371 | } |
| 372 | #ifdef V8_INTERPRETED_REGEXP |
| 373 | // Byte-code regexp needs space allocated for all its registers. |
| 374 | return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data())); |
| 375 | #else // V8_INTERPRETED_REGEXP |
| 376 | // Native regexp only needs room to output captures. Registers are handled |
| 377 | // internally. |
| 378 | return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2; |
| 379 | #endif // V8_INTERPRETED_REGEXP |
| 380 | } |
| 381 | |
| 382 | |
| 383 | RegExpImpl::IrregexpResult RegExpImpl::IrregexpExecOnce(Handle<JSRegExp> regexp, |
| 384 | Handle<String> subject, |
| 385 | int index, |
| 386 | Vector<int> output) { |
| 387 | Handle<FixedArray> irregexp(FixedArray::cast(regexp->data())); |
| 388 | |
| 389 | ASSERT(index >= 0); |
| 390 | ASSERT(index <= subject->length()); |
| 391 | ASSERT(subject->IsFlat()); |
| 392 | |
Steve Block | 8defd9f | 2010-07-08 12:39:36 +0100 | [diff] [blame] | 393 | // A flat ASCII string might have a two-byte first part. |
| 394 | if (subject->IsConsString()) { |
| 395 | subject = Handle<String>(ConsString::cast(*subject)->first()); |
| 396 | } |
| 397 | |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 398 | #ifndef V8_INTERPRETED_REGEXP |
| 399 | ASSERT(output.length() >= |
| 400 | (IrregexpNumberOfCaptures(*irregexp) + 1) * 2); |
| 401 | do { |
| 402 | bool is_ascii = subject->IsAsciiRepresentation(); |
| 403 | Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii)); |
| 404 | NativeRegExpMacroAssembler::Result res = |
| 405 | NativeRegExpMacroAssembler::Match(code, |
| 406 | subject, |
| 407 | output.start(), |
| 408 | output.length(), |
| 409 | index); |
| 410 | if (res != NativeRegExpMacroAssembler::RETRY) { |
| 411 | ASSERT(res != NativeRegExpMacroAssembler::EXCEPTION || |
| 412 | Top::has_pending_exception()); |
| 413 | STATIC_ASSERT( |
| 414 | static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS); |
| 415 | STATIC_ASSERT( |
| 416 | static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE); |
| 417 | STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION) |
| 418 | == RE_EXCEPTION); |
| 419 | return static_cast<IrregexpResult>(res); |
| 420 | } |
| 421 | // If result is RETRY, the string has changed representation, and we |
| 422 | // must restart from scratch. |
| 423 | // In this case, it means we must make sure we are prepared to handle |
Steve Block | 8defd9f | 2010-07-08 12:39:36 +0100 | [diff] [blame] | 424 | // the, potentially, different subject (the string can switch between |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 425 | // being internal and external, and even between being ASCII and UC16, |
| 426 | // but the characters are always the same). |
| 427 | IrregexpPrepare(regexp, subject); |
| 428 | } while (true); |
| 429 | UNREACHABLE(); |
| 430 | return RE_EXCEPTION; |
| 431 | #else // V8_INTERPRETED_REGEXP |
| 432 | |
| 433 | ASSERT(output.length() >= IrregexpNumberOfRegisters(*irregexp)); |
| 434 | bool is_ascii = subject->IsAsciiRepresentation(); |
| 435 | // We must have done EnsureCompiledIrregexp, so we can get the number of |
| 436 | // registers. |
| 437 | int* register_vector = output.start(); |
| 438 | int number_of_capture_registers = |
| 439 | (IrregexpNumberOfCaptures(*irregexp) + 1) * 2; |
| 440 | for (int i = number_of_capture_registers - 1; i >= 0; i--) { |
| 441 | register_vector[i] = -1; |
| 442 | } |
| 443 | Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii)); |
| 444 | |
| 445 | if (IrregexpInterpreter::Match(byte_codes, |
| 446 | subject, |
| 447 | register_vector, |
| 448 | index)) { |
| 449 | return RE_SUCCESS; |
| 450 | } |
| 451 | return RE_FAILURE; |
| 452 | #endif // V8_INTERPRETED_REGEXP |
| 453 | } |
| 454 | |
| 455 | |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 456 | Handle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> jsregexp, |
| 457 | Handle<String> subject, |
| 458 | int previous_index, |
| 459 | Handle<JSArray> last_match_info) { |
| 460 | ASSERT_EQ(jsregexp->TypeTag(), JSRegExp::IRREGEXP); |
| 461 | |
| 462 | // Prepare space for the return values. |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 463 | #ifdef V8_INTERPRETED_REGEXP |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 464 | #ifdef DEBUG |
| 465 | if (FLAG_trace_regexp_bytecodes) { |
| 466 | String* pattern = jsregexp->Pattern(); |
| 467 | PrintF("\n\nRegexp match: /%s/\n\n", *(pattern->ToCString())); |
| 468 | PrintF("\n\nSubject string: '%s'\n\n", *(subject->ToCString())); |
| 469 | } |
| 470 | #endif |
| 471 | #endif |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 472 | int required_registers = RegExpImpl::IrregexpPrepare(jsregexp, subject); |
| 473 | if (required_registers < 0) { |
| 474 | // Compiling failed with an exception. |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 475 | ASSERT(Top::has_pending_exception()); |
| 476 | return Handle<Object>::null(); |
| 477 | } |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 478 | |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 479 | OffsetsVector registers(required_registers); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 480 | |
Iain Merrick | 7568138 | 2010-08-19 15:07:18 +0100 | [diff] [blame^] | 481 | IrregexpResult res = RegExpImpl::IrregexpExecOnce( |
| 482 | jsregexp, subject, previous_index, Vector<int>(registers.vector(), |
| 483 | registers.length())); |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 484 | if (res == RE_SUCCESS) { |
| 485 | int capture_register_count = |
| 486 | (IrregexpNumberOfCaptures(FixedArray::cast(jsregexp->data())) + 1) * 2; |
| 487 | last_match_info->EnsureSize(capture_register_count + kLastMatchOverhead); |
| 488 | AssertNoAllocation no_gc; |
| 489 | int* register_vector = registers.vector(); |
| 490 | FixedArray* array = FixedArray::cast(last_match_info->elements()); |
| 491 | for (int i = 0; i < capture_register_count; i += 2) { |
| 492 | SetCapture(array, i, register_vector[i]); |
| 493 | SetCapture(array, i + 1, register_vector[i + 1]); |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 494 | } |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 495 | SetLastCaptureCount(array, capture_register_count); |
| 496 | SetLastSubject(array, *subject); |
| 497 | SetLastInput(array, *subject); |
| 498 | return last_match_info; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 499 | } |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 500 | if (res == RE_EXCEPTION) { |
| 501 | ASSERT(Top::has_pending_exception()); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 502 | return Handle<Object>::null(); |
| 503 | } |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 504 | ASSERT(res == RE_FAILURE); |
| 505 | return Factory::null_value(); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 506 | } |
| 507 | |
| 508 | |
| 509 | // ------------------------------------------------------------------- |
| 510 | // Implementation of the Irregexp regular expression engine. |
| 511 | // |
| 512 | // The Irregexp regular expression engine is intended to be a complete |
| 513 | // implementation of ECMAScript regular expressions. It generates either |
| 514 | // bytecodes or native code. |
| 515 | |
| 516 | // The Irregexp regexp engine is structured in three steps. |
| 517 | // 1) The parser generates an abstract syntax tree. See ast.cc. |
| 518 | // 2) From the AST a node network is created. The nodes are all |
| 519 | // subclasses of RegExpNode. The nodes represent states when |
| 520 | // executing a regular expression. Several optimizations are |
| 521 | // performed on the node network. |
| 522 | // 3) From the nodes we generate either byte codes or native code |
| 523 | // that can actually execute the regular expression (perform |
| 524 | // the search). The code generation step is described in more |
| 525 | // detail below. |
| 526 | |
| 527 | // Code generation. |
| 528 | // |
| 529 | // The nodes are divided into four main categories. |
| 530 | // * Choice nodes |
| 531 | // These represent places where the regular expression can |
| 532 | // match in more than one way. For example on entry to an |
| 533 | // alternation (foo|bar) or a repetition (*, +, ? or {}). |
| 534 | // * Action nodes |
| 535 | // These represent places where some action should be |
| 536 | // performed. Examples include recording the current position |
| 537 | // in the input string to a register (in order to implement |
| 538 | // captures) or other actions on register for example in order |
| 539 | // to implement the counters needed for {} repetitions. |
| 540 | // * Matching nodes |
| 541 | // These attempt to match some element part of the input string. |
| 542 | // Examples of elements include character classes, plain strings |
| 543 | // or back references. |
| 544 | // * End nodes |
| 545 | // These are used to implement the actions required on finding |
| 546 | // a successful match or failing to find a match. |
| 547 | // |
| 548 | // The code generated (whether as byte codes or native code) maintains |
| 549 | // some state as it runs. This consists of the following elements: |
| 550 | // |
| 551 | // * The capture registers. Used for string captures. |
| 552 | // * Other registers. Used for counters etc. |
| 553 | // * The current position. |
| 554 | // * The stack of backtracking information. Used when a matching node |
| 555 | // fails to find a match and needs to try an alternative. |
| 556 | // |
| 557 | // Conceptual regular expression execution model: |
| 558 | // |
| 559 | // There is a simple conceptual model of regular expression execution |
| 560 | // which will be presented first. The actual code generated is a more |
| 561 | // efficient simulation of the simple conceptual model: |
| 562 | // |
| 563 | // * Choice nodes are implemented as follows: |
| 564 | // For each choice except the last { |
| 565 | // push current position |
| 566 | // push backtrack code location |
| 567 | // <generate code to test for choice> |
| 568 | // backtrack code location: |
| 569 | // pop current position |
| 570 | // } |
| 571 | // <generate code to test for last choice> |
| 572 | // |
| 573 | // * Actions nodes are generated as follows |
| 574 | // <push affected registers on backtrack stack> |
| 575 | // <generate code to perform action> |
| 576 | // push backtrack code location |
| 577 | // <generate code to test for following nodes> |
| 578 | // backtrack code location: |
| 579 | // <pop affected registers to restore their state> |
| 580 | // <pop backtrack location from stack and go to it> |
| 581 | // |
| 582 | // * Matching nodes are generated as follows: |
| 583 | // if input string matches at current position |
| 584 | // update current position |
| 585 | // <generate code to test for following nodes> |
| 586 | // else |
| 587 | // <pop backtrack location from stack and go to it> |
| 588 | // |
| 589 | // Thus it can be seen that the current position is saved and restored |
| 590 | // by the choice nodes, whereas the registers are saved and restored by |
| 591 | // by the action nodes that manipulate them. |
| 592 | // |
| 593 | // The other interesting aspect of this model is that nodes are generated |
| 594 | // at the point where they are needed by a recursive call to Emit(). If |
| 595 | // the node has already been code generated then the Emit() call will |
| 596 | // generate a jump to the previously generated code instead. In order to |
| 597 | // limit recursion it is possible for the Emit() function to put the node |
| 598 | // on a work list for later generation and instead generate a jump. The |
| 599 | // destination of the jump is resolved later when the code is generated. |
| 600 | // |
| 601 | // Actual regular expression code generation. |
| 602 | // |
| 603 | // Code generation is actually more complicated than the above. In order |
| 604 | // to improve the efficiency of the generated code some optimizations are |
| 605 | // performed |
| 606 | // |
| 607 | // * Choice nodes have 1-character lookahead. |
| 608 | // A choice node looks at the following character and eliminates some of |
| 609 | // the choices immediately based on that character. This is not yet |
| 610 | // implemented. |
| 611 | // * Simple greedy loops store reduced backtracking information. |
| 612 | // A quantifier like /.*foo/m will greedily match the whole input. It will |
| 613 | // then need to backtrack to a point where it can match "foo". The naive |
| 614 | // implementation of this would push each character position onto the |
| 615 | // backtracking stack, then pop them off one by one. This would use space |
| 616 | // proportional to the length of the input string. However since the "." |
| 617 | // can only match in one way and always has a constant length (in this case |
| 618 | // of 1) it suffices to store the current position on the top of the stack |
| 619 | // once. Matching now becomes merely incrementing the current position and |
| 620 | // backtracking becomes decrementing the current position and checking the |
| 621 | // result against the stored current position. This is faster and saves |
| 622 | // space. |
| 623 | // * The current state is virtualized. |
| 624 | // This is used to defer expensive operations until it is clear that they |
| 625 | // are needed and to generate code for a node more than once, allowing |
| 626 | // specialized an efficient versions of the code to be created. This is |
| 627 | // explained in the section below. |
| 628 | // |
| 629 | // Execution state virtualization. |
| 630 | // |
| 631 | // Instead of emitting code, nodes that manipulate the state can record their |
| 632 | // manipulation in an object called the Trace. The Trace object can record a |
| 633 | // current position offset, an optional backtrack code location on the top of |
| 634 | // the virtualized backtrack stack and some register changes. When a node is |
| 635 | // to be emitted it can flush the Trace or update it. Flushing the Trace |
| 636 | // will emit code to bring the actual state into line with the virtual state. |
| 637 | // Avoiding flushing the state can postpone some work (eg updates of capture |
| 638 | // registers). Postponing work can save time when executing the regular |
| 639 | // expression since it may be found that the work never has to be done as a |
| 640 | // failure to match can occur. In addition it is much faster to jump to a |
| 641 | // known backtrack code location than it is to pop an unknown backtrack |
| 642 | // location from the stack and jump there. |
| 643 | // |
| 644 | // The virtual state found in the Trace affects code generation. For example |
| 645 | // the virtual state contains the difference between the actual current |
| 646 | // position and the virtual current position, and matching code needs to use |
| 647 | // this offset to attempt a match in the correct location of the input |
| 648 | // string. Therefore code generated for a non-trivial trace is specialized |
| 649 | // to that trace. The code generator therefore has the ability to generate |
| 650 | // code for each node several times. In order to limit the size of the |
| 651 | // generated code there is an arbitrary limit on how many specialized sets of |
| 652 | // code may be generated for a given node. If the limit is reached, the |
| 653 | // trace is flushed and a generic version of the code for a node is emitted. |
| 654 | // This is subsequently used for that node. The code emitted for non-generic |
| 655 | // trace is not recorded in the node and so it cannot currently be reused in |
| 656 | // the event that code generation is requested for an identical trace. |
| 657 | |
| 658 | |
| 659 | void RegExpTree::AppendToText(RegExpText* text) { |
| 660 | UNREACHABLE(); |
| 661 | } |
| 662 | |
| 663 | |
| 664 | void RegExpAtom::AppendToText(RegExpText* text) { |
| 665 | text->AddElement(TextElement::Atom(this)); |
| 666 | } |
| 667 | |
| 668 | |
| 669 | void RegExpCharacterClass::AppendToText(RegExpText* text) { |
| 670 | text->AddElement(TextElement::CharClass(this)); |
| 671 | } |
| 672 | |
| 673 | |
| 674 | void RegExpText::AppendToText(RegExpText* text) { |
| 675 | for (int i = 0; i < elements()->length(); i++) |
| 676 | text->AddElement(elements()->at(i)); |
| 677 | } |
| 678 | |
| 679 | |
| 680 | TextElement TextElement::Atom(RegExpAtom* atom) { |
| 681 | TextElement result = TextElement(ATOM); |
| 682 | result.data.u_atom = atom; |
| 683 | return result; |
| 684 | } |
| 685 | |
| 686 | |
| 687 | TextElement TextElement::CharClass( |
| 688 | RegExpCharacterClass* char_class) { |
| 689 | TextElement result = TextElement(CHAR_CLASS); |
| 690 | result.data.u_char_class = char_class; |
| 691 | return result; |
| 692 | } |
| 693 | |
| 694 | |
| 695 | int TextElement::length() { |
| 696 | if (type == ATOM) { |
| 697 | return data.u_atom->length(); |
| 698 | } else { |
| 699 | ASSERT(type == CHAR_CLASS); |
| 700 | return 1; |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | |
| 705 | DispatchTable* ChoiceNode::GetTable(bool ignore_case) { |
| 706 | if (table_ == NULL) { |
| 707 | table_ = new DispatchTable(); |
| 708 | DispatchTableConstructor cons(table_, ignore_case); |
| 709 | cons.BuildTable(this); |
| 710 | } |
| 711 | return table_; |
| 712 | } |
| 713 | |
| 714 | |
| 715 | class RegExpCompiler { |
| 716 | public: |
| 717 | RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii); |
| 718 | |
| 719 | int AllocateRegister() { |
| 720 | if (next_register_ >= RegExpMacroAssembler::kMaxRegister) { |
| 721 | reg_exp_too_big_ = true; |
| 722 | return next_register_; |
| 723 | } |
| 724 | return next_register_++; |
| 725 | } |
| 726 | |
| 727 | RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler, |
| 728 | RegExpNode* start, |
| 729 | int capture_count, |
| 730 | Handle<String> pattern); |
| 731 | |
| 732 | inline void AddWork(RegExpNode* node) { work_list_->Add(node); } |
| 733 | |
| 734 | static const int kImplementationOffset = 0; |
| 735 | static const int kNumberOfRegistersOffset = 0; |
| 736 | static const int kCodeOffset = 1; |
| 737 | |
| 738 | RegExpMacroAssembler* macro_assembler() { return macro_assembler_; } |
| 739 | EndNode* accept() { return accept_; } |
| 740 | |
| 741 | static const int kMaxRecursion = 100; |
| 742 | inline int recursion_depth() { return recursion_depth_; } |
| 743 | inline void IncrementRecursionDepth() { recursion_depth_++; } |
| 744 | inline void DecrementRecursionDepth() { recursion_depth_--; } |
| 745 | |
| 746 | void SetRegExpTooBig() { reg_exp_too_big_ = true; } |
| 747 | |
| 748 | inline bool ignore_case() { return ignore_case_; } |
| 749 | inline bool ascii() { return ascii_; } |
| 750 | |
| 751 | static const int kNoRegister = -1; |
| 752 | private: |
| 753 | EndNode* accept_; |
| 754 | int next_register_; |
| 755 | List<RegExpNode*>* work_list_; |
| 756 | int recursion_depth_; |
| 757 | RegExpMacroAssembler* macro_assembler_; |
| 758 | bool ignore_case_; |
| 759 | bool ascii_; |
| 760 | bool reg_exp_too_big_; |
| 761 | }; |
| 762 | |
| 763 | |
| 764 | class RecursionCheck { |
| 765 | public: |
| 766 | explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) { |
| 767 | compiler->IncrementRecursionDepth(); |
| 768 | } |
| 769 | ~RecursionCheck() { compiler_->DecrementRecursionDepth(); } |
| 770 | private: |
| 771 | RegExpCompiler* compiler_; |
| 772 | }; |
| 773 | |
| 774 | |
| 775 | static RegExpEngine::CompilationResult IrregexpRegExpTooBig() { |
| 776 | return RegExpEngine::CompilationResult("RegExp too big"); |
| 777 | } |
| 778 | |
| 779 | |
| 780 | // Attempts to compile the regexp using an Irregexp code generator. Returns |
| 781 | // a fixed array or a null handle depending on whether it succeeded. |
| 782 | RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii) |
| 783 | : next_register_(2 * (capture_count + 1)), |
| 784 | work_list_(NULL), |
| 785 | recursion_depth_(0), |
| 786 | ignore_case_(ignore_case), |
| 787 | ascii_(ascii), |
| 788 | reg_exp_too_big_(false) { |
| 789 | accept_ = new EndNode(EndNode::ACCEPT); |
| 790 | ASSERT(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister); |
| 791 | } |
| 792 | |
| 793 | |
| 794 | RegExpEngine::CompilationResult RegExpCompiler::Assemble( |
| 795 | RegExpMacroAssembler* macro_assembler, |
| 796 | RegExpNode* start, |
| 797 | int capture_count, |
| 798 | Handle<String> pattern) { |
| 799 | #ifdef DEBUG |
| 800 | if (FLAG_trace_regexp_assembler) |
| 801 | macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler); |
| 802 | else |
| 803 | #endif |
| 804 | macro_assembler_ = macro_assembler; |
| 805 | List <RegExpNode*> work_list(0); |
| 806 | work_list_ = &work_list; |
| 807 | Label fail; |
| 808 | macro_assembler_->PushBacktrack(&fail); |
| 809 | Trace new_trace; |
| 810 | start->Emit(this, &new_trace); |
| 811 | macro_assembler_->Bind(&fail); |
| 812 | macro_assembler_->Fail(); |
| 813 | while (!work_list.is_empty()) { |
| 814 | work_list.RemoveLast()->Emit(this, &new_trace); |
| 815 | } |
| 816 | if (reg_exp_too_big_) return IrregexpRegExpTooBig(); |
| 817 | |
| 818 | Handle<Object> code = macro_assembler_->GetCode(pattern); |
| 819 | |
| 820 | work_list_ = NULL; |
| 821 | #ifdef DEBUG |
| 822 | if (FLAG_trace_regexp_assembler) { |
| 823 | delete macro_assembler_; |
| 824 | } |
| 825 | #endif |
| 826 | return RegExpEngine::CompilationResult(*code, next_register_); |
| 827 | } |
| 828 | |
| 829 | |
| 830 | bool Trace::DeferredAction::Mentions(int that) { |
| 831 | if (type() == ActionNode::CLEAR_CAPTURES) { |
| 832 | Interval range = static_cast<DeferredClearCaptures*>(this)->range(); |
| 833 | return range.Contains(that); |
| 834 | } else { |
| 835 | return reg() == that; |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | |
| 840 | bool Trace::mentions_reg(int reg) { |
| 841 | for (DeferredAction* action = actions_; |
| 842 | action != NULL; |
| 843 | action = action->next()) { |
| 844 | if (action->Mentions(reg)) |
| 845 | return true; |
| 846 | } |
| 847 | return false; |
| 848 | } |
| 849 | |
| 850 | |
| 851 | bool Trace::GetStoredPosition(int reg, int* cp_offset) { |
| 852 | ASSERT_EQ(0, *cp_offset); |
| 853 | for (DeferredAction* action = actions_; |
| 854 | action != NULL; |
| 855 | action = action->next()) { |
| 856 | if (action->Mentions(reg)) { |
| 857 | if (action->type() == ActionNode::STORE_POSITION) { |
| 858 | *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset(); |
| 859 | return true; |
| 860 | } else { |
| 861 | return false; |
| 862 | } |
| 863 | } |
| 864 | } |
| 865 | return false; |
| 866 | } |
| 867 | |
| 868 | |
| 869 | int Trace::FindAffectedRegisters(OutSet* affected_registers) { |
| 870 | int max_register = RegExpCompiler::kNoRegister; |
| 871 | for (DeferredAction* action = actions_; |
| 872 | action != NULL; |
| 873 | action = action->next()) { |
| 874 | if (action->type() == ActionNode::CLEAR_CAPTURES) { |
| 875 | Interval range = static_cast<DeferredClearCaptures*>(action)->range(); |
| 876 | for (int i = range.from(); i <= range.to(); i++) |
| 877 | affected_registers->Set(i); |
| 878 | if (range.to() > max_register) max_register = range.to(); |
| 879 | } else { |
| 880 | affected_registers->Set(action->reg()); |
| 881 | if (action->reg() > max_register) max_register = action->reg(); |
| 882 | } |
| 883 | } |
| 884 | return max_register; |
| 885 | } |
| 886 | |
| 887 | |
| 888 | void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler, |
| 889 | int max_register, |
| 890 | OutSet& registers_to_pop, |
| 891 | OutSet& registers_to_clear) { |
| 892 | for (int reg = max_register; reg >= 0; reg--) { |
| 893 | if (registers_to_pop.Get(reg)) assembler->PopRegister(reg); |
| 894 | else if (registers_to_clear.Get(reg)) { |
| 895 | int clear_to = reg; |
| 896 | while (reg > 0 && registers_to_clear.Get(reg - 1)) { |
| 897 | reg--; |
| 898 | } |
| 899 | assembler->ClearRegisters(reg, clear_to); |
| 900 | } |
| 901 | } |
| 902 | } |
| 903 | |
| 904 | |
| 905 | void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler, |
| 906 | int max_register, |
| 907 | OutSet& affected_registers, |
| 908 | OutSet* registers_to_pop, |
| 909 | OutSet* registers_to_clear) { |
| 910 | // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1. |
| 911 | const int push_limit = (assembler->stack_limit_slack() + 1) / 2; |
| 912 | |
| 913 | // Count pushes performed to force a stack limit check occasionally. |
| 914 | int pushes = 0; |
| 915 | |
| 916 | for (int reg = 0; reg <= max_register; reg++) { |
| 917 | if (!affected_registers.Get(reg)) { |
| 918 | continue; |
| 919 | } |
| 920 | |
| 921 | // The chronologically first deferred action in the trace |
| 922 | // is used to infer the action needed to restore a register |
| 923 | // to its previous state (or not, if it's safe to ignore it). |
| 924 | enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR }; |
| 925 | DeferredActionUndoType undo_action = IGNORE; |
| 926 | |
| 927 | int value = 0; |
| 928 | bool absolute = false; |
| 929 | bool clear = false; |
| 930 | int store_position = -1; |
| 931 | // This is a little tricky because we are scanning the actions in reverse |
| 932 | // historical order (newest first). |
| 933 | for (DeferredAction* action = actions_; |
| 934 | action != NULL; |
| 935 | action = action->next()) { |
| 936 | if (action->Mentions(reg)) { |
| 937 | switch (action->type()) { |
| 938 | case ActionNode::SET_REGISTER: { |
| 939 | Trace::DeferredSetRegister* psr = |
| 940 | static_cast<Trace::DeferredSetRegister*>(action); |
| 941 | if (!absolute) { |
| 942 | value += psr->value(); |
| 943 | absolute = true; |
| 944 | } |
| 945 | // SET_REGISTER is currently only used for newly introduced loop |
| 946 | // counters. They can have a significant previous value if they |
| 947 | // occour in a loop. TODO(lrn): Propagate this information, so |
| 948 | // we can set undo_action to IGNORE if we know there is no value to |
| 949 | // restore. |
| 950 | undo_action = RESTORE; |
| 951 | ASSERT_EQ(store_position, -1); |
| 952 | ASSERT(!clear); |
| 953 | break; |
| 954 | } |
| 955 | case ActionNode::INCREMENT_REGISTER: |
| 956 | if (!absolute) { |
| 957 | value++; |
| 958 | } |
| 959 | ASSERT_EQ(store_position, -1); |
| 960 | ASSERT(!clear); |
| 961 | undo_action = RESTORE; |
| 962 | break; |
| 963 | case ActionNode::STORE_POSITION: { |
| 964 | Trace::DeferredCapture* pc = |
| 965 | static_cast<Trace::DeferredCapture*>(action); |
| 966 | if (!clear && store_position == -1) { |
| 967 | store_position = pc->cp_offset(); |
| 968 | } |
| 969 | |
| 970 | // For captures we know that stores and clears alternate. |
| 971 | // Other register, are never cleared, and if the occur |
| 972 | // inside a loop, they might be assigned more than once. |
| 973 | if (reg <= 1) { |
| 974 | // Registers zero and one, aka "capture zero", is |
| 975 | // always set correctly if we succeed. There is no |
| 976 | // need to undo a setting on backtrack, because we |
| 977 | // will set it again or fail. |
| 978 | undo_action = IGNORE; |
| 979 | } else { |
| 980 | undo_action = pc->is_capture() ? CLEAR : RESTORE; |
| 981 | } |
| 982 | ASSERT(!absolute); |
| 983 | ASSERT_EQ(value, 0); |
| 984 | break; |
| 985 | } |
| 986 | case ActionNode::CLEAR_CAPTURES: { |
| 987 | // Since we're scanning in reverse order, if we've already |
| 988 | // set the position we have to ignore historically earlier |
| 989 | // clearing operations. |
| 990 | if (store_position == -1) { |
| 991 | clear = true; |
| 992 | } |
| 993 | undo_action = RESTORE; |
| 994 | ASSERT(!absolute); |
| 995 | ASSERT_EQ(value, 0); |
| 996 | break; |
| 997 | } |
| 998 | default: |
| 999 | UNREACHABLE(); |
| 1000 | break; |
| 1001 | } |
| 1002 | } |
| 1003 | } |
| 1004 | // Prepare for the undo-action (e.g., push if it's going to be popped). |
| 1005 | if (undo_action == RESTORE) { |
| 1006 | pushes++; |
| 1007 | RegExpMacroAssembler::StackCheckFlag stack_check = |
| 1008 | RegExpMacroAssembler::kNoStackLimitCheck; |
| 1009 | if (pushes == push_limit) { |
| 1010 | stack_check = RegExpMacroAssembler::kCheckStackLimit; |
| 1011 | pushes = 0; |
| 1012 | } |
| 1013 | |
| 1014 | assembler->PushRegister(reg, stack_check); |
| 1015 | registers_to_pop->Set(reg); |
| 1016 | } else if (undo_action == CLEAR) { |
| 1017 | registers_to_clear->Set(reg); |
| 1018 | } |
| 1019 | // Perform the chronologically last action (or accumulated increment) |
| 1020 | // for the register. |
| 1021 | if (store_position != -1) { |
| 1022 | assembler->WriteCurrentPositionToRegister(reg, store_position); |
| 1023 | } else if (clear) { |
| 1024 | assembler->ClearRegisters(reg, reg); |
| 1025 | } else if (absolute) { |
| 1026 | assembler->SetRegister(reg, value); |
| 1027 | } else if (value != 0) { |
| 1028 | assembler->AdvanceRegister(reg, value); |
| 1029 | } |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | |
| 1034 | // This is called as we come into a loop choice node and some other tricky |
| 1035 | // nodes. It normalizes the state of the code generator to ensure we can |
| 1036 | // generate generic code. |
| 1037 | void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) { |
| 1038 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 1039 | |
| 1040 | ASSERT(!is_trivial()); |
| 1041 | |
| 1042 | if (actions_ == NULL && backtrack() == NULL) { |
| 1043 | // Here we just have some deferred cp advances to fix and we are back to |
| 1044 | // a normal situation. We may also have to forget some information gained |
| 1045 | // through a quick check that was already performed. |
| 1046 | if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_); |
| 1047 | // Create a new trivial state and generate the node with that. |
| 1048 | Trace new_state; |
| 1049 | successor->Emit(compiler, &new_state); |
| 1050 | return; |
| 1051 | } |
| 1052 | |
| 1053 | // Generate deferred actions here along with code to undo them again. |
| 1054 | OutSet affected_registers; |
| 1055 | |
| 1056 | if (backtrack() != NULL) { |
| 1057 | // Here we have a concrete backtrack location. These are set up by choice |
| 1058 | // nodes and so they indicate that we have a deferred save of the current |
| 1059 | // position which we may need to emit here. |
| 1060 | assembler->PushCurrentPosition(); |
| 1061 | } |
| 1062 | |
| 1063 | int max_register = FindAffectedRegisters(&affected_registers); |
| 1064 | OutSet registers_to_pop; |
| 1065 | OutSet registers_to_clear; |
| 1066 | PerformDeferredActions(assembler, |
| 1067 | max_register, |
| 1068 | affected_registers, |
| 1069 | ®isters_to_pop, |
| 1070 | ®isters_to_clear); |
| 1071 | if (cp_offset_ != 0) { |
| 1072 | assembler->AdvanceCurrentPosition(cp_offset_); |
| 1073 | } |
| 1074 | |
| 1075 | // Create a new trivial state and generate the node with that. |
| 1076 | Label undo; |
| 1077 | assembler->PushBacktrack(&undo); |
| 1078 | Trace new_state; |
| 1079 | successor->Emit(compiler, &new_state); |
| 1080 | |
| 1081 | // On backtrack we need to restore state. |
| 1082 | assembler->Bind(&undo); |
| 1083 | RestoreAffectedRegisters(assembler, |
| 1084 | max_register, |
| 1085 | registers_to_pop, |
| 1086 | registers_to_clear); |
| 1087 | if (backtrack() == NULL) { |
| 1088 | assembler->Backtrack(); |
| 1089 | } else { |
| 1090 | assembler->PopCurrentPosition(); |
| 1091 | assembler->GoTo(backtrack()); |
| 1092 | } |
| 1093 | } |
| 1094 | |
| 1095 | |
| 1096 | void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) { |
| 1097 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 1098 | |
| 1099 | // Omit flushing the trace. We discard the entire stack frame anyway. |
| 1100 | |
| 1101 | if (!label()->is_bound()) { |
| 1102 | // We are completely independent of the trace, since we ignore it, |
| 1103 | // so this code can be used as the generic version. |
| 1104 | assembler->Bind(label()); |
| 1105 | } |
| 1106 | |
| 1107 | // Throw away everything on the backtrack stack since the start |
| 1108 | // of the negative submatch and restore the character position. |
| 1109 | assembler->ReadCurrentPositionFromRegister(current_position_register_); |
| 1110 | assembler->ReadStackPointerFromRegister(stack_pointer_register_); |
| 1111 | if (clear_capture_count_ > 0) { |
| 1112 | // Clear any captures that might have been performed during the success |
| 1113 | // of the body of the negative look-ahead. |
| 1114 | int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1; |
| 1115 | assembler->ClearRegisters(clear_capture_start_, clear_capture_end); |
| 1116 | } |
| 1117 | // Now that we have unwound the stack we find at the top of the stack the |
| 1118 | // backtrack that the BeginSubmatch node got. |
| 1119 | assembler->Backtrack(); |
| 1120 | } |
| 1121 | |
| 1122 | |
| 1123 | void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| 1124 | if (!trace->is_trivial()) { |
| 1125 | trace->Flush(compiler, this); |
| 1126 | return; |
| 1127 | } |
| 1128 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 1129 | if (!label()->is_bound()) { |
| 1130 | assembler->Bind(label()); |
| 1131 | } |
| 1132 | switch (action_) { |
| 1133 | case ACCEPT: |
| 1134 | assembler->Succeed(); |
| 1135 | return; |
| 1136 | case BACKTRACK: |
| 1137 | assembler->GoTo(trace->backtrack()); |
| 1138 | return; |
| 1139 | case NEGATIVE_SUBMATCH_SUCCESS: |
| 1140 | // This case is handled in a different virtual method. |
| 1141 | UNREACHABLE(); |
| 1142 | } |
| 1143 | UNIMPLEMENTED(); |
| 1144 | } |
| 1145 | |
| 1146 | |
| 1147 | void GuardedAlternative::AddGuard(Guard* guard) { |
| 1148 | if (guards_ == NULL) |
| 1149 | guards_ = new ZoneList<Guard*>(1); |
| 1150 | guards_->Add(guard); |
| 1151 | } |
| 1152 | |
| 1153 | |
| 1154 | ActionNode* ActionNode::SetRegister(int reg, |
| 1155 | int val, |
| 1156 | RegExpNode* on_success) { |
| 1157 | ActionNode* result = new ActionNode(SET_REGISTER, on_success); |
| 1158 | result->data_.u_store_register.reg = reg; |
| 1159 | result->data_.u_store_register.value = val; |
| 1160 | return result; |
| 1161 | } |
| 1162 | |
| 1163 | |
| 1164 | ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) { |
| 1165 | ActionNode* result = new ActionNode(INCREMENT_REGISTER, on_success); |
| 1166 | result->data_.u_increment_register.reg = reg; |
| 1167 | return result; |
| 1168 | } |
| 1169 | |
| 1170 | |
| 1171 | ActionNode* ActionNode::StorePosition(int reg, |
| 1172 | bool is_capture, |
| 1173 | RegExpNode* on_success) { |
| 1174 | ActionNode* result = new ActionNode(STORE_POSITION, on_success); |
| 1175 | result->data_.u_position_register.reg = reg; |
| 1176 | result->data_.u_position_register.is_capture = is_capture; |
| 1177 | return result; |
| 1178 | } |
| 1179 | |
| 1180 | |
| 1181 | ActionNode* ActionNode::ClearCaptures(Interval range, |
| 1182 | RegExpNode* on_success) { |
| 1183 | ActionNode* result = new ActionNode(CLEAR_CAPTURES, on_success); |
| 1184 | result->data_.u_clear_captures.range_from = range.from(); |
| 1185 | result->data_.u_clear_captures.range_to = range.to(); |
| 1186 | return result; |
| 1187 | } |
| 1188 | |
| 1189 | |
| 1190 | ActionNode* ActionNode::BeginSubmatch(int stack_reg, |
| 1191 | int position_reg, |
| 1192 | RegExpNode* on_success) { |
| 1193 | ActionNode* result = new ActionNode(BEGIN_SUBMATCH, on_success); |
| 1194 | result->data_.u_submatch.stack_pointer_register = stack_reg; |
| 1195 | result->data_.u_submatch.current_position_register = position_reg; |
| 1196 | return result; |
| 1197 | } |
| 1198 | |
| 1199 | |
| 1200 | ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg, |
| 1201 | int position_reg, |
| 1202 | int clear_register_count, |
| 1203 | int clear_register_from, |
| 1204 | RegExpNode* on_success) { |
| 1205 | ActionNode* result = new ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success); |
| 1206 | result->data_.u_submatch.stack_pointer_register = stack_reg; |
| 1207 | result->data_.u_submatch.current_position_register = position_reg; |
| 1208 | result->data_.u_submatch.clear_register_count = clear_register_count; |
| 1209 | result->data_.u_submatch.clear_register_from = clear_register_from; |
| 1210 | return result; |
| 1211 | } |
| 1212 | |
| 1213 | |
| 1214 | ActionNode* ActionNode::EmptyMatchCheck(int start_register, |
| 1215 | int repetition_register, |
| 1216 | int repetition_limit, |
| 1217 | RegExpNode* on_success) { |
| 1218 | ActionNode* result = new ActionNode(EMPTY_MATCH_CHECK, on_success); |
| 1219 | result->data_.u_empty_match_check.start_register = start_register; |
| 1220 | result->data_.u_empty_match_check.repetition_register = repetition_register; |
| 1221 | result->data_.u_empty_match_check.repetition_limit = repetition_limit; |
| 1222 | return result; |
| 1223 | } |
| 1224 | |
| 1225 | |
| 1226 | #define DEFINE_ACCEPT(Type) \ |
| 1227 | void Type##Node::Accept(NodeVisitor* visitor) { \ |
| 1228 | visitor->Visit##Type(this); \ |
| 1229 | } |
| 1230 | FOR_EACH_NODE_TYPE(DEFINE_ACCEPT) |
| 1231 | #undef DEFINE_ACCEPT |
| 1232 | |
| 1233 | |
| 1234 | void LoopChoiceNode::Accept(NodeVisitor* visitor) { |
| 1235 | visitor->VisitLoopChoice(this); |
| 1236 | } |
| 1237 | |
| 1238 | |
| 1239 | // ------------------------------------------------------------------- |
| 1240 | // Emit code. |
| 1241 | |
| 1242 | |
| 1243 | void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler, |
| 1244 | Guard* guard, |
| 1245 | Trace* trace) { |
| 1246 | switch (guard->op()) { |
| 1247 | case Guard::LT: |
| 1248 | ASSERT(!trace->mentions_reg(guard->reg())); |
| 1249 | macro_assembler->IfRegisterGE(guard->reg(), |
| 1250 | guard->value(), |
| 1251 | trace->backtrack()); |
| 1252 | break; |
| 1253 | case Guard::GEQ: |
| 1254 | ASSERT(!trace->mentions_reg(guard->reg())); |
| 1255 | macro_assembler->IfRegisterLT(guard->reg(), |
| 1256 | guard->value(), |
| 1257 | trace->backtrack()); |
| 1258 | break; |
| 1259 | } |
| 1260 | } |
| 1261 | |
| 1262 | |
| 1263 | static unibrow::Mapping<unibrow::Ecma262UnCanonicalize> uncanonicalize; |
| 1264 | static unibrow::Mapping<unibrow::CanonicalizationRange> canonrange; |
| 1265 | |
| 1266 | |
| 1267 | // Returns the number of characters in the equivalence class, omitting those |
| 1268 | // that cannot occur in the source string because it is ASCII. |
| 1269 | static int GetCaseIndependentLetters(uc16 character, |
| 1270 | bool ascii_subject, |
| 1271 | unibrow::uchar* letters) { |
| 1272 | int length = uncanonicalize.get(character, '\0', letters); |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 1273 | // Unibrow returns 0 or 1 for characters where case independence is |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 1274 | // trivial. |
| 1275 | if (length == 0) { |
| 1276 | letters[0] = character; |
| 1277 | length = 1; |
| 1278 | } |
| 1279 | if (!ascii_subject || character <= String::kMaxAsciiCharCode) { |
| 1280 | return length; |
| 1281 | } |
| 1282 | // The standard requires that non-ASCII characters cannot have ASCII |
| 1283 | // character codes in their equivalence class. |
| 1284 | return 0; |
| 1285 | } |
| 1286 | |
| 1287 | |
| 1288 | static inline bool EmitSimpleCharacter(RegExpCompiler* compiler, |
| 1289 | uc16 c, |
| 1290 | Label* on_failure, |
| 1291 | int cp_offset, |
| 1292 | bool check, |
| 1293 | bool preloaded) { |
| 1294 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 1295 | bool bound_checked = false; |
| 1296 | if (!preloaded) { |
| 1297 | assembler->LoadCurrentCharacter( |
| 1298 | cp_offset, |
| 1299 | on_failure, |
| 1300 | check); |
| 1301 | bound_checked = true; |
| 1302 | } |
| 1303 | assembler->CheckNotCharacter(c, on_failure); |
| 1304 | return bound_checked; |
| 1305 | } |
| 1306 | |
| 1307 | |
| 1308 | // Only emits non-letters (things that don't have case). Only used for case |
| 1309 | // independent matches. |
| 1310 | static inline bool EmitAtomNonLetter(RegExpCompiler* compiler, |
| 1311 | uc16 c, |
| 1312 | Label* on_failure, |
| 1313 | int cp_offset, |
| 1314 | bool check, |
| 1315 | bool preloaded) { |
| 1316 | RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| 1317 | bool ascii = compiler->ascii(); |
| 1318 | unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| 1319 | int length = GetCaseIndependentLetters(c, ascii, chars); |
| 1320 | if (length < 1) { |
| 1321 | // This can't match. Must be an ASCII subject and a non-ASCII character. |
| 1322 | // We do not need to do anything since the ASCII pass already handled this. |
| 1323 | return false; // Bounds not checked. |
| 1324 | } |
| 1325 | bool checked = false; |
| 1326 | // We handle the length > 1 case in a later pass. |
| 1327 | if (length == 1) { |
| 1328 | if (ascii && c > String::kMaxAsciiCharCodeU) { |
| 1329 | // Can't match - see above. |
| 1330 | return false; // Bounds not checked. |
| 1331 | } |
| 1332 | if (!preloaded) { |
| 1333 | macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check); |
| 1334 | checked = check; |
| 1335 | } |
| 1336 | macro_assembler->CheckNotCharacter(c, on_failure); |
| 1337 | } |
| 1338 | return checked; |
| 1339 | } |
| 1340 | |
| 1341 | |
| 1342 | static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler, |
| 1343 | bool ascii, |
| 1344 | uc16 c1, |
| 1345 | uc16 c2, |
| 1346 | Label* on_failure) { |
| 1347 | uc16 char_mask; |
| 1348 | if (ascii) { |
| 1349 | char_mask = String::kMaxAsciiCharCode; |
| 1350 | } else { |
| 1351 | char_mask = String::kMaxUC16CharCode; |
| 1352 | } |
| 1353 | uc16 exor = c1 ^ c2; |
| 1354 | // Check whether exor has only one bit set. |
| 1355 | if (((exor - 1) & exor) == 0) { |
| 1356 | // If c1 and c2 differ only by one bit. |
| 1357 | // Ecma262UnCanonicalize always gives the highest number last. |
| 1358 | ASSERT(c2 > c1); |
| 1359 | uc16 mask = char_mask ^ exor; |
| 1360 | macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure); |
| 1361 | return true; |
| 1362 | } |
| 1363 | ASSERT(c2 > c1); |
| 1364 | uc16 diff = c2 - c1; |
| 1365 | if (((diff - 1) & diff) == 0 && c1 >= diff) { |
| 1366 | // If the characters differ by 2^n but don't differ by one bit then |
| 1367 | // subtract the difference from the found character, then do the or |
| 1368 | // trick. We avoid the theoretical case where negative numbers are |
| 1369 | // involved in order to simplify code generation. |
| 1370 | uc16 mask = char_mask ^ diff; |
| 1371 | macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff, |
| 1372 | diff, |
| 1373 | mask, |
| 1374 | on_failure); |
| 1375 | return true; |
| 1376 | } |
| 1377 | return false; |
| 1378 | } |
| 1379 | |
| 1380 | |
| 1381 | typedef bool EmitCharacterFunction(RegExpCompiler* compiler, |
| 1382 | uc16 c, |
| 1383 | Label* on_failure, |
| 1384 | int cp_offset, |
| 1385 | bool check, |
| 1386 | bool preloaded); |
| 1387 | |
| 1388 | // Only emits letters (things that have case). Only used for case independent |
| 1389 | // matches. |
| 1390 | static inline bool EmitAtomLetter(RegExpCompiler* compiler, |
| 1391 | uc16 c, |
| 1392 | Label* on_failure, |
| 1393 | int cp_offset, |
| 1394 | bool check, |
| 1395 | bool preloaded) { |
| 1396 | RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| 1397 | bool ascii = compiler->ascii(); |
| 1398 | unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| 1399 | int length = GetCaseIndependentLetters(c, ascii, chars); |
| 1400 | if (length <= 1) return false; |
| 1401 | // We may not need to check against the end of the input string |
| 1402 | // if this character lies before a character that matched. |
| 1403 | if (!preloaded) { |
| 1404 | macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check); |
| 1405 | } |
| 1406 | Label ok; |
| 1407 | ASSERT(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4); |
| 1408 | switch (length) { |
| 1409 | case 2: { |
| 1410 | if (ShortCutEmitCharacterPair(macro_assembler, |
| 1411 | ascii, |
| 1412 | chars[0], |
| 1413 | chars[1], |
| 1414 | on_failure)) { |
| 1415 | } else { |
| 1416 | macro_assembler->CheckCharacter(chars[0], &ok); |
| 1417 | macro_assembler->CheckNotCharacter(chars[1], on_failure); |
| 1418 | macro_assembler->Bind(&ok); |
| 1419 | } |
| 1420 | break; |
| 1421 | } |
| 1422 | case 4: |
| 1423 | macro_assembler->CheckCharacter(chars[3], &ok); |
| 1424 | // Fall through! |
| 1425 | case 3: |
| 1426 | macro_assembler->CheckCharacter(chars[0], &ok); |
| 1427 | macro_assembler->CheckCharacter(chars[1], &ok); |
| 1428 | macro_assembler->CheckNotCharacter(chars[2], on_failure); |
| 1429 | macro_assembler->Bind(&ok); |
| 1430 | break; |
| 1431 | default: |
| 1432 | UNREACHABLE(); |
| 1433 | break; |
| 1434 | } |
| 1435 | return true; |
| 1436 | } |
| 1437 | |
| 1438 | |
| 1439 | static void EmitCharClass(RegExpMacroAssembler* macro_assembler, |
| 1440 | RegExpCharacterClass* cc, |
| 1441 | bool ascii, |
| 1442 | Label* on_failure, |
| 1443 | int cp_offset, |
| 1444 | bool check_offset, |
| 1445 | bool preloaded) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 1446 | ZoneList<CharacterRange>* ranges = cc->ranges(); |
| 1447 | int max_char; |
| 1448 | if (ascii) { |
| 1449 | max_char = String::kMaxAsciiCharCode; |
| 1450 | } else { |
| 1451 | max_char = String::kMaxUC16CharCode; |
| 1452 | } |
| 1453 | |
| 1454 | Label success; |
| 1455 | |
| 1456 | Label* char_is_in_class = |
| 1457 | cc->is_negated() ? on_failure : &success; |
| 1458 | |
| 1459 | int range_count = ranges->length(); |
| 1460 | |
| 1461 | int last_valid_range = range_count - 1; |
| 1462 | while (last_valid_range >= 0) { |
| 1463 | CharacterRange& range = ranges->at(last_valid_range); |
| 1464 | if (range.from() <= max_char) { |
| 1465 | break; |
| 1466 | } |
| 1467 | last_valid_range--; |
| 1468 | } |
| 1469 | |
| 1470 | if (last_valid_range < 0) { |
| 1471 | if (!cc->is_negated()) { |
| 1472 | // TODO(plesner): We can remove this when the node level does our |
| 1473 | // ASCII optimizations for us. |
| 1474 | macro_assembler->GoTo(on_failure); |
| 1475 | } |
| 1476 | if (check_offset) { |
| 1477 | macro_assembler->CheckPosition(cp_offset, on_failure); |
| 1478 | } |
| 1479 | return; |
| 1480 | } |
| 1481 | |
| 1482 | if (last_valid_range == 0 && |
| 1483 | !cc->is_negated() && |
| 1484 | ranges->at(0).IsEverything(max_char)) { |
| 1485 | // This is a common case hit by non-anchored expressions. |
| 1486 | if (check_offset) { |
| 1487 | macro_assembler->CheckPosition(cp_offset, on_failure); |
| 1488 | } |
| 1489 | return; |
| 1490 | } |
| 1491 | |
| 1492 | if (!preloaded) { |
| 1493 | macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset); |
| 1494 | } |
| 1495 | |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 1496 | if (cc->is_standard() && |
| 1497 | macro_assembler->CheckSpecialCharacterClass(cc->standard_type(), |
| 1498 | on_failure)) { |
| 1499 | return; |
| 1500 | } |
| 1501 | |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 1502 | for (int i = 0; i < last_valid_range; i++) { |
| 1503 | CharacterRange& range = ranges->at(i); |
| 1504 | Label next_range; |
| 1505 | uc16 from = range.from(); |
| 1506 | uc16 to = range.to(); |
| 1507 | if (from > max_char) { |
| 1508 | continue; |
| 1509 | } |
| 1510 | if (to > max_char) to = max_char; |
| 1511 | if (to == from) { |
| 1512 | macro_assembler->CheckCharacter(to, char_is_in_class); |
| 1513 | } else { |
| 1514 | if (from != 0) { |
| 1515 | macro_assembler->CheckCharacterLT(from, &next_range); |
| 1516 | } |
| 1517 | if (to != max_char) { |
| 1518 | macro_assembler->CheckCharacterLT(to + 1, char_is_in_class); |
| 1519 | } else { |
| 1520 | macro_assembler->GoTo(char_is_in_class); |
| 1521 | } |
| 1522 | } |
| 1523 | macro_assembler->Bind(&next_range); |
| 1524 | } |
| 1525 | |
| 1526 | CharacterRange& range = ranges->at(last_valid_range); |
| 1527 | uc16 from = range.from(); |
| 1528 | uc16 to = range.to(); |
| 1529 | |
| 1530 | if (to > max_char) to = max_char; |
| 1531 | ASSERT(to >= from); |
| 1532 | |
| 1533 | if (to == from) { |
| 1534 | if (cc->is_negated()) { |
| 1535 | macro_assembler->CheckCharacter(to, on_failure); |
| 1536 | } else { |
| 1537 | macro_assembler->CheckNotCharacter(to, on_failure); |
| 1538 | } |
| 1539 | } else { |
| 1540 | if (from != 0) { |
| 1541 | if (cc->is_negated()) { |
| 1542 | macro_assembler->CheckCharacterLT(from, &success); |
| 1543 | } else { |
| 1544 | macro_assembler->CheckCharacterLT(from, on_failure); |
| 1545 | } |
| 1546 | } |
| 1547 | if (to != String::kMaxUC16CharCode) { |
| 1548 | if (cc->is_negated()) { |
| 1549 | macro_assembler->CheckCharacterLT(to + 1, on_failure); |
| 1550 | } else { |
| 1551 | macro_assembler->CheckCharacterGT(to, on_failure); |
| 1552 | } |
| 1553 | } else { |
| 1554 | if (cc->is_negated()) { |
| 1555 | macro_assembler->GoTo(on_failure); |
| 1556 | } |
| 1557 | } |
| 1558 | } |
| 1559 | macro_assembler->Bind(&success); |
| 1560 | } |
| 1561 | |
| 1562 | |
| 1563 | RegExpNode::~RegExpNode() { |
| 1564 | } |
| 1565 | |
| 1566 | |
| 1567 | RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler, |
| 1568 | Trace* trace) { |
| 1569 | // If we are generating a greedy loop then don't stop and don't reuse code. |
| 1570 | if (trace->stop_node() != NULL) { |
| 1571 | return CONTINUE; |
| 1572 | } |
| 1573 | |
| 1574 | RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| 1575 | if (trace->is_trivial()) { |
| 1576 | if (label_.is_bound()) { |
| 1577 | // We are being asked to generate a generic version, but that's already |
| 1578 | // been done so just go to it. |
| 1579 | macro_assembler->GoTo(&label_); |
| 1580 | return DONE; |
| 1581 | } |
| 1582 | if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) { |
| 1583 | // To avoid too deep recursion we push the node to the work queue and just |
| 1584 | // generate a goto here. |
| 1585 | compiler->AddWork(this); |
| 1586 | macro_assembler->GoTo(&label_); |
| 1587 | return DONE; |
| 1588 | } |
| 1589 | // Generate generic version of the node and bind the label for later use. |
| 1590 | macro_assembler->Bind(&label_); |
| 1591 | return CONTINUE; |
| 1592 | } |
| 1593 | |
| 1594 | // We are being asked to make a non-generic version. Keep track of how many |
| 1595 | // non-generic versions we generate so as not to overdo it. |
| 1596 | trace_count_++; |
| 1597 | if (FLAG_regexp_optimization && |
| 1598 | trace_count_ < kMaxCopiesCodeGenerated && |
| 1599 | compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) { |
| 1600 | return CONTINUE; |
| 1601 | } |
| 1602 | |
| 1603 | // If we get here code has been generated for this node too many times or |
| 1604 | // recursion is too deep. Time to switch to a generic version. The code for |
| 1605 | // generic versions above can handle deep recursion properly. |
| 1606 | trace->Flush(compiler, this); |
| 1607 | return DONE; |
| 1608 | } |
| 1609 | |
| 1610 | |
| 1611 | int ActionNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
| 1612 | if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0; |
| 1613 | if (type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input! |
| 1614 | return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1); |
| 1615 | } |
| 1616 | |
| 1617 | |
| 1618 | int AssertionNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
| 1619 | if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0; |
| 1620 | return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1); |
| 1621 | } |
| 1622 | |
| 1623 | |
| 1624 | int BackReferenceNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
| 1625 | if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0; |
| 1626 | return on_success()->EatsAtLeast(still_to_find, recursion_depth + 1); |
| 1627 | } |
| 1628 | |
| 1629 | |
| 1630 | int TextNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
| 1631 | int answer = Length(); |
| 1632 | if (answer >= still_to_find) return answer; |
| 1633 | if (recursion_depth > RegExpCompiler::kMaxRecursion) return answer; |
| 1634 | return answer + on_success()->EatsAtLeast(still_to_find - answer, |
| 1635 | recursion_depth + 1); |
| 1636 | } |
| 1637 | |
| 1638 | |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 1639 | int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find, |
| 1640 | int recursion_depth) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 1641 | if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0; |
| 1642 | // Alternative 0 is the negative lookahead, alternative 1 is what comes |
| 1643 | // afterwards. |
| 1644 | RegExpNode* node = alternatives_->at(1).node(); |
| 1645 | return node->EatsAtLeast(still_to_find, recursion_depth + 1); |
| 1646 | } |
| 1647 | |
| 1648 | |
| 1649 | void NegativeLookaheadChoiceNode::GetQuickCheckDetails( |
| 1650 | QuickCheckDetails* details, |
| 1651 | RegExpCompiler* compiler, |
| 1652 | int filled_in, |
| 1653 | bool not_at_start) { |
| 1654 | // Alternative 0 is the negative lookahead, alternative 1 is what comes |
| 1655 | // afterwards. |
| 1656 | RegExpNode* node = alternatives_->at(1).node(); |
| 1657 | return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start); |
| 1658 | } |
| 1659 | |
| 1660 | |
| 1661 | int ChoiceNode::EatsAtLeastHelper(int still_to_find, |
| 1662 | int recursion_depth, |
| 1663 | RegExpNode* ignore_this_node) { |
| 1664 | if (recursion_depth > RegExpCompiler::kMaxRecursion) return 0; |
| 1665 | int min = 100; |
| 1666 | int choice_count = alternatives_->length(); |
| 1667 | for (int i = 0; i < choice_count; i++) { |
| 1668 | RegExpNode* node = alternatives_->at(i).node(); |
| 1669 | if (node == ignore_this_node) continue; |
| 1670 | int node_eats_at_least = node->EatsAtLeast(still_to_find, |
| 1671 | recursion_depth + 1); |
| 1672 | if (node_eats_at_least < min) min = node_eats_at_least; |
| 1673 | } |
| 1674 | return min; |
| 1675 | } |
| 1676 | |
| 1677 | |
| 1678 | int LoopChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
| 1679 | return EatsAtLeastHelper(still_to_find, recursion_depth, loop_node_); |
| 1680 | } |
| 1681 | |
| 1682 | |
| 1683 | int ChoiceNode::EatsAtLeast(int still_to_find, int recursion_depth) { |
| 1684 | return EatsAtLeastHelper(still_to_find, recursion_depth, NULL); |
| 1685 | } |
| 1686 | |
| 1687 | |
| 1688 | // Takes the left-most 1-bit and smears it out, setting all bits to its right. |
| 1689 | static inline uint32_t SmearBitsRight(uint32_t v) { |
| 1690 | v |= v >> 1; |
| 1691 | v |= v >> 2; |
| 1692 | v |= v >> 4; |
| 1693 | v |= v >> 8; |
| 1694 | v |= v >> 16; |
| 1695 | return v; |
| 1696 | } |
| 1697 | |
| 1698 | |
| 1699 | bool QuickCheckDetails::Rationalize(bool asc) { |
| 1700 | bool found_useful_op = false; |
| 1701 | uint32_t char_mask; |
| 1702 | if (asc) { |
| 1703 | char_mask = String::kMaxAsciiCharCode; |
| 1704 | } else { |
| 1705 | char_mask = String::kMaxUC16CharCode; |
| 1706 | } |
| 1707 | mask_ = 0; |
| 1708 | value_ = 0; |
| 1709 | int char_shift = 0; |
| 1710 | for (int i = 0; i < characters_; i++) { |
| 1711 | Position* pos = &positions_[i]; |
| 1712 | if ((pos->mask & String::kMaxAsciiCharCode) != 0) { |
| 1713 | found_useful_op = true; |
| 1714 | } |
| 1715 | mask_ |= (pos->mask & char_mask) << char_shift; |
| 1716 | value_ |= (pos->value & char_mask) << char_shift; |
| 1717 | char_shift += asc ? 8 : 16; |
| 1718 | } |
| 1719 | return found_useful_op; |
| 1720 | } |
| 1721 | |
| 1722 | |
| 1723 | bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler, |
| 1724 | Trace* trace, |
| 1725 | bool preload_has_checked_bounds, |
| 1726 | Label* on_possible_success, |
| 1727 | QuickCheckDetails* details, |
| 1728 | bool fall_through_on_failure) { |
| 1729 | if (details->characters() == 0) return false; |
| 1730 | GetQuickCheckDetails(details, compiler, 0, trace->at_start() == Trace::FALSE); |
| 1731 | if (details->cannot_match()) return false; |
| 1732 | if (!details->Rationalize(compiler->ascii())) return false; |
| 1733 | ASSERT(details->characters() == 1 || |
| 1734 | compiler->macro_assembler()->CanReadUnaligned()); |
| 1735 | uint32_t mask = details->mask(); |
| 1736 | uint32_t value = details->value(); |
| 1737 | |
| 1738 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 1739 | |
| 1740 | if (trace->characters_preloaded() != details->characters()) { |
| 1741 | assembler->LoadCurrentCharacter(trace->cp_offset(), |
| 1742 | trace->backtrack(), |
| 1743 | !preload_has_checked_bounds, |
| 1744 | details->characters()); |
| 1745 | } |
| 1746 | |
| 1747 | |
| 1748 | bool need_mask = true; |
| 1749 | |
| 1750 | if (details->characters() == 1) { |
| 1751 | // If number of characters preloaded is 1 then we used a byte or 16 bit |
| 1752 | // load so the value is already masked down. |
| 1753 | uint32_t char_mask; |
| 1754 | if (compiler->ascii()) { |
| 1755 | char_mask = String::kMaxAsciiCharCode; |
| 1756 | } else { |
| 1757 | char_mask = String::kMaxUC16CharCode; |
| 1758 | } |
| 1759 | if ((mask & char_mask) == char_mask) need_mask = false; |
| 1760 | mask &= char_mask; |
| 1761 | } else { |
Kristian Monsen | 9dcf7e2 | 2010-06-28 14:14:28 +0100 | [diff] [blame] | 1762 | // For 2-character preloads in ASCII mode or 1-character preloads in |
| 1763 | // TWO_BYTE mode we also use a 16 bit load with zero extend. |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 1764 | if (details->characters() == 2 && compiler->ascii()) { |
Kristian Monsen | 9dcf7e2 | 2010-06-28 14:14:28 +0100 | [diff] [blame] | 1765 | if ((mask & 0x7f7f) == 0x7f7f) need_mask = false; |
| 1766 | } else if (details->characters() == 1 && !compiler->ascii()) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 1767 | if ((mask & 0xffff) == 0xffff) need_mask = false; |
| 1768 | } else { |
| 1769 | if (mask == 0xffffffff) need_mask = false; |
| 1770 | } |
| 1771 | } |
| 1772 | |
| 1773 | if (fall_through_on_failure) { |
| 1774 | if (need_mask) { |
| 1775 | assembler->CheckCharacterAfterAnd(value, mask, on_possible_success); |
| 1776 | } else { |
| 1777 | assembler->CheckCharacter(value, on_possible_success); |
| 1778 | } |
| 1779 | } else { |
| 1780 | if (need_mask) { |
| 1781 | assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack()); |
| 1782 | } else { |
| 1783 | assembler->CheckNotCharacter(value, trace->backtrack()); |
| 1784 | } |
| 1785 | } |
| 1786 | return true; |
| 1787 | } |
| 1788 | |
| 1789 | |
| 1790 | // Here is the meat of GetQuickCheckDetails (see also the comment on the |
| 1791 | // super-class in the .h file). |
| 1792 | // |
| 1793 | // We iterate along the text object, building up for each character a |
| 1794 | // mask and value that can be used to test for a quick failure to match. |
| 1795 | // The masks and values for the positions will be combined into a single |
| 1796 | // machine word for the current character width in order to be used in |
| 1797 | // generating a quick check. |
| 1798 | void TextNode::GetQuickCheckDetails(QuickCheckDetails* details, |
| 1799 | RegExpCompiler* compiler, |
| 1800 | int characters_filled_in, |
| 1801 | bool not_at_start) { |
| 1802 | ASSERT(characters_filled_in < details->characters()); |
| 1803 | int characters = details->characters(); |
| 1804 | int char_mask; |
| 1805 | int char_shift; |
| 1806 | if (compiler->ascii()) { |
| 1807 | char_mask = String::kMaxAsciiCharCode; |
| 1808 | char_shift = 8; |
| 1809 | } else { |
| 1810 | char_mask = String::kMaxUC16CharCode; |
| 1811 | char_shift = 16; |
| 1812 | } |
| 1813 | for (int k = 0; k < elms_->length(); k++) { |
| 1814 | TextElement elm = elms_->at(k); |
| 1815 | if (elm.type == TextElement::ATOM) { |
| 1816 | Vector<const uc16> quarks = elm.data.u_atom->data(); |
| 1817 | for (int i = 0; i < characters && i < quarks.length(); i++) { |
| 1818 | QuickCheckDetails::Position* pos = |
| 1819 | details->positions(characters_filled_in); |
| 1820 | uc16 c = quarks[i]; |
| 1821 | if (c > char_mask) { |
| 1822 | // If we expect a non-ASCII character from an ASCII string, |
| 1823 | // there is no way we can match. Not even case independent |
| 1824 | // matching can turn an ASCII character into non-ASCII or |
| 1825 | // vice versa. |
| 1826 | details->set_cannot_match(); |
| 1827 | pos->determines_perfectly = false; |
| 1828 | return; |
| 1829 | } |
| 1830 | if (compiler->ignore_case()) { |
| 1831 | unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| 1832 | int length = GetCaseIndependentLetters(c, compiler->ascii(), chars); |
| 1833 | ASSERT(length != 0); // Can only happen if c > char_mask (see above). |
| 1834 | if (length == 1) { |
| 1835 | // This letter has no case equivalents, so it's nice and simple |
| 1836 | // and the mask-compare will determine definitely whether we have |
| 1837 | // a match at this character position. |
| 1838 | pos->mask = char_mask; |
| 1839 | pos->value = c; |
| 1840 | pos->determines_perfectly = true; |
| 1841 | } else { |
| 1842 | uint32_t common_bits = char_mask; |
| 1843 | uint32_t bits = chars[0]; |
| 1844 | for (int j = 1; j < length; j++) { |
| 1845 | uint32_t differing_bits = ((chars[j] & common_bits) ^ bits); |
| 1846 | common_bits ^= differing_bits; |
| 1847 | bits &= common_bits; |
| 1848 | } |
| 1849 | // If length is 2 and common bits has only one zero in it then |
| 1850 | // our mask and compare instruction will determine definitely |
| 1851 | // whether we have a match at this character position. Otherwise |
| 1852 | // it can only be an approximate check. |
| 1853 | uint32_t one_zero = (common_bits | ~char_mask); |
| 1854 | if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) { |
| 1855 | pos->determines_perfectly = true; |
| 1856 | } |
| 1857 | pos->mask = common_bits; |
| 1858 | pos->value = bits; |
| 1859 | } |
| 1860 | } else { |
| 1861 | // Don't ignore case. Nice simple case where the mask-compare will |
| 1862 | // determine definitely whether we have a match at this character |
| 1863 | // position. |
| 1864 | pos->mask = char_mask; |
| 1865 | pos->value = c; |
| 1866 | pos->determines_perfectly = true; |
| 1867 | } |
| 1868 | characters_filled_in++; |
| 1869 | ASSERT(characters_filled_in <= details->characters()); |
| 1870 | if (characters_filled_in == details->characters()) { |
| 1871 | return; |
| 1872 | } |
| 1873 | } |
| 1874 | } else { |
| 1875 | QuickCheckDetails::Position* pos = |
| 1876 | details->positions(characters_filled_in); |
| 1877 | RegExpCharacterClass* tree = elm.data.u_char_class; |
| 1878 | ZoneList<CharacterRange>* ranges = tree->ranges(); |
| 1879 | if (tree->is_negated()) { |
| 1880 | // A quick check uses multi-character mask and compare. There is no |
| 1881 | // useful way to incorporate a negative char class into this scheme |
| 1882 | // so we just conservatively create a mask and value that will always |
| 1883 | // succeed. |
| 1884 | pos->mask = 0; |
| 1885 | pos->value = 0; |
| 1886 | } else { |
| 1887 | int first_range = 0; |
| 1888 | while (ranges->at(first_range).from() > char_mask) { |
| 1889 | first_range++; |
| 1890 | if (first_range == ranges->length()) { |
| 1891 | details->set_cannot_match(); |
| 1892 | pos->determines_perfectly = false; |
| 1893 | return; |
| 1894 | } |
| 1895 | } |
| 1896 | CharacterRange range = ranges->at(first_range); |
| 1897 | uc16 from = range.from(); |
| 1898 | uc16 to = range.to(); |
| 1899 | if (to > char_mask) { |
| 1900 | to = char_mask; |
| 1901 | } |
| 1902 | uint32_t differing_bits = (from ^ to); |
| 1903 | // A mask and compare is only perfect if the differing bits form a |
| 1904 | // number like 00011111 with one single block of trailing 1s. |
| 1905 | if ((differing_bits & (differing_bits + 1)) == 0 && |
| 1906 | from + differing_bits == to) { |
| 1907 | pos->determines_perfectly = true; |
| 1908 | } |
| 1909 | uint32_t common_bits = ~SmearBitsRight(differing_bits); |
| 1910 | uint32_t bits = (from & common_bits); |
| 1911 | for (int i = first_range + 1; i < ranges->length(); i++) { |
| 1912 | CharacterRange range = ranges->at(i); |
| 1913 | uc16 from = range.from(); |
| 1914 | uc16 to = range.to(); |
| 1915 | if (from > char_mask) continue; |
| 1916 | if (to > char_mask) to = char_mask; |
| 1917 | // Here we are combining more ranges into the mask and compare |
| 1918 | // value. With each new range the mask becomes more sparse and |
| 1919 | // so the chances of a false positive rise. A character class |
| 1920 | // with multiple ranges is assumed never to be equivalent to a |
| 1921 | // mask and compare operation. |
| 1922 | pos->determines_perfectly = false; |
| 1923 | uint32_t new_common_bits = (from ^ to); |
| 1924 | new_common_bits = ~SmearBitsRight(new_common_bits); |
| 1925 | common_bits &= new_common_bits; |
| 1926 | bits &= new_common_bits; |
| 1927 | uint32_t differing_bits = (from & common_bits) ^ bits; |
| 1928 | common_bits ^= differing_bits; |
| 1929 | bits &= common_bits; |
| 1930 | } |
| 1931 | pos->mask = common_bits; |
| 1932 | pos->value = bits; |
| 1933 | } |
| 1934 | characters_filled_in++; |
| 1935 | ASSERT(characters_filled_in <= details->characters()); |
| 1936 | if (characters_filled_in == details->characters()) { |
| 1937 | return; |
| 1938 | } |
| 1939 | } |
| 1940 | } |
| 1941 | ASSERT(characters_filled_in != details->characters()); |
| 1942 | on_success()-> GetQuickCheckDetails(details, |
| 1943 | compiler, |
| 1944 | characters_filled_in, |
| 1945 | true); |
| 1946 | } |
| 1947 | |
| 1948 | |
| 1949 | void QuickCheckDetails::Clear() { |
| 1950 | for (int i = 0; i < characters_; i++) { |
| 1951 | positions_[i].mask = 0; |
| 1952 | positions_[i].value = 0; |
| 1953 | positions_[i].determines_perfectly = false; |
| 1954 | } |
| 1955 | characters_ = 0; |
| 1956 | } |
| 1957 | |
| 1958 | |
| 1959 | void QuickCheckDetails::Advance(int by, bool ascii) { |
| 1960 | ASSERT(by >= 0); |
| 1961 | if (by >= characters_) { |
| 1962 | Clear(); |
| 1963 | return; |
| 1964 | } |
| 1965 | for (int i = 0; i < characters_ - by; i++) { |
| 1966 | positions_[i] = positions_[by + i]; |
| 1967 | } |
| 1968 | for (int i = characters_ - by; i < characters_; i++) { |
| 1969 | positions_[i].mask = 0; |
| 1970 | positions_[i].value = 0; |
| 1971 | positions_[i].determines_perfectly = false; |
| 1972 | } |
| 1973 | characters_ -= by; |
| 1974 | // We could change mask_ and value_ here but we would never advance unless |
| 1975 | // they had already been used in a check and they won't be used again because |
| 1976 | // it would gain us nothing. So there's no point. |
| 1977 | } |
| 1978 | |
| 1979 | |
| 1980 | void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) { |
| 1981 | ASSERT(characters_ == other->characters_); |
| 1982 | if (other->cannot_match_) { |
| 1983 | return; |
| 1984 | } |
| 1985 | if (cannot_match_) { |
| 1986 | *this = *other; |
| 1987 | return; |
| 1988 | } |
| 1989 | for (int i = from_index; i < characters_; i++) { |
| 1990 | QuickCheckDetails::Position* pos = positions(i); |
| 1991 | QuickCheckDetails::Position* other_pos = other->positions(i); |
| 1992 | if (pos->mask != other_pos->mask || |
| 1993 | pos->value != other_pos->value || |
| 1994 | !other_pos->determines_perfectly) { |
| 1995 | // Our mask-compare operation will be approximate unless we have the |
| 1996 | // exact same operation on both sides of the alternation. |
| 1997 | pos->determines_perfectly = false; |
| 1998 | } |
| 1999 | pos->mask &= other_pos->mask; |
| 2000 | pos->value &= pos->mask; |
| 2001 | other_pos->value &= pos->mask; |
| 2002 | uc16 differing_bits = (pos->value ^ other_pos->value); |
| 2003 | pos->mask &= ~differing_bits; |
| 2004 | pos->value &= pos->mask; |
| 2005 | } |
| 2006 | } |
| 2007 | |
| 2008 | |
| 2009 | class VisitMarker { |
| 2010 | public: |
| 2011 | explicit VisitMarker(NodeInfo* info) : info_(info) { |
| 2012 | ASSERT(!info->visited); |
| 2013 | info->visited = true; |
| 2014 | } |
| 2015 | ~VisitMarker() { |
| 2016 | info_->visited = false; |
| 2017 | } |
| 2018 | private: |
| 2019 | NodeInfo* info_; |
| 2020 | }; |
| 2021 | |
| 2022 | |
| 2023 | void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details, |
| 2024 | RegExpCompiler* compiler, |
| 2025 | int characters_filled_in, |
| 2026 | bool not_at_start) { |
| 2027 | if (body_can_be_zero_length_ || info()->visited) return; |
| 2028 | VisitMarker marker(info()); |
| 2029 | return ChoiceNode::GetQuickCheckDetails(details, |
| 2030 | compiler, |
| 2031 | characters_filled_in, |
| 2032 | not_at_start); |
| 2033 | } |
| 2034 | |
| 2035 | |
| 2036 | void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details, |
| 2037 | RegExpCompiler* compiler, |
| 2038 | int characters_filled_in, |
| 2039 | bool not_at_start) { |
| 2040 | not_at_start = (not_at_start || not_at_start_); |
| 2041 | int choice_count = alternatives_->length(); |
| 2042 | ASSERT(choice_count > 0); |
| 2043 | alternatives_->at(0).node()->GetQuickCheckDetails(details, |
| 2044 | compiler, |
| 2045 | characters_filled_in, |
| 2046 | not_at_start); |
| 2047 | for (int i = 1; i < choice_count; i++) { |
| 2048 | QuickCheckDetails new_details(details->characters()); |
| 2049 | RegExpNode* node = alternatives_->at(i).node(); |
| 2050 | node->GetQuickCheckDetails(&new_details, compiler, |
| 2051 | characters_filled_in, |
| 2052 | not_at_start); |
| 2053 | // Here we merge the quick match details of the two branches. |
| 2054 | details->Merge(&new_details, characters_filled_in); |
| 2055 | } |
| 2056 | } |
| 2057 | |
| 2058 | |
| 2059 | // Check for [0-9A-Z_a-z]. |
| 2060 | static void EmitWordCheck(RegExpMacroAssembler* assembler, |
| 2061 | Label* word, |
| 2062 | Label* non_word, |
| 2063 | bool fall_through_on_word) { |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 2064 | if (assembler->CheckSpecialCharacterClass( |
| 2065 | fall_through_on_word ? 'w' : 'W', |
| 2066 | fall_through_on_word ? non_word : word)) { |
| 2067 | // Optimized implementation available. |
| 2068 | return; |
| 2069 | } |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2070 | assembler->CheckCharacterGT('z', non_word); |
| 2071 | assembler->CheckCharacterLT('0', non_word); |
| 2072 | assembler->CheckCharacterGT('a' - 1, word); |
| 2073 | assembler->CheckCharacterLT('9' + 1, word); |
| 2074 | assembler->CheckCharacterLT('A', non_word); |
| 2075 | assembler->CheckCharacterLT('Z' + 1, word); |
| 2076 | if (fall_through_on_word) { |
| 2077 | assembler->CheckNotCharacter('_', non_word); |
| 2078 | } else { |
| 2079 | assembler->CheckCharacter('_', word); |
| 2080 | } |
| 2081 | } |
| 2082 | |
| 2083 | |
| 2084 | // Emit the code to check for a ^ in multiline mode (1-character lookbehind |
| 2085 | // that matches newline or the start of input). |
| 2086 | static void EmitHat(RegExpCompiler* compiler, |
| 2087 | RegExpNode* on_success, |
| 2088 | Trace* trace) { |
| 2089 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 2090 | // We will be loading the previous character into the current character |
| 2091 | // register. |
| 2092 | Trace new_trace(*trace); |
| 2093 | new_trace.InvalidateCurrentCharacter(); |
| 2094 | |
| 2095 | Label ok; |
| 2096 | if (new_trace.cp_offset() == 0) { |
| 2097 | // The start of input counts as a newline in this context, so skip to |
| 2098 | // ok if we are at the start. |
| 2099 | assembler->CheckAtStart(&ok); |
| 2100 | } |
| 2101 | // We already checked that we are not at the start of input so it must be |
| 2102 | // OK to load the previous character. |
| 2103 | assembler->LoadCurrentCharacter(new_trace.cp_offset() -1, |
| 2104 | new_trace.backtrack(), |
| 2105 | false); |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 2106 | if (!assembler->CheckSpecialCharacterClass('n', |
| 2107 | new_trace.backtrack())) { |
| 2108 | // Newline means \n, \r, 0x2028 or 0x2029. |
| 2109 | if (!compiler->ascii()) { |
| 2110 | assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok); |
| 2111 | } |
| 2112 | assembler->CheckCharacter('\n', &ok); |
| 2113 | assembler->CheckNotCharacter('\r', new_trace.backtrack()); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2114 | } |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2115 | assembler->Bind(&ok); |
| 2116 | on_success->Emit(compiler, &new_trace); |
| 2117 | } |
| 2118 | |
| 2119 | |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 2120 | // Emit the code to handle \b and \B (word-boundary or non-word-boundary) |
| 2121 | // when we know whether the next character must be a word character or not. |
| 2122 | static void EmitHalfBoundaryCheck(AssertionNode::AssertionNodeType type, |
| 2123 | RegExpCompiler* compiler, |
| 2124 | RegExpNode* on_success, |
| 2125 | Trace* trace) { |
| 2126 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 2127 | Label done; |
| 2128 | |
| 2129 | Trace new_trace(*trace); |
| 2130 | |
| 2131 | bool expect_word_character = (type == AssertionNode::AFTER_WORD_CHARACTER); |
| 2132 | Label* on_word = expect_word_character ? &done : new_trace.backtrack(); |
| 2133 | Label* on_non_word = expect_word_character ? new_trace.backtrack() : &done; |
| 2134 | |
| 2135 | // Check whether previous character was a word character. |
| 2136 | switch (trace->at_start()) { |
| 2137 | case Trace::TRUE: |
| 2138 | if (expect_word_character) { |
| 2139 | assembler->GoTo(on_non_word); |
| 2140 | } |
| 2141 | break; |
| 2142 | case Trace::UNKNOWN: |
| 2143 | ASSERT_EQ(0, trace->cp_offset()); |
| 2144 | assembler->CheckAtStart(on_non_word); |
| 2145 | // Fall through. |
| 2146 | case Trace::FALSE: |
| 2147 | int prev_char_offset = trace->cp_offset() - 1; |
| 2148 | assembler->LoadCurrentCharacter(prev_char_offset, NULL, false, 1); |
| 2149 | EmitWordCheck(assembler, on_word, on_non_word, expect_word_character); |
| 2150 | // We may or may not have loaded the previous character. |
| 2151 | new_trace.InvalidateCurrentCharacter(); |
| 2152 | } |
| 2153 | |
| 2154 | assembler->Bind(&done); |
| 2155 | |
| 2156 | on_success->Emit(compiler, &new_trace); |
| 2157 | } |
| 2158 | |
| 2159 | |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2160 | // Emit the code to handle \b and \B (word-boundary or non-word-boundary). |
| 2161 | static void EmitBoundaryCheck(AssertionNode::AssertionNodeType type, |
| 2162 | RegExpCompiler* compiler, |
| 2163 | RegExpNode* on_success, |
| 2164 | Trace* trace) { |
| 2165 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 2166 | Label before_non_word; |
| 2167 | Label before_word; |
| 2168 | if (trace->characters_preloaded() != 1) { |
| 2169 | assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word); |
| 2170 | } |
| 2171 | // Fall through on non-word. |
| 2172 | EmitWordCheck(assembler, &before_word, &before_non_word, false); |
| 2173 | |
| 2174 | // We will be loading the previous character into the current character |
| 2175 | // register. |
| 2176 | Trace new_trace(*trace); |
| 2177 | new_trace.InvalidateCurrentCharacter(); |
| 2178 | |
| 2179 | Label ok; |
| 2180 | Label* boundary; |
| 2181 | Label* not_boundary; |
| 2182 | if (type == AssertionNode::AT_BOUNDARY) { |
| 2183 | boundary = &ok; |
| 2184 | not_boundary = new_trace.backtrack(); |
| 2185 | } else { |
| 2186 | not_boundary = &ok; |
| 2187 | boundary = new_trace.backtrack(); |
| 2188 | } |
| 2189 | |
| 2190 | // Next character is not a word character. |
| 2191 | assembler->Bind(&before_non_word); |
| 2192 | if (new_trace.cp_offset() == 0) { |
| 2193 | // The start of input counts as a non-word character, so the question is |
| 2194 | // decided if we are at the start. |
| 2195 | assembler->CheckAtStart(not_boundary); |
| 2196 | } |
| 2197 | // We already checked that we are not at the start of input so it must be |
| 2198 | // OK to load the previous character. |
| 2199 | assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, |
| 2200 | &ok, // Unused dummy label in this call. |
| 2201 | false); |
| 2202 | // Fall through on non-word. |
| 2203 | EmitWordCheck(assembler, boundary, not_boundary, false); |
| 2204 | assembler->GoTo(not_boundary); |
| 2205 | |
| 2206 | // Next character is a word character. |
| 2207 | assembler->Bind(&before_word); |
| 2208 | if (new_trace.cp_offset() == 0) { |
| 2209 | // The start of input counts as a non-word character, so the question is |
| 2210 | // decided if we are at the start. |
| 2211 | assembler->CheckAtStart(boundary); |
| 2212 | } |
| 2213 | // We already checked that we are not at the start of input so it must be |
| 2214 | // OK to load the previous character. |
| 2215 | assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, |
| 2216 | &ok, // Unused dummy label in this call. |
| 2217 | false); |
| 2218 | bool fall_through_on_word = (type == AssertionNode::AT_NON_BOUNDARY); |
| 2219 | EmitWordCheck(assembler, not_boundary, boundary, fall_through_on_word); |
| 2220 | |
| 2221 | assembler->Bind(&ok); |
| 2222 | |
| 2223 | on_success->Emit(compiler, &new_trace); |
| 2224 | } |
| 2225 | |
| 2226 | |
| 2227 | void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details, |
| 2228 | RegExpCompiler* compiler, |
| 2229 | int filled_in, |
| 2230 | bool not_at_start) { |
| 2231 | if (type_ == AT_START && not_at_start) { |
| 2232 | details->set_cannot_match(); |
| 2233 | return; |
| 2234 | } |
| 2235 | return on_success()->GetQuickCheckDetails(details, |
| 2236 | compiler, |
| 2237 | filled_in, |
| 2238 | not_at_start); |
| 2239 | } |
| 2240 | |
| 2241 | |
| 2242 | void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| 2243 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 2244 | switch (type_) { |
| 2245 | case AT_END: { |
| 2246 | Label ok; |
| 2247 | assembler->CheckPosition(trace->cp_offset(), &ok); |
| 2248 | assembler->GoTo(trace->backtrack()); |
| 2249 | assembler->Bind(&ok); |
| 2250 | break; |
| 2251 | } |
| 2252 | case AT_START: { |
| 2253 | if (trace->at_start() == Trace::FALSE) { |
| 2254 | assembler->GoTo(trace->backtrack()); |
| 2255 | return; |
| 2256 | } |
| 2257 | if (trace->at_start() == Trace::UNKNOWN) { |
| 2258 | assembler->CheckNotAtStart(trace->backtrack()); |
| 2259 | Trace at_start_trace = *trace; |
| 2260 | at_start_trace.set_at_start(true); |
| 2261 | on_success()->Emit(compiler, &at_start_trace); |
| 2262 | return; |
| 2263 | } |
| 2264 | } |
| 2265 | break; |
| 2266 | case AFTER_NEWLINE: |
| 2267 | EmitHat(compiler, on_success(), trace); |
| 2268 | return; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2269 | case AT_BOUNDARY: |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 2270 | case AT_NON_BOUNDARY: { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2271 | EmitBoundaryCheck(type_, compiler, on_success(), trace); |
| 2272 | return; |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 2273 | } |
| 2274 | case AFTER_WORD_CHARACTER: |
| 2275 | case AFTER_NONWORD_CHARACTER: { |
| 2276 | EmitHalfBoundaryCheck(type_, compiler, on_success(), trace); |
| 2277 | } |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2278 | } |
| 2279 | on_success()->Emit(compiler, trace); |
| 2280 | } |
| 2281 | |
| 2282 | |
| 2283 | static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) { |
| 2284 | if (quick_check == NULL) return false; |
| 2285 | if (offset >= quick_check->characters()) return false; |
| 2286 | return quick_check->positions(offset)->determines_perfectly; |
| 2287 | } |
| 2288 | |
| 2289 | |
| 2290 | static void UpdateBoundsCheck(int index, int* checked_up_to) { |
| 2291 | if (index > *checked_up_to) { |
| 2292 | *checked_up_to = index; |
| 2293 | } |
| 2294 | } |
| 2295 | |
| 2296 | |
| 2297 | // We call this repeatedly to generate code for each pass over the text node. |
| 2298 | // The passes are in increasing order of difficulty because we hope one |
| 2299 | // of the first passes will fail in which case we are saved the work of the |
| 2300 | // later passes. for example for the case independent regexp /%[asdfghjkl]a/ |
| 2301 | // we will check the '%' in the first pass, the case independent 'a' in the |
| 2302 | // second pass and the character class in the last pass. |
| 2303 | // |
| 2304 | // The passes are done from right to left, so for example to test for /bar/ |
| 2305 | // we will first test for an 'r' with offset 2, then an 'a' with offset 1 |
| 2306 | // and then a 'b' with offset 0. This means we can avoid the end-of-input |
| 2307 | // bounds check most of the time. In the example we only need to check for |
| 2308 | // end-of-input when loading the putative 'r'. |
| 2309 | // |
| 2310 | // A slight complication involves the fact that the first character may already |
| 2311 | // be fetched into a register by the previous node. In this case we want to |
| 2312 | // do the test for that character first. We do this in separate passes. The |
| 2313 | // 'preloaded' argument indicates that we are doing such a 'pass'. If such a |
| 2314 | // pass has been performed then subsequent passes will have true in |
| 2315 | // first_element_checked to indicate that that character does not need to be |
| 2316 | // checked again. |
| 2317 | // |
| 2318 | // In addition to all this we are passed a Trace, which can |
| 2319 | // contain an AlternativeGeneration object. In this AlternativeGeneration |
| 2320 | // object we can see details of any quick check that was already passed in |
| 2321 | // order to get to the code we are now generating. The quick check can involve |
| 2322 | // loading characters, which means we do not need to recheck the bounds |
| 2323 | // up to the limit the quick check already checked. In addition the quick |
| 2324 | // check can have involved a mask and compare operation which may simplify |
| 2325 | // or obviate the need for further checks at some character positions. |
| 2326 | void TextNode::TextEmitPass(RegExpCompiler* compiler, |
| 2327 | TextEmitPassType pass, |
| 2328 | bool preloaded, |
| 2329 | Trace* trace, |
| 2330 | bool first_element_checked, |
| 2331 | int* checked_up_to) { |
| 2332 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 2333 | bool ascii = compiler->ascii(); |
| 2334 | Label* backtrack = trace->backtrack(); |
| 2335 | QuickCheckDetails* quick_check = trace->quick_check_performed(); |
| 2336 | int element_count = elms_->length(); |
| 2337 | for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) { |
| 2338 | TextElement elm = elms_->at(i); |
| 2339 | int cp_offset = trace->cp_offset() + elm.cp_offset; |
| 2340 | if (elm.type == TextElement::ATOM) { |
| 2341 | Vector<const uc16> quarks = elm.data.u_atom->data(); |
| 2342 | for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) { |
| 2343 | if (first_element_checked && i == 0 && j == 0) continue; |
| 2344 | if (DeterminedAlready(quick_check, elm.cp_offset + j)) continue; |
| 2345 | EmitCharacterFunction* emit_function = NULL; |
| 2346 | switch (pass) { |
| 2347 | case NON_ASCII_MATCH: |
| 2348 | ASSERT(ascii); |
| 2349 | if (quarks[j] > String::kMaxAsciiCharCode) { |
| 2350 | assembler->GoTo(backtrack); |
| 2351 | return; |
| 2352 | } |
| 2353 | break; |
| 2354 | case NON_LETTER_CHARACTER_MATCH: |
| 2355 | emit_function = &EmitAtomNonLetter; |
| 2356 | break; |
| 2357 | case SIMPLE_CHARACTER_MATCH: |
| 2358 | emit_function = &EmitSimpleCharacter; |
| 2359 | break; |
| 2360 | case CASE_CHARACTER_MATCH: |
| 2361 | emit_function = &EmitAtomLetter; |
| 2362 | break; |
| 2363 | default: |
| 2364 | break; |
| 2365 | } |
| 2366 | if (emit_function != NULL) { |
| 2367 | bool bound_checked = emit_function(compiler, |
| 2368 | quarks[j], |
| 2369 | backtrack, |
| 2370 | cp_offset + j, |
| 2371 | *checked_up_to < cp_offset + j, |
| 2372 | preloaded); |
| 2373 | if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to); |
| 2374 | } |
| 2375 | } |
| 2376 | } else { |
| 2377 | ASSERT_EQ(elm.type, TextElement::CHAR_CLASS); |
| 2378 | if (pass == CHARACTER_CLASS_MATCH) { |
| 2379 | if (first_element_checked && i == 0) continue; |
| 2380 | if (DeterminedAlready(quick_check, elm.cp_offset)) continue; |
| 2381 | RegExpCharacterClass* cc = elm.data.u_char_class; |
| 2382 | EmitCharClass(assembler, |
| 2383 | cc, |
| 2384 | ascii, |
| 2385 | backtrack, |
| 2386 | cp_offset, |
| 2387 | *checked_up_to < cp_offset, |
| 2388 | preloaded); |
| 2389 | UpdateBoundsCheck(cp_offset, checked_up_to); |
| 2390 | } |
| 2391 | } |
| 2392 | } |
| 2393 | } |
| 2394 | |
| 2395 | |
| 2396 | int TextNode::Length() { |
| 2397 | TextElement elm = elms_->last(); |
| 2398 | ASSERT(elm.cp_offset >= 0); |
| 2399 | if (elm.type == TextElement::ATOM) { |
| 2400 | return elm.cp_offset + elm.data.u_atom->data().length(); |
| 2401 | } else { |
| 2402 | return elm.cp_offset + 1; |
| 2403 | } |
| 2404 | } |
| 2405 | |
| 2406 | |
| 2407 | bool TextNode::SkipPass(int int_pass, bool ignore_case) { |
| 2408 | TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass); |
| 2409 | if (ignore_case) { |
| 2410 | return pass == SIMPLE_CHARACTER_MATCH; |
| 2411 | } else { |
| 2412 | return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH; |
| 2413 | } |
| 2414 | } |
| 2415 | |
| 2416 | |
| 2417 | // This generates the code to match a text node. A text node can contain |
| 2418 | // straight character sequences (possibly to be matched in a case-independent |
| 2419 | // way) and character classes. For efficiency we do not do this in a single |
| 2420 | // pass from left to right. Instead we pass over the text node several times, |
| 2421 | // emitting code for some character positions every time. See the comment on |
| 2422 | // TextEmitPass for details. |
| 2423 | void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| 2424 | LimitResult limit_result = LimitVersions(compiler, trace); |
| 2425 | if (limit_result == DONE) return; |
| 2426 | ASSERT(limit_result == CONTINUE); |
| 2427 | |
| 2428 | if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) { |
| 2429 | compiler->SetRegExpTooBig(); |
| 2430 | return; |
| 2431 | } |
| 2432 | |
| 2433 | if (compiler->ascii()) { |
| 2434 | int dummy = 0; |
| 2435 | TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy); |
| 2436 | } |
| 2437 | |
| 2438 | bool first_elt_done = false; |
| 2439 | int bound_checked_to = trace->cp_offset() - 1; |
| 2440 | bound_checked_to += trace->bound_checked_up_to(); |
| 2441 | |
| 2442 | // If a character is preloaded into the current character register then |
| 2443 | // check that now. |
| 2444 | if (trace->characters_preloaded() == 1) { |
| 2445 | for (int pass = kFirstRealPass; pass <= kLastPass; pass++) { |
| 2446 | if (!SkipPass(pass, compiler->ignore_case())) { |
| 2447 | TextEmitPass(compiler, |
| 2448 | static_cast<TextEmitPassType>(pass), |
| 2449 | true, |
| 2450 | trace, |
| 2451 | false, |
| 2452 | &bound_checked_to); |
| 2453 | } |
| 2454 | } |
| 2455 | first_elt_done = true; |
| 2456 | } |
| 2457 | |
| 2458 | for (int pass = kFirstRealPass; pass <= kLastPass; pass++) { |
| 2459 | if (!SkipPass(pass, compiler->ignore_case())) { |
| 2460 | TextEmitPass(compiler, |
| 2461 | static_cast<TextEmitPassType>(pass), |
| 2462 | false, |
| 2463 | trace, |
| 2464 | first_elt_done, |
| 2465 | &bound_checked_to); |
| 2466 | } |
| 2467 | } |
| 2468 | |
| 2469 | Trace successor_trace(*trace); |
| 2470 | successor_trace.set_at_start(false); |
| 2471 | successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler); |
| 2472 | RecursionCheck rc(compiler); |
| 2473 | on_success()->Emit(compiler, &successor_trace); |
| 2474 | } |
| 2475 | |
| 2476 | |
| 2477 | void Trace::InvalidateCurrentCharacter() { |
| 2478 | characters_preloaded_ = 0; |
| 2479 | } |
| 2480 | |
| 2481 | |
| 2482 | void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) { |
| 2483 | ASSERT(by > 0); |
| 2484 | // We don't have an instruction for shifting the current character register |
| 2485 | // down or for using a shifted value for anything so lets just forget that |
| 2486 | // we preloaded any characters into it. |
| 2487 | characters_preloaded_ = 0; |
| 2488 | // Adjust the offsets of the quick check performed information. This |
| 2489 | // information is used to find out what we already determined about the |
| 2490 | // characters by means of mask and compare. |
| 2491 | quick_check_performed_.Advance(by, compiler->ascii()); |
| 2492 | cp_offset_ += by; |
| 2493 | if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) { |
| 2494 | compiler->SetRegExpTooBig(); |
| 2495 | cp_offset_ = 0; |
| 2496 | } |
| 2497 | bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by); |
| 2498 | } |
| 2499 | |
| 2500 | |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 2501 | void TextNode::MakeCaseIndependent(bool is_ascii) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2502 | int element_count = elms_->length(); |
| 2503 | for (int i = 0; i < element_count; i++) { |
| 2504 | TextElement elm = elms_->at(i); |
| 2505 | if (elm.type == TextElement::CHAR_CLASS) { |
| 2506 | RegExpCharacterClass* cc = elm.data.u_char_class; |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 2507 | // None of the standard character classses is different in the case |
| 2508 | // independent case and it slows us down if we don't know that. |
| 2509 | if (cc->is_standard()) continue; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2510 | ZoneList<CharacterRange>* ranges = cc->ranges(); |
| 2511 | int range_count = ranges->length(); |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 2512 | for (int j = 0; j < range_count; j++) { |
| 2513 | ranges->at(j).AddCaseEquivalents(ranges, is_ascii); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2514 | } |
| 2515 | } |
| 2516 | } |
| 2517 | } |
| 2518 | |
| 2519 | |
| 2520 | int TextNode::GreedyLoopTextLength() { |
| 2521 | TextElement elm = elms_->at(elms_->length() - 1); |
| 2522 | if (elm.type == TextElement::CHAR_CLASS) { |
| 2523 | return elm.cp_offset + 1; |
| 2524 | } else { |
| 2525 | return elm.cp_offset + elm.data.u_atom->data().length(); |
| 2526 | } |
| 2527 | } |
| 2528 | |
| 2529 | |
| 2530 | // Finds the fixed match length of a sequence of nodes that goes from |
| 2531 | // this alternative and back to this choice node. If there are variable |
| 2532 | // length nodes or other complications in the way then return a sentinel |
| 2533 | // value indicating that a greedy loop cannot be constructed. |
| 2534 | int ChoiceNode::GreedyLoopTextLength(GuardedAlternative* alternative) { |
| 2535 | int length = 0; |
| 2536 | RegExpNode* node = alternative->node(); |
| 2537 | // Later we will generate code for all these text nodes using recursion |
| 2538 | // so we have to limit the max number. |
| 2539 | int recursion_depth = 0; |
| 2540 | while (node != this) { |
| 2541 | if (recursion_depth++ > RegExpCompiler::kMaxRecursion) { |
| 2542 | return kNodeIsTooComplexForGreedyLoops; |
| 2543 | } |
| 2544 | int node_length = node->GreedyLoopTextLength(); |
| 2545 | if (node_length == kNodeIsTooComplexForGreedyLoops) { |
| 2546 | return kNodeIsTooComplexForGreedyLoops; |
| 2547 | } |
| 2548 | length += node_length; |
| 2549 | SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node); |
| 2550 | node = seq_node->on_success(); |
| 2551 | } |
| 2552 | return length; |
| 2553 | } |
| 2554 | |
| 2555 | |
| 2556 | void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) { |
| 2557 | ASSERT_EQ(loop_node_, NULL); |
| 2558 | AddAlternative(alt); |
| 2559 | loop_node_ = alt.node(); |
| 2560 | } |
| 2561 | |
| 2562 | |
| 2563 | void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) { |
| 2564 | ASSERT_EQ(continue_node_, NULL); |
| 2565 | AddAlternative(alt); |
| 2566 | continue_node_ = alt.node(); |
| 2567 | } |
| 2568 | |
| 2569 | |
| 2570 | void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| 2571 | RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| 2572 | if (trace->stop_node() == this) { |
| 2573 | int text_length = GreedyLoopTextLength(&(alternatives_->at(0))); |
| 2574 | ASSERT(text_length != kNodeIsTooComplexForGreedyLoops); |
| 2575 | // Update the counter-based backtracking info on the stack. This is an |
| 2576 | // optimization for greedy loops (see below). |
| 2577 | ASSERT(trace->cp_offset() == text_length); |
| 2578 | macro_assembler->AdvanceCurrentPosition(text_length); |
| 2579 | macro_assembler->GoTo(trace->loop_label()); |
| 2580 | return; |
| 2581 | } |
| 2582 | ASSERT(trace->stop_node() == NULL); |
| 2583 | if (!trace->is_trivial()) { |
| 2584 | trace->Flush(compiler, this); |
| 2585 | return; |
| 2586 | } |
| 2587 | ChoiceNode::Emit(compiler, trace); |
| 2588 | } |
| 2589 | |
| 2590 | |
| 2591 | int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler) { |
| 2592 | int preload_characters = EatsAtLeast(4, 0); |
| 2593 | if (compiler->macro_assembler()->CanReadUnaligned()) { |
| 2594 | bool ascii = compiler->ascii(); |
| 2595 | if (ascii) { |
| 2596 | if (preload_characters > 4) preload_characters = 4; |
| 2597 | // We can't preload 3 characters because there is no machine instruction |
| 2598 | // to do that. We can't just load 4 because we could be reading |
| 2599 | // beyond the end of the string, which could cause a memory fault. |
| 2600 | if (preload_characters == 3) preload_characters = 2; |
| 2601 | } else { |
| 2602 | if (preload_characters > 2) preload_characters = 2; |
| 2603 | } |
| 2604 | } else { |
| 2605 | if (preload_characters > 1) preload_characters = 1; |
| 2606 | } |
| 2607 | return preload_characters; |
| 2608 | } |
| 2609 | |
| 2610 | |
| 2611 | // This class is used when generating the alternatives in a choice node. It |
| 2612 | // records the way the alternative is being code generated. |
| 2613 | class AlternativeGeneration: public Malloced { |
| 2614 | public: |
| 2615 | AlternativeGeneration() |
| 2616 | : possible_success(), |
| 2617 | expects_preload(false), |
| 2618 | after(), |
| 2619 | quick_check_details() { } |
| 2620 | Label possible_success; |
| 2621 | bool expects_preload; |
| 2622 | Label after; |
| 2623 | QuickCheckDetails quick_check_details; |
| 2624 | }; |
| 2625 | |
| 2626 | |
| 2627 | // Creates a list of AlternativeGenerations. If the list has a reasonable |
| 2628 | // size then it is on the stack, otherwise the excess is on the heap. |
| 2629 | class AlternativeGenerationList { |
| 2630 | public: |
| 2631 | explicit AlternativeGenerationList(int count) |
| 2632 | : alt_gens_(count) { |
| 2633 | for (int i = 0; i < count && i < kAFew; i++) { |
| 2634 | alt_gens_.Add(a_few_alt_gens_ + i); |
| 2635 | } |
| 2636 | for (int i = kAFew; i < count; i++) { |
| 2637 | alt_gens_.Add(new AlternativeGeneration()); |
| 2638 | } |
| 2639 | } |
| 2640 | ~AlternativeGenerationList() { |
| 2641 | for (int i = kAFew; i < alt_gens_.length(); i++) { |
| 2642 | delete alt_gens_[i]; |
| 2643 | alt_gens_[i] = NULL; |
| 2644 | } |
| 2645 | } |
| 2646 | |
| 2647 | AlternativeGeneration* at(int i) { |
| 2648 | return alt_gens_[i]; |
| 2649 | } |
| 2650 | private: |
| 2651 | static const int kAFew = 10; |
| 2652 | ZoneList<AlternativeGeneration*> alt_gens_; |
| 2653 | AlternativeGeneration a_few_alt_gens_[kAFew]; |
| 2654 | }; |
| 2655 | |
| 2656 | |
| 2657 | /* Code generation for choice nodes. |
| 2658 | * |
| 2659 | * We generate quick checks that do a mask and compare to eliminate a |
| 2660 | * choice. If the quick check succeeds then it jumps to the continuation to |
| 2661 | * do slow checks and check subsequent nodes. If it fails (the common case) |
| 2662 | * it falls through to the next choice. |
| 2663 | * |
| 2664 | * Here is the desired flow graph. Nodes directly below each other imply |
| 2665 | * fallthrough. Alternatives 1 and 2 have quick checks. Alternative |
| 2666 | * 3 doesn't have a quick check so we have to call the slow check. |
| 2667 | * Nodes are marked Qn for quick checks and Sn for slow checks. The entire |
| 2668 | * regexp continuation is generated directly after the Sn node, up to the |
| 2669 | * next GoTo if we decide to reuse some already generated code. Some |
| 2670 | * nodes expect preload_characters to be preloaded into the current |
| 2671 | * character register. R nodes do this preloading. Vertices are marked |
| 2672 | * F for failures and S for success (possible success in the case of quick |
| 2673 | * nodes). L, V, < and > are used as arrow heads. |
| 2674 | * |
| 2675 | * ----------> R |
| 2676 | * | |
| 2677 | * V |
| 2678 | * Q1 -----> S1 |
| 2679 | * | S / |
| 2680 | * F| / |
| 2681 | * | F/ |
| 2682 | * | / |
| 2683 | * | R |
| 2684 | * | / |
| 2685 | * V L |
| 2686 | * Q2 -----> S2 |
| 2687 | * | S / |
| 2688 | * F| / |
| 2689 | * | F/ |
| 2690 | * | / |
| 2691 | * | R |
| 2692 | * | / |
| 2693 | * V L |
| 2694 | * S3 |
| 2695 | * | |
| 2696 | * F| |
| 2697 | * | |
| 2698 | * R |
| 2699 | * | |
| 2700 | * backtrack V |
| 2701 | * <----------Q4 |
| 2702 | * \ F | |
| 2703 | * \ |S |
| 2704 | * \ F V |
| 2705 | * \-----S4 |
| 2706 | * |
| 2707 | * For greedy loops we reverse our expectation and expect to match rather |
| 2708 | * than fail. Therefore we want the loop code to look like this (U is the |
| 2709 | * unwind code that steps back in the greedy loop). The following alternatives |
| 2710 | * look the same as above. |
| 2711 | * _____ |
| 2712 | * / \ |
| 2713 | * V | |
| 2714 | * ----------> S1 | |
| 2715 | * /| | |
| 2716 | * / |S | |
| 2717 | * F/ \_____/ |
| 2718 | * / |
| 2719 | * |<----------- |
| 2720 | * | \ |
| 2721 | * V \ |
| 2722 | * Q2 ---> S2 \ |
| 2723 | * | S / | |
| 2724 | * F| / | |
| 2725 | * | F/ | |
| 2726 | * | / | |
| 2727 | * | R | |
| 2728 | * | / | |
| 2729 | * F VL | |
| 2730 | * <------U | |
| 2731 | * back |S | |
| 2732 | * \______________/ |
| 2733 | */ |
| 2734 | |
| 2735 | |
| 2736 | void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| 2737 | RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| 2738 | int choice_count = alternatives_->length(); |
| 2739 | #ifdef DEBUG |
| 2740 | for (int i = 0; i < choice_count - 1; i++) { |
| 2741 | GuardedAlternative alternative = alternatives_->at(i); |
| 2742 | ZoneList<Guard*>* guards = alternative.guards(); |
| 2743 | int guard_count = (guards == NULL) ? 0 : guards->length(); |
| 2744 | for (int j = 0; j < guard_count; j++) { |
| 2745 | ASSERT(!trace->mentions_reg(guards->at(j)->reg())); |
| 2746 | } |
| 2747 | } |
| 2748 | #endif |
| 2749 | |
| 2750 | LimitResult limit_result = LimitVersions(compiler, trace); |
| 2751 | if (limit_result == DONE) return; |
| 2752 | ASSERT(limit_result == CONTINUE); |
| 2753 | |
| 2754 | int new_flush_budget = trace->flush_budget() / choice_count; |
| 2755 | if (trace->flush_budget() == 0 && trace->actions() != NULL) { |
| 2756 | trace->Flush(compiler, this); |
| 2757 | return; |
| 2758 | } |
| 2759 | |
| 2760 | RecursionCheck rc(compiler); |
| 2761 | |
| 2762 | Trace* current_trace = trace; |
| 2763 | |
| 2764 | int text_length = GreedyLoopTextLength(&(alternatives_->at(0))); |
| 2765 | bool greedy_loop = false; |
| 2766 | Label greedy_loop_label; |
| 2767 | Trace counter_backtrack_trace; |
| 2768 | counter_backtrack_trace.set_backtrack(&greedy_loop_label); |
| 2769 | if (not_at_start()) counter_backtrack_trace.set_at_start(false); |
| 2770 | |
| 2771 | if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) { |
| 2772 | // Here we have special handling for greedy loops containing only text nodes |
| 2773 | // and other simple nodes. These are handled by pushing the current |
| 2774 | // position on the stack and then incrementing the current position each |
| 2775 | // time around the switch. On backtrack we decrement the current position |
| 2776 | // and check it against the pushed value. This avoids pushing backtrack |
| 2777 | // information for each iteration of the loop, which could take up a lot of |
| 2778 | // space. |
| 2779 | greedy_loop = true; |
| 2780 | ASSERT(trace->stop_node() == NULL); |
| 2781 | macro_assembler->PushCurrentPosition(); |
| 2782 | current_trace = &counter_backtrack_trace; |
| 2783 | Label greedy_match_failed; |
| 2784 | Trace greedy_match_trace; |
| 2785 | if (not_at_start()) greedy_match_trace.set_at_start(false); |
| 2786 | greedy_match_trace.set_backtrack(&greedy_match_failed); |
| 2787 | Label loop_label; |
| 2788 | macro_assembler->Bind(&loop_label); |
| 2789 | greedy_match_trace.set_stop_node(this); |
| 2790 | greedy_match_trace.set_loop_label(&loop_label); |
| 2791 | alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace); |
| 2792 | macro_assembler->Bind(&greedy_match_failed); |
| 2793 | } |
| 2794 | |
| 2795 | Label second_choice; // For use in greedy matches. |
| 2796 | macro_assembler->Bind(&second_choice); |
| 2797 | |
| 2798 | int first_normal_choice = greedy_loop ? 1 : 0; |
| 2799 | |
| 2800 | int preload_characters = CalculatePreloadCharacters(compiler); |
| 2801 | bool preload_is_current = |
| 2802 | (current_trace->characters_preloaded() == preload_characters); |
| 2803 | bool preload_has_checked_bounds = preload_is_current; |
| 2804 | |
| 2805 | AlternativeGenerationList alt_gens(choice_count); |
| 2806 | |
| 2807 | // For now we just call all choices one after the other. The idea ultimately |
| 2808 | // is to use the Dispatch table to try only the relevant ones. |
| 2809 | for (int i = first_normal_choice; i < choice_count; i++) { |
| 2810 | GuardedAlternative alternative = alternatives_->at(i); |
| 2811 | AlternativeGeneration* alt_gen = alt_gens.at(i); |
| 2812 | alt_gen->quick_check_details.set_characters(preload_characters); |
| 2813 | ZoneList<Guard*>* guards = alternative.guards(); |
| 2814 | int guard_count = (guards == NULL) ? 0 : guards->length(); |
| 2815 | Trace new_trace(*current_trace); |
| 2816 | new_trace.set_characters_preloaded(preload_is_current ? |
| 2817 | preload_characters : |
| 2818 | 0); |
| 2819 | if (preload_has_checked_bounds) { |
| 2820 | new_trace.set_bound_checked_up_to(preload_characters); |
| 2821 | } |
| 2822 | new_trace.quick_check_performed()->Clear(); |
| 2823 | if (not_at_start_) new_trace.set_at_start(Trace::FALSE); |
| 2824 | alt_gen->expects_preload = preload_is_current; |
| 2825 | bool generate_full_check_inline = false; |
| 2826 | if (FLAG_regexp_optimization && |
| 2827 | try_to_emit_quick_check_for_alternative(i) && |
| 2828 | alternative.node()->EmitQuickCheck(compiler, |
| 2829 | &new_trace, |
| 2830 | preload_has_checked_bounds, |
| 2831 | &alt_gen->possible_success, |
| 2832 | &alt_gen->quick_check_details, |
| 2833 | i < choice_count - 1)) { |
| 2834 | // Quick check was generated for this choice. |
| 2835 | preload_is_current = true; |
| 2836 | preload_has_checked_bounds = true; |
| 2837 | // On the last choice in the ChoiceNode we generated the quick |
| 2838 | // check to fall through on possible success. So now we need to |
| 2839 | // generate the full check inline. |
| 2840 | if (i == choice_count - 1) { |
| 2841 | macro_assembler->Bind(&alt_gen->possible_success); |
| 2842 | new_trace.set_quick_check_performed(&alt_gen->quick_check_details); |
| 2843 | new_trace.set_characters_preloaded(preload_characters); |
| 2844 | new_trace.set_bound_checked_up_to(preload_characters); |
| 2845 | generate_full_check_inline = true; |
| 2846 | } |
| 2847 | } else if (alt_gen->quick_check_details.cannot_match()) { |
| 2848 | if (i == choice_count - 1 && !greedy_loop) { |
| 2849 | macro_assembler->GoTo(trace->backtrack()); |
| 2850 | } |
| 2851 | continue; |
| 2852 | } else { |
| 2853 | // No quick check was generated. Put the full code here. |
| 2854 | // If this is not the first choice then there could be slow checks from |
| 2855 | // previous cases that go here when they fail. There's no reason to |
| 2856 | // insist that they preload characters since the slow check we are about |
| 2857 | // to generate probably can't use it. |
| 2858 | if (i != first_normal_choice) { |
| 2859 | alt_gen->expects_preload = false; |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 2860 | new_trace.InvalidateCurrentCharacter(); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 2861 | } |
| 2862 | if (i < choice_count - 1) { |
| 2863 | new_trace.set_backtrack(&alt_gen->after); |
| 2864 | } |
| 2865 | generate_full_check_inline = true; |
| 2866 | } |
| 2867 | if (generate_full_check_inline) { |
| 2868 | if (new_trace.actions() != NULL) { |
| 2869 | new_trace.set_flush_budget(new_flush_budget); |
| 2870 | } |
| 2871 | for (int j = 0; j < guard_count; j++) { |
| 2872 | GenerateGuard(macro_assembler, guards->at(j), &new_trace); |
| 2873 | } |
| 2874 | alternative.node()->Emit(compiler, &new_trace); |
| 2875 | preload_is_current = false; |
| 2876 | } |
| 2877 | macro_assembler->Bind(&alt_gen->after); |
| 2878 | } |
| 2879 | if (greedy_loop) { |
| 2880 | macro_assembler->Bind(&greedy_loop_label); |
| 2881 | // If we have unwound to the bottom then backtrack. |
| 2882 | macro_assembler->CheckGreedyLoop(trace->backtrack()); |
| 2883 | // Otherwise try the second priority at an earlier position. |
| 2884 | macro_assembler->AdvanceCurrentPosition(-text_length); |
| 2885 | macro_assembler->GoTo(&second_choice); |
| 2886 | } |
| 2887 | |
| 2888 | // At this point we need to generate slow checks for the alternatives where |
| 2889 | // the quick check was inlined. We can recognize these because the associated |
| 2890 | // label was bound. |
| 2891 | for (int i = first_normal_choice; i < choice_count - 1; i++) { |
| 2892 | AlternativeGeneration* alt_gen = alt_gens.at(i); |
| 2893 | Trace new_trace(*current_trace); |
| 2894 | // If there are actions to be flushed we have to limit how many times |
| 2895 | // they are flushed. Take the budget of the parent trace and distribute |
| 2896 | // it fairly amongst the children. |
| 2897 | if (new_trace.actions() != NULL) { |
| 2898 | new_trace.set_flush_budget(new_flush_budget); |
| 2899 | } |
| 2900 | EmitOutOfLineContinuation(compiler, |
| 2901 | &new_trace, |
| 2902 | alternatives_->at(i), |
| 2903 | alt_gen, |
| 2904 | preload_characters, |
| 2905 | alt_gens.at(i + 1)->expects_preload); |
| 2906 | } |
| 2907 | } |
| 2908 | |
| 2909 | |
| 2910 | void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler, |
| 2911 | Trace* trace, |
| 2912 | GuardedAlternative alternative, |
| 2913 | AlternativeGeneration* alt_gen, |
| 2914 | int preload_characters, |
| 2915 | bool next_expects_preload) { |
| 2916 | if (!alt_gen->possible_success.is_linked()) return; |
| 2917 | |
| 2918 | RegExpMacroAssembler* macro_assembler = compiler->macro_assembler(); |
| 2919 | macro_assembler->Bind(&alt_gen->possible_success); |
| 2920 | Trace out_of_line_trace(*trace); |
| 2921 | out_of_line_trace.set_characters_preloaded(preload_characters); |
| 2922 | out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details); |
| 2923 | if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE); |
| 2924 | ZoneList<Guard*>* guards = alternative.guards(); |
| 2925 | int guard_count = (guards == NULL) ? 0 : guards->length(); |
| 2926 | if (next_expects_preload) { |
| 2927 | Label reload_current_char; |
| 2928 | out_of_line_trace.set_backtrack(&reload_current_char); |
| 2929 | for (int j = 0; j < guard_count; j++) { |
| 2930 | GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace); |
| 2931 | } |
| 2932 | alternative.node()->Emit(compiler, &out_of_line_trace); |
| 2933 | macro_assembler->Bind(&reload_current_char); |
| 2934 | // Reload the current character, since the next quick check expects that. |
| 2935 | // We don't need to check bounds here because we only get into this |
| 2936 | // code through a quick check which already did the checked load. |
| 2937 | macro_assembler->LoadCurrentCharacter(trace->cp_offset(), |
| 2938 | NULL, |
| 2939 | false, |
| 2940 | preload_characters); |
| 2941 | macro_assembler->GoTo(&(alt_gen->after)); |
| 2942 | } else { |
| 2943 | out_of_line_trace.set_backtrack(&(alt_gen->after)); |
| 2944 | for (int j = 0; j < guard_count; j++) { |
| 2945 | GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace); |
| 2946 | } |
| 2947 | alternative.node()->Emit(compiler, &out_of_line_trace); |
| 2948 | } |
| 2949 | } |
| 2950 | |
| 2951 | |
| 2952 | void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| 2953 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 2954 | LimitResult limit_result = LimitVersions(compiler, trace); |
| 2955 | if (limit_result == DONE) return; |
| 2956 | ASSERT(limit_result == CONTINUE); |
| 2957 | |
| 2958 | RecursionCheck rc(compiler); |
| 2959 | |
| 2960 | switch (type_) { |
| 2961 | case STORE_POSITION: { |
| 2962 | Trace::DeferredCapture |
| 2963 | new_capture(data_.u_position_register.reg, |
| 2964 | data_.u_position_register.is_capture, |
| 2965 | trace); |
| 2966 | Trace new_trace = *trace; |
| 2967 | new_trace.add_action(&new_capture); |
| 2968 | on_success()->Emit(compiler, &new_trace); |
| 2969 | break; |
| 2970 | } |
| 2971 | case INCREMENT_REGISTER: { |
| 2972 | Trace::DeferredIncrementRegister |
| 2973 | new_increment(data_.u_increment_register.reg); |
| 2974 | Trace new_trace = *trace; |
| 2975 | new_trace.add_action(&new_increment); |
| 2976 | on_success()->Emit(compiler, &new_trace); |
| 2977 | break; |
| 2978 | } |
| 2979 | case SET_REGISTER: { |
| 2980 | Trace::DeferredSetRegister |
| 2981 | new_set(data_.u_store_register.reg, data_.u_store_register.value); |
| 2982 | Trace new_trace = *trace; |
| 2983 | new_trace.add_action(&new_set); |
| 2984 | on_success()->Emit(compiler, &new_trace); |
| 2985 | break; |
| 2986 | } |
| 2987 | case CLEAR_CAPTURES: { |
| 2988 | Trace::DeferredClearCaptures |
| 2989 | new_capture(Interval(data_.u_clear_captures.range_from, |
| 2990 | data_.u_clear_captures.range_to)); |
| 2991 | Trace new_trace = *trace; |
| 2992 | new_trace.add_action(&new_capture); |
| 2993 | on_success()->Emit(compiler, &new_trace); |
| 2994 | break; |
| 2995 | } |
| 2996 | case BEGIN_SUBMATCH: |
| 2997 | if (!trace->is_trivial()) { |
| 2998 | trace->Flush(compiler, this); |
| 2999 | } else { |
| 3000 | assembler->WriteCurrentPositionToRegister( |
| 3001 | data_.u_submatch.current_position_register, 0); |
| 3002 | assembler->WriteStackPointerToRegister( |
| 3003 | data_.u_submatch.stack_pointer_register); |
| 3004 | on_success()->Emit(compiler, trace); |
| 3005 | } |
| 3006 | break; |
| 3007 | case EMPTY_MATCH_CHECK: { |
| 3008 | int start_pos_reg = data_.u_empty_match_check.start_register; |
| 3009 | int stored_pos = 0; |
| 3010 | int rep_reg = data_.u_empty_match_check.repetition_register; |
| 3011 | bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister); |
| 3012 | bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos); |
| 3013 | if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) { |
| 3014 | // If we know we haven't advanced and there is no minimum we |
| 3015 | // can just backtrack immediately. |
| 3016 | assembler->GoTo(trace->backtrack()); |
| 3017 | } else if (know_dist && stored_pos < trace->cp_offset()) { |
| 3018 | // If we know we've advanced we can generate the continuation |
| 3019 | // immediately. |
| 3020 | on_success()->Emit(compiler, trace); |
| 3021 | } else if (!trace->is_trivial()) { |
| 3022 | trace->Flush(compiler, this); |
| 3023 | } else { |
| 3024 | Label skip_empty_check; |
| 3025 | // If we have a minimum number of repetitions we check the current |
| 3026 | // number first and skip the empty check if it's not enough. |
| 3027 | if (has_minimum) { |
| 3028 | int limit = data_.u_empty_match_check.repetition_limit; |
| 3029 | assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check); |
| 3030 | } |
| 3031 | // If the match is empty we bail out, otherwise we fall through |
| 3032 | // to the on-success continuation. |
| 3033 | assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register, |
| 3034 | trace->backtrack()); |
| 3035 | assembler->Bind(&skip_empty_check); |
| 3036 | on_success()->Emit(compiler, trace); |
| 3037 | } |
| 3038 | break; |
| 3039 | } |
| 3040 | case POSITIVE_SUBMATCH_SUCCESS: { |
| 3041 | if (!trace->is_trivial()) { |
| 3042 | trace->Flush(compiler, this); |
| 3043 | return; |
| 3044 | } |
| 3045 | assembler->ReadCurrentPositionFromRegister( |
| 3046 | data_.u_submatch.current_position_register); |
| 3047 | assembler->ReadStackPointerFromRegister( |
| 3048 | data_.u_submatch.stack_pointer_register); |
| 3049 | int clear_register_count = data_.u_submatch.clear_register_count; |
| 3050 | if (clear_register_count == 0) { |
| 3051 | on_success()->Emit(compiler, trace); |
| 3052 | return; |
| 3053 | } |
| 3054 | int clear_registers_from = data_.u_submatch.clear_register_from; |
| 3055 | Label clear_registers_backtrack; |
| 3056 | Trace new_trace = *trace; |
| 3057 | new_trace.set_backtrack(&clear_registers_backtrack); |
| 3058 | on_success()->Emit(compiler, &new_trace); |
| 3059 | |
| 3060 | assembler->Bind(&clear_registers_backtrack); |
| 3061 | int clear_registers_to = clear_registers_from + clear_register_count - 1; |
| 3062 | assembler->ClearRegisters(clear_registers_from, clear_registers_to); |
| 3063 | |
| 3064 | ASSERT(trace->backtrack() == NULL); |
| 3065 | assembler->Backtrack(); |
| 3066 | return; |
| 3067 | } |
| 3068 | default: |
| 3069 | UNREACHABLE(); |
| 3070 | } |
| 3071 | } |
| 3072 | |
| 3073 | |
| 3074 | void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) { |
| 3075 | RegExpMacroAssembler* assembler = compiler->macro_assembler(); |
| 3076 | if (!trace->is_trivial()) { |
| 3077 | trace->Flush(compiler, this); |
| 3078 | return; |
| 3079 | } |
| 3080 | |
| 3081 | LimitResult limit_result = LimitVersions(compiler, trace); |
| 3082 | if (limit_result == DONE) return; |
| 3083 | ASSERT(limit_result == CONTINUE); |
| 3084 | |
| 3085 | RecursionCheck rc(compiler); |
| 3086 | |
| 3087 | ASSERT_EQ(start_reg_ + 1, end_reg_); |
| 3088 | if (compiler->ignore_case()) { |
| 3089 | assembler->CheckNotBackReferenceIgnoreCase(start_reg_, |
| 3090 | trace->backtrack()); |
| 3091 | } else { |
| 3092 | assembler->CheckNotBackReference(start_reg_, trace->backtrack()); |
| 3093 | } |
| 3094 | on_success()->Emit(compiler, trace); |
| 3095 | } |
| 3096 | |
| 3097 | |
| 3098 | // ------------------------------------------------------------------- |
| 3099 | // Dot/dotty output |
| 3100 | |
| 3101 | |
| 3102 | #ifdef DEBUG |
| 3103 | |
| 3104 | |
| 3105 | class DotPrinter: public NodeVisitor { |
| 3106 | public: |
| 3107 | explicit DotPrinter(bool ignore_case) |
| 3108 | : ignore_case_(ignore_case), |
| 3109 | stream_(&alloc_) { } |
| 3110 | void PrintNode(const char* label, RegExpNode* node); |
| 3111 | void Visit(RegExpNode* node); |
| 3112 | void PrintAttributes(RegExpNode* from); |
| 3113 | StringStream* stream() { return &stream_; } |
| 3114 | void PrintOnFailure(RegExpNode* from, RegExpNode* to); |
| 3115 | #define DECLARE_VISIT(Type) \ |
| 3116 | virtual void Visit##Type(Type##Node* that); |
| 3117 | FOR_EACH_NODE_TYPE(DECLARE_VISIT) |
| 3118 | #undef DECLARE_VISIT |
| 3119 | private: |
| 3120 | bool ignore_case_; |
| 3121 | HeapStringAllocator alloc_; |
| 3122 | StringStream stream_; |
| 3123 | }; |
| 3124 | |
| 3125 | |
| 3126 | void DotPrinter::PrintNode(const char* label, RegExpNode* node) { |
| 3127 | stream()->Add("digraph G {\n graph [label=\""); |
| 3128 | for (int i = 0; label[i]; i++) { |
| 3129 | switch (label[i]) { |
| 3130 | case '\\': |
| 3131 | stream()->Add("\\\\"); |
| 3132 | break; |
| 3133 | case '"': |
| 3134 | stream()->Add("\""); |
| 3135 | break; |
| 3136 | default: |
| 3137 | stream()->Put(label[i]); |
| 3138 | break; |
| 3139 | } |
| 3140 | } |
| 3141 | stream()->Add("\"];\n"); |
| 3142 | Visit(node); |
| 3143 | stream()->Add("}\n"); |
| 3144 | printf("%s", *(stream()->ToCString())); |
| 3145 | } |
| 3146 | |
| 3147 | |
| 3148 | void DotPrinter::Visit(RegExpNode* node) { |
| 3149 | if (node->info()->visited) return; |
| 3150 | node->info()->visited = true; |
| 3151 | node->Accept(this); |
| 3152 | } |
| 3153 | |
| 3154 | |
| 3155 | void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) { |
| 3156 | stream()->Add(" n%p -> n%p [style=dotted];\n", from, on_failure); |
| 3157 | Visit(on_failure); |
| 3158 | } |
| 3159 | |
| 3160 | |
| 3161 | class TableEntryBodyPrinter { |
| 3162 | public: |
| 3163 | TableEntryBodyPrinter(StringStream* stream, ChoiceNode* choice) |
| 3164 | : stream_(stream), choice_(choice) { } |
| 3165 | void Call(uc16 from, DispatchTable::Entry entry) { |
| 3166 | OutSet* out_set = entry.out_set(); |
| 3167 | for (unsigned i = 0; i < OutSet::kFirstLimit; i++) { |
| 3168 | if (out_set->Get(i)) { |
| 3169 | stream()->Add(" n%p:s%io%i -> n%p;\n", |
| 3170 | choice(), |
| 3171 | from, |
| 3172 | i, |
| 3173 | choice()->alternatives()->at(i).node()); |
| 3174 | } |
| 3175 | } |
| 3176 | } |
| 3177 | private: |
| 3178 | StringStream* stream() { return stream_; } |
| 3179 | ChoiceNode* choice() { return choice_; } |
| 3180 | StringStream* stream_; |
| 3181 | ChoiceNode* choice_; |
| 3182 | }; |
| 3183 | |
| 3184 | |
| 3185 | class TableEntryHeaderPrinter { |
| 3186 | public: |
| 3187 | explicit TableEntryHeaderPrinter(StringStream* stream) |
| 3188 | : first_(true), stream_(stream) { } |
| 3189 | void Call(uc16 from, DispatchTable::Entry entry) { |
| 3190 | if (first_) { |
| 3191 | first_ = false; |
| 3192 | } else { |
| 3193 | stream()->Add("|"); |
| 3194 | } |
| 3195 | stream()->Add("{\\%k-\\%k|{", from, entry.to()); |
| 3196 | OutSet* out_set = entry.out_set(); |
| 3197 | int priority = 0; |
| 3198 | for (unsigned i = 0; i < OutSet::kFirstLimit; i++) { |
| 3199 | if (out_set->Get(i)) { |
| 3200 | if (priority > 0) stream()->Add("|"); |
| 3201 | stream()->Add("<s%io%i> %i", from, i, priority); |
| 3202 | priority++; |
| 3203 | } |
| 3204 | } |
| 3205 | stream()->Add("}}"); |
| 3206 | } |
| 3207 | private: |
| 3208 | bool first_; |
| 3209 | StringStream* stream() { return stream_; } |
| 3210 | StringStream* stream_; |
| 3211 | }; |
| 3212 | |
| 3213 | |
| 3214 | class AttributePrinter { |
| 3215 | public: |
| 3216 | explicit AttributePrinter(DotPrinter* out) |
| 3217 | : out_(out), first_(true) { } |
| 3218 | void PrintSeparator() { |
| 3219 | if (first_) { |
| 3220 | first_ = false; |
| 3221 | } else { |
| 3222 | out_->stream()->Add("|"); |
| 3223 | } |
| 3224 | } |
| 3225 | void PrintBit(const char* name, bool value) { |
| 3226 | if (!value) return; |
| 3227 | PrintSeparator(); |
| 3228 | out_->stream()->Add("{%s}", name); |
| 3229 | } |
| 3230 | void PrintPositive(const char* name, int value) { |
| 3231 | if (value < 0) return; |
| 3232 | PrintSeparator(); |
| 3233 | out_->stream()->Add("{%s|%x}", name, value); |
| 3234 | } |
| 3235 | private: |
| 3236 | DotPrinter* out_; |
| 3237 | bool first_; |
| 3238 | }; |
| 3239 | |
| 3240 | |
| 3241 | void DotPrinter::PrintAttributes(RegExpNode* that) { |
| 3242 | stream()->Add(" a%p [shape=Mrecord, color=grey, fontcolor=grey, " |
| 3243 | "margin=0.1, fontsize=10, label=\"{", |
| 3244 | that); |
| 3245 | AttributePrinter printer(this); |
| 3246 | NodeInfo* info = that->info(); |
| 3247 | printer.PrintBit("NI", info->follows_newline_interest); |
| 3248 | printer.PrintBit("WI", info->follows_word_interest); |
| 3249 | printer.PrintBit("SI", info->follows_start_interest); |
| 3250 | Label* label = that->label(); |
| 3251 | if (label->is_bound()) |
| 3252 | printer.PrintPositive("@", label->pos()); |
| 3253 | stream()->Add("}\"];\n"); |
| 3254 | stream()->Add(" a%p -> n%p [style=dashed, color=grey, " |
| 3255 | "arrowhead=none];\n", that, that); |
| 3256 | } |
| 3257 | |
| 3258 | |
| 3259 | static const bool kPrintDispatchTable = false; |
| 3260 | void DotPrinter::VisitChoice(ChoiceNode* that) { |
| 3261 | if (kPrintDispatchTable) { |
| 3262 | stream()->Add(" n%p [shape=Mrecord, label=\"", that); |
| 3263 | TableEntryHeaderPrinter header_printer(stream()); |
| 3264 | that->GetTable(ignore_case_)->ForEach(&header_printer); |
| 3265 | stream()->Add("\"]\n", that); |
| 3266 | PrintAttributes(that); |
| 3267 | TableEntryBodyPrinter body_printer(stream(), that); |
| 3268 | that->GetTable(ignore_case_)->ForEach(&body_printer); |
| 3269 | } else { |
| 3270 | stream()->Add(" n%p [shape=Mrecord, label=\"?\"];\n", that); |
| 3271 | for (int i = 0; i < that->alternatives()->length(); i++) { |
| 3272 | GuardedAlternative alt = that->alternatives()->at(i); |
| 3273 | stream()->Add(" n%p -> n%p;\n", that, alt.node()); |
| 3274 | } |
| 3275 | } |
| 3276 | for (int i = 0; i < that->alternatives()->length(); i++) { |
| 3277 | GuardedAlternative alt = that->alternatives()->at(i); |
| 3278 | alt.node()->Accept(this); |
| 3279 | } |
| 3280 | } |
| 3281 | |
| 3282 | |
| 3283 | void DotPrinter::VisitText(TextNode* that) { |
| 3284 | stream()->Add(" n%p [label=\"", that); |
| 3285 | for (int i = 0; i < that->elements()->length(); i++) { |
| 3286 | if (i > 0) stream()->Add(" "); |
| 3287 | TextElement elm = that->elements()->at(i); |
| 3288 | switch (elm.type) { |
| 3289 | case TextElement::ATOM: { |
| 3290 | stream()->Add("'%w'", elm.data.u_atom->data()); |
| 3291 | break; |
| 3292 | } |
| 3293 | case TextElement::CHAR_CLASS: { |
| 3294 | RegExpCharacterClass* node = elm.data.u_char_class; |
| 3295 | stream()->Add("["); |
| 3296 | if (node->is_negated()) |
| 3297 | stream()->Add("^"); |
| 3298 | for (int j = 0; j < node->ranges()->length(); j++) { |
| 3299 | CharacterRange range = node->ranges()->at(j); |
| 3300 | stream()->Add("%k-%k", range.from(), range.to()); |
| 3301 | } |
| 3302 | stream()->Add("]"); |
| 3303 | break; |
| 3304 | } |
| 3305 | default: |
| 3306 | UNREACHABLE(); |
| 3307 | } |
| 3308 | } |
| 3309 | stream()->Add("\", shape=box, peripheries=2];\n"); |
| 3310 | PrintAttributes(that); |
| 3311 | stream()->Add(" n%p -> n%p;\n", that, that->on_success()); |
| 3312 | Visit(that->on_success()); |
| 3313 | } |
| 3314 | |
| 3315 | |
| 3316 | void DotPrinter::VisitBackReference(BackReferenceNode* that) { |
| 3317 | stream()->Add(" n%p [label=\"$%i..$%i\", shape=doubleoctagon];\n", |
| 3318 | that, |
| 3319 | that->start_register(), |
| 3320 | that->end_register()); |
| 3321 | PrintAttributes(that); |
| 3322 | stream()->Add(" n%p -> n%p;\n", that, that->on_success()); |
| 3323 | Visit(that->on_success()); |
| 3324 | } |
| 3325 | |
| 3326 | |
| 3327 | void DotPrinter::VisitEnd(EndNode* that) { |
| 3328 | stream()->Add(" n%p [style=bold, shape=point];\n", that); |
| 3329 | PrintAttributes(that); |
| 3330 | } |
| 3331 | |
| 3332 | |
| 3333 | void DotPrinter::VisitAssertion(AssertionNode* that) { |
| 3334 | stream()->Add(" n%p [", that); |
| 3335 | switch (that->type()) { |
| 3336 | case AssertionNode::AT_END: |
| 3337 | stream()->Add("label=\"$\", shape=septagon"); |
| 3338 | break; |
| 3339 | case AssertionNode::AT_START: |
| 3340 | stream()->Add("label=\"^\", shape=septagon"); |
| 3341 | break; |
| 3342 | case AssertionNode::AT_BOUNDARY: |
| 3343 | stream()->Add("label=\"\\b\", shape=septagon"); |
| 3344 | break; |
| 3345 | case AssertionNode::AT_NON_BOUNDARY: |
| 3346 | stream()->Add("label=\"\\B\", shape=septagon"); |
| 3347 | break; |
| 3348 | case AssertionNode::AFTER_NEWLINE: |
| 3349 | stream()->Add("label=\"(?<=\\n)\", shape=septagon"); |
| 3350 | break; |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 3351 | case AssertionNode::AFTER_WORD_CHARACTER: |
| 3352 | stream()->Add("label=\"(?<=\\w)\", shape=septagon"); |
| 3353 | break; |
| 3354 | case AssertionNode::AFTER_NONWORD_CHARACTER: |
| 3355 | stream()->Add("label=\"(?<=\\W)\", shape=septagon"); |
| 3356 | break; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 3357 | } |
| 3358 | stream()->Add("];\n"); |
| 3359 | PrintAttributes(that); |
| 3360 | RegExpNode* successor = that->on_success(); |
| 3361 | stream()->Add(" n%p -> n%p;\n", that, successor); |
| 3362 | Visit(successor); |
| 3363 | } |
| 3364 | |
| 3365 | |
| 3366 | void DotPrinter::VisitAction(ActionNode* that) { |
| 3367 | stream()->Add(" n%p [", that); |
| 3368 | switch (that->type_) { |
| 3369 | case ActionNode::SET_REGISTER: |
| 3370 | stream()->Add("label=\"$%i:=%i\", shape=octagon", |
| 3371 | that->data_.u_store_register.reg, |
| 3372 | that->data_.u_store_register.value); |
| 3373 | break; |
| 3374 | case ActionNode::INCREMENT_REGISTER: |
| 3375 | stream()->Add("label=\"$%i++\", shape=octagon", |
| 3376 | that->data_.u_increment_register.reg); |
| 3377 | break; |
| 3378 | case ActionNode::STORE_POSITION: |
| 3379 | stream()->Add("label=\"$%i:=$pos\", shape=octagon", |
| 3380 | that->data_.u_position_register.reg); |
| 3381 | break; |
| 3382 | case ActionNode::BEGIN_SUBMATCH: |
| 3383 | stream()->Add("label=\"$%i:=$pos,begin\", shape=septagon", |
| 3384 | that->data_.u_submatch.current_position_register); |
| 3385 | break; |
| 3386 | case ActionNode::POSITIVE_SUBMATCH_SUCCESS: |
| 3387 | stream()->Add("label=\"escape\", shape=septagon"); |
| 3388 | break; |
| 3389 | case ActionNode::EMPTY_MATCH_CHECK: |
| 3390 | stream()->Add("label=\"$%i=$pos?,$%i<%i?\", shape=septagon", |
| 3391 | that->data_.u_empty_match_check.start_register, |
| 3392 | that->data_.u_empty_match_check.repetition_register, |
| 3393 | that->data_.u_empty_match_check.repetition_limit); |
| 3394 | break; |
| 3395 | case ActionNode::CLEAR_CAPTURES: { |
| 3396 | stream()->Add("label=\"clear $%i to $%i\", shape=septagon", |
| 3397 | that->data_.u_clear_captures.range_from, |
| 3398 | that->data_.u_clear_captures.range_to); |
| 3399 | break; |
| 3400 | } |
| 3401 | } |
| 3402 | stream()->Add("];\n"); |
| 3403 | PrintAttributes(that); |
| 3404 | RegExpNode* successor = that->on_success(); |
| 3405 | stream()->Add(" n%p -> n%p;\n", that, successor); |
| 3406 | Visit(successor); |
| 3407 | } |
| 3408 | |
| 3409 | |
| 3410 | class DispatchTableDumper { |
| 3411 | public: |
| 3412 | explicit DispatchTableDumper(StringStream* stream) : stream_(stream) { } |
| 3413 | void Call(uc16 key, DispatchTable::Entry entry); |
| 3414 | StringStream* stream() { return stream_; } |
| 3415 | private: |
| 3416 | StringStream* stream_; |
| 3417 | }; |
| 3418 | |
| 3419 | |
| 3420 | void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) { |
| 3421 | stream()->Add("[%k-%k]: {", key, entry.to()); |
| 3422 | OutSet* set = entry.out_set(); |
| 3423 | bool first = true; |
| 3424 | for (unsigned i = 0; i < OutSet::kFirstLimit; i++) { |
| 3425 | if (set->Get(i)) { |
| 3426 | if (first) { |
| 3427 | first = false; |
| 3428 | } else { |
| 3429 | stream()->Add(", "); |
| 3430 | } |
| 3431 | stream()->Add("%i", i); |
| 3432 | } |
| 3433 | } |
| 3434 | stream()->Add("}\n"); |
| 3435 | } |
| 3436 | |
| 3437 | |
| 3438 | void DispatchTable::Dump() { |
| 3439 | HeapStringAllocator alloc; |
| 3440 | StringStream stream(&alloc); |
| 3441 | DispatchTableDumper dumper(&stream); |
| 3442 | tree()->ForEach(&dumper); |
| 3443 | OS::PrintError("%s", *stream.ToCString()); |
| 3444 | } |
| 3445 | |
| 3446 | |
| 3447 | void RegExpEngine::DotPrint(const char* label, |
| 3448 | RegExpNode* node, |
| 3449 | bool ignore_case) { |
| 3450 | DotPrinter printer(ignore_case); |
| 3451 | printer.PrintNode(label, node); |
| 3452 | } |
| 3453 | |
| 3454 | |
| 3455 | #endif // DEBUG |
| 3456 | |
| 3457 | |
| 3458 | // ------------------------------------------------------------------- |
| 3459 | // Tree to graph conversion |
| 3460 | |
| 3461 | static const int kSpaceRangeCount = 20; |
| 3462 | static const int kSpaceRangeAsciiCount = 4; |
| 3463 | static const uc16 kSpaceRanges[kSpaceRangeCount] = { 0x0009, 0x000D, 0x0020, |
| 3464 | 0x0020, 0x00A0, 0x00A0, 0x1680, 0x1680, 0x180E, 0x180E, 0x2000, 0x200A, |
| 3465 | 0x2028, 0x2029, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000 }; |
| 3466 | |
| 3467 | static const int kWordRangeCount = 8; |
| 3468 | static const uc16 kWordRanges[kWordRangeCount] = { '0', '9', 'A', 'Z', '_', |
| 3469 | '_', 'a', 'z' }; |
| 3470 | |
| 3471 | static const int kDigitRangeCount = 2; |
| 3472 | static const uc16 kDigitRanges[kDigitRangeCount] = { '0', '9' }; |
| 3473 | |
| 3474 | static const int kLineTerminatorRangeCount = 6; |
| 3475 | static const uc16 kLineTerminatorRanges[kLineTerminatorRangeCount] = { 0x000A, |
| 3476 | 0x000A, 0x000D, 0x000D, 0x2028, 0x2029 }; |
| 3477 | |
| 3478 | RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler, |
| 3479 | RegExpNode* on_success) { |
| 3480 | ZoneList<TextElement>* elms = new ZoneList<TextElement>(1); |
| 3481 | elms->Add(TextElement::Atom(this)); |
| 3482 | return new TextNode(elms, on_success); |
| 3483 | } |
| 3484 | |
| 3485 | |
| 3486 | RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler, |
| 3487 | RegExpNode* on_success) { |
| 3488 | return new TextNode(elements(), on_success); |
| 3489 | } |
| 3490 | |
| 3491 | static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges, |
| 3492 | const uc16* special_class, |
| 3493 | int length) { |
| 3494 | ASSERT(ranges->length() != 0); |
| 3495 | ASSERT(length != 0); |
| 3496 | ASSERT(special_class[0] != 0); |
| 3497 | if (ranges->length() != (length >> 1) + 1) { |
| 3498 | return false; |
| 3499 | } |
| 3500 | CharacterRange range = ranges->at(0); |
| 3501 | if (range.from() != 0) { |
| 3502 | return false; |
| 3503 | } |
| 3504 | for (int i = 0; i < length; i += 2) { |
| 3505 | if (special_class[i] != (range.to() + 1)) { |
| 3506 | return false; |
| 3507 | } |
| 3508 | range = ranges->at((i >> 1) + 1); |
| 3509 | if (special_class[i+1] != range.from() - 1) { |
| 3510 | return false; |
| 3511 | } |
| 3512 | } |
| 3513 | if (range.to() != 0xffff) { |
| 3514 | return false; |
| 3515 | } |
| 3516 | return true; |
| 3517 | } |
| 3518 | |
| 3519 | |
| 3520 | static bool CompareRanges(ZoneList<CharacterRange>* ranges, |
| 3521 | const uc16* special_class, |
| 3522 | int length) { |
| 3523 | if (ranges->length() * 2 != length) { |
| 3524 | return false; |
| 3525 | } |
| 3526 | for (int i = 0; i < length; i += 2) { |
| 3527 | CharacterRange range = ranges->at(i >> 1); |
| 3528 | if (range.from() != special_class[i] || range.to() != special_class[i+1]) { |
| 3529 | return false; |
| 3530 | } |
| 3531 | } |
| 3532 | return true; |
| 3533 | } |
| 3534 | |
| 3535 | |
| 3536 | bool RegExpCharacterClass::is_standard() { |
| 3537 | // TODO(lrn): Remove need for this function, by not throwing away information |
| 3538 | // along the way. |
| 3539 | if (is_negated_) { |
| 3540 | return false; |
| 3541 | } |
| 3542 | if (set_.is_standard()) { |
| 3543 | return true; |
| 3544 | } |
| 3545 | if (CompareRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) { |
| 3546 | set_.set_standard_set_type('s'); |
| 3547 | return true; |
| 3548 | } |
| 3549 | if (CompareInverseRanges(set_.ranges(), kSpaceRanges, kSpaceRangeCount)) { |
| 3550 | set_.set_standard_set_type('S'); |
| 3551 | return true; |
| 3552 | } |
| 3553 | if (CompareInverseRanges(set_.ranges(), |
| 3554 | kLineTerminatorRanges, |
| 3555 | kLineTerminatorRangeCount)) { |
| 3556 | set_.set_standard_set_type('.'); |
| 3557 | return true; |
| 3558 | } |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 3559 | if (CompareRanges(set_.ranges(), |
| 3560 | kLineTerminatorRanges, |
| 3561 | kLineTerminatorRangeCount)) { |
| 3562 | set_.set_standard_set_type('n'); |
| 3563 | return true; |
| 3564 | } |
| 3565 | if (CompareRanges(set_.ranges(), kWordRanges, kWordRangeCount)) { |
| 3566 | set_.set_standard_set_type('w'); |
| 3567 | return true; |
| 3568 | } |
| 3569 | if (CompareInverseRanges(set_.ranges(), kWordRanges, kWordRangeCount)) { |
| 3570 | set_.set_standard_set_type('W'); |
| 3571 | return true; |
| 3572 | } |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 3573 | return false; |
| 3574 | } |
| 3575 | |
| 3576 | |
| 3577 | RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler, |
| 3578 | RegExpNode* on_success) { |
| 3579 | return new TextNode(this, on_success); |
| 3580 | } |
| 3581 | |
| 3582 | |
| 3583 | RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler, |
| 3584 | RegExpNode* on_success) { |
| 3585 | ZoneList<RegExpTree*>* alternatives = this->alternatives(); |
| 3586 | int length = alternatives->length(); |
| 3587 | ChoiceNode* result = new ChoiceNode(length); |
| 3588 | for (int i = 0; i < length; i++) { |
| 3589 | GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler, |
| 3590 | on_success)); |
| 3591 | result->AddAlternative(alternative); |
| 3592 | } |
| 3593 | return result; |
| 3594 | } |
| 3595 | |
| 3596 | |
| 3597 | RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler, |
| 3598 | RegExpNode* on_success) { |
| 3599 | return ToNode(min(), |
| 3600 | max(), |
| 3601 | is_greedy(), |
| 3602 | body(), |
| 3603 | compiler, |
| 3604 | on_success); |
| 3605 | } |
| 3606 | |
| 3607 | |
| 3608 | RegExpNode* RegExpQuantifier::ToNode(int min, |
| 3609 | int max, |
| 3610 | bool is_greedy, |
| 3611 | RegExpTree* body, |
| 3612 | RegExpCompiler* compiler, |
| 3613 | RegExpNode* on_success, |
| 3614 | bool not_at_start) { |
| 3615 | // x{f, t} becomes this: |
| 3616 | // |
| 3617 | // (r++)<-. |
| 3618 | // | ` |
| 3619 | // | (x) |
| 3620 | // v ^ |
| 3621 | // (r=0)-->(?)---/ [if r < t] |
| 3622 | // | |
| 3623 | // [if r >= f] \----> ... |
| 3624 | // |
| 3625 | |
| 3626 | // 15.10.2.5 RepeatMatcher algorithm. |
| 3627 | // The parser has already eliminated the case where max is 0. In the case |
| 3628 | // where max_match is zero the parser has removed the quantifier if min was |
| 3629 | // > 0 and removed the atom if min was 0. See AddQuantifierToAtom. |
| 3630 | |
| 3631 | // If we know that we cannot match zero length then things are a little |
| 3632 | // simpler since we don't need to make the special zero length match check |
| 3633 | // from step 2.1. If the min and max are small we can unroll a little in |
| 3634 | // this case. |
| 3635 | static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,} |
| 3636 | static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3} |
| 3637 | if (max == 0) return on_success; // This can happen due to recursion. |
| 3638 | bool body_can_be_empty = (body->min_match() == 0); |
| 3639 | int body_start_reg = RegExpCompiler::kNoRegister; |
| 3640 | Interval capture_registers = body->CaptureRegisters(); |
| 3641 | bool needs_capture_clearing = !capture_registers.is_empty(); |
| 3642 | if (body_can_be_empty) { |
| 3643 | body_start_reg = compiler->AllocateRegister(); |
| 3644 | } else if (FLAG_regexp_optimization && !needs_capture_clearing) { |
| 3645 | // Only unroll if there are no captures and the body can't be |
| 3646 | // empty. |
| 3647 | if (min > 0 && min <= kMaxUnrolledMinMatches) { |
| 3648 | int new_max = (max == kInfinity) ? max : max - min; |
| 3649 | // Recurse once to get the loop or optional matches after the fixed ones. |
| 3650 | RegExpNode* answer = ToNode( |
| 3651 | 0, new_max, is_greedy, body, compiler, on_success, true); |
| 3652 | // Unroll the forced matches from 0 to min. This can cause chains of |
| 3653 | // TextNodes (which the parser does not generate). These should be |
| 3654 | // combined if it turns out they hinder good code generation. |
| 3655 | for (int i = 0; i < min; i++) { |
| 3656 | answer = body->ToNode(compiler, answer); |
| 3657 | } |
| 3658 | return answer; |
| 3659 | } |
| 3660 | if (max <= kMaxUnrolledMaxMatches) { |
| 3661 | ASSERT(min == 0); |
| 3662 | // Unroll the optional matches up to max. |
| 3663 | RegExpNode* answer = on_success; |
| 3664 | for (int i = 0; i < max; i++) { |
| 3665 | ChoiceNode* alternation = new ChoiceNode(2); |
| 3666 | if (is_greedy) { |
| 3667 | alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler, |
| 3668 | answer))); |
| 3669 | alternation->AddAlternative(GuardedAlternative(on_success)); |
| 3670 | } else { |
| 3671 | alternation->AddAlternative(GuardedAlternative(on_success)); |
| 3672 | alternation->AddAlternative(GuardedAlternative(body->ToNode(compiler, |
| 3673 | answer))); |
| 3674 | } |
| 3675 | answer = alternation; |
| 3676 | if (not_at_start) alternation->set_not_at_start(); |
| 3677 | } |
| 3678 | return answer; |
| 3679 | } |
| 3680 | } |
| 3681 | bool has_min = min > 0; |
| 3682 | bool has_max = max < RegExpTree::kInfinity; |
| 3683 | bool needs_counter = has_min || has_max; |
| 3684 | int reg_ctr = needs_counter |
| 3685 | ? compiler->AllocateRegister() |
| 3686 | : RegExpCompiler::kNoRegister; |
| 3687 | LoopChoiceNode* center = new LoopChoiceNode(body->min_match() == 0); |
| 3688 | if (not_at_start) center->set_not_at_start(); |
| 3689 | RegExpNode* loop_return = needs_counter |
| 3690 | ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center)) |
| 3691 | : static_cast<RegExpNode*>(center); |
| 3692 | if (body_can_be_empty) { |
| 3693 | // If the body can be empty we need to check if it was and then |
| 3694 | // backtrack. |
| 3695 | loop_return = ActionNode::EmptyMatchCheck(body_start_reg, |
| 3696 | reg_ctr, |
| 3697 | min, |
| 3698 | loop_return); |
| 3699 | } |
| 3700 | RegExpNode* body_node = body->ToNode(compiler, loop_return); |
| 3701 | if (body_can_be_empty) { |
| 3702 | // If the body can be empty we need to store the start position |
| 3703 | // so we can bail out if it was empty. |
| 3704 | body_node = ActionNode::StorePosition(body_start_reg, false, body_node); |
| 3705 | } |
| 3706 | if (needs_capture_clearing) { |
| 3707 | // Before entering the body of this loop we need to clear captures. |
| 3708 | body_node = ActionNode::ClearCaptures(capture_registers, body_node); |
| 3709 | } |
| 3710 | GuardedAlternative body_alt(body_node); |
| 3711 | if (has_max) { |
| 3712 | Guard* body_guard = new Guard(reg_ctr, Guard::LT, max); |
| 3713 | body_alt.AddGuard(body_guard); |
| 3714 | } |
| 3715 | GuardedAlternative rest_alt(on_success); |
| 3716 | if (has_min) { |
| 3717 | Guard* rest_guard = new Guard(reg_ctr, Guard::GEQ, min); |
| 3718 | rest_alt.AddGuard(rest_guard); |
| 3719 | } |
| 3720 | if (is_greedy) { |
| 3721 | center->AddLoopAlternative(body_alt); |
| 3722 | center->AddContinueAlternative(rest_alt); |
| 3723 | } else { |
| 3724 | center->AddContinueAlternative(rest_alt); |
| 3725 | center->AddLoopAlternative(body_alt); |
| 3726 | } |
| 3727 | if (needs_counter) { |
| 3728 | return ActionNode::SetRegister(reg_ctr, 0, center); |
| 3729 | } else { |
| 3730 | return center; |
| 3731 | } |
| 3732 | } |
| 3733 | |
| 3734 | |
| 3735 | RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler, |
| 3736 | RegExpNode* on_success) { |
| 3737 | NodeInfo info; |
| 3738 | switch (type()) { |
| 3739 | case START_OF_LINE: |
| 3740 | return AssertionNode::AfterNewline(on_success); |
| 3741 | case START_OF_INPUT: |
| 3742 | return AssertionNode::AtStart(on_success); |
| 3743 | case BOUNDARY: |
| 3744 | return AssertionNode::AtBoundary(on_success); |
| 3745 | case NON_BOUNDARY: |
| 3746 | return AssertionNode::AtNonBoundary(on_success); |
| 3747 | case END_OF_INPUT: |
| 3748 | return AssertionNode::AtEnd(on_success); |
| 3749 | case END_OF_LINE: { |
| 3750 | // Compile $ in multiline regexps as an alternation with a positive |
| 3751 | // lookahead in one side and an end-of-input on the other side. |
| 3752 | // We need two registers for the lookahead. |
| 3753 | int stack_pointer_register = compiler->AllocateRegister(); |
| 3754 | int position_register = compiler->AllocateRegister(); |
| 3755 | // The ChoiceNode to distinguish between a newline and end-of-input. |
| 3756 | ChoiceNode* result = new ChoiceNode(2); |
| 3757 | // Create a newline atom. |
| 3758 | ZoneList<CharacterRange>* newline_ranges = |
| 3759 | new ZoneList<CharacterRange>(3); |
| 3760 | CharacterRange::AddClassEscape('n', newline_ranges); |
| 3761 | RegExpCharacterClass* newline_atom = new RegExpCharacterClass('n'); |
| 3762 | TextNode* newline_matcher = new TextNode( |
| 3763 | newline_atom, |
| 3764 | ActionNode::PositiveSubmatchSuccess(stack_pointer_register, |
| 3765 | position_register, |
| 3766 | 0, // No captures inside. |
| 3767 | -1, // Ignored if no captures. |
| 3768 | on_success)); |
| 3769 | // Create an end-of-input matcher. |
| 3770 | RegExpNode* end_of_line = ActionNode::BeginSubmatch( |
| 3771 | stack_pointer_register, |
| 3772 | position_register, |
| 3773 | newline_matcher); |
| 3774 | // Add the two alternatives to the ChoiceNode. |
| 3775 | GuardedAlternative eol_alternative(end_of_line); |
| 3776 | result->AddAlternative(eol_alternative); |
| 3777 | GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success)); |
| 3778 | result->AddAlternative(end_alternative); |
| 3779 | return result; |
| 3780 | } |
| 3781 | default: |
| 3782 | UNREACHABLE(); |
| 3783 | } |
| 3784 | return on_success; |
| 3785 | } |
| 3786 | |
| 3787 | |
| 3788 | RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler, |
| 3789 | RegExpNode* on_success) { |
| 3790 | return new BackReferenceNode(RegExpCapture::StartRegister(index()), |
| 3791 | RegExpCapture::EndRegister(index()), |
| 3792 | on_success); |
| 3793 | } |
| 3794 | |
| 3795 | |
| 3796 | RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler, |
| 3797 | RegExpNode* on_success) { |
| 3798 | return on_success; |
| 3799 | } |
| 3800 | |
| 3801 | |
| 3802 | RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler, |
| 3803 | RegExpNode* on_success) { |
| 3804 | int stack_pointer_register = compiler->AllocateRegister(); |
| 3805 | int position_register = compiler->AllocateRegister(); |
| 3806 | |
| 3807 | const int registers_per_capture = 2; |
| 3808 | const int register_of_first_capture = 2; |
| 3809 | int register_count = capture_count_ * registers_per_capture; |
| 3810 | int register_start = |
| 3811 | register_of_first_capture + capture_from_ * registers_per_capture; |
| 3812 | |
| 3813 | RegExpNode* success; |
| 3814 | if (is_positive()) { |
| 3815 | RegExpNode* node = ActionNode::BeginSubmatch( |
| 3816 | stack_pointer_register, |
| 3817 | position_register, |
| 3818 | body()->ToNode( |
| 3819 | compiler, |
| 3820 | ActionNode::PositiveSubmatchSuccess(stack_pointer_register, |
| 3821 | position_register, |
| 3822 | register_count, |
| 3823 | register_start, |
| 3824 | on_success))); |
| 3825 | return node; |
| 3826 | } else { |
| 3827 | // We use a ChoiceNode for a negative lookahead because it has most of |
| 3828 | // the characteristics we need. It has the body of the lookahead as its |
| 3829 | // first alternative and the expression after the lookahead of the second |
| 3830 | // alternative. If the first alternative succeeds then the |
| 3831 | // NegativeSubmatchSuccess will unwind the stack including everything the |
| 3832 | // choice node set up and backtrack. If the first alternative fails then |
| 3833 | // the second alternative is tried, which is exactly the desired result |
| 3834 | // for a negative lookahead. The NegativeLookaheadChoiceNode is a special |
| 3835 | // ChoiceNode that knows to ignore the first exit when calculating quick |
| 3836 | // checks. |
| 3837 | GuardedAlternative body_alt( |
| 3838 | body()->ToNode( |
| 3839 | compiler, |
| 3840 | success = new NegativeSubmatchSuccess(stack_pointer_register, |
| 3841 | position_register, |
| 3842 | register_count, |
| 3843 | register_start))); |
| 3844 | ChoiceNode* choice_node = |
| 3845 | new NegativeLookaheadChoiceNode(body_alt, |
| 3846 | GuardedAlternative(on_success)); |
| 3847 | return ActionNode::BeginSubmatch(stack_pointer_register, |
| 3848 | position_register, |
| 3849 | choice_node); |
| 3850 | } |
| 3851 | } |
| 3852 | |
| 3853 | |
| 3854 | RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler, |
| 3855 | RegExpNode* on_success) { |
| 3856 | return ToNode(body(), index(), compiler, on_success); |
| 3857 | } |
| 3858 | |
| 3859 | |
| 3860 | RegExpNode* RegExpCapture::ToNode(RegExpTree* body, |
| 3861 | int index, |
| 3862 | RegExpCompiler* compiler, |
| 3863 | RegExpNode* on_success) { |
| 3864 | int start_reg = RegExpCapture::StartRegister(index); |
| 3865 | int end_reg = RegExpCapture::EndRegister(index); |
| 3866 | RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success); |
| 3867 | RegExpNode* body_node = body->ToNode(compiler, store_end); |
| 3868 | return ActionNode::StorePosition(start_reg, true, body_node); |
| 3869 | } |
| 3870 | |
| 3871 | |
| 3872 | RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler, |
| 3873 | RegExpNode* on_success) { |
| 3874 | ZoneList<RegExpTree*>* children = nodes(); |
| 3875 | RegExpNode* current = on_success; |
| 3876 | for (int i = children->length() - 1; i >= 0; i--) { |
| 3877 | current = children->at(i)->ToNode(compiler, current); |
| 3878 | } |
| 3879 | return current; |
| 3880 | } |
| 3881 | |
| 3882 | |
| 3883 | static void AddClass(const uc16* elmv, |
| 3884 | int elmc, |
| 3885 | ZoneList<CharacterRange>* ranges) { |
| 3886 | for (int i = 0; i < elmc; i += 2) { |
| 3887 | ASSERT(elmv[i] <= elmv[i + 1]); |
| 3888 | ranges->Add(CharacterRange(elmv[i], elmv[i + 1])); |
| 3889 | } |
| 3890 | } |
| 3891 | |
| 3892 | |
| 3893 | static void AddClassNegated(const uc16 *elmv, |
| 3894 | int elmc, |
| 3895 | ZoneList<CharacterRange>* ranges) { |
| 3896 | ASSERT(elmv[0] != 0x0000); |
| 3897 | ASSERT(elmv[elmc-1] != String::kMaxUC16CharCode); |
| 3898 | uc16 last = 0x0000; |
| 3899 | for (int i = 0; i < elmc; i += 2) { |
| 3900 | ASSERT(last <= elmv[i] - 1); |
| 3901 | ASSERT(elmv[i] <= elmv[i + 1]); |
| 3902 | ranges->Add(CharacterRange(last, elmv[i] - 1)); |
| 3903 | last = elmv[i + 1] + 1; |
| 3904 | } |
| 3905 | ranges->Add(CharacterRange(last, String::kMaxUC16CharCode)); |
| 3906 | } |
| 3907 | |
| 3908 | |
| 3909 | void CharacterRange::AddClassEscape(uc16 type, |
| 3910 | ZoneList<CharacterRange>* ranges) { |
| 3911 | switch (type) { |
| 3912 | case 's': |
| 3913 | AddClass(kSpaceRanges, kSpaceRangeCount, ranges); |
| 3914 | break; |
| 3915 | case 'S': |
| 3916 | AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges); |
| 3917 | break; |
| 3918 | case 'w': |
| 3919 | AddClass(kWordRanges, kWordRangeCount, ranges); |
| 3920 | break; |
| 3921 | case 'W': |
| 3922 | AddClassNegated(kWordRanges, kWordRangeCount, ranges); |
| 3923 | break; |
| 3924 | case 'd': |
| 3925 | AddClass(kDigitRanges, kDigitRangeCount, ranges); |
| 3926 | break; |
| 3927 | case 'D': |
| 3928 | AddClassNegated(kDigitRanges, kDigitRangeCount, ranges); |
| 3929 | break; |
| 3930 | case '.': |
| 3931 | AddClassNegated(kLineTerminatorRanges, |
| 3932 | kLineTerminatorRangeCount, |
| 3933 | ranges); |
| 3934 | break; |
| 3935 | // This is not a character range as defined by the spec but a |
| 3936 | // convenient shorthand for a character class that matches any |
| 3937 | // character. |
| 3938 | case '*': |
| 3939 | ranges->Add(CharacterRange::Everything()); |
| 3940 | break; |
| 3941 | // This is the set of characters matched by the $ and ^ symbols |
| 3942 | // in multiline mode. |
| 3943 | case 'n': |
| 3944 | AddClass(kLineTerminatorRanges, |
| 3945 | kLineTerminatorRangeCount, |
| 3946 | ranges); |
| 3947 | break; |
| 3948 | default: |
| 3949 | UNREACHABLE(); |
| 3950 | } |
| 3951 | } |
| 3952 | |
| 3953 | |
| 3954 | Vector<const uc16> CharacterRange::GetWordBounds() { |
| 3955 | return Vector<const uc16>(kWordRanges, kWordRangeCount); |
| 3956 | } |
| 3957 | |
| 3958 | |
| 3959 | class CharacterRangeSplitter { |
| 3960 | public: |
| 3961 | CharacterRangeSplitter(ZoneList<CharacterRange>** included, |
| 3962 | ZoneList<CharacterRange>** excluded) |
| 3963 | : included_(included), |
| 3964 | excluded_(excluded) { } |
| 3965 | void Call(uc16 from, DispatchTable::Entry entry); |
| 3966 | |
| 3967 | static const int kInBase = 0; |
| 3968 | static const int kInOverlay = 1; |
| 3969 | |
| 3970 | private: |
| 3971 | ZoneList<CharacterRange>** included_; |
| 3972 | ZoneList<CharacterRange>** excluded_; |
| 3973 | }; |
| 3974 | |
| 3975 | |
| 3976 | void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) { |
| 3977 | if (!entry.out_set()->Get(kInBase)) return; |
| 3978 | ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay) |
| 3979 | ? included_ |
| 3980 | : excluded_; |
| 3981 | if (*target == NULL) *target = new ZoneList<CharacterRange>(2); |
| 3982 | (*target)->Add(CharacterRange(entry.from(), entry.to())); |
| 3983 | } |
| 3984 | |
| 3985 | |
| 3986 | void CharacterRange::Split(ZoneList<CharacterRange>* base, |
| 3987 | Vector<const uc16> overlay, |
| 3988 | ZoneList<CharacterRange>** included, |
| 3989 | ZoneList<CharacterRange>** excluded) { |
| 3990 | ASSERT_EQ(NULL, *included); |
| 3991 | ASSERT_EQ(NULL, *excluded); |
| 3992 | DispatchTable table; |
| 3993 | for (int i = 0; i < base->length(); i++) |
| 3994 | table.AddRange(base->at(i), CharacterRangeSplitter::kInBase); |
| 3995 | for (int i = 0; i < overlay.length(); i += 2) { |
| 3996 | table.AddRange(CharacterRange(overlay[i], overlay[i+1]), |
| 3997 | CharacterRangeSplitter::kInOverlay); |
| 3998 | } |
| 3999 | CharacterRangeSplitter callback(included, excluded); |
| 4000 | table.ForEach(&callback); |
| 4001 | } |
| 4002 | |
| 4003 | |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4004 | static void AddUncanonicals(ZoneList<CharacterRange>* ranges, |
| 4005 | int bottom, |
| 4006 | int top); |
| 4007 | |
| 4008 | |
| 4009 | void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges, |
| 4010 | bool is_ascii) { |
| 4011 | uc16 bottom = from(); |
| 4012 | uc16 top = to(); |
| 4013 | if (is_ascii) { |
| 4014 | if (bottom > String::kMaxAsciiCharCode) return; |
| 4015 | if (top > String::kMaxAsciiCharCode) top = String::kMaxAsciiCharCode; |
| 4016 | } |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4017 | unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4018 | if (top == bottom) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4019 | // If this is a singleton we just expand the one character. |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4020 | int length = uncanonicalize.get(bottom, '\0', chars); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4021 | for (int i = 0; i < length; i++) { |
| 4022 | uc32 chr = chars[i]; |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4023 | if (chr != bottom) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4024 | ranges->Add(CharacterRange::Singleton(chars[i])); |
| 4025 | } |
| 4026 | } |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4027 | } else { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4028 | // If this is a range we expand the characters block by block, |
| 4029 | // expanding contiguous subranges (blocks) one at a time. |
| 4030 | // The approach is as follows. For a given start character we |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4031 | // look up the remainder of the block that contains it (represented |
| 4032 | // by the end point), for instance we find 'z' if the character |
| 4033 | // is 'c'. A block is characterized by the property |
| 4034 | // that all characters uncanonicalize in the same way, except that |
| 4035 | // each entry in the result is incremented by the distance from the first |
| 4036 | // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and |
| 4037 | // the k'th letter uncanonicalizes to ['a' + k, 'A' + k]. |
| 4038 | // Once we've found the end point we look up its uncanonicalization |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4039 | // and produce a range for each element. For instance for [c-f] |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4040 | // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4041 | // add a range if it is not already contained in the input, so [c-f] |
| 4042 | // will be skipped but [C-F] will be added. If this range is not |
| 4043 | // completely contained in a block we do this for all the blocks |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4044 | // covered by the range (handling characters that is not in a block |
| 4045 | // as a "singleton block"). |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4046 | unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4047 | int pos = bottom; |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4048 | while (pos < top) { |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4049 | int length = canonrange.get(pos, '\0', range); |
| 4050 | uc16 block_end; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4051 | if (length == 0) { |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4052 | block_end = pos; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4053 | } else { |
| 4054 | ASSERT_EQ(1, length); |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4055 | block_end = range[0]; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4056 | } |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4057 | int end = (block_end > top) ? top : block_end; |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4058 | length = uncanonicalize.get(block_end, '\0', range); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4059 | for (int i = 0; i < length; i++) { |
| 4060 | uc32 c = range[i]; |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4061 | uc16 range_from = c - (block_end - pos); |
| 4062 | uc16 range_to = c - (block_end - end); |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4063 | if (!(bottom <= range_from && range_to <= top)) { |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4064 | ranges->Add(CharacterRange(range_from, range_to)); |
| 4065 | } |
| 4066 | } |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4067 | pos = end + 1; |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4068 | } |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4069 | } |
| 4070 | } |
| 4071 | |
| 4072 | |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4073 | bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) { |
| 4074 | ASSERT_NOT_NULL(ranges); |
| 4075 | int n = ranges->length(); |
| 4076 | if (n <= 1) return true; |
| 4077 | int max = ranges->at(0).to(); |
| 4078 | for (int i = 1; i < n; i++) { |
| 4079 | CharacterRange next_range = ranges->at(i); |
| 4080 | if (next_range.from() <= max + 1) return false; |
| 4081 | max = next_range.to(); |
| 4082 | } |
| 4083 | return true; |
| 4084 | } |
| 4085 | |
| 4086 | SetRelation CharacterRange::WordCharacterRelation( |
| 4087 | ZoneList<CharacterRange>* range) { |
| 4088 | ASSERT(IsCanonical(range)); |
| 4089 | int i = 0; // Word character range index. |
| 4090 | int j = 0; // Argument range index. |
| 4091 | ASSERT_NE(0, kWordRangeCount); |
| 4092 | SetRelation result; |
| 4093 | if (range->length() == 0) { |
| 4094 | result.SetElementsInSecondSet(); |
| 4095 | return result; |
| 4096 | } |
| 4097 | CharacterRange argument_range = range->at(0); |
| 4098 | CharacterRange word_range = CharacterRange(kWordRanges[0], kWordRanges[1]); |
| 4099 | while (i < kWordRangeCount && j < range->length()) { |
| 4100 | // Check the two ranges for the five cases: |
| 4101 | // - no overlap. |
| 4102 | // - partial overlap (there are elements in both ranges that isn't |
| 4103 | // in the other, and there are also elements that are in both). |
| 4104 | // - argument range entirely inside word range. |
| 4105 | // - word range entirely inside argument range. |
| 4106 | // - ranges are completely equal. |
| 4107 | |
| 4108 | // First check for no overlap. The earlier range is not in the other set. |
| 4109 | if (argument_range.from() > word_range.to()) { |
| 4110 | // Ranges are disjoint. The earlier word range contains elements that |
| 4111 | // cannot be in the argument set. |
| 4112 | result.SetElementsInSecondSet(); |
| 4113 | } else if (word_range.from() > argument_range.to()) { |
| 4114 | // Ranges are disjoint. The earlier argument range contains elements that |
| 4115 | // cannot be in the word set. |
| 4116 | result.SetElementsInFirstSet(); |
| 4117 | } else if (word_range.from() <= argument_range.from() && |
| 4118 | word_range.to() >= argument_range.from()) { |
| 4119 | result.SetElementsInBothSets(); |
| 4120 | // argument range completely inside word range. |
| 4121 | if (word_range.from() < argument_range.from() || |
| 4122 | word_range.to() > argument_range.from()) { |
| 4123 | result.SetElementsInSecondSet(); |
| 4124 | } |
| 4125 | } else if (word_range.from() >= argument_range.from() && |
| 4126 | word_range.to() <= argument_range.from()) { |
| 4127 | result.SetElementsInBothSets(); |
| 4128 | result.SetElementsInFirstSet(); |
| 4129 | } else { |
| 4130 | // There is overlap, and neither is a subrange of the other |
| 4131 | result.SetElementsInFirstSet(); |
| 4132 | result.SetElementsInSecondSet(); |
| 4133 | result.SetElementsInBothSets(); |
| 4134 | } |
| 4135 | if (result.NonTrivialIntersection()) { |
| 4136 | // The result is as (im)precise as we can possibly make it. |
| 4137 | return result; |
| 4138 | } |
| 4139 | // Progress the range(s) with minimal to-character. |
| 4140 | uc16 word_to = word_range.to(); |
| 4141 | uc16 argument_to = argument_range.to(); |
| 4142 | if (argument_to <= word_to) { |
| 4143 | j++; |
| 4144 | if (j < range->length()) { |
| 4145 | argument_range = range->at(j); |
| 4146 | } |
| 4147 | } |
| 4148 | if (word_to <= argument_to) { |
| 4149 | i += 2; |
| 4150 | if (i < kWordRangeCount) { |
| 4151 | word_range = CharacterRange(kWordRanges[i], kWordRanges[i + 1]); |
| 4152 | } |
| 4153 | } |
| 4154 | } |
| 4155 | // Check if anything wasn't compared in the loop. |
| 4156 | if (i < kWordRangeCount) { |
| 4157 | // word range contains something not in argument range. |
| 4158 | result.SetElementsInSecondSet(); |
| 4159 | } else if (j < range->length()) { |
| 4160 | // Argument range contains something not in word range. |
| 4161 | result.SetElementsInFirstSet(); |
| 4162 | } |
| 4163 | |
| 4164 | return result; |
| 4165 | } |
| 4166 | |
| 4167 | |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4168 | static void AddUncanonicals(ZoneList<CharacterRange>* ranges, |
| 4169 | int bottom, |
| 4170 | int top) { |
| 4171 | unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth]; |
| 4172 | // Zones with no case mappings. There is a DEBUG-mode loop to assert that |
| 4173 | // this table is correct. |
| 4174 | // 0x0600 - 0x0fff |
| 4175 | // 0x1100 - 0x1cff |
| 4176 | // 0x2000 - 0x20ff |
| 4177 | // 0x2200 - 0x23ff |
| 4178 | // 0x2500 - 0x2bff |
| 4179 | // 0x2e00 - 0xa5ff |
| 4180 | // 0xa800 - 0xfaff |
| 4181 | // 0xfc00 - 0xfeff |
| 4182 | const int boundary_count = 18; |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4183 | int boundaries[] = { |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4184 | 0x600, 0x1000, 0x1100, 0x1d00, 0x2000, 0x2100, 0x2200, 0x2400, 0x2500, |
| 4185 | 0x2c00, 0x2e00, 0xa600, 0xa800, 0xfb00, 0xfc00, 0xff00}; |
| 4186 | |
| 4187 | // Special ASCII rule from spec can save us some work here. |
| 4188 | if (bottom == 0x80 && top == 0xffff) return; |
| 4189 | |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4190 | if (top <= boundaries[0]) { |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4191 | CharacterRange range(bottom, top); |
| 4192 | range.AddCaseEquivalents(ranges, false); |
| 4193 | return; |
| 4194 | } |
| 4195 | |
| 4196 | // Split up very large ranges. This helps remove ranges where there are no |
| 4197 | // case mappings. |
| 4198 | for (int i = 0; i < boundary_count; i++) { |
| 4199 | if (bottom < boundaries[i] && top >= boundaries[i]) { |
| 4200 | AddUncanonicals(ranges, bottom, boundaries[i] - 1); |
| 4201 | AddUncanonicals(ranges, boundaries[i], top); |
| 4202 | return; |
| 4203 | } |
| 4204 | } |
| 4205 | |
| 4206 | // If we are completely in a zone with no case mappings then we are done. |
Ben Murdoch | bb769b2 | 2010-08-11 14:56:33 +0100 | [diff] [blame] | 4207 | for (int i = 0; i < boundary_count; i += 2) { |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4208 | if (bottom >= boundaries[i] && top < boundaries[i + 1]) { |
| 4209 | #ifdef DEBUG |
| 4210 | for (int j = bottom; j <= top; j++) { |
| 4211 | unsigned current_char = j; |
| 4212 | int length = uncanonicalize.get(current_char, '\0', chars); |
| 4213 | for (int k = 0; k < length; k++) { |
| 4214 | ASSERT(chars[k] == current_char); |
| 4215 | } |
| 4216 | } |
| 4217 | #endif |
| 4218 | return; |
| 4219 | } |
| 4220 | } |
| 4221 | |
| 4222 | // Step through the range finding equivalent characters. |
| 4223 | ZoneList<unibrow::uchar> *characters = new ZoneList<unibrow::uchar>(100); |
| 4224 | for (int i = bottom; i <= top; i++) { |
| 4225 | int length = uncanonicalize.get(i, '\0', chars); |
| 4226 | for (int j = 0; j < length; j++) { |
| 4227 | uc32 chr = chars[j]; |
| 4228 | if (chr != i && (chr < bottom || chr > top)) { |
| 4229 | characters->Add(chr); |
| 4230 | } |
| 4231 | } |
| 4232 | } |
| 4233 | |
| 4234 | // Step through the equivalent characters finding simple ranges and |
| 4235 | // adding ranges to the character class. |
| 4236 | if (characters->length() > 0) { |
| 4237 | int new_from = characters->at(0); |
| 4238 | int new_to = new_from; |
| 4239 | for (int i = 1; i < characters->length(); i++) { |
| 4240 | int chr = characters->at(i); |
| 4241 | if (chr == new_to + 1) { |
| 4242 | new_to++; |
| 4243 | } else { |
| 4244 | if (new_to == new_from) { |
| 4245 | ranges->Add(CharacterRange::Singleton(new_from)); |
| 4246 | } else { |
| 4247 | ranges->Add(CharacterRange(new_from, new_to)); |
| 4248 | } |
| 4249 | new_from = new_to = chr; |
| 4250 | } |
| 4251 | } |
| 4252 | if (new_to == new_from) { |
| 4253 | ranges->Add(CharacterRange::Singleton(new_from)); |
| 4254 | } else { |
| 4255 | ranges->Add(CharacterRange(new_from, new_to)); |
| 4256 | } |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4257 | } |
| 4258 | } |
| 4259 | |
| 4260 | |
| 4261 | ZoneList<CharacterRange>* CharacterSet::ranges() { |
| 4262 | if (ranges_ == NULL) { |
| 4263 | ranges_ = new ZoneList<CharacterRange>(2); |
| 4264 | CharacterRange::AddClassEscape(standard_set_type_, ranges_); |
| 4265 | } |
| 4266 | return ranges_; |
| 4267 | } |
| 4268 | |
| 4269 | |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4270 | // Move a number of elements in a zonelist to another position |
| 4271 | // in the same list. Handles overlapping source and target areas. |
| 4272 | static void MoveRanges(ZoneList<CharacterRange>* list, |
| 4273 | int from, |
| 4274 | int to, |
| 4275 | int count) { |
| 4276 | // Ranges are potentially overlapping. |
| 4277 | if (from < to) { |
| 4278 | for (int i = count - 1; i >= 0; i--) { |
| 4279 | list->at(to + i) = list->at(from + i); |
| 4280 | } |
| 4281 | } else { |
| 4282 | for (int i = 0; i < count; i++) { |
| 4283 | list->at(to + i) = list->at(from + i); |
| 4284 | } |
| 4285 | } |
| 4286 | } |
| 4287 | |
| 4288 | |
| 4289 | static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list, |
| 4290 | int count, |
| 4291 | CharacterRange insert) { |
| 4292 | // Inserts a range into list[0..count[, which must be sorted |
| 4293 | // by from value and non-overlapping and non-adjacent, using at most |
| 4294 | // list[0..count] for the result. Returns the number of resulting |
| 4295 | // canonicalized ranges. Inserting a range may collapse existing ranges into |
| 4296 | // fewer ranges, so the return value can be anything in the range 1..count+1. |
| 4297 | uc16 from = insert.from(); |
| 4298 | uc16 to = insert.to(); |
| 4299 | int start_pos = 0; |
| 4300 | int end_pos = count; |
| 4301 | for (int i = count - 1; i >= 0; i--) { |
| 4302 | CharacterRange current = list->at(i); |
| 4303 | if (current.from() > to + 1) { |
| 4304 | end_pos = i; |
| 4305 | } else if (current.to() + 1 < from) { |
| 4306 | start_pos = i + 1; |
| 4307 | break; |
| 4308 | } |
| 4309 | } |
| 4310 | |
| 4311 | // Inserted range overlaps, or is adjacent to, ranges at positions |
| 4312 | // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are |
| 4313 | // not affected by the insertion. |
| 4314 | // If start_pos == end_pos, the range must be inserted before start_pos. |
| 4315 | // if start_pos < end_pos, the entire range from start_pos to end_pos |
| 4316 | // must be merged with the insert range. |
| 4317 | |
| 4318 | if (start_pos == end_pos) { |
| 4319 | // Insert between existing ranges at position start_pos. |
| 4320 | if (start_pos < count) { |
| 4321 | MoveRanges(list, start_pos, start_pos + 1, count - start_pos); |
| 4322 | } |
| 4323 | list->at(start_pos) = insert; |
| 4324 | return count + 1; |
| 4325 | } |
| 4326 | if (start_pos + 1 == end_pos) { |
| 4327 | // Replace single existing range at position start_pos. |
| 4328 | CharacterRange to_replace = list->at(start_pos); |
| 4329 | int new_from = Min(to_replace.from(), from); |
| 4330 | int new_to = Max(to_replace.to(), to); |
| 4331 | list->at(start_pos) = CharacterRange(new_from, new_to); |
| 4332 | return count; |
| 4333 | } |
| 4334 | // Replace a number of existing ranges from start_pos to end_pos - 1. |
| 4335 | // Move the remaining ranges down. |
| 4336 | |
| 4337 | int new_from = Min(list->at(start_pos).from(), from); |
| 4338 | int new_to = Max(list->at(end_pos - 1).to(), to); |
| 4339 | if (end_pos < count) { |
| 4340 | MoveRanges(list, end_pos, start_pos + 1, count - end_pos); |
| 4341 | } |
| 4342 | list->at(start_pos) = CharacterRange(new_from, new_to); |
| 4343 | return count - (end_pos - start_pos) + 1; |
| 4344 | } |
| 4345 | |
| 4346 | |
| 4347 | void CharacterSet::Canonicalize() { |
| 4348 | // Special/default classes are always considered canonical. The result |
| 4349 | // of calling ranges() will be sorted. |
| 4350 | if (ranges_ == NULL) return; |
| 4351 | CharacterRange::Canonicalize(ranges_); |
| 4352 | } |
| 4353 | |
| 4354 | |
| 4355 | void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) { |
| 4356 | if (character_ranges->length() <= 1) return; |
| 4357 | // Check whether ranges are already canonical (increasing, non-overlapping, |
| 4358 | // non-adjacent). |
| 4359 | int n = character_ranges->length(); |
| 4360 | int max = character_ranges->at(0).to(); |
| 4361 | int i = 1; |
| 4362 | while (i < n) { |
| 4363 | CharacterRange current = character_ranges->at(i); |
| 4364 | if (current.from() <= max + 1) { |
| 4365 | break; |
| 4366 | } |
| 4367 | max = current.to(); |
| 4368 | i++; |
| 4369 | } |
| 4370 | // Canonical until the i'th range. If that's all of them, we are done. |
| 4371 | if (i == n) return; |
| 4372 | |
| 4373 | // The ranges at index i and forward are not canonicalized. Make them so by |
| 4374 | // doing the equivalent of insertion sort (inserting each into the previous |
| 4375 | // list, in order). |
| 4376 | // Notice that inserting a range can reduce the number of ranges in the |
| 4377 | // result due to combining of adjacent and overlapping ranges. |
| 4378 | int read = i; // Range to insert. |
| 4379 | int num_canonical = i; // Length of canonicalized part of list. |
| 4380 | do { |
| 4381 | num_canonical = InsertRangeInCanonicalList(character_ranges, |
| 4382 | num_canonical, |
| 4383 | character_ranges->at(read)); |
| 4384 | read++; |
| 4385 | } while (read < n); |
| 4386 | character_ranges->Rewind(num_canonical); |
| 4387 | |
| 4388 | ASSERT(CharacterRange::IsCanonical(character_ranges)); |
| 4389 | } |
| 4390 | |
| 4391 | |
| 4392 | // Utility function for CharacterRange::Merge. Adds a range at the end of |
| 4393 | // a canonicalized range list, if necessary merging the range with the last |
| 4394 | // range of the list. |
| 4395 | static void AddRangeToSet(ZoneList<CharacterRange>* set, CharacterRange range) { |
| 4396 | if (set == NULL) return; |
| 4397 | ASSERT(set->length() == 0 || set->at(set->length() - 1).to() < range.from()); |
| 4398 | int n = set->length(); |
| 4399 | if (n > 0) { |
| 4400 | CharacterRange lastRange = set->at(n - 1); |
| 4401 | if (lastRange.to() == range.from() - 1) { |
| 4402 | set->at(n - 1) = CharacterRange(lastRange.from(), range.to()); |
| 4403 | return; |
| 4404 | } |
| 4405 | } |
| 4406 | set->Add(range); |
| 4407 | } |
| 4408 | |
| 4409 | |
| 4410 | static void AddRangeToSelectedSet(int selector, |
| 4411 | ZoneList<CharacterRange>* first_set, |
| 4412 | ZoneList<CharacterRange>* second_set, |
| 4413 | ZoneList<CharacterRange>* intersection_set, |
| 4414 | CharacterRange range) { |
| 4415 | switch (selector) { |
| 4416 | case kInsideFirst: |
| 4417 | AddRangeToSet(first_set, range); |
| 4418 | break; |
| 4419 | case kInsideSecond: |
| 4420 | AddRangeToSet(second_set, range); |
| 4421 | break; |
| 4422 | case kInsideBoth: |
| 4423 | AddRangeToSet(intersection_set, range); |
| 4424 | break; |
| 4425 | } |
| 4426 | } |
| 4427 | |
| 4428 | |
| 4429 | |
| 4430 | void CharacterRange::Merge(ZoneList<CharacterRange>* first_set, |
| 4431 | ZoneList<CharacterRange>* second_set, |
| 4432 | ZoneList<CharacterRange>* first_set_only_out, |
| 4433 | ZoneList<CharacterRange>* second_set_only_out, |
| 4434 | ZoneList<CharacterRange>* both_sets_out) { |
| 4435 | // Inputs are canonicalized. |
| 4436 | ASSERT(CharacterRange::IsCanonical(first_set)); |
| 4437 | ASSERT(CharacterRange::IsCanonical(second_set)); |
| 4438 | // Outputs are empty, if applicable. |
| 4439 | ASSERT(first_set_only_out == NULL || first_set_only_out->length() == 0); |
| 4440 | ASSERT(second_set_only_out == NULL || second_set_only_out->length() == 0); |
| 4441 | ASSERT(both_sets_out == NULL || both_sets_out->length() == 0); |
| 4442 | |
| 4443 | // Merge sets by iterating through the lists in order of lowest "from" value, |
| 4444 | // and putting intervals into one of three sets. |
| 4445 | |
| 4446 | if (first_set->length() == 0) { |
| 4447 | second_set_only_out->AddAll(*second_set); |
| 4448 | return; |
| 4449 | } |
| 4450 | if (second_set->length() == 0) { |
| 4451 | first_set_only_out->AddAll(*first_set); |
| 4452 | return; |
| 4453 | } |
| 4454 | // Indices into input lists. |
| 4455 | int i1 = 0; |
| 4456 | int i2 = 0; |
| 4457 | // Cache length of input lists. |
| 4458 | int n1 = first_set->length(); |
| 4459 | int n2 = second_set->length(); |
| 4460 | // Current range. May be invalid if state is kInsideNone. |
| 4461 | int from = 0; |
| 4462 | int to = -1; |
| 4463 | // Where current range comes from. |
| 4464 | int state = kInsideNone; |
| 4465 | |
| 4466 | while (i1 < n1 || i2 < n2) { |
| 4467 | CharacterRange next_range; |
| 4468 | int range_source; |
Leon Clarke | d91b9f7 | 2010-01-27 17:25:45 +0000 | [diff] [blame] | 4469 | if (i2 == n2 || |
| 4470 | (i1 < n1 && first_set->at(i1).from() < second_set->at(i2).from())) { |
| 4471 | // Next smallest element is in first set. |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4472 | next_range = first_set->at(i1++); |
| 4473 | range_source = kInsideFirst; |
| 4474 | } else { |
Leon Clarke | d91b9f7 | 2010-01-27 17:25:45 +0000 | [diff] [blame] | 4475 | // Next smallest element is in second set. |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4476 | next_range = second_set->at(i2++); |
| 4477 | range_source = kInsideSecond; |
| 4478 | } |
| 4479 | if (to < next_range.from()) { |
| 4480 | // Ranges disjoint: |current| |next| |
| 4481 | AddRangeToSelectedSet(state, |
| 4482 | first_set_only_out, |
| 4483 | second_set_only_out, |
| 4484 | both_sets_out, |
| 4485 | CharacterRange(from, to)); |
| 4486 | from = next_range.from(); |
| 4487 | to = next_range.to(); |
| 4488 | state = range_source; |
| 4489 | } else { |
| 4490 | if (from < next_range.from()) { |
| 4491 | AddRangeToSelectedSet(state, |
| 4492 | first_set_only_out, |
| 4493 | second_set_only_out, |
| 4494 | both_sets_out, |
| 4495 | CharacterRange(from, next_range.from()-1)); |
| 4496 | } |
| 4497 | if (to < next_range.to()) { |
| 4498 | // Ranges overlap: |current| |
| 4499 | // |next| |
| 4500 | AddRangeToSelectedSet(state | range_source, |
| 4501 | first_set_only_out, |
| 4502 | second_set_only_out, |
| 4503 | both_sets_out, |
| 4504 | CharacterRange(next_range.from(), to)); |
| 4505 | from = to + 1; |
| 4506 | to = next_range.to(); |
| 4507 | state = range_source; |
| 4508 | } else { |
| 4509 | // Range included: |current| , possibly ending at same character. |
| 4510 | // |next| |
| 4511 | AddRangeToSelectedSet( |
| 4512 | state | range_source, |
| 4513 | first_set_only_out, |
| 4514 | second_set_only_out, |
| 4515 | both_sets_out, |
| 4516 | CharacterRange(next_range.from(), next_range.to())); |
| 4517 | from = next_range.to() + 1; |
| 4518 | // If ranges end at same character, both ranges are consumed completely. |
| 4519 | if (next_range.to() == to) state = kInsideNone; |
| 4520 | } |
| 4521 | } |
| 4522 | } |
| 4523 | AddRangeToSelectedSet(state, |
| 4524 | first_set_only_out, |
| 4525 | second_set_only_out, |
| 4526 | both_sets_out, |
| 4527 | CharacterRange(from, to)); |
| 4528 | } |
| 4529 | |
| 4530 | |
| 4531 | void CharacterRange::Negate(ZoneList<CharacterRange>* ranges, |
| 4532 | ZoneList<CharacterRange>* negated_ranges) { |
| 4533 | ASSERT(CharacterRange::IsCanonical(ranges)); |
| 4534 | ASSERT_EQ(0, negated_ranges->length()); |
| 4535 | int range_count = ranges->length(); |
| 4536 | uc16 from = 0; |
| 4537 | int i = 0; |
| 4538 | if (range_count > 0 && ranges->at(0).from() == 0) { |
| 4539 | from = ranges->at(0).to(); |
| 4540 | i = 1; |
| 4541 | } |
| 4542 | while (i < range_count) { |
| 4543 | CharacterRange range = ranges->at(i); |
| 4544 | negated_ranges->Add(CharacterRange(from + 1, range.from() - 1)); |
| 4545 | from = range.to(); |
| 4546 | i++; |
| 4547 | } |
| 4548 | if (from < String::kMaxUC16CharCode) { |
| 4549 | negated_ranges->Add(CharacterRange(from + 1, String::kMaxUC16CharCode)); |
| 4550 | } |
| 4551 | } |
| 4552 | |
| 4553 | |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4554 | |
| 4555 | // ------------------------------------------------------------------- |
| 4556 | // Interest propagation |
| 4557 | |
| 4558 | |
| 4559 | RegExpNode* RegExpNode::TryGetSibling(NodeInfo* info) { |
| 4560 | for (int i = 0; i < siblings_.length(); i++) { |
| 4561 | RegExpNode* sibling = siblings_.Get(i); |
| 4562 | if (sibling->info()->Matches(info)) |
| 4563 | return sibling; |
| 4564 | } |
| 4565 | return NULL; |
| 4566 | } |
| 4567 | |
| 4568 | |
| 4569 | RegExpNode* RegExpNode::EnsureSibling(NodeInfo* info, bool* cloned) { |
| 4570 | ASSERT_EQ(false, *cloned); |
| 4571 | siblings_.Ensure(this); |
| 4572 | RegExpNode* result = TryGetSibling(info); |
| 4573 | if (result != NULL) return result; |
| 4574 | result = this->Clone(); |
| 4575 | NodeInfo* new_info = result->info(); |
| 4576 | new_info->ResetCompilationState(); |
| 4577 | new_info->AddFromPreceding(info); |
| 4578 | AddSibling(result); |
| 4579 | *cloned = true; |
| 4580 | return result; |
| 4581 | } |
| 4582 | |
| 4583 | |
| 4584 | template <class C> |
| 4585 | static RegExpNode* PropagateToEndpoint(C* node, NodeInfo* info) { |
| 4586 | NodeInfo full_info(*node->info()); |
| 4587 | full_info.AddFromPreceding(info); |
| 4588 | bool cloned = false; |
| 4589 | return RegExpNode::EnsureSibling(node, &full_info, &cloned); |
| 4590 | } |
| 4591 | |
| 4592 | |
| 4593 | // ------------------------------------------------------------------- |
| 4594 | // Splay tree |
| 4595 | |
| 4596 | |
| 4597 | OutSet* OutSet::Extend(unsigned value) { |
| 4598 | if (Get(value)) |
| 4599 | return this; |
| 4600 | if (successors() != NULL) { |
| 4601 | for (int i = 0; i < successors()->length(); i++) { |
| 4602 | OutSet* successor = successors()->at(i); |
| 4603 | if (successor->Get(value)) |
| 4604 | return successor; |
| 4605 | } |
| 4606 | } else { |
| 4607 | successors_ = new ZoneList<OutSet*>(2); |
| 4608 | } |
| 4609 | OutSet* result = new OutSet(first_, remaining_); |
| 4610 | result->Set(value); |
| 4611 | successors()->Add(result); |
| 4612 | return result; |
| 4613 | } |
| 4614 | |
| 4615 | |
| 4616 | void OutSet::Set(unsigned value) { |
| 4617 | if (value < kFirstLimit) { |
| 4618 | first_ |= (1 << value); |
| 4619 | } else { |
| 4620 | if (remaining_ == NULL) |
| 4621 | remaining_ = new ZoneList<unsigned>(1); |
| 4622 | if (remaining_->is_empty() || !remaining_->Contains(value)) |
| 4623 | remaining_->Add(value); |
| 4624 | } |
| 4625 | } |
| 4626 | |
| 4627 | |
| 4628 | bool OutSet::Get(unsigned value) { |
| 4629 | if (value < kFirstLimit) { |
| 4630 | return (first_ & (1 << value)) != 0; |
| 4631 | } else if (remaining_ == NULL) { |
| 4632 | return false; |
| 4633 | } else { |
| 4634 | return remaining_->Contains(value); |
| 4635 | } |
| 4636 | } |
| 4637 | |
| 4638 | |
| 4639 | const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar; |
| 4640 | const DispatchTable::Entry DispatchTable::Config::kNoValue; |
| 4641 | |
| 4642 | |
| 4643 | void DispatchTable::AddRange(CharacterRange full_range, int value) { |
| 4644 | CharacterRange current = full_range; |
| 4645 | if (tree()->is_empty()) { |
| 4646 | // If this is the first range we just insert into the table. |
| 4647 | ZoneSplayTree<Config>::Locator loc; |
| 4648 | ASSERT_RESULT(tree()->Insert(current.from(), &loc)); |
| 4649 | loc.set_value(Entry(current.from(), current.to(), empty()->Extend(value))); |
| 4650 | return; |
| 4651 | } |
| 4652 | // First see if there is a range to the left of this one that |
| 4653 | // overlaps. |
| 4654 | ZoneSplayTree<Config>::Locator loc; |
| 4655 | if (tree()->FindGreatestLessThan(current.from(), &loc)) { |
| 4656 | Entry* entry = &loc.value(); |
| 4657 | // If we've found a range that overlaps with this one, and it |
| 4658 | // starts strictly to the left of this one, we have to fix it |
| 4659 | // because the following code only handles ranges that start on |
| 4660 | // or after the start point of the range we're adding. |
| 4661 | if (entry->from() < current.from() && entry->to() >= current.from()) { |
| 4662 | // Snap the overlapping range in half around the start point of |
| 4663 | // the range we're adding. |
| 4664 | CharacterRange left(entry->from(), current.from() - 1); |
| 4665 | CharacterRange right(current.from(), entry->to()); |
| 4666 | // The left part of the overlapping range doesn't overlap. |
| 4667 | // Truncate the whole entry to be just the left part. |
| 4668 | entry->set_to(left.to()); |
| 4669 | // The right part is the one that overlaps. We add this part |
| 4670 | // to the map and let the next step deal with merging it with |
| 4671 | // the range we're adding. |
| 4672 | ZoneSplayTree<Config>::Locator loc; |
| 4673 | ASSERT_RESULT(tree()->Insert(right.from(), &loc)); |
| 4674 | loc.set_value(Entry(right.from(), |
| 4675 | right.to(), |
| 4676 | entry->out_set())); |
| 4677 | } |
| 4678 | } |
| 4679 | while (current.is_valid()) { |
| 4680 | if (tree()->FindLeastGreaterThan(current.from(), &loc) && |
| 4681 | (loc.value().from() <= current.to()) && |
| 4682 | (loc.value().to() >= current.from())) { |
| 4683 | Entry* entry = &loc.value(); |
| 4684 | // We have overlap. If there is space between the start point of |
| 4685 | // the range we're adding and where the overlapping range starts |
| 4686 | // then we have to add a range covering just that space. |
| 4687 | if (current.from() < entry->from()) { |
| 4688 | ZoneSplayTree<Config>::Locator ins; |
| 4689 | ASSERT_RESULT(tree()->Insert(current.from(), &ins)); |
| 4690 | ins.set_value(Entry(current.from(), |
| 4691 | entry->from() - 1, |
| 4692 | empty()->Extend(value))); |
| 4693 | current.set_from(entry->from()); |
| 4694 | } |
| 4695 | ASSERT_EQ(current.from(), entry->from()); |
| 4696 | // If the overlapping range extends beyond the one we want to add |
| 4697 | // we have to snap the right part off and add it separately. |
| 4698 | if (entry->to() > current.to()) { |
| 4699 | ZoneSplayTree<Config>::Locator ins; |
| 4700 | ASSERT_RESULT(tree()->Insert(current.to() + 1, &ins)); |
| 4701 | ins.set_value(Entry(current.to() + 1, |
| 4702 | entry->to(), |
| 4703 | entry->out_set())); |
| 4704 | entry->set_to(current.to()); |
| 4705 | } |
| 4706 | ASSERT(entry->to() <= current.to()); |
| 4707 | // The overlapping range is now completely contained by the range |
| 4708 | // we're adding so we can just update it and move the start point |
| 4709 | // of the range we're adding just past it. |
| 4710 | entry->AddValue(value); |
| 4711 | // Bail out if the last interval ended at 0xFFFF since otherwise |
| 4712 | // adding 1 will wrap around to 0. |
| 4713 | if (entry->to() == String::kMaxUC16CharCode) |
| 4714 | break; |
| 4715 | ASSERT(entry->to() + 1 > current.from()); |
| 4716 | current.set_from(entry->to() + 1); |
| 4717 | } else { |
| 4718 | // There is no overlap so we can just add the range |
| 4719 | ZoneSplayTree<Config>::Locator ins; |
| 4720 | ASSERT_RESULT(tree()->Insert(current.from(), &ins)); |
| 4721 | ins.set_value(Entry(current.from(), |
| 4722 | current.to(), |
| 4723 | empty()->Extend(value))); |
| 4724 | break; |
| 4725 | } |
| 4726 | } |
| 4727 | } |
| 4728 | |
| 4729 | |
| 4730 | OutSet* DispatchTable::Get(uc16 value) { |
| 4731 | ZoneSplayTree<Config>::Locator loc; |
| 4732 | if (!tree()->FindGreatestLessThan(value, &loc)) |
| 4733 | return empty(); |
| 4734 | Entry* entry = &loc.value(); |
| 4735 | if (value <= entry->to()) |
| 4736 | return entry->out_set(); |
| 4737 | else |
| 4738 | return empty(); |
| 4739 | } |
| 4740 | |
| 4741 | |
| 4742 | // ------------------------------------------------------------------- |
| 4743 | // Analysis |
| 4744 | |
| 4745 | |
| 4746 | void Analysis::EnsureAnalyzed(RegExpNode* that) { |
| 4747 | StackLimitCheck check; |
| 4748 | if (check.HasOverflowed()) { |
| 4749 | fail("Stack overflow"); |
| 4750 | return; |
| 4751 | } |
| 4752 | if (that->info()->been_analyzed || that->info()->being_analyzed) |
| 4753 | return; |
| 4754 | that->info()->being_analyzed = true; |
| 4755 | that->Accept(this); |
| 4756 | that->info()->being_analyzed = false; |
| 4757 | that->info()->been_analyzed = true; |
| 4758 | } |
| 4759 | |
| 4760 | |
| 4761 | void Analysis::VisitEnd(EndNode* that) { |
| 4762 | // nothing to do |
| 4763 | } |
| 4764 | |
| 4765 | |
| 4766 | void TextNode::CalculateOffsets() { |
| 4767 | int element_count = elements()->length(); |
| 4768 | // Set up the offsets of the elements relative to the start. This is a fixed |
| 4769 | // quantity since a TextNode can only contain fixed-width things. |
| 4770 | int cp_offset = 0; |
| 4771 | for (int i = 0; i < element_count; i++) { |
| 4772 | TextElement& elm = elements()->at(i); |
| 4773 | elm.cp_offset = cp_offset; |
| 4774 | if (elm.type == TextElement::ATOM) { |
| 4775 | cp_offset += elm.data.u_atom->data().length(); |
| 4776 | } else { |
| 4777 | cp_offset++; |
| 4778 | Vector<const uc16> quarks = elm.data.u_atom->data(); |
| 4779 | } |
| 4780 | } |
| 4781 | } |
| 4782 | |
| 4783 | |
| 4784 | void Analysis::VisitText(TextNode* that) { |
| 4785 | if (ignore_case_) { |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 4786 | that->MakeCaseIndependent(is_ascii_); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4787 | } |
| 4788 | EnsureAnalyzed(that->on_success()); |
| 4789 | if (!has_failed()) { |
| 4790 | that->CalculateOffsets(); |
| 4791 | } |
| 4792 | } |
| 4793 | |
| 4794 | |
| 4795 | void Analysis::VisitAction(ActionNode* that) { |
| 4796 | RegExpNode* target = that->on_success(); |
| 4797 | EnsureAnalyzed(target); |
| 4798 | if (!has_failed()) { |
| 4799 | // If the next node is interested in what it follows then this node |
| 4800 | // has to be interested too so it can pass the information on. |
| 4801 | that->info()->AddFromFollowing(target->info()); |
| 4802 | } |
| 4803 | } |
| 4804 | |
| 4805 | |
| 4806 | void Analysis::VisitChoice(ChoiceNode* that) { |
| 4807 | NodeInfo* info = that->info(); |
| 4808 | for (int i = 0; i < that->alternatives()->length(); i++) { |
| 4809 | RegExpNode* node = that->alternatives()->at(i).node(); |
| 4810 | EnsureAnalyzed(node); |
| 4811 | if (has_failed()) return; |
| 4812 | // Anything the following nodes need to know has to be known by |
| 4813 | // this node also, so it can pass it on. |
| 4814 | info->AddFromFollowing(node->info()); |
| 4815 | } |
| 4816 | } |
| 4817 | |
| 4818 | |
| 4819 | void Analysis::VisitLoopChoice(LoopChoiceNode* that) { |
| 4820 | NodeInfo* info = that->info(); |
| 4821 | for (int i = 0; i < that->alternatives()->length(); i++) { |
| 4822 | RegExpNode* node = that->alternatives()->at(i).node(); |
| 4823 | if (node != that->loop_node()) { |
| 4824 | EnsureAnalyzed(node); |
| 4825 | if (has_failed()) return; |
| 4826 | info->AddFromFollowing(node->info()); |
| 4827 | } |
| 4828 | } |
| 4829 | // Check the loop last since it may need the value of this node |
| 4830 | // to get a correct result. |
| 4831 | EnsureAnalyzed(that->loop_node()); |
| 4832 | if (!has_failed()) { |
| 4833 | info->AddFromFollowing(that->loop_node()->info()); |
| 4834 | } |
| 4835 | } |
| 4836 | |
| 4837 | |
| 4838 | void Analysis::VisitBackReference(BackReferenceNode* that) { |
| 4839 | EnsureAnalyzed(that->on_success()); |
| 4840 | } |
| 4841 | |
| 4842 | |
| 4843 | void Analysis::VisitAssertion(AssertionNode* that) { |
| 4844 | EnsureAnalyzed(that->on_success()); |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4845 | AssertionNode::AssertionNodeType type = that->type(); |
| 4846 | if (type == AssertionNode::AT_BOUNDARY || |
| 4847 | type == AssertionNode::AT_NON_BOUNDARY) { |
| 4848 | // Check if the following character is known to be a word character |
| 4849 | // or known to not be a word character. |
| 4850 | ZoneList<CharacterRange>* following_chars = that->FirstCharacterSet(); |
| 4851 | |
| 4852 | CharacterRange::Canonicalize(following_chars); |
| 4853 | |
| 4854 | SetRelation word_relation = |
| 4855 | CharacterRange::WordCharacterRelation(following_chars); |
Andrei Popescu | 6d3d5a3 | 2010-04-27 19:40:12 +0100 | [diff] [blame] | 4856 | if (word_relation.Disjoint()) { |
| 4857 | // Includes the case where following_chars is empty (e.g., end-of-input). |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4858 | // Following character is definitely *not* a word character. |
| 4859 | type = (type == AssertionNode::AT_BOUNDARY) ? |
Andrei Popescu | 6d3d5a3 | 2010-04-27 19:40:12 +0100 | [diff] [blame] | 4860 | AssertionNode::AFTER_WORD_CHARACTER : |
| 4861 | AssertionNode::AFTER_NONWORD_CHARACTER; |
| 4862 | that->set_type(type); |
| 4863 | } else if (word_relation.ContainedIn()) { |
| 4864 | // Following character is definitely a word character. |
| 4865 | type = (type == AssertionNode::AT_BOUNDARY) ? |
| 4866 | AssertionNode::AFTER_NONWORD_CHARACTER : |
| 4867 | AssertionNode::AFTER_WORD_CHARACTER; |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4868 | that->set_type(type); |
| 4869 | } |
| 4870 | } |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 4871 | } |
| 4872 | |
| 4873 | |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4874 | ZoneList<CharacterRange>* RegExpNode::FirstCharacterSet() { |
| 4875 | if (first_character_set_ == NULL) { |
| 4876 | if (ComputeFirstCharacterSet(kFirstCharBudget) < 0) { |
| 4877 | // If we can't find an exact solution within the budget, we |
| 4878 | // set the value to the set of every character, i.e., all characters |
| 4879 | // are possible. |
| 4880 | ZoneList<CharacterRange>* all_set = new ZoneList<CharacterRange>(1); |
| 4881 | all_set->Add(CharacterRange::Everything()); |
| 4882 | first_character_set_ = all_set; |
| 4883 | } |
| 4884 | } |
| 4885 | return first_character_set_; |
| 4886 | } |
| 4887 | |
| 4888 | |
| 4889 | int RegExpNode::ComputeFirstCharacterSet(int budget) { |
| 4890 | // Default behavior is to not be able to determine the first character. |
| 4891 | return kComputeFirstCharacterSetFail; |
| 4892 | } |
| 4893 | |
| 4894 | |
| 4895 | int LoopChoiceNode::ComputeFirstCharacterSet(int budget) { |
| 4896 | budget--; |
| 4897 | if (budget >= 0) { |
| 4898 | // Find loop min-iteration. It's the value of the guarded choice node |
| 4899 | // with a GEQ guard, if any. |
| 4900 | int min_repetition = 0; |
| 4901 | |
| 4902 | for (int i = 0; i <= 1; i++) { |
| 4903 | GuardedAlternative alternative = alternatives()->at(i); |
| 4904 | ZoneList<Guard*>* guards = alternative.guards(); |
| 4905 | if (guards != NULL && guards->length() > 0) { |
| 4906 | Guard* guard = guards->at(0); |
| 4907 | if (guard->op() == Guard::GEQ) { |
| 4908 | min_repetition = guard->value(); |
| 4909 | break; |
| 4910 | } |
| 4911 | } |
| 4912 | } |
| 4913 | |
| 4914 | budget = loop_node()->ComputeFirstCharacterSet(budget); |
| 4915 | if (budget >= 0) { |
| 4916 | ZoneList<CharacterRange>* character_set = |
| 4917 | loop_node()->first_character_set(); |
| 4918 | if (body_can_be_zero_length() || min_repetition == 0) { |
| 4919 | budget = continue_node()->ComputeFirstCharacterSet(budget); |
| 4920 | if (budget < 0) return budget; |
| 4921 | ZoneList<CharacterRange>* body_set = |
| 4922 | continue_node()->first_character_set(); |
| 4923 | ZoneList<CharacterRange>* union_set = |
| 4924 | new ZoneList<CharacterRange>(Max(character_set->length(), |
| 4925 | body_set->length())); |
| 4926 | CharacterRange::Merge(character_set, |
| 4927 | body_set, |
| 4928 | union_set, |
| 4929 | union_set, |
| 4930 | union_set); |
| 4931 | character_set = union_set; |
| 4932 | } |
| 4933 | set_first_character_set(character_set); |
| 4934 | } |
| 4935 | } |
| 4936 | return budget; |
| 4937 | } |
| 4938 | |
| 4939 | |
| 4940 | int NegativeLookaheadChoiceNode::ComputeFirstCharacterSet(int budget) { |
| 4941 | budget--; |
| 4942 | if (budget >= 0) { |
| 4943 | GuardedAlternative successor = this->alternatives()->at(1); |
| 4944 | RegExpNode* successor_node = successor.node(); |
| 4945 | budget = successor_node->ComputeFirstCharacterSet(budget); |
| 4946 | if (budget >= 0) { |
| 4947 | set_first_character_set(successor_node->first_character_set()); |
| 4948 | } |
| 4949 | } |
| 4950 | return budget; |
| 4951 | } |
| 4952 | |
| 4953 | |
| 4954 | // The first character set of an EndNode is unknowable. Just use the |
| 4955 | // default implementation that fails and returns all characters as possible. |
| 4956 | |
| 4957 | |
| 4958 | int AssertionNode::ComputeFirstCharacterSet(int budget) { |
| 4959 | budget -= 1; |
| 4960 | if (budget >= 0) { |
| 4961 | switch (type_) { |
| 4962 | case AT_END: { |
| 4963 | set_first_character_set(new ZoneList<CharacterRange>(0)); |
| 4964 | break; |
| 4965 | } |
| 4966 | case AT_START: |
| 4967 | case AT_BOUNDARY: |
| 4968 | case AT_NON_BOUNDARY: |
| 4969 | case AFTER_NEWLINE: |
| 4970 | case AFTER_NONWORD_CHARACTER: |
| 4971 | case AFTER_WORD_CHARACTER: { |
| 4972 | ASSERT_NOT_NULL(on_success()); |
| 4973 | budget = on_success()->ComputeFirstCharacterSet(budget); |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 4974 | if (budget >= 0) { |
| 4975 | set_first_character_set(on_success()->first_character_set()); |
| 4976 | } |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 4977 | break; |
| 4978 | } |
| 4979 | } |
| 4980 | } |
| 4981 | return budget; |
| 4982 | } |
| 4983 | |
| 4984 | |
| 4985 | int ActionNode::ComputeFirstCharacterSet(int budget) { |
| 4986 | if (type_ == POSITIVE_SUBMATCH_SUCCESS) return kComputeFirstCharacterSetFail; |
| 4987 | budget--; |
| 4988 | if (budget >= 0) { |
| 4989 | ASSERT_NOT_NULL(on_success()); |
| 4990 | budget = on_success()->ComputeFirstCharacterSet(budget); |
| 4991 | if (budget >= 0) { |
| 4992 | set_first_character_set(on_success()->first_character_set()); |
| 4993 | } |
| 4994 | } |
| 4995 | return budget; |
| 4996 | } |
| 4997 | |
| 4998 | |
| 4999 | int BackReferenceNode::ComputeFirstCharacterSet(int budget) { |
| 5000 | // We don't know anything about the first character of a backreference |
| 5001 | // at this point. |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 5002 | // The potential first characters are the first characters of the capture, |
| 5003 | // and the first characters of the on_success node, depending on whether the |
| 5004 | // capture can be empty and whether it is known to be participating or known |
| 5005 | // not to be. |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 5006 | return kComputeFirstCharacterSetFail; |
| 5007 | } |
| 5008 | |
| 5009 | |
| 5010 | int TextNode::ComputeFirstCharacterSet(int budget) { |
| 5011 | budget--; |
| 5012 | if (budget >= 0) { |
| 5013 | ASSERT_NE(0, elements()->length()); |
| 5014 | TextElement text = elements()->at(0); |
| 5015 | if (text.type == TextElement::ATOM) { |
| 5016 | RegExpAtom* atom = text.data.u_atom; |
| 5017 | ASSERT_NE(0, atom->length()); |
| 5018 | uc16 first_char = atom->data()[0]; |
| 5019 | ZoneList<CharacterRange>* range = new ZoneList<CharacterRange>(1); |
| 5020 | range->Add(CharacterRange(first_char, first_char)); |
| 5021 | set_first_character_set(range); |
| 5022 | } else { |
| 5023 | ASSERT(text.type == TextElement::CHAR_CLASS); |
| 5024 | RegExpCharacterClass* char_class = text.data.u_char_class; |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 5025 | ZoneList<CharacterRange>* ranges = char_class->ranges(); |
| 5026 | // TODO(lrn): Canonicalize ranges when they are created |
| 5027 | // instead of waiting until now. |
| 5028 | CharacterRange::Canonicalize(ranges); |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 5029 | if (char_class->is_negated()) { |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 5030 | int length = ranges->length(); |
| 5031 | int new_length = length + 1; |
| 5032 | if (length > 0) { |
| 5033 | if (ranges->at(0).from() == 0) new_length--; |
| 5034 | if (ranges->at(length - 1).to() == String::kMaxUC16CharCode) { |
| 5035 | new_length--; |
| 5036 | } |
| 5037 | } |
| 5038 | ZoneList<CharacterRange>* negated_ranges = |
| 5039 | new ZoneList<CharacterRange>(new_length); |
| 5040 | CharacterRange::Negate(ranges, negated_ranges); |
| 5041 | set_first_character_set(negated_ranges); |
| 5042 | } else { |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 5043 | set_first_character_set(ranges); |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 5044 | } |
| 5045 | } |
| 5046 | } |
| 5047 | return budget; |
| 5048 | } |
| 5049 | |
| 5050 | |
| 5051 | |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 5052 | // ------------------------------------------------------------------- |
| 5053 | // Dispatch table construction |
| 5054 | |
| 5055 | |
| 5056 | void DispatchTableConstructor::VisitEnd(EndNode* that) { |
| 5057 | AddRange(CharacterRange::Everything()); |
| 5058 | } |
| 5059 | |
| 5060 | |
| 5061 | void DispatchTableConstructor::BuildTable(ChoiceNode* node) { |
| 5062 | node->set_being_calculated(true); |
| 5063 | ZoneList<GuardedAlternative>* alternatives = node->alternatives(); |
| 5064 | for (int i = 0; i < alternatives->length(); i++) { |
| 5065 | set_choice_index(i); |
| 5066 | alternatives->at(i).node()->Accept(this); |
| 5067 | } |
| 5068 | node->set_being_calculated(false); |
| 5069 | } |
| 5070 | |
| 5071 | |
| 5072 | class AddDispatchRange { |
| 5073 | public: |
| 5074 | explicit AddDispatchRange(DispatchTableConstructor* constructor) |
| 5075 | : constructor_(constructor) { } |
| 5076 | void Call(uc32 from, DispatchTable::Entry entry); |
| 5077 | private: |
| 5078 | DispatchTableConstructor* constructor_; |
| 5079 | }; |
| 5080 | |
| 5081 | |
| 5082 | void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) { |
| 5083 | CharacterRange range(from, entry.to()); |
| 5084 | constructor_->AddRange(range); |
| 5085 | } |
| 5086 | |
| 5087 | |
| 5088 | void DispatchTableConstructor::VisitChoice(ChoiceNode* node) { |
| 5089 | if (node->being_calculated()) |
| 5090 | return; |
| 5091 | DispatchTable* table = node->GetTable(ignore_case_); |
| 5092 | AddDispatchRange adder(this); |
| 5093 | table->ForEach(&adder); |
| 5094 | } |
| 5095 | |
| 5096 | |
| 5097 | void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) { |
| 5098 | // TODO(160): Find the node that we refer back to and propagate its start |
| 5099 | // set back to here. For now we just accept anything. |
| 5100 | AddRange(CharacterRange::Everything()); |
| 5101 | } |
| 5102 | |
| 5103 | |
| 5104 | void DispatchTableConstructor::VisitAssertion(AssertionNode* that) { |
| 5105 | RegExpNode* target = that->on_success(); |
| 5106 | target->Accept(this); |
| 5107 | } |
| 5108 | |
| 5109 | |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 5110 | static int CompareRangeByFrom(const CharacterRange* a, |
| 5111 | const CharacterRange* b) { |
| 5112 | return Compare<uc16>(a->from(), b->from()); |
| 5113 | } |
| 5114 | |
| 5115 | |
| 5116 | void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) { |
| 5117 | ranges->Sort(CompareRangeByFrom); |
| 5118 | uc16 last = 0; |
| 5119 | for (int i = 0; i < ranges->length(); i++) { |
| 5120 | CharacterRange range = ranges->at(i); |
| 5121 | if (last < range.from()) |
| 5122 | AddRange(CharacterRange(last, range.from() - 1)); |
| 5123 | if (range.to() >= last) { |
| 5124 | if (range.to() == String::kMaxUC16CharCode) { |
| 5125 | return; |
| 5126 | } else { |
| 5127 | last = range.to() + 1; |
| 5128 | } |
| 5129 | } |
| 5130 | } |
| 5131 | AddRange(CharacterRange(last, String::kMaxUC16CharCode)); |
| 5132 | } |
| 5133 | |
| 5134 | |
| 5135 | void DispatchTableConstructor::VisitText(TextNode* that) { |
| 5136 | TextElement elm = that->elements()->at(0); |
| 5137 | switch (elm.type) { |
| 5138 | case TextElement::ATOM: { |
| 5139 | uc16 c = elm.data.u_atom->data()[0]; |
| 5140 | AddRange(CharacterRange(c, c)); |
| 5141 | break; |
| 5142 | } |
| 5143 | case TextElement::CHAR_CLASS: { |
| 5144 | RegExpCharacterClass* tree = elm.data.u_char_class; |
| 5145 | ZoneList<CharacterRange>* ranges = tree->ranges(); |
| 5146 | if (tree->is_negated()) { |
| 5147 | AddInverse(ranges); |
| 5148 | } else { |
| 5149 | for (int i = 0; i < ranges->length(); i++) |
| 5150 | AddRange(ranges->at(i)); |
| 5151 | } |
| 5152 | break; |
| 5153 | } |
| 5154 | default: { |
| 5155 | UNIMPLEMENTED(); |
| 5156 | } |
| 5157 | } |
| 5158 | } |
| 5159 | |
| 5160 | |
| 5161 | void DispatchTableConstructor::VisitAction(ActionNode* that) { |
| 5162 | RegExpNode* target = that->on_success(); |
| 5163 | target->Accept(this); |
| 5164 | } |
| 5165 | |
| 5166 | |
| 5167 | RegExpEngine::CompilationResult RegExpEngine::Compile(RegExpCompileData* data, |
| 5168 | bool ignore_case, |
| 5169 | bool is_multiline, |
| 5170 | Handle<String> pattern, |
| 5171 | bool is_ascii) { |
| 5172 | if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) { |
| 5173 | return IrregexpRegExpTooBig(); |
| 5174 | } |
| 5175 | RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii); |
| 5176 | // Wrap the body of the regexp in capture #0. |
| 5177 | RegExpNode* captured_body = RegExpCapture::ToNode(data->tree, |
| 5178 | 0, |
| 5179 | &compiler, |
| 5180 | compiler.accept()); |
| 5181 | RegExpNode* node = captured_body; |
| 5182 | if (!data->tree->IsAnchored()) { |
| 5183 | // Add a .*? at the beginning, outside the body capture, unless |
| 5184 | // this expression is anchored at the beginning. |
| 5185 | RegExpNode* loop_node = |
| 5186 | RegExpQuantifier::ToNode(0, |
| 5187 | RegExpTree::kInfinity, |
| 5188 | false, |
| 5189 | new RegExpCharacterClass('*'), |
| 5190 | &compiler, |
| 5191 | captured_body, |
| 5192 | data->contains_anchor); |
| 5193 | |
| 5194 | if (data->contains_anchor) { |
| 5195 | // Unroll loop once, to take care of the case that might start |
| 5196 | // at the start of input. |
| 5197 | ChoiceNode* first_step_node = new ChoiceNode(2); |
| 5198 | first_step_node->AddAlternative(GuardedAlternative(captured_body)); |
| 5199 | first_step_node->AddAlternative(GuardedAlternative( |
| 5200 | new TextNode(new RegExpCharacterClass('*'), loop_node))); |
| 5201 | node = first_step_node; |
| 5202 | } else { |
| 5203 | node = loop_node; |
| 5204 | } |
| 5205 | } |
| 5206 | data->node = node; |
Steve Block | d0582a6 | 2009-12-15 09:54:21 +0000 | [diff] [blame] | 5207 | Analysis analysis(ignore_case, is_ascii); |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 5208 | analysis.EnsureAnalyzed(node); |
| 5209 | if (analysis.has_failed()) { |
| 5210 | const char* error_message = analysis.error_message(); |
| 5211 | return CompilationResult(error_message); |
| 5212 | } |
| 5213 | |
| 5214 | NodeInfo info = *node->info(); |
| 5215 | |
| 5216 | // Create the correct assembler for the architecture. |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 5217 | #ifndef V8_INTERPRETED_REGEXP |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 5218 | // Native regexp implementation. |
| 5219 | |
| 5220 | NativeRegExpMacroAssembler::Mode mode = |
| 5221 | is_ascii ? NativeRegExpMacroAssembler::ASCII |
| 5222 | : NativeRegExpMacroAssembler::UC16; |
| 5223 | |
| 5224 | #if V8_TARGET_ARCH_IA32 |
| 5225 | RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2); |
| 5226 | #elif V8_TARGET_ARCH_X64 |
| 5227 | RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2); |
| 5228 | #elif V8_TARGET_ARCH_ARM |
| 5229 | RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2); |
| 5230 | #endif |
| 5231 | |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 5232 | #else // V8_INTERPRETED_REGEXP |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 5233 | // Interpreted regexp implementation. |
| 5234 | EmbeddedVector<byte, 1024> codes; |
| 5235 | RegExpMacroAssemblerIrregexp macro_assembler(codes); |
Steve Block | 6ded16b | 2010-05-10 14:33:55 +0100 | [diff] [blame] | 5236 | #endif // V8_INTERPRETED_REGEXP |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 5237 | |
| 5238 | return compiler.Assemble(¯o_assembler, |
| 5239 | node, |
| 5240 | data->capture_count, |
| 5241 | pattern); |
| 5242 | } |
| 5243 | |
Leon Clarke | e46be81 | 2010-01-19 14:06:41 +0000 | [diff] [blame] | 5244 | |
| 5245 | int OffsetsVector::static_offsets_vector_[ |
| 5246 | OffsetsVector::kStaticOffsetsVectorSize]; |
| 5247 | |
Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame] | 5248 | }} // namespace v8::internal |