blob: 39856b67612094866a3df1cc88185fa56351f37d [file] [log] [blame]
Ben Murdoch8b112d22011-06-08 16:22:53 +01001// Copyright 2011 the V8 project authors. All rights reserved.
Steve Blockd0582a62009-12-15 09:54:21 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include <stdlib.h>
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080029#include <stdio.h>
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080030#include <string.h>
Steve Blockd0582a62009-12-15 09:54:21 +000031
32#include "v8.h"
33
Steve Block44f0eee2011-05-26 01:26:41 +010034#include "isolate.h"
Steve Blockd0582a62009-12-15 09:54:21 +000035#include "token.h"
36#include "scanner.h"
Iain Merrick9ac36c92010-09-13 15:29:50 +010037#include "parser.h"
Steve Blockd0582a62009-12-15 09:54:21 +000038#include "utils.h"
Iain Merrick9ac36c92010-09-13 15:29:50 +010039#include "execution.h"
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080040#include "preparser.h"
Steve Blockd0582a62009-12-15 09:54:21 +000041#include "cctest.h"
42
43namespace i = ::v8::internal;
44
45TEST(KeywordMatcher) {
46 struct KeywordToken {
47 const char* keyword;
48 i::Token::Value token;
49 };
50
51 static const KeywordToken keywords[] = {
52#define KEYWORD(t, s, d) { s, i::Token::t },
53#define IGNORE(t, s, d) /* */
54 TOKEN_LIST(IGNORE, KEYWORD, IGNORE)
55#undef KEYWORD
56 { NULL, i::Token::IDENTIFIER }
57 };
58
59 static const char* future_keywords[] = {
60#define FUTURE(t, s, d) s,
61 TOKEN_LIST(IGNORE, IGNORE, FUTURE)
62#undef FUTURE
63#undef IGNORE
64 NULL
65 };
66
67 KeywordToken key_token;
68 for (int i = 0; (key_token = keywords[i]).keyword != NULL; i++) {
69 i::KeywordMatcher matcher;
70 const char* keyword = key_token.keyword;
71 int length = i::StrLength(keyword);
72 for (int j = 0; j < length; j++) {
73 if (key_token.token == i::Token::INSTANCEOF && j == 2) {
74 // "in" is a prefix of "instanceof". It's the only keyword
75 // that is a prefix of another.
76 CHECK_EQ(i::Token::IN, matcher.token());
77 } else {
78 CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
79 }
80 matcher.AddChar(keyword[j]);
81 }
82 CHECK_EQ(key_token.token, matcher.token());
83 // Adding more characters will make keyword matching fail.
84 matcher.AddChar('z');
85 CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
86 // Adding a keyword later will not make it match again.
87 matcher.AddChar('i');
88 matcher.AddChar('f');
89 CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
90 }
91
92 // Future keywords are not recognized.
93 const char* future_keyword;
94 for (int i = 0; (future_keyword = future_keywords[i]) != NULL; i++) {
95 i::KeywordMatcher matcher;
96 int length = i::StrLength(future_keyword);
97 for (int j = 0; j < length; j++) {
98 matcher.AddChar(future_keyword[j]);
99 }
100 CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
101 }
102
103 // Zero isn't ignored at first.
104 i::KeywordMatcher bad_start;
105 bad_start.AddChar(0);
106 CHECK_EQ(i::Token::IDENTIFIER, bad_start.token());
107 bad_start.AddChar('i');
108 bad_start.AddChar('f');
109 CHECK_EQ(i::Token::IDENTIFIER, bad_start.token());
110
111 // Zero isn't ignored at end.
112 i::KeywordMatcher bad_end;
113 bad_end.AddChar('i');
114 bad_end.AddChar('f');
115 CHECK_EQ(i::Token::IF, bad_end.token());
116 bad_end.AddChar(0);
117 CHECK_EQ(i::Token::IDENTIFIER, bad_end.token());
118
119 // Case isn't ignored.
120 i::KeywordMatcher bad_case;
121 bad_case.AddChar('i');
122 bad_case.AddChar('F');
123 CHECK_EQ(i::Token::IDENTIFIER, bad_case.token());
124
125 // If we mark it as failure, continuing won't help.
126 i::KeywordMatcher full_stop;
127 full_stop.AddChar('i');
128 CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
129 full_stop.Fail();
130 CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
131 full_stop.AddChar('f');
132 CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
133}
134
Iain Merrick9ac36c92010-09-13 15:29:50 +0100135
136TEST(ScanHTMLEndComments) {
137 // Regression test. See:
138 // http://code.google.com/p/chromium/issues/detail?id=53548
139 // Tests that --> is correctly interpreted as comment-to-end-of-line if there
140 // is only whitespace before it on the line, even after a multiline-comment
141 // comment. This was not the case if it occurred before the first real token
142 // in the input.
143 const char* tests[] = {
144 // Before first real token.
145 "--> is eol-comment\nvar y = 37;\n",
146 "\n --> is eol-comment\nvar y = 37;\n",
147 "/* precomment */ --> is eol-comment\nvar y = 37;\n",
148 "\n/* precomment */ --> is eol-comment\nvar y = 37;\n",
149 // After first real token.
150 "var x = 42;\n--> is eol-comment\nvar y = 37;\n",
151 "var x = 42;\n/* precomment */ --> is eol-comment\nvar y = 37;\n",
152 NULL
153 };
154
155 // Parser/Scanner needs a stack limit.
156 int marker;
Steve Block44f0eee2011-05-26 01:26:41 +0100157 i::Isolate::Current()->stack_guard()->SetStackLimit(
Iain Merrick9ac36c92010-09-13 15:29:50 +0100158 reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);
159
160 for (int i = 0; tests[i]; i++) {
161 v8::ScriptData* data =
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100162 v8::ScriptData::PreCompile(tests[i], i::StrLength(tests[i]));
Iain Merrick9ac36c92010-09-13 15:29:50 +0100163 CHECK(data != NULL && !data->HasError());
164 delete data;
165 }
166}
167
168
169class ScriptResource : public v8::String::ExternalAsciiStringResource {
170 public:
171 ScriptResource(const char* data, size_t length)
172 : data_(data), length_(length) { }
173
174 const char* data() const { return data_; }
175 size_t length() const { return length_; }
176
177 private:
178 const char* data_;
179 size_t length_;
180};
181
182
183TEST(Preparsing) {
184 v8::HandleScope handles;
185 v8::Persistent<v8::Context> context = v8::Context::New();
186 v8::Context::Scope context_scope(context);
187 int marker;
Steve Block44f0eee2011-05-26 01:26:41 +0100188 i::Isolate::Current()->stack_guard()->SetStackLimit(
Iain Merrick9ac36c92010-09-13 15:29:50 +0100189 reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);
190
191 // Source containing functions that might be lazily compiled and all types
192 // of symbols (string, propertyName, regexp).
193 const char* source =
194 "var x = 42;"
195 "function foo(a) { return function nolazy(b) { return a + b; } }"
196 "function bar(a) { if (a) return function lazy(b) { return b; } }"
197 "var z = {'string': 'string literal', bareword: 'propertyName', "
198 " 42: 'number literal', for: 'keyword as propertyName', "
199 " f\\u006fr: 'keyword propertyname with escape'};"
200 "var v = /RegExp Literal/;"
201 "var w = /RegExp Literal\\u0020With Escape/gin;"
202 "var y = { get getter() { return 42; }, "
203 " set setter(v) { this.value = v; }};";
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100204 int source_length = i::StrLength(source);
Iain Merrick9ac36c92010-09-13 15:29:50 +0100205 const char* error_source = "var x = y z;";
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100206 int error_source_length = i::StrLength(error_source);
Iain Merrick9ac36c92010-09-13 15:29:50 +0100207
208 v8::ScriptData* preparse =
209 v8::ScriptData::PreCompile(source, source_length);
210 CHECK(!preparse->HasError());
211 bool lazy_flag = i::FLAG_lazy;
212 {
213 i::FLAG_lazy = true;
214 ScriptResource* resource = new ScriptResource(source, source_length);
215 v8::Local<v8::String> script_source = v8::String::NewExternal(resource);
216 v8::Script::Compile(script_source, NULL, preparse);
217 }
218
219 {
220 i::FLAG_lazy = false;
221
222 ScriptResource* resource = new ScriptResource(source, source_length);
223 v8::Local<v8::String> script_source = v8::String::NewExternal(resource);
224 v8::Script::New(script_source, NULL, preparse, v8::Local<v8::String>());
225 }
226 delete preparse;
227 i::FLAG_lazy = lazy_flag;
228
229 // Syntax error.
230 v8::ScriptData* error_preparse =
231 v8::ScriptData::PreCompile(error_source, error_source_length);
232 CHECK(error_preparse->HasError());
233 i::ScriptDataImpl *pre_impl =
234 reinterpret_cast<i::ScriptDataImpl*>(error_preparse);
235 i::Scanner::Location error_location =
236 pre_impl->MessageLocation();
237 // Error is at "z" in source, location 10..11.
238 CHECK_EQ(10, error_location.beg_pos);
239 CHECK_EQ(11, error_location.end_pos);
240 // Should not crash.
241 const char* message = pre_impl->BuildMessage();
242 i::Vector<const char*> args = pre_impl->BuildArgs();
243 CHECK_GT(strlen(message), 0);
244}
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800245
246
247TEST(StandAlonePreParser) {
248 int marker;
Steve Block44f0eee2011-05-26 01:26:41 +0100249 i::Isolate::Current()->stack_guard()->SetStackLimit(
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800250 reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);
251
252 const char* programs[] = {
253 "{label: 42}",
254 "var x = 42;",
255 "function foo(x, y) { return x + y; }",
256 "native function foo(); return %ArgleBargle(glop);",
257 "var x = new new Function('this.x = 42');",
258 NULL
259 };
260
Ben Murdoch8b112d22011-06-08 16:22:53 +0100261 uintptr_t stack_limit = i::Isolate::Current()->stack_guard()->real_climit();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800262 for (int i = 0; programs[i]; i++) {
263 const char* program = programs[i];
Ben Murdochb0fe1622011-05-05 13:52:32 +0100264 i::Utf8ToUC16CharacterStream stream(
265 reinterpret_cast<const i::byte*>(program),
266 static_cast<unsigned>(strlen(program)));
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800267 i::CompleteParserRecorder log;
Ben Murdoch8b112d22011-06-08 16:22:53 +0100268 i::V8JavaScriptScanner scanner(i::Isolate::Current()->unicode_cache());
Ben Murdochb0fe1622011-05-05 13:52:32 +0100269 scanner.Initialize(&stream);
270
271 v8::preparser::PreParser::PreParseResult result =
272 v8::preparser::PreParser::PreParseProgram(&scanner,
273 &log,
274 true,
275 stack_limit);
276 CHECK_EQ(v8::preparser::PreParser::kPreParseSuccess, result);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800277 i::ScriptDataImpl data(log.ExtractData());
278 CHECK(!data.has_error());
279 }
280}
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800281
282
283TEST(RegressChromium62639) {
284 int marker;
Ben Murdoch8b112d22011-06-08 16:22:53 +0100285 i::Isolate::Current()->stack_guard()->SetStackLimit(
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800286 reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);
287
288 const char* program = "var x = 'something';\n"
289 "escape: function() {}";
290 // Fails parsing expecting an identifier after "function".
291 // Before fix, didn't check *ok after Expect(Token::Identifier, ok),
292 // and then used the invalid currently scanned literal. This always
293 // failed in debug mode, and sometimes crashed in release mode.
294
Ben Murdochb0fe1622011-05-05 13:52:32 +0100295 i::Utf8ToUC16CharacterStream stream(reinterpret_cast<const i::byte*>(program),
296 static_cast<unsigned>(strlen(program)));
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800297 i::ScriptDataImpl* data =
Ben Murdochb0fe1622011-05-05 13:52:32 +0100298 i::ParserApi::PreParse(&stream, NULL);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800299 CHECK(data->HasError());
300 delete data;
301}
302
303
304TEST(Regress928) {
305 // Preparsing didn't consider the catch clause of a try statement
306 // as with-content, which made it assume that a function inside
307 // the block could be lazily compiled, and an extra, unexpected,
308 // entry was added to the data.
309 int marker;
Ben Murdoch8b112d22011-06-08 16:22:53 +0100310 i::Isolate::Current()->stack_guard()->SetStackLimit(
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800311 reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);
312
313 const char* program =
314 "try { } catch (e) { var foo = function () { /* first */ } }"
315 "var bar = function () { /* second */ }";
316
Ben Murdochb0fe1622011-05-05 13:52:32 +0100317 i::Utf8ToUC16CharacterStream stream(reinterpret_cast<const i::byte*>(program),
318 static_cast<unsigned>(strlen(program)));
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800319 i::ScriptDataImpl* data =
Ben Murdochb0fe1622011-05-05 13:52:32 +0100320 i::ParserApi::PartialPreParse(&stream, NULL);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800321 CHECK(!data->HasError());
322
323 data->Initialize();
324
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100325 int first_function =
326 static_cast<int>(strstr(program, "function") - program);
327 int first_lbrace = first_function + static_cast<int>(strlen("function () "));
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800328 CHECK_EQ('{', program[first_lbrace]);
329 i::FunctionEntry entry1 = data->GetFunctionEntry(first_lbrace);
330 CHECK(!entry1.is_valid());
331
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100332 int second_function =
333 static_cast<int>(strstr(program + first_lbrace, "function") - program);
334 int second_lbrace =
335 second_function + static_cast<int>(strlen("function () "));
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800336 CHECK_EQ('{', program[second_lbrace]);
337 i::FunctionEntry entry2 = data->GetFunctionEntry(second_lbrace);
338 CHECK(entry2.is_valid());
339 CHECK_EQ('}', program[entry2.end_pos() - 1]);
340 delete data;
341}
Ben Murdochb0fe1622011-05-05 13:52:32 +0100342
343
344TEST(PreParseOverflow) {
345 int marker;
Ben Murdoch8b112d22011-06-08 16:22:53 +0100346 i::Isolate::Current()->stack_guard()->SetStackLimit(
Ben Murdochb0fe1622011-05-05 13:52:32 +0100347 reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);
348
349 size_t kProgramSize = 1024 * 1024;
350 i::SmartPointer<char> program(
351 reinterpret_cast<char*>(malloc(kProgramSize + 1)));
352 memset(*program, '(', kProgramSize);
353 program[kProgramSize] = '\0';
354
Ben Murdoch8b112d22011-06-08 16:22:53 +0100355 uintptr_t stack_limit = i::Isolate::Current()->stack_guard()->real_climit();
Ben Murdochb0fe1622011-05-05 13:52:32 +0100356
357 i::Utf8ToUC16CharacterStream stream(
358 reinterpret_cast<const i::byte*>(*program),
359 static_cast<unsigned>(kProgramSize));
360 i::CompleteParserRecorder log;
Ben Murdoch8b112d22011-06-08 16:22:53 +0100361 i::V8JavaScriptScanner scanner(i::Isolate::Current()->unicode_cache());
Ben Murdochb0fe1622011-05-05 13:52:32 +0100362 scanner.Initialize(&stream);
363
364
365 v8::preparser::PreParser::PreParseResult result =
366 v8::preparser::PreParser::PreParseProgram(&scanner,
367 &log,
368 true,
369 stack_limit);
370 CHECK_EQ(v8::preparser::PreParser::kPreParseStackOverflow, result);
371}
372
373
374class TestExternalResource: public v8::String::ExternalStringResource {
375 public:
376 explicit TestExternalResource(uint16_t* data, int length)
377 : data_(data), length_(static_cast<size_t>(length)) { }
378
379 ~TestExternalResource() { }
380
381 const uint16_t* data() const {
382 return data_;
383 }
384
385 size_t length() const {
386 return length_;
387 }
388 private:
389 uint16_t* data_;
390 size_t length_;
391};
392
393
394#define CHECK_EQU(v1, v2) CHECK_EQ(static_cast<int>(v1), static_cast<int>(v2))
395
396void TestCharacterStream(const char* ascii_source,
397 unsigned length,
398 unsigned start = 0,
399 unsigned end = 0) {
400 if (end == 0) end = length;
401 unsigned sub_length = end - start;
402 i::HandleScope test_scope;
403 i::SmartPointer<i::uc16> uc16_buffer(new i::uc16[length]);
404 for (unsigned i = 0; i < length; i++) {
405 uc16_buffer[i] = static_cast<i::uc16>(ascii_source[i]);
406 }
407 i::Vector<const char> ascii_vector(ascii_source, static_cast<int>(length));
408 i::Handle<i::String> ascii_string(
Steve Block44f0eee2011-05-26 01:26:41 +0100409 FACTORY->NewStringFromAscii(ascii_vector));
Ben Murdochb0fe1622011-05-05 13:52:32 +0100410 TestExternalResource resource(*uc16_buffer, length);
411 i::Handle<i::String> uc16_string(
Steve Block44f0eee2011-05-26 01:26:41 +0100412 FACTORY->NewExternalStringFromTwoByte(&resource));
Ben Murdochb0fe1622011-05-05 13:52:32 +0100413
414 i::ExternalTwoByteStringUC16CharacterStream uc16_stream(
415 i::Handle<i::ExternalTwoByteString>::cast(uc16_string), start, end);
416 i::GenericStringUC16CharacterStream string_stream(ascii_string, start, end);
417 i::Utf8ToUC16CharacterStream utf8_stream(
418 reinterpret_cast<const i::byte*>(ascii_source), end);
419 utf8_stream.SeekForward(start);
420
421 unsigned i = start;
422 while (i < end) {
423 // Read streams one char at a time
424 CHECK_EQU(i, uc16_stream.pos());
425 CHECK_EQU(i, string_stream.pos());
426 CHECK_EQU(i, utf8_stream.pos());
427 int32_t c0 = ascii_source[i];
428 int32_t c1 = uc16_stream.Advance();
429 int32_t c2 = string_stream.Advance();
430 int32_t c3 = utf8_stream.Advance();
431 i++;
432 CHECK_EQ(c0, c1);
433 CHECK_EQ(c0, c2);
434 CHECK_EQ(c0, c3);
435 CHECK_EQU(i, uc16_stream.pos());
436 CHECK_EQU(i, string_stream.pos());
437 CHECK_EQU(i, utf8_stream.pos());
438 }
439 while (i > start + sub_length / 4) {
440 // Pushback, re-read, pushback again.
441 int32_t c0 = ascii_source[i - 1];
442 CHECK_EQU(i, uc16_stream.pos());
443 CHECK_EQU(i, string_stream.pos());
444 CHECK_EQU(i, utf8_stream.pos());
445 uc16_stream.PushBack(c0);
446 string_stream.PushBack(c0);
447 utf8_stream.PushBack(c0);
448 i--;
449 CHECK_EQU(i, uc16_stream.pos());
450 CHECK_EQU(i, string_stream.pos());
451 CHECK_EQU(i, utf8_stream.pos());
452 int32_t c1 = uc16_stream.Advance();
453 int32_t c2 = string_stream.Advance();
454 int32_t c3 = utf8_stream.Advance();
455 i++;
456 CHECK_EQU(i, uc16_stream.pos());
457 CHECK_EQU(i, string_stream.pos());
458 CHECK_EQU(i, utf8_stream.pos());
459 CHECK_EQ(c0, c1);
460 CHECK_EQ(c0, c2);
461 CHECK_EQ(c0, c3);
462 uc16_stream.PushBack(c0);
463 string_stream.PushBack(c0);
464 utf8_stream.PushBack(c0);
465 i--;
466 CHECK_EQU(i, uc16_stream.pos());
467 CHECK_EQU(i, string_stream.pos());
468 CHECK_EQU(i, utf8_stream.pos());
469 }
470 unsigned halfway = start + sub_length / 2;
471 uc16_stream.SeekForward(halfway - i);
472 string_stream.SeekForward(halfway - i);
473 utf8_stream.SeekForward(halfway - i);
474 i = halfway;
475 CHECK_EQU(i, uc16_stream.pos());
476 CHECK_EQU(i, string_stream.pos());
477 CHECK_EQU(i, utf8_stream.pos());
478
479 while (i < end) {
480 // Read streams one char at a time
481 CHECK_EQU(i, uc16_stream.pos());
482 CHECK_EQU(i, string_stream.pos());
483 CHECK_EQU(i, utf8_stream.pos());
484 int32_t c0 = ascii_source[i];
485 int32_t c1 = uc16_stream.Advance();
486 int32_t c2 = string_stream.Advance();
487 int32_t c3 = utf8_stream.Advance();
488 i++;
489 CHECK_EQ(c0, c1);
490 CHECK_EQ(c0, c2);
491 CHECK_EQ(c0, c3);
492 CHECK_EQU(i, uc16_stream.pos());
493 CHECK_EQU(i, string_stream.pos());
494 CHECK_EQU(i, utf8_stream.pos());
495 }
496
497 int32_t c1 = uc16_stream.Advance();
498 int32_t c2 = string_stream.Advance();
499 int32_t c3 = utf8_stream.Advance();
500 CHECK_LT(c1, 0);
501 CHECK_LT(c2, 0);
502 CHECK_LT(c3, 0);
503}
504
505
506TEST(CharacterStreams) {
507 v8::HandleScope handles;
508 v8::Persistent<v8::Context> context = v8::Context::New();
509 v8::Context::Scope context_scope(context);
510
511 TestCharacterStream("abc\0\n\r\x7f", 7);
512 static const unsigned kBigStringSize = 4096;
513 char buffer[kBigStringSize + 1];
514 for (unsigned i = 0; i < kBigStringSize; i++) {
515 buffer[i] = static_cast<char>(i & 0x7f);
516 }
517 TestCharacterStream(buffer, kBigStringSize);
518
519 TestCharacterStream(buffer, kBigStringSize, 576, 3298);
520
521 TestCharacterStream("\0", 1);
522 TestCharacterStream("", 0);
523}
524
525
526TEST(Utf8CharacterStream) {
527 static const unsigned kMaxUC16CharU = unibrow::Utf8::kMaxThreeByteChar;
528 static const int kMaxUC16Char = static_cast<int>(kMaxUC16CharU);
529
530 static const int kAllUtf8CharsSize =
531 (unibrow::Utf8::kMaxOneByteChar + 1) +
532 (unibrow::Utf8::kMaxTwoByteChar - unibrow::Utf8::kMaxOneByteChar) * 2 +
533 (unibrow::Utf8::kMaxThreeByteChar - unibrow::Utf8::kMaxTwoByteChar) * 3;
534 static const unsigned kAllUtf8CharsSizeU =
535 static_cast<unsigned>(kAllUtf8CharsSize);
536
537 char buffer[kAllUtf8CharsSizeU];
538 unsigned cursor = 0;
539 for (int i = 0; i <= kMaxUC16Char; i++) {
540 cursor += unibrow::Utf8::Encode(buffer + cursor, i);
541 }
542 ASSERT(cursor == kAllUtf8CharsSizeU);
543
544 i::Utf8ToUC16CharacterStream stream(reinterpret_cast<const i::byte*>(buffer),
545 kAllUtf8CharsSizeU);
546 for (int i = 0; i <= kMaxUC16Char; i++) {
547 CHECK_EQU(i, stream.pos());
548 int32_t c = stream.Advance();
549 CHECK_EQ(i, c);
550 CHECK_EQU(i + 1, stream.pos());
551 }
552 for (int i = kMaxUC16Char; i >= 0; i--) {
553 CHECK_EQU(i + 1, stream.pos());
554 stream.PushBack(i);
555 CHECK_EQU(i, stream.pos());
556 }
557 int i = 0;
558 while (stream.pos() < kMaxUC16CharU) {
559 CHECK_EQU(i, stream.pos());
560 unsigned progress = stream.SeekForward(12);
561 i += progress;
562 int32_t c = stream.Advance();
563 if (i <= kMaxUC16Char) {
564 CHECK_EQ(i, c);
565 } else {
566 CHECK_EQ(-1, c);
567 }
568 i += 1;
569 CHECK_EQU(i, stream.pos());
570 }
571}
572
573#undef CHECK_EQU
574
575void TestStreamScanner(i::UC16CharacterStream* stream,
576 i::Token::Value* expected_tokens,
577 int skip_pos = 0, // Zero means not skipping.
578 int skip_to = 0) {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100579 i::V8JavaScriptScanner scanner(i::Isolate::Current()->unicode_cache());
Steve Block9fac8402011-05-12 15:51:54 +0100580 scanner.Initialize(stream);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100581
582 int i = 0;
583 do {
584 i::Token::Value expected = expected_tokens[i];
585 i::Token::Value actual = scanner.Next();
586 CHECK_EQ(i::Token::String(expected), i::Token::String(actual));
587 if (scanner.location().end_pos == skip_pos) {
588 scanner.SeekForward(skip_to);
589 }
590 i++;
591 } while (expected_tokens[i] != i::Token::ILLEGAL);
592}
593
594TEST(StreamScanner) {
595 const char* str1 = "{ foo get for : */ <- \n\n /*foo*/ bib";
596 i::Utf8ToUC16CharacterStream stream1(reinterpret_cast<const i::byte*>(str1),
597 static_cast<unsigned>(strlen(str1)));
598 i::Token::Value expectations1[] = {
599 i::Token::LBRACE,
600 i::Token::IDENTIFIER,
601 i::Token::IDENTIFIER,
602 i::Token::FOR,
603 i::Token::COLON,
604 i::Token::MUL,
605 i::Token::DIV,
606 i::Token::LT,
607 i::Token::SUB,
608 i::Token::IDENTIFIER,
609 i::Token::EOS,
610 i::Token::ILLEGAL
611 };
612 TestStreamScanner(&stream1, expectations1, 0, 0);
613
614 const char* str2 = "case default const {THIS\nPART\nSKIPPED} do";
615 i::Utf8ToUC16CharacterStream stream2(reinterpret_cast<const i::byte*>(str2),
616 static_cast<unsigned>(strlen(str2)));
617 i::Token::Value expectations2[] = {
618 i::Token::CASE,
619 i::Token::DEFAULT,
620 i::Token::CONST,
621 i::Token::LBRACE,
622 // Skipped part here
623 i::Token::RBRACE,
624 i::Token::DO,
625 i::Token::EOS,
626 i::Token::ILLEGAL
627 };
628 ASSERT_EQ('{', str2[19]);
629 ASSERT_EQ('}', str2[37]);
630 TestStreamScanner(&stream2, expectations2, 20, 37);
631
632 const char* str3 = "{}}}}";
633 i::Token::Value expectations3[] = {
634 i::Token::LBRACE,
635 i::Token::RBRACE,
636 i::Token::RBRACE,
637 i::Token::RBRACE,
638 i::Token::RBRACE,
639 i::Token::EOS,
640 i::Token::ILLEGAL
641 };
642 // Skip zero-four RBRACEs.
643 for (int i = 0; i <= 4; i++) {
644 expectations3[6 - i] = i::Token::ILLEGAL;
645 expectations3[5 - i] = i::Token::EOS;
646 i::Utf8ToUC16CharacterStream stream3(
647 reinterpret_cast<const i::byte*>(str3),
648 static_cast<unsigned>(strlen(str3)));
649 TestStreamScanner(&stream3, expectations3, 1, 1 + i);
650 }
651}
Ben Murdoch086aeea2011-05-13 15:57:08 +0100652
653
654void TestScanRegExp(const char* re_source, const char* expected) {
655 i::Utf8ToUC16CharacterStream stream(
656 reinterpret_cast<const i::byte*>(re_source),
657 static_cast<unsigned>(strlen(re_source)));
Ben Murdoch8b112d22011-06-08 16:22:53 +0100658 i::V8JavaScriptScanner scanner(i::Isolate::Current()->unicode_cache());
Ben Murdoch086aeea2011-05-13 15:57:08 +0100659 scanner.Initialize(&stream);
660
661 i::Token::Value start = scanner.peek();
662 CHECK(start == i::Token::DIV || start == i::Token::ASSIGN_DIV);
663 CHECK(scanner.ScanRegExpPattern(start == i::Token::ASSIGN_DIV));
664 scanner.Next(); // Current token is now the regexp literal.
665 CHECK(scanner.is_literal_ascii());
666 i::Vector<const char> actual = scanner.literal_ascii_string();
667 for (int i = 0; i < actual.length(); i++) {
668 CHECK_NE('\0', expected[i]);
669 CHECK_EQ(expected[i], actual[i]);
670 }
671}
672
673
674TEST(RegExpScanning) {
675 // RegExp token with added garbage at the end. The scanner should only
676 // scan the RegExp until the terminating slash just before "flipperwald".
677 TestScanRegExp("/b/flipperwald", "b");
678 // Incomplete escape sequences doesn't hide the terminating slash.
679 TestScanRegExp("/\\x/flipperwald", "\\x");
680 TestScanRegExp("/\\u/flipperwald", "\\u");
681 TestScanRegExp("/\\u1/flipperwald", "\\u1");
682 TestScanRegExp("/\\u12/flipperwald", "\\u12");
683 TestScanRegExp("/\\u123/flipperwald", "\\u123");
684 TestScanRegExp("/\\c/flipperwald", "\\c");
685 TestScanRegExp("/\\c//flipperwald", "\\c");
686 // Slashes inside character classes are not terminating.
687 TestScanRegExp("/[/]/flipperwald", "[/]");
688 TestScanRegExp("/[\\s-/]/flipperwald", "[\\s-/]");
689 // Incomplete escape sequences inside a character class doesn't hide
690 // the end of the character class.
691 TestScanRegExp("/[\\c/]/flipperwald", "[\\c/]");
692 TestScanRegExp("/[\\c]/flipperwald", "[\\c]");
693 TestScanRegExp("/[\\x]/flipperwald", "[\\x]");
694 TestScanRegExp("/[\\x1]/flipperwald", "[\\x1]");
695 TestScanRegExp("/[\\u]/flipperwald", "[\\u]");
696 TestScanRegExp("/[\\u1]/flipperwald", "[\\u1]");
697 TestScanRegExp("/[\\u12]/flipperwald", "[\\u12]");
698 TestScanRegExp("/[\\u123]/flipperwald", "[\\u123]");
699 // Escaped ']'s wont end the character class.
700 TestScanRegExp("/[\\]/]/flipperwald", "[\\]/]");
701 // Escaped slashes are not terminating.
702 TestScanRegExp("/\\//flipperwald", "\\/");
703 // Starting with '=' works too.
704 TestScanRegExp("/=/", "=");
705 TestScanRegExp("/=?/", "=?");
706}