blob: e7026d42e49c062663d87944f7237ff07cdee1e7 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2008 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
29#include <stdlib.h>
30
31#include "v8.h"
32
33#include "string-stream.h"
34#include "cctest.h"
35#include "zone-inl.h"
36#include "parser.h"
37#include "ast.h"
38#include "jsregexp.h"
39#include "regexp-macro-assembler.h"
40#include "regexp-macro-assembler-irregexp.h"
Steve Block6ded16b2010-05-10 14:33:55 +010041#ifdef V8_INTERPRETED_REGEXP
42#include "interpreter-irregexp.h"
43#else // V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +000044#ifdef V8_TARGET_ARCH_ARM
45#include "arm/macro-assembler-arm.h"
46#include "arm/regexp-macro-assembler-arm.h"
47#endif
Steve Block44f0eee2011-05-26 01:26:41 +010048#ifdef V8_TARGET_ARCH_MIPS
49#include "mips/macro-assembler-mips.h"
50#include "mips/regexp-macro-assembler-mips.h"
51#endif
Steve Blocka7e24c12009-10-30 11:49:00 +000052#ifdef V8_TARGET_ARCH_X64
53#include "x64/macro-assembler-x64.h"
54#include "x64/regexp-macro-assembler-x64.h"
55#endif
56#ifdef V8_TARGET_ARCH_IA32
57#include "ia32/macro-assembler-ia32.h"
58#include "ia32/regexp-macro-assembler-ia32.h"
59#endif
Steve Block6ded16b2010-05-10 14:33:55 +010060#endif // V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +000061
62using namespace v8::internal;
63
64
Leon Clarkee46be812010-01-19 14:06:41 +000065static bool CheckParse(const char* input) {
66 V8::Initialize(NULL);
67 v8::HandleScope scope;
68 ZoneScope zone_scope(DELETE_ON_EXIT);
Steve Block44f0eee2011-05-26 01:26:41 +010069 FlatStringReader reader(Isolate::Current(), CStrVector(input));
Leon Clarkee46be812010-01-19 14:06:41 +000070 RegExpCompileData result;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080071 return v8::internal::RegExpParser::ParseRegExp(&reader, false, &result);
Leon Clarkee46be812010-01-19 14:06:41 +000072}
73
74
Steve Blocka7e24c12009-10-30 11:49:00 +000075static SmartPointer<const char> Parse(const char* input) {
76 V8::Initialize(NULL);
77 v8::HandleScope scope;
78 ZoneScope zone_scope(DELETE_ON_EXIT);
Steve Block44f0eee2011-05-26 01:26:41 +010079 FlatStringReader reader(Isolate::Current(), CStrVector(input));
Steve Blocka7e24c12009-10-30 11:49:00 +000080 RegExpCompileData result;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080081 CHECK(v8::internal::RegExpParser::ParseRegExp(&reader, false, &result));
Steve Blocka7e24c12009-10-30 11:49:00 +000082 CHECK(result.tree != NULL);
83 CHECK(result.error.is_null());
84 SmartPointer<const char> output = result.tree->ToString();
85 return output;
86}
87
88static bool CheckSimple(const char* input) {
89 V8::Initialize(NULL);
90 v8::HandleScope scope;
Steve Blockd0582a62009-12-15 09:54:21 +000091 unibrow::Utf8InputBuffer<> buffer(input, StrLength(input));
Steve Blocka7e24c12009-10-30 11:49:00 +000092 ZoneScope zone_scope(DELETE_ON_EXIT);
Steve Block44f0eee2011-05-26 01:26:41 +010093 FlatStringReader reader(Isolate::Current(), CStrVector(input));
Steve Blocka7e24c12009-10-30 11:49:00 +000094 RegExpCompileData result;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080095 CHECK(v8::internal::RegExpParser::ParseRegExp(&reader, false, &result));
Steve Blocka7e24c12009-10-30 11:49:00 +000096 CHECK(result.tree != NULL);
97 CHECK(result.error.is_null());
98 return result.simple;
99}
100
101struct MinMaxPair {
102 int min_match;
103 int max_match;
104};
105
106static MinMaxPair CheckMinMaxMatch(const char* input) {
107 V8::Initialize(NULL);
108 v8::HandleScope scope;
Steve Blockd0582a62009-12-15 09:54:21 +0000109 unibrow::Utf8InputBuffer<> buffer(input, StrLength(input));
Steve Blocka7e24c12009-10-30 11:49:00 +0000110 ZoneScope zone_scope(DELETE_ON_EXIT);
Steve Block44f0eee2011-05-26 01:26:41 +0100111 FlatStringReader reader(Isolate::Current(), CStrVector(input));
Steve Blocka7e24c12009-10-30 11:49:00 +0000112 RegExpCompileData result;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800113 CHECK(v8::internal::RegExpParser::ParseRegExp(&reader, false, &result));
Steve Blocka7e24c12009-10-30 11:49:00 +0000114 CHECK(result.tree != NULL);
115 CHECK(result.error.is_null());
116 int min_match = result.tree->min_match();
117 int max_match = result.tree->max_match();
118 MinMaxPair pair = { min_match, max_match };
119 return pair;
120}
121
122
Leon Clarkee46be812010-01-19 14:06:41 +0000123#define CHECK_PARSE_ERROR(input) CHECK(!CheckParse(input))
Steve Blocka7e24c12009-10-30 11:49:00 +0000124#define CHECK_PARSE_EQ(input, expected) CHECK_EQ(expected, *Parse(input))
125#define CHECK_SIMPLE(input, simple) CHECK_EQ(simple, CheckSimple(input));
126#define CHECK_MIN_MAX(input, min, max) \
127 { MinMaxPair min_max = CheckMinMaxMatch(input); \
128 CHECK_EQ(min, min_max.min_match); \
129 CHECK_EQ(max, min_max.max_match); \
130 }
131
132TEST(Parser) {
133 V8::Initialize(NULL);
Leon Clarkee46be812010-01-19 14:06:41 +0000134
135 CHECK_PARSE_ERROR("?");
136
Steve Blocka7e24c12009-10-30 11:49:00 +0000137 CHECK_PARSE_EQ("abc", "'abc'");
138 CHECK_PARSE_EQ("", "%");
139 CHECK_PARSE_EQ("abc|def", "(| 'abc' 'def')");
140 CHECK_PARSE_EQ("abc|def|ghi", "(| 'abc' 'def' 'ghi')");
141 CHECK_PARSE_EQ("^xxx$", "(: @^i 'xxx' @$i)");
142 CHECK_PARSE_EQ("ab\\b\\d\\bcd", "(: 'ab' @b [0-9] @b 'cd')");
143 CHECK_PARSE_EQ("\\w|\\d", "(| [0-9 A-Z _ a-z] [0-9])");
144 CHECK_PARSE_EQ("a*", "(# 0 - g 'a')");
145 CHECK_PARSE_EQ("a*?", "(# 0 - n 'a')");
146 CHECK_PARSE_EQ("abc+", "(: 'ab' (# 1 - g 'c'))");
147 CHECK_PARSE_EQ("abc+?", "(: 'ab' (# 1 - n 'c'))");
148 CHECK_PARSE_EQ("xyz?", "(: 'xy' (# 0 1 g 'z'))");
149 CHECK_PARSE_EQ("xyz??", "(: 'xy' (# 0 1 n 'z'))");
150 CHECK_PARSE_EQ("xyz{0,1}", "(: 'xy' (# 0 1 g 'z'))");
151 CHECK_PARSE_EQ("xyz{0,1}?", "(: 'xy' (# 0 1 n 'z'))");
152 CHECK_PARSE_EQ("xyz{93}", "(: 'xy' (# 93 93 g 'z'))");
153 CHECK_PARSE_EQ("xyz{93}?", "(: 'xy' (# 93 93 n 'z'))");
154 CHECK_PARSE_EQ("xyz{1,32}", "(: 'xy' (# 1 32 g 'z'))");
155 CHECK_PARSE_EQ("xyz{1,32}?", "(: 'xy' (# 1 32 n 'z'))");
156 CHECK_PARSE_EQ("xyz{1,}", "(: 'xy' (# 1 - g 'z'))");
157 CHECK_PARSE_EQ("xyz{1,}?", "(: 'xy' (# 1 - n 'z'))");
158 CHECK_PARSE_EQ("a\\fb\\nc\\rd\\te\\vf", "'a\\x0cb\\x0ac\\x0dd\\x09e\\x0bf'");
159 CHECK_PARSE_EQ("a\\nb\\bc", "(: 'a\\x0ab' @b 'c')");
160 CHECK_PARSE_EQ("(?:foo)", "'foo'");
161 CHECK_PARSE_EQ("(?: foo )", "' foo '");
162 CHECK_PARSE_EQ("(foo|bar|baz)", "(^ (| 'foo' 'bar' 'baz'))");
163 CHECK_PARSE_EQ("foo|(bar|baz)|quux", "(| 'foo' (^ (| 'bar' 'baz')) 'quux')");
164 CHECK_PARSE_EQ("foo(?=bar)baz", "(: 'foo' (-> + 'bar') 'baz')");
165 CHECK_PARSE_EQ("foo(?!bar)baz", "(: 'foo' (-> - 'bar') 'baz')");
166 CHECK_PARSE_EQ("()", "(^ %)");
167 CHECK_PARSE_EQ("(?=)", "(-> + %)");
168 CHECK_PARSE_EQ("[]", "^[\\x00-\\uffff]"); // Doesn't compile on windows
169 CHECK_PARSE_EQ("[^]", "[\\x00-\\uffff]"); // \uffff isn't in codepage 1252
170 CHECK_PARSE_EQ("[x]", "[x]");
171 CHECK_PARSE_EQ("[xyz]", "[x y z]");
172 CHECK_PARSE_EQ("[a-zA-Z0-9]", "[a-z A-Z 0-9]");
173 CHECK_PARSE_EQ("[-123]", "[- 1 2 3]");
174 CHECK_PARSE_EQ("[^123]", "^[1 2 3]");
175 CHECK_PARSE_EQ("]", "']'");
176 CHECK_PARSE_EQ("}", "'}'");
177 CHECK_PARSE_EQ("[a-b-c]", "[a-b - c]");
178 CHECK_PARSE_EQ("[\\d]", "[0-9]");
179 CHECK_PARSE_EQ("[x\\dz]", "[x 0-9 z]");
180 CHECK_PARSE_EQ("[\\d-z]", "[0-9 - z]");
181 CHECK_PARSE_EQ("[\\d-\\d]", "[0-9 - 0-9]");
182 CHECK_PARSE_EQ("[z-\\d]", "[z - 0-9]");
Ben Murdoch086aeea2011-05-13 15:57:08 +0100183 // Control character outside character class.
Steve Blocka7e24c12009-10-30 11:49:00 +0000184 CHECK_PARSE_EQ("\\cj\\cJ\\ci\\cI\\ck\\cK",
185 "'\\x0a\\x0a\\x09\\x09\\x0b\\x0b'");
Ben Murdoch086aeea2011-05-13 15:57:08 +0100186 CHECK_PARSE_EQ("\\c!", "'\\c!'");
187 CHECK_PARSE_EQ("\\c_", "'\\c_'");
188 CHECK_PARSE_EQ("\\c~", "'\\c~'");
189 CHECK_PARSE_EQ("\\c1", "'\\c1'");
190 // Control character inside character class.
191 CHECK_PARSE_EQ("[\\c!]", "[\\ c !]");
192 CHECK_PARSE_EQ("[\\c_]", "[\\x1f]");
193 CHECK_PARSE_EQ("[\\c~]", "[\\ c ~]");
194 CHECK_PARSE_EQ("[\\ca]", "[\\x01]");
195 CHECK_PARSE_EQ("[\\cz]", "[\\x1a]");
196 CHECK_PARSE_EQ("[\\cA]", "[\\x01]");
197 CHECK_PARSE_EQ("[\\cZ]", "[\\x1a]");
198 CHECK_PARSE_EQ("[\\c1]", "[\\x11]");
199
Steve Blocka7e24c12009-10-30 11:49:00 +0000200 CHECK_PARSE_EQ("[a\\]c]", "[a ] c]");
201 CHECK_PARSE_EQ("\\[\\]\\{\\}\\(\\)\\%\\^\\#\\ ", "'[]{}()%^# '");
202 CHECK_PARSE_EQ("[\\[\\]\\{\\}\\(\\)\\%\\^\\#\\ ]", "[[ ] { } ( ) % ^ # ]");
203 CHECK_PARSE_EQ("\\0", "'\\x00'");
204 CHECK_PARSE_EQ("\\8", "'8'");
205 CHECK_PARSE_EQ("\\9", "'9'");
206 CHECK_PARSE_EQ("\\11", "'\\x09'");
207 CHECK_PARSE_EQ("\\11a", "'\\x09a'");
208 CHECK_PARSE_EQ("\\011", "'\\x09'");
209 CHECK_PARSE_EQ("\\00011", "'\\x0011'");
210 CHECK_PARSE_EQ("\\118", "'\\x098'");
211 CHECK_PARSE_EQ("\\111", "'I'");
212 CHECK_PARSE_EQ("\\1111", "'I1'");
213 CHECK_PARSE_EQ("(x)(x)(x)\\1", "(: (^ 'x') (^ 'x') (^ 'x') (<- 1))");
214 CHECK_PARSE_EQ("(x)(x)(x)\\2", "(: (^ 'x') (^ 'x') (^ 'x') (<- 2))");
215 CHECK_PARSE_EQ("(x)(x)(x)\\3", "(: (^ 'x') (^ 'x') (^ 'x') (<- 3))");
216 CHECK_PARSE_EQ("(x)(x)(x)\\4", "(: (^ 'x') (^ 'x') (^ 'x') '\\x04')");
217 CHECK_PARSE_EQ("(x)(x)(x)\\1*", "(: (^ 'x') (^ 'x') (^ 'x')"
218 " (# 0 - g (<- 1)))");
219 CHECK_PARSE_EQ("(x)(x)(x)\\2*", "(: (^ 'x') (^ 'x') (^ 'x')"
220 " (# 0 - g (<- 2)))");
221 CHECK_PARSE_EQ("(x)(x)(x)\\3*", "(: (^ 'x') (^ 'x') (^ 'x')"
222 " (# 0 - g (<- 3)))");
223 CHECK_PARSE_EQ("(x)(x)(x)\\4*", "(: (^ 'x') (^ 'x') (^ 'x')"
224 " (# 0 - g '\\x04'))");
225 CHECK_PARSE_EQ("(x)(x)(x)(x)(x)(x)(x)(x)(x)(x)\\10",
226 "(: (^ 'x') (^ 'x') (^ 'x') (^ 'x') (^ 'x') (^ 'x')"
227 " (^ 'x') (^ 'x') (^ 'x') (^ 'x') (<- 10))");
228 CHECK_PARSE_EQ("(x)(x)(x)(x)(x)(x)(x)(x)(x)(x)\\11",
229 "(: (^ 'x') (^ 'x') (^ 'x') (^ 'x') (^ 'x') (^ 'x')"
230 " (^ 'x') (^ 'x') (^ 'x') (^ 'x') '\\x09')");
231 CHECK_PARSE_EQ("(a)\\1", "(: (^ 'a') (<- 1))");
232 CHECK_PARSE_EQ("(a\\1)", "(^ 'a')");
233 CHECK_PARSE_EQ("(\\1a)", "(^ 'a')");
234 CHECK_PARSE_EQ("(?=a)?a", "'a'");
235 CHECK_PARSE_EQ("(?=a){0,10}a", "'a'");
236 CHECK_PARSE_EQ("(?=a){1,10}a", "(: (-> + 'a') 'a')");
237 CHECK_PARSE_EQ("(?=a){9,10}a", "(: (-> + 'a') 'a')");
238 CHECK_PARSE_EQ("(?!a)?a", "'a'");
239 CHECK_PARSE_EQ("\\1(a)", "(^ 'a')");
240 CHECK_PARSE_EQ("(?!(a))\\1", "(: (-> - (^ 'a')) (<- 1))");
241 CHECK_PARSE_EQ("(?!\\1(a\\1)\\1)\\1", "(: (-> - (: (^ 'a') (<- 1))) (<- 1))");
242 CHECK_PARSE_EQ("[\\0]", "[\\x00]");
243 CHECK_PARSE_EQ("[\\11]", "[\\x09]");
244 CHECK_PARSE_EQ("[\\11a]", "[\\x09 a]");
245 CHECK_PARSE_EQ("[\\011]", "[\\x09]");
246 CHECK_PARSE_EQ("[\\00011]", "[\\x00 1 1]");
247 CHECK_PARSE_EQ("[\\118]", "[\\x09 8]");
248 CHECK_PARSE_EQ("[\\111]", "[I]");
249 CHECK_PARSE_EQ("[\\1111]", "[I 1]");
250 CHECK_PARSE_EQ("\\x34", "'\x34'");
251 CHECK_PARSE_EQ("\\x60", "'\x60'");
252 CHECK_PARSE_EQ("\\x3z", "'x3z'");
Ben Murdoch086aeea2011-05-13 15:57:08 +0100253 CHECK_PARSE_EQ("\\c", "'\\c'");
Steve Blocka7e24c12009-10-30 11:49:00 +0000254 CHECK_PARSE_EQ("\\u0034", "'\x34'");
255 CHECK_PARSE_EQ("\\u003z", "'u003z'");
256 CHECK_PARSE_EQ("foo[z]*", "(: 'foo' (# 0 - g [z]))");
257
258 CHECK_SIMPLE("a", true);
259 CHECK_SIMPLE("a|b", false);
260 CHECK_SIMPLE("a\\n", false);
261 CHECK_SIMPLE("^a", false);
262 CHECK_SIMPLE("a$", false);
263 CHECK_SIMPLE("a\\b!", false);
264 CHECK_SIMPLE("a\\Bb", false);
265 CHECK_SIMPLE("a*", false);
266 CHECK_SIMPLE("a*?", false);
267 CHECK_SIMPLE("a?", false);
268 CHECK_SIMPLE("a??", false);
269 CHECK_SIMPLE("a{0,1}?", false);
270 CHECK_SIMPLE("a{1,1}?", false);
271 CHECK_SIMPLE("a{1,2}?", false);
272 CHECK_SIMPLE("a+?", false);
273 CHECK_SIMPLE("(a)", false);
274 CHECK_SIMPLE("(a)\\1", false);
275 CHECK_SIMPLE("(\\1a)", false);
276 CHECK_SIMPLE("\\1(a)", false);
277 CHECK_SIMPLE("a\\s", false);
278 CHECK_SIMPLE("a\\S", false);
279 CHECK_SIMPLE("a\\d", false);
280 CHECK_SIMPLE("a\\D", false);
281 CHECK_SIMPLE("a\\w", false);
282 CHECK_SIMPLE("a\\W", false);
283 CHECK_SIMPLE("a.", false);
284 CHECK_SIMPLE("a\\q", false);
285 CHECK_SIMPLE("a[a]", false);
286 CHECK_SIMPLE("a[^a]", false);
287 CHECK_SIMPLE("a[a-z]", false);
288 CHECK_SIMPLE("a[\\q]", false);
289 CHECK_SIMPLE("a(?:b)", false);
290 CHECK_SIMPLE("a(?=b)", false);
291 CHECK_SIMPLE("a(?!b)", false);
292 CHECK_SIMPLE("\\x60", false);
293 CHECK_SIMPLE("\\u0060", false);
294 CHECK_SIMPLE("\\cA", false);
295 CHECK_SIMPLE("\\q", false);
296 CHECK_SIMPLE("\\1112", false);
297 CHECK_SIMPLE("\\0", false);
298 CHECK_SIMPLE("(a)\\1", false);
299 CHECK_SIMPLE("(?=a)?a", false);
300 CHECK_SIMPLE("(?!a)?a\\1", false);
301 CHECK_SIMPLE("(?:(?=a))a\\1", false);
302
303 CHECK_PARSE_EQ("a{}", "'a{}'");
304 CHECK_PARSE_EQ("a{,}", "'a{,}'");
305 CHECK_PARSE_EQ("a{", "'a{'");
306 CHECK_PARSE_EQ("a{z}", "'a{z}'");
307 CHECK_PARSE_EQ("a{1z}", "'a{1z}'");
308 CHECK_PARSE_EQ("a{12z}", "'a{12z}'");
309 CHECK_PARSE_EQ("a{12,", "'a{12,'");
310 CHECK_PARSE_EQ("a{12,3b", "'a{12,3b'");
311 CHECK_PARSE_EQ("{}", "'{}'");
312 CHECK_PARSE_EQ("{,}", "'{,}'");
313 CHECK_PARSE_EQ("{", "'{'");
314 CHECK_PARSE_EQ("{z}", "'{z}'");
315 CHECK_PARSE_EQ("{1z}", "'{1z}'");
316 CHECK_PARSE_EQ("{12z}", "'{12z}'");
317 CHECK_PARSE_EQ("{12,", "'{12,'");
318 CHECK_PARSE_EQ("{12,3b", "'{12,3b'");
319
320 CHECK_MIN_MAX("a", 1, 1);
321 CHECK_MIN_MAX("abc", 3, 3);
322 CHECK_MIN_MAX("a[bc]d", 3, 3);
323 CHECK_MIN_MAX("a|bc", 1, 2);
324 CHECK_MIN_MAX("ab|c", 1, 2);
325 CHECK_MIN_MAX("a||bc", 0, 2);
326 CHECK_MIN_MAX("|", 0, 0);
327 CHECK_MIN_MAX("(?:ab)", 2, 2);
328 CHECK_MIN_MAX("(?:ab|cde)", 2, 3);
329 CHECK_MIN_MAX("(?:ab)|cde", 2, 3);
330 CHECK_MIN_MAX("(ab)", 2, 2);
331 CHECK_MIN_MAX("(ab|cde)", 2, 3);
332 CHECK_MIN_MAX("(ab)\\1", 2, 4);
333 CHECK_MIN_MAX("(ab|cde)\\1", 2, 6);
334 CHECK_MIN_MAX("(?:ab)?", 0, 2);
335 CHECK_MIN_MAX("(?:ab)*", 0, RegExpTree::kInfinity);
336 CHECK_MIN_MAX("(?:ab)+", 2, RegExpTree::kInfinity);
337 CHECK_MIN_MAX("a?", 0, 1);
338 CHECK_MIN_MAX("a*", 0, RegExpTree::kInfinity);
339 CHECK_MIN_MAX("a+", 1, RegExpTree::kInfinity);
340 CHECK_MIN_MAX("a??", 0, 1);
341 CHECK_MIN_MAX("a*?", 0, RegExpTree::kInfinity);
342 CHECK_MIN_MAX("a+?", 1, RegExpTree::kInfinity);
343 CHECK_MIN_MAX("(?:a?)?", 0, 1);
344 CHECK_MIN_MAX("(?:a*)?", 0, RegExpTree::kInfinity);
345 CHECK_MIN_MAX("(?:a+)?", 0, RegExpTree::kInfinity);
346 CHECK_MIN_MAX("(?:a?)+", 0, RegExpTree::kInfinity);
347 CHECK_MIN_MAX("(?:a*)+", 0, RegExpTree::kInfinity);
348 CHECK_MIN_MAX("(?:a+)+", 1, RegExpTree::kInfinity);
349 CHECK_MIN_MAX("(?:a?)*", 0, RegExpTree::kInfinity);
350 CHECK_MIN_MAX("(?:a*)*", 0, RegExpTree::kInfinity);
351 CHECK_MIN_MAX("(?:a+)*", 0, RegExpTree::kInfinity);
352 CHECK_MIN_MAX("a{0}", 0, 0);
353 CHECK_MIN_MAX("(?:a+){0}", 0, 0);
354 CHECK_MIN_MAX("(?:a+){0,0}", 0, 0);
355 CHECK_MIN_MAX("a*b", 1, RegExpTree::kInfinity);
356 CHECK_MIN_MAX("a+b", 2, RegExpTree::kInfinity);
357 CHECK_MIN_MAX("a*b|c", 1, RegExpTree::kInfinity);
358 CHECK_MIN_MAX("a+b|c", 1, RegExpTree::kInfinity);
359 CHECK_MIN_MAX("(?:a{5,1000000}){3,1000000}", 15, RegExpTree::kInfinity);
360 CHECK_MIN_MAX("(?:ab){4,7}", 8, 14);
361 CHECK_MIN_MAX("a\\bc", 2, 2);
362 CHECK_MIN_MAX("a\\Bc", 2, 2);
363 CHECK_MIN_MAX("a\\sc", 3, 3);
364 CHECK_MIN_MAX("a\\Sc", 3, 3);
365 CHECK_MIN_MAX("a(?=b)c", 2, 2);
366 CHECK_MIN_MAX("a(?=bbb|bb)c", 2, 2);
367 CHECK_MIN_MAX("a(?!bbb|bb)c", 2, 2);
368}
369
370TEST(ParserRegression) {
371 CHECK_PARSE_EQ("[A-Z$-][x]", "(! [A-Z $ -] [x])");
372 CHECK_PARSE_EQ("a{3,4*}", "(: 'a{3,' (# 0 - g '4') '}')");
373 CHECK_PARSE_EQ("{", "'{'");
374 CHECK_PARSE_EQ("a|", "(| 'a' %)");
375}
376
377static void ExpectError(const char* input,
378 const char* expected) {
379 V8::Initialize(NULL);
380 v8::HandleScope scope;
381 ZoneScope zone_scope(DELETE_ON_EXIT);
Steve Block44f0eee2011-05-26 01:26:41 +0100382 FlatStringReader reader(Isolate::Current(), CStrVector(input));
Steve Blocka7e24c12009-10-30 11:49:00 +0000383 RegExpCompileData result;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800384 CHECK(!v8::internal::RegExpParser::ParseRegExp(&reader, false, &result));
Steve Blocka7e24c12009-10-30 11:49:00 +0000385 CHECK(result.tree == NULL);
386 CHECK(!result.error.is_null());
387 SmartPointer<char> str = result.error->ToCString(ALLOW_NULLS);
388 CHECK_EQ(expected, *str);
389}
390
391
392TEST(Errors) {
393 V8::Initialize(NULL);
394 const char* kEndBackslash = "\\ at end of pattern";
395 ExpectError("\\", kEndBackslash);
396 const char* kUnterminatedGroup = "Unterminated group";
397 ExpectError("(foo", kUnterminatedGroup);
398 const char* kInvalidGroup = "Invalid group";
399 ExpectError("(?", kInvalidGroup);
400 const char* kUnterminatedCharacterClass = "Unterminated character class";
401 ExpectError("[", kUnterminatedCharacterClass);
402 ExpectError("[a-", kUnterminatedCharacterClass);
403 const char* kNothingToRepeat = "Nothing to repeat";
404 ExpectError("*", kNothingToRepeat);
405 ExpectError("?", kNothingToRepeat);
406 ExpectError("+", kNothingToRepeat);
407 ExpectError("{1}", kNothingToRepeat);
408 ExpectError("{1,2}", kNothingToRepeat);
409 ExpectError("{1,}", kNothingToRepeat);
410
411 // Check that we don't allow more than kMaxCapture captures
412 const int kMaxCaptures = 1 << 16; // Must match RegExpParser::kMaxCaptures.
413 const char* kTooManyCaptures = "Too many captures";
414 HeapStringAllocator allocator;
415 StringStream accumulator(&allocator);
416 for (int i = 0; i <= kMaxCaptures; i++) {
417 accumulator.Add("()");
418 }
419 SmartPointer<const char> many_captures(accumulator.ToCString());
420 ExpectError(*many_captures, kTooManyCaptures);
421}
422
423
424static bool IsDigit(uc16 c) {
425 return ('0' <= c && c <= '9');
426}
427
428
429static bool NotDigit(uc16 c) {
430 return !IsDigit(c);
431}
432
433
434static bool IsWhiteSpace(uc16 c) {
435 switch (c) {
436 case 0x09:
437 case 0x0A:
438 case 0x0B:
439 case 0x0C:
440 case 0x0d:
441 case 0x20:
442 case 0xA0:
443 case 0x2028:
444 case 0x2029:
445 return true;
446 default:
447 return unibrow::Space::Is(c);
448 }
449}
450
451
452static bool NotWhiteSpace(uc16 c) {
453 return !IsWhiteSpace(c);
454}
455
456
457static bool NotWord(uc16 c) {
458 return !IsRegExpWord(c);
459}
460
461
462static void TestCharacterClassEscapes(uc16 c, bool (pred)(uc16 c)) {
463 ZoneScope scope(DELETE_ON_EXIT);
464 ZoneList<CharacterRange>* ranges = new ZoneList<CharacterRange>(2);
465 CharacterRange::AddClassEscape(c, ranges);
466 for (unsigned i = 0; i < (1 << 16); i++) {
467 bool in_class = false;
468 for (int j = 0; !in_class && j < ranges->length(); j++) {
469 CharacterRange& range = ranges->at(j);
470 in_class = (range.from() <= i && i <= range.to());
471 }
472 CHECK_EQ(pred(i), in_class);
473 }
474}
475
476
477TEST(CharacterClassEscapes) {
Steve Block44f0eee2011-05-26 01:26:41 +0100478 v8::internal::V8::Initialize(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000479 TestCharacterClassEscapes('.', IsRegExpNewline);
480 TestCharacterClassEscapes('d', IsDigit);
481 TestCharacterClassEscapes('D', NotDigit);
482 TestCharacterClassEscapes('s', IsWhiteSpace);
483 TestCharacterClassEscapes('S', NotWhiteSpace);
484 TestCharacterClassEscapes('w', IsRegExpWord);
485 TestCharacterClassEscapes('W', NotWord);
486}
487
488
489static RegExpNode* Compile(const char* input, bool multiline, bool is_ascii) {
490 V8::Initialize(NULL);
Steve Block44f0eee2011-05-26 01:26:41 +0100491 FlatStringReader reader(Isolate::Current(), CStrVector(input));
Steve Blocka7e24c12009-10-30 11:49:00 +0000492 RegExpCompileData compile_data;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800493 if (!v8::internal::RegExpParser::ParseRegExp(&reader, multiline,
494 &compile_data))
Steve Blocka7e24c12009-10-30 11:49:00 +0000495 return NULL;
Steve Block44f0eee2011-05-26 01:26:41 +0100496 Handle<String> pattern = FACTORY->NewStringFromUtf8(CStrVector(input));
Steve Blocka7e24c12009-10-30 11:49:00 +0000497 RegExpEngine::Compile(&compile_data, false, multiline, pattern, is_ascii);
498 return compile_data.node;
499}
500
501
502static void Execute(const char* input,
503 bool multiline,
504 bool is_ascii,
505 bool dot_output = false) {
506 v8::HandleScope scope;
507 ZoneScope zone_scope(DELETE_ON_EXIT);
508 RegExpNode* node = Compile(input, multiline, is_ascii);
509 USE(node);
510#ifdef DEBUG
511 if (dot_output) {
512 RegExpEngine::DotPrint(input, node, false);
513 exit(0);
514 }
515#endif // DEBUG
516}
517
518
519class TestConfig {
520 public:
521 typedef int Key;
522 typedef int Value;
523 static const int kNoKey;
524 static const int kNoValue;
525 static inline int Compare(int a, int b) {
526 if (a < b)
527 return -1;
528 else if (a > b)
529 return 1;
530 else
531 return 0;
532 }
533};
534
535
536const int TestConfig::kNoKey = 0;
537const int TestConfig::kNoValue = 0;
538
539
540static unsigned PseudoRandom(int i, int j) {
541 return ~(~((i * 781) ^ (j * 329)));
542}
543
544
545TEST(SplayTreeSimple) {
Steve Block44f0eee2011-05-26 01:26:41 +0100546 v8::internal::V8::Initialize(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000547 static const unsigned kLimit = 1000;
548 ZoneScope zone_scope(DELETE_ON_EXIT);
549 ZoneSplayTree<TestConfig> tree;
550 bool seen[kLimit];
551 for (unsigned i = 0; i < kLimit; i++) seen[i] = false;
552#define CHECK_MAPS_EQUAL() do { \
553 for (unsigned k = 0; k < kLimit; k++) \
554 CHECK_EQ(seen[k], tree.Find(k, &loc)); \
555 } while (false)
556 for (int i = 0; i < 50; i++) {
557 for (int j = 0; j < 50; j++) {
558 unsigned next = PseudoRandom(i, j) % kLimit;
559 if (seen[next]) {
560 // We've already seen this one. Check the value and remove
561 // it.
562 ZoneSplayTree<TestConfig>::Locator loc;
563 CHECK(tree.Find(next, &loc));
564 CHECK_EQ(next, loc.key());
565 CHECK_EQ(3 * next, loc.value());
566 tree.Remove(next);
567 seen[next] = false;
568 CHECK_MAPS_EQUAL();
569 } else {
570 // Check that it wasn't there already and then add it.
571 ZoneSplayTree<TestConfig>::Locator loc;
572 CHECK(!tree.Find(next, &loc));
573 CHECK(tree.Insert(next, &loc));
574 CHECK_EQ(next, loc.key());
575 loc.set_value(3 * next);
576 seen[next] = true;
577 CHECK_MAPS_EQUAL();
578 }
579 int val = PseudoRandom(j, i) % kLimit;
580 if (seen[val]) {
581 ZoneSplayTree<TestConfig>::Locator loc;
582 CHECK(tree.FindGreatestLessThan(val, &loc));
583 CHECK_EQ(loc.key(), val);
584 break;
585 }
586 val = PseudoRandom(i + j, i - j) % kLimit;
587 if (seen[val]) {
588 ZoneSplayTree<TestConfig>::Locator loc;
589 CHECK(tree.FindLeastGreaterThan(val, &loc));
590 CHECK_EQ(loc.key(), val);
591 break;
592 }
593 }
594 }
595}
596
597
598TEST(DispatchTableConstruction) {
Steve Block44f0eee2011-05-26 01:26:41 +0100599 v8::internal::V8::Initialize(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000600 // Initialize test data.
601 static const int kLimit = 1000;
602 static const int kRangeCount = 8;
603 static const int kRangeSize = 16;
604 uc16 ranges[kRangeCount][2 * kRangeSize];
605 for (int i = 0; i < kRangeCount; i++) {
606 Vector<uc16> range(ranges[i], 2 * kRangeSize);
607 for (int j = 0; j < 2 * kRangeSize; j++) {
608 range[j] = PseudoRandom(i + 25, j + 87) % kLimit;
609 }
610 range.Sort();
611 for (int j = 1; j < 2 * kRangeSize; j++) {
612 CHECK(range[j-1] <= range[j]);
613 }
614 }
615 // Enter test data into dispatch table.
616 ZoneScope zone_scope(DELETE_ON_EXIT);
617 DispatchTable table;
618 for (int i = 0; i < kRangeCount; i++) {
619 uc16* range = ranges[i];
620 for (int j = 0; j < 2 * kRangeSize; j += 2)
621 table.AddRange(CharacterRange(range[j], range[j + 1]), i);
622 }
623 // Check that the table looks as we would expect
624 for (int p = 0; p < kLimit; p++) {
625 OutSet* outs = table.Get(p);
626 for (int j = 0; j < kRangeCount; j++) {
627 uc16* range = ranges[j];
628 bool is_on = false;
629 for (int k = 0; !is_on && (k < 2 * kRangeSize); k += 2)
630 is_on = (range[k] <= p && p <= range[k + 1]);
631 CHECK_EQ(is_on, outs->Get(j));
632 }
633 }
634}
635
Leon Clarkee46be812010-01-19 14:06:41 +0000636// Test of debug-only syntax.
637#ifdef DEBUG
638
639TEST(ParsePossessiveRepetition) {
640 bool old_flag_value = FLAG_regexp_possessive_quantifier;
641
642 // Enable possessive quantifier syntax.
643 FLAG_regexp_possessive_quantifier = true;
644
645 CHECK_PARSE_EQ("a*+", "(# 0 - p 'a')");
646 CHECK_PARSE_EQ("a++", "(# 1 - p 'a')");
647 CHECK_PARSE_EQ("a?+", "(# 0 1 p 'a')");
648 CHECK_PARSE_EQ("a{10,20}+", "(# 10 20 p 'a')");
649 CHECK_PARSE_EQ("za{10,20}+b", "(: 'z' (# 10 20 p 'a') 'b')");
650
651 // Disable possessive quantifier syntax.
652 FLAG_regexp_possessive_quantifier = false;
653
654 CHECK_PARSE_ERROR("a*+");
655 CHECK_PARSE_ERROR("a++");
656 CHECK_PARSE_ERROR("a?+");
657 CHECK_PARSE_ERROR("a{10,20}+");
658 CHECK_PARSE_ERROR("a{10,20}+b");
659
660 FLAG_regexp_possessive_quantifier = old_flag_value;
661}
662
663#endif
Steve Blocka7e24c12009-10-30 11:49:00 +0000664
665// Tests of interpreter.
666
667
Steve Block6ded16b2010-05-10 14:33:55 +0100668#ifndef V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +0000669
670#if V8_TARGET_ARCH_IA32
671typedef RegExpMacroAssemblerIA32 ArchRegExpMacroAssembler;
672#elif V8_TARGET_ARCH_X64
673typedef RegExpMacroAssemblerX64 ArchRegExpMacroAssembler;
674#elif V8_TARGET_ARCH_ARM
675typedef RegExpMacroAssemblerARM ArchRegExpMacroAssembler;
Andrei Popescu31002712010-02-23 13:46:05 +0000676#elif V8_TARGET_ARCH_MIPS
Steve Block44f0eee2011-05-26 01:26:41 +0100677typedef RegExpMacroAssemblerMIPS ArchRegExpMacroAssembler;
Steve Blocka7e24c12009-10-30 11:49:00 +0000678#endif
679
680class ContextInitializer {
681 public:
682 ContextInitializer()
Steve Block44f0eee2011-05-26 01:26:41 +0100683 : env_(), scope_(), zone_(DELETE_ON_EXIT) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000684 env_ = v8::Context::New();
685 env_->Enter();
686 }
687 ~ContextInitializer() {
688 env_->Exit();
689 env_.Dispose();
690 }
691 private:
692 v8::Persistent<v8::Context> env_;
693 v8::HandleScope scope_;
694 v8::internal::ZoneScope zone_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000695};
696
697
698static ArchRegExpMacroAssembler::Result Execute(Code* code,
699 String* input,
700 int start_offset,
701 const byte* input_start,
702 const byte* input_end,
Leon Clarked91b9f72010-01-27 17:25:45 +0000703 int* captures) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000704 return NativeRegExpMacroAssembler::Execute(
705 code,
706 input,
707 start_offset,
708 input_start,
709 input_end,
Steve Block44f0eee2011-05-26 01:26:41 +0100710 captures,
711 Isolate::Current());
Steve Blocka7e24c12009-10-30 11:49:00 +0000712}
713
714
715TEST(MacroAssemblerNativeSuccess) {
716 v8::V8::Initialize();
717 ContextInitializer initializer;
718
719 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 4);
720
721 m.Succeed();
722
Steve Block44f0eee2011-05-26 01:26:41 +0100723 Handle<String> source = FACTORY->NewStringFromAscii(CStrVector(""));
Steve Blocka7e24c12009-10-30 11:49:00 +0000724 Handle<Object> code_object = m.GetCode(source);
725 Handle<Code> code = Handle<Code>::cast(code_object);
726
727 int captures[4] = {42, 37, 87, 117};
Steve Block44f0eee2011-05-26 01:26:41 +0100728 Handle<String> input = FACTORY->NewStringFromAscii(CStrVector("foofoo"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000729 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
730 const byte* start_adr =
731 reinterpret_cast<const byte*>(seq_input->GetCharsAddress());
732
733 NativeRegExpMacroAssembler::Result result =
734 Execute(*code,
735 *input,
736 0,
737 start_adr,
738 start_adr + seq_input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +0000739 captures);
Steve Blocka7e24c12009-10-30 11:49:00 +0000740
741 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
742 CHECK_EQ(-1, captures[0]);
743 CHECK_EQ(-1, captures[1]);
744 CHECK_EQ(-1, captures[2]);
745 CHECK_EQ(-1, captures[3]);
746}
747
748
749TEST(MacroAssemblerNativeSimple) {
750 v8::V8::Initialize();
751 ContextInitializer initializer;
752
753 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 4);
754
755 uc16 foo_chars[3] = {'f', 'o', 'o'};
756 Vector<const uc16> foo(foo_chars, 3);
757
758 Label fail;
759 m.CheckCharacters(foo, 0, &fail, true);
760 m.WriteCurrentPositionToRegister(0, 0);
761 m.AdvanceCurrentPosition(3);
762 m.WriteCurrentPositionToRegister(1, 0);
763 m.Succeed();
764 m.Bind(&fail);
765 m.Fail();
766
Steve Block44f0eee2011-05-26 01:26:41 +0100767 Handle<String> source = FACTORY->NewStringFromAscii(CStrVector("^foo"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000768 Handle<Object> code_object = m.GetCode(source);
769 Handle<Code> code = Handle<Code>::cast(code_object);
770
771 int captures[4] = {42, 37, 87, 117};
Steve Block44f0eee2011-05-26 01:26:41 +0100772 Handle<String> input = FACTORY->NewStringFromAscii(CStrVector("foofoo"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000773 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
774 Address start_adr = seq_input->GetCharsAddress();
775
776 NativeRegExpMacroAssembler::Result result =
777 Execute(*code,
778 *input,
779 0,
780 start_adr,
781 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +0000782 captures);
Steve Blocka7e24c12009-10-30 11:49:00 +0000783
784 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
785 CHECK_EQ(0, captures[0]);
786 CHECK_EQ(3, captures[1]);
787 CHECK_EQ(-1, captures[2]);
788 CHECK_EQ(-1, captures[3]);
789
Steve Block44f0eee2011-05-26 01:26:41 +0100790 input = FACTORY->NewStringFromAscii(CStrVector("barbarbar"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000791 seq_input = Handle<SeqAsciiString>::cast(input);
792 start_adr = seq_input->GetCharsAddress();
793
794 result = Execute(*code,
795 *input,
796 0,
797 start_adr,
798 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +0000799 captures);
Steve Blocka7e24c12009-10-30 11:49:00 +0000800
801 CHECK_EQ(NativeRegExpMacroAssembler::FAILURE, result);
802}
803
804
805TEST(MacroAssemblerNativeSimpleUC16) {
806 v8::V8::Initialize();
807 ContextInitializer initializer;
808
809 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::UC16, 4);
810
811 uc16 foo_chars[3] = {'f', 'o', 'o'};
812 Vector<const uc16> foo(foo_chars, 3);
813
814 Label fail;
815 m.CheckCharacters(foo, 0, &fail, true);
816 m.WriteCurrentPositionToRegister(0, 0);
817 m.AdvanceCurrentPosition(3);
818 m.WriteCurrentPositionToRegister(1, 0);
819 m.Succeed();
820 m.Bind(&fail);
821 m.Fail();
822
Steve Block44f0eee2011-05-26 01:26:41 +0100823 Handle<String> source = FACTORY->NewStringFromAscii(CStrVector("^foo"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000824 Handle<Object> code_object = m.GetCode(source);
825 Handle<Code> code = Handle<Code>::cast(code_object);
826
827 int captures[4] = {42, 37, 87, 117};
828 const uc16 input_data[6] = {'f', 'o', 'o', 'f', 'o', '\xa0'};
829 Handle<String> input =
Steve Block44f0eee2011-05-26 01:26:41 +0100830 FACTORY->NewStringFromTwoByte(Vector<const uc16>(input_data, 6));
Steve Blocka7e24c12009-10-30 11:49:00 +0000831 Handle<SeqTwoByteString> seq_input = Handle<SeqTwoByteString>::cast(input);
832 Address start_adr = seq_input->GetCharsAddress();
833
834 NativeRegExpMacroAssembler::Result result =
835 Execute(*code,
836 *input,
837 0,
838 start_adr,
839 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +0000840 captures);
Steve Blocka7e24c12009-10-30 11:49:00 +0000841
842 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
843 CHECK_EQ(0, captures[0]);
844 CHECK_EQ(3, captures[1]);
845 CHECK_EQ(-1, captures[2]);
846 CHECK_EQ(-1, captures[3]);
847
848 const uc16 input_data2[9] = {'b', 'a', 'r', 'b', 'a', 'r', 'b', 'a', '\xa0'};
Steve Block44f0eee2011-05-26 01:26:41 +0100849 input = FACTORY->NewStringFromTwoByte(Vector<const uc16>(input_data2, 9));
Steve Blocka7e24c12009-10-30 11:49:00 +0000850 seq_input = Handle<SeqTwoByteString>::cast(input);
851 start_adr = seq_input->GetCharsAddress();
852
853 result = Execute(*code,
854 *input,
855 0,
856 start_adr,
857 start_adr + input->length() * 2,
Leon Clarked91b9f72010-01-27 17:25:45 +0000858 captures);
Steve Blocka7e24c12009-10-30 11:49:00 +0000859
860 CHECK_EQ(NativeRegExpMacroAssembler::FAILURE, result);
861}
862
863
864TEST(MacroAssemblerNativeBacktrack) {
865 v8::V8::Initialize();
866 ContextInitializer initializer;
867
868 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 0);
869
870 Label fail;
871 Label backtrack;
872 m.LoadCurrentCharacter(10, &fail);
873 m.Succeed();
874 m.Bind(&fail);
875 m.PushBacktrack(&backtrack);
876 m.LoadCurrentCharacter(10, NULL);
877 m.Succeed();
878 m.Bind(&backtrack);
879 m.Fail();
880
Steve Block44f0eee2011-05-26 01:26:41 +0100881 Handle<String> source = FACTORY->NewStringFromAscii(CStrVector(".........."));
Steve Blocka7e24c12009-10-30 11:49:00 +0000882 Handle<Object> code_object = m.GetCode(source);
883 Handle<Code> code = Handle<Code>::cast(code_object);
884
Steve Block44f0eee2011-05-26 01:26:41 +0100885 Handle<String> input = FACTORY->NewStringFromAscii(CStrVector("foofoo"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000886 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
887 Address start_adr = seq_input->GetCharsAddress();
888
889 NativeRegExpMacroAssembler::Result result =
890 Execute(*code,
891 *input,
892 0,
893 start_adr,
894 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +0000895 NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000896
897 CHECK_EQ(NativeRegExpMacroAssembler::FAILURE, result);
898}
899
900
901TEST(MacroAssemblerNativeBackReferenceASCII) {
902 v8::V8::Initialize();
903 ContextInitializer initializer;
904
905 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 4);
906
907 m.WriteCurrentPositionToRegister(0, 0);
908 m.AdvanceCurrentPosition(2);
909 m.WriteCurrentPositionToRegister(1, 0);
910 Label nomatch;
911 m.CheckNotBackReference(0, &nomatch);
912 m.Fail();
913 m.Bind(&nomatch);
914 m.AdvanceCurrentPosition(2);
915 Label missing_match;
916 m.CheckNotBackReference(0, &missing_match);
917 m.WriteCurrentPositionToRegister(2, 0);
918 m.Succeed();
919 m.Bind(&missing_match);
920 m.Fail();
921
Steve Block44f0eee2011-05-26 01:26:41 +0100922 Handle<String> source = FACTORY->NewStringFromAscii(CStrVector("^(..)..\1"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000923 Handle<Object> code_object = m.GetCode(source);
924 Handle<Code> code = Handle<Code>::cast(code_object);
925
Steve Block44f0eee2011-05-26 01:26:41 +0100926 Handle<String> input = FACTORY->NewStringFromAscii(CStrVector("fooofo"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000927 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
928 Address start_adr = seq_input->GetCharsAddress();
929
930 int output[4];
931 NativeRegExpMacroAssembler::Result result =
932 Execute(*code,
933 *input,
934 0,
935 start_adr,
936 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +0000937 output);
Steve Blocka7e24c12009-10-30 11:49:00 +0000938
939 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
940 CHECK_EQ(0, output[0]);
941 CHECK_EQ(2, output[1]);
942 CHECK_EQ(6, output[2]);
943 CHECK_EQ(-1, output[3]);
944}
945
946
947TEST(MacroAssemblerNativeBackReferenceUC16) {
948 v8::V8::Initialize();
949 ContextInitializer initializer;
950
951 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::UC16, 4);
952
953 m.WriteCurrentPositionToRegister(0, 0);
954 m.AdvanceCurrentPosition(2);
955 m.WriteCurrentPositionToRegister(1, 0);
956 Label nomatch;
957 m.CheckNotBackReference(0, &nomatch);
958 m.Fail();
959 m.Bind(&nomatch);
960 m.AdvanceCurrentPosition(2);
961 Label missing_match;
962 m.CheckNotBackReference(0, &missing_match);
963 m.WriteCurrentPositionToRegister(2, 0);
964 m.Succeed();
965 m.Bind(&missing_match);
966 m.Fail();
967
Steve Block44f0eee2011-05-26 01:26:41 +0100968 Handle<String> source = FACTORY->NewStringFromAscii(CStrVector("^(..)..\1"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000969 Handle<Object> code_object = m.GetCode(source);
970 Handle<Code> code = Handle<Code>::cast(code_object);
971
972 const uc16 input_data[6] = {'f', 0x2028, 'o', 'o', 'f', 0x2028};
973 Handle<String> input =
Steve Block44f0eee2011-05-26 01:26:41 +0100974 FACTORY->NewStringFromTwoByte(Vector<const uc16>(input_data, 6));
Steve Blocka7e24c12009-10-30 11:49:00 +0000975 Handle<SeqTwoByteString> seq_input = Handle<SeqTwoByteString>::cast(input);
976 Address start_adr = seq_input->GetCharsAddress();
977
978 int output[4];
979 NativeRegExpMacroAssembler::Result result =
980 Execute(*code,
981 *input,
982 0,
983 start_adr,
984 start_adr + input->length() * 2,
Leon Clarked91b9f72010-01-27 17:25:45 +0000985 output);
Steve Blocka7e24c12009-10-30 11:49:00 +0000986
987 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
988 CHECK_EQ(0, output[0]);
989 CHECK_EQ(2, output[1]);
990 CHECK_EQ(6, output[2]);
991 CHECK_EQ(-1, output[3]);
992}
993
994
995
996TEST(MacroAssemblernativeAtStart) {
997 v8::V8::Initialize();
998 ContextInitializer initializer;
999
1000 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 0);
1001
1002 Label not_at_start, newline, fail;
1003 m.CheckNotAtStart(&not_at_start);
1004 // Check that prevchar = '\n' and current = 'f'.
1005 m.CheckCharacter('\n', &newline);
1006 m.Bind(&fail);
1007 m.Fail();
1008 m.Bind(&newline);
1009 m.LoadCurrentCharacter(0, &fail);
1010 m.CheckNotCharacter('f', &fail);
1011 m.Succeed();
1012
1013 m.Bind(&not_at_start);
1014 // Check that prevchar = 'o' and current = 'b'.
1015 Label prevo;
1016 m.CheckCharacter('o', &prevo);
1017 m.Fail();
1018 m.Bind(&prevo);
1019 m.LoadCurrentCharacter(0, &fail);
1020 m.CheckNotCharacter('b', &fail);
1021 m.Succeed();
1022
Steve Block44f0eee2011-05-26 01:26:41 +01001023 Handle<String> source = FACTORY->NewStringFromAscii(CStrVector("(^f|ob)"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001024 Handle<Object> code_object = m.GetCode(source);
1025 Handle<Code> code = Handle<Code>::cast(code_object);
1026
Steve Block44f0eee2011-05-26 01:26:41 +01001027 Handle<String> input = FACTORY->NewStringFromAscii(CStrVector("foobar"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001028 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
1029 Address start_adr = seq_input->GetCharsAddress();
1030
1031 NativeRegExpMacroAssembler::Result result =
1032 Execute(*code,
1033 *input,
1034 0,
1035 start_adr,
1036 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +00001037 NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00001038
1039 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
1040
1041 result = Execute(*code,
1042 *input,
1043 3,
1044 start_adr + 3,
1045 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +00001046 NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00001047
1048 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
1049}
1050
1051
1052TEST(MacroAssemblerNativeBackRefNoCase) {
1053 v8::V8::Initialize();
1054 ContextInitializer initializer;
1055
1056 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 4);
1057
1058 Label fail, succ;
1059
1060 m.WriteCurrentPositionToRegister(0, 0);
1061 m.WriteCurrentPositionToRegister(2, 0);
1062 m.AdvanceCurrentPosition(3);
1063 m.WriteCurrentPositionToRegister(3, 0);
1064 m.CheckNotBackReferenceIgnoreCase(2, &fail); // Match "AbC".
1065 m.CheckNotBackReferenceIgnoreCase(2, &fail); // Match "ABC".
1066 Label expected_fail;
1067 m.CheckNotBackReferenceIgnoreCase(2, &expected_fail);
1068 m.Bind(&fail);
1069 m.Fail();
1070
1071 m.Bind(&expected_fail);
1072 m.AdvanceCurrentPosition(3); // Skip "xYz"
1073 m.CheckNotBackReferenceIgnoreCase(2, &succ);
1074 m.Fail();
1075
1076 m.Bind(&succ);
1077 m.WriteCurrentPositionToRegister(1, 0);
1078 m.Succeed();
1079
1080 Handle<String> source =
Steve Block44f0eee2011-05-26 01:26:41 +01001081 FACTORY->NewStringFromAscii(CStrVector("^(abc)\1\1(?!\1)...(?!\1)"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001082 Handle<Object> code_object = m.GetCode(source);
1083 Handle<Code> code = Handle<Code>::cast(code_object);
1084
1085 Handle<String> input =
Steve Block44f0eee2011-05-26 01:26:41 +01001086 FACTORY->NewStringFromAscii(CStrVector("aBcAbCABCxYzab"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001087 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
1088 Address start_adr = seq_input->GetCharsAddress();
1089
1090 int output[4];
1091 NativeRegExpMacroAssembler::Result result =
1092 Execute(*code,
1093 *input,
1094 0,
1095 start_adr,
1096 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +00001097 output);
Steve Blocka7e24c12009-10-30 11:49:00 +00001098
1099 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
1100 CHECK_EQ(0, output[0]);
1101 CHECK_EQ(12, output[1]);
1102 CHECK_EQ(0, output[2]);
1103 CHECK_EQ(3, output[3]);
1104}
1105
1106
1107
1108TEST(MacroAssemblerNativeRegisters) {
1109 v8::V8::Initialize();
1110 ContextInitializer initializer;
1111
1112 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 6);
1113
1114 uc16 foo_chars[3] = {'f', 'o', 'o'};
1115 Vector<const uc16> foo(foo_chars, 3);
1116
1117 enum registers { out1, out2, out3, out4, out5, out6, sp, loop_cnt };
1118 Label fail;
1119 Label backtrack;
1120 m.WriteCurrentPositionToRegister(out1, 0); // Output: [0]
1121 m.PushRegister(out1, RegExpMacroAssembler::kNoStackLimitCheck);
1122 m.PushBacktrack(&backtrack);
1123 m.WriteStackPointerToRegister(sp);
1124 // Fill stack and registers
1125 m.AdvanceCurrentPosition(2);
1126 m.WriteCurrentPositionToRegister(out1, 0);
1127 m.PushRegister(out1, RegExpMacroAssembler::kNoStackLimitCheck);
1128 m.PushBacktrack(&fail);
1129 // Drop backtrack stack frames.
1130 m.ReadStackPointerFromRegister(sp);
1131 // And take the first backtrack (to &backtrack)
1132 m.Backtrack();
1133
1134 m.PushCurrentPosition();
1135 m.AdvanceCurrentPosition(2);
1136 m.PopCurrentPosition();
1137
1138 m.Bind(&backtrack);
1139 m.PopRegister(out1);
1140 m.ReadCurrentPositionFromRegister(out1);
1141 m.AdvanceCurrentPosition(3);
1142 m.WriteCurrentPositionToRegister(out2, 0); // [0,3]
1143
1144 Label loop;
1145 m.SetRegister(loop_cnt, 0); // loop counter
1146 m.Bind(&loop);
1147 m.AdvanceRegister(loop_cnt, 1);
1148 m.AdvanceCurrentPosition(1);
1149 m.IfRegisterLT(loop_cnt, 3, &loop);
1150 m.WriteCurrentPositionToRegister(out3, 0); // [0,3,6]
1151
1152 Label loop2;
1153 m.SetRegister(loop_cnt, 2); // loop counter
1154 m.Bind(&loop2);
1155 m.AdvanceRegister(loop_cnt, -1);
1156 m.AdvanceCurrentPosition(1);
1157 m.IfRegisterGE(loop_cnt, 0, &loop2);
1158 m.WriteCurrentPositionToRegister(out4, 0); // [0,3,6,9]
1159
1160 Label loop3;
1161 Label exit_loop3;
1162 m.PushRegister(out4, RegExpMacroAssembler::kNoStackLimitCheck);
1163 m.PushRegister(out4, RegExpMacroAssembler::kNoStackLimitCheck);
1164 m.ReadCurrentPositionFromRegister(out3);
1165 m.Bind(&loop3);
1166 m.AdvanceCurrentPosition(1);
1167 m.CheckGreedyLoop(&exit_loop3);
1168 m.GoTo(&loop3);
1169 m.Bind(&exit_loop3);
1170 m.PopCurrentPosition();
1171 m.WriteCurrentPositionToRegister(out5, 0); // [0,3,6,9,9,-1]
1172
1173 m.Succeed();
1174
1175 m.Bind(&fail);
1176 m.Fail();
1177
1178 Handle<String> source =
Steve Block44f0eee2011-05-26 01:26:41 +01001179 FACTORY->NewStringFromAscii(CStrVector("<loop test>"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001180 Handle<Object> code_object = m.GetCode(source);
1181 Handle<Code> code = Handle<Code>::cast(code_object);
1182
1183 // String long enough for test (content doesn't matter).
1184 Handle<String> input =
Steve Block44f0eee2011-05-26 01:26:41 +01001185 FACTORY->NewStringFromAscii(CStrVector("foofoofoofoofoo"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001186 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
1187 Address start_adr = seq_input->GetCharsAddress();
1188
1189 int output[6];
1190 NativeRegExpMacroAssembler::Result result =
1191 Execute(*code,
1192 *input,
1193 0,
1194 start_adr,
1195 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +00001196 output);
Steve Blocka7e24c12009-10-30 11:49:00 +00001197
1198 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
1199 CHECK_EQ(0, output[0]);
1200 CHECK_EQ(3, output[1]);
1201 CHECK_EQ(6, output[2]);
1202 CHECK_EQ(9, output[3]);
1203 CHECK_EQ(9, output[4]);
1204 CHECK_EQ(-1, output[5]);
1205}
1206
1207
1208TEST(MacroAssemblerStackOverflow) {
1209 v8::V8::Initialize();
1210 ContextInitializer initializer;
1211
1212 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 0);
1213
1214 Label loop;
1215 m.Bind(&loop);
1216 m.PushBacktrack(&loop);
1217 m.GoTo(&loop);
1218
1219 Handle<String> source =
Steve Block44f0eee2011-05-26 01:26:41 +01001220 FACTORY->NewStringFromAscii(CStrVector("<stack overflow test>"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001221 Handle<Object> code_object = m.GetCode(source);
1222 Handle<Code> code = Handle<Code>::cast(code_object);
1223
1224 // String long enough for test (content doesn't matter).
1225 Handle<String> input =
Steve Block44f0eee2011-05-26 01:26:41 +01001226 FACTORY->NewStringFromAscii(CStrVector("dummy"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001227 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
1228 Address start_adr = seq_input->GetCharsAddress();
1229
1230 NativeRegExpMacroAssembler::Result result =
1231 Execute(*code,
1232 *input,
1233 0,
1234 start_adr,
1235 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +00001236 NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00001237
1238 CHECK_EQ(NativeRegExpMacroAssembler::EXCEPTION, result);
Steve Block44f0eee2011-05-26 01:26:41 +01001239 CHECK(Isolate::Current()->has_pending_exception());
1240 Isolate::Current()->clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +00001241}
1242
1243
1244TEST(MacroAssemblerNativeLotsOfRegisters) {
1245 v8::V8::Initialize();
1246 ContextInitializer initializer;
1247
1248 ArchRegExpMacroAssembler m(NativeRegExpMacroAssembler::ASCII, 2);
1249
1250 // At least 2048, to ensure the allocated space for registers
1251 // span one full page.
1252 const int large_number = 8000;
1253 m.WriteCurrentPositionToRegister(large_number, 42);
1254 m.WriteCurrentPositionToRegister(0, 0);
1255 m.WriteCurrentPositionToRegister(1, 1);
1256 Label done;
1257 m.CheckNotBackReference(0, &done); // Performs a system-stack push.
1258 m.Bind(&done);
1259 m.PushRegister(large_number, RegExpMacroAssembler::kNoStackLimitCheck);
1260 m.PopRegister(1);
1261 m.Succeed();
1262
1263 Handle<String> source =
Steve Block44f0eee2011-05-26 01:26:41 +01001264 FACTORY->NewStringFromAscii(CStrVector("<huge register space test>"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001265 Handle<Object> code_object = m.GetCode(source);
1266 Handle<Code> code = Handle<Code>::cast(code_object);
1267
1268 // String long enough for test (content doesn't matter).
1269 Handle<String> input =
Steve Block44f0eee2011-05-26 01:26:41 +01001270 FACTORY->NewStringFromAscii(CStrVector("sample text"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001271 Handle<SeqAsciiString> seq_input = Handle<SeqAsciiString>::cast(input);
1272 Address start_adr = seq_input->GetCharsAddress();
1273
1274 int captures[2];
1275 NativeRegExpMacroAssembler::Result result =
1276 Execute(*code,
1277 *input,
1278 0,
1279 start_adr,
1280 start_adr + input->length(),
Leon Clarked91b9f72010-01-27 17:25:45 +00001281 captures);
Steve Blocka7e24c12009-10-30 11:49:00 +00001282
1283 CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
1284 CHECK_EQ(0, captures[0]);
1285 CHECK_EQ(42, captures[1]);
1286
Steve Block44f0eee2011-05-26 01:26:41 +01001287 Isolate::Current()->clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +00001288}
1289
Steve Block6ded16b2010-05-10 14:33:55 +01001290#else // V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00001291
1292TEST(MacroAssembler) {
1293 V8::Initialize(NULL);
1294 byte codes[1024];
1295 RegExpMacroAssemblerIrregexp m(Vector<byte>(codes, 1024));
1296 // ^f(o)o.
1297 Label fail, fail2, start;
1298 uc16 foo_chars[3];
1299 foo_chars[0] = 'f';
1300 foo_chars[1] = 'o';
1301 foo_chars[2] = 'o';
1302 Vector<const uc16> foo(foo_chars, 3);
1303 m.SetRegister(4, 42);
1304 m.PushRegister(4, RegExpMacroAssembler::kNoStackLimitCheck);
1305 m.AdvanceRegister(4, 42);
1306 m.GoTo(&start);
1307 m.Fail();
1308 m.Bind(&start);
1309 m.PushBacktrack(&fail2);
1310 m.CheckCharacters(foo, 0, &fail, true);
1311 m.WriteCurrentPositionToRegister(0, 0);
1312 m.PushCurrentPosition();
1313 m.AdvanceCurrentPosition(3);
1314 m.WriteCurrentPositionToRegister(1, 0);
1315 m.PopCurrentPosition();
1316 m.AdvanceCurrentPosition(1);
1317 m.WriteCurrentPositionToRegister(2, 0);
1318 m.AdvanceCurrentPosition(1);
1319 m.WriteCurrentPositionToRegister(3, 0);
1320 m.Succeed();
1321
1322 m.Bind(&fail);
1323 m.Backtrack();
1324 m.Succeed();
1325
1326 m.Bind(&fail2);
1327 m.PopRegister(0);
1328 m.Fail();
1329
1330 v8::HandleScope scope;
1331
Steve Block44f0eee2011-05-26 01:26:41 +01001332 Handle<String> source = FACTORY->NewStringFromAscii(CStrVector("^f(o)o"));
Steve Blocka7e24c12009-10-30 11:49:00 +00001333 Handle<ByteArray> array = Handle<ByteArray>::cast(m.GetCode(source));
1334 int captures[5];
1335
1336 const uc16 str1[] = {'f', 'o', 'o', 'b', 'a', 'r'};
1337 Handle<String> f1_16 =
Steve Block44f0eee2011-05-26 01:26:41 +01001338 FACTORY->NewStringFromTwoByte(Vector<const uc16>(str1, 6));
Steve Blocka7e24c12009-10-30 11:49:00 +00001339
1340 CHECK(IrregexpInterpreter::Match(array, f1_16, captures, 0));
1341 CHECK_EQ(0, captures[0]);
1342 CHECK_EQ(3, captures[1]);
1343 CHECK_EQ(1, captures[2]);
1344 CHECK_EQ(2, captures[3]);
1345 CHECK_EQ(84, captures[4]);
1346
1347 const uc16 str2[] = {'b', 'a', 'r', 'f', 'o', 'o'};
1348 Handle<String> f2_16 =
Steve Block44f0eee2011-05-26 01:26:41 +01001349 FACTORY->NewStringFromTwoByte(Vector<const uc16>(str2, 6));
Steve Blocka7e24c12009-10-30 11:49:00 +00001350
1351 CHECK(!IrregexpInterpreter::Match(array, f2_16, captures, 0));
1352 CHECK_EQ(42, captures[0]);
1353}
1354
Steve Block6ded16b2010-05-10 14:33:55 +01001355#endif // V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00001356
1357
1358TEST(AddInverseToTable) {
Steve Block44f0eee2011-05-26 01:26:41 +01001359 v8::internal::V8::Initialize(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00001360 static const int kLimit = 1000;
1361 static const int kRangeCount = 16;
1362 for (int t = 0; t < 10; t++) {
1363 ZoneScope zone_scope(DELETE_ON_EXIT);
1364 ZoneList<CharacterRange>* ranges =
1365 new ZoneList<CharacterRange>(kRangeCount);
1366 for (int i = 0; i < kRangeCount; i++) {
1367 int from = PseudoRandom(t + 87, i + 25) % kLimit;
1368 int to = from + (PseudoRandom(i + 87, t + 25) % (kLimit / 20));
1369 if (to > kLimit) to = kLimit;
1370 ranges->Add(CharacterRange(from, to));
1371 }
1372 DispatchTable table;
1373 DispatchTableConstructor cons(&table, false);
1374 cons.set_choice_index(0);
1375 cons.AddInverse(ranges);
1376 for (int i = 0; i < kLimit; i++) {
1377 bool is_on = false;
1378 for (int j = 0; !is_on && j < kRangeCount; j++)
1379 is_on = ranges->at(j).Contains(i);
1380 OutSet* set = table.Get(i);
1381 CHECK_EQ(is_on, set->Get(0) == false);
1382 }
1383 }
1384 ZoneScope zone_scope(DELETE_ON_EXIT);
1385 ZoneList<CharacterRange>* ranges =
1386 new ZoneList<CharacterRange>(1);
1387 ranges->Add(CharacterRange(0xFFF0, 0xFFFE));
1388 DispatchTable table;
1389 DispatchTableConstructor cons(&table, false);
1390 cons.set_choice_index(0);
1391 cons.AddInverse(ranges);
1392 CHECK(!table.Get(0xFFFE)->Get(0));
1393 CHECK(table.Get(0xFFFF)->Get(0));
1394}
1395
1396
1397static uc32 canonicalize(uc32 c) {
1398 unibrow::uchar canon[unibrow::Ecma262Canonicalize::kMaxWidth];
1399 int count = unibrow::Ecma262Canonicalize::Convert(c, '\0', canon, NULL);
1400 if (count == 0) {
1401 return c;
1402 } else {
1403 CHECK_EQ(1, count);
1404 return canon[0];
1405 }
1406}
1407
1408
1409TEST(LatinCanonicalize) {
1410 unibrow::Mapping<unibrow::Ecma262UnCanonicalize> un_canonicalize;
1411 for (char lower = 'a'; lower <= 'z'; lower++) {
1412 char upper = lower + ('A' - 'a');
1413 CHECK_EQ(canonicalize(lower), canonicalize(upper));
1414 unibrow::uchar uncanon[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1415 int length = un_canonicalize.get(lower, '\0', uncanon);
1416 CHECK_EQ(2, length);
1417 CHECK_EQ(upper, uncanon[0]);
1418 CHECK_EQ(lower, uncanon[1]);
1419 }
1420 for (uc32 c = 128; c < (1 << 21); c++)
1421 CHECK_GE(canonicalize(c), 128);
1422 unibrow::Mapping<unibrow::ToUppercase> to_upper;
Ben Murdochbb769b22010-08-11 14:56:33 +01001423 // Canonicalization is only defined for the Basic Multilingual Plane.
1424 for (uc32 c = 0; c < (1 << 16); c++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001425 unibrow::uchar upper[unibrow::ToUppercase::kMaxWidth];
1426 int length = to_upper.get(c, '\0', upper);
1427 if (length == 0) {
1428 length = 1;
1429 upper[0] = c;
1430 }
1431 uc32 u = upper[0];
1432 if (length > 1 || (c >= 128 && u < 128))
1433 u = c;
1434 CHECK_EQ(u, canonicalize(c));
1435 }
1436}
1437
1438
Ben Murdochbb769b22010-08-11 14:56:33 +01001439static uc32 CanonRangeEnd(uc32 c) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001440 unibrow::uchar canon[unibrow::CanonicalizationRange::kMaxWidth];
1441 int count = unibrow::CanonicalizationRange::Convert(c, '\0', canon, NULL);
1442 if (count == 0) {
1443 return c;
1444 } else {
1445 CHECK_EQ(1, count);
1446 return canon[0];
1447 }
1448}
1449
1450
1451TEST(RangeCanonicalization) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001452 // Check that we arrive at the same result when using the basic
1453 // range canonicalization primitives as when using immediate
1454 // canonicalization.
1455 unibrow::Mapping<unibrow::Ecma262UnCanonicalize> un_canonicalize;
Ben Murdochbb769b22010-08-11 14:56:33 +01001456 int block_start = 0;
1457 while (block_start <= 0xFFFF) {
1458 uc32 block_end = CanonRangeEnd(block_start);
1459 unsigned block_length = block_end - block_start + 1;
1460 if (block_length > 1) {
1461 unibrow::uchar first[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1462 int first_length = un_canonicalize.get(block_start, '\0', first);
1463 for (unsigned i = 1; i < block_length; i++) {
1464 unibrow::uchar succ[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1465 int succ_length = un_canonicalize.get(block_start + i, '\0', succ);
1466 CHECK_EQ(first_length, succ_length);
1467 for (int j = 0; j < succ_length; j++) {
1468 int calc = first[j] + i;
1469 int found = succ[j];
1470 CHECK_EQ(calc, found);
1471 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001472 }
1473 }
Ben Murdochbb769b22010-08-11 14:56:33 +01001474 block_start = block_start + block_length;
Steve Blocka7e24c12009-10-30 11:49:00 +00001475 }
1476}
1477
1478
1479TEST(UncanonicalizeEquivalence) {
1480 unibrow::Mapping<unibrow::Ecma262UnCanonicalize> un_canonicalize;
1481 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1482 for (int i = 0; i < (1 << 16); i++) {
1483 int length = un_canonicalize.get(i, '\0', chars);
1484 for (int j = 0; j < length; j++) {
1485 unibrow::uchar chars2[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1486 int length2 = un_canonicalize.get(chars[j], '\0', chars2);
1487 CHECK_EQ(length, length2);
1488 for (int k = 0; k < length; k++)
1489 CHECK_EQ(static_cast<int>(chars[k]), static_cast<int>(chars2[k]));
1490 }
1491 }
1492}
1493
1494
1495static void TestRangeCaseIndependence(CharacterRange input,
1496 Vector<CharacterRange> expected) {
1497 ZoneScope zone_scope(DELETE_ON_EXIT);
1498 int count = expected.length();
1499 ZoneList<CharacterRange>* list = new ZoneList<CharacterRange>(count);
Steve Blockd0582a62009-12-15 09:54:21 +00001500 input.AddCaseEquivalents(list, false);
Steve Blocka7e24c12009-10-30 11:49:00 +00001501 CHECK_EQ(count, list->length());
1502 for (int i = 0; i < list->length(); i++) {
1503 CHECK_EQ(expected[i].from(), list->at(i).from());
1504 CHECK_EQ(expected[i].to(), list->at(i).to());
1505 }
1506}
1507
1508
1509static void TestSimpleRangeCaseIndependence(CharacterRange input,
1510 CharacterRange expected) {
1511 EmbeddedVector<CharacterRange, 1> vector;
1512 vector[0] = expected;
1513 TestRangeCaseIndependence(input, vector);
1514}
1515
1516
1517TEST(CharacterRangeCaseIndependence) {
Steve Block44f0eee2011-05-26 01:26:41 +01001518 v8::internal::V8::Initialize(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00001519 TestSimpleRangeCaseIndependence(CharacterRange::Singleton('a'),
1520 CharacterRange::Singleton('A'));
1521 TestSimpleRangeCaseIndependence(CharacterRange::Singleton('z'),
1522 CharacterRange::Singleton('Z'));
1523 TestSimpleRangeCaseIndependence(CharacterRange('a', 'z'),
1524 CharacterRange('A', 'Z'));
1525 TestSimpleRangeCaseIndependence(CharacterRange('c', 'f'),
1526 CharacterRange('C', 'F'));
1527 TestSimpleRangeCaseIndependence(CharacterRange('a', 'b'),
1528 CharacterRange('A', 'B'));
1529 TestSimpleRangeCaseIndependence(CharacterRange('y', 'z'),
1530 CharacterRange('Y', 'Z'));
1531 TestSimpleRangeCaseIndependence(CharacterRange('a' - 1, 'z' + 1),
1532 CharacterRange('A', 'Z'));
1533 TestSimpleRangeCaseIndependence(CharacterRange('A', 'Z'),
1534 CharacterRange('a', 'z'));
1535 TestSimpleRangeCaseIndependence(CharacterRange('C', 'F'),
1536 CharacterRange('c', 'f'));
1537 TestSimpleRangeCaseIndependence(CharacterRange('A' - 1, 'Z' + 1),
1538 CharacterRange('a', 'z'));
1539 // Here we need to add [l-z] to complete the case independence of
1540 // [A-Za-z] but we expect [a-z] to be added since we always add a
1541 // whole block at a time.
1542 TestSimpleRangeCaseIndependence(CharacterRange('A', 'k'),
1543 CharacterRange('a', 'z'));
1544}
1545
1546
1547static bool InClass(uc16 c, ZoneList<CharacterRange>* ranges) {
1548 if (ranges == NULL)
1549 return false;
1550 for (int i = 0; i < ranges->length(); i++) {
1551 CharacterRange range = ranges->at(i);
1552 if (range.from() <= c && c <= range.to())
1553 return true;
1554 }
1555 return false;
1556}
1557
1558
1559TEST(CharClassDifference) {
Steve Block44f0eee2011-05-26 01:26:41 +01001560 v8::internal::V8::Initialize(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00001561 ZoneScope zone_scope(DELETE_ON_EXIT);
1562 ZoneList<CharacterRange>* base = new ZoneList<CharacterRange>(1);
1563 base->Add(CharacterRange::Everything());
1564 Vector<const uc16> overlay = CharacterRange::GetWordBounds();
1565 ZoneList<CharacterRange>* included = NULL;
1566 ZoneList<CharacterRange>* excluded = NULL;
1567 CharacterRange::Split(base, overlay, &included, &excluded);
1568 for (int i = 0; i < (1 << 16); i++) {
1569 bool in_base = InClass(i, base);
1570 if (in_base) {
1571 bool in_overlay = false;
1572 for (int j = 0; !in_overlay && j < overlay.length(); j += 2) {
1573 if (overlay[j] <= i && i <= overlay[j+1])
1574 in_overlay = true;
1575 }
1576 CHECK_EQ(in_overlay, InClass(i, included));
1577 CHECK_EQ(!in_overlay, InClass(i, excluded));
1578 } else {
1579 CHECK(!InClass(i, included));
1580 CHECK(!InClass(i, excluded));
1581 }
1582 }
1583}
1584
1585
Leon Clarkee46be812010-01-19 14:06:41 +00001586TEST(CanonicalizeCharacterSets) {
Steve Block44f0eee2011-05-26 01:26:41 +01001587 v8::internal::V8::Initialize(NULL);
Leon Clarkee46be812010-01-19 14:06:41 +00001588 ZoneScope scope(DELETE_ON_EXIT);
1589 ZoneList<CharacterRange>* list = new ZoneList<CharacterRange>(4);
1590 CharacterSet set(list);
1591
1592 list->Add(CharacterRange(10, 20));
1593 list->Add(CharacterRange(30, 40));
1594 list->Add(CharacterRange(50, 60));
1595 set.Canonicalize();
1596 ASSERT_EQ(3, list->length());
1597 ASSERT_EQ(10, list->at(0).from());
1598 ASSERT_EQ(20, list->at(0).to());
1599 ASSERT_EQ(30, list->at(1).from());
1600 ASSERT_EQ(40, list->at(1).to());
1601 ASSERT_EQ(50, list->at(2).from());
1602 ASSERT_EQ(60, list->at(2).to());
1603
1604 list->Rewind(0);
1605 list->Add(CharacterRange(10, 20));
1606 list->Add(CharacterRange(50, 60));
1607 list->Add(CharacterRange(30, 40));
1608 set.Canonicalize();
1609 ASSERT_EQ(3, list->length());
1610 ASSERT_EQ(10, list->at(0).from());
1611 ASSERT_EQ(20, list->at(0).to());
1612 ASSERT_EQ(30, list->at(1).from());
1613 ASSERT_EQ(40, list->at(1).to());
1614 ASSERT_EQ(50, list->at(2).from());
1615 ASSERT_EQ(60, list->at(2).to());
1616
1617 list->Rewind(0);
1618 list->Add(CharacterRange(30, 40));
1619 list->Add(CharacterRange(10, 20));
1620 list->Add(CharacterRange(25, 25));
1621 list->Add(CharacterRange(100, 100));
1622 list->Add(CharacterRange(1, 1));
1623 set.Canonicalize();
1624 ASSERT_EQ(5, list->length());
1625 ASSERT_EQ(1, list->at(0).from());
1626 ASSERT_EQ(1, list->at(0).to());
1627 ASSERT_EQ(10, list->at(1).from());
1628 ASSERT_EQ(20, list->at(1).to());
1629 ASSERT_EQ(25, list->at(2).from());
1630 ASSERT_EQ(25, list->at(2).to());
1631 ASSERT_EQ(30, list->at(3).from());
1632 ASSERT_EQ(40, list->at(3).to());
1633 ASSERT_EQ(100, list->at(4).from());
1634 ASSERT_EQ(100, list->at(4).to());
1635
1636 list->Rewind(0);
1637 list->Add(CharacterRange(10, 19));
1638 list->Add(CharacterRange(21, 30));
1639 list->Add(CharacterRange(20, 20));
1640 set.Canonicalize();
1641 ASSERT_EQ(1, list->length());
1642 ASSERT_EQ(10, list->at(0).from());
1643 ASSERT_EQ(30, list->at(0).to());
1644}
1645
Leon Clarked91b9f72010-01-27 17:25:45 +00001646// Checks whether a character is in the set represented by a list of ranges.
1647static bool CharacterInSet(ZoneList<CharacterRange>* set, uc16 value) {
1648 for (int i = 0; i < set->length(); i++) {
1649 CharacterRange range = set->at(i);
1650 if (range.from() <= value && value <= range.to()) {
1651 return true;
1652 }
1653 }
1654 return false;
1655}
1656
1657TEST(CharacterRangeMerge) {
Steve Block44f0eee2011-05-26 01:26:41 +01001658 v8::internal::V8::Initialize(NULL);
Leon Clarked91b9f72010-01-27 17:25:45 +00001659 ZoneScope zone_scope(DELETE_ON_EXIT);
1660 ZoneList<CharacterRange> l1(4);
1661 ZoneList<CharacterRange> l2(4);
1662 // Create all combinations of intersections of ranges, both singletons and
1663 // longer.
1664
1665 int offset = 0;
1666
1667 // The five kinds of singleton intersections:
1668 // X
1669 // Y - outside before
1670 // Y - outside touching start
1671 // Y - overlap
1672 // Y - outside touching end
1673 // Y - outside after
1674
1675 for (int i = 0; i < 5; i++) {
1676 l1.Add(CharacterRange::Singleton(offset + 2));
1677 l2.Add(CharacterRange::Singleton(offset + i));
1678 offset += 6;
1679 }
1680
1681 // The seven kinds of singleton/non-singleton intersections:
1682 // XXX
1683 // Y - outside before
1684 // Y - outside touching start
1685 // Y - inside touching start
1686 // Y - entirely inside
1687 // Y - inside touching end
1688 // Y - outside touching end
1689 // Y - disjoint after
1690
1691 for (int i = 0; i < 7; i++) {
1692 l1.Add(CharacterRange::Range(offset + 2, offset + 4));
1693 l2.Add(CharacterRange::Singleton(offset + i));
1694 offset += 8;
1695 }
1696
1697 // The eleven kinds of non-singleton intersections:
1698 //
1699 // XXXXXXXX
1700 // YYYY - outside before.
1701 // YYYY - outside touching start.
1702 // YYYY - overlapping start
1703 // YYYY - inside touching start
1704 // YYYY - entirely inside
1705 // YYYY - inside touching end
1706 // YYYY - overlapping end
1707 // YYYY - outside touching end
1708 // YYYY - outside after
1709 // YYYYYYYY - identical
1710 // YYYYYYYYYYYY - containing entirely.
1711
1712 for (int i = 0; i < 9; i++) {
1713 l1.Add(CharacterRange::Range(offset + 6, offset + 15)); // Length 8.
1714 l2.Add(CharacterRange::Range(offset + 2 * i, offset + 2 * i + 3));
1715 offset += 22;
1716 }
1717 l1.Add(CharacterRange::Range(offset + 6, offset + 15));
1718 l2.Add(CharacterRange::Range(offset + 6, offset + 15));
1719 offset += 22;
1720 l1.Add(CharacterRange::Range(offset + 6, offset + 15));
1721 l2.Add(CharacterRange::Range(offset + 4, offset + 17));
1722 offset += 22;
1723
1724 // Different kinds of multi-range overlap:
1725 // XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX
1726 // YYYY Y YYYY Y YYYY Y YYYY Y YYYY Y YYYY Y
1727
1728 l1.Add(CharacterRange::Range(offset, offset + 21));
1729 l1.Add(CharacterRange::Range(offset + 31, offset + 52));
1730 for (int i = 0; i < 6; i++) {
1731 l2.Add(CharacterRange::Range(offset + 2, offset + 5));
1732 l2.Add(CharacterRange::Singleton(offset + 8));
1733 offset += 9;
1734 }
1735
1736 ASSERT(CharacterRange::IsCanonical(&l1));
1737 ASSERT(CharacterRange::IsCanonical(&l2));
1738
1739 ZoneList<CharacterRange> first_only(4);
1740 ZoneList<CharacterRange> second_only(4);
1741 ZoneList<CharacterRange> both(4);
1742
1743 // Merge one direction.
1744 CharacterRange::Merge(&l1, &l2, &first_only, &second_only, &both);
1745
1746 CHECK(CharacterRange::IsCanonical(&first_only));
1747 CHECK(CharacterRange::IsCanonical(&second_only));
1748 CHECK(CharacterRange::IsCanonical(&both));
1749
1750 for (uc16 i = 0; i < offset; i++) {
1751 bool in_first = CharacterInSet(&l1, i);
1752 bool in_second = CharacterInSet(&l2, i);
1753 CHECK((in_first && !in_second) == CharacterInSet(&first_only, i));
1754 CHECK((!in_first && in_second) == CharacterInSet(&second_only, i));
1755 CHECK((in_first && in_second) == CharacterInSet(&both, i));
1756 }
1757
1758 first_only.Clear();
1759 second_only.Clear();
1760 both.Clear();
1761
1762 // Merge other direction.
1763 CharacterRange::Merge(&l2, &l1, &second_only, &first_only, &both);
1764
1765 CHECK(CharacterRange::IsCanonical(&first_only));
1766 CHECK(CharacterRange::IsCanonical(&second_only));
1767 CHECK(CharacterRange::IsCanonical(&both));
1768
1769 for (uc16 i = 0; i < offset; i++) {
1770 bool in_first = CharacterInSet(&l1, i);
1771 bool in_second = CharacterInSet(&l2, i);
1772 CHECK((in_first && !in_second) == CharacterInSet(&first_only, i));
1773 CHECK((!in_first && in_second) == CharacterInSet(&second_only, i));
1774 CHECK((in_first && in_second) == CharacterInSet(&both, i));
1775 }
1776
1777 first_only.Clear();
1778 second_only.Clear();
1779 both.Clear();
1780
1781 // Merge but don't record all combinations.
1782 CharacterRange::Merge(&l1, &l2, NULL, NULL, &both);
1783
1784 CHECK(CharacterRange::IsCanonical(&both));
1785
1786 for (uc16 i = 0; i < offset; i++) {
1787 bool in_first = CharacterInSet(&l1, i);
1788 bool in_second = CharacterInSet(&l2, i);
1789 CHECK((in_first && in_second) == CharacterInSet(&both, i));
1790 }
1791
1792 // Merge into same set.
1793 ZoneList<CharacterRange> all(4);
1794 CharacterRange::Merge(&l1, &l2, &all, &all, &all);
1795
1796 CHECK(CharacterRange::IsCanonical(&all));
1797
1798 for (uc16 i = 0; i < offset; i++) {
1799 bool in_first = CharacterInSet(&l1, i);
1800 bool in_second = CharacterInSet(&l2, i);
1801 CHECK((in_first || in_second) == CharacterInSet(&all, i));
1802 }
1803}
Leon Clarkee46be812010-01-19 14:06:41 +00001804
1805
Steve Blocka7e24c12009-10-30 11:49:00 +00001806TEST(Graph) {
1807 V8::Initialize(NULL);
Leon Clarkee46be812010-01-19 14:06:41 +00001808 Execute("\\b\\w+\\b", false, true, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001809}