blob: a28c235c5e3f036049c8cdf32d6ba6fedcdcacd1 [file] [log] [blame]
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "src/v8.h"
#include "src/ast/ast.h"
#include "src/ast/ast-numbering.h"
#include "src/ast/ast-value-factory.h"
#include "src/compiler.h"
#include "src/execution.h"
#include "src/isolate.h"
#include "src/objects.h"
#include "src/parsing/parser.h"
#include "src/parsing/preparser.h"
#include "src/parsing/rewriter.h"
#include "src/parsing/scanner-character-streams.h"
#include "src/parsing/token.h"
#include "src/utils.h"
#include "test/cctest/cctest.h"
TEST(ScanKeywords) {
struct KeywordToken {
const char* keyword;
i::Token::Value token;
};
static const KeywordToken keywords[] = {
#define KEYWORD(t, s, d) { s, i::Token::t },
TOKEN_LIST(IGNORE_TOKEN, KEYWORD)
#undef KEYWORD
{ NULL, i::Token::IDENTIFIER }
};
KeywordToken key_token;
i::UnicodeCache unicode_cache;
i::byte buffer[32];
for (int i = 0; (key_token = keywords[i]).keyword != NULL; i++) {
const i::byte* keyword =
reinterpret_cast<const i::byte*>(key_token.keyword);
int length = i::StrLength(key_token.keyword);
CHECK(static_cast<int>(sizeof(buffer)) >= length);
{
i::Utf8ToUtf16CharacterStream stream(keyword, length);
i::Scanner scanner(&unicode_cache);
scanner.Initialize(&stream);
CHECK_EQ(key_token.token, scanner.Next());
CHECK_EQ(i::Token::EOS, scanner.Next());
}
// Removing characters will make keyword matching fail.
{
i::Utf8ToUtf16CharacterStream stream(keyword, length - 1);
i::Scanner scanner(&unicode_cache);
scanner.Initialize(&stream);
CHECK_EQ(i::Token::IDENTIFIER, scanner.Next());
CHECK_EQ(i::Token::EOS, scanner.Next());
}
// Adding characters will make keyword matching fail.
static const char chars_to_append[] = { 'z', '0', '_' };
for (int j = 0; j < static_cast<int>(arraysize(chars_to_append)); ++j) {
i::MemMove(buffer, keyword, length);
buffer[length] = chars_to_append[j];
i::Utf8ToUtf16CharacterStream stream(buffer, length + 1);
i::Scanner scanner(&unicode_cache);
scanner.Initialize(&stream);
CHECK_EQ(i::Token::IDENTIFIER, scanner.Next());
CHECK_EQ(i::Token::EOS, scanner.Next());
}
// Replacing characters will make keyword matching fail.
{
i::MemMove(buffer, keyword, length);
buffer[length - 1] = '_';
i::Utf8ToUtf16CharacterStream stream(buffer, length);
i::Scanner scanner(&unicode_cache);
scanner.Initialize(&stream);
CHECK_EQ(i::Token::IDENTIFIER, scanner.Next());
CHECK_EQ(i::Token::EOS, scanner.Next());
}
}
}
TEST(ScanHTMLEndComments) {
v8::V8::Initialize();
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope handles(isolate);
// Regression test. See:
// http://code.google.com/p/chromium/issues/detail?id=53548
// Tests that --> is correctly interpreted as comment-to-end-of-line if there
// is only whitespace before it on the line (with comments considered as
// whitespace, even a multiline-comment containing a newline).
// This was not the case if it occurred before the first real token
// in the input.
const char* tests[] = {
// Before first real token.
"--> is eol-comment\nvar y = 37;\n",
"\n --> is eol-comment\nvar y = 37;\n",
"/* precomment */ --> is eol-comment\nvar y = 37;\n",
"\n/* precomment */ --> is eol-comment\nvar y = 37;\n",
// After first real token.
"var x = 42;\n--> is eol-comment\nvar y = 37;\n",
"var x = 42;\n/* precomment */ --> is eol-comment\nvar y = 37;\n",
NULL
};
const char* fail_tests[] = {
"x --> is eol-comment\nvar y = 37;\n",
"\"\\n\" --> is eol-comment\nvar y = 37;\n",
"x/* precomment */ --> is eol-comment\nvar y = 37;\n",
"x/* precomment\n */ --> is eol-comment\nvar y = 37;\n",
"var x = 42; --> is eol-comment\nvar y = 37;\n",
"var x = 42; /* precomment\n */ --> is eol-comment\nvar y = 37;\n",
NULL
};
// Parser/Scanner needs a stack limit.
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
uintptr_t stack_limit = CcTest::i_isolate()->stack_guard()->real_climit();
for (int i = 0; tests[i]; i++) {
const i::byte* source =
reinterpret_cast<const i::byte*>(tests[i]);
i::Utf8ToUtf16CharacterStream stream(source, i::StrLength(tests[i]));
i::CompleteParserRecorder log;
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(&stream);
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(
&zone, CcTest::i_isolate()->heap()->HashSeed());
i::PreParser preparser(&zone, &scanner, &ast_value_factory, &log,
stack_limit);
preparser.set_allow_lazy(true);
i::PreParser::PreParseResult result = preparser.PreParseProgram();
CHECK_EQ(i::PreParser::kPreParseSuccess, result);
CHECK(!log.HasError());
}
for (int i = 0; fail_tests[i]; i++) {
const i::byte* source =
reinterpret_cast<const i::byte*>(fail_tests[i]);
i::Utf8ToUtf16CharacterStream stream(source, i::StrLength(fail_tests[i]));
i::CompleteParserRecorder log;
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(&stream);
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(
&zone, CcTest::i_isolate()->heap()->HashSeed());
i::PreParser preparser(&zone, &scanner, &ast_value_factory, &log,
stack_limit);
preparser.set_allow_lazy(true);
i::PreParser::PreParseResult result = preparser.PreParseProgram();
// Even in the case of a syntax error, kPreParseSuccess is returned.
CHECK_EQ(i::PreParser::kPreParseSuccess, result);
CHECK(log.HasError());
}
}
class ScriptResource : public v8::String::ExternalOneByteStringResource {
public:
ScriptResource(const char* data, size_t length)
: data_(data), length_(length) { }
const char* data() const { return data_; }
size_t length() const { return length_; }
private:
const char* data_;
size_t length_;
};
TEST(UsingCachedData) {
// Producing cached parser data while parsing eagerly is not supported.
if (!i::FLAG_lazy || (i::FLAG_ignition && i::FLAG_ignition_eager)) return;
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope handles(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
v8::Context::Scope context_scope(context);
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
// Source containing functions that might be lazily compiled and all types
// of symbols (string, propertyName, regexp).
const char* source =
"var x = 42;"
"function foo(a) { return function nolazy(b) { return a + b; } }"
"function bar(a) { if (a) return function lazy(b) { return b; } }"
"var z = {'string': 'string literal', bareword: 'propertyName', "
" 42: 'number literal', for: 'keyword as propertyName', "
" f\\u006fr: 'keyword propertyname with escape'};"
"var v = /RegExp Literal/;"
"var w = /RegExp Literal\\u0020With Escape/gi;"
"var y = { get getter() { return 42; }, "
" set setter(v) { this.value = v; }};"
"var f = a => function (b) { return a + b; };"
"var g = a => b => a + b;";
int source_length = i::StrLength(source);
// ScriptResource will be deleted when the corresponding String is GCd.
v8::ScriptCompiler::Source script_source(
v8::String::NewExternalOneByte(isolate,
new ScriptResource(source, source_length))
.ToLocalChecked());
i::FLAG_min_preparse_length = 0;
v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &script_source,
v8::ScriptCompiler::kProduceParserCache)
.ToLocalChecked();
CHECK(script_source.GetCachedData());
// Compile the script again, using the cached data.
bool lazy_flag = i::FLAG_lazy;
i::FLAG_lazy = true;
v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &script_source,
v8::ScriptCompiler::kConsumeParserCache)
.ToLocalChecked();
i::FLAG_lazy = false;
v8::ScriptCompiler::CompileUnboundScript(
isolate, &script_source, v8::ScriptCompiler::kConsumeParserCache)
.ToLocalChecked();
i::FLAG_lazy = lazy_flag;
}
TEST(PreparseFunctionDataIsUsed) {
// Producing cached parser data while parsing eagerly is not supported.
if (!i::FLAG_lazy || (i::FLAG_ignition && i::FLAG_ignition_eager)) return;
// This tests that we actually do use the function data generated by the
// preparser.
// Make preparsing work for short scripts.
i::FLAG_min_preparse_length = 0;
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope handles(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
v8::Context::Scope context_scope(context);
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
const char* good_code[] = {
"function this_is_lazy() { var a; } function foo() { return 25; } foo();",
"var this_is_lazy = () => { var a; }; var foo = () => 25; foo();",
};
// Insert a syntax error inside the lazy function.
const char* bad_code[] = {
"function this_is_lazy() { if ( } function foo() { return 25; } foo();",
"var this_is_lazy = () => { if ( }; var foo = () => 25; foo();",
};
for (unsigned i = 0; i < arraysize(good_code); i++) {
v8::ScriptCompiler::Source good_source(v8_str(good_code[i]));
v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &good_source,
v8::ScriptCompiler::kProduceParserCache)
.ToLocalChecked();
const v8::ScriptCompiler::CachedData* cached_data =
good_source.GetCachedData();
CHECK(cached_data->data != NULL);
CHECK_GT(cached_data->length, 0);
// Now compile the erroneous code with the good preparse data. If the
// preparse data is used, the lazy function is skipped and it should
// compile fine.
v8::ScriptCompiler::Source bad_source(
v8_str(bad_code[i]), new v8::ScriptCompiler::CachedData(
cached_data->data, cached_data->length));
v8::Local<v8::Value> result =
CompileRun(isolate->GetCurrentContext(), &bad_source,
v8::ScriptCompiler::kConsumeParserCache);
CHECK(result->IsInt32());
CHECK_EQ(25, result->Int32Value(isolate->GetCurrentContext()).FromJust());
}
}
TEST(StandAlonePreParser) {
v8::V8::Initialize();
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
const char* programs[] = {
"{label: 42}",
"var x = 42;",
"function foo(x, y) { return x + y; }",
"%ArgleBargle(glop);",
"var x = new new Function('this.x = 42');",
"var f = (x, y) => x + y;",
NULL
};
uintptr_t stack_limit = CcTest::i_isolate()->stack_guard()->real_climit();
for (int i = 0; programs[i]; i++) {
const char* program = programs[i];
i::Utf8ToUtf16CharacterStream stream(
reinterpret_cast<const i::byte*>(program),
static_cast<unsigned>(strlen(program)));
i::CompleteParserRecorder log;
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(&stream);
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(
&zone, CcTest::i_isolate()->heap()->HashSeed());
i::PreParser preparser(&zone, &scanner, &ast_value_factory, &log,
stack_limit);
preparser.set_allow_lazy(true);
preparser.set_allow_natives(true);
i::PreParser::PreParseResult result = preparser.PreParseProgram();
CHECK_EQ(i::PreParser::kPreParseSuccess, result);
CHECK(!log.HasError());
}
}
TEST(StandAlonePreParserNoNatives) {
v8::V8::Initialize();
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
const char* programs[] = {
"%ArgleBargle(glop);",
"var x = %_IsSmi(42);",
NULL
};
uintptr_t stack_limit = CcTest::i_isolate()->stack_guard()->real_climit();
for (int i = 0; programs[i]; i++) {
const char* program = programs[i];
i::Utf8ToUtf16CharacterStream stream(
reinterpret_cast<const i::byte*>(program),
static_cast<unsigned>(strlen(program)));
i::CompleteParserRecorder log;
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(&stream);
// Preparser defaults to disallowing natives syntax.
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(
&zone, CcTest::i_isolate()->heap()->HashSeed());
i::PreParser preparser(&zone, &scanner, &ast_value_factory, &log,
stack_limit);
preparser.set_allow_lazy(true);
i::PreParser::PreParseResult result = preparser.PreParseProgram();
CHECK_EQ(i::PreParser::kPreParseSuccess, result);
CHECK(log.HasError());
}
}
TEST(PreparsingObjectLiterals) {
// Regression test for a bug where the symbol stream produced by PreParser
// didn't match what Parser wanted to consume.
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope handles(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
v8::Context::Scope context_scope(context);
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
{
const char* source = "var myo = {if: \"foo\"}; myo.if;";
v8::Local<v8::Value> result = ParserCacheCompileRun(source);
CHECK(result->IsString());
v8::String::Utf8Value utf8(result);
CHECK_EQ(0, strcmp("foo", *utf8));
}
{
const char* source = "var myo = {\"bar\": \"foo\"}; myo[\"bar\"];";
v8::Local<v8::Value> result = ParserCacheCompileRun(source);
CHECK(result->IsString());
v8::String::Utf8Value utf8(result);
CHECK_EQ(0, strcmp("foo", *utf8));
}
{
const char* source = "var myo = {1: \"foo\"}; myo[1];";
v8::Local<v8::Value> result = ParserCacheCompileRun(source);
CHECK(result->IsString());
v8::String::Utf8Value utf8(result);
CHECK_EQ(0, strcmp("foo", *utf8));
}
}
TEST(RegressChromium62639) {
v8::V8::Initialize();
i::Isolate* isolate = CcTest::i_isolate();
isolate->stack_guard()->SetStackLimit(i::GetCurrentStackPosition() -
128 * 1024);
const char* program = "var x = 'something';\n"
"escape: function() {}";
// Fails parsing expecting an identifier after "function".
// Before fix, didn't check *ok after Expect(Token::Identifier, ok),
// and then used the invalid currently scanned literal. This always
// failed in debug mode, and sometimes crashed in release mode.
i::Utf8ToUtf16CharacterStream stream(
reinterpret_cast<const i::byte*>(program),
static_cast<unsigned>(strlen(program)));
i::CompleteParserRecorder log;
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(&stream);
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(&zone,
CcTest::i_isolate()->heap()->HashSeed());
i::PreParser preparser(&zone, &scanner, &ast_value_factory, &log,
CcTest::i_isolate()->stack_guard()->real_climit());
preparser.set_allow_lazy(true);
i::PreParser::PreParseResult result = preparser.PreParseProgram();
// Even in the case of a syntax error, kPreParseSuccess is returned.
CHECK_EQ(i::PreParser::kPreParseSuccess, result);
CHECK(log.HasError());
}
TEST(Regress928) {
v8::V8::Initialize();
i::Isolate* isolate = CcTest::i_isolate();
i::Factory* factory = isolate->factory();
// Preparsing didn't consider the catch clause of a try statement
// as with-content, which made it assume that a function inside
// the block could be lazily compiled, and an extra, unexpected,
// entry was added to the data.
isolate->stack_guard()->SetStackLimit(i::GetCurrentStackPosition() -
128 * 1024);
const char* program =
"try { } catch (e) { var foo = function () { /* first */ } }"
"var bar = function () { /* second */ }";
v8::HandleScope handles(CcTest::isolate());
i::Handle<i::String> source = factory->NewStringFromAsciiChecked(program);
i::GenericStringUtf16CharacterStream stream(source, 0, source->length());
i::CompleteParserRecorder log;
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(&stream);
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(&zone,
CcTest::i_isolate()->heap()->HashSeed());
i::PreParser preparser(&zone, &scanner, &ast_value_factory, &log,
CcTest::i_isolate()->stack_guard()->real_climit());
preparser.set_allow_lazy(true);
i::PreParser::PreParseResult result = preparser.PreParseProgram();
CHECK_EQ(i::PreParser::kPreParseSuccess, result);
i::ScriptData* sd = log.GetScriptData();
i::ParseData* pd = i::ParseData::FromCachedData(sd);
pd->Initialize();
int first_function =
static_cast<int>(strstr(program, "function") - program);
int first_lbrace = first_function + i::StrLength("function () ");
CHECK_EQ('{', program[first_lbrace]);
i::FunctionEntry entry1 = pd->GetFunctionEntry(first_lbrace);
CHECK(!entry1.is_valid());
int second_function =
static_cast<int>(strstr(program + first_lbrace, "function") - program);
int second_lbrace =
second_function + i::StrLength("function () ");
CHECK_EQ('{', program[second_lbrace]);
i::FunctionEntry entry2 = pd->GetFunctionEntry(second_lbrace);
CHECK(entry2.is_valid());
CHECK_EQ('}', program[entry2.end_pos() - 1]);
delete sd;
delete pd;
}
TEST(PreParseOverflow) {
v8::V8::Initialize();
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
size_t kProgramSize = 1024 * 1024;
v8::base::SmartArrayPointer<char> program(
i::NewArray<char>(kProgramSize + 1));
memset(program.get(), '(', kProgramSize);
program[kProgramSize] = '\0';
uintptr_t stack_limit = CcTest::i_isolate()->stack_guard()->real_climit();
i::Utf8ToUtf16CharacterStream stream(
reinterpret_cast<const i::byte*>(program.get()),
static_cast<unsigned>(kProgramSize));
i::CompleteParserRecorder log;
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(&stream);
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(&zone,
CcTest::i_isolate()->heap()->HashSeed());
i::PreParser preparser(&zone, &scanner, &ast_value_factory, &log,
stack_limit);
preparser.set_allow_lazy(true);
i::PreParser::PreParseResult result = preparser.PreParseProgram();
CHECK_EQ(i::PreParser::kPreParseStackOverflow, result);
}
class TestExternalResource: public v8::String::ExternalStringResource {
public:
explicit TestExternalResource(uint16_t* data, int length)
: data_(data), length_(static_cast<size_t>(length)) { }
~TestExternalResource() { }
const uint16_t* data() const {
return data_;
}
size_t length() const {
return length_;
}
private:
uint16_t* data_;
size_t length_;
};
#define CHECK_EQU(v1, v2) CHECK_EQ(static_cast<int>(v1), static_cast<int>(v2))
void TestCharacterStream(const char* one_byte_source, unsigned length,
unsigned start = 0, unsigned end = 0) {
if (end == 0) end = length;
unsigned sub_length = end - start;
i::Isolate* isolate = CcTest::i_isolate();
i::Factory* factory = isolate->factory();
i::HandleScope test_scope(isolate);
v8::base::SmartArrayPointer<i::uc16> uc16_buffer(new i::uc16[length]);
for (unsigned i = 0; i < length; i++) {
uc16_buffer[i] = static_cast<i::uc16>(one_byte_source[i]);
}
i::Vector<const char> one_byte_vector(one_byte_source,
static_cast<int>(length));
i::Handle<i::String> one_byte_string =
factory->NewStringFromAscii(one_byte_vector).ToHandleChecked();
TestExternalResource resource(uc16_buffer.get(), length);
i::Handle<i::String> uc16_string(
factory->NewExternalStringFromTwoByte(&resource).ToHandleChecked());
i::ExternalTwoByteStringUtf16CharacterStream uc16_stream(
i::Handle<i::ExternalTwoByteString>::cast(uc16_string), start, end);
i::GenericStringUtf16CharacterStream string_stream(one_byte_string, start,
end);
i::Utf8ToUtf16CharacterStream utf8_stream(
reinterpret_cast<const i::byte*>(one_byte_source), end);
utf8_stream.SeekForward(start);
unsigned i = start;
while (i < end) {
// Read streams one char at a time
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
int32_t c0 = one_byte_source[i];
int32_t c1 = uc16_stream.Advance();
int32_t c2 = string_stream.Advance();
int32_t c3 = utf8_stream.Advance();
i++;
CHECK_EQ(c0, c1);
CHECK_EQ(c0, c2);
CHECK_EQ(c0, c3);
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
}
while (i > start + sub_length / 4) {
// Pushback, re-read, pushback again.
int32_t c0 = one_byte_source[i - 1];
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
uc16_stream.PushBack(c0);
string_stream.PushBack(c0);
utf8_stream.PushBack(c0);
i--;
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
int32_t c1 = uc16_stream.Advance();
int32_t c2 = string_stream.Advance();
int32_t c3 = utf8_stream.Advance();
i++;
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
CHECK_EQ(c0, c1);
CHECK_EQ(c0, c2);
CHECK_EQ(c0, c3);
uc16_stream.PushBack(c0);
string_stream.PushBack(c0);
utf8_stream.PushBack(c0);
i--;
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
}
unsigned halfway = start + sub_length / 2;
uc16_stream.SeekForward(halfway - i);
string_stream.SeekForward(halfway - i);
utf8_stream.SeekForward(halfway - i);
i = halfway;
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
while (i < end) {
// Read streams one char at a time
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
int32_t c0 = one_byte_source[i];
int32_t c1 = uc16_stream.Advance();
int32_t c2 = string_stream.Advance();
int32_t c3 = utf8_stream.Advance();
i++;
CHECK_EQ(c0, c1);
CHECK_EQ(c0, c2);
CHECK_EQ(c0, c3);
CHECK_EQU(i, uc16_stream.pos());
CHECK_EQU(i, string_stream.pos());
CHECK_EQU(i, utf8_stream.pos());
}
int32_t c1 = uc16_stream.Advance();
int32_t c2 = string_stream.Advance();
int32_t c3 = utf8_stream.Advance();
CHECK_LT(c1, 0);
CHECK_LT(c2, 0);
CHECK_LT(c3, 0);
}
TEST(CharacterStreams) {
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope handles(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
v8::Context::Scope context_scope(context);
TestCharacterStream("abc\0\n\r\x7f", 7);
static const unsigned kBigStringSize = 4096;
char buffer[kBigStringSize + 1];
for (unsigned i = 0; i < kBigStringSize; i++) {
buffer[i] = static_cast<char>(i & 0x7f);
}
TestCharacterStream(buffer, kBigStringSize);
TestCharacterStream(buffer, kBigStringSize, 576, 3298);
TestCharacterStream("\0", 1);
TestCharacterStream("", 0);
}
TEST(Utf8CharacterStream) {
static const unsigned kMaxUC16CharU = unibrow::Utf8::kMaxThreeByteChar;
static const int kMaxUC16Char = static_cast<int>(kMaxUC16CharU);
static const int kAllUtf8CharsSize =
(unibrow::Utf8::kMaxOneByteChar + 1) +
(unibrow::Utf8::kMaxTwoByteChar - unibrow::Utf8::kMaxOneByteChar) * 2 +
(unibrow::Utf8::kMaxThreeByteChar - unibrow::Utf8::kMaxTwoByteChar) * 3;
static const unsigned kAllUtf8CharsSizeU =
static_cast<unsigned>(kAllUtf8CharsSize);
char buffer[kAllUtf8CharsSizeU];
unsigned cursor = 0;
for (int i = 0; i <= kMaxUC16Char; i++) {
cursor += unibrow::Utf8::Encode(buffer + cursor, i,
unibrow::Utf16::kNoPreviousCharacter, true);
}
CHECK(cursor == kAllUtf8CharsSizeU);
i::Utf8ToUtf16CharacterStream stream(reinterpret_cast<const i::byte*>(buffer),
kAllUtf8CharsSizeU);
int32_t bad = unibrow::Utf8::kBadChar;
for (int i = 0; i <= kMaxUC16Char; i++) {
CHECK_EQU(i, stream.pos());
int32_t c = stream.Advance();
if (i >= 0xd800 && i <= 0xdfff) {
CHECK_EQ(bad, c);
} else {
CHECK_EQ(i, c);
}
CHECK_EQU(i + 1, stream.pos());
}
for (int i = kMaxUC16Char; i >= 0; i--) {
CHECK_EQU(i + 1, stream.pos());
stream.PushBack(i);
CHECK_EQU(i, stream.pos());
}
int i = 0;
while (stream.pos() < kMaxUC16CharU) {
CHECK_EQU(i, stream.pos());
int progress = static_cast<int>(stream.SeekForward(12));
i += progress;
int32_t c = stream.Advance();
if (i >= 0xd800 && i <= 0xdfff) {
CHECK_EQ(bad, c);
} else if (i <= kMaxUC16Char) {
CHECK_EQ(i, c);
} else {
CHECK_EQ(-1, c);
}
i += 1;
CHECK_EQU(i, stream.pos());
}
}
#undef CHECK_EQU
void TestStreamScanner(i::Utf16CharacterStream* stream,
i::Token::Value* expected_tokens,
int skip_pos = 0, // Zero means not skipping.
int skip_to = 0) {
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(stream);
int i = 0;
do {
i::Token::Value expected = expected_tokens[i];
i::Token::Value actual = scanner.Next();
CHECK_EQ(i::Token::String(expected), i::Token::String(actual));
if (scanner.location().end_pos == skip_pos) {
scanner.SeekForward(skip_to);
}
i++;
} while (expected_tokens[i] != i::Token::ILLEGAL);
}
TEST(StreamScanner) {
v8::V8::Initialize();
const char* str1 = "{ foo get for : */ <- \n\n /*foo*/ bib";
i::Utf8ToUtf16CharacterStream stream1(reinterpret_cast<const i::byte*>(str1),
static_cast<unsigned>(strlen(str1)));
i::Token::Value expectations1[] = {
i::Token::LBRACE,
i::Token::IDENTIFIER,
i::Token::IDENTIFIER,
i::Token::FOR,
i::Token::COLON,
i::Token::MUL,
i::Token::DIV,
i::Token::LT,
i::Token::SUB,
i::Token::IDENTIFIER,
i::Token::EOS,
i::Token::ILLEGAL
};
TestStreamScanner(&stream1, expectations1, 0, 0);
const char* str2 = "case default const {THIS\nPART\nSKIPPED} do";
i::Utf8ToUtf16CharacterStream stream2(reinterpret_cast<const i::byte*>(str2),
static_cast<unsigned>(strlen(str2)));
i::Token::Value expectations2[] = {
i::Token::CASE,
i::Token::DEFAULT,
i::Token::CONST,
i::Token::LBRACE,
// Skipped part here
i::Token::RBRACE,
i::Token::DO,
i::Token::EOS,
i::Token::ILLEGAL
};
CHECK_EQ('{', str2[19]);
CHECK_EQ('}', str2[37]);
TestStreamScanner(&stream2, expectations2, 20, 37);
const char* str3 = "{}}}}";
i::Token::Value expectations3[] = {
i::Token::LBRACE,
i::Token::RBRACE,
i::Token::RBRACE,
i::Token::RBRACE,
i::Token::RBRACE,
i::Token::EOS,
i::Token::ILLEGAL
};
// Skip zero-four RBRACEs.
for (int i = 0; i <= 4; i++) {
expectations3[6 - i] = i::Token::ILLEGAL;
expectations3[5 - i] = i::Token::EOS;
i::Utf8ToUtf16CharacterStream stream3(
reinterpret_cast<const i::byte*>(str3),
static_cast<unsigned>(strlen(str3)));
TestStreamScanner(&stream3, expectations3, 1, 1 + i);
}
}
void TestScanRegExp(const char* re_source, const char* expected) {
i::Utf8ToUtf16CharacterStream stream(
reinterpret_cast<const i::byte*>(re_source),
static_cast<unsigned>(strlen(re_source)));
i::HandleScope scope(CcTest::i_isolate());
i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
scanner.Initialize(&stream);
i::Token::Value start = scanner.peek();
CHECK(start == i::Token::DIV || start == i::Token::ASSIGN_DIV);
CHECK(scanner.ScanRegExpPattern(start == i::Token::ASSIGN_DIV));
scanner.Next(); // Current token is now the regexp literal.
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(&zone,
CcTest::i_isolate()->heap()->HashSeed());
ast_value_factory.Internalize(CcTest::i_isolate());
i::Handle<i::String> val =
scanner.CurrentSymbol(&ast_value_factory)->string();
i::DisallowHeapAllocation no_alloc;
i::String::FlatContent content = val->GetFlatContent();
CHECK(content.IsOneByte());
i::Vector<const uint8_t> actual = content.ToOneByteVector();
for (int i = 0; i < actual.length(); i++) {
CHECK_NE('\0', expected[i]);
CHECK_EQ(expected[i], actual[i]);
}
}
TEST(RegExpScanning) {
v8::V8::Initialize();
// RegExp token with added garbage at the end. The scanner should only
// scan the RegExp until the terminating slash just before "flipperwald".
TestScanRegExp("/b/flipperwald", "b");
// Incomplete escape sequences doesn't hide the terminating slash.
TestScanRegExp("/\\x/flipperwald", "\\x");
TestScanRegExp("/\\u/flipperwald", "\\u");
TestScanRegExp("/\\u1/flipperwald", "\\u1");
TestScanRegExp("/\\u12/flipperwald", "\\u12");
TestScanRegExp("/\\u123/flipperwald", "\\u123");
TestScanRegExp("/\\c/flipperwald", "\\c");
TestScanRegExp("/\\c//flipperwald", "\\c");
// Slashes inside character classes are not terminating.
TestScanRegExp("/[/]/flipperwald", "[/]");
TestScanRegExp("/[\\s-/]/flipperwald", "[\\s-/]");
// Incomplete escape sequences inside a character class doesn't hide
// the end of the character class.
TestScanRegExp("/[\\c/]/flipperwald", "[\\c/]");
TestScanRegExp("/[\\c]/flipperwald", "[\\c]");
TestScanRegExp("/[\\x]/flipperwald", "[\\x]");
TestScanRegExp("/[\\x1]/flipperwald", "[\\x1]");
TestScanRegExp("/[\\u]/flipperwald", "[\\u]");
TestScanRegExp("/[\\u1]/flipperwald", "[\\u1]");
TestScanRegExp("/[\\u12]/flipperwald", "[\\u12]");
TestScanRegExp("/[\\u123]/flipperwald", "[\\u123]");
// Escaped ']'s wont end the character class.
TestScanRegExp("/[\\]/]/flipperwald", "[\\]/]");
// Escaped slashes are not terminating.
TestScanRegExp("/\\//flipperwald", "\\/");
// Starting with '=' works too.
TestScanRegExp("/=/", "=");
TestScanRegExp("/=?/", "=?");
}
static int Utf8LengthHelper(const char* s) {
int len = i::StrLength(s);
int character_length = len;
for (int i = 0; i < len; i++) {
unsigned char c = s[i];
int input_offset = 0;
int output_adjust = 0;
if (c > 0x7f) {
if (c < 0xc0) continue;
if (c >= 0xf0) {
if (c >= 0xf8) {
// 5 and 6 byte UTF-8 sequences turn into a kBadChar for each UTF-8
// byte.
continue; // Handle first UTF-8 byte.
}
if ((c & 7) == 0 && ((s[i + 1] & 0x30) == 0)) {
// This 4 byte sequence could have been coded as a 3 byte sequence.
// Record a single kBadChar for the first byte and continue.
continue;
}
input_offset = 3;
// 4 bytes of UTF-8 turn into 2 UTF-16 code units.
character_length -= 2;
} else if (c >= 0xe0) {
if ((c & 0xf) == 0 && ((s[i + 1] & 0x20) == 0)) {
// This 3 byte sequence could have been coded as a 2 byte sequence.
// Record a single kBadChar for the first byte and continue.
continue;
}
if (c == 0xed) {
unsigned char d = s[i + 1];
if ((d < 0x80) || (d > 0x9f)) {
// This 3 byte sequence is part of a surrogate pair which is not
// supported by UTF-8. Record a single kBadChar for the first byte
// and continue.
continue;
}
}
input_offset = 2;
// 3 bytes of UTF-8 turn into 1 UTF-16 code unit.
output_adjust = 2;
} else {
if ((c & 0x1e) == 0) {
// This 2 byte sequence could have been coded as a 1 byte sequence.
// Record a single kBadChar for the first byte and continue.
continue;
}
input_offset = 1;
// 2 bytes of UTF-8 turn into 1 UTF-16 code unit.
output_adjust = 1;
}
bool bad = false;
for (int j = 1; j <= input_offset; j++) {
if ((s[i + j] & 0xc0) != 0x80) {
// Bad UTF-8 sequence turns the first in the sequence into kBadChar,
// which is a single UTF-16 code unit.
bad = true;
break;
}
}
if (!bad) {
i += input_offset;
character_length -= output_adjust;
}
}
}
return character_length;
}
TEST(ScopeUsesArgumentsSuperThis) {
static const struct {
const char* prefix;
const char* suffix;
} surroundings[] = {
{ "function f() {", "}" },
{ "var f = () => {", "};" },
{ "class C { constructor() {", "} }" },
};
enum Expected {
NONE = 0,
ARGUMENTS = 1,
SUPER_PROPERTY = 1 << 1,
THIS = 1 << 2,
EVAL = 1 << 4
};
// clang-format off
static const struct {
const char* body;
int expected;
} source_data[] = {
{"", NONE},
{"return this", THIS},
{"return arguments", ARGUMENTS},
{"return super.x", SUPER_PROPERTY},
{"return arguments[0]", ARGUMENTS},
{"return this + arguments[0]", ARGUMENTS | THIS},
{"return this + arguments[0] + super.x",
ARGUMENTS | SUPER_PROPERTY | THIS},
{"return x => this + x", THIS},
{"return x => super.f() + x", SUPER_PROPERTY},
{"this.foo = 42;", THIS},
{"this.foo();", THIS},
{"if (foo()) { this.f() }", THIS},
{"if (foo()) { super.f() }", SUPER_PROPERTY},
{"if (arguments.length) { this.f() }", ARGUMENTS | THIS},
{"while (true) { this.f() }", THIS},
{"while (true) { super.f() }", SUPER_PROPERTY},
{"if (true) { while (true) this.foo(arguments) }", ARGUMENTS | THIS},
// Multiple nesting levels must work as well.
{"while (true) { while (true) { while (true) return this } }", THIS},
{"while (true) { while (true) { while (true) return super.f() } }",
SUPER_PROPERTY},
{"if (1) { return () => { while (true) new this() } }", THIS},
{"return function (x) { return this + x }", NONE},
{"return { m(x) { return super.m() + x } }", NONE},
{"var x = function () { this.foo = 42 };", NONE},
{"var x = { m() { super.foo = 42 } };", NONE},
{"if (1) { return function () { while (true) new this() } }", NONE},
{"if (1) { return { m() { while (true) super.m() } } }", NONE},
{"return function (x) { return () => this }", NONE},
{"return { m(x) { return () => super.m() } }", NONE},
// Flags must be correctly set when using block scoping.
{"\"use strict\"; while (true) { let x; this, arguments; }",
THIS},
{"\"use strict\"; while (true) { let x; this, super.f(), arguments; }",
SUPER_PROPERTY | THIS},
{"\"use strict\"; if (foo()) { let x; this.f() }", THIS},
{"\"use strict\"; if (foo()) { let x; super.f() }", SUPER_PROPERTY},
{"\"use strict\"; if (1) {"
" let x; return { m() { return this + super.m() + arguments } }"
"}",
NONE},
{"eval(42)", EVAL},
{"if (1) { eval(42) }", EVAL},
{"eval('super.x')", EVAL},
{"eval('this.x')", EVAL},
{"eval('arguments')", EVAL},
};
// clang-format on
i::Isolate* isolate = CcTest::i_isolate();
i::Factory* factory = isolate->factory();
v8::HandleScope handles(CcTest::isolate());
v8::Local<v8::Context> context = v8::Context::New(CcTest::isolate());
v8::Context::Scope context_scope(context);
isolate->stack_guard()->SetStackLimit(i::GetCurrentStackPosition() -
128 * 1024);
for (unsigned j = 0; j < arraysize(surroundings); ++j) {
for (unsigned i = 0; i < arraysize(source_data); ++i) {
// Super property is only allowed in constructor and method.
if (((source_data[i].expected & SUPER_PROPERTY) ||
(source_data[i].expected == NONE)) && j != 2) {
continue;
}
int kProgramByteSize = i::StrLength(surroundings[j].prefix) +
i::StrLength(surroundings[j].suffix) +
i::StrLength(source_data[i].body);
i::ScopedVector<char> program(kProgramByteSize + 1);
i::SNPrintF(program, "%s%s%s", surroundings[j].prefix,
source_data[i].body, surroundings[j].suffix);
i::Handle<i::String> source =
factory->NewStringFromUtf8(i::CStrVector(program.start()))
.ToHandleChecked();
i::Handle<i::Script> script = factory->NewScript(source);
i::Zone zone(CcTest::i_isolate()->allocator());
i::ParseInfo info(&zone, script);
i::Parser parser(&info);
info.set_global();
CHECK(parser.Parse(&info));
CHECK(i::Rewriter::Rewrite(&info));
CHECK(i::Scope::Analyze(&info));
CHECK(info.literal() != NULL);
i::Scope* script_scope = info.literal()->scope();
CHECK(script_scope->is_script_scope());
CHECK_EQ(1, script_scope->inner_scopes()->length());
i::Scope* scope = script_scope->inner_scopes()->at(0);
// Adjust for constructor scope.
if (j == 2) {
CHECK_EQ(1, scope->inner_scopes()->length());
scope = scope->inner_scopes()->at(0);
}
CHECK_EQ((source_data[i].expected & ARGUMENTS) != 0,
scope->uses_arguments());
CHECK_EQ((source_data[i].expected & SUPER_PROPERTY) != 0,
scope->uses_super_property());
if ((source_data[i].expected & THIS) != 0) {
// Currently the is_used() flag is conservative; all variables in a
// script scope are marked as used.
CHECK(
scope->Lookup(info.ast_value_factory()->this_string())->is_used());
}
CHECK_EQ((source_data[i].expected & EVAL) != 0, scope->calls_eval());
}
}
}
static void CheckParsesToNumber(const char* source, bool with_dot) {
v8::V8::Initialize();
HandleAndZoneScope handles;
i::Isolate* isolate = CcTest::i_isolate();
i::Factory* factory = isolate->factory();
std::string full_source = "function f() { return ";
full_source += source;
full_source += "; }";
i::Handle<i::String> source_code =
factory->NewStringFromUtf8(i::CStrVector(full_source.c_str()))
.ToHandleChecked();
i::Handle<i::Script> script = factory->NewScript(source_code);
i::ParseInfo info(handles.main_zone(), script);
i::Parser parser(&info);
info.set_global();
info.set_lazy(false);
info.set_allow_lazy_parsing(false);
info.set_toplevel(true);
CHECK(i::Compiler::ParseAndAnalyze(&info));
CHECK(info.scope()->declarations()->length() == 1);
i::FunctionLiteral* fun =
info.scope()->declarations()->at(0)->AsFunctionDeclaration()->fun();
CHECK(fun->body()->length() == 1);
CHECK(fun->body()->at(0)->IsReturnStatement());
i::ReturnStatement* ret = fun->body()->at(0)->AsReturnStatement();
i::Literal* lit = ret->expression()->AsLiteral();
if (lit != NULL) {
const i::AstValue* val = lit->raw_value();
CHECK(with_dot == val->ContainsDot());
} else if (with_dot) {
i::BinaryOperation* bin = ret->expression()->AsBinaryOperation();
CHECK(bin != NULL);
CHECK_EQ(i::Token::MUL, bin->op());
i::Literal* rlit = bin->right()->AsLiteral();
const i::AstValue* val = rlit->raw_value();
CHECK(with_dot == val->ContainsDot());
CHECK_EQ(1.0, val->AsNumber());
}
}
TEST(ParseNumbers) {
CheckParsesToNumber("1.", true);
CheckParsesToNumber("1.34", true);
CheckParsesToNumber("134", false);
CheckParsesToNumber("134e44", false);
CheckParsesToNumber("134.e44", true);
CheckParsesToNumber("134.44e44", true);
CheckParsesToNumber(".44", true);
CheckParsesToNumber("-1.", true);
CheckParsesToNumber("-1.0", true);
CheckParsesToNumber("-1.34", true);
CheckParsesToNumber("-134", false);
CheckParsesToNumber("-134e44", false);
CheckParsesToNumber("-134.e44", true);
CheckParsesToNumber("-134.44e44", true);
CheckParsesToNumber("-.44", true);
CheckParsesToNumber("+x", true);
}
TEST(ScopePositions) {
// Test the parser for correctly setting the start and end positions
// of a scope. We check the scope positions of exactly one scope
// nested in the global scope of a program. 'inner source' is the
// source code that determines the part of the source belonging
// to the nested scope. 'outer_prefix' and 'outer_suffix' are
// parts of the source that belong to the global scope.
struct SourceData {
const char* outer_prefix;
const char* inner_source;
const char* outer_suffix;
i::ScopeType scope_type;
i::LanguageMode language_mode;
};
const SourceData source_data[] = {
{ " with ({}) ", "{ block; }", " more;", i::WITH_SCOPE, i::SLOPPY },
{ " with ({}) ", "{ block; }", "; more;", i::WITH_SCOPE, i::SLOPPY },
{ " with ({}) ", "{\n"
" block;\n"
" }", "\n"
" more;", i::WITH_SCOPE, i::SLOPPY },
{ " with ({}) ", "statement;", " more;", i::WITH_SCOPE, i::SLOPPY },
{ " with ({}) ", "statement", "\n"
" more;", i::WITH_SCOPE, i::SLOPPY },
{ " with ({})\n"
" ", "statement;", "\n"
" more;", i::WITH_SCOPE, i::SLOPPY },
{ " try {} catch ", "(e) { block; }", " more;",
i::CATCH_SCOPE, i::SLOPPY },
{ " try {} catch ", "(e) { block; }", "; more;",
i::CATCH_SCOPE, i::SLOPPY },
{ " try {} catch ", "(e) {\n"
" block;\n"
" }", "\n"
" more;", i::CATCH_SCOPE, i::SLOPPY },
{ " try {} catch ", "(e) { block; }", " finally { block; } more;",
i::CATCH_SCOPE, i::SLOPPY },
{ " start;\n"
" ", "{ let block; }", " more;", i::BLOCK_SCOPE, i::STRICT },
{ " start;\n"
" ", "{ let block; }", "; more;", i::BLOCK_SCOPE, i::STRICT },
{ " start;\n"
" ", "{\n"
" let block;\n"
" }", "\n"
" more;", i::BLOCK_SCOPE, i::STRICT },
{ " start;\n"
" function fun", "(a,b) { infunction; }", " more;",
i::FUNCTION_SCOPE, i::SLOPPY },
{ " start;\n"
" function fun", "(a,b) {\n"
" infunction;\n"
" }", "\n"
" more;", i::FUNCTION_SCOPE, i::SLOPPY },
{ " start;\n", "(a,b) => a + b", "; more;",
i::FUNCTION_SCOPE, i::SLOPPY },
{ " start;\n", "(a,b) => { return a+b; }", "\nmore;",
i::FUNCTION_SCOPE, i::SLOPPY },
{ " start;\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
{ " for ", "(let x = 1 ; x < 10; ++ x) { block; }", " more;",
i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x = 1 ; x < 10; ++ x) { block; }", "; more;",
i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x = 1 ; x < 10; ++ x) {\n"
" block;\n"
" }", "\n"
" more;", i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x = 1 ; x < 10; ++ x) statement;", " more;",
i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x = 1 ; x < 10; ++ x) statement", "\n"
" more;", i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x = 1 ; x < 10; ++ x)\n"
" statement;", "\n"
" more;", i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x in {}) { block; }", " more;",
i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x in {}) { block; }", "; more;",
i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x in {}) {\n"
" block;\n"
" }", "\n"
" more;", i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x in {}) statement;", " more;",
i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x in {}) statement", "\n"
" more;", i::BLOCK_SCOPE, i::STRICT },
{ " for ", "(let x in {})\n"
" statement;", "\n"
" more;", i::BLOCK_SCOPE, i::STRICT },
// Check that 6-byte and 4-byte encodings of UTF-8 strings do not throw
// the preparser off in terms of byte offsets.
// 6 byte encoding.
{ " 'foo\355\240\201\355\260\211';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// 4 byte encoding.
{ " 'foo\360\220\220\212';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// 3 byte encoding of \u0fff.
{ " 'foo\340\277\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Broken 6 byte encoding with missing last byte.
{ " 'foo\355\240\201\355\211';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Broken 3 byte encoding of \u0fff with missing last byte.
{ " 'foo\340\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Broken 3 byte encoding of \u0fff with missing 2 last bytes.
{ " 'foo\340';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Broken 3 byte encoding of \u00ff should be a 2 byte encoding.
{ " 'foo\340\203\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Broken 3 byte encoding of \u007f should be a 2 byte encoding.
{ " 'foo\340\201\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Unpaired lead surrogate.
{ " 'foo\355\240\201';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Unpaired lead surrogate where following code point is a 3 byte sequence.
{ " 'foo\355\240\201\340\277\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Unpaired lead surrogate where following code point is a 4 byte encoding
// of a trail surrogate.
{ " 'foo\355\240\201\360\215\260\211';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Unpaired trail surrogate.
{ " 'foo\355\260\211';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// 2 byte encoding of \u00ff.
{ " 'foo\303\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Broken 2 byte encoding of \u00ff with missing last byte.
{ " 'foo\303';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Broken 2 byte encoding of \u007f should be a 1 byte encoding.
{ " 'foo\301\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Illegal 5 byte encoding.
{ " 'foo\370\277\277\277\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Illegal 6 byte encoding.
{ " 'foo\374\277\277\277\277\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Illegal 0xfe byte
{ " 'foo\376\277\277\277\277\277\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
// Illegal 0xff byte
{ " 'foo\377\277\277\277\277\277\277\277';\n"
" (function fun", "(a,b) { infunction; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
{ " 'foo';\n"
" (function fun", "(a,b) { 'bar\355\240\201\355\260\213'; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
{ " 'foo';\n"
" (function fun", "(a,b) { 'bar\360\220\220\214'; }", ")();",
i::FUNCTION_SCOPE, i::SLOPPY },
{ NULL, NULL, NULL, i::EVAL_SCOPE, i::SLOPPY }
};
i::Isolate* isolate = CcTest::i_isolate();
i::Factory* factory = isolate->factory();
v8::HandleScope handles(CcTest::isolate());
v8::Local<v8::Context> context = v8::Context::New(CcTest::isolate());
v8::Context::Scope context_scope(context);
isolate->stack_guard()->SetStackLimit(i::GetCurrentStackPosition() -
128 * 1024);
for (int i = 0; source_data[i].outer_prefix; i++) {
int kPrefixLen = Utf8LengthHelper(source_data[i].outer_prefix);
int kInnerLen = Utf8LengthHelper(source_data[i].inner_source);
int kSuffixLen = Utf8LengthHelper(source_data[i].outer_suffix);
int kPrefixByteLen = i::StrLength(source_data[i].outer_prefix);
int kInnerByteLen = i::StrLength(source_data[i].inner_source);
int kSuffixByteLen = i::StrLength(source_data[i].outer_suffix);
int kProgramSize = kPrefixLen + kInnerLen + kSuffixLen;
int kProgramByteSize = kPrefixByteLen + kInnerByteLen + kSuffixByteLen;
i::ScopedVector<char> program(kProgramByteSize + 1);
i::SNPrintF(program, "%s%s%s",
source_data[i].outer_prefix,
source_data[i].inner_source,
source_data[i].outer_suffix);
// Parse program source.
i::Handle<i::String> source = factory->NewStringFromUtf8(
i::CStrVector(program.start())).ToHandleChecked();
CHECK_EQ(source->length(), kProgramSize);
i::Handle<i::Script> script = factory->NewScript(source);
i::Zone zone(CcTest::i_isolate()->allocator());
i::ParseInfo info(&zone, script);
i::Parser parser(&info);
parser.set_allow_lazy(true);
info.set_global();
info.set_language_mode(source_data[i].language_mode);
parser.Parse(&info);
CHECK(info.literal() != NULL);
// Check scope types and positions.
i::Scope* scope = info.literal()->scope();
CHECK(scope->is_script_scope());
CHECK_EQ(scope->start_position(), 0);
CHECK_EQ(scope->end_position(), kProgramSize);
CHECK_EQ(scope->inner_scopes()->length(), 1);
i::Scope* inner_scope = scope->inner_scopes()->at(0);
CHECK_EQ(inner_scope->scope_type(), source_data[i].scope_type);
CHECK_EQ(inner_scope->start_position(), kPrefixLen);
// The end position of a token is one position after the last
// character belonging to that token.
CHECK_EQ(inner_scope->end_position(), kPrefixLen + kInnerLen);
}
}
TEST(DiscardFunctionBody) {
// Test that inner function bodies are discarded if possible.
// See comments in ParseFunctionLiteral in parser.cc.
const char* discard_sources[] = {
"(function f() { function g() { var a; } })();",
"(function f() { function g() { { function h() { } } } })();",
/* TODO(conradw): In future it may be possible to apply this optimisation
* to these productions.
"(function f() { 0, function g() { var a; } })();",
"(function f() { 0, { g() { var a; } } })();",
"(function f() { 0, class c { g() { var a; } } })();", */
NULL};
i::Isolate* isolate = CcTest::i_isolate();
i::Factory* factory = isolate->factory();
v8::HandleScope handles(CcTest::isolate());
i::FunctionLiteral* function;
for (int i = 0; discard_sources[i]; i++) {
const char* source = discard_sources[i];
i::Handle<i::String> source_code =
factory->NewStringFromUtf8(i::CStrVector(source)).ToHandleChecked();
i::Handle<i::Script> script = factory->NewScript(source_code);
i::Zone zone(CcTest::i_isolate()->allocator());
i::ParseInfo info(&zone, script);
info.set_allow_lazy_parsing();
i::Parser parser(&info);
parser.Parse(&info);
function = info.literal();
CHECK_NOT_NULL(function);
CHECK_NOT_NULL(function->body());
CHECK_EQ(1, function->body()->length());
i::FunctionLiteral* inner =
function->body()->first()->AsExpressionStatement()->expression()->
AsCall()->expression()->AsFunctionLiteral();
i::Scope* inner_scope = inner->scope();
i::FunctionLiteral* fun = nullptr;
if (inner_scope->declarations()->length() > 1) {
fun = inner_scope->declarations()->at(1)->AsFunctionDeclaration()->fun();
} else {
// TODO(conradw): This path won't be hit until the other test cases can be
// uncommented.
UNREACHABLE();
CHECK_NOT_NULL(inner->body());
CHECK_GE(2, inner->body()->length());
i::Expression* exp = inner->body()->at(1)->AsExpressionStatement()->
expression()->AsBinaryOperation()->right();
if (exp->IsFunctionLiteral()) {
fun = exp->AsFunctionLiteral();
} else if (exp->IsObjectLiteral()) {
fun = exp->AsObjectLiteral()->properties()->at(0)->value()->
AsFunctionLiteral();
} else {
fun = exp->AsClassLiteral()->properties()->at(0)->value()->
AsFunctionLiteral();
}
}
CHECK_NULL(fun->body());
}
}
const char* ReadString(unsigned* start) {
int length = start[0];
char* result = i::NewArray<char>(length + 1);
for (int i = 0; i < length; i++) {
result[i] = start[i + 1];
}
result[length] = '\0';
return result;
}
i::Handle<i::String> FormatMessage(i::Vector<unsigned> data) {
i::Isolate* isolate = CcTest::i_isolate();
int message = data[i::PreparseDataConstants::kMessageTemplatePos];
int arg_count = data[i::PreparseDataConstants::kMessageArgCountPos];
i::Handle<i::Object> arg_object;
if (arg_count == 1) {
// Position after text found by skipping past length field and
// length field content words.
const char* arg =
ReadString(&data[i::PreparseDataConstants::kMessageArgPos]);
arg_object = v8::Utils::OpenHandle(*v8_str(arg));
i::DeleteArray(arg);
} else {
CHECK_EQ(0, arg_count);
arg_object = isolate->factory()->undefined_value();
}
data.Dispose();
return i::MessageTemplate::FormatMessage(isolate, message, arg_object);
}
enum ParserFlag {
kAllowLazy,
kAllowNatives,
kAllowHarmonyFunctionSent,
kAllowHarmonyRestrictiveDeclarations,
kAllowHarmonyExponentiationOperator,
kAllowHarmonyForIn
};
enum ParserSyncTestResult {
kSuccessOrError,
kSuccess,
kError
};
template <typename Traits>
void SetParserFlags(i::ParserBase<Traits>* parser,
i::EnumSet<ParserFlag> flags) {
parser->set_allow_lazy(flags.Contains(kAllowLazy));
parser->set_allow_natives(flags.Contains(kAllowNatives));
parser->set_allow_harmony_function_sent(
flags.Contains(kAllowHarmonyFunctionSent));
parser->set_allow_harmony_restrictive_declarations(
flags.Contains(kAllowHarmonyRestrictiveDeclarations));
parser->set_allow_harmony_exponentiation_operator(
flags.Contains(kAllowHarmonyExponentiationOperator));
parser->set_allow_harmony_for_in(flags.Contains(kAllowHarmonyForIn));
}
void TestParserSyncWithFlags(i::Handle<i::String> source,
i::EnumSet<ParserFlag> flags,
ParserSyncTestResult result,
bool is_module = false) {
i::Isolate* isolate = CcTest::i_isolate();
i::Factory* factory = isolate->factory();
uintptr_t stack_limit = isolate->stack_guard()->real_climit();
int preparser_materialized_literals = -1;
int parser_materialized_literals = -2;
// Preparse the data.
i::CompleteParserRecorder log;
{
i::Scanner scanner(isolate->unicode_cache());
i::GenericStringUtf16CharacterStream stream(source, 0, source->length());
i::Zone zone(CcTest::i_isolate()->allocator());
i::AstValueFactory ast_value_factory(
&zone, CcTest::i_isolate()->heap()->HashSeed());
i::PreParser preparser(&zone, &scanner, &ast_value_factory, &log,
stack_limit);
SetParserFlags(&preparser, flags);
scanner.Initialize(&stream);
i::PreParser::PreParseResult result =
preparser.PreParseProgram(&preparser_materialized_literals, is_module);
CHECK_EQ(i::PreParser::kPreParseSuccess, result);
}
bool preparse_error = log.HasError();
// Parse the data
i::FunctionLiteral* function;
{
i::Handle<i::Script> script = factory->NewScript(source);
i::Zone zone(CcTest::i_isolate()->allocator());
i::ParseInfo info(&zone, script);
i::Parser parser(&info);
SetParserFlags(&parser, flags);
if (is_module) {
info.set_module();
} else {
info.set_global();
}
parser.Parse(&info);
function = info.literal();
if (function) {
parser_materialized_literals = function->materialized_literal_count();
}
}
// Check that preparsing fails iff parsing fails.
if (function == NULL) {
// Extract exception from the parser.
CHECK(isolate->has_pending_exception());
i::Handle<i::JSObject> exception_handle(
i::JSObject::cast(isolate->pending_exception()));
i::Handle<i::String> message_string = i::Handle<i::String>::cast(
i::JSReceiver::GetProperty(isolate, exception_handle, "message")
.ToHandleChecked());
if (result == kSuccess) {
v8::base::OS::Print(
"Parser failed on:\n"
"\t%s\n"
"with error:\n"
"\t%s\n"
"However, we expected no error.",
source->ToCString().get(), message_string->ToCString().get());
CHECK(false);
}
if (!preparse_error) {
v8::base::OS::Print(
"Parser failed on:\n"
"\t%s\n"
"with error:\n"
"\t%s\n"
"However, the preparser succeeded",
source->ToCString().get(), message_string->ToCString().get());
CHECK(false);
}
// Check that preparser and parser produce the same error.
{
i::Handle<i::String> preparser_message =
FormatMessage(log.ErrorMessageData());
if (!i::String::Equals(message_string, preparser_message)) {
v8::base::OS::Print(
"Expected parser and preparser to produce the same error on:\n"
"\t%s\n"
"However, found the following error messages\n"
"\tparser: %s\n"
"\tpreparser: %s\n",
source->ToCString().get(), message_string->ToCString().get(),
preparser_message->ToCString().get());
CHECK(false);
}
}
} else if (preparse_error) {
v8::base::OS::Print(
"Preparser failed on:\n"
"\t%s\n"
"with error:\n"
"\t%s\n"
"However, the parser succeeded",
source->ToCString().get(),
FormatMessage(log.ErrorMessageData())->ToCString().get());
CHECK(false);
} else if (result == kError) {
v8::base::OS::Print(
"Expected error on:\n"
"\t%s\n"
"However, parser and preparser succeeded",
source->ToCString().get());
CHECK(false);
} else if (preparser_materialized_literals != parser_materialized_literals) {
v8::base::OS::Print(
"Preparser materialized literals (%d) differ from Parser materialized "
"literals (%d) on:\n"
"\t%s\n"
"However, parser and preparser succeeded",
preparser_materialized_literals, parser_materialized_literals,
source->ToCString().get());
CHECK(false);
}
}
void TestParserSync(const char* source, const ParserFlag* varying_flags,
size_t varying_flags_length,
ParserSyncTestResult result = kSuccessOrError,
const ParserFlag* always_true_flags = NULL,
size_t always_true_flags_length = 0,
const ParserFlag* always_false_flags = NULL,
size_t always_false_flags_length = 0,
bool is_module = false) {
i::Handle<i::String> str =
CcTest::i_isolate()->factory()->NewStringFromAsciiChecked(source);
for (int bits = 0; bits < (1 << varying_flags_length); bits++) {
i::EnumSet<ParserFlag> flags;
for (size_t flag_index = 0; flag_index < varying_flags_length;
++flag_index) {
if ((bits & (1 << flag_index)) != 0) flags.Add(varying_flags[flag_index]);
}
for (size_t flag_index = 0; flag_index < always_true_flags_length;
++flag_index) {
flags.Add(always_true_flags[flag_index]);
}
for (size_t flag_index = 0; flag_index < always_false_flags_length;
++flag_index) {
flags.Remove(always_false_flags[flag_index]);
}
TestParserSyncWithFlags(str, flags, result, is_module);
}
}
TEST(ParserSync) {
const char* context_data[][2] = {
{ "", "" },
{ "{", "}" },
{ "if (true) ", " else {}" },
{ "if (true) {} else ", "" },
{ "if (true) ", "" },
{ "do ", " while (false)" },
{ "while (false) ", "" },
{ "for (;;) ", "" },
{ "with ({})", "" },
{ "switch (12) { case 12: ", "}" },
{ "switch (12) { default: ", "}" },
{ "switch (12) { ", "case 12: }" },
{ "label2: ", "" },
{ NULL, NULL }
};
const char* statement_data[] = {
"{}",
"var x",
"var x = 1",
"const x",
"const x = 1",
";",
"12",
"if (false) {} else ;",
"if (false) {} else {}",
"if (false) {} else 12",
"if (false) ;",
"if (false) {}",
"if (false) 12",
"do {} while (false)",
"for (;;) ;",
"for (;;) {}",
"for (;;) 12",
"continue",
"continue label",
"continue\nlabel",
"break",
"break label",
"break\nlabel",
// TODO(marja): activate once parsing 'return' is merged into ParserBase.
// "return",
// "return 12",
// "return\n12",
"with ({}) ;",
"with ({}) {}",
"with ({}) 12",
"switch ({}) { default: }",
"label3: ",
"throw",
"throw 12",
"throw\n12",
"try {} catch(e) {}",
"try {} finally {}",
"try {} catch(e) {} finally {}",
"debugger",
NULL
};
const char* termination_data[] = {
"",
";",
"\n",
";\n",
"\n;",
NULL
};
v8::HandleScope handles(CcTest::isolate());
v8::Local<v8::Context> context = v8::Context::New(CcTest::isolate());
v8::Context::Scope context_scope(context);
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
for (int i = 0; context_data[i][0] != NULL; ++i) {
for (int j = 0; statement_data[j] != NULL; ++j) {
for (int k = 0; termination_data[k] != NULL; ++k) {
int kPrefixLen = i::StrLength(context_data[i][0]);
int kStatementLen = i::StrLength(statement_data[j]);
int kTerminationLen = i::StrLength(termination_data[k]);
int kSuffixLen = i::StrLength(context_data[i][1]);
int kProgramSize = kPrefixLen + kStatementLen + kTerminationLen
+ kSuffixLen + i::StrLength("label: for (;;) { }");
// Plug the source code pieces together.
i::ScopedVector<char> program(kProgramSize + 1);
int length = i::SNPrintF(program,
"label: for (;;) { %s%s%s%s }",
context_data[i][0],
statement_data[j],
termination_data[k],
context_data[i][1]);
CHECK(length == kProgramSize);
TestParserSync(program.start(), NULL, 0);
}
}
}
// Neither Harmony numeric literals nor our natives syntax have any
// interaction with the flags above, so test these separately to reduce
// the combinatorial explosion.
TestParserSync("0o1234", NULL, 0);
TestParserSync("0b1011", NULL, 0);
static const ParserFlag flags3[] = { kAllowNatives };
TestParserSync("%DebugPrint(123)", flags3, arraysize(flags3));
}
TEST(StrictOctal) {
// Test that syntax error caused by octal literal is reported correctly as
// such (issue 2220).
v8::V8::Initialize();
v8::HandleScope scope(CcTest::isolate());
v8::Context::Scope context_scope(
v8::Context::New(CcTest::isolate()));
v8::TryCatch try_catch(CcTest::isolate());
const char* script =
"\"use strict\"; \n"
"a = function() { \n"
" b = function() { \n"
" 01; \n"
" }; \n"
"}; \n";
v8_compile(v8_str(script));
CHECK(try_catch.HasCaught());
v8::String::Utf8Value exception(try_catch.Exception());
CHECK_EQ(0,
strcmp("SyntaxError: Octal literals are not allowed in strict mode.",
*exception));
}
void RunParserSyncTest(const char* context_data[][2],
const char* statement_data[],
ParserSyncTestResult result,
const ParserFlag* flags = NULL, int flags_len = 0,
const ParserFlag* always_true_flags = NULL,
int always_true_len = 0,
const ParserFlag* always_false_flags = NULL,
int always_false_len = 0, bool is_module = false) {
v8::HandleScope handles(CcTest::isolate());
v8::Local<v8::Context> context = v8::Context::New(CcTest::isolate());
v8::Context::Scope context_scope(context);
CcTest::i_isolate()->stack_guard()->SetStackLimit(
i::GetCurrentStackPosition() - 128 * 1024);
// Experimental feature flags should not go here; pass the flags as
// always_true_flags if the test needs them.
static const ParserFlag default_flags[] = {
kAllowLazy,
kAllowNatives,
};
ParserFlag* generated_flags = NULL;
if (flags == NULL) {
flags = default_flags;
flags_len = arraysize(default_flags);
if (always_true_flags != NULL || always_false_flags != NULL) {
// Remove always_true/false_flags from default_flags (if present).
CHECK((always_true_flags != NULL) == (always_true_len > 0));
CHECK((always_false_flags != NULL) == (always_false_len > 0));
generated_flags = new ParserFlag[flags_len + always_true_len];
int flag_index = 0;
for (int i = 0; i < flags_len; ++i) {
bool use_flag = true;
for (int j = 0; use_flag && j < always_true_len; ++j) {
if (flags[i] == always_true_flags[j]) use_flag = false;
}
for (int j = 0; use_flag && j < always_false_len; ++j) {
if (flags[i] == always_false_flags[j]) use_flag = false;
}
if (use_flag) generated_flags[flag_index++] = flags[i];
}
flags_len = flag_index;
flags = generated_flags;
}
}
for (int i = 0; context_data[i][0] != NULL; ++i) {
for (int j = 0; statement_data[j] != NULL; ++j) {
int kPrefixLen = i::StrLength(context_data[i][0]);
int kStatementLen = i::StrLength(statement_data[j]);
int kSuffixLen = i::StrLength(context_data[i][1]);
int kProgramSize = kPrefixLen + kStatementLen + kSuffixLen;
// Plug the source code pieces together.
i::ScopedVector<char> program(kProgramSize + 1);
int length = i::SNPrintF(program,
"%s%s%s",
context_data[i][0],
statement_data[j],
context_data[i][1]);
CHECK(length == kProgramSize);
TestParserSync(program.start(), flags, flags_len, result,
always_true_flags, always_true_len, always_false_flags,
always_false_len, is_module);
}
}
delete[] generated_flags;
}
void RunModuleParserSyncTest(const char* context_data[][2],
const char* statement_data[],
ParserSyncTestResult result,
const ParserFlag* flags = NULL, int flags_len = 0,
const ParserFlag* always_true_flags = NULL,
int always_true_len = 0,
const ParserFlag* always_false_flags = NULL,
int always_false_len = 0) {
RunParserSyncTest(context_data, statement_data, result, flags, flags_len,
always_true_flags, always_true_len, always_false_flags,
always_false_len, true);
}
TEST(ErrorsEvalAndArguments) {
// Tests that both preparsing and parsing produce the right kind of errors for
// using "eval" and "arguments" as identifiers. Without the strict mode, it's
// ok to use "eval" or "arguments" as identifiers. With the strict mode, it
// isn't.
const char* context_data[][2] = {
{"\"use strict\";", ""},
{"var eval; function test_func() {\"use strict\"; ", "}"},
{NULL, NULL}};
const char* statement_data[] = {
"var eval;",
"var arguments",
"var foo, eval;",
"var foo, arguments;",
"try { } catch (eval) { }",
"try { } catch (arguments) { }",
"function eval() { }",
"function arguments() { }",
"function foo(eval) { }",
"function foo(arguments) { }",
"function foo(bar, eval) { }",
"function foo(bar, arguments) { }",
"(eval) => { }",
"(arguments) => { }",
"(foo, eval) => { }",
"(foo, arguments) => { }",
"eval = 1;",
"arguments = 1;",
"var foo = eval = 1;",
"var foo = arguments = 1;",
"++eval;",
"++arguments;",
"eval++;",
"arguments++;",
NULL
};
RunParserSyncTest(context_data, statement_data, kError);
}
TEST(NoErrorsEvalAndArgumentsSloppy) {
// Tests that both preparsing and parsing accept "eval" and "arguments" as
// identifiers when needed.
const char* context_data[][2] = {
{ "", "" },
{ "function test_func() {", "}"},
{ NULL, NULL }
};
const char* statement_data[] = {
"var eval;",
"var arguments",
"var foo, eval;",
"var foo, arguments;",
"try { } catch (eval) { }",
"try { } catch (arguments) { }",
"function eval() { }",
"function arguments() { }",
"function foo(eval) { }",
"function foo(arguments) { }",
"function foo(bar, eval) { }",
"function foo(bar, arguments) { }",
"eval = 1;",
"arguments = 1;",
"var foo = eval = 1;",
"var foo = arguments = 1;",
"++eval;",
"++arguments;",
"eval++;",
"arguments++;",
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(NoErrorsEvalAndArgumentsStrict) {
const char* context_data[][2] = {
{ "\"use strict\";", "" },
{ "function test_func() { \"use strict\";", "}" },
{ "() => { \"use strict\"; ", "}" },
{ NULL, NULL }
};
const char* statement_data[] = {
"eval;",
"arguments;",
"var foo = eval;",
"var foo = arguments;",
"var foo = { eval: 1 };",
"var foo = { arguments: 1 };",
"var foo = { }; foo.eval = {};",
"var foo = { }; foo.arguments = {};",
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
#define FUTURE_STRICT_RESERVED_WORDS(V) \
V(implements) \
V(interface) \
V(let) \
V(package) \
V(private) \
V(protected) \
V(public) \
V(static) \
V(yield)
#define LIMITED_FUTURE_STRICT_RESERVED_WORDS(V) \
V(implements) \
V(let) \
V(static) \
V(yield)
#define FUTURE_STRICT_RESERVED_STATEMENTS(NAME) \
"var " #NAME ";", \
"var foo, " #NAME ";", \
"try { } catch (" #NAME ") { }", \
"function " #NAME "() { }", \
"(function " #NAME "() { })", \
"function foo(" #NAME ") { }", \
"function foo(bar, " #NAME ") { }", \
#NAME " = 1;", \
#NAME " += 1;", \
"var foo = " #NAME " = 1;", \
"++" #NAME ";", \
#NAME " ++;",
TEST(ErrorsFutureStrictReservedWords) {
// Tests that both preparsing and parsing produce the right kind of errors for
// using future strict reserved words as identifiers. Without the strict mode,
// it's ok to use future strict reserved words as identifiers. With the strict
// mode, it isn't.
const char* context_data[][2] = {
{"function test_func() {\"use strict\"; ", "}"},
{"() => { \"use strict\"; ", "}"},
{NULL, NULL}};
const char* statement_data[] {
LIMITED_FUTURE_STRICT_RESERVED_WORDS(FUTURE_STRICT_RESERVED_STATEMENTS)
NULL
};
RunParserSyncTest(context_data, statement_data, kError);
}
#undef LIMITED_FUTURE_STRICT_RESERVED_WORDS
TEST(NoErrorsFutureStrictReservedWords) {
const char* context_data[][2] = {
{ "", "" },
{ "function test_func() {", "}"},
{ "() => {", "}" },
{ NULL, NULL }
};
const char* statement_data[] = {
FUTURE_STRICT_RESERVED_WORDS(FUTURE_STRICT_RESERVED_STATEMENTS)
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(ErrorsReservedWords) {
// Tests that both preparsing and parsing produce the right kind of errors for
// using future reserved words as identifiers. These tests don't depend on the
// strict mode.
const char* context_data[][2] = {
{ "", "" },
{ "\"use strict\";", "" },
{ "var eval; function test_func() {", "}"},
{ "var eval; function test_func() {\"use strict\"; ", "}"},
{ "var eval; () => {", "}"},
{ "var eval; () => {\"use strict\"; ", "}"},
{ NULL, NULL }
};
const char* statement_data[] = {
"var super;",
"var foo, super;",
"try { } catch (super) { }",
"function super() { }",
"function foo(super) { }",
"function foo(bar, super) { }",
"(super) => { }",
"(bar, super) => { }",
"super = 1;",
"var foo = super = 1;",
"++super;",
"super++;",
"function foo super",
NULL
};
RunParserSyncTest(context_data, statement_data, kError);
}
TEST(NoErrorsLetSloppyAllModes) {
// In sloppy mode, it's okay to use "let" as identifier.
const char* context_data[][2] = {
{ "", "" },
{ "function f() {", "}" },
{ "(function f() {", "})" },
{ NULL, NULL }
};
const char* statement_data[] = {
"var let;",
"var foo, let;",
"try { } catch (let) { }",
"function let() { }",
"(function let() { })",
"function foo(let) { }",
"function foo(bar, let) { }",
"let = 1;",
"var foo = let = 1;",
"let * 2;",
"++let;",
"let++;",
"let: 34",
"function let(let) { let: let(let + let(0)); }",
"({ let: 1 })",
"({ get let() { 1 } })",
"let(100)",
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(NoErrorsYieldSloppyAllModes) {
// In sloppy mode, it's okay to use "yield" as identifier, *except* inside a
// generator (see other test).
const char* context_data[][2] = {
{ "", "" },
{ "function not_gen() {", "}" },
{ "(function not_gen() {", "})" },
{ NULL, NULL }
};
const char* statement_data[] = {
"var yield;",
"var foo, yield;",
"try { } catch (yield) { }",
"function yield() { }",
"(function yield() { })",
"function foo(yield) { }",
"function foo(bar, yield) { }",
"yield = 1;",
"var foo = yield = 1;",
"yield * 2;",
"++yield;",
"yield++;",
"yield: 34",
"function yield(yield) { yield: yield (yield + yield(0)); }",
"({ yield: 1 })",
"({ get yield() { 1 } })",
"yield(100)",
"yield[100]",
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(NoErrorsYieldSloppyGeneratorsEnabled) {
// In sloppy mode, it's okay to use "yield" as identifier, *except* inside a
// generator (see next test).
const char* context_data[][2] = {
{ "", "" },
{ "function not_gen() {", "}" },
{ "function * gen() { function not_gen() {", "} }" },
{ "(function not_gen() {", "})" },
{ "(function * gen() { (function not_gen() {", "}) })" },
{ NULL, NULL }
};
const char* statement_data[] = {
"var yield;",
"var foo, yield;",
"try { } catch (yield) { }",
"function yield() { }",
"(function yield() { })",
"function foo(yield) { }",
"function foo(bar, yield) { }",
"function * yield() { }",
"yield = 1;",
"var foo = yield = 1;",
"yield * 2;",
"++yield;",
"yield++;",
"yield: 34",
"function yield(yield) { yield: yield (yield + yield(0)); }",
"({ yield: 1 })",
"({ get yield() { 1 } })",
"yield(100)",
"yield[100]",
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(ErrorsYieldStrict) {
const char* context_data[][2] = {
{"\"use strict\";", ""},
{"\"use strict\"; function not_gen() {", "}"},
{"function test_func() {\"use strict\"; ", "}"},
{"\"use strict\"; function * gen() { function not_gen() {", "} }"},
{"\"use strict\"; (function not_gen() {", "})"},
{"\"use strict\"; (function * gen() { (function not_gen() {", "}) })"},
{"() => {\"use strict\"; ", "}"},
{NULL, NULL}};
const char* statement_data[] = {
"var yield;",
"var foo, yield;",
"try { } catch (yield) { }",
"function yield() { }",
"(function yield() { })",
"function foo(yield) { }",
"function foo(bar, yield) { }",
"function * yield() { }",
"(function * yield() { })",
"yield = 1;",
"var foo = yield = 1;",
"++yield;",
"yield++;",
"yield: 34;",
NULL
};
RunParserSyncTest(context_data, statement_data, kError);
}
TEST(ErrorsYieldSloppy) {
const char* context_data[][2] = {
{ "", "" },
{ "function not_gen() {", "}" },
{ "(function not_gen() {", "})" },
{ NULL, NULL }
};
const char* statement_data[] = {
"(function * yield() { })",
NULL
};
RunParserSyncTest(context_data, statement_data, kError);
}
TEST(NoErrorsGenerator) {
// clang-format off
const char* context_data[][2] = {
{ "function * gen() {", "}" },
{ "(function * gen() {", "})" },
{ "(function * () {", "})" },
{ NULL, NULL }
};
const char* statement_data[] = {
// A generator without a body is valid.
""
// Valid yield expressions inside generators.
"yield 2;",
"yield * 2;",
"yield * \n 2;",
"yield yield 1;",
"yield * yield * 1;",
"yield 3 + (yield 4);",
"yield * 3 + (yield * 4);",
"(yield * 3) + (yield * 4);",
"yield 3; yield 4;",
"yield * 3; yield * 4;",
"(function (yield) { })",
"(function yield() { })",
"yield { yield: 12 }",
"yield /* comment */ { yield: 12 }",
"yield * \n { yield: 12 }",
"yield /* comment */ * \n { yield: 12 }",
// You can return in a generator.
"yield 1; return",
"yield * 1; return",
"yield 1; return 37",
"yield * 1; return 37",
"yield 1; return 37; yield 'dead';",
"yield * 1; return 37; yield * 'dead';",
// Yield is still a valid key in object literals.
"({ yield: 1 })",
"({ get yield() { } })",
// And in assignment pattern computed properties
"({ [yield]: x } = { })",
// Yield without RHS.
"yield;",
"yield",
"yield\n",
"yield /* comment */"
"yield // comment\n"
"(yield)",
"[yield]",
"{yield}",
"yield, yield",
"yield; yield",
"(yield) ? yield : yield",
"(yield) \n ? yield : yield",
// If there is a newline before the next token, we don't look for RHS.
"yield\nfor (;;) {}",
NULL
};
// clang-format on
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(ErrorsYieldGenerator) {
// clang-format off
const char* context_data[][2] = {
{ "function * gen() {", "}" },
{ "\"use strict\"; function * gen() {", "}" },
{ NULL, NULL }
};
const char* statement_data[] = {
// Invalid yield expressions inside generators.
"var yield;",
"var foo, yield;",
"try { } catch (yield) { }",
"function yield() { }",
// The name of the NFE is bound in the generator, which does not permit
// yield to be an identifier.
"(function * yield() { })",
// Yield isn't valid as a formal parameter for generators.
"function * foo(yield) { }",
"(function * foo(yield) { })",
"yield = 1;",
"var foo = yield = 1;",
"++yield;",
"yield++;",
"yield *",
"(yield *)",
// Yield binds very loosely, so this parses as "yield (3 + yield 4)", which
// is invalid.
"yield 3 + yield 4;",
"yield: 34",
"yield ? 1 : 2",
// Parses as yield (/ yield): invalid.
"yield / yield",
"+ yield",
"+ yield 3",
// Invalid (no newline allowed between yield and *).
"yield\n*3",
// Invalid (we see a newline, so we parse {yield:42} as a statement, not an
// object literal, and yield is not a valid label).
"yield\n{yield: 42}",
"yield /* comment */\n {yield: 42}",
"yield //comment\n {yield: 42}",
// Destructuring binding and assignment are both disallowed
"var [yield] = [42];",
"var {foo: yield} = {a: 42};",
"[yield] = [42];",
"({a: yield} = {a: 42});",
// Also disallow full yield expressions on LHS
"var [yield 24] = [42];",
"var {foo: yield 24} = {a: 42};",
"[yield 24] = [42];",
"({a: yield 24} = {a: 42});",
"for (yield 'x' in {});",
"for (yield 'x' of {});",
"for (yield 'x' in {} in {});",
"for (yield 'x' in {} of {});",
NULL
};
// clang-format on
RunParserSyncTest(context_data, statement_data, kError);
}
TEST(ErrorsNameOfStrictFunction) {
// Tests that illegal tokens as names of a strict function produce the correct
// errors.
const char* context_data[][2] = {
{ "function ", ""},
{ "\"use strict\"; function", ""},
{ "function * ", ""},
{ "\"use strict\"; function * ", ""},
{ NULL, NULL }
};
const char* statement_data[] = {
"eval() {\"use strict\";}",
"arguments() {\"use strict\";}",
"interface() {\"use strict\";}",
"yield() {\"use strict\";}",
// Future reserved words are always illegal
"super() { }",
"super() {\"use strict\";}",
NULL
};
RunParserSyncTest(context_data, statement_data, kError);
}
TEST(NoErrorsNameOfStrictFunction) {
const char* context_data[][2] = {
{ "function ", ""},
{ NULL, NULL }
};
const char* statement_data[] = {
"eval() { }",
"arguments() { }",
"interface() { }",
"yield() { }",
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(NoErrorsNameOfStrictGenerator) {
const char* context_data[][2] = {
{ "function * ", ""},
{ NULL, NULL }
};
const char* statement_data[] = {
"eval() { }",
"arguments() { }",
"interface() { }",
"yield() { }",
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(ErrorsIllegalWordsAsLabelsSloppy) {
// Using future reserved words as labels is always an error.
const char* context_data[][2] = {
{ "", ""},
{ "function test_func() {", "}" },
{ "() => {", "}" },
{ NULL, NULL }
};
const char* statement_data[] = {
"super: while(true) { break super; }",
NULL
};
RunParserSyncTest(context_data, statement_data, kError);
}
TEST(ErrorsIllegalWordsAsLabelsStrict) {
// Tests that illegal tokens as labels produce the correct errors.
const char* context_data[][2] = {
{"\"use strict\";", ""},
{"function test_func() {\"use strict\"; ", "}"},
{"() => {\"use strict\"; ", "}"},
{NULL, NULL}};
#define LABELLED_WHILE(NAME) #NAME ": while (true) { break " #NAME "; }",
const char* statement_data[] = {
"super: while(true) { break super; }",
FUTURE_STRICT_RESERVED_WORDS(LABELLED_WHILE)
NULL
};
#undef LABELLED_WHILE
RunParserSyncTest(context_data, statement_data, kError);
}
TEST(NoErrorsIllegalWordsAsLabels) {
// Using eval and arguments as labels is legal even in strict mode.
const char* context_data[][2] = {
{ "", ""},
{ "function test_func() {", "}" },
{ "() => {", "}" },
{ "\"use strict\";", "" },
{ "\"use strict\"; function test_func() {", "}" },
{ "\"use strict\"; () => {", "}" },
{ NULL, NULL }
};
const char* statement_data[] = {
"mylabel: while(true) { break mylabel; }",
"eval: while(true) { break eval; }",
"arguments: while(true) { break arguments; }",
NULL
};
RunParserSyncTest(context_data, statement_data, kSuccess);
}
TEST(NoErrorsFutureStrictReservedAsLabelsSloppy) {
const char* context_data[][2] = {
{ "", ""},
{ "function test_func() {", "}" },
{ "() => {", "}" },
{ NULL, NULL }
};
#define LABELLED_WHILE(NAME) #NAME ": while (true) { break " #NAME "; }",
const char* statement_data[] {
FUTURE_STRICT_RESERVED_WORDS(LABELLED_WHILE)
NULL
};
#undef LABELLED_WHILE
RunParserSyncTest(context_data, statement_data, kSuccess);
}