Upgrade to https://github.com/acornjs/acorn.git commit 84eda6bf
authorNick Downing <nick@ndcode.org>
Sun, 9 Jan 2022 00:17:50 +0000 (19:17 -0500)
committerNick Downing <nick@ndcode.org>
Sun, 9 Jan 2022 01:20:40 +0000 (12:20 +1100)
31 files changed:
CHANGELOG.md
LICENSE
dist/acorn.d.ts [deleted file]
jst.js
package.json
rollup.config.bin.js [deleted file]
rollup.config.js
src/.eslintrc [deleted file]
src/bin/.eslintrc [deleted file]
src/bin/acorn.js
src/expression.js
src/identifier.js
src/index.js
src/location.js
src/locutil.js
src/lval.js
src/node.js
src/options.js
src/package.json [new file with mode: 0644]
src/parseutil.js
src/regexp.js
src/scope.js
src/scopeflags.js
src/state.js
src/statement.js
src/tokencontext.js
src/tokenize.js
src/tokentype.js
src/unicode-property-data.js
src/util.js
src/whitespace.js

index 59ae22d..d19b5f1 100644 (file)
@@ -1,3 +1,353 @@
+## 8.7.0 (2021-12-27)
+
+### New features
+
+Support quoted export names.
+
+Upgrade to Unicode 14.
+
+Add support for Unicode 13 properties in regular expressions.
+
+### Bug fixes
+
+Use a loop to find line breaks, because the existing regexp search would overrun the end of the searched range and waste a lot of time in minified code.
+
+## 8.6.0 (2021-11-18)
+
+### Bug fixes
+
+Fix a bug where an object literal with multiple `__proto__` properties would incorrectly be accepted if a later property value held an assigment.
+
+### New features
+
+Support class private fields with the `in` operator.
+
+## 8.5.0 (2021-09-06)
+
+### Bug fixes
+
+Improve context-dependent tokenization in a number of corner cases.
+
+Fix location tracking after a 0x2028 or 0x2029 character in a string literal (which before did not increase the line number).
+
+Fix an issue where arrow function bodies in for loop context would inappropriately consume `in` operators.
+
+Fix wrong end locations stored on SequenceExpression nodes.
+
+Implement restriction that `for`/`of` loop LHS can't start with `let`.
+
+### New features
+
+Add support for ES2022 class static blocks.
+
+Allow multiple input files to be passed to the CLI tool.
+
+## 8.4.1 (2021-06-24)
+
+### Bug fixes
+
+Fix a bug where `allowAwaitOutsideFunction` would allow `await` in class field initializers, and setting `ecmaVersion` to 13 or higher would allow top-level await in non-module sources.
+
+## 8.4.0 (2021-06-11)
+
+### New features
+
+A new option, `allowSuperOutsideMethod`, can be used to suppress the error when `super` is used in the wrong context.
+
+## 8.3.0 (2021-05-31)
+
+### New features
+
+Default `allowAwaitOutsideFunction` to true for ECMAScript 2022 an higher.
+
+Add support for the `d` ([indices](https://github.com/tc39/proposal-regexp-match-indices)) regexp flag.
+
+## 8.2.4 (2021-05-04)
+
+### Bug fixes
+
+Fix spec conformity in corner case 'for await (async of ...)'.
+
+## 8.2.3 (2021-05-04)
+
+### Bug fixes
+
+Fix an issue where the library couldn't parse 'for (async of ...)'.
+
+Fix a bug in UTF-16 decoding that would read characters incorrectly in some circumstances.
+
+## 8.2.2 (2021-04-29)
+
+### Bug fixes
+
+Fix a bug where a class field initialized to an async arrow function wouldn't allow await inside it. Same issue existed for generator arrow functions with yield.
+
+## 8.2.1 (2021-04-24)
+
+### Bug fixes
+
+Fix a regression introduced in 8.2.0 where static or async class methods with keyword names fail to parse.
+
+## 8.2.0 (2021-04-24)
+
+### New features
+
+Add support for ES2022 class fields and private methods.
+
+## 8.1.1 (2021-04-12)
+
+### Various
+
+Stop shipping source maps in the NPM package.
+
+## 8.1.0 (2021-03-09)
+
+### Bug fixes
+
+Fix a spurious error in nested destructuring arrays.
+
+### New features
+
+Expose `allowAwaitOutsideFunction` in CLI interface.
+
+Make `allowImportExportAnywhere` also apply to `import.meta`.
+
+## 8.0.5 (2021-01-25)
+
+### Bug fixes
+
+Adjust package.json to work with Node 12.16.0 and 13.0-13.6.
+
+## 8.0.4 (2020-10-05)
+
+### Bug fixes
+
+Make `await x ** y` an error, following the spec.
+
+Fix potentially exponential regular expression.
+
+## 8.0.3 (2020-10-02)
+
+### Bug fixes
+
+Fix a wasteful loop during `Parser` creation when setting `ecmaVersion` to `"latest"`.
+
+## 8.0.2 (2020-09-30)
+
+### Bug fixes
+
+Make the TypeScript types reflect the current allowed values for `ecmaVersion`.
+
+Fix another regexp/division tokenizer issue.
+
+## 8.0.1 (2020-08-12)
+
+### Bug fixes
+
+Provide the correct value in the `version` export.
+
+## 8.0.0 (2020-08-12)
+
+### Bug fixes
+
+Disallow expressions like `(a = b) = c`.
+
+Make non-octal escape sequences a syntax error in strict mode.
+
+### New features
+
+The package can now be loaded directly as an ECMAScript module in node 13+.
+
+Update to the set of Unicode properties from ES2021.
+
+### Breaking changes
+
+The `ecmaVersion` option is now required. For the moment, omitting it will still work with a warning, but that will change in a future release.
+
+Some changes to method signatures that may be used by plugins.
+
+## 7.4.0 (2020-08-03)
+
+### New features
+
+Add support for logical assignment operators.
+
+Add support for numeric separators.
+
+## 7.3.1 (2020-06-11)
+
+### Bug fixes
+
+Make the string in the `version` export match the actual library version.
+
+## 7.3.0 (2020-06-11)
+
+### Bug fixes
+
+Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail.
+
+### New features
+
+Add support for optional chaining (`?.`).
+
+## 7.2.0 (2020-05-09)
+
+### Bug fixes
+
+Fix precedence issue in parsing of async arrow functions.
+
+### New features
+
+Add support for nullish coalescing.
+
+Add support for `import.meta`.
+
+Support `export * as ...` syntax.
+
+Upgrade to Unicode 13.
+
+## 6.4.1 (2020-03-09)
+
+### Bug fixes
+
+More carefully check for valid UTF16 surrogate pairs in regexp validator.
+
+## 7.1.1 (2020-03-01)
+
+### Bug fixes
+
+Treat `\8` and `\9` as invalid escapes in template strings.
+
+Allow unicode escapes in property names that are keywords.
+
+Don't error on an exponential operator expression as argument to `await`.
+
+More carefully check for valid UTF16 surrogate pairs in regexp validator.
+
+## 7.1.0 (2019-09-24)
+
+### Bug fixes
+
+Disallow trailing object literal commas when ecmaVersion is less than 5.
+
+### New features
+
+Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on.
+
+## 7.0.0 (2019-08-13)
+
+### Breaking changes
+
+Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression).
+
+Makes 10 (ES2019) the default value for the `ecmaVersion` option.
+
+## 6.3.0 (2019-08-12)
+
+### New features
+
+`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard.
+
+## 6.2.1 (2019-07-21)
+
+### Bug fixes
+
+Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such.
+
+Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances.
+
+## 6.2.0 (2019-07-04)
+
+### Bug fixes
+
+Improve valid assignment checking in `for`/`in` and `for`/`of` loops.
+
+Disallow binding `let` in patterns.
+
+### New features
+
+Support bigint syntax with `ecmaVersion` >= 11.
+
+Support dynamic `import` syntax with `ecmaVersion` >= 11.
+
+Upgrade to Unicode version 12.
+
+## 6.1.1 (2019-02-27)
+
+### Bug fixes
+
+Fix bug that caused parsing default exports of with names to fail.
+
+## 6.1.0 (2019-02-08)
+
+### Bug fixes
+
+Fix scope checking when redefining a `var` as a lexical binding.
+
+### New features
+
+Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins.
+
+## 6.0.7 (2019-02-04)
+
+### Bug fixes
+
+Check that exported bindings are defined.
+
+Don't treat `\u180e` as a whitespace character.
+
+Check for duplicate parameter names in methods.
+
+Don't allow shorthand properties when they are generators or async methods.
+
+Forbid binding `await` in async arrow function's parameter list.
+
+## 6.0.6 (2019-01-30)
+
+### Bug fixes
+
+The content of class declarations and expressions is now always parsed in strict mode.
+
+Don't allow `let` or `const` to bind the variable name `let`.
+
+Treat class declarations as lexical.
+
+Don't allow a generator function declaration as the sole body of an `if` or `else`.
+
+Ignore `"use strict"` when after an empty statement.
+
+Allow string line continuations with special line terminator characters.
+
+Treat `for` bodies as part of the `for` scope when checking for conflicting bindings.
+
+Fix bug with parsing `yield` in a `for` loop initializer.
+
+Implement special cases around scope checking for functions.
+
+## 6.0.5 (2019-01-02)
+
+### Bug fixes
+
+Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type.
+
+Don't treat `let` as a keyword when the next token is `{` on the next line.
+
+Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on.
+
+## 6.0.4 (2018-11-05)
+
+### Bug fixes
+
+Further improvements to tokenizing regular expressions in corner cases.
+
+## 6.0.3 (2018-11-04)
+
+### Bug fixes
+
+Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression.
+
+Remove stray symlink in the package tarball.
+
 ## 6.0.2 (2018-09-26)
 
 ### Bug fixes
diff --git a/LICENSE b/LICENSE
index 07a38e3..4775a53 100644 (file)
--- a/LICENSE
+++ b/LICENSE
-Copyright (C) 2012-2018 by acorn contributors: Adrian Heine, Adrian Rakovsky,
-Alistair Braidwood, Amila Welihinda, Andres Suarez, Angelo, Aparajita
-Fishman, Arian Stolwijk, Artem Govorov, Boopesh Mahendran, Bradley Heinz,
-Brandon Mills, Charles Hughes, Charmander, Chris McKnight, Conrad Irwin,
-Daniel Tschinder, David Bonnet, Domenico Matteo, ehmicky, Eugene Obrezkov,
-Felix Maier, Forbes Lindesay, Gilad Peleg, impinball, Ingvar Stepanyan,
-Jackson Ray Hamilton, Jesse McCarthy, Jiaxing Wang, Joel Kemp, Johannes Herr,
-John-David Dalton, Jordan Klassen, Jürg Lehni, Kai Cataldo, keeyipchan,
-Keheliya Gallaba, Kevin Irish, Kevin Kwok, krator, laosb, luckyzeng, Marek,
-Marijn Haverbeke, Martin Carlberg, Mat Garcia, Mathias Bynens, Mathieu 'p01'
-Henri, Matthew Bastien, Max Schaefer, Max Zerzouri, Mihai Bazon, Mike Rennie,
-naoh, Nicholas C. Zakas, Nick Fitzgerald, Olivier Thomann, Oskar Schöldström,
-Paul Harper, Peter Rust, PlNG, Prayag Verma, ReadmeCritic, r-e-d, Renée Kooi,
-Richard Gibson, Rich Harris, Sebastian McKenzie, Shahar Soel, Sheel Bedi,
-Simen Bekkhus, Teddy Katz, Timothy Gu, Toru Nagashima, Victor Homyakov, Wexpo
-Lyu, zsjforcn
+Copyright (C) 2012-2021 by acorn contributors:
 
-Copyright (C) 2018 Nick Downing <nick@ndcode.org>
+Adam Walsh
+Adrian Heine
+Adrian Rakovsky
+Alistair Braidwood
+Amila Welihinda
+Andres Suarez
+Angelo
+Aparajita Fishman
+Arian Stolwijk
+Artem Govorov
+Benedikt Meurer
+Ben Page
+Boopesh Mahendran
+Bradley Heinz
+Brandon Mills
+Brian Donovan
+Charles Hughes
+Charmander
+Chris McKnight
+Conrad Irwin
+Cyril Auburtin
+Daniel Nalborczyk
+Daniel Tschinder
+David Bonnet
+daychongyang
+dnalborczyk
+Domenico Matteo
+ehmicky
+ericrannaud
+Eugene Obrezkov
+Fabien LOISON
+Felix Maier
+fn âŒƒ âŒ¥
+Forbes Lindesay
+Gilad Peleg
+HonkingGoose
+Huáng Jùnliàng
+impinball
+Ingvar Stepanyan
+Jackson Ray Hamilton
+Jesse McCarthy
+Jiaxing Wang
+Joe Krump
+Joel Kemp
+Johannes Herr
+John-David Dalton
+Jordan Gensler
+Jordan Harband
+Jordan Klassen
+Julian Wyzykowski
+Jürg Lehni
+Kai Cataldo
+keeyipchan
+Keheliya Gallaba
+Kevin Irish
+Kevin Kwok
+krator
+kyranet
+laosb
+luckyzeng
+Marek
+Marijn Haverbeke
+Martin Carlberg
+Mat Garcia
+Mathias Bynens
+Mathieu 'p01' Henri
+Matthew Bastien
+Max Schaefer
+Max Zerzouri
+Mihai Bazon
+Mike Rennie
+naoh
+Nauja
+Nicholas C. Zakas
+Nick Fitzgerald
+Olivier Thomann
+Oskar Schöldström
+Paul Harper
+peakchen90
+Peter Rust
+piotr
+PlNG
+Praveen N
+Prayag Verma
+ReadmeCritic
+r-e-d
+Renée Kooi
+Richard Gibson
+Rich Harris
+Robert Palmer
+Rouven Weßling
+Sebastian McKenzie
+Shahar Soel
+Sheel Bedi
+Simen Bekkhus
+sosukesuzuki
+susiwen
+susiwen8
+Teddy Katz
+Timothy Gu
+Timo Tijhof
+Tim van der Lippe
+Tony Ross
+Toru Nagashima
+tuesmiddt
+Victor Homyakov
+Vladislav Tupikin
+Wexpo Lyu
+yosuke ota
+ZÌŒiga ZupancÌŒicÌŒ
+zsjforcn
+就是喜欢陈粒
+æˆä»•ä¼Ÿ
+星çµ
+龙腾é“
+
+Copyright (C) 2022 Nick Downing <nick@ndcode.org>
 SPDX-License-Identifier: MIT
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
diff --git a/dist/acorn.d.ts b/dist/acorn.d.ts
deleted file mode 100644 (file)
index 1c8d927..0000000
+++ /dev/null
@@ -1,208 +0,0 @@
-export as namespace acorn
-export = acorn
-
-declare namespace acorn {
-  function parse(input: string, options?: Options): Node
-
-  function parseExpressionAt(input: string, pos?: number, options?: Options): Node
-
-  function tokenizer(input: string, options?: Options): {
-    getToken(): Token
-    [Symbol.iterator](): Iterator<Token>
-  }
-
-  interface Options {
-    ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 2015 | 2016 | 2017 | 2018 | 2019
-    sourceType?: 'script' | 'module'
-    onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
-    onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
-    allowReserved?: boolean
-    allowReturnOutsideFunction?: boolean
-    allowImportExportEverywhere?: boolean
-    allowHashBang?: boolean
-    locations?: boolean
-    onToken?: ((token: Token) => any) | Token[]
-    onComment?: ((
-      isBlock: boolean, text: string, start: number, end: number, startLoc?: Position,
-      endLoc?: Position
-    ) => void) | Comment[]
-    ranges?: boolean
-    program?: Node
-    sourceFile?: string
-    directSourceFile?: string
-    preserveParens?: boolean
-  }
-
-  class Parser {
-    constructor(options: Options, input: string, startPos?: number)
-    parse(): Node
-    static parse(input: string, options?: Options): Node
-    static parseExpressionAt(input: string, pos: number, options?: Options): Node
-    static tokenizer(input: string, options?: Options): {
-      getToken(): Token
-      [Symbol.iterator](): Iterator<Token>
-    }
-    static extend(...plugins: (typeof Parser)[]): typeof Parser
-  }
-
-  interface Position { line: number; column: number; offset: number }
-
-  const defaultOptions: Options
-
-  function getLineInfo(input: string, offset: number): Position
-
-  class SourceLocation {
-    start: Position
-    end: Position
-    source?: string | null
-    constructor(p: Parser, start: Position, end: Position)
-  }
-
-  class Node {
-    type: string
-    start: number
-    end: number
-    loc?: SourceLocation
-    sourceFile?: string
-    range?: [number, number]
-    constructor(parser: Parser, pos: number, loc?: SourceLocation)
-  }
-
-  class TokenType {
-    label: string
-    keyword: string
-    beforeExpr: boolean
-    startsExpr: boolean
-    isLoop: boolean
-    isAssign: boolean
-    prefix: boolean
-    postfix: boolean
-    binop: number
-    updateContext?: (prevType: TokenType) => void
-    constructor(label: string, conf?: any)
-  }
-
-  const tokTypes: {
-    num: TokenType
-    regexp: TokenType
-    string: TokenType
-    name: TokenType
-    eof: TokenType
-    bracketL: TokenType
-    bracketR: TokenType
-    braceL: TokenType
-    braceR: TokenType
-    parenL: TokenType
-    parenR: TokenType
-    comma: TokenType
-    semi: TokenType
-    colon: TokenType
-    dot: TokenType
-    question: TokenType
-    arrow: TokenType
-    template: TokenType
-    ellipsis: TokenType
-    backQuote: TokenType
-    dollarBraceL: TokenType
-    eq: TokenType
-    assign: TokenType
-    incDec: TokenType
-    prefix: TokenType
-    logicalOR: TokenType
-    logicalAND: TokenType
-    bitwiseOR: TokenType
-    bitwiseXOR: TokenType
-    bitwiseAND: TokenType
-    equality: TokenType
-    relational: TokenType
-    bitShift: TokenType
-    plusMin: TokenType
-    modulo: TokenType
-    star: TokenType
-    slash: TokenType
-    starstar: TokenType
-    _break: TokenType
-    _case: TokenType
-    _catch: TokenType
-    _continue: TokenType
-    _debugger: TokenType
-    _default: TokenType
-    _do: TokenType
-    _else: TokenType
-    _finally: TokenType
-    _for: TokenType
-    _function: TokenType
-    _if: TokenType
-    _return: TokenType
-    _switch: TokenType
-    _throw: TokenType
-    _try: TokenType
-    _var: TokenType
-    _const: TokenType
-    _while: TokenType
-    _with: TokenType
-    _new: TokenType
-    _this: TokenType
-    _super: TokenType
-    _class: TokenType
-    _extends: TokenType
-    _export: TokenType
-    _import: TokenType
-    _null: TokenType
-    _true: TokenType
-    _false: TokenType
-    _in: TokenType
-    _instanceof: TokenType
-    _typeof: TokenType
-    _void: TokenType
-    _delete: TokenType
-  }
-
-  class TokContext {
-    constructor(token: string, isExpr: boolean, preserveSpace: boolean, override?: (p: Parser) => void)
-  }
-
-  const tokContexts: {
-    b_stat: TokContext
-    b_expr: TokContext
-    b_tmpl: TokContext
-    p_stat: TokContext
-    p_expr: TokContext
-    q_tmpl: TokContext
-    f_expr: TokContext
-  }
-
-  function isIdentifierStart(code: number, astral?: boolean): boolean
-
-  function isIdentifierChar(code: number, astral?: boolean): boolean
-
-  interface AbstractToken {
-  }
-
-  interface Comment extends AbstractToken {
-    type: string
-    value: string
-    start: number
-    end: number
-    loc?: SourceLocation
-    range?: [number, number]
-  }
-
-  class Token {
-    type: TokenType
-    value: any
-    start: number
-    end: number
-    loc?: SourceLocation
-    range?: [number, number]
-    constructor(p: Parser)
-  }
-
-  function isNewLine(code: number): boolean
-
-  const lineBreak: RegExp
-
-  const lineBreakG: RegExp
-
-  const version: string
-}
diff --git a/jst.js b/jst.js
index 94f72ed..5fbf41b 100644 (file)
--- a/jst.js
+++ b/jst.js
@@ -28,13 +28,24 @@ let visitors = require('./visitors')
 
 let jst = (text, options) => {
   options = Object.assign(
-    {bare_returns: true, indent: 2, initial_indent: 0},
+    {
+      bare_returns: true,
+      ecma_version: 'latest', // or 11, 12, 13, etc
+      indent: 2,
+      initial_indent: 0
+    },
     options || {}
   )
   return astring.generate(
     transform.transform(
       visitors,
-      acorn.parse(text, {allowReturnOutsideFunction: options.bare_returns})
+      acorn.parse(
+        text,
+        {
+          allowReturnOutsideFunction: options.bare_returns,
+          ecmaVersion: options.ecma_version
+        }
+      )
     ),
     {
       indent: ' '.repeat(options.indent),
index b6998b9..26b3f67 100644 (file)
     "@ndcode/build_cache": "^0.1.0",
     "@ndcode/clean-css": "^0.1.0",
     "@ndcode/disk_build": "^0.1.1",
+    "@rollup/plugin-buble": "^0.21.3",
+    "@unicode/unicode-14.0.0": "^1.2.1",
     "assert": "^1.4.1",
     "astring": "^1.3.1",
     "commander": "^2.17.0",
-    "rollup": "^0.45.0",
-    "rollup-plugin-buble": "^0.16.0",
+    "rollup": "^2.60.2",
     "uglify-es": "^3.3.9"
   },
   "devDependencies": {},
diff --git a/rollup.config.bin.js b/rollup.config.bin.js
deleted file mode 100644 (file)
index 19234cb..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-import buble from "rollup-plugin-buble"
-
-export default {
-  entry: "acorn/src/bin/acorn.js",
-  dest: "acorn/dist/bin.js",
-  format: "cjs",
-  external: ["fs", "path", "acorn"],
-  paths: {acorn: "./acorn.js"},
-  plugins: [buble()]
-}
index f6dea7d..9898709 100644 (file)
@@ -1,14 +1,33 @@
-import buble from "rollup-plugin-buble"
+import buble from "@rollup/plugin-buble"
 
-export default {
-  entry: "src/index.js",
-  moduleName: "acorn",
-  plugins: [
-    buble({transforms: {dangerousForOf: true}})
-  ],
-  sourceMap: true,
-  targets: [
-    {dest: "dist/acorn.js", format: "umd"},
-    {dest: "dist/acorn.mjs", format: "es"}
-  ]
-}
+export default [
+  {
+    input: "src/index.js",
+    output: [
+      {
+        file: "dist/acorn.js",
+        format: "umd",
+        name: "acorn"
+      },
+      {
+        file: "dist/acorn.mjs",
+        format: "es"
+      }
+    ],
+    plugins: [
+      buble({transforms: {dangerousForOf: true}})
+    ]
+  },
+  {
+    external: ["acorn", "fs", "path"],
+    input: "src/bin/acorn.js",
+    output: {
+      file: "dist/bin.js",
+      format: "cjs",
+      paths: {acorn: "./acorn.js"}
+    },
+    plugins: [
+      buble({transforms: {dangerousForOf: true}})
+    ]
+  }
+]
diff --git a/src/.eslintrc b/src/.eslintrc
deleted file mode 100644 (file)
index ea6fbdf..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-{
-    "extends": [
-        "eslint:recommended",
-        "standard",
-        "plugin:import/errors",
-        "plugin:import/warnings"
-    ],
-    "rules": {
-        "curly": "off",
-        "eqeqeq": ["error", "always", { "null": "ignore" }],
-        "indent": ["error", 2, { "SwitchCase": 0, "VariableDeclarator": 2, "CallExpression": { "arguments": "off" } }],
-        "new-parens": "off",
-        "no-case-declarations": "off",
-        "no-cond-assign": "off",
-        "no-fallthrough": "off",
-        "no-labels": "off",
-        "no-mixed-operators": "off",
-        "no-return-assign": "off",
-        "no-unused-labels": "error",
-        "no-var": "error",
-        "object-curly-spacing": ["error", "never"],
-        "one-var": "off",
-        "quotes": ["error", "double"],
-        "semi-spacing": "off",
-        "space-before-function-paren": ["error", "never"]
-    },
-    "globals": {
-        "Packages": false
-    },
-    "plugins": [
-        "import"
-    ]
-}
diff --git a/src/bin/.eslintrc b/src/bin/.eslintrc
deleted file mode 100644 (file)
index 2598b25..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-{
-    "extends": "../.eslintrc",
-    "rules": {
-        "no-console": "off"
-    }
-}
\ No newline at end of file
index 2aa4139..c33e61f 100644 (file)
@@ -2,22 +2,26 @@ import {basename} from "path"
 import {readFileSync as readFile} from "fs"
 import * as acorn from "acorn"
 
-let infile, forceFile, silent = false, compact = false, tokenize = false
+let inputFilePaths = [], forceFileName = false, fileMode = false, silent = false, compact = false, tokenize = false
 const options = {}
 
 function help(status) {
   const print = (status === 0) ? console.log : console.error
   print("usage: " + basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|...|--ecma2015|--ecma2016|--ecma2017|--ecma2018|...]")
-  print("        [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]")
+  print("        [--tokenize] [--locations] [--allow-hash-bang] [--allow-await-outside-function] [--compact] [--silent] [--module] [--help] [--] [<infile>...]")
   process.exit(status)
 }
 
 for (let i = 2; i < process.argv.length; ++i) {
   const arg = process.argv[i]
-  if ((arg === "-" || arg[0] !== "-") && !infile) infile = arg
-  else if (arg === "--" && !infile && i + 2 === process.argv.length) forceFile = infile = process.argv[++i]
-  else if (arg === "--locations") options.locations = true
+  if (arg[0] !== "-" || arg === "-") inputFilePaths.push(arg)
+  else if (arg === "--") {
+    inputFilePaths.push(...process.argv.slice(i + 1))
+    forceFileName = true
+    break
+  } else if (arg === "--locations") options.locations = true
   else if (arg === "--allow-hash-bang") options.allowHashBang = true
+  else if (arg === "--allow-await-outside-function") options.allowAwaitOutsideFunction = true
   else if (arg === "--silent") silent = true
   else if (arg === "--compact") compact = true
   else if (arg === "--help") help(0)
@@ -32,31 +36,34 @@ for (let i = 2; i < process.argv.length; ++i) {
   }
 }
 
-function run(code) {
-  let result
+function run(codeList) {
+  let result = [], fileIdx = 0
   try {
-    if (!tokenize) {
-      result = acorn.parse(code, options)
-    } else {
-      result = []
-      let tokenizer = acorn.tokenizer(code, options), token
-      do {
-        token = tokenizer.getToken()
-        result.push(token)
-      } while (token.type !== acorn.tokTypes.eof)
-    }
+    codeList.forEach((code, idx) => {
+      fileIdx = idx
+      if (!tokenize) {
+        result = acorn.parse(code, options)
+        options.program = result
+      } else {
+        let tokenizer = acorn.tokenizer(code, options), token
+        do {
+          token = tokenizer.getToken()
+          result.push(token)
+        } while (token.type !== acorn.tokTypes.eof)
+      }
+    })
   } catch (e) {
-    console.error(e.message)
+    console.error(fileMode ? e.message.replace(/\(\d+:\d+\)$/, m => m.slice(0, 1) + inputFilePaths[fileIdx] + " " + m.slice(1)) : e.message)
     process.exit(1)
   }
   if (!silent) console.log(JSON.stringify(result, null, compact ? null : 2))
 }
 
-if (forceFile || infile && infile !== "-") {
-  run(readFile(infile, "utf8"))
+if (fileMode = inputFilePaths.length && (forceFileName || !inputFilePaths.includes("-") || inputFilePaths.length !== 1)) {
+  run(inputFilePaths.map(path => readFile(path, "utf8")))
 } else {
   let code = ""
   process.stdin.resume()
   process.stdin.on("data", chunk => code += chunk)
-  process.stdin.on("end", () => run(code))
+  process.stdin.on("end", () => run([code]))
 }
index e40808f..78bc2df 100644 (file)
 //
 // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
 
-import {types as tt} from "./tokentype"
-import {Parser} from "./state"
-import {DestructuringErrors} from "./parseutil"
-import {lineBreak} from "./whitespace"
-import {functionFlags, SCOPE_ARROW, SCOPE_SUPER, SCOPE_DIRECT_SUPER, BIND_OUTSIDE, BIND_VAR} from "./scopeflags"
+import {types as tt} from "./tokentype.js"
+import {types as tokenCtxTypes} from "./tokencontext.js"
+import {Parser} from "./state.js"
+import {DestructuringErrors} from "./parseutil.js"
+import {lineBreak} from "./whitespace.js"
+import {functionFlags, SCOPE_ARROW, SCOPE_SUPER, SCOPE_DIRECT_SUPER, BIND_OUTSIDE, BIND_VAR} from "./scopeflags.js"
 
 // Nick
 import CleanCSS from "@ndcode/clean-css"
@@ -48,9 +49,13 @@ pp.checkPropClash = function(prop, propHash, refDestructuringErrors) {
   if (this.options.ecmaVersion >= 6) {
     if (name === "__proto__" && kind === "init") {
       if (propHash.proto) {
-        if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) refDestructuringErrors.doubleProto = key.start
-        // Backwards-compat kludge. Can be removed in version 6.0
-        else this.raiseRecoverable(key.start, "Redefinition of __proto__ property")
+        if (refDestructuringErrors) {
+          if (refDestructuringErrors.doubleProto < 0) {
+            refDestructuringErrors.doubleProto = key.start
+          }
+        } else {
+          this.raiseRecoverable(key.start, "Redefinition of __proto__ property")
+        }
       }
       propHash.proto = true
     }
@@ -92,13 +97,13 @@ pp.checkPropClash = function(prop, propHash, refDestructuringErrors) {
 // and object pattern might appear (so it's possible to raise
 // delayed syntax error at correct position).
 
-pp.parseExpression = function(noIn, refDestructuringErrors) {
+pp.parseExpression = function(forInit, refDestructuringErrors) {
   let startPos = this.start, startLoc = this.startLoc
-  let expr = this.parseMaybeAssign(noIn, refDestructuringErrors)
+  let expr = this.parseMaybeAssign(forInit, refDestructuringErrors)
   if (this.type === tt.comma) {
     let node = this.startNodeAt(startPos, startLoc)
     node.expressions = [expr]
-    while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors))
+    while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors))
     return this.finishNode(node, "SequenceExpression")
   }
   return expr
@@ -107,61 +112,71 @@ pp.parseExpression = function(noIn, refDestructuringErrors) {
 // Parse an assignment expression. This includes applications of
 // operators like `+=`.
 
-pp.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
+pp.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
   if (this.isContextual("yield")) {
-    if (this.inGenerator) return this.parseYield()
+    if (this.inGenerator) return this.parseYield(forInit)
     // The tokenizer will assume an expression is allowed after
     // `yield`, but this isn't that kind of yield
     else this.exprAllowed = false
   }
 
-  let ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1
+  let ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1
   if (refDestructuringErrors) {
     oldParenAssign = refDestructuringErrors.parenthesizedAssign
     oldTrailingComma = refDestructuringErrors.trailingComma
-    oldShorthandAssign = refDestructuringErrors.shorthandAssign
-    refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -1
+    oldDoubleProto = refDestructuringErrors.doubleProto
+    refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1
   } else {
     refDestructuringErrors = new DestructuringErrors
     ownDestructuringErrors = true
   }
 
   let startPos = this.start, startLoc = this.startLoc
-  if (this.type === tt.parenL || this.type === tt.name)
+  if (this.type === tt.parenL || this.type === tt.name) {
     this.potentialArrowAt = this.start
-  let left = this.parseMaybeConditional(noIn, refDestructuringErrors)
+    this.potentialArrowInForAwait = forInit === "await"
+  }
+  let left = this.parseMaybeConditional(forInit, refDestructuringErrors)
   if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc)
   if (this.type.isAssign) {
     let node = this.startNodeAt(startPos, startLoc)
     node.operator = this.value
-    node.left = this.type === tt.eq ? this.toAssignable(left, false, refDestructuringErrors) : left
-    if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors)
-    refDestructuringErrors.shorthandAssign = -1 // reset because shorthand default was used correctly
-    this.checkLVal(left)
+    if (this.type === tt.eq)
+      left = this.toAssignable(left, false, refDestructuringErrors)
+    if (!ownDestructuringErrors) {
+      refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1
+    }
+    if (refDestructuringErrors.shorthandAssign >= left.start)
+      refDestructuringErrors.shorthandAssign = -1 // reset because shorthand default was used correctly
+    if (this.type === tt.eq)
+      this.checkLValPattern(left)
+    else
+      this.checkLValSimple(left)
+    node.left = left
     this.next()
-    node.right = this.parseMaybeAssign(noIn)
+    node.right = this.parseMaybeAssign(forInit)
+    if (oldDoubleProto > -1) refDestructuringErrors.doubleProto = oldDoubleProto
     return this.finishNode(node, "AssignmentExpression")
   } else {
     if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true)
   }
   if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign
   if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma
-  if (oldShorthandAssign > -1) refDestructuringErrors.shorthandAssign = oldShorthandAssign
   return left
 }
 
 // Parse a ternary conditional (`?:`) operator.
 
-pp.parseMaybeConditional = function(noIn, refDestructuringErrors) {
+pp.parseMaybeConditional = function(forInit, refDestructuringErrors) {
   let startPos = this.start, startLoc = this.startLoc
-  let expr = this.parseExprOps(noIn, refDestructuringErrors)
+  let expr = this.parseExprOps(forInit, refDestructuringErrors)
   if (this.checkExpressionErrors(refDestructuringErrors)) return expr
   if (this.eat(tt.question)) {
     let node = this.startNodeAt(startPos, startLoc)
     node.test = expr
     node.consequent = this.parseMaybeAssign()
     this.expect(tt.colon)
-    node.alternate = this.parseMaybeAssign(noIn)
+    node.alternate = this.parseMaybeAssign(forInit)
     return this.finishNode(node, "ConditionalExpression")
   }
   return expr
@@ -169,11 +184,11 @@ pp.parseMaybeConditional = function(noIn, refDestructuringErrors) {
 
 // Start the precedence parser.
 
-pp.parseExprOps = function(noIn, refDestructuringErrors) {
+pp.parseExprOps = function(forInit, refDestructuringErrors) {
   let startPos = this.start, startLoc = this.startLoc
-  let expr = this.parseMaybeUnary(refDestructuringErrors, false)
+  let expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit)
   if (this.checkExpressionErrors(refDestructuringErrors)) return expr
-  return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
+  return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
 }
 
 // Parse binary operators with the operator precedence parsing
@@ -182,23 +197,33 @@ pp.parseExprOps = function(noIn, refDestructuringErrors) {
 // defer further parser to one of its callers when it encounters an
 // operator that has a lower precedence than the set it is parsing.
 
-pp.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
+pp.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
   let prec = this.type.binop
-  if (prec != null && (!noIn || this.type !== tt._in)) {
+  if (prec != null && (!forInit || this.type !== tt._in)) {
     if (prec > minPrec) {
       let logical = this.type === tt.logicalOR || this.type === tt.logicalAND
+      let coalesce = this.type === tt.coalesce
+      if (coalesce) {
+        // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
+        // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
+        prec = tt.logicalAND.binop
+      }
       let op = this.value
       this.next()
       let startPos = this.start, startLoc = this.startLoc
-      let right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn)
-      let node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical)
-      return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
+      let right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit)
+      let node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce)
+      if ((logical && this.type === tt.coalesce) || (coalesce && (this.type === tt.logicalOR || this.type === tt.logicalAND))) {
+        this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses")
+      }
+      return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
     }
   }
   return left
 }
 
 pp.buildBinary = function(startPos, startLoc, left, right, op, logical) {
+  if (right.type === "PrivateIdentifier") this.raise(right.start, "Private identifier can only be left side of binary expression")
   let node = this.startNodeAt(startPos, startLoc)
   node.left = left
   node.operator = op
@@ -208,143 +233,206 @@ pp.buildBinary = function(startPos, startLoc, left, right, op, logical) {
 
 // Parse unary operators, both prefix and postfix.
 
-pp.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
+pp.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
   let startPos = this.start, startLoc = this.startLoc, expr
-  if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
-    expr = this.parseAwait()
+  if (this.isContextual("await") && this.canAwait) {
+    expr = this.parseAwait(forInit)
     sawUnary = true
   } else if (this.type.prefix) {
     let node = this.startNode(), update = this.type === tt.incDec
     node.operator = this.value
     node.prefix = true
     this.next()
-    node.argument = this.parseMaybeUnary(null, true)
+    node.argument = this.parseMaybeUnary(null, true, update, forInit)
     this.checkExpressionErrors(refDestructuringErrors, true)
-    if (update) this.checkLVal(node.argument)
+    if (update) this.checkLValSimple(node.argument)
     else if (this.strict && node.operator === "delete" &&
              node.argument.type === "Identifier")
       this.raiseRecoverable(node.start, "Deleting local variable in strict mode")
+    else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
+      this.raiseRecoverable(node.start, "Private fields can not be deleted")
     else sawUnary = true
     expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
+  } else if (!sawUnary && this.type === tt.privateId) {
+    if (forInit || this.privateNameStack.length === 0) this.unexpected()
+    expr = this.parsePrivateIdent()
+    // only could be private fields in 'in', such as #x in obj
+    if (this.type !== tt._in) this.unexpected()
   } else {
-    expr = this.parseExprSubscripts(refDestructuringErrors)
+    expr = this.parseExprSubscripts(refDestructuringErrors, forInit)
     if (this.checkExpressionErrors(refDestructuringErrors)) return expr
     while (this.type.postfix && !this.canInsertSemicolon()) {
       let node = this.startNodeAt(startPos, startLoc)
       node.operator = this.value
       node.prefix = false
       node.argument = expr
-      this.checkLVal(expr)
+      this.checkLValSimple(expr)
       this.next()
       expr = this.finishNode(node, "UpdateExpression")
     }
   }
 
-  if (!sawUnary && this.eat(tt.starstar))
-    return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false)
-  else
+  if (!incDec && this.eat(tt.starstar)) {
+    if (sawUnary)
+      this.unexpected(this.lastTokStart)
+    else
+      return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false)
+  } else {
     return expr
+  }
+}
+
+function isPrivateFieldAccess(node) {
+  return (
+    node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
+    node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
+  )
 }
 
 // Parse call, dot, and `[]`-subscript expressions.
 
-pp.parseExprSubscripts = function(refDestructuringErrors) {
+pp.parseExprSubscripts = function(refDestructuringErrors, forInit) {
   let startPos = this.start, startLoc = this.startLoc
-  let expr = this.parseExprAtom(refDestructuringErrors)
-  let skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"
-  if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr
-  let result = this.parseSubscripts(expr, startPos, startLoc)
+  let expr = this.parseExprAtom(refDestructuringErrors, forInit)
+  if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
+    return expr
+  let result = this.parseSubscripts(expr, startPos, startLoc, false, forInit)
   if (refDestructuringErrors && result.type === "MemberExpression") {
     if (refDestructuringErrors.parenthesizedAssign >= result.start) refDestructuringErrors.parenthesizedAssign = -1
     if (refDestructuringErrors.parenthesizedBind >= result.start) refDestructuringErrors.parenthesizedBind = -1
+    if (refDestructuringErrors.trailingComma >= result.start) refDestructuringErrors.trailingComma = -1
   }
   return result
 }
 
-pp.parseSubscripts = function(base, startPos, startLoc, noCalls) {
+pp.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
   let maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
-      this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"
-  for (let computed;;) {
-    if ((computed = this.eat(tt.bracketL)) || this.eat(tt.dot)) {
-      let node = this.startNodeAt(startPos, startLoc)
-      node.object = base
-      //node.property = computed ? this.parseExpression() : this.parseIdent(true)
-      node.property = computed ? this.parseExpression() : this.type === tt.string ? this.parseLiteral(this.value) : this.parseIdent(true) // Nick
-      node.computed = !!computed
-      if (computed) this.expect(tt.bracketR)
-      base = this.finishNode(node, "MemberExpression")
+      this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
+      this.potentialArrowAt === base.start
+  let optionalChained = false
+
+  while (true) {
+    let element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit)
+
+    if (element.optional) optionalChained = true
+    if (element === base || element.type === "ArrowFunctionExpression") {
+      if (optionalChained) {
+        const chainNode = this.startNodeAt(startPos, startLoc)
+        chainNode.expression = element
+        element = this.finishNode(chainNode, "ChainExpression")
+      }
+      return element
+    }
+
+    base = element
+  }
+}
+
+pp.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
+  let optionalSupported = this.options.ecmaVersion >= 11
+  let optional = optionalSupported && this.eat(tt.questionDot)
+  if (noCalls && optional) this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions")
+
+  let computed = this.eat(tt.bracketL)
+  if (computed || (optional && this.type !== tt.parenL && this.type !== tt.backQuote) || this.eat(tt.dot)) {
+    let node = this.startNodeAt(startPos, startLoc)
+    node.object = base
+    if (computed) {
+      node.property = this.parseExpression()
+      this.expect(tt.bracketR)
+    } else if (this.type === tt.privateId && base.type !== "Super") {
+      node.property = this.parsePrivateIdent()
+    } else if (this.type === tt.string) { // Nick
+      node.property = this.parseLiteral(this.value)
+    } else {
+      node.property = this.parseIdent(this.options.allowReserved !== "never")
+    }
+    node.computed = !!computed
+    if (optionalSupported) {
+      node.optional = optional
+    }
+    base = this.finishNode(node, "MemberExpression")
     } else if (this.eat(tt.hash)) { // Nick
       let node = this.startNodeAt(startPos, startLoc)
       node.object = base
       //node.property = this.parseIdent(true)
       node.property = this.type === tt.string ? this.parseLiteral(this.value) : this.parseIdent(true) // Nick
       base = this.finishNode(node, "MemberExpressionHash")
-    } else if (!noCalls && this.eat(tt.parenL)) {
-      let refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos
-      this.yieldPos = 0
-      this.awaitPos = 0
-      let exprList = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors)
-      if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
-        this.checkPatternErrors(refDestructuringErrors, false)
-        this.checkYieldAwaitInDefaultParams()
-        this.yieldPos = oldYieldPos
-        this.awaitPos = oldAwaitPos
-        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
-      }
-      this.checkExpressionErrors(refDestructuringErrors, true)
-      this.yieldPos = oldYieldPos || this.yieldPos
-      this.awaitPos = oldAwaitPos || this.awaitPos
-      let node = this.startNodeAt(startPos, startLoc)
-      node.callee = base
-      node.arguments = exprList
-      base = this.finishNode(node, "CallExpression")
-    } else if (this.type === tt.backQuote) {
-      let node = this.startNodeAt(startPos, startLoc)
-      node.tag = base
-      node.quasi = this.parseTemplate({isTagged: true})
-      base = this.finishNode(node, "TaggedTemplateExpression")
-    } else if (this.type === tt.braceL) { // Nick
-      let node = this.startNodeAt(startPos, startLoc)
-      node.tag = base
-      if (
-        (
-          base.type === 'Identifier' &&
-          base.name === 'style'
-        ) ||
-        (
-          base.type === 'CallExpression' &&
-          base.callee.type === 'Identifier' &&
-          base.callee.name === 'style'
-        )
-      ) {
-        let render = clean_css.minifyEmbedded(this.input, this.pos)
-        if (render.errors.length)
-          throw render.errors
-        for (let i = 0; i < render.warnings.length; ++i)
-          console.log(`clean-css warning: ${render.warnings[i]}`)
-        node.body = {
-          type: 'BlockStatement',
-          body: [
-            {
-              type: 'ExpressionStatement',
-              expression: {
-                type: 'Literal',
-                value: render.styles // we simply assume it does not contain </style> tags, should HTML escape it??
-              }
+  } else if (!noCalls && this.eat(tt.parenL)) {
+    let refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos
+    this.yieldPos = 0
+    this.awaitPos = 0
+    this.awaitIdentPos = 0
+    let exprList = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors)
+    if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
+      this.checkPatternErrors(refDestructuringErrors, false)
+      this.checkYieldAwaitInDefaultParams()
+      if (this.awaitIdentPos > 0)
+        this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function")
+      this.yieldPos = oldYieldPos
+      this.awaitPos = oldAwaitPos
+      this.awaitIdentPos = oldAwaitIdentPos
+      return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
+    }
+    this.checkExpressionErrors(refDestructuringErrors, true)
+    this.yieldPos = oldYieldPos || this.yieldPos
+    this.awaitPos = oldAwaitPos || this.awaitPos
+    this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos
+    let node = this.startNodeAt(startPos, startLoc)
+    node.callee = base
+    node.arguments = exprList
+    if (optionalSupported) {
+      node.optional = optional
+    }
+    base = this.finishNode(node, "CallExpression")
+  } else if (this.type === tt.backQuote) {
+    if (optional || optionalChained) {
+      this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions")
+    }
+    let node = this.startNodeAt(startPos, startLoc)
+    node.tag = base
+    node.quasi = this.parseTemplate({isTagged: true})
+    base = this.finishNode(node, "TaggedTemplateExpression")
+  } else if (this.type === tt.braceL) { // Nick
+    let node = this.startNodeAt(startPos, startLoc)
+    node.tag = base
+    if (
+      (
+        base.type === 'Identifier' &&
+        base.name === 'style'
+      ) ||
+      (
+        base.type === 'CallExpression' &&
+        base.callee.type === 'Identifier' &&
+        base.callee.name === 'style'
+      )
+    ) {
+      let render = clean_css.minifyEmbedded(this.input, this.pos)
+      if (render.errors.length)
+        throw render.errors
+      for (let i = 0; i < render.warnings.length; ++i)
+        console.log(`clean-css warning: ${render.warnings[i]}`)
+      node.body = {
+        type: 'BlockStatement',
+        body: [
+          {
+            type: 'ExpressionStatement',
+            expression: {
+              type: 'Literal',
+              value: render.styles // we simply assume it does not contain </style> tags, should HTML escape it??
             }
-          ]
-        }
-        this.pos = render.embeddedEnd
-        this.next()
-        this.expect(tt.braceR)
+          }
+        ]
       }
-      else
-        node.body = this.parseBlock(false)
-      base = this.finishNode(node, "HTMLExpression")
-    } else {
-      return base
+      this.pos = render.embeddedEnd
+      this.next()
+      this.expect(tt.braceR)
     }
+    else
+      node.body = this.parseBlock(false)
+    base = this.finishNode(node, "HTMLExpression")
   }
+  return base
 }
 
 // Parse an atomic expression â€” either a single token that is an
@@ -352,7 +440,11 @@ pp.parseSubscripts = function(base, startPos, startLoc, noCalls) {
 // `new`, or an expression wrapped in punctuation like `()`, `[]`,
 // or `{}`.
 
-pp.parseExprAtom = function(refDestructuringErrors) {
+pp.parseExprAtom = function(refDestructuringErrors, forInit) {
+  // If a division operator appears in an expression position, the
+  // tokenizer got confused, and we force it to read a regexp instead.
+  if (this.type === tt.slash) this.readRegexp()
+
   let node, canBeArrow = this.potentialArrowAt === this.start
   switch (this.type) {
   case tt._super:
@@ -367,7 +459,7 @@ pp.parseExprAtom = function(refDestructuringErrors) {
     //     super [ Expression ]
     //     super . IdentifierName
     // SuperCall:
-    //     super Arguments
+    //     super ( Arguments )
     if (this.type !== tt.dot && this.type !== tt.bracketL && this.type !== tt.parenL)
       this.unexpected()
     return this.finishNode(node, "Super")
@@ -379,17 +471,20 @@ pp.parseExprAtom = function(refDestructuringErrors) {
 
   case tt.name:
     let startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc
-    let id = this.parseIdent(this.type !== tt.name)
-    if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function))
-      return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true)
+    let id = this.parseIdent(false)
+    if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function)) {
+      this.overrideContext(tokenCtxTypes.f_expr)
+      return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
+    }
     if (canBeArrow && !this.canInsertSemicolon()) {
       if (this.eat(tt.arrow))
-        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false)
-      if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name && !containsEsc) {
-        id = this.parseIdent()
+        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit)
+      if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name && !containsEsc &&
+          (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
+        id = this.parseIdent(false)
         if (this.canInsertSemicolon() || !this.eat(tt.arrow))
           this.unexpected()
-        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
+        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
       }
     }
     return id
@@ -411,7 +506,7 @@ pp.parseExprAtom = function(refDestructuringErrors) {
     return this.finishNode(node, "Literal")
 
   case tt.parenL:
-    let start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow)
+    let start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit)
     if (refDestructuringErrors) {
       if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
         refDestructuringErrors.parenthesizedAssign = start
@@ -427,6 +522,7 @@ pp.parseExprAtom = function(refDestructuringErrors) {
     return this.finishNode(node, "ArrayExpression")
 
   case tt.braceL:
+    this.overrideContext(tokenCtxTypes.b_expr)
     return this.parseObj(false, refDestructuringErrors)
 
   case tt._function:
@@ -443,15 +539,77 @@ pp.parseExprAtom = function(refDestructuringErrors) {
   case tt.backQuote:
     return this.parseTemplate()
 
+  case tt._import:
+    if (this.options.ecmaVersion >= 11) {
+      return this.parseExprImport()
+    } else {
+      return this.unexpected()
+    }
+
   default:
     return this.parseIdent(true) // Nick this.unexpected()
   }
 }
 
+pp.parseExprImport = function() {
+  const node = this.startNode()
+
+  // Consume `import` as an identifier for `import.meta`.
+  // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
+  if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword import")
+  const meta = this.parseIdent(true)
+
+  switch (this.type) {
+  case tt.parenL:
+    return this.parseDynamicImport(node)
+  case tt.dot:
+    node.meta = meta
+    return this.parseImportMeta(node)
+  default:
+    this.unexpected()
+  }
+}
+
+pp.parseDynamicImport = function(node) {
+  this.next() // skip `(`
+
+  // Parse node.source.
+  node.source = this.parseMaybeAssign()
+
+  // Verify ending.
+  if (!this.eat(tt.parenR)) {
+    const errorPos = this.start
+    if (this.eat(tt.comma) && this.eat(tt.parenR)) {
+      this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()")
+    } else {
+      this.unexpected(errorPos)
+    }
+  }
+
+  return this.finishNode(node, "ImportExpression")
+}
+
+pp.parseImportMeta = function(node) {
+  this.next() // skip `.`
+
+  const containsEsc = this.containsEsc
+  node.property = this.parseIdent(true)
+
+  if (node.property.name !== "meta")
+    this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'")
+  if (containsEsc)
+    this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters")
+  if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
+    this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module")
+
+  return this.finishNode(node, "MetaProperty")
+}
+
 pp.parseLiteral = function(value) {
   let node = this.startNode()
   node.value = value
   node.raw = this.input.slice(this.start, this.end)
+  if (node.raw.charCodeAt(node.raw.length - 1) === 110) node.bigint = node.raw.slice(0, -1).replace(/_/g, "")
   this.next()
   return this.finishNode(node, "Literal")
 }
@@ -463,7 +621,7 @@ pp.parseParenExpression = function() {
   return val
 }
 
-pp.parseParenAndDistinguishExpression = function(canBeArrow) {
+pp.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
   let startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8
   if (this.options.ecmaVersion >= 6) {
     this.next()
@@ -473,6 +631,7 @@ pp.parseParenAndDistinguishExpression = function(canBeArrow) {
     let refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart
     this.yieldPos = 0
     this.awaitPos = 0
+    // Do not save awaitIdentPos to allow checking awaits nested in parameters
     while (this.type !== tt.parenR) {
       first ? first = false : this.expect(tt.comma)
       if (allowTrailingComma && this.afterTrailingComma(tt.parenR, true)) {
@@ -487,7 +646,7 @@ pp.parseParenAndDistinguishExpression = function(canBeArrow) {
         exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem))
       }
     }
-    let innerEndPos = this.start, innerEndLoc = this.startLoc
+    let innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc
     this.expect(tt.parenR)
 
     if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
@@ -495,7 +654,7 @@ pp.parseParenAndDistinguishExpression = function(canBeArrow) {
       this.checkYieldAwaitInDefaultParams()
       this.yieldPos = oldYieldPos
       this.awaitPos = oldAwaitPos
-      return this.parseParenArrowList(startPos, startLoc, exprList)
+      return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
     }
 
     if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart)
@@ -528,8 +687,8 @@ pp.parseParenItem = function(item) {
   return item
 }
 
-pp.parseParenArrowList = function(startPos, startLoc, exprList) {
-  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
+pp.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
+  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
 }
 
 // New's precedence is slightly tricky. It must allow its argument to
@@ -541,20 +700,26 @@ pp.parseParenArrowList = function(startPos, startLoc, exprList) {
 const empty = []
 
 pp.parseNew = function() {
+  if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword new")
   let node = this.startNode()
   let meta = this.parseIdent(true)
   if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
     node.meta = meta
     let containsEsc = this.containsEsc
     node.property = this.parseIdent(true)
-    if (node.property.name !== "target" || containsEsc)
-      this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target")
-    if (!this.inNonArrowFunction())
-      this.raiseRecoverable(node.start, "new.target can only be used in functions")
+    if (node.property.name !== "target")
+      this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'")
+    if (containsEsc)
+      this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters")
+    if (!this.allowNewDotTarget)
+      this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block")
     return this.finishNode(node, "MetaProperty")
   }
-  let startPos = this.start, startLoc = this.startLoc
-  node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true)
+  let startPos = this.start, startLoc = this.startLoc, isImport = this.type === tt._import
+  node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false)
+  if (isImport && node.callee.type === "ImportExpression") {
+    this.raise(startPos, "Cannot use new with import()")
+  }
   if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false)
   else node.arguments = empty
   return this.finishNode(node, "NewExpression")
@@ -615,7 +780,7 @@ pp.parseObj = function(isPattern, refDestructuringErrors) {
   while (!this.eat(tt.braceR)) {
     if (!first) {
       this.expect(tt.comma)
-      if (this.afterTrailingComma(tt.braceR)) break
+      if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(tt.braceR)) break
     } else first = false
 
     const prop = this.parseProperty(isPattern, refDestructuringErrors)
@@ -691,7 +856,7 @@ pp.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos
   } else if (!isPattern && !containsEsc &&
              this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
              (prop.key.name === "get" || prop.key.name === "set") &&
-             (this.type !== tt.comma && this.type !== tt.braceR)) {
+             (this.type !== tt.comma && this.type !== tt.braceR && this.type !== tt.eq)) {
     if (isGenerator || isAsync) this.unexpected()
     prop.kind = prop.key.name
     this.parsePropertyName(prop)
@@ -708,16 +873,19 @@ pp.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos
         this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params")
     }
   } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
+    if (isGenerator || isAsync) this.unexpected()
     this.checkUnreserved(prop.key)
+    if (prop.key.name === "await" && !this.awaitIdentPos)
+      this.awaitIdentPos = startPos
     prop.kind = "init"
     if (isPattern) {
-      prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
+      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key))
     } else if (this.type === tt.eq && refDestructuringErrors) {
       if (refDestructuringErrors.shorthandAssign < 0)
         refDestructuringErrors.shorthandAssign = this.start
-      prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
+      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key))
     } else {
-      prop.value = prop.key
+      prop.value = this.copyNode(prop.key)
     }
     prop.shorthand = true
   } else this.unexpected()
@@ -734,7 +902,7 @@ pp.parsePropertyName = function(prop) {
       prop.computed = false
     }
   }
-  return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true)
+  return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
 }
 
 // Initialize empty function node.
@@ -748,7 +916,7 @@ pp.initFunction = function(node) {
 // Parse object or class method.
 
 pp.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
-  let node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos
+  let node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos
 
   this.initFunction(node)
   if (this.options.ecmaVersion >= 6)
@@ -758,22 +926,24 @@ pp.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
 
   this.yieldPos = 0
   this.awaitPos = 0
+  this.awaitIdentPos = 0
   this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0))
 
   this.expect(tt.parenL)
   node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8)
   this.checkYieldAwaitInDefaultParams()
-  this.parseFunctionBody(node, false)
+  this.parseFunctionBody(node, false, true, false)
 
   this.yieldPos = oldYieldPos
   this.awaitPos = oldAwaitPos
+  this.awaitIdentPos = oldAwaitIdentPos
   return this.finishNode(node, "FunctionExpression")
 }
 
 // Parse arrow function expression with given parameters.
 
-pp.parseArrowExpression = function(node, params, isAsync) {
-  let oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos
+pp.parseArrowExpression = function(node, params, isAsync, forInit) {
+  let oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos
 
   this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW)
   this.initFunction(node)
@@ -781,23 +951,25 @@ pp.parseArrowExpression = function(node, params, isAsync) {
 
   this.yieldPos = 0
   this.awaitPos = 0
+  this.awaitIdentPos = 0
 
   node.params = this.toAssignableList(params, true)
-  this.parseFunctionBody(node, true)
+  this.parseFunctionBody(node, true, false, forInit)
 
   this.yieldPos = oldYieldPos
   this.awaitPos = oldAwaitPos
+  this.awaitIdentPos = oldAwaitIdentPos
   return this.finishNode(node, "ArrowFunctionExpression")
 }
 
 // Parse function body and check parameters.
 
-pp.parseFunctionBody = function(node, isArrowFunction) {
+pp.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
   let isExpression = isArrowFunction && this.type !== tt.braceL
   let oldStrict = this.strict, useStrict = false
 
   if (isExpression) {
-    node.body = this.parseMaybeAssign()
+    node.body = this.parseMaybeAssign(forInit)
     node.expression = true
     this.checkParams(node, false)
   } else {
@@ -818,17 +990,15 @@ pp.parseFunctionBody = function(node, isArrowFunction) {
 
     // Add the params to varDeclaredNames to ensure that an error is thrown
     // if a let/const declaration in the function clashes with one of the params.
-    this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params))
-    node.body = this.parseBlock(false)
+    this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params))
+    // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
+    if (this.strict && node.id) this.checkLValSimple(node.id, BIND_OUTSIDE)
+    node.body = this.parseBlock(false, undefined, useStrict && !oldStrict)
     node.expression = false
     this.adaptDirectivePrologue(node.body.body)
     this.labels = oldLabels
   }
   this.exitScope()
-
-  // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
-  if (this.strict && node.id) this.checkLVal(node.id, BIND_OUTSIDE)
-  this.strict = oldStrict
 }
 
 pp.isSimpleParamList = function(params) {
@@ -841,9 +1011,9 @@ pp.isSimpleParamList = function(params) {
 // or "arguments" and duplicate parameters.
 
 pp.checkParams = function(node, allowDuplicates) {
-  let nameHash = {}
+  let nameHash = Object.create(null)
   for (let param of node.params)
-    this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash)
+    this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash)
 }
 
 // Parses a comma-separated list of expressions, and returns them as
@@ -877,9 +1047,13 @@ pp.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructur
 
 pp.checkUnreserved = function({start, end, name}) {
   if (this.inGenerator && name === "yield")
-    this.raiseRecoverable(start, "Can not use 'yield' as identifier inside a generator")
+    this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator")
   if (this.inAsync && name === "await")
-    this.raiseRecoverable(start, "Can not use 'await' as identifier inside an async function")
+    this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function")
+  if (this.currentThisScope().inClassFieldInit && name === "arguments")
+    this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer")
+  if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
+    this.raise(start, `Cannot use ${name} in class static initialization block`)
   if (this.keywords.test(name))
     this.raise(start, `Unexpected keyword '${name}'`)
   if (this.options.ecmaVersion < 6 &&
@@ -887,7 +1061,7 @@ pp.checkUnreserved = function({start, end, name}) {
   const re = this.strict ? this.reservedWordsStrict : this.reservedWords
   if (re.test(name)) {
     if (!this.inAsync && name === "await")
-      this.raiseRecoverable(start, "Can not use keyword 'await' outside an async function")
+      this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function")
     this.raiseRecoverable(start, `The keyword '${name}' is reserved`)
   }
 }
@@ -898,7 +1072,6 @@ pp.checkUnreserved = function({start, end, name}) {
 
 pp.parseIdent = function(liberal, isBinding) {
   let node = this.startNode()
-  if (liberal && this.options.allowReserved === "never") liberal = false
   if (this.type === tt.name) {
     node.name = this.value
   } else if (this.type.keyword) {
@@ -915,15 +1088,39 @@ pp.parseIdent = function(liberal, isBinding) {
   } else {
     this.unexpected()
   }
-  this.next()
+  this.next(!!liberal)
   this.finishNode(node, "Identifier")
-  if (!liberal) this.checkUnreserved(node)
+  if (!liberal) {
+    this.checkUnreserved(node)
+    if (node.name === "await" && !this.awaitIdentPos)
+      this.awaitIdentPos = node.start
+  }
+  return node
+}
+
+pp.parsePrivateIdent = function() {
+  const node = this.startNode()
+  if (this.type === tt.privateId) {
+    node.name = this.value
+  } else {
+    this.unexpected()
+  }
+  this.next()
+  this.finishNode(node, "PrivateIdentifier")
+
+  // For validating existence
+  if (this.privateNameStack.length === 0) {
+    this.raise(node.start, `Private field '#${node.name}' must be declared in an enclosing class`)
+  } else {
+    this.privateNameStack[this.privateNameStack.length - 1].used.push(node)
+  }
+
   return node
 }
 
 // Parses yield expression inside generator.
 
-pp.parseYield = function() {
+pp.parseYield = function(forInit) {
   if (!this.yieldPos) this.yieldPos = this.start
 
   let node = this.startNode()
@@ -933,16 +1130,16 @@ pp.parseYield = function() {
     node.argument = null
   } else {
     node.delegate = this.eat(tt.star)
-    node.argument = this.parseMaybeAssign()
+    node.argument = this.parseMaybeAssign(forInit)
   }
   return this.finishNode(node, "YieldExpression")
 }
 
-pp.parseAwait = function() {
+pp.parseAwait = function(forInit) {
   if (!this.awaitPos) this.awaitPos = this.start
 
   let node = this.startNode()
   this.next()
-  node.argument = this.parseMaybeUnary(null, true)
+  node.argument = this.parseMaybeUnary(null, true, false, forInit)
   return this.finishNode(node, "AwaitExpression")
 }
index 2e6464d..fdcdc18 100644 (file)
@@ -14,6 +14,7 @@ const ecma5AndLessKeywords = "break case catch continue debugger default do else
 
 export const keywords = {
   5: ecma5AndLessKeywords,
+  "5module": ecma5AndLessKeywords + " export import",
   6: ecma5AndLessKeywords + " const class extends export import super"
 }
 
@@ -26,9 +27,8 @@ export const keywordRelationalOperator = /^in(stanceof)?$/
 // are only applied when a character is found to actually have a
 // code point above 128.
 // Generated by `bin/generate-identifier-regex.js`.
-
-let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"
-let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"
+let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"
+let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"
 
 const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]")
 const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]")
@@ -42,10 +42,10 @@ nonASCIIidentifierStartChars = nonASCIIidentifierChars = null
 // generated by bin/generate-identifier-regex.js
 
 // eslint-disable-next-line comma-spacing
-const astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,477,28,11,0,9,21,190,52,76,44,33,24,27,35,30,0,12,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,26,230,43,117,63,32,0,257,0,11,39,8,0,22,0,12,39,3,3,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,270,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,68,12,0,67,12,65,1,31,6129,15,754,9486,286,82,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541]
+const astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,68,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2637,96,16,1070,4050,582,8634,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8936,3,2,6,2,1,2,290,46,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,482,44,11,6,17,0,322,29,19,43,1269,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4152,8,221,3,5761,15,7472,3104,541,1507,4938]
 
 // eslint-disable-next-line comma-spacing
-const astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,525,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,4,9,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,280,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239]
+const astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,87,9,39,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,4706,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,357,0,62,13,1495,6,110,6,6,9,4759,9,787719,239]
 
 // This has a complexity linear to the value of the code. The
 // assumption is that looking up astral identifier characters is
index 9c3ba6e..a988960 100644 (file)
 //
 // [walk]: util/walk.js
 
-import {Parser} from "./state"
-import "./parseutil"
-import "./statement"
-import "./lval"
-import "./expression"
-import "./location"
-import "./scope"
-
-export {Parser} from "./state"
-export {defaultOptions} from "./options"
-export {Position, SourceLocation, getLineInfo} from "./locutil"
-export {Node} from "./node"
-export {TokenType, types as tokTypes, keywords as keywordTypes} from "./tokentype"
-export {TokContext, types as tokContexts} from "./tokencontext"
-export {isIdentifierChar, isIdentifierStart} from "./identifier"
-export {Token} from "./tokenize"
-export {isNewLine, lineBreak, lineBreakG, nonASCIIwhitespace} from "./whitespace"
-
-export const version = "6.0.2"
+import {Parser} from "./state.js"
+import "./parseutil.js"
+import "./statement.js"
+import "./lval.js"
+import "./expression.js"
+import "./location.js"
+import "./scope.js"
+
+import {defaultOptions} from "./options.js"
+import {Position, SourceLocation, getLineInfo} from "./locutil.js"
+import {Node} from "./node.js"
+import {TokenType, types as tokTypes, keywords as keywordTypes} from "./tokentype.js"
+import {TokContext, types as tokContexts} from "./tokencontext.js"
+import {isIdentifierChar, isIdentifierStart} from "./identifier.js"
+import {Token} from "./tokenize.js"
+import {isNewLine, lineBreak, lineBreakG, nonASCIIwhitespace} from "./whitespace.js"
+
+export const version = "8.7.0"
+export {
+  Parser,
+  defaultOptions,
+  Position,
+  SourceLocation,
+  getLineInfo,
+  Node,
+  TokenType,
+  tokTypes,
+  keywordTypes,
+  TokContext,
+  tokContexts,
+  isIdentifierChar,
+  isIdentifierStart,
+  Token,
+  isNewLine,
+  lineBreak,
+  lineBreakG,
+  nonASCIIwhitespace
+}
+
+Parser.acorn = {
+  Parser,
+  version,
+  defaultOptions,
+  Position,
+  SourceLocation,
+  getLineInfo,
+  Node,
+  TokenType,
+  tokTypes,
+  keywordTypes,
+  TokContext,
+  tokContexts,
+  isIdentifierChar,
+  isIdentifierStart,
+  Token,
+  isNewLine,
+  lineBreak,
+  lineBreakG,
+  nonASCIIwhitespace
+}
 
 // The main exported interface (under `self.acorn` when in the
 // browser) is a `parse` function that takes a code string and
index 99e7123..a7a2d6c 100644 (file)
@@ -1,5 +1,5 @@
-import {Parser} from "./state"
-import {Position, getLineInfo} from "./locutil"
+import {Parser} from "./state.js"
+import {Position, getLineInfo} from "./locutil.js"
 
 const pp = Parser.prototype
 
index 5a9465e..b6dc773 100644 (file)
@@ -1,4 +1,4 @@
-import {lineBreakG} from "./whitespace"
+import {nextLineBreak} from "./whitespace.js"
 
 // These are used when `options.locations` is on, for the
 // `startLoc` and `endLoc` properties.
@@ -30,13 +30,9 @@ export class SourceLocation {
 
 export function getLineInfo(input, offset) {
   for (let line = 1, cur = 0;;) {
-    lineBreakG.lastIndex = cur
-    let match = lineBreakG.exec(input)
-    if (match && match.index < offset) {
-      ++line
-      cur = match.index + match[0].length
-    } else {
-      return new Position(line, offset - cur)
-    }
+    let nextBreak = nextLineBreak(input, cur, offset)
+    if (nextBreak < 0) return new Position(line, offset - cur)
+    ++line
+    cur = nextBreak
   }
 }
index e5ba610..d68a35f 100644 (file)
@@ -1,7 +1,7 @@
-import {types as tt} from "./tokentype"
-import {Parser} from "./state"
-import {has} from "./util"
-import {BIND_NONE, BIND_OUTSIDE} from "./scopeflags"
+import {types as tt} from "./tokentype.js"
+import {Parser} from "./state.js"
+import {hasOwn} from "./util.js"
+import {BIND_NONE, BIND_OUTSIDE, BIND_LEXICAL} from "./scopeflags.js"
 
 const pp = Parser.prototype
 
@@ -13,11 +13,12 @@ pp.toAssignable = function(node, isBinding, refDestructuringErrors) {
     switch (node.type) {
     case "Identifier":
       if (this.inAsync && node.name === "await")
-        this.raise(node.start, "Can not use 'await' as identifier inside an async function")
+        this.raise(node.start, "Cannot use 'await' as identifier inside an async function")
       break
 
     case "ObjectPattern":
     case "ArrayPattern":
+    case "AssignmentPattern":
     case "RestElement":
       break
 
@@ -64,13 +65,14 @@ pp.toAssignable = function(node, isBinding, refDestructuringErrors) {
       node.type = "AssignmentPattern"
       delete node.operator
       this.toAssignable(node.left, isBinding)
-      // falls through to AssignmentPattern
-
-    case "AssignmentPattern":
       break
 
     case "ParenthesizedExpression":
-      this.toAssignable(node.expression, isBinding)
+      this.toAssignable(node.expression, isBinding, refDestructuringErrors)
+      break
+
+    case "ChainExpression":
+      this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side")
       break
 
     case "MemberExpression":
@@ -192,60 +194,103 @@ pp.parseMaybeDefault = function(startPos, startLoc, left) {
   return this.finishNode(node, "AssignmentPattern")
 }
 
-// Verify that a node is an lval â€” something that can be assigned
-// to.
-// bindingType can be either:
-// 'var' indicating that the lval creates a 'var' binding
-// 'let' indicating that the lval creates a lexical ('let' or 'const') binding
-// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
+// The following three functions all verify that a node is an lvalue â€”
+// something that can be bound, or assigned to. In order to do so, they perform
+// a variety of checks:
+//
+// - Check that none of the bound/assigned-to identifiers are reserved words.
+// - Record name declarations for bindings in the appropriate scope.
+// - Check duplicate argument names, if checkClashes is set.
+//
+// If a complex binding pattern is encountered (e.g., object and array
+// destructuring), the entire pattern is recursively checked.
+//
+// There are three versions of checkLVal*() appropriate for different
+// circumstances:
+//
+// - checkLValSimple() shall be used if the syntactic construct supports
+//   nothing other than identifiers and member expressions. Parenthesized
+//   expressions are also correctly handled. This is generally appropriate for
+//   constructs for which the spec says
+//
+//   > It is a Syntax Error if AssignmentTargetType of [the production] is not
+//   > simple.
+//
+//   It is also appropriate for checking if an identifier is valid and not
+//   defined elsewhere, like import declarations or function/class identifiers.
+//
+//   Examples where this is used include:
+//     a += â€¦;
+//     import a from '…';
+//   where a is the node to be checked.
+//
+// - checkLValPattern() shall be used if the syntactic construct supports
+//   anything checkLValSimple() supports, as well as object and array
+//   destructuring patterns. This is generally appropriate for constructs for
+//   which the spec says
+//
+//   > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
+//   > an ArrayLiteral and AssignmentTargetType of [the production] is not
+//   > simple.
+//
+//   Examples where this is used include:
+//     (a = â€¦);
+//     const a = â€¦;
+//     try { â€¦ } catch (a) { â€¦ }
+//   where a is the node to be checked.
+//
+// - checkLValInnerPattern() shall be used if the syntactic construct supports
+//   anything checkLValPattern() supports, as well as default assignment
+//   patterns, rest elements, and other constructs that may appear within an
+//   object or array destructuring pattern.
+//
+//   As a special case, function parameters also use checkLValInnerPattern(),
+//   as they also support defaults and rest constructs.
+//
+// These functions deliberately support both assignment and binding constructs,
+// as the logic for both is exceedingly similar. If the node is the target of
+// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
+// should be set to the appropriate BIND_* constant, like BIND_VAR or
+// BIND_LEXICAL.
+//
+// If the function is called with a non-BIND_NONE bindingType, then
+// additionally a checkClashes object may be specified to allow checking for
+// duplicate argument names. checkClashes is ignored if the provided construct
+// is an assignment (i.e., bindingType is BIND_NONE).
+
+pp.checkLValSimple = function(expr, bindingType = BIND_NONE, checkClashes) {
+  const isBind = bindingType !== BIND_NONE
 
-pp.checkLVal = function(expr, bindingType = BIND_NONE, checkClashes) {
   switch (expr.type) {
   case "Identifier":
     if (this.strict && this.reservedWordsStrictBind.test(expr.name))
-      this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode")
-    if (checkClashes) {
-      if (has(checkClashes, expr.name))
-        this.raiseRecoverable(expr.start, "Argument name clash")
-      checkClashes[expr.name] = true
-    }
-    if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) this.declareName(expr.name, bindingType, expr.start)
-    break
-
-  case "MemberExpression":
-    if (bindingType) this.raiseRecoverable(expr.start, "Binding member expression")
-    break
-
-  case "ObjectPattern":
-    for (let prop of expr.properties)
-      this.checkLVal(prop, bindingType, checkClashes)
-    break
-
-  case "Property":
-    // AssignmentProperty has type === "Property"
-    this.checkLVal(expr.value, bindingType, checkClashes)
-    break
-
-  case "ArrayPattern":
-    for (let elem of expr.elements) {
-      if (elem) this.checkLVal(elem, bindingType, checkClashes)
+      this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode")
+    if (isBind) {
+      if (bindingType === BIND_LEXICAL && expr.name === "let")
+        this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name")
+      if (checkClashes) {
+        if (hasOwn(checkClashes, expr.name))
+          this.raiseRecoverable(expr.start, "Argument name clash")
+        checkClashes[expr.name] = true
+      }
+      if (bindingType !== BIND_OUTSIDE) this.declareName(expr.name, bindingType, expr.start)
     }
     break
 
-  case "AssignmentPattern":
-    this.checkLVal(expr.left, bindingType, checkClashes)
+  case "ChainExpression":
+    this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side")
     break
 
-  case "RestElement":
-    this.checkLVal(expr.argument, bindingType, checkClashes)
+  case "MemberExpression":
+    if (isBind) this.raiseRecoverable(expr.start, "Binding member expression")
     break
 
   case "ParenthesizedExpression":
-    this.checkLVal(expr.expression, bindingType, checkClashes)
-    break
+    if (isBind) this.raiseRecoverable(expr.start, "Binding parenthesized expression")
+    return this.checkLValSimple(expr.expression, bindingType, checkClashes)
 
   default:
-    this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue")
+    this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue")
 
   case "BinaryExpression": // Nick
   case "Literal": // Nick
@@ -257,7 +302,46 @@ pp.checkLVal = function(expr, bindingType = BIND_NONE, checkClashes) {
     )
       temp = temp.left
     if (temp.type !== "Identifier" && temp.type !== "Literal")
-      this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue")
+      this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue")
+    break
+  }
+}
+
+pp.checkLValPattern = function(expr, bindingType = BIND_NONE, checkClashes) {
+  switch (expr.type) {
+  case "ObjectPattern":
+    for (let prop of expr.properties) {
+      this.checkLValInnerPattern(prop, bindingType, checkClashes)
+    }
+    break
+
+  case "ArrayPattern":
+    for (let elem of expr.elements) {
+      if (elem) this.checkLValInnerPattern(elem, bindingType, checkClashes)
+    }
     break
+
+  default:
+    this.checkLValSimple(expr, bindingType, checkClashes)
+  }
+}
+
+pp.checkLValInnerPattern = function(expr, bindingType = BIND_NONE, checkClashes) {
+  switch (expr.type) {
+  case "Property":
+    // AssignmentProperty has type === "Property"
+    this.checkLValInnerPattern(expr.value, bindingType, checkClashes)
+    break
+
+  case "AssignmentPattern":
+    this.checkLValPattern(expr.left, bindingType, checkClashes)
+    break
+
+  case "RestElement":
+    this.checkLValPattern(expr.argument, bindingType, checkClashes)
+    break
+
+  default:
+    this.checkLValPattern(expr, bindingType, checkClashes)
   }
 }
index 76b5b09..cdc5714 100644 (file)
@@ -1,5 +1,5 @@
-import {Parser} from "./state"
-import {SourceLocation} from "./locutil"
+import {Parser} from "./state.js"
+import {SourceLocation} from "./locutil.js"
 
 export class Node {
   constructor(parser, pos, loc) {
@@ -48,3 +48,9 @@ pp.finishNode = function(node, type) {
 pp.finishNodeAt = function(node, type, pos, loc) {
   return finishNodeAt.call(this, node, type, pos, loc)
 }
+
+pp.copyNode = function(node) {
+  let newNode = new Node(this, node.start, this.startLoc)
+  for (let prop in node) newNode[prop] = node[prop]
+  return newNode
+}
index e7fa9c5..8467c1c 100644 (file)
@@ -1,23 +1,24 @@
-import {has, isArray} from "./util"
-import {SourceLocation} from "./locutil"
+import {hasOwn, isArray} from "./util.js"
+import {SourceLocation} from "./locutil.js"
 
-// A second optional argument can be given to further configure
-// the parser process. These options are recognized:
+// A second argument must be given to configure the parser process.
+// These options are recognized (only `ecmaVersion` is required):
 
 export const defaultOptions = {
   // `ecmaVersion` indicates the ECMAScript version to parse. Must be
-  // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10
-  // (2019). This influences support for strict mode, the set of
-  // reserved words, and support for new syntax features. The default
-  // is 9.
-  ecmaVersion: 9,
+  // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
+  // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
+  // latest version the library supports). This influences support
+  // for strict mode, the set of reserved words, and support for
+  // new syntax features.
+  ecmaVersion: null,
   // `sourceType` indicates the mode the code should be parsed in.
   // Can be either `"script"` or `"module"`. This influences global
   // strict mode and parsing of `import` and `export` declarations.
   sourceType: "script",
   // `onInsertedSemicolon` can be a callback that will be called
   // when a semicolon is automatically inserted. It will be passed
-  // th position of the comma as an offset, and if `locations` is
+  // the position of the comma as an offset, and if `locations` is
   // enabled, it is given the location as a `{line, column}` object
   // as second argument.
   onInsertedSemicolon: null,
@@ -33,11 +34,16 @@ export const defaultOptions = {
   // error.
   allowReturnOutsideFunction: false,
   // When enabled, import/export statements are not constrained to
-  // appearing at the top of the program.
+  // appearing at the top of the program, and an import.meta expression
+  // in a script isn't considered an error.
   allowImportExportEverywhere: false,
+  // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
   // When enabled, await identifiers are allowed to appear at the top-level scope,
   // but they are still not allowed in non-async functions.
-  allowAwaitOutsideFunction: false,
+  allowAwaitOutsideFunction: null,
+  // When enabled, super identifiers are not constrained to
+  // appearing in methods and do not raise an error when they appear elsewhere.
+  allowSuperOutsideMethod: null,
   // When enabled, hashbang directive in the beginning of file
   // is allowed and treated as a line comment.
   allowHashBang: false,
@@ -91,14 +97,25 @@ export const defaultOptions = {
 
 // Interpret and default an options object
 
+let warnedAboutEcmaVersion = false
+
 export function getOptions(opts) {
   let options = {}
 
   for (let opt in defaultOptions)
-    options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]
+    options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]
 
-  if (options.ecmaVersion >= 2015)
+  if (options.ecmaVersion === "latest") {
+    options.ecmaVersion = 1e8
+  } else if (options.ecmaVersion == null) {
+    if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
+      warnedAboutEcmaVersion = true
+      console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")
+    }
+    options.ecmaVersion = 11
+  } else if (options.ecmaVersion >= 2015) {
     options.ecmaVersion -= 2009
+  }
 
   if (options.allowReserved == null)
     options.allowReserved = options.ecmaVersion < 5
diff --git a/src/package.json b/src/package.json
new file mode 100644 (file)
index 0000000..3dbc1ca
--- /dev/null
@@ -0,0 +1,3 @@
+{
+  "type": "module"
+}
index 0409cb9..22d7d54 100644 (file)
@@ -1,20 +1,34 @@
-import {types as tt} from "./tokentype"
-import {Parser} from "./state"
-import {lineBreak, skipWhiteSpace} from "./whitespace"
+import {types as tt} from "./tokentype.js"
+import {Parser} from "./state.js"
+import {lineBreak, skipWhiteSpace} from "./whitespace.js"
 
 const pp = Parser.prototype
 
 // ## Parser utilities
 
-const literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/
+const literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/
 pp.strictDirective = function(start) {
   for (;;) {
+    // Try to find string literal.
     skipWhiteSpace.lastIndex = start
     start += skipWhiteSpace.exec(this.input)[0].length
     let match = literal.exec(this.input.slice(start))
     if (!match) return false
-    if ((match[1] || match[2]) === "use strict") return true
+    if ((match[1] || match[2]) === "use strict") {
+      skipWhiteSpace.lastIndex = start + match[0].length
+      let spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length
+      let next = this.input.charAt(end)
+      return next === ";" || next === "}" ||
+        (lineBreak.test(spaceAfter[0]) &&
+         !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
+    }
     start += match[0].length
+
+    // Skip semicolon, if any.
+    skipWhiteSpace.lastIndex = start
+    start += skipWhiteSpace.exec(this.input)[0].length
+    if (this.input[start] === ";")
+      start++
   }
 }
 
index c18ee6d..37cc75b 100644 (file)
@@ -1,13 +1,15 @@
 import {isIdentifierStart, isIdentifierChar} from "./identifier.js"
 import {Parser} from "./state.js"
 import UNICODE_PROPERTY_VALUES from "./unicode-property-data.js"
+import {hasOwn} from "./util.js"
 
 const pp = Parser.prototype
 
 export class RegExpValidationState {
   constructor(parser) {
     this.parser = parser
-    this.validFlags = `gim${parser.options.ecmaVersion >= 6 ? "uy" : ""}${parser.options.ecmaVersion >= 9 ? "s" : ""}`
+    this.validFlags = `gim${parser.options.ecmaVersion >= 6 ? "uy" : ""}${parser.options.ecmaVersion >= 9 ? "s" : ""}${parser.options.ecmaVersion >= 13 ? "d" : ""}`
+    this.unicodeProperties = UNICODE_PROPERTY_VALUES[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion]
     this.source = ""
     this.flags = ""
     this.start = 0
@@ -38,47 +40,49 @@ export class RegExpValidationState {
 
   // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
   // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
-  at(i) {
+  at(i, forceU = false) {
     const s = this.source
     const l = s.length
     if (i >= l) {
       return -1
     }
     const c = s.charCodeAt(i)
-    if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
+    if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
       return c
     }
-    return (c << 10) + s.charCodeAt(i + 1) - 0x35FDC00
+    const next = s.charCodeAt(i + 1)
+    return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
   }
 
-  nextIndex(i) {
+  nextIndex(i, forceU = false) {
     const s = this.source
     const l = s.length
     if (i >= l) {
       return l
     }
-    const c = s.charCodeAt(i)
-    if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
+    let c = s.charCodeAt(i), next
+    if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
+        (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
       return i + 1
     }
     return i + 2
   }
 
-  current() {
-    return this.at(this.pos)
+  current(forceU = false) {
+    return this.at(this.pos, forceU)
   }
 
-  lookahead() {
-    return this.at(this.nextIndex(this.pos))
+  lookahead(forceU = false) {
+    return this.at(this.nextIndex(this.pos, forceU), forceU)
   }
 
-  advance() {
-    this.pos = this.nextIndex(this.pos)
+  advance(forceU = false) {
+    this.pos = this.nextIndex(this.pos, forceU)
   }
 
-  eat(ch) {
-    if (this.current() === ch) {
-      this.advance()
+  eat(ch, forceU = false) {
+    if (this.current(forceU) === ch) {
+      this.advance(forceU)
       return true
     }
     return false
@@ -150,7 +154,7 @@ pp.regexp_pattern = function(state) {
     if (state.eat(0x29 /* ) */)) {
       state.raise("Unmatched ')'")
     }
-    if (state.eat(0x5D /* [ */) || state.eat(0x7D /* } */)) {
+    if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
       state.raise("Lone quantifier brackets")
     }
   }
@@ -414,9 +418,9 @@ pp.regexp_eatExtendedPatternCharacter = function(state) {
   return false
 }
 
-// GroupSpecifier[U] ::
+// GroupSpecifier ::
 //   [empty]
-//   `?` GroupName[?U]
+//   `?` GroupName
 pp.regexp_groupSpecifier = function(state) {
   if (state.eat(0x3F /* ? */)) {
     if (this.regexp_eatGroupName(state)) {
@@ -430,8 +434,8 @@ pp.regexp_groupSpecifier = function(state) {
   }
 }
 
-// GroupName[U] ::
-//   `<` RegExpIdentifierName[?U] `>`
+// GroupName ::
+//   `<` RegExpIdentifierName `>`
 // Note: this updates `state.lastStringValue` property with the eaten name.
 pp.regexp_eatGroupName = function(state) {
   state.lastStringValue = ""
@@ -444,9 +448,9 @@ pp.regexp_eatGroupName = function(state) {
   return false
 }
 
-// RegExpIdentifierName[U] ::
-//   RegExpIdentifierStart[?U]
-//   RegExpIdentifierName[?U] RegExpIdentifierPart[?U]
+// RegExpIdentifierName ::
+//   RegExpIdentifierStart
+//   RegExpIdentifierName RegExpIdentifierPart
 // Note: this updates `state.lastStringValue` property with the eaten name.
 pp.regexp_eatRegExpIdentifierName = function(state) {
   state.lastStringValue = ""
@@ -460,17 +464,18 @@ pp.regexp_eatRegExpIdentifierName = function(state) {
   return false
 }
 
-// RegExpIdentifierStart[U] ::
+// RegExpIdentifierStart ::
 //   UnicodeIDStart
 //   `$`
 //   `_`
-//   `\` RegExpUnicodeEscapeSequence[?U]
+//   `\` RegExpUnicodeEscapeSequence[+U]
 pp.regexp_eatRegExpIdentifierStart = function(state) {
   const start = state.pos
-  let ch = state.current()
-  state.advance()
+  const forceU = this.options.ecmaVersion >= 11
+  let ch = state.current(forceU)
+  state.advance(forceU)
 
-  if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) {
+  if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
     ch = state.lastIntValue
   }
   if (isRegExpIdentifierStart(ch)) {
@@ -485,19 +490,20 @@ function isRegExpIdentifierStart(ch) {
   return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
 }
 
-// RegExpIdentifierPart[U] ::
+// RegExpIdentifierPart ::
 //   UnicodeIDContinue
 //   `$`
 //   `_`
-//   `\` RegExpUnicodeEscapeSequence[?U]
+//   `\` RegExpUnicodeEscapeSequence[+U]
 //   <ZWNJ>
 //   <ZWJ>
 pp.regexp_eatRegExpIdentifierPart = function(state) {
   const start = state.pos
-  let ch = state.current()
-  state.advance()
+  const forceU = this.options.ecmaVersion >= 11
+  let ch = state.current(forceU)
+  state.advance(forceU)
 
-  if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) {
+  if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
     ch = state.lastIntValue
   }
   if (isRegExpIdentifierPart(ch)) {
@@ -567,7 +573,7 @@ pp.regexp_eatCharacterEscape = function(state) {
     this.regexp_eatCControlLetter(state) ||
     this.regexp_eatZero(state) ||
     this.regexp_eatHexEscapeSequence(state) ||
-    this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
+    this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
     (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
     this.regexp_eatIdentityEscape(state)
   )
@@ -640,13 +646,14 @@ function isControlLetter(ch) {
 }
 
 // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
-pp.regexp_eatRegExpUnicodeEscapeSequence = function(state) {
+pp.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU = false) {
   const start = state.pos
+  const switchU = forceU || state.switchU
 
   if (state.eat(0x75 /* u */)) {
     if (this.regexp_eatFixedHexDigits(state, 4)) {
       const lead = state.lastIntValue
-      if (state.switchU && lead >= 0xD800 && lead <= 0xDBFF) {
+      if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
         const leadSurrogateEnd = state.pos
         if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
           const trail = state.lastIntValue
@@ -661,7 +668,7 @@ pp.regexp_eatRegExpUnicodeEscapeSequence = function(state) {
       return true
     }
     if (
-      state.switchU &&
+      switchU &&
       state.eat(0x7B /* { */) &&
       this.regexp_eatHexDigits(state) &&
       state.eat(0x7D /* } */) &&
@@ -669,7 +676,7 @@ pp.regexp_eatRegExpUnicodeEscapeSequence = function(state) {
     ) {
       return true
     }
-    if (state.switchU) {
+    if (switchU) {
       state.raise("Invalid unicode escape")
     }
     state.pos = start
@@ -784,14 +791,14 @@ pp.regexp_eatUnicodePropertyValueExpression = function(state) {
   return false
 }
 pp.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
-  if (!UNICODE_PROPERTY_VALUES.hasOwnProperty(name) || UNICODE_PROPERTY_VALUES[name].indexOf(value) === -1) {
+  if (!hasOwn(state.unicodeProperties.nonBinary, name))
     state.raise("Invalid property name")
-  }
+  if (!state.unicodeProperties.nonBinary[name].test(value))
+    state.raise("Invalid property value")
 }
 pp.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
-  if (UNICODE_PROPERTY_VALUES.$LONE.indexOf(nameOrValue) === -1) {
+  if (!state.unicodeProperties.binary.test(nameOrValue))
     state.raise("Invalid property name")
-  }
 }
 
 // UnicodePropertyName ::
@@ -835,7 +842,7 @@ pp.regexp_eatCharacterClass = function(state) {
   if (state.eat(0x5B /* [ */)) {
     state.eat(0x5E /* ^ */)
     this.regexp_classRanges(state)
-    if (state.eat(0x5D /* [ */)) {
+    if (state.eat(0x5D /* ] */)) {
       return true
     }
     // Unreachable since it threw "unterminated regular expression" error before.
@@ -883,7 +890,7 @@ pp.regexp_eatClassAtom = function(state) {
   }
 
   const ch = state.current()
-  if (ch !== 0x5D /* [ */) {
+  if (ch !== 0x5D /* ] */) {
     state.lastIntValue = ch
     state.advance()
     return true
index bcf34ec..0f06609 100644 (file)
@@ -1,5 +1,5 @@
-import {Parser} from "./state"
-import {SCOPE_VAR, SCOPE_ARROW, SCOPE_SIMPLE_CATCH, BIND_LEXICAL, BIND_SIMPLE_CATCH, BIND_FUNCTION} from "./scopeflags"
+import {Parser} from "./state.js"
+import {SCOPE_VAR, SCOPE_FUNCTION, SCOPE_TOP, SCOPE_ARROW, SCOPE_SIMPLE_CATCH, BIND_LEXICAL, BIND_SIMPLE_CATCH, BIND_FUNCTION} from "./scopeflags.js"
 
 const pp = Parser.prototype
 
@@ -10,6 +10,10 @@ class Scope {
     this.var = []
     // A list of lexically-declared names in the current lexical scope
     this.lexical = []
+    // A list of lexically-declared FunctionDeclaration names in the current lexical scope
+    this.functions = []
+    // A switch to disallow the identifier reference 'arguments'
+    this.inClassFieldInit = false
   }
 }
 
@@ -23,30 +27,56 @@ pp.exitScope = function() {
   this.scopeStack.pop()
 }
 
+// The spec says:
+// > At the top level of a function, or script, function declarations are
+// > treated like var declarations rather than like lexical declarations.
+pp.treatFunctionsAsVarInScope = function(scope) {
+  return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
+}
+
 pp.declareName = function(name, bindingType, pos) {
   let redeclared = false
   if (bindingType === BIND_LEXICAL) {
     const scope = this.currentScope()
-    redeclared = scope.lexical.indexOf(name) > -1 || scope.var.indexOf(name) > -1
+    redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1
     scope.lexical.push(name)
+    if (this.inModule && (scope.flags & SCOPE_TOP))
+      delete this.undefinedExports[name]
   } else if (bindingType === BIND_SIMPLE_CATCH) {
     const scope = this.currentScope()
     scope.lexical.push(name)
   } else if (bindingType === BIND_FUNCTION) {
     const scope = this.currentScope()
-    redeclared = scope.lexical.indexOf(name) > -1
-    scope.var.push(name)
+    if (this.treatFunctionsAsVar)
+      redeclared = scope.lexical.indexOf(name) > -1
+    else
+      redeclared = scope.lexical.indexOf(name) > -1 || scope.var.indexOf(name) > -1
+    scope.functions.push(name)
   } else {
     for (let i = this.scopeStack.length - 1; i >= 0; --i) {
       const scope = this.scopeStack[i]
-      if (scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH) && scope.lexical[0] === name) redeclared = true
+      if (scope.lexical.indexOf(name) > -1 && !((scope.flags & SCOPE_SIMPLE_CATCH) && scope.lexical[0] === name) ||
+          !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1) {
+        redeclared = true
+        break
+      }
       scope.var.push(name)
+      if (this.inModule && (scope.flags & SCOPE_TOP))
+        delete this.undefinedExports[name]
       if (scope.flags & SCOPE_VAR) break
     }
   }
   if (redeclared) this.raiseRecoverable(pos, `Identifier '${name}' has already been declared`)
 }
 
+pp.checkLocalExport = function(id) {
+  // scope.functions must be empty as Module code is always strict.
+  if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
+      this.scopeStack[0].var.indexOf(id.name) === -1) {
+    this.undefinedExports[id.name] = id
+  }
+}
+
 pp.currentScope = function() {
   return this.scopeStack[this.scopeStack.length - 1]
 }
index ccb16ec..4574e44 100644 (file)
@@ -2,19 +2,20 @@
 export const
     SCOPE_TOP = 1,
     SCOPE_FUNCTION = 2,
-    SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
     SCOPE_ASYNC = 4,
     SCOPE_GENERATOR = 8,
     SCOPE_ARROW = 16,
     SCOPE_SIMPLE_CATCH = 32,
     SCOPE_SUPER = 64,
-    SCOPE_DIRECT_SUPER = 128
+    SCOPE_DIRECT_SUPER = 128,
+    SCOPE_CLASS_STATIC_BLOCK = 256,
+    SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK
 
 export function functionFlags(async, generator) {
   return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
 }
 
-// Used in checkLVal and declareName to determine the type of a binding
+// Used in checkLVal* and declareName to determine the type of a binding
 export const
     BIND_NONE = 0, // Not a binding
     BIND_VAR = 1, // Var-style binding
index a838742..c2e4111 100644 (file)
@@ -1,28 +1,24 @@
-import {reservedWords, keywords} from "./identifier"
-import {types as tt} from "./tokentype"
-import {lineBreak} from "./whitespace"
-import {getOptions} from "./options"
-import {SCOPE_TOP, SCOPE_FUNCTION, SCOPE_ASYNC, SCOPE_GENERATOR, SCOPE_SUPER, SCOPE_DIRECT_SUPER} from "./scopeflags"
-
-function keywordRegexp(words) {
-  return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
-}
+import {reservedWords, keywords} from "./identifier.js"
+import {types as tt} from "./tokentype.js"
+import {lineBreak} from "./whitespace.js"
+import {getOptions} from "./options.js"
+import {wordsRegexp} from "./util.js"
+import {SCOPE_TOP, SCOPE_FUNCTION, SCOPE_ASYNC, SCOPE_GENERATOR, SCOPE_SUPER, SCOPE_DIRECT_SUPER, SCOPE_CLASS_STATIC_BLOCK} from "./scopeflags.js"
 
 export class Parser {
   constructor(options, input, startPos) {
     this.options = options = getOptions(options)
     this.sourceFile = options.sourceFile
-    this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5])
+    this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5])
     let reserved = ""
-    if (!options.allowReserved) {
-      for (let v = options.ecmaVersion;; v--)
-        if (reserved = reservedWords[v]) break
+    if (options.allowReserved !== true) {
+      reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]
       if (options.sourceType === "module") reserved += " await"
     }
-    this.reservedWords = keywordRegexp(reserved)
+    this.reservedWords = wordsRegexp(reserved)
     let reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict
-    this.reservedWordsStrict = keywordRegexp(reservedStrict)
-    this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind)
+    this.reservedWordsStrict = wordsRegexp(reservedStrict)
+    this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind)
     this.input = String(input)
 
     // Used to signal to callers of `readWord1` whether the word
@@ -69,11 +65,14 @@ export class Parser {
 
     // Used to signify the start of a potential arrow function
     this.potentialArrowAt = -1
+    this.potentialArrowInForAwait = false
 
     // Positions to delayed-check that yield/await does not exist in default parameters.
-    this.yieldPos = this.awaitPos = 0
+    this.yieldPos = this.awaitPos = this.awaitIdentPos = 0
     // Labels in scope.
     this.labels = []
+    // Thus-far undefined exports.
+    this.undefinedExports = Object.create(null)
 
     // If enabled, skip leading hashbang line.
     if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
@@ -85,6 +84,11 @@ export class Parser {
 
     // For RegExp validation
     this.regexpState = null
+
+    // The stack of private names.
+    // Each element has two properties: 'declared' and 'used'.
+    // When it exited from the outermost class definition, all used private names must be declared.
+    this.privateNameStack = []
   }
 
   parse() {
@@ -94,13 +98,37 @@ export class Parser {
   }
 
   get inFunction() { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }
-  get inGenerator() { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }
-  get inAsync() { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }
-  get allowSuper() { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }
+
+  get inGenerator() { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }
+
+  get inAsync() { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }
+
+  get canAwait() {
+    for (let i = this.scopeStack.length - 1; i >= 0; i--) {
+      let scope = this.scopeStack[i]
+      if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) return false
+      if (scope.flags & SCOPE_FUNCTION) return (scope.flags & SCOPE_ASYNC) > 0
+    }
+    return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
+  }
+
+  get allowSuper() {
+    const {flags, inClassFieldInit} = this.currentThisScope()
+    return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
+  }
+
   get allowDirectSuper() { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }
 
-  // Switch to a getter for 7.0.0.
-  inNonArrowFunction() { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }
+  get treatFunctionsAsVar() { return this.treatFunctionsAsVarInScope(this.currentScope()) }
+
+  get allowNewDotTarget() {
+    const {flags, inClassFieldInit} = this.currentThisScope()
+    return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
+  }
+
+  get inClassStaticBlock() {
+    return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
+  }
 
   static extend(...plugins) {
     let cls = this
index f5e65ef..3d11d18 100644 (file)
@@ -1,10 +1,10 @@
-import {types as tt} from "./tokentype"
-import {Parser} from "./state"
-import {lineBreak, skipWhiteSpace} from "./whitespace"
-import {isIdentifierStart, isIdentifierChar, keywordRelationalOperator} from "./identifier"
-import {has} from "./util"
-import {DestructuringErrors} from "./parseutil"
-import {functionFlags, SCOPE_SIMPLE_CATCH, BIND_SIMPLE_CATCH, BIND_LEXICAL, BIND_VAR, BIND_FUNCTION} from "./scopeflags"
+import {types as tt} from "./tokentype.js"
+import {Parser} from "./state.js"
+import {lineBreak, skipWhiteSpace} from "./whitespace.js"
+import {isIdentifierStart, isIdentifierChar, keywordRelationalOperator} from "./identifier.js"
+import {hasOwn, loneSurrogate} from "./util.js"
+import {DestructuringErrors} from "./parseutil.js"
+import {functionFlags, SCOPE_SIMPLE_CATCH, BIND_SIMPLE_CATCH, BIND_LEXICAL, BIND_VAR, BIND_FUNCTION, SCOPE_CLASS_STATIC_BLOCK, SCOPE_SUPER} from "./scopeflags.js"
 
 const pp = Parser.prototype
 
@@ -16,31 +16,40 @@ const pp = Parser.prototype
 // to its body instead of creating a new node.
 
 pp.parseTopLevel = function(node) {
-  let exports = {}
+  let exports = Object.create(null)
   if (!node.body) node.body = []
   while (this.type !== tt.eof) {
     let stmt = this.parseStatement(null, true, exports)
     node.body.push(stmt)
   }
+  if (this.inModule)
+    for (let name of Object.keys(this.undefinedExports))
+      this.raiseRecoverable(this.undefinedExports[name].start, `Export '${name}' is not defined`)
   this.adaptDirectivePrologue(node.body)
   this.next()
-  if (this.options.ecmaVersion >= 6) {
-    node.sourceType = this.options.sourceType
-  }
+  node.sourceType = this.options.sourceType
   return this.finishNode(node, "Program")
 }
 
 const loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}
 
-pp.isLet = function() {
+pp.isLet = function(context) {
   if (this.options.ecmaVersion < 6 || !this.isContextual("let")) return false
   skipWhiteSpace.lastIndex = this.pos
   let skip = skipWhiteSpace.exec(this.input)
   let next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next)
-  if (nextCh === 91 || nextCh === 123) return true // '{' and '['
+  // For ambiguous cases, determine if a LexicalDeclaration (or only a
+  // Statement) is allowed here. If context is not empty then only a Statement
+  // is allowed. However, `let [` is an explicit negative lookahead for
+  // ExpressionStatement, so special-case it first.
+  if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) return true // '[', '/', astral
+  if (context) return false
+
+  if (nextCh === 123) return true // '{'
   if (isIdentifierStart(nextCh, true)) {
     let pos = next + 1
-    while (isIdentifierChar(this.input.charCodeAt(pos), true)) ++pos
+    while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) ++pos
+    if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) return true
     let ident = this.input.slice(next, pos)
     if (!keywordRelationalOperator.test(ident)) return true
   }
@@ -56,10 +65,11 @@ pp.isAsyncFunction = function() {
 
   skipWhiteSpace.lastIndex = this.pos
   let skip = skipWhiteSpace.exec(this.input)
-  let next = this.pos + skip[0].length
+  let next = this.pos + skip[0].length, after
   return !lineBreak.test(this.input.slice(this.pos, next)) &&
     this.input.slice(next, next + 8) === "function" &&
-    (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
+    (next + 8 === this.input.length ||
+     !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
 }
 
 // Parse a single statement.
@@ -72,7 +82,7 @@ pp.isAsyncFunction = function() {
 pp.parseStatement = function(context, topLevel, exports) {
   let starttype = this.type, node = this.startNode(), kind
 
-  if (this.isLet()) {
+  if (this.isLet(context)) {
     starttype = tt._var
     kind = "let"
   }
@@ -87,7 +97,10 @@ pp.parseStatement = function(context, topLevel, exports) {
   case tt._do: return this.parseDoStatement(node)
   case tt._for: return this.parseForStatement(node)
   case tt._function:
-    if ((context && (this.strict || context !== "if")) && this.options.ecmaVersion >= 6) this.unexpected()
+    // Function as sole body of either an if statement or a labeled statement
+    // works, but not when it is part of a labeled statement that is the sole
+    // body of an if statement.
+    if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) this.unexpected()
     return this.parseFunctionStatement(node, false, !context)
   case tt._class:
     if (context) this.unexpected()
@@ -107,6 +120,14 @@ pp.parseStatement = function(context, topLevel, exports) {
   case tt.semi: return this.parseEmptyStatement(node)
   case tt._export:
   case tt._import:
+    if (this.options.ecmaVersion > 10 && starttype === tt._import) {
+      skipWhiteSpace.lastIndex = this.pos
+      let skip = skipWhiteSpace.exec(this.input)
+      let next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next)
+      if (nextCh === 40 || nextCh === 46) // '(' or '.'
+        return this.parseExpressionStatement(node, this.parseExpression())
+    }
+
     if (!this.options.allowImportExportEverywhere) {
       if (!topLevel)
         this.raise(this.start, "'import' and 'export' may only appear at the top level")
@@ -188,7 +209,7 @@ pp.parseDoStatement = function(node) {
 
 pp.parseForStatement = function(node) {
   this.next()
-  let awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1
+  let awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1
   this.labels.push(loopLabel)
   this.enterScope(0)
   this.expect(tt.parenL)
@@ -202,8 +223,7 @@ pp.parseForStatement = function(node) {
     this.next()
     this.parseVar(init, true, kind)
     this.finishNode(init, "VariableDeclaration")
-    if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init.declarations.length === 1 &&
-        !(kind !== "var" && init.declarations[0].init)) {
+    if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init.declarations.length === 1) {
       if (this.options.ecmaVersion >= 9) {
         if (this.type === tt._in) {
           if (awaitAt > -1) this.unexpected(awaitAt)
@@ -214,16 +234,18 @@ pp.parseForStatement = function(node) {
     if (awaitAt > -1) this.unexpected(awaitAt)
     return this.parseFor(node, init)
   }
+  let startsWithLet = this.isContextual("let"), isForOf = false
   let refDestructuringErrors = new DestructuringErrors
-  let init = this.parseExpression(true, refDestructuringErrors)
-  if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
+  let init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors)
+  if (this.type === tt._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
     if (this.options.ecmaVersion >= 9) {
       if (this.type === tt._in) {
         if (awaitAt > -1) this.unexpected(awaitAt)
       } else node.await = awaitAt > -1
     }
+    if (startsWithLet && isForOf) this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'.")
     this.toAssignable(init, false, refDestructuringErrors)
-    this.checkLVal(init)
+    this.checkLValPattern(init)
     return this.parseForIn(node, init)
   } else {
     this.checkExpressionErrors(refDestructuringErrors, true)
@@ -324,7 +346,7 @@ pp.parseTryStatement = function(node) {
       clause.param = this.parseBindingAtom()
       let simple = clause.param.type === "Identifier"
       this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0)
-      this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL)
+      this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL)
       this.expect(tt.parenR)
     } else {
       if (this.options.ecmaVersion < 10) this.unexpected()
@@ -384,11 +406,7 @@ pp.parseLabeledStatement = function(node, maybeName, expr, context) {
     } else break
   }
   this.labels.push({name: maybeName, kind, statementStart: this.start})
-  node.body = this.parseStatement(context)
-  if (node.body.type === "ClassDeclaration" ||
-      node.body.type === "VariableDeclaration" && node.body.kind !== "var" ||
-      node.body.type === "FunctionDeclaration" && (this.strict || node.body.generator || node.body.async))
-    this.raiseRecoverable(node.body.start, "Invalid labeled declaration")
+  node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label")
   this.labels.pop()
   node.label = expr
   return this.finishNode(node, "LabeledStatement")
@@ -404,14 +422,16 @@ pp.parseExpressionStatement = function(node, expr) {
 // strict"` declarations when `allowStrict` is true (used for
 // function bodies).
 
-pp.parseBlock = function(createNewLexicalScope = true, node = this.startNode()) {
+pp.parseBlock = function(createNewLexicalScope = true, node = this.startNode(), exitStrict) {
   node.body = []
   this.expect(tt.braceL)
   if (createNewLexicalScope) this.enterScope(0)
-  while (!this.eat(tt.braceR)) {
+  while (this.type !== tt.braceR) {
     let stmt = this.parseStatement(null)
     node.body.push(stmt)
   }
+  if (exitStrict) this.strict = false
+  this.next()
   if (createNewLexicalScope) this.exitScope()
   return this.finishNode(node, "BlockStatement")
 }
@@ -427,8 +447,8 @@ pp.parseFor = function(node, init) {
   this.expect(tt.semi)
   node.update = this.type === tt.parenR ? null : this.parseExpression()
   this.expect(tt.parenR)
-  this.exitScope()
   node.body = this.parseStatement("for")
+  this.exitScope()
   this.labels.pop()
   return this.finishNode(node, "ForStatement")
 }
@@ -437,21 +457,34 @@ pp.parseFor = function(node, init) {
 // same from parser's perspective.
 
 pp.parseForIn = function(node, init) {
-  let type = this.type === tt._in ? "ForInStatement" : "ForOfStatement"
+  const isForIn = this.type === tt._in
   this.next()
-  if (type === "ForInStatement") {
-    if (init.type === "AssignmentPattern" ||
-      (init.type === "VariableDeclaration" && init.declarations[0].init != null &&
-       (this.strict || init.declarations[0].id.type !== "Identifier")))
-      this.raise(init.start, "Invalid assignment in for-in loop head")
+
+  if (
+    init.type === "VariableDeclaration" &&
+    init.declarations[0].init != null &&
+    (
+      !isForIn ||
+      this.options.ecmaVersion < 8 ||
+      this.strict ||
+      init.kind !== "var" ||
+      init.declarations[0].id.type !== "Identifier"
+    )
+  ) {
+    this.raise(
+      init.start,
+      `${
+        isForIn ? "for-in" : "for-of"
+      } loop variable declaration may not have an initializer`
+    )
   }
   node.left = init
-  node.right = type === "ForInStatement" ? this.parseExpression() : this.parseMaybeAssign()
+  node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign()
   this.expect(tt.parenR)
-  this.exitScope()
   node.body = this.parseStatement("for")
+  this.exitScope()
   this.labels.pop()
-  return this.finishNode(node, type)
+  return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
 }
 
 // Parse a list of variable declarations.
@@ -478,41 +511,51 @@ pp.parseVar = function(node, isFor, kind) {
 }
 
 pp.parseVarId = function(decl, kind) {
-  decl.id = this.parseBindingAtom(kind)
-  this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false)
+  decl.id = this.parseBindingAtom()
+  this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false)
 }
 
 const FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4
 
 // Parse a function declaration or literal (depending on the
-// `isStatement` parameter).
+// `statement & FUNC_STATEMENT`).
 
-pp.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
+// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
+pp.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
   this.initFunction(node)
-  if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync)
+  if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
+    if (this.type === tt.star && (statement & FUNC_HANGING_STATEMENT))
+      this.unexpected()
     node.generator = this.eat(tt.star)
+  }
   if (this.options.ecmaVersion >= 8)
     node.async = !!isAsync
 
   if (statement & FUNC_STATEMENT) {
     node.id = (statement & FUNC_NULLABLE_ID) && this.type !== tt.name ? null : this.parseIdent()
     if (node.id && !(statement & FUNC_HANGING_STATEMENT))
-      this.checkLVal(node.id, this.inModule && !this.inFunction ? BIND_LEXICAL : BIND_FUNCTION)
+      // If it is a regular function declaration in sloppy mode, then it is
+      // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
+      // mode depends on properties of the current scope (see
+      // treatFunctionsAsVar).
+      this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION)
   }
 
-  let oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos
+  let oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos
   this.yieldPos = 0
   this.awaitPos = 0
+  this.awaitIdentPos = 0
   this.enterScope(functionFlags(node.async, node.generator))
 
   if (!(statement & FUNC_STATEMENT))
     node.id = this.type === tt.name ? this.parseIdent() : null
 
   this.parseFunctionParams(node)
-  this.parseFunctionBody(node, allowExpressionBody)
+  this.parseFunctionBody(node, allowExpressionBody, false, forInit)
 
   this.yieldPos = oldYieldPos
   this.awaitPos = oldAwaitPos
+  this.awaitIdentPos = oldAwaitIdentPos
   return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
 }
 
@@ -528,90 +571,265 @@ pp.parseFunctionParams = function(node) {
 pp.parseClass = function(node, isStatement) {
   this.next()
 
+  // ecma-262 14.6 Class Definitions
+  // A class definition is always strict mode code.
+  const oldStrict = this.strict
+  this.strict = true
+
   this.parseClassId(node, isStatement)
   this.parseClassSuper(node)
-  let classBody = this.startNode()
+  const privateNameMap = this.enterClassBody()
+  const classBody = this.startNode()
   let hadConstructor = false
   classBody.body = []
   this.expect(tt.braceL)
-  while (!this.eat(tt.braceR)) {
+  while (this.type !== tt.braceR) {
     const element = this.parseClassElement(node.superClass !== null)
     if (element) {
       classBody.body.push(element)
       if (element.type === "MethodDefinition" && element.kind === "constructor") {
         if (hadConstructor) this.raise(element.start, "Duplicate constructor in the same class")
         hadConstructor = true
+      } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
+        this.raiseRecoverable(element.key.start, `Identifier '#${element.key.name}' has already been declared`)
       }
     }
   }
+  this.strict = oldStrict
+  this.next()
   node.body = this.finishNode(classBody, "ClassBody")
+  this.exitClassBody()
   return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
 }
 
 pp.parseClassElement = function(constructorAllowsSuper) {
   if (this.eat(tt.semi)) return null
 
-  let method = this.startNode()
-  const tryContextual = (k, noLineBreak = false) => {
-    const start = this.start, startLoc = this.startLoc
-    if (!this.eatContextual(k)) return false
-    if (this.type !== tt.parenL && (!noLineBreak || !this.canInsertSemicolon())) return true
-    if (method.key) this.unexpected()
-    method.computed = false
-    method.key = this.startNodeAt(start, startLoc)
-    method.key.name = k
-    this.finishNode(method.key, "Identifier")
-    return false
-  }
-
-  method.kind = "method"
-  method.static = tryContextual("static")
-  let isGenerator = this.eat(tt.star)
+  const ecmaVersion = this.options.ecmaVersion
+  const node = this.startNode()
+  let keyName = ""
+  let isGenerator = false
   let isAsync = false
-  if (!isGenerator) {
-    if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
+  let kind = "method"
+  let isStatic = false
+
+  if (this.eatContextual("static")) {
+    // Parse static init block
+    if (ecmaVersion >= 13 && this.eat(tt.braceL)) {
+      this.parseClassStaticBlock(node)
+      return node
+    }
+    if (this.isClassElementNameStart() || this.type === tt.star) {
+      isStatic = true
+    } else {
+      keyName = "static"
+    }
+  }
+  node.static = isStatic
+  if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
+    if ((this.isClassElementNameStart() || this.type === tt.star) && !this.canInsertSemicolon()) {
       isAsync = true
-      isGenerator = this.options.ecmaVersion >= 9 && this.eat(tt.star)
-    } else if (tryContextual("get")) {
-      method.kind = "get"
-    } else if (tryContextual("set")) {
-      method.kind = "set"
+    } else {
+      keyName = "async"
+    }
+  }
+  if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(tt.star)) {
+    isGenerator = true
+  }
+  if (!keyName && !isAsync && !isGenerator) {
+    const lastValue = this.value
+    if (this.eatContextual("get") || this.eatContextual("set")) {
+      if (this.isClassElementNameStart()) {
+        kind = lastValue
+      } else {
+        keyName = lastValue
+      }
+    }
+  }
+
+  // Parse element name
+  if (keyName) {
+    // 'async', 'get', 'set', or 'static' were not a keyword contextually.
+    // The last token is any of those. Make it the element name.
+    node.computed = false
+    node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc)
+    node.key.name = keyName
+    this.finishNode(node.key, "Identifier")
+  } else {
+    this.parseClassElementName(node)
+  }
+
+  // Parse element value
+  if (ecmaVersion < 13 || this.type === tt.parenL || kind !== "method" || isGenerator || isAsync) {
+    const isConstructor = !node.static && checkKeyName(node, "constructor")
+    const allowsDirectSuper = isConstructor && constructorAllowsSuper
+    // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
+    if (isConstructor && kind !== "method") this.raise(node.key.start, "Constructor can't have get/set modifier")
+    node.kind = isConstructor ? "constructor" : kind
+    this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper)
+  } else {
+    this.parseClassField(node)
+  }
+
+  return node
+}
+
+pp.isClassElementNameStart = function() {
+  return (
+    this.type === tt.name ||
+    this.type === tt.privateId ||
+    this.type === tt.num ||
+    this.type === tt.string ||
+    this.type === tt.bracketL ||
+    this.type.keyword
+  )
+}
+
+pp.parseClassElementName = function(element) {
+  if (this.type === tt.privateId) {
+    if (this.value === "constructor") {
+      this.raise(this.start, "Classes can't have an element named '#constructor'")
     }
+    element.computed = false
+    element.key = this.parsePrivateIdent()
+  } else {
+    this.parsePropertyName(element)
   }
-  if (!method.key) this.parsePropertyName(method)
-  let {key} = method
-  let allowsDirectSuper = false
-  if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
-      key.type === "Literal" && key.value === "constructor")) {
-    if (method.kind !== "method") this.raise(key.start, "Constructor can't have get/set modifier")
+}
+
+pp.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
+  // Check key and flags
+  const key = method.key
+  if (method.kind === "constructor") {
     if (isGenerator) this.raise(key.start, "Constructor can't be a generator")
     if (isAsync) this.raise(key.start, "Constructor can't be an async method")
-    method.kind = "constructor"
-    allowsDirectSuper = constructorAllowsSuper
-  } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
+  } else if (method.static && checkKeyName(method, "prototype")) {
     this.raise(key.start, "Classes may not have a static property named prototype")
   }
-  this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper)
-  if (method.kind === "get" && method.value.params.length !== 0)
-    this.raiseRecoverable(method.value.start, "getter should have no params")
-  if (method.kind === "set" && method.value.params.length !== 1)
-    this.raiseRecoverable(method.value.start, "setter should have exactly one param")
-  if (method.kind === "set" && method.value.params[0].type === "RestElement")
-    this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params")
-  return method
-}
 
-pp.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
-  method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper)
+  // Parse value
+  const value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper)
+
+  // Check value
+  if (method.kind === "get" && value.params.length !== 0)
+    this.raiseRecoverable(value.start, "getter should have no params")
+  if (method.kind === "set" && value.params.length !== 1)
+    this.raiseRecoverable(value.start, "setter should have exactly one param")
+  if (method.kind === "set" && value.params[0].type === "RestElement")
+    this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params")
+
   return this.finishNode(method, "MethodDefinition")
 }
 
+pp.parseClassField = function(field) {
+  if (checkKeyName(field, "constructor")) {
+    this.raise(field.key.start, "Classes can't have a field named 'constructor'")
+  } else if (field.static && checkKeyName(field, "prototype")) {
+    this.raise(field.key.start, "Classes can't have a static field named 'prototype'")
+  }
+
+  if (this.eat(tt.eq)) {
+    // To raise SyntaxError if 'arguments' exists in the initializer.
+    const scope = this.currentThisScope()
+    const inClassFieldInit = scope.inClassFieldInit
+    scope.inClassFieldInit = true
+    field.value = this.parseMaybeAssign()
+    scope.inClassFieldInit = inClassFieldInit
+  } else {
+    field.value = null
+  }
+  this.semicolon()
+
+  return this.finishNode(field, "PropertyDefinition")
+}
+
+pp.parseClassStaticBlock = function(node) {
+  node.body = []
+
+  let oldLabels = this.labels
+  this.labels = []
+  this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER)
+  while (this.type !== tt.braceR) {
+    let stmt = this.parseStatement(null)
+    node.body.push(stmt)
+  }
+  this.next()
+  this.exitScope()
+  this.labels = oldLabels
+
+  return this.finishNode(node, "StaticBlock")
+}
+
 pp.parseClassId = function(node, isStatement) {
-  node.id = this.type === tt.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null
+  if (this.type === tt.name) {
+    node.id = this.parseIdent()
+    if (isStatement)
+      this.checkLValSimple(node.id, BIND_LEXICAL, false)
+  } else {
+    if (isStatement === true)
+      this.unexpected()
+    node.id = null
+  }
 }
 
 pp.parseClassSuper = function(node) {
-  node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null
+  node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts(false) : null
+}
+
+pp.enterClassBody = function() {
+  const element = {declared: Object.create(null), used: []}
+  this.privateNameStack.push(element)
+  return element.declared
+}
+
+pp.exitClassBody = function() {
+  const {declared, used} = this.privateNameStack.pop()
+  const len = this.privateNameStack.length
+  const parent = len === 0 ? null : this.privateNameStack[len - 1]
+  for (let i = 0; i < used.length; ++i) {
+    const id = used[i]
+    if (!hasOwn(declared, id.name)) {
+      if (parent) {
+        parent.used.push(id)
+      } else {
+        this.raiseRecoverable(id.start, `Private field '#${id.name}' must be declared in an enclosing class`)
+      }
+    }
+  }
+}
+
+function isPrivateNameConflicted(privateNameMap, element) {
+  const name = element.key.name
+  const curr = privateNameMap[name]
+
+  let next = "true"
+  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
+    next = (element.static ? "s" : "i") + element.kind
+  }
+
+  // `class { get #a(){}; static set #a(_){} }` is also conflict.
+  if (
+    curr === "iget" && next === "iset" ||
+    curr === "iset" && next === "iget" ||
+    curr === "sget" && next === "sset" ||
+    curr === "sset" && next === "sget"
+  ) {
+    privateNameMap[name] = "true"
+    return false
+  } else if (!curr) {
+    privateNameMap[name] = next
+    return false
+  } else {
+    return true
+  }
+}
+
+function checkKeyName(node, name) {
+  const {computed, key} = node
+  return !computed && (
+    key.type === "Identifier" && key.name === name ||
+    key.type === "Literal" && key.value === name
+  )
 }
 
 // Parses module export declaration.
@@ -620,6 +838,14 @@ pp.parseExport = function(node, exports) {
   this.next()
   // export * from '...'
   if (this.eat(tt.star)) {
+    if (this.options.ecmaVersion >= 11) {
+      if (this.eatContextual("as")) {
+        node.exported = this.parseModuleExportName()
+        this.checkExport(exports, node.exported, this.lastTokStart)
+      } else {
+        node.exported = null
+      }
+    }
     this.expectContextual("from")
     if (this.type !== tt.string) this.unexpected()
     node.source = this.parseExprAtom()
@@ -633,7 +859,7 @@ pp.parseExport = function(node, exports) {
       let fNode = this.startNode()
       this.next()
       if (isAsync) this.next()
-      node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync, true)
+      node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync)
     } else if (this.type === tt._class) {
       let cNode = this.startNode()
       node.declaration = this.parseClass(cNode, "nullableID")
@@ -649,7 +875,7 @@ pp.parseExport = function(node, exports) {
     if (node.declaration.type === "VariableDeclaration")
       this.checkVariableExport(exports, node.declaration.declarations)
     else
-      this.checkExport(exports, node.declaration.id.name, node.declaration.id.start)
+      this.checkExport(exports, node.declaration.id, node.declaration.id.start)
     node.specifiers = []
     node.source = null
   } else { // export { x, y as z } [from '...']
@@ -659,9 +885,15 @@ pp.parseExport = function(node, exports) {
       if (this.type !== tt.string) this.unexpected()
       node.source = this.parseExprAtom()
     } else {
-      // check for keywords used as local names
       for (let spec of node.specifiers) {
+        // check for keywords used as local names
         this.checkUnreserved(spec.local)
+        // check if export is defined
+        this.checkLocalExport(spec.local)
+
+        if (spec.local.type === "Literal") {
+          this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.")
+        }
       }
 
       node.source = null
@@ -673,7 +905,9 @@ pp.parseExport = function(node, exports) {
 
 pp.checkExport = function(exports, name, pos) {
   if (!exports) return
-  if (has(exports, name))
+  if (typeof name !== "string")
+    name = name.type === "Identifier" ? name.name : name.value
+  if (hasOwn(exports, name))
     this.raiseRecoverable(pos, "Duplicate export '" + name + "'")
   exports[name] = true
 }
@@ -681,7 +915,7 @@ pp.checkExport = function(exports, name, pos) {
 pp.checkPatternExport = function(exports, pat) {
   let type = pat.type
   if (type === "Identifier")
-    this.checkExport(exports, pat.name, pat.start)
+    this.checkExport(exports, pat, pat.start)
   else if (type === "ObjectPattern")
     for (let prop of pat.properties)
       this.checkPatternExport(exports, prop)
@@ -727,9 +961,13 @@ pp.parseExportSpecifiers = function(exports) {
     } else first = false
 
     let node = this.startNode()
-    node.local = this.parseIdent(true)
-    node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local
-    this.checkExport(exports, node.exported.name, node.exported.start)
+    node.local = this.parseModuleExportName()
+    node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local
+    this.checkExport(
+      exports,
+      node.exported,
+      node.exported.start
+    )
     nodes.push(this.finishNode(node, "ExportSpecifier"))
   }
   return nodes
@@ -760,7 +998,7 @@ pp.parseImportSpecifiers = function() {
     // import defaultObj, { x, y as z } from '...'
     let node = this.startNode()
     node.local = this.parseIdent()
-    this.checkLVal(node.local, BIND_LEXICAL)
+    this.checkLValSimple(node.local, BIND_LEXICAL)
     nodes.push(this.finishNode(node, "ImportDefaultSpecifier"))
     if (!this.eat(tt.comma)) return nodes
   }
@@ -769,7 +1007,7 @@ pp.parseImportSpecifiers = function() {
     this.next()
     this.expectContextual("as")
     node.local = this.parseIdent()
-    this.checkLVal(node.local, BIND_LEXICAL)
+    this.checkLValSimple(node.local, BIND_LEXICAL)
     nodes.push(this.finishNode(node, "ImportNamespaceSpecifier"))
     return nodes
   }
@@ -781,19 +1019,30 @@ pp.parseImportSpecifiers = function() {
     } else first = false
 
     let node = this.startNode()
-    node.imported = this.parseIdent(true)
+    node.imported = this.parseModuleExportName()
     if (this.eatContextual("as")) {
       node.local = this.parseIdent()
     } else {
       this.checkUnreserved(node.imported)
       node.local = node.imported
     }
-    this.checkLVal(node.local, BIND_LEXICAL)
+    this.checkLValSimple(node.local, BIND_LEXICAL)
     nodes.push(this.finishNode(node, "ImportSpecifier"))
   }
   return nodes
 }
 
+pp.parseModuleExportName = function() {
+  if (this.options.ecmaVersion >= 13 && this.type === tt.string) {
+    const stringLiteral = this.parseLiteral(this.value)
+    if (loneSurrogate.test(stringLiteral.value)) {
+      this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.")
+    }
+    return stringLiteral
+  }
+  return this.parseIdent(true)
+}
+
 // Set `ExpressionStatement#directive` property for directive prologues.
 pp.adaptDirectivePrologue = function(statements) {
   for (let i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
index 6a89c7f..4df2b41 100644 (file)
@@ -2,9 +2,9 @@
 // given point in the program is loosely based on sweet.js' approach.
 // See https://github.com/mozilla/sweet.js/wiki/design
 
-import {Parser} from "./state"
-import {types as tt} from "./tokentype"
-import {lineBreak} from "./whitespace"
+import {Parser} from "./state.js"
+import {types as tt} from "./tokentype.js"
+import {lineBreak} from "./whitespace.js"
 
 export class TokContext {
   constructor(token, isExpr, preserveSpace, override, generator) {
@@ -35,6 +35,10 @@ pp.initialContext = function() {
   return [types.b_stat]
 }
 
+pp.curContext = function() {
+  return this.context[this.context.length - 1]
+}
+
 pp.braceIsBlock = function(prevType) {
   let parent = this.curContext()
   if (parent === types.f_expr || parent === types.f_stat)
@@ -51,7 +55,7 @@ pp.braceIsBlock = function(prevType) {
     return true
   if (prevType === tt.braceL)
     return parent === types.b_stat
-  if (prevType === tt._var || prevType === tt.name)
+  if (prevType === tt._var || prevType === tt._const || prevType === tt.name)
     return false
   return !this.exprAllowed
 }
@@ -75,6 +79,13 @@ pp.updateContext = function(prevType) {
     this.exprAllowed = type.beforeExpr
 }
 
+// Used to handle egde case when token context could not be inferred correctly in tokenize phase
+pp.overrideContext = function(tokenCtx) {
+  if (this.curContext() !== tokenCtx) {
+    this.context[this.context.length - 1] = tokenCtx
+  }
+}
+
 // Token-specific context update code
 
 tt.parenR.updateContext = tt.braceR.updateContext = function() {
@@ -110,7 +121,9 @@ tt.incDec.updateContext = function() {
 }
 
 tt._function.updateContext = tt._class.updateContext = function(prevType) {
-  if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else &&
+  if (prevType.beforeExpr && prevType !== tt._else &&
+      !(prevType === tt.semi && this.curContext() !== types.p_stat) &&
+      !(prevType === tt._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
       !((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat))
     this.context.push(types.f_expr)
   else
index 3014ddc..99f8b44 100644 (file)
@@ -1,9 +1,9 @@
-import {isIdentifierStart, isIdentifierChar} from "./identifier"
-import {types as tt, keywords as keywordTypes} from "./tokentype"
-import {Parser} from "./state"
-import {SourceLocation} from "./locutil"
-import {RegExpValidationState} from "./regexp"
-import {lineBreak, lineBreakG, isNewLine, nonASCIIwhitespace} from "./whitespace"
+import {isIdentifierStart, isIdentifierChar} from "./identifier.js"
+import {types as tt, keywords as keywordTypes} from "./tokentype.js"
+import {Parser} from "./state.js"
+import {SourceLocation} from "./locutil.js"
+import {RegExpValidationState} from "./regexp.js"
+import {lineBreak, nextLineBreak, isNewLine, nonASCIIwhitespace} from "./whitespace.js"
 
 // Object type used to represent tokens. Note that normally, tokens
 // simply exist as properties on the parser object. This is only
@@ -28,7 +28,9 @@ const pp = Parser.prototype
 
 // Move to the next token
 
-pp.next = function() {
+pp.next = function(ignoreEscapeSequenceInKeyword) {
+  if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
+    this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword)
   if (this.options.onToken)
     this.options.onToken(new Token(this))
 
@@ -61,10 +63,6 @@ if (typeof Symbol !== "undefined")
 // Toggle strict mode. Re-reads the next number or string to please
 // pedantic tests (`"use strict"; 010;` should fail).
 
-pp.curContext = function() {
-  return this.context[this.context.length - 1]
-}
-
 // Read a single token, updating the parser object's token-related
 // properties.
 
@@ -91,9 +89,9 @@ pp.readToken = function(code) {
 
 pp.fullCharCodeAtPos = function() {
   let code = this.input.charCodeAt(this.pos)
-  if (code <= 0xd7ff || code >= 0xe000) return code
+  if (code <= 0xd7ff || code >= 0xdc00) return code
   let next = this.input.charCodeAt(this.pos + 1)
-  return (code << 10) + next - 0x35fdc00
+  return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
 }
 
 pp.skipBlockComment = function() {
@@ -102,11 +100,9 @@ pp.skipBlockComment = function() {
   if (end === -1) this.raise(this.pos - 2, "Unterminated comment")
   this.pos = end + 2
   if (this.options.locations) {
-    lineBreakG.lastIndex = start
-    let match
-    while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
+    for (let nextBreak, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
       ++this.curLine
-      this.lineStart = match.index + match[0].length
+      pos = this.lineStart = nextBreak
     }
   }
   if (this.options.onComment)
@@ -231,7 +227,13 @@ pp.readToken_mult_modulo_exp = function(code) { // '%*'
 
 pp.readToken_pipe_amp = function(code) { // '|&'
   let next = this.input.charCodeAt(this.pos + 1)
-  if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)
+  if (next === code) {
+    if (this.options.ecmaVersion >= 12) {
+      let next2 = this.input.charCodeAt(this.pos + 2)
+      if (next2 === 61) return this.finishOp(tt.assign, 3)
+    }
+    return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)
+  }
   if (next === 61) return this.finishOp(tt.assign, 2)
   return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1)
 }
@@ -287,6 +289,39 @@ pp.readToken_eq_excl = function(code) { // '=!'
   return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1)
 }
 
+pp.readToken_question = function() { // '?'
+  const ecmaVersion = this.options.ecmaVersion
+  if (ecmaVersion >= 11) {
+    let next = this.input.charCodeAt(this.pos + 1)
+    if (next === 46) {
+      let next2 = this.input.charCodeAt(this.pos + 2)
+      if (next2 < 48 || next2 > 57) return this.finishOp(tt.questionDot, 2)
+    }
+    if (next === 63) {
+      if (ecmaVersion >= 12) {
+        let next2 = this.input.charCodeAt(this.pos + 2)
+        if (next2 === 61) return this.finishOp(tt.assign, 3)
+      }
+      return this.finishOp(tt.coalesce, 2)
+    }
+  }
+  return this.finishOp(tt.question, 1)
+}
+
+pp.readToken_numberSign = function() { // '#'
+  const ecmaVersion = this.options.ecmaVersion
+  let code = 35 // '#'
+  if (ecmaVersion >= 13) {
+    ++this.pos
+    code = this.fullCharCodeAtPos()
+    if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
+      return this.finishToken(tt.privateId, this.readWord1())
+    }
+  }
+
+  this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'")
+}
+
 pp.getTokenFromCode = function(code) {
   switch (code) {
   // The interpretation of a dot depends on whether it is followed
@@ -306,7 +341,6 @@ pp.getTokenFromCode = function(code) {
   case 123: ++this.pos; return this.finishToken(tt.braceL)
   case 125: ++this.pos; return this.finishToken(tt.braceR)
   case 58: ++this.pos; return this.finishToken(tt.colon)
-  case 63: ++this.pos; return this.finishToken(tt.question)
 
   case 96: // '`'
     if (this.options.ecmaVersion < 6) break
@@ -334,7 +368,6 @@ pp.getTokenFromCode = function(code) {
   // often referred to. `finishOp` simply skips the amount of
   // characters it is given as second argument, and returns a token
   // of the type given by its first argument.
-
   case 47: // '/'
     return this.readToken_slash()
 
@@ -356,8 +389,14 @@ pp.getTokenFromCode = function(code) {
   case 61: case 33: // '=!'
     return this.readToken_eq_excl(code)
 
+  case 63: // '?'
+    return this.readToken_question()
+
   case 126: // '~'
     return this.finishOp(tt.prefix, 1)
+
+  case 35: // '#'
+    return this.readToken_numberSign()
   }
 
   this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'")
@@ -411,28 +450,69 @@ pp.readRegexp = function() {
 // were read, the integer value otherwise. When `len` is given, this
 // will return `null` unless the integer has exactly `len` digits.
 
-pp.readInt = function(radix, len) {
-  let start = this.pos, total = 0
-  for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
+pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
+  // `len` is used for character escape sequences. In that case, disallow separators.
+  const allowSeparators = this.options.ecmaVersion >= 12 && len === undefined
+
+  // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
+  // and isn't fraction part nor exponent part. In that case, if the first digit
+  // is zero then disallow separators.
+  const isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48
+
+  let start = this.pos, total = 0, lastCode = 0
+  for (let i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
     let code = this.input.charCodeAt(this.pos), val
+
+    if (allowSeparators && code === 95) {
+      if (isLegacyOctalNumericLiteral) this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals")
+      if (lastCode === 95) this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore")
+      if (i === 0) this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits")
+      lastCode = code
+      continue
+    }
+
     if (code >= 97) val = code - 97 + 10 // a
     else if (code >= 65) val = code - 65 + 10 // A
     else if (code >= 48 && code <= 57) val = code - 48 // 0-9
     else val = Infinity
     if (val >= radix) break
-    ++this.pos
+    lastCode = code
     total = total * radix + val
   }
+
+  if (allowSeparators && lastCode === 95) this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits")
   if (this.pos === start || len != null && this.pos - start !== len) return null
 
   return total
 }
 
+function stringToNumber(str, isLegacyOctalNumericLiteral) {
+  if (isLegacyOctalNumericLiteral) {
+    return parseInt(str, 8)
+  }
+
+  // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
+  return parseFloat(str.replace(/_/g, ""))
+}
+
+function stringToBigInt(str) {
+  if (typeof BigInt !== "function") {
+    return null
+  }
+
+  // `BigInt(value)` throws syntax error if the string contains numeric separators.
+  return BigInt(str.replace(/_/g, ""))
+}
+
 pp.readRadixNumber = function(radix) {
+  let start = this.pos
   this.pos += 2 // 0x
   let val = this.readInt(radix)
   if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix)
-  if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
+  if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
+    val = stringToBigInt(this.input.slice(start, this.pos))
+    ++this.pos
+  } else if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
   return this.finishToken(tt.num, val)
 }
 
@@ -440,11 +520,17 @@ pp.readRadixNumber = function(radix) {
 
 pp.readNumber = function(startsWithDot) {
   let start = this.pos
-  if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number")
+  if (!startsWithDot && this.readInt(10, undefined, true) === null) this.raise(start, "Invalid number")
   let octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48
   if (octal && this.strict) this.raise(start, "Invalid number")
-  if (octal && /[89]/.test(this.input.slice(start, this.pos))) octal = false
   let next = this.input.charCodeAt(this.pos)
+  if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
+    let val = stringToBigInt(this.input.slice(start, this.pos))
+    ++this.pos
+    if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
+    return this.finishToken(tt.num, val)
+  }
+  if (octal && /[89]/.test(this.input.slice(start, this.pos))) octal = false
   if (next === 46 && !octal) { // '.'
     ++this.pos
     this.readInt(10)
@@ -457,8 +543,7 @@ pp.readNumber = function(startsWithDot) {
   }
   if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
 
-  let str = this.input.slice(start, this.pos)
-  let val = octal ? parseInt(str, 8) : parseFloat(str)
+  let val = stringToNumber(this.input.slice(start, this.pos), octal)
   return this.finishToken(tt.num, val)
 }
 
@@ -496,8 +581,15 @@ pp.readString = function(quote) {
       out += this.input.slice(chunkStart, this.pos)
       out += this.readEscapedChar(false)
       chunkStart = this.pos
+    } else if (ch === 0x2028 || ch === 0x2029) {
+      if (this.options.ecmaVersion < 10) this.raise(this.start, "Unterminated string constant")
+      ++this.pos
+      if (this.options.locations) {
+        this.curLine++
+        this.lineStart = this.pos
+      }
     } else {
-      if (isNewLine(ch, this.options.ecmaVersion >= 10)) this.raise(this.start, "Unterminated string constant")
+      if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant")
       ++this.pos
     }
   }
@@ -590,8 +682,8 @@ pp.readInvalidTemplateToken = function() {
       if (this.input[this.pos + 1] !== "{") {
         break
       }
-    // falls through
 
+    // falls through
     case "`":
       return this.finishToken(tt.invalidTemplate, this.input.slice(this.start, this.pos))
 
@@ -619,6 +711,24 @@ pp.readEscapedChar = function(inTemplate) {
   case 10: // ' \n'
     if (this.options.locations) { this.lineStart = this.pos; ++this.curLine }
     return ""
+  case 56:
+  case 57:
+    if (this.strict) {
+      this.invalidStringToken(
+        this.pos - 1,
+        "Invalid escape sequence"
+      )
+    }
+    if (inTemplate) {
+      const codePos = this.pos - 1
+
+      this.invalidStringToken(
+        codePos,
+        "Invalid escape sequence in template string"
+      )
+
+      return null
+    }
   default:
     if (ch >= 48 && ch <= 55) {
       let octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]
@@ -639,6 +749,11 @@ pp.readEscapedChar = function(inTemplate) {
       }
       return String.fromCharCode(octal)
     }
+    if (isNewLine(ch)) {
+      // Unicode new line characters after \ get removed from output in both
+      // template literals and strings
+      return ""
+    }
     return String.fromCharCode(ch)
   }
 }
@@ -693,7 +808,6 @@ pp.readWord = function() {
   let word = this.readWord1()
   let type = tt.name
   if (this.keywords.test(word)) {
-    if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword " + word)
     type = keywordTypes[word]
   }
   return this.finishToken(type, word)
index 2fe565c..06fc2c1 100644 (file)
@@ -56,6 +56,7 @@ export const types = {
   regexp: new TokenType("regexp", startsExpr),
   string: new TokenType("string", startsExpr),
   name: new TokenType("name", startsExpr),
+  privateId: new TokenType("privateId", startsExpr),
   eof: new TokenType("eof"),
 
   // Punctuation token types.
@@ -71,6 +72,7 @@ export const types = {
   dot: new TokenType("."),
   hash: new TokenType("#"), // Nick
   question: new TokenType("?", beforeExpr),
+  questionDot: new TokenType("?."),
   arrow: new TokenType("=>", beforeExpr),
   template: new TokenType("template"),
   invalidTemplate: new TokenType("invalidTemplate"),
@@ -109,6 +111,7 @@ export const types = {
   star: binop("*", 10),
   slash: binop("/", 10),
   starstar: new TokenType("**", {beforeExpr: true}),
+  coalesce: binop("??", 1),
 
   // Keyword token types.
   _break: kw("break"),
@@ -137,7 +140,7 @@ export const types = {
   _class: kw("class", startsExpr),
   _extends: kw("extends", beforeExpr),
   _export: kw("export"),
-  _import: kw("import"),
+  _import: kw("import", startsExpr),
   _null: kw("null", startsExpr),
   _true: kw("true", startsExpr),
   _false: kw("false", startsExpr),
index d44f1a2..50020c3 100644 (file)
-const data = {
-  "$LONE": [
-    "ASCII",
-    "ASCII_Hex_Digit",
-    "AHex",
-    "Alphabetic",
-    "Alpha",
-    "Any",
-    "Assigned",
-    "Bidi_Control",
-    "Bidi_C",
-    "Bidi_Mirrored",
-    "Bidi_M",
-    "Case_Ignorable",
-    "CI",
-    "Cased",
-    "Changes_When_Casefolded",
-    "CWCF",
-    "Changes_When_Casemapped",
-    "CWCM",
-    "Changes_When_Lowercased",
-    "CWL",
-    "Changes_When_NFKC_Casefolded",
-    "CWKCF",
-    "Changes_When_Titlecased",
-    "CWT",
-    "Changes_When_Uppercased",
-    "CWU",
-    "Dash",
-    "Default_Ignorable_Code_Point",
-    "DI",
-    "Deprecated",
-    "Dep",
-    "Diacritic",
-    "Dia",
-    "Emoji",
-    "Emoji_Component",
-    "Emoji_Modifier",
-    "Emoji_Modifier_Base",
-    "Emoji_Presentation",
-    "Extender",
-    "Ext",
-    "Grapheme_Base",
-    "Gr_Base",
-    "Grapheme_Extend",
-    "Gr_Ext",
-    "Hex_Digit",
-    "Hex",
-    "IDS_Binary_Operator",
-    "IDSB",
-    "IDS_Trinary_Operator",
-    "IDST",
-    "ID_Continue",
-    "IDC",
-    "ID_Start",
-    "IDS",
-    "Ideographic",
-    "Ideo",
-    "Join_Control",
-    "Join_C",
-    "Logical_Order_Exception",
-    "LOE",
-    "Lowercase",
-    "Lower",
-    "Math",
-    "Noncharacter_Code_Point",
-    "NChar",
-    "Pattern_Syntax",
-    "Pat_Syn",
-    "Pattern_White_Space",
-    "Pat_WS",
-    "Quotation_Mark",
-    "QMark",
-    "Radical",
-    "Regional_Indicator",
-    "RI",
-    "Sentence_Terminal",
-    "STerm",
-    "Soft_Dotted",
-    "SD",
-    "Terminal_Punctuation",
-    "Term",
-    "Unified_Ideograph",
-    "UIdeo",
-    "Uppercase",
-    "Upper",
-    "Variation_Selector",
-    "VS",
-    "White_Space",
-    "space",
-    "XID_Continue",
-    "XIDC",
-    "XID_Start",
-    "XIDS"
-  ],
-  "General_Category": [
-    "Cased_Letter",
-    "LC",
-    "Close_Punctuation",
-    "Pe",
-    "Connector_Punctuation",
-    "Pc",
-    "Control",
-    "Cc",
-    "cntrl",
-    "Currency_Symbol",
-    "Sc",
-    "Dash_Punctuation",
-    "Pd",
-    "Decimal_Number",
-    "Nd",
-    "digit",
-    "Enclosing_Mark",
-    "Me",
-    "Final_Punctuation",
-    "Pf",
-    "Format",
-    "Cf",
-    "Initial_Punctuation",
-    "Pi",
-    "Letter",
-    "L",
-    "Letter_Number",
-    "Nl",
-    "Line_Separator",
-    "Zl",
-    "Lowercase_Letter",
-    "Ll",
-    "Mark",
-    "M",
-    "Combining_Mark",
-    "Math_Symbol",
-    "Sm",
-    "Modifier_Letter",
-    "Lm",
-    "Modifier_Symbol",
-    "Sk",
-    "Nonspacing_Mark",
-    "Mn",
-    "Number",
-    "N",
-    "Open_Punctuation",
-    "Ps",
-    "Other",
-    "C",
-    "Other_Letter",
-    "Lo",
-    "Other_Number",
-    "No",
-    "Other_Punctuation",
-    "Po",
-    "Other_Symbol",
-    "So",
-    "Paragraph_Separator",
-    "Zp",
-    "Private_Use",
-    "Co",
-    "Punctuation",
-    "P",
-    "punct",
-    "Separator",
-    "Z",
-    "Space_Separator",
-    "Zs",
-    "Spacing_Mark",
-    "Mc",
-    "Surrogate",
-    "Cs",
-    "Symbol",
-    "S",
-    "Titlecase_Letter",
-    "Lt",
-    "Unassigned",
-    "Cn",
-    "Uppercase_Letter",
-    "Lu"
-  ],
-  "Script": [
-    "Adlam",
-    "Adlm",
-    "Ahom",
-    "Anatolian_Hieroglyphs",
-    "Hluw",
-    "Arabic",
-    "Arab",
-    "Armenian",
-    "Armn",
-    "Avestan",
-    "Avst",
-    "Balinese",
-    "Bali",
-    "Bamum",
-    "Bamu",
-    "Bassa_Vah",
-    "Bass",
-    "Batak",
-    "Batk",
-    "Bengali",
-    "Beng",
-    "Bhaiksuki",
-    "Bhks",
-    "Bopomofo",
-    "Bopo",
-    "Brahmi",
-    "Brah",
-    "Braille",
-    "Brai",
-    "Buginese",
-    "Bugi",
-    "Buhid",
-    "Buhd",
-    "Canadian_Aboriginal",
-    "Cans",
-    "Carian",
-    "Cari",
-    "Caucasian_Albanian",
-    "Aghb",
-    "Chakma",
-    "Cakm",
-    "Cham",
-    "Cherokee",
-    "Cher",
-    "Common",
-    "Zyyy",
-    "Coptic",
-    "Copt",
-    "Qaac",
-    "Cuneiform",
-    "Xsux",
-    "Cypriot",
-    "Cprt",
-    "Cyrillic",
-    "Cyrl",
-    "Deseret",
-    "Dsrt",
-    "Devanagari",
-    "Deva",
-    "Duployan",
-    "Dupl",
-    "Egyptian_Hieroglyphs",
-    "Egyp",
-    "Elbasan",
-    "Elba",
-    "Ethiopic",
-    "Ethi",
-    "Georgian",
-    "Geor",
-    "Glagolitic",
-    "Glag",
-    "Gothic",
-    "Goth",
-    "Grantha",
-    "Gran",
-    "Greek",
-    "Grek",
-    "Gujarati",
-    "Gujr",
-    "Gurmukhi",
-    "Guru",
-    "Han",
-    "Hani",
-    "Hangul",
-    "Hang",
-    "Hanunoo",
-    "Hano",
-    "Hatran",
-    "Hatr",
-    "Hebrew",
-    "Hebr",
-    "Hiragana",
-    "Hira",
-    "Imperial_Aramaic",
-    "Armi",
-    "Inherited",
-    "Zinh",
-    "Qaai",
-    "Inscriptional_Pahlavi",
-    "Phli",
-    "Inscriptional_Parthian",
-    "Prti",
-    "Javanese",
-    "Java",
-    "Kaithi",
-    "Kthi",
-    "Kannada",
-    "Knda",
-    "Katakana",
-    "Kana",
-    "Kayah_Li",
-    "Kali",
-    "Kharoshthi",
-    "Khar",
-    "Khmer",
-    "Khmr",
-    "Khojki",
-    "Khoj",
-    "Khudawadi",
-    "Sind",
-    "Lao",
-    "Laoo",
-    "Latin",
-    "Latn",
-    "Lepcha",
-    "Lepc",
-    "Limbu",
-    "Limb",
-    "Linear_A",
-    "Lina",
-    "Linear_B",
-    "Linb",
-    "Lisu",
-    "Lycian",
-    "Lyci",
-    "Lydian",
-    "Lydi",
-    "Mahajani",
-    "Mahj",
-    "Malayalam",
-    "Mlym",
-    "Mandaic",
-    "Mand",
-    "Manichaean",
-    "Mani",
-    "Marchen",
-    "Marc",
-    "Masaram_Gondi",
-    "Gonm",
-    "Meetei_Mayek",
-    "Mtei",
-    "Mende_Kikakui",
-    "Mend",
-    "Meroitic_Cursive",
-    "Merc",
-    "Meroitic_Hieroglyphs",
-    "Mero",
-    "Miao",
-    "Plrd",
-    "Modi",
-    "Mongolian",
-    "Mong",
-    "Mro",
-    "Mroo",
-    "Multani",
-    "Mult",
-    "Myanmar",
-    "Mymr",
-    "Nabataean",
-    "Nbat",
-    "New_Tai_Lue",
-    "Talu",
-    "Newa",
-    "Nko",
-    "Nkoo",
-    "Nushu",
-    "Nshu",
-    "Ogham",
-    "Ogam",
-    "Ol_Chiki",
-    "Olck",
-    "Old_Hungarian",
-    "Hung",
-    "Old_Italic",
-    "Ital",
-    "Old_North_Arabian",
-    "Narb",
-    "Old_Permic",
-    "Perm",
-    "Old_Persian",
-    "Xpeo",
-    "Old_South_Arabian",
-    "Sarb",
-    "Old_Turkic",
-    "Orkh",
-    "Oriya",
-    "Orya",
-    "Osage",
-    "Osge",
-    "Osmanya",
-    "Osma",
-    "Pahawh_Hmong",
-    "Hmng",
-    "Palmyrene",
-    "Palm",
-    "Pau_Cin_Hau",
-    "Pauc",
-    "Phags_Pa",
-    "Phag",
-    "Phoenician",
-    "Phnx",
-    "Psalter_Pahlavi",
-    "Phlp",
-    "Rejang",
-    "Rjng",
-    "Runic",
-    "Runr",
-    "Samaritan",
-    "Samr",
-    "Saurashtra",
-    "Saur",
-    "Sharada",
-    "Shrd",
-    "Shavian",
-    "Shaw",
-    "Siddham",
-    "Sidd",
-    "SignWriting",
-    "Sgnw",
-    "Sinhala",
-    "Sinh",
-    "Sora_Sompeng",
-    "Sora",
-    "Soyombo",
-    "Soyo",
-    "Sundanese",
-    "Sund",
-    "Syloti_Nagri",
-    "Sylo",
-    "Syriac",
-    "Syrc",
-    "Tagalog",
-    "Tglg",
-    "Tagbanwa",
-    "Tagb",
-    "Tai_Le",
-    "Tale",
-    "Tai_Tham",
-    "Lana",
-    "Tai_Viet",
-    "Tavt",
-    "Takri",
-    "Takr",
-    "Tamil",
-    "Taml",
-    "Tangut",
-    "Tang",
-    "Telugu",
-    "Telu",
-    "Thaana",
-    "Thaa",
-    "Thai",
-    "Tibetan",
-    "Tibt",
-    "Tifinagh",
-    "Tfng",
-    "Tirhuta",
-    "Tirh",
-    "Ugaritic",
-    "Ugar",
-    "Vai",
-    "Vaii",
-    "Warang_Citi",
-    "Wara",
-    "Yi",
-    "Yiii",
-    "Zanabazar_Square",
-    "Zanb"
-  ]
+import {wordsRegexp} from "./util.js"
+
+// This file contains Unicode properties extracted from the ECMAScript
+// specification. The lists are extracted like so:
+// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
+
+// #table-binary-unicode-properties
+const ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"
+const ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"
+const ecma11BinaryProperties = ecma10BinaryProperties
+const ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"
+const ecma13BinaryProperties = ecma12BinaryProperties
+const unicodeBinaryProperties = {
+  9: ecma9BinaryProperties,
+  10: ecma10BinaryProperties,
+  11: ecma11BinaryProperties,
+  12: ecma12BinaryProperties,
+  13: ecma13BinaryProperties
+}
+
+// #table-unicode-general-category-values
+const unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"
+
+// #table-unicode-script-values
+const ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"
+const ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"
+const ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"
+const ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"
+const ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"
+const unicodeScriptValues = {
+  9: ecma9ScriptValues,
+  10: ecma10ScriptValues,
+  11: ecma11ScriptValues,
+  12: ecma12ScriptValues,
+  13: ecma13ScriptValues
+}
+
+const data = {}
+function buildUnicodeData(ecmaVersion) {
+  const d = data[ecmaVersion] = {
+    binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
+    nonBinary: {
+      General_Category: wordsRegexp(unicodeGeneralCategoryValues),
+      Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
+    }
+  }
+  d.nonBinary.Script_Extensions = d.nonBinary.Script
+
+  d.nonBinary.gc = d.nonBinary.General_Category
+  d.nonBinary.sc = d.nonBinary.Script
+  d.nonBinary.scx = d.nonBinary.Script_Extensions
+}
+
+for (const ecmaVersion of [9, 10, 11, 12, 13]) {
+  buildUnicodeData(ecmaVersion)
 }
-Array.prototype.push.apply(data.$LONE, data.General_Category)
-data.gc = data.General_Category
-data.sc = data.Script_Extensions = data.scx = data.Script
 
 export default data
index 9f548a1..8262cc6 100644 (file)
@@ -1,11 +1,15 @@
 const {hasOwnProperty, toString} = Object.prototype
 
-// Checks if an object has a property.
-
-export function has(obj, propName) {
-  return hasOwnProperty.call(obj, propName)
-}
+export const hasOwn = Object.hasOwn || ((obj, propName) => (
+  hasOwnProperty.call(obj, propName)
+))
 
 export const isArray = Array.isArray || ((obj) => (
   toString.call(obj) === "[object Array]"
 ))
+
+export function wordsRegexp(words) {
+  return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
+}
+
+export const loneSurrogate = /[\uD800-\uDFFF]/u
index cf8d913..7ec3ed0 100644 (file)
@@ -4,10 +4,19 @@
 export const lineBreak = /\r\n?|\n|\u2028|\u2029/
 export const lineBreakG = new RegExp(lineBreak.source, "g")
 
-export function isNewLine(code, ecma2019String) {
-  return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
+export function isNewLine(code) {
+  return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
 }
 
-export const nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/
+export function nextLineBreak(code, from, end = code.length) {
+  for (let i = from; i < end; i++) {
+    let next = code.charCodeAt(i)
+    if (isNewLine(next))
+      return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1
+  }
+  return -1
+}
+
+export const nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/
 
 export const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g