test-parsing.cc 133 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// 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.

28
#include <stdio.h>
29
#include <stdlib.h>
30
#include <string.h>
31

32
#include "src/v8.h"
33

34 35
#include "src/ast.h"
#include "src/ast-numbering.h"
36
#include "src/ast-value-factory.h"
37 38 39 40 41 42
#include "src/compiler.h"
#include "src/execution.h"
#include "src/isolate.h"
#include "src/objects.h"
#include "src/parser.h"
#include "src/preparser.h"
43
#include "src/rewriter.h"
44 45 46
#include "src/scanner-character-streams.h"
#include "src/token.h"
#include "src/utils.h"
47

48
#include "test/cctest/cctest.h"
49

50
TEST(ScanKeywords) {
51 52 53 54 55 56 57
  struct KeywordToken {
    const char* keyword;
    i::Token::Value token;
  };

  static const KeywordToken keywords[] = {
#define KEYWORD(t, s, d) { s, i::Token::t },
58
      TOKEN_LIST(IGNORE_TOKEN, KEYWORD)
59 60 61 62 63
#undef KEYWORD
      { NULL, i::Token::IDENTIFIER }
  };

  KeywordToken key_token;
64 65
  i::UnicodeCache unicode_cache;
  i::byte buffer[32];
66
  for (int i = 0; (key_token = keywords[i]).keyword != NULL; i++) {
67 68 69 70 71
    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);
    {
72
      i::Utf8ToUtf16CharacterStream stream(keyword, length);
73
      i::Scanner scanner(&unicode_cache);
74
      // The scanner should parse Harmony keywords for this test.
75
      scanner.SetHarmonyScoping(true);
76
      scanner.SetHarmonyModules(true);
77
      scanner.SetHarmonyClasses(true);
78
      scanner.Initialize(&stream);
79 80
      CHECK_EQ(key_token.token, scanner.Next());
      CHECK_EQ(i::Token::EOS, scanner.Next());
81
    }
82 83
    // Removing characters will make keyword matching fail.
    {
84
      i::Utf8ToUtf16CharacterStream stream(keyword, length - 1);
85
      i::Scanner scanner(&unicode_cache);
86 87 88 89 90 91
      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', '_' };
92
    for (int j = 0; j < static_cast<int>(arraysize(chars_to_append)); ++j) {
93
      i::MemMove(buffer, keyword, length);
94
      buffer[length] = chars_to_append[j];
95
      i::Utf8ToUtf16CharacterStream stream(buffer, length + 1);
96
      i::Scanner scanner(&unicode_cache);
97 98 99 100 101 102
      scanner.Initialize(&stream);
      CHECK_EQ(i::Token::IDENTIFIER, scanner.Next());
      CHECK_EQ(i::Token::EOS, scanner.Next());
    }
    // Replacing characters will make keyword matching fail.
    {
103
      i::MemMove(buffer, keyword, length);
104
      buffer[length - 1] = '_';
105
      i::Utf8ToUtf16CharacterStream stream(buffer, length);
106
      i::Scanner scanner(&unicode_cache);
107 108 109
      scanner.Initialize(&stream);
      CHECK_EQ(i::Token::IDENTIFIER, scanner.Next());
      CHECK_EQ(i::Token::EOS, scanner.Next());
110 111 112 113
    }
  }
}

114 115

TEST(ScanHTMLEndComments) {
116
  v8::V8::Initialize();
117
  v8::Isolate* isolate = CcTest::isolate();
118
  v8::HandleScope handles(isolate);
119

120 121 122
  // 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
123 124 125
  // 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
126 127 128 129 130 131 132 133 134 135 136 137 138
  // 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
  };

139 140 141 142 143 144 145 146 147 148
  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
  };

149
  // Parser/Scanner needs a stack limit.
150 151
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
152
  uintptr_t stack_limit = CcTest::i_isolate()->stack_guard()->real_climit();
153
  for (int i = 0; tests[i]; i++) {
154 155 156 157 158 159 160 161 162 163
    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::PreParser preparser(&scanner, &log, stack_limit);
    preparser.set_allow_lazy(true);
    i::PreParser::PreParseResult result = preparser.PreParseProgram();
    CHECK_EQ(i::PreParser::kPreParseSuccess, result);
164
    CHECK(!log.HasError());
165
  }
166 167

  for (int i = 0; fail_tests[i]; i++) {
168 169 170 171 172 173 174 175 176 177 178
    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::PreParser preparser(&scanner, &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);
179
    CHECK(log.HasError());
180
  }
181
}
182 183


184
class ScriptResource : public v8::String::ExternalOneByteStringResource {
185 186 187 188 189 190 191 192 193 194 195 196 197
 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_;
};


198
TEST(UsingCachedData) {
199
  v8::Isolate* isolate = CcTest::isolate();
200 201 202
  v8::HandleScope handles(isolate);
  v8::Local<v8::Context> context = v8::Context::New(isolate);
  v8::Context::Scope context_scope(context);
203 204
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
205 206 207 208 209 210 211 212 213 214 215 216 217

  // 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/gin;"
      "var y = { get getter() { return 42; }, "
218 219 220
      "          set setter(v) { this.value = v; }};"
      "var f = a => function (b) { return a + b; };"
      "var g = a => b => a + b;";
221
  int source_length = i::StrLength(source);
222

223 224 225
  // ScriptResource will be deleted when the corresponding String is GCd.
  v8::ScriptCompiler::Source script_source(v8::String::NewExternal(
      isolate, new ScriptResource(source, source_length)));
226
  i::FLAG_harmony_arrow_functions = true;
227 228
  i::FLAG_min_preparse_length = 0;
  v8::ScriptCompiler::Compile(isolate, &script_source,
229
                              v8::ScriptCompiler::kProduceParserCache);
230
  CHECK(script_source.GetCachedData());
231

232 233 234
  // Compile the script again, using the cached data.
  bool lazy_flag = i::FLAG_lazy;
  i::FLAG_lazy = true;
235 236
  v8::ScriptCompiler::Compile(isolate, &script_source,
                              v8::ScriptCompiler::kConsumeParserCache);
237
  i::FLAG_lazy = false;
238 239
  v8::ScriptCompiler::CompileUnbound(isolate, &script_source,
                                     v8::ScriptCompiler::kConsumeParserCache);
240 241
  i::FLAG_lazy = lazy_flag;
}
242 243


244 245 246
TEST(PreparseFunctionDataIsUsed) {
  // This tests that we actually do use the function data generated by the
  // preparser.
247 248 249

  // Make preparsing work for short scripts.
  i::FLAG_min_preparse_length = 0;
250
  i::FLAG_harmony_arrow_functions = true;
251

252 253 254 255
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope handles(isolate);
  v8::Local<v8::Context> context = v8::Context::New(isolate);
  v8::Context::Scope context_scope(context);
256 257
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
258

259 260 261 262
  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();",
  };
263 264

  // Insert a syntax error inside the lazy function.
265 266 267 268
  const char* bad_code[] = {
      "function this_is_lazy() { if (   } function foo() { return 25; } foo();",
      "var this_is_lazy = () => { if (   }; var foo = () => 25; foo();",
  };
269

270
  for (unsigned i = 0; i < arraysize(good_code); i++) {
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    v8::ScriptCompiler::Source good_source(v8_str(good_code[i]));
    v8::ScriptCompiler::Compile(isolate, &good_source,
                                v8::ScriptCompiler::kProduceDataToCache);

    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 =
        v8::ScriptCompiler::Compile(isolate, &bad_source)->Run();
    CHECK(result->IsInt32());
    CHECK_EQ(25, result->Int32Value());
  }
291 292 293
}


294
TEST(StandAlonePreParser) {
295 296
  v8::V8::Initialize();

297 298
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
299 300

  const char* programs[] = {
301 302 303 304 305
      "{label: 42}",
      "var x = 42;",
      "function foo(x, y) { return x + y; }",
      "%ArgleBargle(glop);",
      "var x = new new Function('this.x = 42');",
306
      "var f = (x, y) => x + y;",
307 308
      NULL
  };
309

310
  uintptr_t stack_limit = CcTest::i_isolate()->stack_guard()->real_climit();
311 312
  for (int i = 0; programs[i]; i++) {
    const char* program = programs[i];
313
    i::Utf8ToUtf16CharacterStream stream(
314 315
        reinterpret_cast<const i::byte*>(program),
        static_cast<unsigned>(strlen(program)));
316
    i::CompleteParserRecorder log;
317
    i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
318
    scanner.Initialize(&stream);
319

320
    i::PreParser preparser(&scanner, &log, stack_limit);
321 322
    preparser.set_allow_lazy(true);
    preparser.set_allow_natives_syntax(true);
323
    preparser.set_allow_arrow_functions(true);
324 325
    i::PreParser::PreParseResult result = preparser.PreParseProgram();
    CHECK_EQ(i::PreParser::kPreParseSuccess, result);
326
    CHECK(!log.HasError());
327 328
  }
}
329 330


331 332 333
TEST(StandAlonePreParserNoNatives) {
  v8::V8::Initialize();

334 335
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
336 337 338 339 340 341 342

  const char* programs[] = {
      "%ArgleBargle(glop);",
      "var x = %_IsSmi(42);",
      NULL
  };

343
  uintptr_t stack_limit = CcTest::i_isolate()->stack_guard()->real_climit();
344 345
  for (int i = 0; programs[i]; i++) {
    const char* program = programs[i];
346
    i::Utf8ToUtf16CharacterStream stream(
347 348 349
        reinterpret_cast<const i::byte*>(program),
        static_cast<unsigned>(strlen(program)));
    i::CompleteParserRecorder log;
350
    i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
351 352
    scanner.Initialize(&stream);

353
    // Preparser defaults to disallowing natives syntax.
354
    i::PreParser preparser(&scanner, &log, stack_limit);
355
    preparser.set_allow_lazy(true);
356 357
    i::PreParser::PreParseResult result = preparser.PreParseProgram();
    CHECK_EQ(i::PreParser::kPreParseSuccess, result);
358
    CHECK(log.HasError());
359 360 361 362
  }
}


363 364 365 366 367 368 369
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);
370 371
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
372 373 374

  {
    const char* source = "var myo = {if: \"foo\"}; myo.if;";
375
    v8::Local<v8::Value> result = ParserCacheCompileRun(source);
376 377 378 379 380 381 382
    CHECK(result->IsString());
    v8::String::Utf8Value utf8(result);
    CHECK_EQ("foo", *utf8);
  }

  {
    const char* source = "var myo = {\"bar\": \"foo\"}; myo[\"bar\"];";
383
    v8::Local<v8::Value> result = ParserCacheCompileRun(source);
384 385 386 387 388 389 390
    CHECK(result->IsString());
    v8::String::Utf8Value utf8(result);
    CHECK_EQ("foo", *utf8);
  }

  {
    const char* source = "var myo = {1: \"foo\"}; myo[1];";
391
    v8::Local<v8::Value> result = ParserCacheCompileRun(source);
392 393 394 395 396 397 398
    CHECK(result->IsString());
    v8::String::Utf8Value utf8(result);
    CHECK_EQ("foo", *utf8);
  }
}


399
TEST(RegressChromium62639) {
400
  v8::V8::Initialize();
401
  i::Isolate* isolate = CcTest::i_isolate();
402

403 404
  isolate->stack_guard()->SetStackLimit(i::GetCurrentStackPosition() -
                                        128 * 1024);
405

406 407
  const char* program = "var x = 'something';\n"
                        "escape: function() {}";
408 409 410 411 412
  // 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.

413 414 415
  i::Utf8ToUtf16CharacterStream stream(
      reinterpret_cast<const i::byte*>(program),
      static_cast<unsigned>(strlen(program)));
416 417 418 419 420 421 422 423 424
  i::CompleteParserRecorder log;
  i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
  scanner.Initialize(&stream);
  i::PreParser preparser(&scanner, &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);
425
  CHECK(log.HasError());
426
}
427 428 429


TEST(Regress928) {
430
  v8::V8::Initialize();
431
  i::Isolate* isolate = CcTest::i_isolate();
432
  i::Factory* factory = isolate->factory();
433

434 435 436 437
  // 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.
438 439
  isolate->stack_guard()->SetStackLimit(i::GetCurrentStackPosition() -
                                        128 * 1024);
440 441 442 443 444

  const char* program =
      "try { } catch (e) { var foo = function () { /* first */ } }"
      "var bar = function () { /* second */ }";

445
  v8::HandleScope handles(CcTest::isolate());
446
  i::Handle<i::String> source = factory->NewStringFromAsciiChecked(program);
447
  i::GenericStringUtf16CharacterStream stream(source, 0, source->length());
448 449 450 451 452 453 454 455
  i::CompleteParserRecorder log;
  i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
  scanner.Initialize(&stream);
  i::PreParser preparser(&scanner, &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);
456 457 458
  i::ScriptData* sd = log.GetScriptData();
  i::ParseData pd(sd);
  pd.Initialize();
459

460 461
  int first_function =
      static_cast<int>(strstr(program, "function") - program);
462
  int first_lbrace = first_function + i::StrLength("function () ");
463
  CHECK_EQ('{', program[first_lbrace]);
464
  i::FunctionEntry entry1 = pd.GetFunctionEntry(first_lbrace);
465 466
  CHECK(!entry1.is_valid());

467 468
  int second_function =
      static_cast<int>(strstr(program + first_lbrace, "function") - program);
469
  int second_lbrace =
470
      second_function + i::StrLength("function () ");
471
  CHECK_EQ('{', program[second_lbrace]);
472
  i::FunctionEntry entry2 = pd.GetFunctionEntry(second_lbrace);
473 474
  CHECK(entry2.is_valid());
  CHECK_EQ('}', program[entry2.end_pos() - 1]);
475
  delete sd;
476
}
477 478 479


TEST(PreParseOverflow) {
480 481
  v8::V8::Initialize();

482 483
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
484 485

  size_t kProgramSize = 1024 * 1024;
486
  i::SmartArrayPointer<char> program(i::NewArray<char>(kProgramSize + 1));
487
  memset(program.get(), '(', kProgramSize);
488 489
  program[kProgramSize] = '\0';

490
  uintptr_t stack_limit = CcTest::i_isolate()->stack_guard()->real_climit();
491

492
  i::Utf8ToUtf16CharacterStream stream(
493
      reinterpret_cast<const i::byte*>(program.get()),
494
      static_cast<unsigned>(kProgramSize));
495
  i::CompleteParserRecorder log;
496
  i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
497
  scanner.Initialize(&stream);
498

499
  i::PreParser preparser(&scanner, &log, stack_limit);
500
  preparser.set_allow_lazy(true);
501
  preparser.set_allow_arrow_functions(true);
502 503
  i::PreParser::PreParseResult result = preparser.PreParseProgram();
  CHECK_EQ(i::PreParser::kPreParseStackOverflow, result);
504
}
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528


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))

529 530
void TestCharacterStream(const char* one_byte_source, unsigned length,
                         unsigned start = 0, unsigned end = 0) {
531 532
  if (end == 0) end = length;
  unsigned sub_length = end - start;
533
  i::Isolate* isolate = CcTest::i_isolate();
534 535
  i::Factory* factory = isolate->factory();
  i::HandleScope test_scope(isolate);
536
  i::SmartArrayPointer<i::uc16> uc16_buffer(new i::uc16[length]);
537
  for (unsigned i = 0; i < length; i++) {
538
    uc16_buffer[i] = static_cast<i::uc16>(one_byte_source[i]);
539
  }
540 541 542 543
  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();
544
  TestExternalResource resource(uc16_buffer.get(), length);
545
  i::Handle<i::String> uc16_string(
546
      factory->NewExternalStringFromTwoByte(&resource).ToHandleChecked());
547

548
  i::ExternalTwoByteStringUtf16CharacterStream uc16_stream(
549
      i::Handle<i::ExternalTwoByteString>::cast(uc16_string), start, end);
550 551
  i::GenericStringUtf16CharacterStream string_stream(one_byte_string, start,
                                                     end);
552
  i::Utf8ToUtf16CharacterStream utf8_stream(
553
      reinterpret_cast<const i::byte*>(one_byte_source), end);
554 555 556 557 558 559 560 561
  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());
562
    int32_t c0 = one_byte_source[i];
563 564 565 566 567 568 569 570 571 572 573 574 575
    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.
576
    int32_t c0 = one_byte_source[i - 1];
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    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());
619
    int32_t c0 = one_byte_source[i];
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    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) {
642
  v8::Isolate* isolate = CcTest::isolate();
643 644 645
  v8::HandleScope handles(isolate);
  v8::Local<v8::Context> context = v8::Context::New(isolate);
  v8::Context::Scope context_scope(context);
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675

  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++) {
676 677 678
    cursor += unibrow::Utf8::Encode(buffer + cursor,
                                    i,
                                    unibrow::Utf16::kNoPreviousCharacter);
679
  }
680
  DCHECK(cursor == kAllUtf8CharsSizeU);
681

682 683
  i::Utf8ToUtf16CharacterStream stream(reinterpret_cast<const i::byte*>(buffer),
                                       kAllUtf8CharsSizeU);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
  for (int i = 0; i <= kMaxUC16Char; i++) {
    CHECK_EQU(i, stream.pos());
    int32_t c = stream.Advance();
    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());
    unsigned progress = stream.SeekForward(12);
    i += progress;
    int32_t c = stream.Advance();
    if (i <= kMaxUC16Char) {
      CHECK_EQ(i, c);
    } else {
      CHECK_EQ(-1, c);
    }
    i += 1;
    CHECK_EQU(i, stream.pos());
  }
}

#undef CHECK_EQU

713
void TestStreamScanner(i::Utf16CharacterStream* stream,
714 715 716
                       i::Token::Value* expected_tokens,
                       int skip_pos = 0,  // Zero means not skipping.
                       int skip_to = 0) {
717
  i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
718
  scanner.Initialize(stream);
719 720 721 722 723 724 725 726 727 728 729 730 731

  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);
}

732

733
TEST(StreamScanner) {
734 735
  v8::V8::Initialize();

736
  const char* str1 = "{ foo get for : */ <- \n\n /*foo*/ bib";
737 738
  i::Utf8ToUtf16CharacterStream stream1(reinterpret_cast<const i::byte*>(str1),
                                        static_cast<unsigned>(strlen(str1)));
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
  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";
756 757
  i::Utf8ToUtf16CharacterStream stream2(reinterpret_cast<const i::byte*>(str2),
                                        static_cast<unsigned>(strlen(str2)));
758 759 760 761 762 763 764 765 766 767 768
  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
  };
769 770
  DCHECK_EQ('{', str2[19]);
  DCHECK_EQ('}', str2[37]);
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
  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;
787
     i::Utf8ToUtf16CharacterStream stream3(
788 789 790 791 792
         reinterpret_cast<const i::byte*>(str3),
         static_cast<unsigned>(strlen(str3)));
     TestStreamScanner(&stream3, expectations3, 1, 1 + i);
  }
}
793 794 795


void TestScanRegExp(const char* re_source, const char* expected) {
796
  i::Utf8ToUtf16CharacterStream stream(
797 798
       reinterpret_cast<const i::byte*>(re_source),
       static_cast<unsigned>(strlen(re_source)));
799
  i::HandleScope scope(CcTest::i_isolate());
800
  i::Scanner scanner(CcTest::i_isolate()->unicode_cache());
801 802 803 804 805 806
  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.
807 808 809 810
  i::Zone zone(CcTest::i_isolate());
  i::AstValueFactory ast_value_factory(&zone,
                                       CcTest::i_isolate()->heap()->HashSeed());
  ast_value_factory.Internalize(CcTest::i_isolate());
811
  i::Handle<i::String> val =
812
      scanner.CurrentSymbol(&ast_value_factory)->string();
813 814
  i::DisallowHeapAllocation no_alloc;
  i::String::FlatContent content = val->GetFlatContent();
815
  CHECK(content.IsOneByte());
816
  i::Vector<const uint8_t> actual = content.ToOneByteVector();
817 818 819 820 821 822 823 824
  for (int i = 0; i < actual.length(); i++) {
    CHECK_NE('\0', expected[i]);
    CHECK_EQ(expected[i], actual[i]);
  }
}


TEST(RegExpScanning) {
825 826
  v8::V8::Initialize();

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
  // 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("/=?/", "=?");
}
859 860


861
static int Utf8LengthHelper(const char* s) {
862
  int len = i::StrLength(s);
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
  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;
        }
        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;
}


922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
TEST(ScopeUsesThisAndArguments) {
  static const struct {
    const char* prefix;
    const char* suffix;
  } surroundings[] = {
    { "function f() {", "}" },
    { "var f = () => {", "}" },
  };

  static const struct {
    const char* body;
    bool uses_this;
    bool uses_arguments;
    bool inner_uses_this;
    bool inner_uses_arguments;
  } source_data[] = {
    { "",
      false, false, false, false },
    { "return this",
      true, false, false, false },
    { "return arguments",
      false, true, false, false },
    { "return arguments[0]",
      false, true, false, false },
    { "return this + arguments[0]",
      true, true, false, false },
    { "return x => this + x",
      false, false, true, false },
    { "this.foo = 42;",
      true, false, false, false },
    { "this.foo();",
      true, false, false, false },
    { "if (foo()) { this.f() }",
      true, false, false, false },
    { "if (arguments.length) { this.f() }",
      true, true, false, false },
    { "while (true) { this.f() }",
      true, false, false, false },
    { "if (true) { while (true) this.foo(arguments) }",
      true, true, false, false },
    // Multiple nesting levels must work as well.
    { "while (true) { while (true) { while (true) return this } }",
      true, false, false, false },
    { "if (1) { return () => { while (true) new this() } }",
      false, false, true, false },
    // Note that propagation of the inner_uses_this() value does not
    // cross boundaries of normal functions onto parent scopes.
    { "return function (x) { return this + x }",
      false, false, false, false },
    { "var x = function () { this.foo = 42 };",
      false, false, false, false },
    { "if (1) { return function () { while (true) new this() } }",
      false, false, false, false },
    { "return function (x) { return () => this }",
      false, false, false, false },
    // Flags must be correctly set when using block scoping.
    { "\"use strict\"; while (true) { let x; this, arguments; }",
      false, false, true, true },
    { "\"use strict\"; if (foo()) { let x; this.f() }",
      false, false, true, false },
    { "\"use strict\"; if (1) {"
      "  let x; return function () { return this + arguments }"
      "}",
      false, false, false, false },
  };

  i::Isolate* isolate = CcTest::i_isolate();
  i::Factory* factory = isolate->factory();

  v8::HandleScope handles(CcTest::isolate());
  v8::Handle<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) {
      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::CompilationInfoWithZone info(script);
      i::Parser::ParseInfo parse_info = {isolate->stack_guard()->real_climit(),
                                         isolate->heap()->HashSeed(),
                                         isolate->unicode_cache()};
      i::Parser parser(&info, &parse_info);
      parser.set_allow_arrow_functions(true);
      parser.set_allow_harmony_scoping(true);
      info.MarkAsGlobal();
      parser.Parse();
      CHECK(i::Rewriter::Rewrite(&info));
      CHECK(i::Scope::Analyze(&info));
      CHECK(info.function() != NULL);

      i::Scope* global_scope = info.function()->scope();
      CHECK(global_scope->is_global_scope());
      CHECK_EQ(1, global_scope->inner_scopes()->length());

      i::Scope* scope = global_scope->inner_scopes()->at(0);
      CHECK_EQ(source_data[i].uses_this, scope->uses_this());
      CHECK_EQ(source_data[i].uses_arguments, scope->uses_arguments());
      CHECK_EQ(source_data[i].inner_uses_this, scope->inner_uses_this());
      CHECK_EQ(source_data[i].inner_uses_arguments,
               scope->inner_uses_arguments());
    }
  }
}


1038
TEST(ScopePositions) {
1039 1040
  v8::internal::FLAG_harmony_scoping = true;

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
  // 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;
1052
    i::StrictMode strict_mode;
1053 1054 1055
  };

  const SourceData source_data[] = {
1056 1057
    { "  with ({}) ", "{ block; }", " more;", i::WITH_SCOPE, i::SLOPPY },
    { "  with ({}) ", "{ block; }", "; more;", i::WITH_SCOPE, i::SLOPPY },
1058 1059 1060
    { "  with ({}) ", "{\n"
      "    block;\n"
      "  }", "\n"
1061 1062
      "  more;", i::WITH_SCOPE, i::SLOPPY },
    { "  with ({}) ", "statement;", " more;", i::WITH_SCOPE, i::SLOPPY },
1063
    { "  with ({}) ", "statement", "\n"
1064
      "  more;", i::WITH_SCOPE, i::SLOPPY },
1065 1066
    { "  with ({})\n"
      "    ", "statement;", "\n"
1067
      "  more;", i::WITH_SCOPE, i::SLOPPY },
1068
    { "  try {} catch ", "(e) { block; }", " more;",
1069
      i::CATCH_SCOPE, i::SLOPPY },
1070
    { "  try {} catch ", "(e) { block; }", "; more;",
1071
      i::CATCH_SCOPE, i::SLOPPY },
1072 1073 1074
    { "  try {} catch ", "(e) {\n"
      "    block;\n"
      "  }", "\n"
1075
      "  more;", i::CATCH_SCOPE, i::SLOPPY },
1076
    { "  try {} catch ", "(e) { block; }", " finally { block; } more;",
1077
      i::CATCH_SCOPE, i::SLOPPY },
1078
    { "  start;\n"
1079
      "  ", "{ let block; }", " more;", i::BLOCK_SCOPE, i::STRICT },
1080
    { "  start;\n"
1081
      "  ", "{ let block; }", "; more;", i::BLOCK_SCOPE, i::STRICT },
1082 1083 1084 1085
    { "  start;\n"
      "  ", "{\n"
      "    let block;\n"
      "  }", "\n"
1086
      "  more;", i::BLOCK_SCOPE, i::STRICT },
1087 1088
    { "  start;\n"
      "  function fun", "(a,b) { infunction; }", " more;",
1089
      i::FUNCTION_SCOPE, i::SLOPPY },
1090 1091 1092 1093
    { "  start;\n"
      "  function fun", "(a,b) {\n"
      "    infunction;\n"
      "  }", "\n"
1094
      "  more;", i::FUNCTION_SCOPE, i::SLOPPY },
1095
    { "  start;\n", "(a,b) => a + b", "; more;",
1096
      i::ARROW_SCOPE, i::SLOPPY },
1097
    { "  start;\n", "(a,b) => { return a+b; }", "\nmore;",
1098
      i::ARROW_SCOPE, i::SLOPPY },
1099 1100
    { "  start;\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1101
      i::FUNCTION_SCOPE, i::SLOPPY },
1102
    { "  for ", "(let x = 1 ; x < 10; ++ x) { block; }", " more;",
1103
      i::BLOCK_SCOPE, i::STRICT },
1104
    { "  for ", "(let x = 1 ; x < 10; ++ x) { block; }", "; more;",
1105
      i::BLOCK_SCOPE, i::STRICT },
1106 1107 1108
    { "  for ", "(let x = 1 ; x < 10; ++ x) {\n"
      "    block;\n"
      "  }", "\n"
1109
      "  more;", i::BLOCK_SCOPE, i::STRICT },
1110
    { "  for ", "(let x = 1 ; x < 10; ++ x) statement;", " more;",
1111
      i::BLOCK_SCOPE, i::STRICT },
1112
    { "  for ", "(let x = 1 ; x < 10; ++ x) statement", "\n"
1113
      "  more;", i::BLOCK_SCOPE, i::STRICT },
1114 1115
    { "  for ", "(let x = 1 ; x < 10; ++ x)\n"
      "    statement;", "\n"
1116
      "  more;", i::BLOCK_SCOPE, i::STRICT },
1117
    { "  for ", "(let x in {}) { block; }", " more;",
1118
      i::BLOCK_SCOPE, i::STRICT },
1119
    { "  for ", "(let x in {}) { block; }", "; more;",
1120
      i::BLOCK_SCOPE, i::STRICT },
1121 1122 1123
    { "  for ", "(let x in {}) {\n"
      "    block;\n"
      "  }", "\n"
1124
      "  more;", i::BLOCK_SCOPE, i::STRICT },
1125
    { "  for ", "(let x in {}) statement;", " more;",
1126
      i::BLOCK_SCOPE, i::STRICT },
1127
    { "  for ", "(let x in {}) statement", "\n"
1128
      "  more;", i::BLOCK_SCOPE, i::STRICT },
1129 1130
    { "  for ", "(let x in {})\n"
      "    statement;", "\n"
1131
      "  more;", i::BLOCK_SCOPE, i::STRICT },
1132 1133 1134 1135 1136
    // 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; }", ")();",
1137
      i::FUNCTION_SCOPE, i::SLOPPY },
1138 1139 1140
    // 4 byte encoding.
    { "  'foo\360\220\220\212';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1141
      i::FUNCTION_SCOPE, i::SLOPPY },
1142 1143 1144
    // 3 byte encoding of \u0fff.
    { "  'foo\340\277\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1145
      i::FUNCTION_SCOPE, i::SLOPPY },
1146 1147 1148
    // Broken 6 byte encoding with missing last byte.
    { "  'foo\355\240\201\355\211';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1149
      i::FUNCTION_SCOPE, i::SLOPPY },
1150 1151 1152
    // Broken 3 byte encoding of \u0fff with missing last byte.
    { "  'foo\340\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1153
      i::FUNCTION_SCOPE, i::SLOPPY },
1154 1155 1156
    // Broken 3 byte encoding of \u0fff with missing 2 last bytes.
    { "  'foo\340';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1157
      i::FUNCTION_SCOPE, i::SLOPPY },
1158 1159 1160
    // Broken 3 byte encoding of \u00ff should be a 2 byte encoding.
    { "  'foo\340\203\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1161
      i::FUNCTION_SCOPE, i::SLOPPY },
1162 1163 1164
    // Broken 3 byte encoding of \u007f should be a 2 byte encoding.
    { "  'foo\340\201\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1165
      i::FUNCTION_SCOPE, i::SLOPPY },
1166 1167 1168
    // Unpaired lead surrogate.
    { "  'foo\355\240\201';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1169
      i::FUNCTION_SCOPE, i::SLOPPY },
1170 1171 1172
    // 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; }", ")();",
1173
      i::FUNCTION_SCOPE, i::SLOPPY },
1174 1175 1176 1177
    // 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; }", ")();",
1178
      i::FUNCTION_SCOPE, i::SLOPPY },
1179 1180 1181
    // Unpaired trail surrogate.
    { "  'foo\355\260\211';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1182
      i::FUNCTION_SCOPE, i::SLOPPY },
1183 1184 1185
    // 2 byte encoding of \u00ff.
    { "  'foo\303\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1186
      i::FUNCTION_SCOPE, i::SLOPPY },
1187 1188 1189
    // Broken 2 byte encoding of \u00ff with missing last byte.
    { "  'foo\303';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1190
      i::FUNCTION_SCOPE, i::SLOPPY },
1191 1192 1193
    // Broken 2 byte encoding of \u007f should be a 1 byte encoding.
    { "  'foo\301\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1194
      i::FUNCTION_SCOPE, i::SLOPPY },
1195 1196 1197
    // Illegal 5 byte encoding.
    { "  'foo\370\277\277\277\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1198
      i::FUNCTION_SCOPE, i::SLOPPY },
1199 1200 1201
    // Illegal 6 byte encoding.
    { "  'foo\374\277\277\277\277\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1202
      i::FUNCTION_SCOPE, i::SLOPPY },
1203 1204 1205
    // Illegal 0xfe byte
    { "  'foo\376\277\277\277\277\277\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1206
      i::FUNCTION_SCOPE, i::SLOPPY },
1207 1208 1209
    // Illegal 0xff byte
    { "  'foo\377\277\277\277\277\277\277\277';\n"
      "  (function fun", "(a,b) { infunction; }", ")();",
1210
      i::FUNCTION_SCOPE, i::SLOPPY },
1211 1212
    { "  'foo';\n"
      "  (function fun", "(a,b) { 'bar\355\240\201\355\260\213'; }", ")();",
1213
      i::FUNCTION_SCOPE, i::SLOPPY },
1214 1215
    { "  'foo';\n"
      "  (function fun", "(a,b) { 'bar\360\220\220\214'; }", ")();",
1216 1217
      i::FUNCTION_SCOPE, i::SLOPPY },
    { NULL, NULL, NULL, i::EVAL_SCOPE, i::SLOPPY }
1218 1219
  };

1220
  i::Isolate* isolate = CcTest::i_isolate();
1221 1222
  i::Factory* factory = isolate->factory();

1223 1224
  v8::HandleScope handles(CcTest::isolate());
  v8::Handle<v8::Context> context = v8::Context::New(CcTest::isolate());
1225 1226
  v8::Context::Scope context_scope(context);

1227 1228
  isolate->stack_guard()->SetStackLimit(i::GetCurrentStackPosition() -
                                        128 * 1024);
1229 1230

  for (int i = 0; source_data[i].outer_prefix; i++) {
1231 1232 1233 1234 1235 1236
    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);
1237
    int kProgramSize = kPrefixLen + kInnerLen + kSuffixLen;
1238
    int kProgramByteSize = kPrefixByteLen + kInnerByteLen + kSuffixByteLen;
1239
    i::ScopedVector<char> program(kProgramByteSize + 1);
1240 1241 1242 1243
    i::SNPrintF(program, "%s%s%s",
                         source_data[i].outer_prefix,
                         source_data[i].inner_source,
                         source_data[i].outer_suffix);
1244 1245

    // Parse program source.
1246 1247
    i::Handle<i::String> source = factory->NewStringFromUtf8(
        i::CStrVector(program.start())).ToHandleChecked();
1248
    CHECK_EQ(source->length(), kProgramSize);
1249
    i::Handle<i::Script> script = factory->NewScript(source);
1250
    i::CompilationInfoWithZone info(script);
1251 1252 1253 1254
    i::Parser::ParseInfo parse_info = {isolate->stack_guard()->real_climit(),
                                       isolate->heap()->HashSeed(),
                                       isolate->unicode_cache()};
    i::Parser parser(&info, &parse_info);
1255 1256
    parser.set_allow_lazy(true);
    parser.set_allow_harmony_scoping(true);
1257
    parser.set_allow_arrow_functions(true);
1258
    info.MarkAsGlobal();
1259
    info.SetStrictMode(source_data[i].strict_mode);
1260 1261
    parser.Parse();
    CHECK(info.function() != NULL);
1262 1263

    // Check scope types and positions.
1264
    i::Scope* scope = info.function()->scope();
1265 1266 1267 1268 1269 1270
    CHECK(scope->is_global_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);
1271
    CHECK_EQ(inner_scope->scope_type(), source_data[i].scope_type);
1272 1273 1274 1275 1276 1277
    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);
  }
}
1278 1279


1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
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) {
1292
  i::Isolate* isolate = CcTest::i_isolate();
1293
  i::Factory* factory = isolate->factory();
1294 1295
  const char* message =
      ReadString(&data[i::PreparseDataConstants::kMessageTextPos]);
1296
  i::Handle<i::String> format = v8::Utils::OpenHandle(
1297
      *v8::String::NewFromUtf8(CcTest::isolate(), message));
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
  int arg_count = data[i::PreparseDataConstants::kMessageArgCountPos];
  const char* arg = NULL;
  i::Handle<i::JSArray> args_array;
  if (arg_count == 1) {
    // Position after text found by skipping past length field and
    // length field content words.
    int pos = i::PreparseDataConstants::kMessageTextPos + 1 +
              data[i::PreparseDataConstants::kMessageTextPos];
    arg = ReadString(&data[pos]);
    args_array = factory->NewJSArray(1);
    i::JSArray::SetElement(args_array, 0, v8::Utils::OpenHandle(*v8_str(arg)),
                           NONE, i::SLOPPY).Check();
  } else {
    CHECK_EQ(0, arg_count);
    args_array = factory->NewJSArray(0);
1313
  }
1314

1315
  i::Handle<i::JSObject> builtins(isolate->js_builtins_object());
1316 1317
  i::Handle<i::Object> format_fun = i::Object::GetProperty(
      isolate, builtins, "FormatMessage").ToHandleChecked();
1318
  i::Handle<i::Object> arg_handles[] = { format, args_array };
1319
  i::Handle<i::Object> result = i::Execution::Call(
1320
      isolate, format_fun, builtins, 2, arg_handles).ToHandleChecked();
1321
  CHECK(result->IsString());
1322
  i::DeleteArray(message);
1323
  i::DeleteArray(arg);
1324
  data.Dispose();
1325 1326 1327 1328
  return i::Handle<i::String>::cast(result);
}


1329 1330 1331 1332 1333
enum ParserFlag {
  kAllowLazy,
  kAllowNativesSyntax,
  kAllowHarmonyScoping,
  kAllowModules,
1334
  kAllowHarmonyNumericLiterals,
1335
  kAllowArrowFunctions,
1336 1337
  kAllowClasses,
  kAllowHarmonyObjectLiterals
1338 1339 1340
};


1341 1342 1343 1344 1345 1346
enum ParserSyncTestResult {
  kSuccessOrError,
  kSuccess,
  kError
};

1347 1348 1349
template <typename Traits>
void SetParserFlags(i::ParserBase<Traits>* parser,
                    i::EnumSet<ParserFlag> flags) {
1350 1351 1352 1353 1354 1355
  parser->set_allow_lazy(flags.Contains(kAllowLazy));
  parser->set_allow_natives_syntax(flags.Contains(kAllowNativesSyntax));
  parser->set_allow_harmony_scoping(flags.Contains(kAllowHarmonyScoping));
  parser->set_allow_modules(flags.Contains(kAllowModules));
  parser->set_allow_harmony_numeric_literals(
      flags.Contains(kAllowHarmonyNumericLiterals));
1356 1357
  parser->set_allow_harmony_object_literals(
      flags.Contains(kAllowHarmonyObjectLiterals));
1358
  parser->set_allow_arrow_functions(flags.Contains(kAllowArrowFunctions));
1359
  parser->set_allow_classes(flags.Contains(kAllowClasses));
1360 1361 1362
}


1363
void TestParserSyncWithFlags(i::Handle<i::String> source,
1364 1365
                             i::EnumSet<ParserFlag> flags,
                             ParserSyncTestResult result) {
1366
  i::Isolate* isolate = CcTest::i_isolate();
1367 1368 1369
  i::Factory* factory = isolate->factory();

  uintptr_t stack_limit = isolate->stack_guard()->real_climit();
1370 1371 1372

  // Preparse the data.
  i::CompleteParserRecorder log;
1373
  {
1374
    i::Scanner scanner(isolate->unicode_cache());
1375
    i::GenericStringUtf16CharacterStream stream(source, 0, source->length());
1376
    i::PreParser preparser(&scanner, &log, stack_limit);
1377
    SetParserFlags(&preparser, flags);
1378
    scanner.Initialize(&stream);
1379 1380
    i::PreParser::PreParseResult result = preparser.PreParseProgram();
    CHECK_EQ(i::PreParser::kPreParseSuccess, result);
1381
  }
1382 1383

  bool preparse_error = log.HasError();
1384 1385

  // Parse the data
1386 1387
  i::FunctionLiteral* function;
  {
1388
    i::Handle<i::Script> script = factory->NewScript(source);
1389
    i::CompilationInfoWithZone info(script);
1390 1391 1392 1393
    i::Parser::ParseInfo parse_info = {isolate->stack_guard()->real_climit(),
                                       isolate->heap()->HashSeed(),
                                       isolate->unicode_cache()};
    i::Parser parser(&info, &parse_info);
1394
    SetParserFlags(&parser, flags);
1395
    info.MarkAsGlobal();
1396 1397
    parser.Parse();
    function = info.function();
1398
  }
1399

1400
  // Check that preparsing fails iff parsing fails.
1401 1402
  if (function == NULL) {
    // Extract exception from the parser.
1403
    CHECK(isolate->has_pending_exception());
1404 1405
    i::Handle<i::JSObject> exception_handle(
        i::JSObject::cast(isolate->pending_exception()));
1406
    i::Handle<i::String> message_string =
1407 1408
        i::Handle<i::String>::cast(i::Object::GetProperty(
            isolate, exception_handle, "message").ToHandleChecked());
1409

1410
    if (result == kSuccess) {
1411
      v8::base::OS::Print(
1412 1413 1414 1415 1416 1417 1418 1419 1420
          "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);
    }

1421
    if (!preparse_error) {
1422
      v8::base::OS::Print(
1423 1424 1425 1426 1427
          "Parser failed on:\n"
          "\t%s\n"
          "with error:\n"
          "\t%s\n"
          "However, the preparser succeeded",
1428
          source->ToCString().get(), message_string->ToCString().get());
1429 1430 1431
      CHECK(false);
    }
    // Check that preparser and parser produce the same error.
1432 1433
    i::Handle<i::String> preparser_message =
        FormatMessage(log.ErrorMessageData());
1434
    if (!i::String::Equals(message_string, preparser_message)) {
1435
      v8::base::OS::Print(
1436 1437 1438 1439 1440
          "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",
1441 1442 1443
          source->ToCString().get(),
          message_string->ToCString().get(),
          preparser_message->ToCString().get());
1444 1445
      CHECK(false);
    }
1446
  } else if (preparse_error) {
1447
    v8::base::OS::Print(
1448 1449 1450 1451 1452
        "Preparser failed on:\n"
        "\t%s\n"
        "with error:\n"
        "\t%s\n"
        "However, the parser succeeded",
yangguo@chromium.org's avatar
yangguo@chromium.org committed
1453 1454
        source->ToCString().get(),
        FormatMessage(log.ErrorMessageData())->ToCString().get());
1455
    CHECK(false);
1456
  } else if (result == kError) {
1457
    v8::base::OS::Print(
1458 1459 1460 1461 1462
        "Expected error on:\n"
        "\t%s\n"
        "However, parser and preparser succeeded",
        source->ToCString().get());
    CHECK(false);
1463 1464 1465 1466
  }
}


1467
void TestParserSync(const char* source,
1468 1469 1470 1471 1472
                    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) {
1473
  i::Handle<i::String> str =
1474
      CcTest::i_isolate()->factory()->NewStringFromAsciiChecked(source);
1475
  for (int bits = 0; bits < (1 << varying_flags_length); bits++) {
1476
    i::EnumSet<ParserFlag> flags;
1477 1478 1479 1480 1481 1482 1483
    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]);
1484
    }
1485
    TestParserSyncWithFlags(str, flags, result);
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
  }
}


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: ", "}" },
1503
    { "switch (12) { ", "case 12: }" },
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    { "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",
1532 1533 1534 1535
    // TODO(marja): activate once parsing 'return' is merged into ParserBase.
    // "return",
    // "return  12",
    // "return\n12",
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
    "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
  };

1560 1561
  v8::HandleScope handles(CcTest::isolate());
  v8::Handle<v8::Context> context = v8::Context::New(CcTest::isolate());
1562 1563
  v8::Context::Scope context_scope(context);

1564 1565
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
1566

1567
  static const ParserFlag flags1[] = {
arv@chromium.org's avatar
arv@chromium.org committed
1568 1569 1570 1571 1572 1573 1574 1575 1576
    kAllowArrowFunctions,
    kAllowClasses,
    kAllowHarmonyNumericLiterals,
    kAllowHarmonyObjectLiterals,
    kAllowHarmonyScoping,
    kAllowLazy,
    kAllowModules,
  };

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
  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.
1588
        i::ScopedVector<char> program(kProgramSize + 1);
1589
        int length = i::SNPrintF(program,
1590 1591 1592 1593 1594 1595
            "label: for (;;) { %s%s%s%s }",
            context_data[i][0],
            statement_data[j],
            termination_data[k],
            context_data[i][1]);
        CHECK(length == kProgramSize);
1596
        TestParserSync(program.start(), flags1, arraysize(flags1));
1597 1598 1599
      }
    }
  }
1600 1601 1602 1603 1604

  // Neither Harmony numeric literals nor our natives syntax have any
  // interaction with the flags above, so test these separately to reduce
  // the combinatorial explosion.
  static const ParserFlag flags2[] = { kAllowHarmonyNumericLiterals };
1605 1606
  TestParserSync("0o1234", flags2, arraysize(flags2));
  TestParserSync("0b1011", flags2, arraysize(flags2));
1607 1608

  static const ParserFlag flags3[] = { kAllowNativesSyntax };
1609
  TestParserSync("%DebugPrint(123)", flags3, arraysize(flags3));
1610
}
1611 1612


1613
TEST(StrictOctal) {
1614 1615 1616
  // Test that syntax error caused by octal literal is reported correctly as
  // such (issue 2220).
  v8::V8::Initialize();
1617
  v8::HandleScope scope(CcTest::isolate());
1618
  v8::Context::Scope context_scope(
1619
      v8::Context::New(CcTest::isolate()));
1620 1621 1622 1623 1624 1625 1626 1627
  v8::TryCatch try_catch;
  const char* script =
      "\"use strict\";       \n"
      "a = function() {      \n"
      "  b = function() {    \n"
      "    01;               \n"
      "  };                  \n"
      "};                    \n";
1628
  v8::Script::Compile(v8::String::NewFromUtf8(CcTest::isolate(), script));
1629 1630 1631 1632 1633
  CHECK(try_catch.HasCaught());
  v8::String::Utf8Value exception(try_catch.Exception());
  CHECK_EQ("SyntaxError: Octal literals are not allowed in strict mode.",
           *exception);
}
1634 1635


1636 1637
void RunParserSyncTest(const char* context_data[][2],
                       const char* statement_data[],
1638 1639
                       ParserSyncTestResult result,
                       const ParserFlag* flags = NULL,
1640 1641 1642
                       int flags_len = 0,
                       const ParserFlag* always_true_flags = NULL,
                       int always_true_flags_len = 0) {
1643 1644 1645 1646
  v8::HandleScope handles(CcTest::isolate());
  v8::Handle<v8::Context> context = v8::Context::New(CcTest::isolate());
  v8::Context::Scope context_scope(context);

1647 1648
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
1649

1650
  static const ParserFlag default_flags[] = {
arv@chromium.org's avatar
arv@chromium.org committed
1651 1652 1653 1654 1655 1656 1657 1658
    kAllowArrowFunctions,
    kAllowClasses,
    kAllowHarmonyNumericLiterals,
    kAllowHarmonyObjectLiterals,
    kAllowHarmonyScoping,
    kAllowLazy,
    kAllowModules,
    kAllowNativesSyntax,
1659
  };
1660 1661
  ParserFlag* generated_flags = NULL;
  if (flags == NULL) {
1662
    flags = default_flags;
1663
    flags_len = arraysize(default_flags);
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
    if (always_true_flags != NULL) {
      // Remove always_true_flags from default_flags.
      CHECK(always_true_flags_len < flags_len);
      generated_flags = new ParserFlag[flags_len - always_true_flags_len];
      int flag_index = 0;
      for (int i = 0; i < flags_len; ++i) {
        bool use_flag = true;
        for (int j = 0; j < always_true_flags_len; ++j) {
          if (flags[i] == always_true_flags[j]) {
            use_flag = false;
            break;
          }
        }
        if (use_flag) generated_flags[flag_index++] = flags[i];
      }
      CHECK(flag_index == flags_len - always_true_flags_len);
      flags_len = flag_index;
      flags = generated_flags;
    }
1683
  }
1684 1685 1686 1687 1688 1689 1690 1691 1692
  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);
1693 1694 1695 1696 1697
      int length = i::SNPrintF(program,
                               "%s%s%s",
                               context_data[i][0],
                               statement_data[j],
                               context_data[i][1]);
1698 1699 1700
      CHECK(length == kProgramSize);
      TestParserSync(program.start(),
                     flags,
1701
                     flags_len,
1702 1703 1704
                     result,
                     always_true_flags,
                     always_true_flags_len);
1705 1706
    }
  }
1707
  delete[] generated_flags;
1708 1709 1710
}


1711 1712 1713 1714 1715
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.
1716
  const char* context_data[][2] = {
1717
    { "\"use strict\";", "" },
1718 1719
    { "var eval; function test_func() {\"use strict\"; ", "}"},
    { NULL, NULL }
1720 1721
  };

1722
  const char* statement_data[] = {
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
    "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) { }",
1735 1736 1737 1738
    "(eval) => { }",
    "(arguments) => { }",
    "(foo, eval) => { }",
    "(foo, arguments) => { }",
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
    "eval = 1;",
    "arguments = 1;",
    "var foo = eval = 1;",
    "var foo = arguments = 1;",
    "++eval;",
    "++arguments;",
    "eval++;",
    "arguments++;",
    NULL
  };
1749

1750 1751
  RunParserSyncTest(context_data, statement_data, kError);
}
1752 1753


1754
TEST(NoErrorsEvalAndArgumentsSloppy) {
1755 1756 1757 1758 1759 1760
  // Tests that both preparsing and parsing accept "eval" and "arguments" as
  // identifiers when needed.
  const char* context_data[][2] = {
    { "", "" },
    { "function test_func() {", "}"},
    { NULL, NULL }
1761 1762
  };

1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
  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] = {
1793 1794
    { "\"use strict\";", "" },
    { "function test_func() { \"use strict\";", "}" },
1795
    { "() => { \"use strict\"; ", "}" },
1796 1797
    { NULL, NULL }
  };
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810

  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
  };

1811 1812
  static const ParserFlag always_flags[] = {kAllowArrowFunctions};
  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
1813
                    always_flags, arraysize(always_flags));
1814 1815 1816
}


1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
#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 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 " ++;",


1844 1845 1846 1847 1848
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.
1849
  const char* context_data[][2] = {
1850 1851
    { "\"use strict\";", "" },
    { "function test_func() {\"use strict\"; ", "}"},
1852
    { "() => { \"use strict\"; ", "}" },
1853 1854
    { NULL, NULL }
  };
1855

1856 1857
  const char* statement_data[] {
    FUTURE_STRICT_RESERVED_WORDS(FUTURE_STRICT_RESERVED_STATEMENTS)
1858
    NULL
1859 1860
  };

1861 1862
  static const ParserFlag always_flags[] = {kAllowArrowFunctions};
  RunParserSyncTest(context_data, statement_data, kError, NULL, 0, always_flags,
1863
                    arraysize(always_flags));
1864 1865 1866 1867 1868

  static const ParserFlag classes_flags[] = {
      kAllowArrowFunctions, kAllowClasses, kAllowHarmonyScoping};
  RunParserSyncTest(context_data, statement_data, kError, NULL, 0,
                    classes_flags, arraysize(classes_flags));
1869
}
1870 1871


1872
TEST(NoErrorsFutureStrictReservedWords) {
1873 1874 1875
  const char* context_data[][2] = {
    { "", "" },
    { "function test_func() {", "}"},
1876
    { "() => {", "}" },
1877 1878
    { NULL, NULL }
  };
1879

1880
  const char* statement_data[] = {
1881
    FUTURE_STRICT_RESERVED_WORDS(FUTURE_STRICT_RESERVED_STATEMENTS)
1882 1883 1884
    NULL
  };

1885 1886
  static const ParserFlag always_flags[] = {kAllowArrowFunctions};
  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
1887
                    always_flags, arraysize(always_flags));
1888 1889 1890 1891 1892

  static const ParserFlag classes_flags[] = {
      kAllowArrowFunctions, kAllowClasses, kAllowHarmonyScoping};
  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
                    classes_flags, arraysize(classes_flags));
1893
}
1894

1895 1896 1897 1898 1899 1900

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] = {
1901 1902 1903 1904
    { "", "" },
    { "\"use strict\";", "" },
    { "var eval; function test_func() {", "}"},
    { "var eval; function test_func() {\"use strict\"; ", "}"},
1905 1906
    { "var eval; () => {", "}"},
    { "var eval; () => {\"use strict\"; ", "}"},
1907 1908
    { NULL, NULL }
  };
1909

1910
  const char* statement_data[] = {
1911 1912 1913 1914 1915 1916
    "var super;",
    "var foo, super;",
    "try { } catch (super) { }",
    "function super() { }",
    "function foo(super) { }",
    "function foo(bar, super) { }",
1917 1918
    "(super) => { }",
    "(bar, super) => { }",
1919 1920 1921 1922 1923 1924 1925
    "super = 1;",
    "var foo = super = 1;",
    "++super;",
    "super++;",
    "function foo super",
    NULL
  };
1926

1927 1928
  RunParserSyncTest(context_data, statement_data, kError);
}
1929

1930

1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
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);
}


1965
TEST(NoErrorsYieldSloppyAllModes) {
1966
  // In sloppy mode, it's okay to use "yield" as identifier, *except* inside a
1967
  // generator (see other test).
1968 1969
  const char* context_data[][2] = {
    { "", "" },
1970 1971
    { "function not_gen() {", "}" },
    { "(function not_gen() {", "})" },
1972
    { NULL, NULL }
1973 1974
  };

1975 1976 1977 1978 1979
  const char* statement_data[] = {
    "var yield;",
    "var foo, yield;",
    "try { } catch (yield) { }",
    "function yield() { }",
1980
    "(function yield() { })",
1981 1982 1983 1984
    "function foo(yield) { }",
    "function foo(bar, yield) { }",
    "yield = 1;",
    "var foo = yield = 1;",
1985
    "yield * 2;",
1986 1987
    "++yield;",
    "yield++;",
1988
    "yield: 34",
1989
    "function yield(yield) { yield: yield (yield + yield(0)); }",
1990 1991
    "({ yield: 1 })",
    "({ get yield() { 1 } })",
1992 1993
    "yield(100)",
    "yield[100]",
1994 1995 1996
    NULL
  };

1997
  RunParserSyncTest(context_data, statement_data, kSuccess);
1998 1999 2000
}


2001 2002 2003
TEST(NoErrorsYieldSloppyGeneratorsEnabled) {
  // In sloppy mode, it's okay to use "yield" as identifier, *except* inside a
  // generator (see next test).
2004
  const char* context_data[][2] = {
2005 2006 2007 2008 2009
    { "", "" },
    { "function not_gen() {", "}" },
    { "function * gen() { function not_gen() {", "} }" },
    { "(function not_gen() {", "})" },
    { "(function * gen() { (function not_gen() {", "}) })" },
2010 2011 2012 2013 2014 2015 2016 2017
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "var yield;",
    "var foo, yield;",
    "try { } catch (yield) { }",
    "function yield() { }",
2018 2019 2020 2021 2022
    "(function yield() { })",
    "function foo(yield) { }",
    "function foo(bar, yield) { }",
    "function * yield() { }",
    "(function * yield() { })",
2023 2024
    "yield = 1;",
    "var foo = yield = 1;",
2025
    "yield * 2;",
2026 2027
    "++yield;",
    "yield++;",
2028
    "yield: 34",
2029
    "function yield(yield) { yield: yield (yield + yield(0)); }",
2030 2031
    "({ yield: 1 })",
    "({ get yield() { 1 } })",
2032 2033
    "yield(100)",
    "yield[100]",
2034 2035 2036
    NULL
  };

wingo@igalia.com's avatar
wingo@igalia.com committed
2037
  RunParserSyncTest(context_data, statement_data, kSuccess);
2038 2039 2040 2041 2042
}


TEST(ErrorsYieldStrict) {
  const char* context_data[][2] = {
2043 2044 2045 2046 2047 2048
    { "\"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() {", "}) })" },
2049
    { "() => {\"use strict\"; ", "}" },
2050 2051
    { NULL, NULL }
  };
2052 2053 2054 2055 2056 2057

  const char* statement_data[] = {
    "var yield;",
    "var foo, yield;",
    "try { } catch (yield) { }",
    "function yield() { }",
2058
    "(function yield() { })",
2059 2060
    "function foo(yield) { }",
    "function foo(bar, yield) { }",
2061 2062
    "function * yield() { }",
    "(function * yield() { })",
2063
    "yield = 1;",
2064
    "var foo = yield = 1;",
2065 2066
    "++yield;",
    "yield++;",
2067
    "yield: 34;",
2068 2069 2070
    NULL
  };

2071 2072
  RunParserSyncTest(context_data, statement_data, kError);
}
2073

2074

2075
TEST(NoErrorsGenerator) {
2076
  const char* context_data[][2] = {
2077 2078 2079
    { "function * gen() {", "}" },
    { "(function * gen() {", "})" },
    { "(function * () {", "})" },
2080
    { NULL, NULL }
2081 2082
  };

2083
  const char* statement_data[] = {
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
    // 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) { })",
2098 2099 2100 2101
    "yield { yield: 12 }",
    "yield /* comment */ { yield: 12 }",
    "yield * \n { yield: 12 }",
    "yield /* comment */ * \n { yield: 12 }",
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
    // 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() { } })",
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
    // 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 (;;) {}",
2127 2128 2129
    NULL
  };

wingo@igalia.com's avatar
wingo@igalia.com committed
2130
  RunParserSyncTest(context_data, statement_data, kSuccess);
2131 2132 2133
}


2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
TEST(ErrorsYieldGenerator) {
  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 let-bound in the generator, which does not permit
    // yield to be an identifier.
    "(function yield() { })",
    "(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",
2167 2168 2169 2170 2171 2172 2173 2174 2175
    "+ 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}",
2176 2177 2178 2179 2180 2181 2182
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kError);
}


2183 2184 2185
TEST(ErrorsNameOfStrictFunction) {
  // Tests that illegal tokens as names of a strict function produce the correct
  // errors.
2186
  const char* context_data[][2] = {
2187 2188 2189 2190
    { "function ", ""},
    { "\"use strict\"; function", ""},
    { "function * ", ""},
    { "\"use strict\"; function * ", ""},
2191 2192 2193
    { NULL, NULL }
  };

2194
  const char* statement_data[] = {
2195 2196 2197 2198
    "eval() {\"use strict\";}",
    "arguments() {\"use strict\";}",
    "interface() {\"use strict\";}",
    "yield() {\"use strict\";}",
2199
    // Future reserved words are always illegal
2200 2201
    "function super() { }",
    "function super() {\"use strict\";}",
2202 2203 2204
    NULL
  };

2205 2206
  RunParserSyncTest(context_data, statement_data, kError);
}
2207 2208


2209 2210
TEST(NoErrorsNameOfStrictFunction) {
  const char* context_data[][2] = {
2211
    { "function ", ""},
2212
    { NULL, NULL }
2213
  };
2214 2215

  const char* statement_data[] = {
2216 2217 2218 2219
    "eval() { }",
    "arguments() { }",
    "interface() { }",
    "yield() { }",
2220 2221 2222 2223 2224 2225 2226
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kSuccess);
}


2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
TEST(NoErrorsNameOfStrictGenerator) {
  const char* context_data[][2] = {
    { "function * ", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "eval() { }",
    "arguments() { }",
    "interface() { }",
    "yield() { }",
    NULL
  };

wingo@igalia.com's avatar
wingo@igalia.com committed
2241
  RunParserSyncTest(context_data, statement_data, kSuccess);
2242 2243
}

2244

2245
TEST(ErrorsIllegalWordsAsLabelsSloppy) {
2246
  // Using future reserved words as labels is always an error.
2247 2248 2249
  const char* context_data[][2] = {
    { "", ""},
    { "function test_func() {", "}" },
2250
    { "() => {", "}" },
2251 2252
    { NULL, NULL }
  };
2253 2254 2255 2256 2257 2258 2259

  const char* statement_data[] = {
    "super: while(true) { break super; }",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kError);
2260 2261 2262
}


2263
TEST(ErrorsIllegalWordsAsLabelsStrict) {
2264 2265
  // Tests that illegal tokens as labels produce the correct errors.
  const char* context_data[][2] = {
2266 2267
    { "\"use strict\";", "" },
    { "function test_func() {\"use strict\"; ", "}"},
2268
    { "() => {\"use strict\"; ", "}" },
2269 2270
    { NULL, NULL }
  };
2271

2272
#define LABELLED_WHILE(NAME) #NAME ": while (true) { break " #NAME "; }",
2273
  const char* statement_data[] = {
2274
    "super: while(true) { break super; }",
2275
    FUTURE_STRICT_RESERVED_WORDS(LABELLED_WHILE)
2276 2277
    NULL
  };
2278
#undef LABELLED_WHILE
2279

2280 2281
  RunParserSyncTest(context_data, statement_data, kError);
}
2282

2283

2284 2285 2286
TEST(NoErrorsIllegalWordsAsLabels) {
  // Using eval and arguments as labels is legal even in strict mode.
  const char* context_data[][2] = {
2287 2288
    { "", ""},
    { "function test_func() {", "}" },
2289
    { "() => {", "}" },
2290 2291
    { "\"use strict\";", "" },
    { "\"use strict\"; function test_func() {", "}" },
2292
    { "\"use strict\"; () => {", "}" },
2293 2294
    { NULL, NULL }
  };
2295

2296 2297 2298 2299 2300 2301 2302
  const char* statement_data[] = {
    "mylabel: while(true) { break mylabel; }",
    "eval: while(true) { break eval; }",
    "arguments: while(true) { break arguments; }",
    NULL
  };

2303 2304
  static const ParserFlag always_flags[] = {kAllowArrowFunctions};
  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
2305
                    always_flags, arraysize(always_flags));
2306
}
2307 2308


2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
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

  static const ParserFlag always_flags[] = {kAllowArrowFunctions};
  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


2330 2331
TEST(ErrorsParenthesizedLabels) {
  // Parenthesized identifiers shouldn't be recognized as labels.
2332 2333 2334
  const char* context_data[][2] = {
    { "", ""},
    { "function test_func() {", "}" },
2335
    { "() => {", "}" },
2336 2337
    { NULL, NULL }
  };
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361

  const char* statement_data[] = {
    "(mylabel): while(true) { break mylabel; }",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kError);
}


TEST(NoErrorsParenthesizedDirectivePrologue) {
  // Parenthesized directive prologue shouldn't be recognized.
  const char* context_data[][2] = {
    { "", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "(\"use strict\"); var eval;",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kSuccess);
}
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404


TEST(ErrorsNotAnIdentifierName) {
  const char* context_data[][2] = {
    { "", ""},
    { "\"use strict\";", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "var foo = {}; foo.{;",
    "var foo = {}; foo.};",
    "var foo = {}; foo.=;",
    "var foo = {}; foo.888;",
    "var foo = {}; foo.-;",
    "var foo = {}; foo.--;",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kError);
}


TEST(NoErrorsIdentifierNames) {
  // Keywords etc. are valid as property names.
  const char* context_data[][2] = {
    { "", ""},
    { "\"use strict\";", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "var foo = {}; foo.if;",
    "var foo = {}; foo.yield;",
    "var foo = {}; foo.super;",
    "var foo = {}; foo.interface;",
    "var foo = {}; foo.eval;",
    "var foo = {}; foo.arguments;",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kSuccess);
}
2405 2406 2407


TEST(DontRegressPreParserDataSizes) {
2408 2409
  // These tests make sure that Parser doesn't start producing less "preparse
  // data" (data which the embedder can cache).
2410
  v8::V8::Initialize();
2411 2412 2413
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope handles(isolate);

2414 2415
  CcTest::i_isolate()->stack_guard()->SetStackLimit(
      i::GetCurrentStackPosition() - 128 * 1024);
2416 2417 2418 2419 2420

  struct TestCase {
    const char* program;
    int functions;
  } test_cases[] = {
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
    // No functions.
    {"var x = 42;", 0},
    // Functions.
    {"function foo() {}", 1}, {"function foo() {} function bar() {}", 2},
    // Getter / setter functions are recorded as functions if they're on the top
    // level.
    {"var x = {get foo(){} };", 1},
    // Functions insize lazy functions are not recorded.
    {"function lazy() { function a() {} function b() {} function c() {} }", 1},
    {"function lazy() { var x = {get foo(){} } }", 1},
    {NULL, 0}
2432 2433 2434 2435
  };

  for (int i = 0; test_cases[i].program; i++) {
    const char* program = test_cases[i].program;
2436
    i::Factory* factory = CcTest::i_isolate()->factory();
2437 2438
    i::Handle<i::String> source =
        factory->NewStringFromUtf8(i::CStrVector(program)).ToHandleChecked();
2439 2440
    i::Handle<i::Script> script = factory->NewScript(source);
    i::CompilationInfoWithZone info(script);
2441
    i::ScriptData* sd = NULL;
2442
    info.SetCachedData(&sd, v8::ScriptCompiler::kProduceParserCache);
2443
    i::Parser::Parse(&info, true);
2444
    i::ParseData pd(sd);
2445

2446
    if (pd.FunctionCount() != test_cases[i].functions) {
2447
      v8::base::OS::Print(
2448 2449 2450
          "Expected preparse data for program:\n"
          "\t%s\n"
          "to contain %d functions, however, received %d functions.\n",
2451
          program, test_cases[i].functions, pd.FunctionCount());
2452 2453
      CHECK(false);
    }
2454
    delete sd;
2455 2456
  }
}
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493


TEST(FunctionDeclaresItselfStrict) {
  // Tests that we produce the right kinds of errors when a function declares
  // itself strict (we cannot produce there errors as soon as we see the
  // offending identifiers, because we don't know at that point whether the
  // function is strict or not).
  const char* context_data[][2] = {
    {"function eval() {", "}"},
    {"function arguments() {", "}"},
    {"function yield() {", "}"},
    {"function interface() {", "}"},
    {"function foo(eval) {", "}"},
    {"function foo(arguments) {", "}"},
    {"function foo(yield) {", "}"},
    {"function foo(interface) {", "}"},
    {"function foo(bar, eval) {", "}"},
    {"function foo(bar, arguments) {", "}"},
    {"function foo(bar, yield) {", "}"},
    {"function foo(bar, interface) {", "}"},
    {"function foo(bar, bar) {", "}"},
    { NULL, NULL }
  };

  const char* strict_statement_data[] = {
    "\"use strict\";",
    NULL
  };

  const char* non_strict_statement_data[] = {
    ";",
    NULL
  };

  RunParserSyncTest(context_data, strict_statement_data, kError);
  RunParserSyncTest(context_data, non_strict_statement_data, kSuccess);
}
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529


TEST(ErrorsTryWithoutCatchOrFinally) {
  const char* context_data[][2] = {
    {"", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "try { }",
    "try { } foo();",
    "try { } catch (e) foo();",
    "try { } catch { }",
    "try { } finally foo();",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kError);
}


TEST(NoErrorsTryCatchFinally) {
  const char* context_data[][2] = {
    {"", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "try { } catch (e) { }",
    "try { } catch (e) { } finally { }",
    "try { } finally { }",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kSuccess);
}
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561


TEST(ErrorsRegexpLiteral) {
  const char* context_data[][2] = {
    {"var r = ", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "/unterminated",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kError);
}


TEST(NoErrorsRegexpLiteral) {
  const char* context_data[][2] = {
    {"var r = ", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "/foo/",
    "/foo/g",
    "/foo/whatever",  // This is an error but not detected by the parser.
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kSuccess);
}
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574


TEST(Intrinsics) {
  const char* context_data[][2] = {
    {"", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "%someintrinsic(arg)",
    NULL
  };

2575 2576 2577 2578 2579 2580 2581
  // This test requires kAllowNativesSyntax to succeed.
  static const ParserFlag always_true_flags[] = {
    kAllowNativesSyntax
  };

  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
                    always_true_flags, 1);
2582
}
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634


TEST(NoErrorsNewExpression) {
  const char* context_data[][2] = {
    {"", ""},
    {"var f =", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "new foo",
    "new foo();",
    "new foo(1);",
    "new foo(1, 2);",
    // The first () will be processed as a part of the NewExpression and the
    // second () will be processed as part of LeftHandSideExpression.
    "new foo()();",
    // The first () will be processed as a part of the inner NewExpression and
    // the second () will be processed as a part of the outer NewExpression.
    "new new foo()();",
    "new foo.bar;",
    "new foo.bar();",
    "new foo.bar.baz;",
    "new foo.bar().baz;",
    "new foo[bar];",
    "new foo[bar]();",
    "new foo[bar][baz];",
    "new foo[bar]()[baz];",
    "new foo[bar].baz(baz)()[bar].baz;",
    "new \"foo\"",  // Runtime error
    "new 1",  // Runtime error
    // This even runs:
    "(new new Function(\"this.x = 1\")).x;",
    "new new Test_Two(String, 2).v(0123).length;",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kSuccess);
}


TEST(ErrorsNewExpression) {
  const char* context_data[][2] = {
    {"", ""},
    {"var f =", ""},
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "new foo bar",
    "new ) foo",
    "new ++foo",
2635
    "new foo ++",
2636 2637 2638 2639 2640
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kError);
}
2641 2642 2643 2644 2645


TEST(StrictObjectLiteralChecking) {
  const char* strict_context_data[][2] = {
    {"\"use strict\"; var myobject = {", "};"},
2646
    {"\"use strict\"; var myobject = {", ",};"},
2647 2648 2649 2650
    { NULL, NULL }
  };
  const char* non_strict_context_data[][2] = {
    {"var myobject = {", "};"},
2651
    {"var myobject = {", ",};"},
2652 2653 2654
    { NULL, NULL }
  };

2655
  // These are only errors in strict mode.
2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
  const char* statement_data[] = {
    "foo: 1, foo: 2",
    "\"foo\": 1, \"foo\": 2",
    "foo: 1, \"foo\": 2",
    "1: 1, 1: 2",
    "1: 1, \"1\": 2",
    "get: 1, get: 2",  // Not a getter for real, just a property called get.
    "set: 1, set: 2",  // Not a setter for real, just a property called set.
    NULL
  };

  RunParserSyncTest(non_strict_context_data, statement_data, kSuccess);
2668
  RunParserSyncTest(strict_context_data, statement_data, kError);
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
}


TEST(ErrorsObjectLiteralChecking) {
  const char* context_data[][2] = {
    {"\"use strict\"; var myobject = {", "};"},
    {"var myobject = {", "};"},
    { NULL, NULL }
  };

  const char* statement_data[] = {
2680 2681 2682 2683 2684 2685 2686 2687 2688
      ",",
      "foo: 1, get foo() {}",
      "foo: 1, set foo(v) {}",
      "\"foo\": 1, get \"foo\"() {}",
      "\"foo\": 1, set \"foo\"(v) {}",
      "1: 1, get 1() {}",
      "1: 1, set 1() {}",
      "get foo() {}, get foo() {}",
      "set foo(_) {}, set foo(_) {}",
2689 2690 2691 2692
      // It's counter-intuitive, but these collide too (even in classic
      // mode). Note that we can have "foo" and foo as properties in classic
      // mode,
      // but we cannot have "foo" and get foo, or foo and get "foo".
2693 2694 2695 2696 2697 2698
      "foo: 1, get \"foo\"() {}",
      "foo: 1, set \"foo\"(v) {}",
      "\"foo\": 1, get foo() {}",
      "\"foo\": 1, set foo(v) {}",
      "1: 1, get \"1\"() {}",
      "1: 1, set \"1\"() {}",
2699 2700 2701 2702
      "\"1\": 1, get 1() {}"
      "\"1\": 1, set 1(v) {}"
      // Wrong number of parameters
      "get bar(x) {}",
2703 2704 2705
      "get bar(x, y) {}",
      "set bar() {}",
      "set bar(x, y) {}",
2706
      // Parsing FunctionLiteral for getter or setter fails
2707 2708 2709
      "get foo( +",
      "get foo() \"error\"",
      NULL};
2710 2711 2712 2713 2714 2715 2716 2717

  RunParserSyncTest(context_data, statement_data, kError);
}


TEST(NoErrorsObjectLiteralChecking) {
  const char* context_data[][2] = {
    {"var myobject = {", "};"},
2718
    {"var myobject = {", ",};"},
2719
    {"\"use strict\"; var myobject = {", "};"},
2720
    {"\"use strict\"; var myobject = {", ",};"},
2721 2722 2723 2724 2725 2726 2727 2728 2729
    { NULL, NULL }
  };

  const char* statement_data[] = {
    "foo: 1, bar: 2",
    "\"foo\": 1, \"bar\": 2",
    "1: 1, 2: 2",
    // Syntax: IdentifierName ':' AssignmentExpression
    "foo: bar = 5 + baz",
2730
    // Syntax: 'get' PropertyName '(' ')' '{' FunctionBody '}'
2731 2732 2733
    "get foo() {}",
    "get \"foo\"() {}",
    "get 1() {}",
2734 2735 2736 2737 2738
    // Syntax: 'set' PropertyName '(' PropertySetParameterList ')'
    //     '{' FunctionBody '}'
    "set foo(v) {}",
    "set \"foo\"(v) {}",
    "set 1(v) {}",
2739 2740
    // Non-colliding getters and setters -> no errors
    "foo: 1, get bar() {}",
2741
    "foo: 1, set bar(v) {}",
2742
    "\"foo\": 1, get \"bar\"() {}",
2743
    "\"foo\": 1, set \"bar\"(v) {}",
2744
    "1: 1, get 2() {}",
2745
    "1: 1, set 2(v) {}",
2746 2747
    "get: 1, get foo() {}",
    "set: 1, set foo(_) {}",
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
    // Keywords, future reserved and strict future reserved are also allowed as
    // property names.
    "if: 4",
    "interface: 5",
    "super: 6",
    "eval: 7",
    "arguments: 8",
    NULL
  };

  RunParserSyncTest(context_data, statement_data, kSuccess);
}
2760 2761 2762 2763 2764 2765 2766 2767 2768


TEST(TooManyArguments) {
  const char* context_data[][2] = {
    {"foo(", "0)"},
    { NULL, NULL }
  };

  using v8::internal::Code;
2769
  char statement[Code::kMaxArguments * 2 + 1];
2770 2771 2772 2773
  for (int i = 0; i < Code::kMaxArguments; ++i) {
    statement[2 * i] = '0';
    statement[2 * i + 1] = ',';
  }
2774
  statement[Code::kMaxArguments * 2] = 0;
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784

  const char* statement_data[] = {
    statement,
    NULL
  };

  // The test is quite slow, so run it with a reduced set of flags.
  static const ParserFlag empty_flags[] = {kAllowLazy};
  RunParserSyncTest(context_data, statement_data, kError, empty_flags, 1);
}
2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838


TEST(StrictDelete) {
  // "delete <Identifier>" is not allowed in strict mode.
  const char* strict_context_data[][2] = {
    {"\"use strict\"; ", ""},
    { NULL, NULL }
  };

  const char* sloppy_context_data[][2] = {
    {"", ""},
    { NULL, NULL }
  };

  // These are errors in the strict mode.
  const char* sloppy_statement_data[] = {
    "delete foo;",
    "delete foo + 1;",
    "delete (foo);",
    "delete eval;",
    "delete interface;",
    NULL
  };

  // These are always OK
  const char* good_statement_data[] = {
    "delete this;",
    "delete 1;",
    "delete 1 + 2;",
    "delete foo();",
    "delete foo.bar;",
    "delete foo[bar];",
    "delete foo--;",
    "delete --foo;",
    "delete new foo();",
    "delete new foo(bar);",
    NULL
  };

  // These are always errors
  const char* bad_statement_data[] = {
    "delete if;",
    NULL
  };

  RunParserSyncTest(strict_context_data, sloppy_statement_data, kError);
  RunParserSyncTest(sloppy_context_data, sloppy_statement_data, kSuccess);

  RunParserSyncTest(strict_context_data, good_statement_data, kSuccess);
  RunParserSyncTest(sloppy_context_data, good_statement_data, kSuccess);

  RunParserSyncTest(strict_context_data, bad_statement_data, kError);
  RunParserSyncTest(sloppy_context_data, bad_statement_data, kError);
}
2839 2840


2841
TEST(InvalidLeftHandSide) {
2842
  const char* assignment_context_data[][2] = {
2843 2844
    {"", " = 1;"},
    {"\"use strict\"; ", " = 1;"},
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
    { NULL, NULL }
  };

  const char* prefix_context_data[][2] = {
    {"++", ";"},
    {"\"use strict\"; ++", ";"},
    {NULL, NULL},
  };

  const char* postfix_context_data[][2] = {
    {"", "++;"},
    {"\"use strict\"; ", "++;"},
    { NULL, NULL }
  };

  // Good left hand sides for assigment or prefix / postfix operations.
  const char* good_statement_data[] = {
    "foo",
    "foo.bar",
    "foo[bar]",
    "foo()[bar]",
    "foo().bar",
    "this.foo",
    "this[foo]",
    "new foo()[bar]",
    "new foo().bar",
2871 2872 2873 2874 2875 2876 2877 2878
    "foo()",
    "foo(bar)",
    "foo[bar]()",
    "foo.bar()",
    "this()",
    "this.foo()",
    "this[foo].bar()",
    "this.foo[foo].bar(this)(bar)[foo]()",
2879 2880 2881 2882 2883 2884
    NULL
  };

  // Bad left hand sides for assigment or prefix / postfix operations.
  const char* bad_statement_data_common[] = {
    "2",
2885 2886
    "new foo",
    "new foo()",
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
    "null",
    "if",  // Unexpected token
    "{x: 1}",  // Unexpected token
    "this",
    "\"bar\"",
    "(foo + bar)",
    "new new foo()[bar]",  // means: new (new foo()[bar])
    "new new foo().bar",  // means: new (new foo()[bar])
    NULL
  };

  // These are not okay for assignment, but okay for prefix / postix.
  const char* bad_statement_data_for_assignment[] = {
    "++foo",
    "foo++",
    "foo + bar",
    NULL
  };

  RunParserSyncTest(assignment_context_data, good_statement_data, kSuccess);
  RunParserSyncTest(assignment_context_data, bad_statement_data_common, kError);
  RunParserSyncTest(assignment_context_data, bad_statement_data_for_assignment,
                    kError);

  RunParserSyncTest(prefix_context_data, good_statement_data, kSuccess);
  RunParserSyncTest(prefix_context_data, bad_statement_data_common, kError);

  RunParserSyncTest(postfix_context_data, good_statement_data, kSuccess);
2915
  RunParserSyncTest(postfix_context_data, bad_statement_data_common, kError);
2916
}
2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969


TEST(FuncNameInferrerBasic) {
  // Tests that function names are inferred properly.
  i::FLAG_allow_natives_syntax = true;
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  LocalContext env;
  CompileRun("var foo1 = function() {}; "
             "var foo2 = function foo3() {}; "
             "function not_ctor() { "
             "  var foo4 = function() {}; "
             "  return %FunctionGetInferredName(foo4); "
             "} "
             "function Ctor() { "
             "  var foo5 = function() {}; "
             "  return %FunctionGetInferredName(foo5); "
             "} "
             "var obj1 = { foo6: function() {} }; "
             "var obj2 = { 'foo7': function() {} }; "
             "var obj3 = {}; "
             "obj3[1] = function() {}; "
             "var obj4 = {}; "
             "obj4[1] = function foo8() {}; "
             "var obj5 = {}; "
             "obj5['foo9'] = function() {}; "
             "var obj6 = { obj7 : { foo10: function() {} } };");
  ExpectString("%FunctionGetInferredName(foo1)", "foo1");
  // foo2 is not unnamed -> its name is not inferred.
  ExpectString("%FunctionGetInferredName(foo2)", "");
  ExpectString("not_ctor()", "foo4");
  ExpectString("Ctor()", "Ctor.foo5");
  ExpectString("%FunctionGetInferredName(obj1.foo6)", "obj1.foo6");
  ExpectString("%FunctionGetInferredName(obj2.foo7)", "obj2.foo7");
  ExpectString("%FunctionGetInferredName(obj3[1])",
               "obj3.(anonymous function)");
  ExpectString("%FunctionGetInferredName(obj4[1])", "");
  ExpectString("%FunctionGetInferredName(obj5['foo9'])", "obj5.foo9");
  ExpectString("%FunctionGetInferredName(obj6.obj7.foo10)", "obj6.obj7.foo10");
}


TEST(FuncNameInferrerTwoByte) {
  // Tests function name inferring in cases where some parts of the inferred
  // function name are two-byte strings.
  i::FLAG_allow_natives_syntax = true;
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  LocalContext env;
  uint16_t* two_byte_source = AsciiToTwoByteString(
      "var obj1 = { oXj2 : { foo1: function() {} } }; "
      "%FunctionGetInferredName(obj1.oXj2.foo1)");
  uint16_t* two_byte_name = AsciiToTwoByteString("obj1.oXj2.foo1");
2970
  // Make it really non-Latin1 (replace the Xs with a non-Latin1 character).
2971 2972 2973 2974 2975 2976 2977 2978
  two_byte_source[14] = two_byte_source[78] = two_byte_name[6] = 0x010d;
  v8::Local<v8::String> source =
      v8::String::NewFromTwoByte(isolate, two_byte_source);
  v8::Local<v8::Value> result = CompileRun(source);
  CHECK(result->IsString());
  v8::Local<v8::String> expected_name =
      v8::String::NewFromTwoByte(isolate, two_byte_name);
  CHECK(result->Equals(expected_name));
2979 2980
  i::DeleteArray(two_byte_source);
  i::DeleteArray(two_byte_name);
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
}


TEST(FuncNameInferrerEscaped) {
  // The same as FuncNameInferrerTwoByte, except that we express the two-byte
  // character as a unicode escape.
  i::FLAG_allow_natives_syntax = true;
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  LocalContext env;
  uint16_t* two_byte_source = AsciiToTwoByteString(
      "var obj1 = { o\\u010dj2 : { foo1: function() {} } }; "
      "%FunctionGetInferredName(obj1.o\\u010dj2.foo1)");
  uint16_t* two_byte_name = AsciiToTwoByteString("obj1.oXj2.foo1");
  // Fix to correspond to the non-ASCII name in two_byte_source.
  two_byte_name[6] = 0x010d;
  v8::Local<v8::String> source =
      v8::String::NewFromTwoByte(isolate, two_byte_source);
  v8::Local<v8::Value> result = CompileRun(source);
  CHECK(result->IsString());
  v8::Local<v8::String> expected_name =
      v8::String::NewFromTwoByte(isolate, two_byte_name);
  CHECK(result->Equals(expected_name));
3004 3005
  i::DeleteArray(two_byte_source);
  i::DeleteArray(two_byte_name);
3006
}
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023


TEST(RegressionLazyFunctionWithErrorWithArg) {
  // The bug occurred when a lazy function had an error which requires a
  // parameter (such as "unknown label" here). The error message was processed
  // before the AstValueFactory containing the error message string was
  // internalized.
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  LocalContext env;
  i::FLAG_lazy = true;
  i::FLAG_min_preparse_length = 0;
  CompileRun("function this_is_lazy() {\n"
             "  break p;\n"
             "}\n"
             "this_is_lazy();\n");
}
3024 3025


3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066
TEST(SerializationOfMaybeAssignmentFlag) {
  i::Isolate* isolate = CcTest::i_isolate();
  i::Factory* factory = isolate->factory();
  i::HandleScope scope(isolate);
  LocalContext env;

  const char* src =
      "function h() {"
      "  var result = [];"
      "  function f() {"
      "    result.push(2);"
      "  }"
      "  function assertResult(r) {"
      "    f();"
      "    result = [];"
      "  }"
      "  assertResult([2]);"
      "  assertResult([2]);"
      "  return f;"
      "};"
      "h();";

  i::ScopedVector<char> program(Utf8LengthHelper(src) + 1);
  i::SNPrintF(program, "%s", src);
  i::Handle<i::String> source = factory->InternalizeUtf8String(program.start());
  source->PrintOn(stdout);
  printf("\n");
  i::Zone zone(isolate);
  v8::Local<v8::Value> v = CompileRun(src);
  i::Handle<i::Object> o = v8::Utils::OpenHandle(*v);
  i::Handle<i::JSFunction> f = i::Handle<i::JSFunction>::cast(o);
  i::Context* context = f->context();
  i::AstValueFactory avf(&zone, isolate->heap()->HashSeed());
  avf.Internalize(isolate);
  const i::AstRawString* name = avf.GetOneByteString("result");
  i::Handle<i::String> str = name->string();
  CHECK(str->IsInternalizedString());
  i::Scope* global_scope =
      new (&zone) i::Scope(NULL, i::GLOBAL_SCOPE, &avf, &zone);
  global_scope->Initialize();
  i::Scope* s = i::Scope::DeserializeScopeChain(context, global_scope, &zone);
3067 3068
  DCHECK(s != global_scope);
  DCHECK(name != NULL);
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113

  // Get result from h's function context (that is f's context)
  i::Variable* var = s->Lookup(name);

  CHECK(var != NULL);
  // Maybe assigned should survive deserialization
  CHECK(var->maybe_assigned() == i::kMaybeAssigned);
  // TODO(sigurds) Figure out if is_used should survive context serialization.
}


TEST(IfArgumentsArrayAccessedThenParametersMaybeAssigned) {
  i::Isolate* isolate = CcTest::i_isolate();
  i::Factory* factory = isolate->factory();
  i::HandleScope scope(isolate);
  LocalContext env;


  const char* src =
      "function f(x) {"
      "    var a = arguments;"
      "    function g(i) {"
      "      ++a[0];"
      "    };"
      "    return g;"
      "  }"
      "f(0);";

  i::ScopedVector<char> program(Utf8LengthHelper(src) + 1);
  i::SNPrintF(program, "%s", src);
  i::Handle<i::String> source = factory->InternalizeUtf8String(program.start());
  source->PrintOn(stdout);
  printf("\n");
  i::Zone zone(isolate);
  v8::Local<v8::Value> v = CompileRun(src);
  i::Handle<i::Object> o = v8::Utils::OpenHandle(*v);
  i::Handle<i::JSFunction> f = i::Handle<i::JSFunction>::cast(o);
  i::Context* context = f->context();
  i::AstValueFactory avf(&zone, isolate->heap()->HashSeed());
  avf.Internalize(isolate);

  i::Scope* global_scope =
      new (&zone) i::Scope(NULL, i::GLOBAL_SCOPE, &avf, &zone);
  global_scope->Initialize();
  i::Scope* s = i::Scope::DeserializeScopeChain(context, global_scope, &zone);
3114
  DCHECK(s != global_scope);
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
  const i::AstRawString* name_x = avf.GetOneByteString("x");

  // Get result from f's function context (that is g's outer context)
  i::Variable* var_x = s->Lookup(name_x);
  CHECK(var_x != NULL);
  CHECK(var_x->maybe_assigned() == i::kMaybeAssigned);
}


TEST(ExportsMaybeAssigned) {
  i::FLAG_use_strict = true;
  i::FLAG_harmony_scoping = true;
  i::FLAG_harmony_modules = true;

  i::Isolate* isolate = CcTest::i_isolate();
  i::Factory* factory = isolate->factory();
  i::HandleScope scope(isolate);
  LocalContext env;

  const char* src =
      "module A {"
      "  export var x = 1;"
      "  export function f() { return x };"
      "  export const y = 2;"
      "  module B {}"
      "  export module C {}"
      "};"
      "A.f";

  i::ScopedVector<char> program(Utf8LengthHelper(src) + 1);
  i::SNPrintF(program, "%s", src);
  i::Handle<i::String> source = factory->InternalizeUtf8String(program.start());
  source->PrintOn(stdout);
  printf("\n");
  i::Zone zone(isolate);
  v8::Local<v8::Value> v = CompileRun(src);
  i::Handle<i::Object> o = v8::Utils::OpenHandle(*v);
  i::Handle<i::JSFunction> f = i::Handle<i::JSFunction>::cast(o);
  i::Context* context = f->context();
  i::AstValueFactory avf(&zone, isolate->heap()->HashSeed());
  avf.Internalize(isolate);

  i::Scope* global_scope =
      new (&zone) i::Scope(NULL, i::GLOBAL_SCOPE, &avf, &zone);
  global_scope->Initialize();
  i::Scope* s = i::Scope::DeserializeScopeChain(context, global_scope, &zone);
3161
  DCHECK(s != global_scope);
3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
  const i::AstRawString* name_x = avf.GetOneByteString("x");
  const i::AstRawString* name_f = avf.GetOneByteString("f");
  const i::AstRawString* name_y = avf.GetOneByteString("y");
  const i::AstRawString* name_B = avf.GetOneByteString("B");
  const i::AstRawString* name_C = avf.GetOneByteString("C");

  // Get result from h's function context (that is f's context)
  i::Variable* var_x = s->Lookup(name_x);
  CHECK(var_x != NULL);
  CHECK(var_x->maybe_assigned() == i::kMaybeAssigned);
  i::Variable* var_f = s->Lookup(name_f);
  CHECK(var_f != NULL);
  CHECK(var_f->maybe_assigned() == i::kMaybeAssigned);
  i::Variable* var_y = s->Lookup(name_y);
  CHECK(var_y != NULL);
  CHECK(var_y->maybe_assigned() == i::kNotAssigned);
  i::Variable* var_B = s->Lookup(name_B);
  CHECK(var_B != NULL);
  CHECK(var_B->maybe_assigned() == i::kNotAssigned);
  i::Variable* var_C = s->Lookup(name_C);
  CHECK(var_C != NULL);
  CHECK(var_C->maybe_assigned() == i::kNotAssigned);
}


3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
TEST(InnerAssignment) {
  i::Isolate* isolate = CcTest::i_isolate();
  i::Factory* factory = isolate->factory();
  i::HandleScope scope(isolate);
  LocalContext env;

  const char* prefix = "function f() {";
  const char* midfix = " function g() {";
  const char* suffix = "}}";
  struct { const char* source; bool assigned; bool strict; } outers[] = {
    // Actual assignments.
    { "var x; var x = 5;", true, false },
    { "var x; { var x = 5; }", true, false },
    { "'use strict'; let x; x = 6;", true, true },
    { "var x = 5; function x() {}", true, false },
    // Actual non-assignments.
    { "var x;", false, false },
    { "var x = 5;", false, false },
    { "'use strict'; let x;", false, true },
    { "'use strict'; let x = 6;", false, true },
    { "'use strict'; var x = 0; { let x = 6; }", false, true },
    { "'use strict'; var x = 0; { let x; x = 6; }", false, true },
    { "'use strict'; let x = 0; { let x = 6; }", false, true },
    { "'use strict'; let x = 0; { let x; x = 6; }", false, true },
    { "var x; try {} catch (x) { x = 5; }", false, false },
    { "function x() {}", false, false },
    // Eval approximation.
    { "var x; eval('');", true, false },
    { "eval(''); var x;", true, false },
    { "'use strict'; let x; eval('');", true, true },
    { "'use strict'; eval(''); let x;", true, true },
    // Non-assignments not recognized, because the analysis is approximative.
    { "var x; var x;", true, false },
    { "var x = 5; var x;", true, false },
    { "var x; { var x; }", true, false },
    { "var x; function x() {}", true, false },
    { "function x() {}; var x;", true, false },
    { "var x; try {} catch (x) { var x = 5; }", true, false },
  };
  struct { const char* source; bool assigned; bool with; } inners[] = {
    // Actual assignments.
    { "x = 1;", true, false },
    { "x++;", true, false },
    { "++x;", true, false },
    { "x--;", true, false },
    { "--x;", true, false },
    { "{ x = 1; }", true, false },
    { "'use strict'; { let x; }; x = 0;", true, false },
    { "'use strict'; { const x = 1; }; x = 0;", true, false },
    { "'use strict'; { function x() {} }; x = 0;", true, false },
    { "with ({}) { x = 1; }", true, true },
    { "eval('');", true, false },
    { "'use strict'; { let y; eval('') }", true, false },
    { "function h() { x = 0; }", true, false },
    { "(function() { x = 0; })", true, false },
    { "(function() { x = 0; })", true, false },
    { "with ({}) (function() { x = 0; })", true, true },
    // Actual non-assignments.
    { "", false, false },
    { "x;", false, false },
    { "var x;", false, false },
    { "var x = 8;", false, false },
    { "var x; x = 8;", false, false },
    { "'use strict'; let x;", false, false },
    { "'use strict'; let x = 8;", false, false },
    { "'use strict'; let x; x = 8;", false, false },
    { "'use strict'; const x = 8;", false, false },
    { "function x() {}", false, false },
    { "function x() { x = 0; }", false, false },
    { "function h(x) { x = 0; }", false, false },
    { "'use strict'; { let x; x = 0; }", false, false },
    { "{ var x; }; x = 0;", false, false },
    { "with ({}) {}", false, true },
    { "var x; { with ({}) { x = 1; } }", false, true },
    { "try {} catch(x) { x = 0; }", false, false },
    { "try {} catch(x) { with ({}) { x = 1; } }", false, true },
    // Eval approximation.
    { "eval('');", true, false },
    { "function h() { eval(''); }", true, false },
    { "(function() { eval(''); })", true, false },
    // Shadowing not recognized because of eval approximation.
    { "var x; eval('');", true, false },
    { "'use strict'; let x; eval('');", true, false },
    { "try {} catch(x) { eval(''); }", true, false },
    { "function x() { eval(''); }", true, false },
    { "(function(x) { eval(''); })", true, false },
  };

3275 3276 3277 3278
  // Used to trigger lazy compilation of function
  int comment_len = 2048;
  i::ScopedVector<char> comment(comment_len + 1);
  i::SNPrintF(comment, "/*%0*d*/", comment_len - 4, 0);
3279 3280 3281
  int prefix_len = Utf8LengthHelper(prefix);
  int midfix_len = Utf8LengthHelper(midfix);
  int suffix_len = Utf8LengthHelper(suffix);
3282
  for (unsigned i = 0; i < arraysize(outers); ++i) {
3283 3284
    const char* outer = outers[i].source;
    int outer_len = Utf8LengthHelper(outer);
3285
    for (unsigned j = 0; j < arraysize(inners); ++j) {
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308
      for (unsigned outer_lazy = 0; outer_lazy < 2; ++outer_lazy) {
        for (unsigned inner_lazy = 0; inner_lazy < 2; ++inner_lazy) {
          if (outers[i].strict && inners[j].with) continue;
          const char* inner = inners[j].source;
          int inner_len = Utf8LengthHelper(inner);

          int outer_comment_len = outer_lazy ? comment_len : 0;
          int inner_comment_len = inner_lazy ? comment_len : 0;
          const char* outer_comment = outer_lazy ? comment.start() : "";
          const char* inner_comment = inner_lazy ? comment.start() : "";
          int len = prefix_len + outer_comment_len + outer_len + midfix_len +
                    inner_comment_len + inner_len + suffix_len;
          i::ScopedVector<char> program(len + 1);

          i::SNPrintF(program, "%s%s%s%s%s%s%s", prefix, outer_comment, outer,
                      midfix, inner_comment, inner, suffix);
          i::Handle<i::String> source =
              factory->InternalizeUtf8String(program.start());
          source->PrintOn(stdout);
          printf("\n");

          i::Handle<i::Script> script = factory->NewScript(source);
          i::CompilationInfoWithZone info(script);
3309 3310 3311 3312
          i::Parser::ParseInfo parse_info = {
              isolate->stack_guard()->real_climit(),
              isolate->heap()->HashSeed(), isolate->unicode_cache()};
          i::Parser parser(&info, &parse_info);
3313 3314
          parser.set_allow_harmony_scoping(true);
          CHECK(parser.Parse());
3315
          CHECK(i::Compiler::Analyze(&info));
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329
          CHECK(info.function() != NULL);

          i::Scope* scope = info.function()->scope();
          CHECK_EQ(scope->inner_scopes()->length(), 1);
          i::Scope* inner_scope = scope->inner_scopes()->at(0);
          const i::AstRawString* var_name =
              info.ast_value_factory()->GetOneByteString("x");
          i::Variable* var = inner_scope->Lookup(var_name);
          bool expected = outers[i].assigned || inners[j].assigned;
          CHECK(var != NULL);
          CHECK(var->is_used() || !expected);
          CHECK((var->maybe_assigned() == i::kMaybeAssigned) == expected);
        }
      }
3330 3331 3332
    }
  }
}
3333 3334 3335 3336 3337

namespace {

int* global_use_counts = NULL;

3338 3339
void MockUseCounterCallback(v8::Isolate* isolate,
                            v8::Isolate::UseCounterFeature feature) {
3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
  ++global_use_counts[feature];
}

}


TEST(UseAsmUseCount) {
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);
  LocalContext env;
  int use_counts[v8::Isolate::kUseCounterFeatureCount] = {};
  global_use_counts = use_counts;
3352
  CcTest::isolate()->SetUseCounterCallback(MockUseCounterCallback);
3353 3354 3355 3356
  CompileRun("\"use asm\";\n"
             "var foo = 1;\n"
             "\"use asm\";\n"  // Only the first one counts.
             "function bar() { \"use asm\"; var baz = 1; }");
3357
  CHECK_EQ(2, use_counts[v8::Isolate::kUseAsm]);
3358
}
3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459


TEST(ErrorsArrowFunctions) {
  // Tests that parser and preparser generate the same kind of errors
  // on invalid arrow function syntax.
  const char* context_data[][2] = {
    {"", ";"},
    {"v = ", ";"},
    {"bar ? (", ") : baz;"},
    {"bar ? baz : (", ");"},
    {"bar[", "];"},
    {"bar, ", ";"},
    {"", ", bar;"},
    {NULL, NULL}
  };

  const char* statement_data[] = {
    "=> 0",
    "=>",
    "() =>",
    "=> {}",
    ") => {}",
    ", => {}",
    "(,) => {}",
    "return => {}",
    "() => {'value': 42}",

    // Check that the early return introduced in ParsePrimaryExpression
    // does not accept stray closing parentheses.
    ")",
    ") => 0",
    "foo[()]",
    "()",

    // Parameter lists with extra parens should be recognized as errors.
    "(()) => 0",
    "((x)) => 0",
    "((x, y)) => 0",
    "(x, (y)) => 0",
    "((x, y, z)) => 0",
    "(x, (y, z)) => 0",
    "((x, y), z) => 0",

    // Parameter lists are always validated as strict, so those are errors.
    "eval => {}",
    "arguments => {}",
    "yield => {}",
    "interface => {}",
    "(eval) => {}",
    "(arguments) => {}",
    "(yield) => {}",
    "(interface) => {}",
    "(eval, bar) => {}",
    "(bar, eval) => {}",
    "(bar, arguments) => {}",
    "(bar, yield) => {}",
    "(bar, interface) => {}",
    // TODO(aperez): Detecting duplicates does not work in PreParser.
    // "(bar, bar) => {}",

    // The parameter list is parsed as an expression, but only
    // a comma-separated list of identifier is valid.
    "32 => {}",
    "(32) => {}",
    "(a, 32) => {}",
    "if => {}",
    "(if) => {}",
    "(a, if) => {}",
    "a + b => {}",
    "(a + b) => {}",
    "(a + b, c) => {}",
    "(a, b - c) => {}",
    "\"a\" => {}",
    "(\"a\") => {}",
    "(\"a\", b) => {}",
    "(a, \"b\") => {}",
    "-a => {}",
    "(-a) => {}",
    "(-a, b) => {}",
    "(a, -b) => {}",
    "{} => {}",
    "({}) => {}",
    "(a, {}) => {}",
    "({}, a) => {}",
    "a++ => {}",
    "(a++) => {}",
    "(a++, b) => {}",
    "(a, b++) => {}",
    "[] => {}",
    "([]) => {}",
    "(a, []) => {}",
    "([], a) => {}",
    "(a = b) => {}",
    "(a = b, c) => {}",
    "(a, b = c) => {}",
    "(foo ? bar : baz) => {}",
    "(a, foo ? bar : baz) => {}",
    "(foo ? bar : baz, a) => {}",
    NULL
  };

3460
  // The test is quite slow, so run it with a reduced set of flags.
wingo@igalia.com's avatar
wingo@igalia.com committed
3461
  static const ParserFlag flags[] = {kAllowLazy, kAllowHarmonyScoping};
3462 3463
  static const ParserFlag always_flags[] = { kAllowArrowFunctions };
  RunParserSyncTest(context_data, statement_data, kError, flags,
3464
                    arraysize(flags), always_flags, arraysize(always_flags));
3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
}


TEST(NoErrorsArrowFunctions) {
  // Tests that parser and preparser accept valid arrow functions syntax.
  const char* context_data[][2] = {
    {"", ";"},
    {"bar ? (", ") : baz;"},
    {"bar ? baz : (", ");"},
    {"bar, ", ";"},
    {"", ", bar;"},
    {NULL, NULL}
  };

  const char* statement_data[] = {
    "() => {}",
    "() => { return 42 }",
    "x => { return x; }",
    "(x) => { return x; }",
    "(x, y) => { return x + y; }",
    "(x, y, z) => { return x + y + z; }",
    "(x, y) => { x.a = y; }",
    "() => 42",
    "x => x",
    "x => x * x",
    "(x) => x",
    "(x) => x * x",
    "(x, y) => x + y",
    "(x, y, z) => x, y, z",
    "(x, y) => x.a = y",
    "() => ({'value': 42})",
    "x => y => x + y",
    "(x, y) => (u, v) => x*u + y*v",
    "(x, y) => z => z * (x + y)",
    "x => (y, z) => z * (x + y)",

    // Those are comma-separated expressions, with arrow functions as items.
    // They stress the code for validating arrow function parameter lists.
    "a, b => 0",
    "a, b, (c, d) => 0",
    "(a, b, (c, d) => 0)",
    "(a, b) => 0, (c, d) => 1",
    "(a, b => {}, a => a + 1)",
    "((a, b) => {}, (a => a + 1))",
    "(a, (a, (b, c) => 0))",

    // Arrow has more precedence, this is the same as: foo ? bar : (baz = {})
    "foo ? bar : baz => {}",
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowArrowFunctions};
  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
3518
                    always_flags, arraysize(always_flags));
3519
}
3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542


TEST(NoErrorsSuper) {
  // Tests that parser and preparser accept 'super' keyword in right places.
  const char* context_data[][2] = {{"", ";"},
                                   {"k = ", ";"},
                                   {"foo(", ");"},
                                   {NULL, NULL}};

  const char* statement_data[] = {
    "super.x",
    "super[27]",
    "new super",
    "new super()",
    "new super(12, 45)",
    "new new super",
    "new new super()",
    "new new super()()",
    "z.super",  // Ok, property lookup.
    NULL};

  static const ParserFlag always_flags[] = {kAllowClasses};
  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
3543
                    always_flags, arraysize(always_flags));
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
}


TEST(ErrorsSuper) {
  // Tests that parser and preparser generate same errors for 'super'.
  const char* context_data[][2] = {{"", ";"},
                                   {"k = ", ";"},
                                   {"foo(", ");"},
                                   {NULL, NULL}};

  const char* statement_data[] = {
    "super = x",
    "y = super",
    "f(super)",
    NULL};

  static const ParserFlag always_flags[] = {kAllowClasses};
  RunParserSyncTest(context_data, statement_data, kError, NULL, 0,
3562
                    always_flags, arraysize(always_flags));
3563
}
3564 3565 3566 3567 3568


TEST(NoErrorsMethodDefinition) {
  const char* context_data[][2] = {{"({", "});"},
                                   {"'use strict'; ({", "});"},
3569 3570
                                   {"({*", "});"},
                                   {"'use strict'; ({*", "});"},
3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590
                                   {NULL, NULL}};

  const char* object_literal_body_data[] = {
    "m() {}",
    "m(x) { return x; }",
    "m(x, y) {}, n() {}",
    "set(x, y) {}",
    "get(x, y) {}",
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowHarmonyObjectLiterals};
  RunParserSyncTest(context_data, object_literal_body_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


TEST(MethodDefinitionNames) {
  const char* context_data[][2] = {{"({", "(x, y) {}});"},
                                   {"'use strict'; ({", "(x, y) {}});"},
3591 3592
                                   {"({*", "(x, y) {}});"},
                                   {"'use strict'; ({*", "(x, y) {}});"},
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666
                                   {NULL, NULL}};

  const char* name_data[] = {
    "m",
    "'m'",
    "\"m\"",
    "\"m n\"",
    "true",
    "false",
    "null",
    "0",
    "1.2",
    "1e1",
    "1E1",
    "1e+1",
    "1e-1",

    // Keywords
    "async",
    "await",
    "break",
    "case",
    "catch",
    "class",
    "const",
    "continue",
    "debugger",
    "default",
    "delete",
    "do",
    "else",
    "enum",
    "export",
    "extends",
    "finally",
    "for",
    "function",
    "if",
    "implements",
    "import",
    "in",
    "instanceof",
    "interface",
    "let",
    "new",
    "package",
    "private",
    "protected",
    "public",
    "return",
    "static",
    "super",
    "switch",
    "this",
    "throw",
    "try",
    "typeof",
    "var",
    "void",
    "while",
    "with",
    "yield",
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowHarmonyObjectLiterals};
  RunParserSyncTest(context_data, name_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


TEST(MethodDefinitionStrictFormalParamereters) {
  const char* context_data[][2] = {{"({method(", "){}});"},
                                   {"'use strict'; ({method(", "){}});"},
3667 3668
                                   {"({*method(", "){}});"},
                                   {"'use strict'; ({*method(", "){}});"},
3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703
                                   {NULL, NULL}};

  const char* params_data[] = {
    "x, x",
    "x, y, x",
    "eval",
    "arguments",
    "var",
    "const",
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowHarmonyObjectLiterals};
  RunParserSyncTest(context_data, params_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


TEST(MethodDefinitionDuplicateProperty) {
  // Duplicate properties are allowed in ES6 but we haven't removed that check
  // yet.
  const char* context_data[][2] = {{"'use strict'; ({", "});"},
                                   {NULL, NULL}};

  const char* params_data[] = {
    "x: 1, x() {}",
    "x() {}, x: 1",
    "x() {}, get x() {}",
    "x() {}, set x(_) {}",
    "x() {}, x() {}",
    "x() {}, y() {}, x() {}",
    "x() {}, \"x\"() {}",
    "x() {}, 'x'() {}",
    "0() {}, '0'() {}",
    "1.0() {}, 1: 1",
3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715

    "x: 1, *x() {}",
    "*x() {}, x: 1",
    "*x() {}, get x() {}",
    "*x() {}, set x(_) {}",
    "*x() {}, *x() {}",
    "*x() {}, y() {}, *x() {}",
    "*x() {}, *\"x\"() {}",
    "*x() {}, *'x'() {}",
    "*0() {}, *'0'() {}",
    "*1.0() {}, 1: 1",

3716 3717 3718 3719 3720 3721 3722
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowHarmonyObjectLiterals};
  RunParserSyncTest(context_data, params_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}
arv@chromium.org's avatar
arv@chromium.org committed
3723 3724


3725
TEST(ClassExpressionNoErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748
  const char* context_data[][2] = {{"(", ");"},
                                   {"var C = ", ";"},
                                   {"bar, ", ";"},
                                   {NULL, NULL}};
  const char* class_data[] = {
    "class {}",
    "class name {}",
    "class extends F {}",
    "class name extends F {}",
    "class extends (F, G) {}",
    "class name extends (F, G) {}",
    "class extends class {} {}",
    "class name extends class {} {}",
    "class extends class base {} {}",
    "class name extends class base {} {}",
    NULL};

  static const ParserFlag always_flags[] = {kAllowClasses};
  RunParserSyncTest(context_data, class_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


3749
TEST(ClassDeclarationNoErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
  const char* context_data[][2] = {{"", ""},
                                   {"{", "}"},
                                   {"if (true) {", "}"},
                                   {NULL, NULL}};
  const char* statement_data[] = {
    "class name {}",
    "class name extends F {}",
    "class name extends (F, G) {}",
    "class name extends class {} {}",
    "class name extends class base {} {}",
    NULL};

  static const ParserFlag always_flags[] = {kAllowClasses};
  RunParserSyncTest(context_data, statement_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


3768
TEST(ClassBodyNoErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779
  // Tests that parser and preparser accept valid class syntax.
  const char* context_data[][2] = {{"(class {", "});"},
                                   {"(class extends Base {", "});"},
                                   {"class C {", "}"},
                                   {"class C extends Base {", "}"},
                                   {NULL, NULL}};
  const char* class_body_data[] = {
    ";",
    ";;",
    "m() {}",
    "m() {};",
3780
    "; m() {}",
arv@chromium.org's avatar
arv@chromium.org committed
3781 3782 3783 3784 3785
    "m() {}; n(x) {}",
    "get x() {}",
    "set x(v) {}",
    "get() {}",
    "set() {}",
3786 3787 3788 3789
    "*g() {}",
    "*g() {};",
    "; *g() {}",
    "*g() {}; *h(x) {}",
arv@chromium.org's avatar
arv@chromium.org committed
3790 3791 3792 3793 3794 3795 3796 3797 3798
    "static() {}",
    "static m() {}",
    "static get x() {}",
    "static set x(v) {}",
    "static get() {}",
    "static set() {}",
    "static static() {}",
    "static get static() {}",
    "static set static(v) {}",
3799 3800 3801 3802
    "*static() {}",
    "*get() {}",
    "*set() {}",
    "static *g() {}",
arv@chromium.org's avatar
arv@chromium.org committed
3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_body_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


3814
TEST(ClassPropertyNameNoErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
3815 3816 3817 3818 3819 3820
  const char* context_data[][2] = {{"(class {", "() {}});"},
                                   {"(class { get ", "() {}});"},
                                   {"(class { set ", "(v) {}});"},
                                   {"(class { static ", "() {}});"},
                                   {"(class { static get ", "() {}});"},
                                   {"(class { static set ", "(v) {}});"},
3821 3822
                                   {"(class { *", "() {}});"},
                                   {"(class { static *", "() {}});"},
arv@chromium.org's avatar
arv@chromium.org committed
3823 3824 3825 3826 3827 3828
                                   {"class C {", "() {}}"},
                                   {"class C { get ", "() {}}"},
                                   {"class C { set ", "(v) {}}"},
                                   {"class C { static ", "() {}}"},
                                   {"class C { static get ", "() {}}"},
                                   {"class C { static set ", "(v) {}}"},
3829 3830
                                   {"class C { *", "() {}}"},
                                   {"class C { static *", "() {}}"},
arv@chromium.org's avatar
arv@chromium.org committed
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871
                                   {NULL, NULL}};
  const char* name_data[] = {
    "42",
    "42.5",
    "42e2",
    "42e+2",
    "42e-2",
    "null",
    "false",
    "true",
    "'str'",
    "\"str\"",
    "static",
    "get",
    "set",
    "var",
    "const",
    "let",
    "this",
    "class",
    "function",
    "yield",
    "if",
    "else",
    "for",
    "while",
    "do",
    "try",
    "catch",
    "finally",
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, name_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


3872
TEST(ClassExpressionErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
  const char* context_data[][2] = {{"(", ");"},
                                   {"var C = ", ";"},
                                   {"bar, ", ";"},
                                   {NULL, NULL}};
  const char* class_data[] = {
    "class",
    "class name",
    "class name extends",
    "class extends",
    "class {",
    "class { m }",
    "class { m; n }",
    "class { m: 1 }",
    "class { m(); n() }",
    "class { get m }",
    "class { get m() }",
    "class { get m() { }",
    "class { set m() {} }",  // Missing required parameter.
    "class { m() {}, n() {} }",  // No commas allowed.
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


3903
TEST(ClassDeclarationErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
  const char* context_data[][2] = {{"", ""},
                                   {"{", "}"},
                                   {"if (true) {", "}"},
                                   {NULL, NULL}};
  const char* class_data[] = {
    "class",
    "class name",
    "class name extends",
    "class extends",
    "class name {",
    "class name { m }",
    "class name { m; n }",
    "class name { m: 1 }",
    "class name { m(); n() }",
3918 3919 3920
    "class name { get x }",
    "class name { get x() }",
    "class name { set x() {) }",  // missing required param
arv@chromium.org's avatar
arv@chromium.org committed
3921 3922
    "class {}",  // Name is required for declaration
    "class extends base {}",
3923 3924 3925 3926 3927 3928
    "class name { *",
    "class name { * }",
    "class name { *; }",
    "class name { *get x() {} }",
    "class name { *set x(_) {} }",
    "class name { *static m() {} }",
arv@chromium.org's avatar
arv@chromium.org committed
3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyNumericLiterals
  };
  RunParserSyncTest(context_data, class_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


3940
TEST(ClassNameErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
  const char* context_data[][2] = {{"class ", "{}"},
                                   {"(class ", "{});"},
                                   {"'use strict'; class ", "{}"},
                                   {"'use strict'; (class ", "{});"},
                                   {NULL, NULL}};
  const char* class_name[] = {
    "arguments",
    "eval",
    "implements",
    "interface",
    "let",
    "package",
    "private",
    "protected",
    "public",
    "static",
    "var",
    "yield",
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_name, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


3970
TEST(ClassGetterParamNameErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002
  const char* context_data[][2] = {
    {"class C { get name(", ") {} }"},
    {"(class { get name(", ") {} });"},
    {"'use strict'; class C { get name(", ") {} }"},
    {"'use strict'; (class { get name(", ") {} })"},
    {NULL, NULL}
  };

  const char* class_name[] = {
    "arguments",
    "eval",
    "implements",
    "interface",
    "let",
    "package",
    "private",
    "protected",
    "public",
    "static",
    "var",
    "yield",
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_name, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


4003
TEST(ClassStaticPrototypeErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
4004 4005 4006 4007 4008 4009 4010 4011
  const char* context_data[][2] = {{"class C {", "}"},
                                   {"(class {", "});"},
                                   {NULL, NULL}};

  const char* class_body_data[] = {
    "static prototype() {}",
    "static get prototype() {}",
    "static set prototype(_) {}",
4012
    "static *prototype() {}",
4013 4014 4015 4016 4017 4018 4019
    "static 'prototype'() {}",
    "static *'prototype'() {}",
    "static prot\\u006ftype() {}",
    "static 'prot\\u006ftype'() {}",
    "static get 'prot\\u006ftype'() {}",
    "static set 'prot\\u006ftype'(_) {}",
    "static *'prot\\u006ftype'() {}",
arv@chromium.org's avatar
arv@chromium.org committed
4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_body_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


4031
TEST(ClassSpecialConstructorErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
4032 4033 4034 4035 4036 4037 4038
  const char* context_data[][2] = {{"class C {", "}"},
                                   {"(class {", "});"},
                                   {NULL, NULL}};

  const char* class_body_data[] = {
    "get constructor() {}",
    "get constructor(_) {}",
4039
    "*constructor() {}",
4040 4041 4042 4043 4044 4045 4046
    "get 'constructor'() {}",
    "*'constructor'() {}",
    "get c\\u006fnstructor() {}",
    "*c\\u006fnstructor() {}",
    "get 'c\\u006fnstructor'() {}",
    "get 'c\\u006fnstructor'(_) {}",
    "*'c\\u006fnstructor'() {}",
arv@chromium.org's avatar
arv@chromium.org committed
4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_body_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


4058
TEST(ClassConstructorNoErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
4059 4060 4061 4062 4063 4064 4065 4066 4067
  const char* context_data[][2] = {{"class C {", "}"},
                                   {"(class {", "});"},
                                   {NULL, NULL}};

  const char* class_body_data[] = {
    "constructor() {}",
    "static constructor() {}",
    "static get constructor() {}",
    "static set constructor(_) {}",
4068
    "static *constructor() {}",
arv@chromium.org's avatar
arv@chromium.org committed
4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_body_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


4080
TEST(ClassMultipleConstructorErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
  const char* context_data[][2] = {{"class C {", "}"},
                                   {"(class {", "});"},
                                   {NULL, NULL}};

  const char* class_body_data[] = {
    "constructor() {}; constructor() {}",
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_body_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


4098
TEST(ClassMultiplePropertyNamesNoErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
4099 4100 4101 4102 4103 4104 4105 4106
  const char* context_data[][2] = {{"class C {", "}"},
                                   {"(class {", "});"},
                                   {NULL, NULL}};

  const char* class_body_data[] = {
    "constructor() {}; static constructor() {}",
    "m() {}; static m() {}",
    "m() {}; m() {}",
4107 4108
    "static m() {}; static m() {}",
    "get m() {}; set m(_) {}; get m() {}; set m(_) {};",
arv@chromium.org's avatar
arv@chromium.org committed
4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_body_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));
}


4120
TEST(ClassesAreStrictErrors) {
arv@chromium.org's avatar
arv@chromium.org committed
4121 4122 4123 4124 4125 4126 4127
  const char* context_data[][2] = {{"", ""},
                                   {"(", ");"},
                                   {NULL, NULL}};

  const char* class_body_data[] = {
    "class C { method() { with ({}) {} } }",
    "class C extends function() { with ({}) {} } {}",
4128
    "class C { *method() { with ({}) {} } }",
arv@chromium.org's avatar
arv@chromium.org committed
4129 4130 4131 4132 4133 4134 4135 4136 4137
    NULL};

  static const ParserFlag always_flags[] = {
    kAllowClasses,
    kAllowHarmonyObjectLiterals
  };
  RunParserSyncTest(context_data, class_body_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}
4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255


TEST(ObjectLiteralPropertyShorthandKeywordsError) {
  const char* context_data[][2] = {{"({", "});"},
                                   {"'use strict'; ({", "});"},
                                   {NULL, NULL}};

  const char* name_data[] = {
    "break",
    "case",
    "catch",
    "class",
    "const",
    "continue",
    "debugger",
    "default",
    "delete",
    "do",
    "else",
    "enum",
    "export",
    "extends",
    "false",
    "finally",
    "for",
    "function",
    "if",
    "import",
    "in",
    "instanceof",
    "new",
    "null",
    "return",
    "super",
    "switch",
    "this",
    "throw",
    "true",
    "try",
    "typeof",
    "var",
    "void",
    "while",
    "with",
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowHarmonyObjectLiterals};
  RunParserSyncTest(context_data, name_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


TEST(ObjectLiteralPropertyShorthandStrictKeywords) {
  const char* context_data[][2] = {{"({", "});"},
                                   {NULL, NULL}};

  const char* name_data[] = {
    "implements",
    "interface",
    "let",
    "package",
    "private",
    "protected",
    "public",
    "static",
    "yield",
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowHarmonyObjectLiterals};
  RunParserSyncTest(context_data, name_data, kSuccess, NULL, 0,
                    always_flags, arraysize(always_flags));

  const char* context_strict_data[][2] = {{"'use strict'; ({", "});"},
                                          {NULL, NULL}};
  RunParserSyncTest(context_strict_data, name_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


TEST(ObjectLiteralPropertyShorthandError) {
  const char* context_data[][2] = {{"({", "});"},
                                   {"'use strict'; ({", "});"},
                                   {NULL, NULL}};

  const char* name_data[] = {
    "1",
    "1.2",
    "0",
    "0.1",
    "1.0",
    "1e1",
    "0x1",
    "\"s\"",
    "'s'",
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowHarmonyObjectLiterals};
  RunParserSyncTest(context_data, name_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}


TEST(ObjectLiteralPropertyShorthandYieldInGeneratorError) {
  const char* context_data[][2] = {{"", ""},
                                   {NULL, NULL}};

  const char* name_data[] = {
    "function* g() { ({yield}); }",
    NULL
  };

  static const ParserFlag always_flags[] = {kAllowHarmonyObjectLiterals};
  RunParserSyncTest(context_data, name_data, kError, NULL, 0,
                    always_flags, arraysize(always_flags));
}
4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294


TEST(ConstParsingInForIn) {
  const char* context_data[][2] = {{"'use strict';", ""},
                                   {"function foo(){ 'use strict';", "}"},
                                   {NULL, NULL}};

  const char* data[] = {
      "for(const x = 1; ; ) {}",
      "for(const x = 1, y = 2;;){}",
      "for(const x in [1,2,3]) {}",
      "for(const x of [1,2,3]) {}",
      NULL};
  static const ParserFlag always_flags[] = {kAllowHarmonyScoping};
  RunParserSyncTest(context_data, data, kSuccess, NULL, 0, always_flags,
                    arraysize(always_flags));
}


TEST(ConstParsingInForInError) {
  const char* context_data[][2] = {{"'use strict';", ""},
                                   {"function foo(){ 'use strict';", "}"},
                                   {NULL, NULL}};

  const char* data[] = {
      "for(const x,y = 1; ; ) {}",
      "for(const x = 4 in [1,2,3]) {}",
      "for(const x = 4, y in [1,2,3]) {}",
      "for(const x = 4 of [1,2,3]) {}",
      "for(const x = 4, y of [1,2,3]) {}",
      "for(const x = 1, y = 2 in []) {}",
      "for(const x,y in []) {}",
      "for(const x = 1, y = 2 of []) {}",
      "for(const x,y of []) {}",
      NULL};
  static const ParserFlag always_flags[] = {kAllowHarmonyScoping};
  RunParserSyncTest(context_data, data, kError, NULL, 0, always_flags,
                    arraysize(always_flags));
}
4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308


TEST(InvalidUnicodeEscapes) {
  const char* context_data[][2] = {{"", ""},
                                   {"'use strict';", ""},
                                   {NULL, NULL}};
  const char* data[] = {
    "var foob\\u123r = 0;",
    "var \\u123roo = 0;",
    "\"foob\\u123rr\"",
    "/regex/g\\u123r",
    NULL};
  RunParserSyncTest(context_data, data, kError);
}