From 6f46b7f87440c648aa1a8699976ceb471b436817 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 20 Jan 2022 11:02:40 +0000 Subject: [PATCH 1/2] chore(deps): bump @babel/parser from 7.16.8 to 7.16.10 Bumps [@babel/parser](https://github.com/babel/babel/tree/HEAD/packages/babel-parser) from 7.16.8 to 7.16.10. - [Release notes](https://github.com/babel/babel/releases) - [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md) - [Commits](https://github.com/babel/babel/commits/v7.16.10/packages/babel-parser) --- updated-dependencies: - dependency-name: "@babel/parser" dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index d5ff2fb0f..13c0c5d86 100644 --- a/package-lock.json +++ b/package-lock.json @@ -310,9 +310,9 @@ } }, "@babel/parser": { - "version": "7.16.8", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.8.tgz", - "integrity": "sha512-i7jDUfrVBWc+7OKcBzEe5n7fbv3i2fWtxKzzCvOjnzSxMfWMigAhtfJ7qzZNGFNMsCCd67+uz553dYKWXPvCKw==" + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.10.tgz", + "integrity": "sha512-Sm/S9Or6nN8uiFsQU1yodyDW3MWXQhFeqzMPM+t8MJjM+pLsnFVxFZzkpXKvUXh+Gz9cbMoYYs484+Jw/NTEFQ==" }, "@babel/plugin-syntax-async-generators": { "version": "7.8.4", diff --git a/package.json b/package.json index 499bc1970..1f1c9170a 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "license": "MIT", "dependencies": { "@actions/core": "^1.6.0", - "@babel/parser": "^7.16.8", + "@babel/parser": "^7.16.10", "child_process": "^1.0.2", "compare-versions": "^4.1.3", "fs": "0.0.1-security", From 122a76088493f10423a45fbe10edc84c4b998a93 Mon Sep 17 00:00:00 2001 From: jiro4989 Date: Thu, 20 Jan 2022 22:18:53 +0900 Subject: [PATCH 2/2] npm ci --- node_modules/.bin/tsc | 1 - node_modules/.bin/tsserver | 1 - node_modules/.package-lock.json | 15 +- node_modules/@babel/parser/lib/index.js | 2046 ++++++++++++------- node_modules/@babel/parser/lib/index.js.map | 2 +- node_modules/@babel/parser/package.json | 2 +- 6 files changed, 1292 insertions(+), 775 deletions(-) delete mode 120000 node_modules/.bin/tsc delete mode 120000 node_modules/.bin/tsserver diff --git a/node_modules/.bin/tsc b/node_modules/.bin/tsc deleted file mode 120000 index 0863208a6..000000000 --- a/node_modules/.bin/tsc +++ /dev/null @@ -1 +0,0 @@ -../typescript/bin/tsc \ No newline at end of file diff --git a/node_modules/.bin/tsserver b/node_modules/.bin/tsserver deleted file mode 120000 index f8f8f1a0c..000000000 --- a/node_modules/.bin/tsserver +++ /dev/null @@ -1 +0,0 @@ -../typescript/bin/tsserver \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 8fc94dd7c..bafe9687a 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -333,9 +333,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.16.8", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.8.tgz", - "integrity": "sha512-i7jDUfrVBWc+7OKcBzEe5n7fbv3i2fWtxKzzCvOjnzSxMfWMigAhtfJ7qzZNGFNMsCCd67+uz553dYKWXPvCKw==", + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.10.tgz", + "integrity": "sha512-Sm/S9Or6nN8uiFsQU1yodyDW3MWXQhFeqzMPM+t8MJjM+pLsnFVxFZzkpXKvUXh+Gz9cbMoYYs484+Jw/NTEFQ==", "bin": { "parser": "bin/babel-parser.js" }, @@ -9237,14 +9237,7 @@ "version": "4.5.4", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz", "integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=4.2.0" - } + "dev": true }, "node_modules/union-value": { "version": "1.0.1", diff --git a/node_modules/@babel/parser/lib/index.js b/node_modules/@babel/parser/lib/index.js index 7cfd5b881..5dc6788a9 100644 --- a/node_modules/@babel/parser/lib/index.js +++ b/node_modules/@babel/parser/lib/index.js @@ -2,59 +2,14 @@ Object.defineProperty(exports, '__esModule', { value: true }); -const lineBreak = /\r\n?|[\n\u2028\u2029]/; -const lineBreakG = new RegExp(lineBreak.source, "g"); -function isNewLine(code) { - switch (code) { - case 10: - case 13: - case 8232: - case 8233: - return true; - - default: - return false; - } -} -const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; -const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y; -const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y"); -function isWhitespace(code) { - switch (code) { - case 0x0009: - case 0x000b: - case 0x000c: - case 32: - case 160: - case 5760: - case 0x2000: - case 0x2001: - case 0x2002: - case 0x2003: - case 0x2004: - case 0x2005: - case 0x2006: - case 0x2007: - case 0x2008: - case 0x2009: - case 0x200a: - case 0x202f: - case 0x205f: - case 0x3000: - case 0xfeff: - return true; - - default: - return false; - } -} - class Position { - constructor(line, col) { + constructor(line, col, index) { this.line = void 0; this.column = void 0; + this.index = void 0; this.line = line; this.column = col; + indexes.set(this, index); } } @@ -69,25 +24,13 @@ class SourceLocation { } } -function getLineInfo(input, offset) { - let line = 1; - let lineStart = 0; - let match; - lineBreakG.lastIndex = 0; - - while ((match = lineBreakG.exec(input)) && match.index < offset) { - line++; - lineStart = lineBreakG.lastIndex; - } - - return new Position(line, offset - lineStart); -} +const indexes = new WeakMap(); function createPositionWithColumnOffset(position, columnOffset) { const { line, column } = position; - return new Position(line, column + columnOffset); + return new Position(line, column + columnOffset, indexes.get(position) + columnOffset); } class BaseParser { @@ -509,28 +452,22 @@ function makeErrorTemplates(messages, code, syntaxPlugin) { return Object.freeze(templates); } class ParserError extends CommentsParser { - getLocationForPosition(pos) { - let loc; - if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos); - return loc; - } - - raise(pos, { + raise({ code, reasonCode, template - }, ...params) { - return this.raiseWithData(pos, { + }, origin, ...params) { + return this.raiseWithData(origin.node ? origin.node.loc.start : origin.at, { code, reasonCode }, template, ...params); } - raiseOverwrite(pos, { + raiseOverwrite(loc, { code, template }, ...params) { - const loc = this.getLocationForPosition(pos); + const pos = indexes.get(loc); const message = template.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`; if (this.options.errorRecovery) { @@ -556,8 +493,8 @@ class ParserError extends CommentsParser { }, message); } - raiseWithData(pos, data, errorTemplate, ...params) { - const loc = this.getLocationForPosition(pos); + raiseWithData(loc, data, errorTemplate, ...params) { + const pos = indexes.get(loc); const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`; return this._raise(Object.assign({ loc, @@ -645,9 +582,9 @@ var estree = (superClass => class extends superClass { const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start); expression.value = directiveLiteral.extra.expressionValue; expression.raw = directiveLiteral.extra.raw; - stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end); + stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.loc.end); stmt.directive = directiveLiteral.extra.raw.slice(1, -1); - return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end); + return this.finishNodeAt(stmt, "ExpressionStatement", directive.loc.end); } initFunction(node, isAsync) { @@ -821,9 +758,13 @@ var estree = (superClass => class extends superClass { toAssignableObjectExpressionProp(prop, ...args) { if (prop.kind === "get" || prop.kind === "set") { - this.raise(prop.key.start, ErrorMessages.PatternHasAccessor); + this.raise(ErrorMessages.PatternHasAccessor, { + node: prop.key + }); } else if (prop.method) { - this.raise(prop.key.start, ErrorMessages.PatternHasMethod); + this.raise(ErrorMessages.PatternHasMethod, { + node: prop.key + }); } else { super.toAssignableObjectExpressionProp(prop, ...args); } @@ -1461,9 +1402,6 @@ function tokenIsTemplate(token) { function getExportedToken(token) { return tokenTypes[token]; } -function isTokenType(obj) { - return typeof obj === "number"; -} { tokenTypes[8].updateContext = context => { context.pop(); @@ -1624,7 +1562,6 @@ class ScopeHandler { constructor(raise, inModule) { this.scopeStack = []; this.undefinedExports = new Map(); - this.undefinedPrivateNames = new Map(); this.raise = raise; this.inModule = inModule; } @@ -1690,11 +1627,11 @@ class ScopeHandler { return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM); } - declareName(name, bindingType, pos) { + declareName(name, bindingType, loc) { let scope = this.currentScope(); if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) { - this.checkRedeclarationInScope(scope, name, bindingType, pos); + this.checkRedeclarationInScope(scope, name, bindingType, loc); if (bindingType & BIND_SCOPE_FUNCTION) { scope.functions.add(name); @@ -1708,7 +1645,7 @@ class ScopeHandler { } else if (bindingType & BIND_SCOPE_VAR) { for (let i = this.scopeStack.length - 1; i >= 0; --i) { scope = this.scopeStack[i]; - this.checkRedeclarationInScope(scope, name, bindingType, pos); + this.checkRedeclarationInScope(scope, name, bindingType, loc); scope.var.add(name); this.maybeExportDefined(scope, name); if (scope.flags & SCOPE_VAR) break; @@ -1726,9 +1663,11 @@ class ScopeHandler { } } - checkRedeclarationInScope(scope, name, bindingType, pos) { + checkRedeclarationInScope(scope, name, bindingType, loc) { if (this.isRedeclaredInScope(scope, name, bindingType)) { - this.raise(pos, ErrorMessages.VarRedeclaration, name); + this.raise(ErrorMessages.VarRedeclaration, { + at: loc + }, name); } } @@ -1753,7 +1692,7 @@ class ScopeHandler { const topLevelScope = this.scopeStack[0]; if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) { - this.undefinedExports.set(name, id.start); + this.undefinedExports.set(name, id.loc.start); } } @@ -1800,11 +1739,11 @@ class FlowScopeHandler extends ScopeHandler { return new FlowScope(flags); } - declareName(name, bindingType, pos) { + declareName(name, bindingType, loc) { const scope = this.currentScope(); if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) { - this.checkRedeclarationInScope(scope, name, bindingType, pos); + this.checkRedeclarationInScope(scope, name, bindingType, loc); this.maybeExportDefined(scope, name); scope.declareFunctions.add(name); return; @@ -1831,6 +1770,53 @@ class FlowScopeHandler extends ScopeHandler { } +const lineBreak = /\r\n?|[\n\u2028\u2029]/; +const lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + switch (code) { + case 10: + case 13: + case 8232: + case 8233: + return true; + + default: + return false; + } +} +const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y; +const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y"); +function isWhitespace(code) { + switch (code) { + case 0x0009: + case 0x000b: + case 0x000c: + case 32: + case 160: + case 5760: + case 0x2000: + case 0x2001: + case 0x2002: + case 0x2003: + case 0x2004: + case 0x2005: + case 0x2006: + case 0x2007: + case 0x2008: + case 0x2009: + case 0x200a: + case 0x202f: + case 0x205f: + case 0x3000: + case 0xfeff: + return true; + + default: + return false; + } +} + class State { constructor() { this.strict = void 0; @@ -1866,7 +1852,6 @@ class State { this.lastTokEndLoc = null; this.lastTokStartLoc = null; this.lastTokStart = 0; - this.lastTokEnd = 0; this.context = [types.brace]; this.canStartJSXElement = true; this.containsEsc = false; @@ -1883,11 +1868,11 @@ class State { this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module"; this.curLine = startLine; this.lineStart = -startColumn; - this.startLoc = this.endLoc = new Position(startLine, startColumn); + this.startLoc = this.endLoc = new Position(startLine, startColumn, 0); } curPosition() { - return new Position(this.curLine, this.pos - this.lineStart); + return new Position(this.curLine, this.pos - this.lineStart, this.pos); } clone(skipArrays) { @@ -1958,7 +1943,6 @@ class Tokenizer extends ParserError { this.pushToken(new Token(this.state)); } - this.state.lastTokEnd = this.state.end; this.state.lastTokStart = this.state.start; this.state.lastTokEndLoc = this.state.endLoc; this.state.lastTokStartLoc = this.state.startLoc; @@ -1985,9 +1969,13 @@ class Tokenizer extends ParserError { type: state.type, start: state.start, end: state.end, - lastTokEnd: state.end, context: [this.curContext()], - inType: state.inType + inType: state.inType, + startLoc: state.startLoc, + lastTokEndLoc: state.lastTokEndLoc, + curLine: state.curLine, + lineStart: state.lineStart, + curPosition: state.curPosition }; } @@ -2033,7 +2021,12 @@ class Tokenizer extends ParserError { this.state.strict = strict; if (strict) { - this.state.strictErrors.forEach((message, pos) => this.raise(pos, message)); + this.state.strictErrors.forEach(({ + message, + loc + }) => this.raise(message, { + at: loc + })); this.state.strictErrors.clear(); } } @@ -2060,7 +2053,13 @@ class Tokenizer extends ParserError { if (!this.isLookahead) startLoc = this.state.curPosition(); const start = this.state.pos; const end = this.input.indexOf("*/", start + 2); - if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment); + + if (end === -1) { + throw this.raise(ErrorMessages.UnterminatedComment, { + at: this.state.curPosition() + }); + } + this.state.pos = end + 2; lineBreakG.lastIndex = start + 2; @@ -2218,12 +2217,12 @@ class Tokenizer extends ParserError { finishToken(type, val) { this.state.end = this.state.pos; + this.state.endLoc = this.state.curPosition(); const prevType = this.state.type; this.state.type = type; this.state.value = val; if (!this.isLookahead) { - this.state.endLoc = this.state.curPosition(); this.updateContext(prevType); } } @@ -2242,14 +2241,18 @@ class Tokenizer extends ParserError { const next = this.codePointAtPos(nextPos); if (next >= 48 && next <= 57) { - throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash); + throw this.raise(ErrorMessages.UnexpectedDigitAfterHash, { + at: this.state.curPosition() + }); } if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { this.expectPlugin("recordAndTuple"); if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") { - throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType); + throw this.raise(next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType, { + at: this.state.curPosition() + }); } this.state.pos += 2; @@ -2353,7 +2356,9 @@ class Tokenizer extends ParserError { if (this.hasPlugin("recordAndTuple") && next === 125) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { - throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType); + throw this.raise(ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType, { + at: this.state.curPosition() + }); } this.state.pos += 2; @@ -2363,7 +2368,9 @@ class Tokenizer extends ParserError { if (this.hasPlugin("recordAndTuple") && next === 93) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { - throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType); + throw this.raise(ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType, { + at: this.state.curPosition() + }); } this.state.pos += 2; @@ -2520,7 +2527,9 @@ class Tokenizer extends ParserError { case 91: if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { - throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType); + throw this.raise(ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType, { + at: this.state.curPosition() + }); } this.state.pos += 2; @@ -2540,7 +2549,9 @@ class Tokenizer extends ParserError { case 123: if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { - throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType); + throw this.raise(ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType, { + at: this.state.curPosition() + }); } this.state.pos += 2; @@ -2673,7 +2684,9 @@ class Tokenizer extends ParserError { } - throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code)); + throw this.raise(ErrorMessages.InvalidOrUnexpectedToken, { + at: this.state.curPosition() + }, String.fromCodePoint(code)); } finishOp(type, size) { @@ -2683,6 +2696,7 @@ class Tokenizer extends ParserError { } readRegexp() { + const startLoc = this.state.startLoc; const start = this.state.start + 1; let escaped, inClass; let { @@ -2691,13 +2705,17 @@ class Tokenizer extends ParserError { for (;; ++pos) { if (pos >= this.length) { - throw this.raise(start, ErrorMessages.UnterminatedRegExp); + throw this.raise(ErrorMessages.UnterminatedRegExp, { + at: createPositionWithColumnOffset(startLoc, 1) + }); } const ch = this.input.charCodeAt(pos); if (isNewLine(ch)) { - throw this.raise(start, ErrorMessages.UnterminatedRegExp); + throw this.raise(ErrorMessages.UnterminatedRegExp, { + at: createPositionWithColumnOffset(startLoc, 1) + }); } if (escaped) { @@ -2725,10 +2743,14 @@ class Tokenizer extends ParserError { if (VALID_REGEX_FLAGS.has(cp)) { if (mods.includes(char)) { - this.raise(pos + 1, ErrorMessages.DuplicateRegExpFlags); + this.raise(ErrorMessages.DuplicateRegExpFlags, { + at: createPositionWithColumnOffset(startLoc, pos + 2 - start) + }); } } else if (isIdentifierChar(cp) || cp === 92) { - this.raise(pos + 1, ErrorMessages.MalformedRegExpFlags); + this.raise(ErrorMessages.MalformedRegExpFlags, { + at: createPositionWithColumnOffset(startLoc, pos + 2 - start) + }); } else { break; } @@ -2760,13 +2782,19 @@ class Tokenizer extends ParserError { const next = this.input.charCodeAt(this.state.pos + 1); if (allowedSiblings.indexOf(next) === -1) { - this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator); + this.raise(ErrorMessages.UnexpectedNumericSeparator, { + at: this.state.curPosition() + }); } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) { - this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator); + this.raise(ErrorMessages.UnexpectedNumericSeparator, { + at: this.state.curPosition() + }); } if (!allowNumSeparator) { - this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence); + this.raise(ErrorMessages.NumericSeparatorInEscapeSequence, { + at: this.state.curPosition() + }); } ++this.state.pos; @@ -2786,7 +2814,9 @@ class Tokenizer extends ParserError { if (val >= radix) { if (this.options.errorRecovery && val <= 9) { val = 0; - this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix); + this.raise(ErrorMessages.InvalidDigit, { + at: this.state.curPosition() + }, radix); } else if (forceLen) { val = 0; invalid = true; @@ -2807,13 +2837,15 @@ class Tokenizer extends ParserError { } readRadixNumber(radix) { - const start = this.state.pos; + const startLoc = this.state.curPosition(); let isBigInt = false; this.state.pos += 2; const val = this.readInt(radix); if (val == null) { - this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix); + this.raise(ErrorMessages.InvalidDigit, { + at: createPositionWithColumnOffset(startLoc, 2) + }, radix); } const next = this.input.charCodeAt(this.state.pos); @@ -2822,15 +2854,19 @@ class Tokenizer extends ParserError { ++this.state.pos; isBigInt = true; } else if (next === 109) { - throw this.raise(start, ErrorMessages.InvalidDecimal); + throw this.raise(ErrorMessages.InvalidDecimal, { + at: startLoc + }); } if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { - throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier); + throw this.raise(ErrorMessages.NumberIdentifier, { + at: this.state.curPosition() + }); } if (isBigInt) { - const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, ""); + const str = this.input.slice(indexes.get(startLoc), this.state.pos).replace(/[_n]/g, ""); this.finishToken(127, str); return; } @@ -2840,6 +2876,7 @@ class Tokenizer extends ParserError { readNumber(startsWithDot) { const start = this.state.pos; + const startLoc = this.state.curPosition(); let isFloat = false; let isBigInt = false; let isDecimal = false; @@ -2847,20 +2884,24 @@ class Tokenizer extends ParserError { let isOctal = false; if (!startsWithDot && this.readInt(10) === null) { - this.raise(start, ErrorMessages.InvalidNumber); + this.raise(ErrorMessages.InvalidNumber, { + at: this.state.curPosition() + }); } const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; if (hasLeadingZero) { const integer = this.input.slice(start, this.state.pos); - this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral); + this.recordStrictModeErrors(ErrorMessages.StrictOctalLiteral, startLoc); if (!this.state.strict) { const underscorePos = integer.indexOf("_"); if (underscorePos > 0) { - this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator); + this.raise(ErrorMessages.ZeroDigitNumericSeparator, { + at: createPositionWithColumnOffset(startLoc, underscorePos) + }); } } @@ -2884,7 +2925,9 @@ class Tokenizer extends ParserError { } if (this.readInt(10) === null) { - this.raise(start, ErrorMessages.InvalidOrMissingExponent); + this.raise(ErrorMessages.InvalidOrMissingExponent, { + at: startLoc + }); } isFloat = true; @@ -2894,7 +2937,9 @@ class Tokenizer extends ParserError { if (next === 110) { if (isFloat || hasLeadingZero) { - this.raise(start, ErrorMessages.InvalidBigIntLiteral); + this.raise(ErrorMessages.InvalidBigIntLiteral, { + at: startLoc + }); } ++this.state.pos; @@ -2902,10 +2947,12 @@ class Tokenizer extends ParserError { } if (next === 109) { - this.expectPlugin("decimal", this.state.pos); + this.expectPlugin("decimal", this.state.curPosition()); if (hasExponent || hasLeadingZero) { - this.raise(start, ErrorMessages.InvalidDecimal); + this.raise(ErrorMessages.InvalidDecimal, { + at: startLoc + }); } ++this.state.pos; @@ -2913,7 +2960,9 @@ class Tokenizer extends ParserError { } if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { - throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier); + throw this.raise(ErrorMessages.NumberIdentifier, { + at: this.state.curPosition() + }); } const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); @@ -2937,13 +2986,15 @@ class Tokenizer extends ParserError { let code; if (ch === 123) { - const codePos = ++this.state.pos; + ++this.state.pos; code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid); ++this.state.pos; if (code !== null && code > 0x10ffff) { if (throwOnInvalid) { - this.raise(codePos, ErrorMessages.InvalidCodePoint); + this.raise(ErrorMessages.InvalidCodePoint, { + at: this.state.curPosition() + }); } else { return null; } @@ -2961,7 +3012,9 @@ class Tokenizer extends ParserError { for (;;) { if (this.state.pos >= this.length) { - throw this.raise(this.state.start, ErrorMessages.UnterminatedString); + throw this.raise(ErrorMessages.UnterminatedString, { + at: this.state.startLoc + }); } const ch = this.input.charCodeAt(this.state.pos); @@ -2976,7 +3029,9 @@ class Tokenizer extends ParserError { ++this.state.curLine; this.state.lineStart = this.state.pos; } else if (isNewLine(ch)) { - throw this.raise(this.state.start, ErrorMessages.UnterminatedString); + throw this.raise(ErrorMessages.UnterminatedString, { + at: this.state.startLoc + }); } else { ++this.state.pos; } @@ -2988,7 +3043,7 @@ class Tokenizer extends ParserError { readTemplateContinuation() { if (!this.match(8)) { - this.unexpected(this.state.start, 8); + this.unexpected(null, 8); } this.state.pos--; @@ -3003,7 +3058,9 @@ class Tokenizer extends ParserError { for (;;) { if (this.state.pos >= this.length) { - throw this.raise(this.state.start + 1, ErrorMessages.UnterminatedTemplate); + throw this.raise(ErrorMessages.UnterminatedTemplate, { + at: createPositionWithColumnOffset(this.state.startLoc, 1) + }); } const ch = this.input.charCodeAt(this.state.pos); @@ -3061,11 +3118,18 @@ class Tokenizer extends ParserError { } } - recordStrictModeErrors(pos, message) { - if (this.state.strict && !this.state.strictErrors.has(pos)) { - this.raise(pos, message); + recordStrictModeErrors(message, loc) { + const index = indexes.get(loc); + + if (this.state.strict && !this.state.strictErrors.has(index)) { + this.raise(message, { + at: loc + }); } else { - this.state.strictErrors.set(pos, message); + this.state.strictErrors.set(index, { + loc, + message + }); } } @@ -3123,12 +3187,12 @@ class Tokenizer extends ParserError { if (inTemplate) { return null; } else { - this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape); + this.recordStrictModeErrors(ErrorMessages.StrictNumericEscape, createPositionWithColumnOffset(this.state.curPosition(), -1)); } default: if (ch >= 48 && ch <= 55) { - const codePos = this.state.pos - 1; + const codePos = createPositionWithColumnOffset(this.state.curPosition(), -1); const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/); let octalStr = match[0]; let octal = parseInt(octalStr, 8); @@ -3145,7 +3209,7 @@ class Tokenizer extends ParserError { if (inTemplate) { return null; } else { - this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape); + this.recordStrictModeErrors(ErrorMessages.StrictNumericEscape, codePos); } } @@ -3157,14 +3221,16 @@ class Tokenizer extends ParserError { } readHexChar(len, forceLen, throwOnInvalid) { - const codePos = this.state.pos; + const codeLoc = this.state.curPosition(); const n = this.readInt(16, len, forceLen, false); if (n === null) { if (throwOnInvalid) { - this.raise(codePos, ErrorMessages.InvalidEscapeSequence); + this.raise(ErrorMessages.InvalidEscapeSequence, { + at: codeLoc + }); } else { - this.state.pos = codePos - 1; + this.state.pos = indexes.get(codeLoc) - 1; } } @@ -3189,11 +3255,13 @@ class Tokenizer extends ParserError { } else if (ch === 92) { this.state.containsEsc = true; word += this.input.slice(chunkStart, this.state.pos); - const escStart = this.state.pos; + const escStart = this.state.curPosition(); const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; if (this.input.charCodeAt(++this.state.pos) !== 117) { - this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape); + this.raise(ErrorMessages.MissingUnicodeEscape, { + at: this.state.curPosition() + }); chunkStart = this.state.pos - 1; continue; } @@ -3203,7 +3271,9 @@ class Tokenizer extends ParserError { if (esc !== null) { if (!identifierCheck(esc)) { - this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier); + this.raise(ErrorMessages.EscapedCharNotAnIdentifier, { + at: escStart + }); } word += String.fromCodePoint(esc); @@ -3235,7 +3305,9 @@ class Tokenizer extends ParserError { } = this.state; if (tokenIsKeyword(type) && this.state.containsEsc) { - this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, tokenLabelName(type)); + this.raise(ErrorMessages.InvalidEscapedReservedWord, { + at: this.state.startLoc + }, tokenLabelName(type)); } } @@ -3270,18 +3342,20 @@ class ClassScopeHandler { const oldClassScope = this.stack.pop(); const current = this.current(); - for (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) { + for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) { if (current) { if (!current.undefinedPrivateNames.has(name)) { - current.undefinedPrivateNames.set(name, pos); + current.undefinedPrivateNames.set(name, loc); } } else { - this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name); + this.raise(ErrorMessages.InvalidPrivateFieldResolution, { + at: loc + }, name); } } } - declarePrivateName(name, elementType, pos) { + declarePrivateName(name, elementType, loc) { const { privateNames, loneAccessors, @@ -3305,14 +3379,16 @@ class ClassScopeHandler { } if (redefined) { - this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name); + this.raise(ErrorMessages.PrivateNameRedeclaration, { + at: loc + }, name); } privateNames.add(name); undefinedPrivateNames.delete(name); } - usePrivateName(name, pos) { + usePrivateName(name, loc) { let classScope; for (classScope of this.stack) { @@ -3320,9 +3396,11 @@ class ClassScopeHandler { } if (classScope) { - classScope.undefinedPrivateNames.set(name, pos); + classScope.undefinedPrivateNames.set(name, loc); } else { - this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name); + this.raise(ErrorMessages.InvalidPrivateFieldResolution, { + at: loc + }, name); } } @@ -3355,12 +3433,15 @@ class ArrowHeadParsingScope extends ExpressionScope { this.errors = new Map(); } - recordDeclarationError(pos, template) { - this.errors.set(pos, template); + recordDeclarationError(message, loc) { + this.errors.set(indexes.get(loc), { + message, + loc + }); } - clearDeclarationError(pos) { - this.errors.delete(pos); + clearDeclarationError(loc) { + this.errors.delete(indexes.get(loc)); } iterateErrors(iterator) { @@ -3383,7 +3464,7 @@ class ExpressionScopeHandler { this.stack.pop(); } - recordParameterInitializerError(pos, template) { + recordParameterInitializerError(loc, template) { const { stack } = this; @@ -3392,7 +3473,7 @@ class ExpressionScopeHandler { while (!scope.isCertainlyParameterDeclaration()) { if (scope.canBeArrowParameterDeclaration()) { - scope.recordDeclarationError(pos, template); + scope.recordDeclarationError(template, loc); } else { return; } @@ -3400,25 +3481,29 @@ class ExpressionScopeHandler { scope = stack[--i]; } - this.raise(pos, template); + this.raise(template, { + at: loc + }); } - recordParenthesizedIdentifierError(pos, template) { + recordParenthesizedIdentifierError(template, loc) { const { stack } = this; const scope = stack[stack.length - 1]; if (scope.isCertainlyParameterDeclaration()) { - this.raise(pos, template); + this.raise(template, { + at: loc + }); } else if (scope.canBeArrowParameterDeclaration()) { - scope.recordDeclarationError(pos, template); + scope.recordDeclarationError(template, loc); } else { return; } } - recordAsyncArrowParametersError(pos, template) { + recordAsyncArrowParametersError(template, loc) { const { stack } = this; @@ -3427,7 +3512,7 @@ class ExpressionScopeHandler { while (scope.canBeArrowParameterDeclaration()) { if (scope.type === kMaybeAsyncArrowParameterDeclaration) { - scope.recordDeclarationError(pos, template); + scope.recordDeclarationError(template, loc); } scope = stack[--i]; @@ -3440,13 +3525,18 @@ class ExpressionScopeHandler { } = this; const currentScope = stack[stack.length - 1]; if (!currentScope.canBeArrowParameterDeclaration()) return; - currentScope.iterateErrors((template, pos) => { - this.raise(pos, template); + currentScope.iterateErrors(({ + message, + loc + }) => { + this.raise(message, { + at: loc + }); let i = stack.length - 2; let scope = stack[i]; while (scope.canBeArrowParameterDeclaration()) { - scope.clearDeclarationError(pos); + scope.clearDeclarationError(loc); scope = stack[--i]; } }); @@ -3510,10 +3600,18 @@ function functionFlags(isAsync, isGenerator) { } class UtilParser extends Tokenizer { - addExtra(node, key, val) { + addExtra(node, key, value, enumerable = true) { if (!node) return; const extra = node.extra = node.extra || {}; - extra[key] = val; + + if (enumerable) { + extra[key] = value; + } else { + Object.defineProperty(extra, key, { + enumerable, + value + }); + } } isContextual(token) { @@ -3546,7 +3644,15 @@ class UtilParser extends Tokenizer { } expectContextual(token, template) { - if (!this.eatContextual(token)) this.unexpected(null, template); + if (!this.eatContextual(token)) { + if (template != null) { + throw this.raise(template, { + at: this.state.startLoc + }); + } + + throw this.unexpected(null, token); + } } canInsertSemicolon() { @@ -3554,7 +3660,7 @@ class UtilParser extends Tokenizer { } hasPrecedingLineBreak() { - return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)); + return lineBreak.test(this.input.slice(indexes.get(this.state.lastTokEndLoc), this.state.start)); } hasFollowingLineBreak() { @@ -3568,37 +3674,35 @@ class UtilParser extends Tokenizer { semicolon(allowAsi = true) { if (allowAsi ? this.isLineTerminator() : this.eat(13)) return; - this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon); + this.raise(ErrorMessages.MissingSemicolon, { + at: this.state.lastTokEndLoc + }); } - expect(type, pos) { - this.eat(type) || this.unexpected(pos, type); + expect(type, loc) { + this.eat(type) || this.unexpected(loc, type); } assertNoSpace(message = "Unexpected space.") { - if (this.state.start > this.state.lastTokEnd) { - this.raise(this.state.lastTokEnd, { + if (this.state.start > indexes.get(this.state.lastTokEndLoc)) { + this.raise({ code: ErrorCodes.SyntaxError, reasonCode: "UnexpectedSpace", template: message + }, { + at: this.state.lastTokEndLoc }); } } - unexpected(pos, messageOrType = { - code: ErrorCodes.SyntaxError, - reasonCode: "UnexpectedToken", - template: "Unexpected token" - }) { - if (isTokenType(messageOrType)) { - messageOrType = { - code: ErrorCodes.SyntaxError, - reasonCode: "UnexpectedToken", - template: `Unexpected token, expected "${tokenLabelName(messageOrType)}"` - }; - } - - throw this.raise(pos != null ? pos : this.state.start, messageOrType); + unexpected(loc, type) { + throw this.raise({ + code: ErrorCodes.SyntaxError, + reasonCode: "UnexpectedToken", + template: type != null ? `Unexpected token, expected "${tokenLabelName(type)}"` : "Unexpected token" + }, { + at: loc != null ? loc : this.state.startLoc + }); } getPluginNamesFromConfigs(pluginConfigs) { @@ -3611,9 +3715,9 @@ class UtilParser extends Tokenizer { }); } - expectPlugin(pluginConfig, pos) { + expectPlugin(pluginConfig, loc) { if (!this.hasPlugin(pluginConfig)) { - throw this.raiseWithData(pos != null ? pos : this.state.start, { + throw this.raiseWithData(loc != null ? loc : this.state.startLoc, { missingPlugin: this.getPluginNamesFromConfigs([pluginConfig]) }, `This experimental syntax requires enabling the parser plugin: ${JSON.stringify(pluginConfig)}.`); } @@ -3621,9 +3725,9 @@ class UtilParser extends Tokenizer { return true; } - expectOnePlugin(pluginConfigs, pos) { + expectOnePlugin(pluginConfigs) { if (!pluginConfigs.some(c => this.hasPlugin(c))) { - throw this.raiseWithData(pos != null ? pos : this.state.start, { + throw this.raiseWithData(this.state.startLoc, { missingPlugin: this.getPluginNamesFromConfigs(pluginConfigs) }, `This experimental syntax requires enabling one of the following parser plugin(s): ${pluginConfigs.map(c => JSON.stringify(c)).join(", ")}.`); } @@ -3691,26 +3795,30 @@ class UtilParser extends Tokenizer { checkExpressionErrors(refExpressionErrors, andThrow) { if (!refExpressionErrors) return false; const { - shorthandAssign, - doubleProto, - optionalParameters + shorthandAssignLoc, + doubleProtoLoc, + optionalParametersLoc } = refExpressionErrors; - const hasErrors = shorthandAssign + doubleProto + optionalParameters > -3; + const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc; if (!andThrow) { return hasErrors; - } else if (hasErrors) { - if (shorthandAssign >= 0) { - this.raise(shorthandAssign, ErrorMessages.InvalidCoverInitializedName); - } + } - if (doubleProto >= 0) { - this.raise(doubleProto, ErrorMessages.DuplicateProto); - } + if (shorthandAssignLoc != null) { + this.raise(ErrorMessages.InvalidCoverInitializedName, { + at: shorthandAssignLoc + }); + } - if (optionalParameters >= 0) { - this.unexpected(optionalParameters); - } + if (doubleProtoLoc != null) { + this.raise(ErrorMessages.DuplicateProto, { + at: doubleProtoLoc + }); + } + + if (optionalParametersLoc != null) { + this.unexpected(optionalParametersLoc); } } @@ -3783,9 +3891,9 @@ class UtilParser extends Tokenizer { } class ExpressionErrors { constructor() { - this.shorthandAssign = -1; - this.doubleProto = -1; - this.optionalParameters = -1; + this.shorthandAssignLoc = null; + this.doubleProtoLoc = null; + this.optionalParametersLoc = null; } } @@ -3893,15 +4001,15 @@ class NodeUtils extends UtilParser { } finishNode(node, type) { - return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc); + return this.finishNodeAt(node, type, this.state.lastTokEndLoc); } - finishNodeAt(node, type, pos, loc) { + finishNodeAt(node, type, endLoc) { node.type = type; - node.end = pos; - node.loc.end = loc; - if (this.options.ranges) node.range[1] = pos; + node.end = indexes.get(endLoc); + node.loc.end = endLoc; + if (this.options.ranges) node.range[1] = node.end; if (this.options.attachComment) this.processComment(node); return node; } @@ -3912,10 +4020,10 @@ class NodeUtils extends UtilParser { if (this.options.ranges) node.range[0] = start; } - resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) { - node.end = end; + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + node.end = indexes.get(endLoc); node.loc.end = endLoc; - if (this.options.ranges) node.range[1] = end; + if (this.options.ranges) node.range[1] = node.end; } resetStartLocationFromNode(node, locationNode) { @@ -4061,12 +4169,14 @@ var flow = (superClass => class extends superClass { flowParsePredicate() { const node = this.startNode(); - const moduloPos = this.state.start; + const moduloLoc = this.state.startLoc; this.next(); this.expectContextual(103); - if (this.state.lastTokStart > moduloPos + 1) { - this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks); + if (this.state.lastTokStart > indexes.get(moduloLoc) + 1) { + this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, { + at: moduloLoc + }); } if (this.eat(10)) { @@ -4129,7 +4239,7 @@ var flow = (superClass => class extends superClass { id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); this.resetEndLocation(id); this.semicolon(); - this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start); + this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.loc.start); return this.finishNode(node, "DeclareFunction"); } @@ -4145,7 +4255,9 @@ var flow = (superClass => class extends superClass { return this.flowParseDeclareModuleExports(node); } else { if (insideModule) { - this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule); + this.raise(FlowErrors.NestedDeclareModule, { + at: this.state.lastTokStartLoc + }); } return this.flowParseDeclareModule(node); @@ -4166,7 +4278,7 @@ var flow = (superClass => class extends superClass { flowParseDeclareVariable(node) { this.next(); node.id = this.flowParseTypeAnnotatableIdentifier(true); - this.scope.declareName(node.id.name, BIND_VAR, node.id.start); + this.scope.declareName(node.id.name, BIND_VAR, node.id.loc.start); this.semicolon(); return this.finishNode(node, "DeclareVariable"); } @@ -4191,7 +4303,9 @@ var flow = (superClass => class extends superClass { this.next(); if (!this.isContextual(122) && !this.match(83)) { - this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule); + this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, { + at: this.state.lastTokStartLoc + }); } this.parseImport(bodyNode); @@ -4211,17 +4325,23 @@ var flow = (superClass => class extends superClass { body.forEach(bodyElement => { if (isEsModuleType(bodyElement)) { if (kind === "CommonJS") { - this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind); + this.raise(FlowErrors.AmbiguousDeclareModuleKind, { + node: bodyElement + }); } kind = "ES"; } else if (bodyElement.type === "DeclareModuleExports") { if (hasModuleExport) { - this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports); + this.raise(FlowErrors.DuplicateDeclareModuleExports, { + node: bodyElement + }); } if (kind === "ES") { - this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind); + this.raise(FlowErrors.AmbiguousDeclareModuleKind, { + node: bodyElement + }); } kind = "CommonJS"; @@ -4249,7 +4369,9 @@ var flow = (superClass => class extends superClass { if (this.match(71) || this.isLet() || (this.isContextual(122) || this.isContextual(121)) && !insideModule) { const label = this.state.value; const suggestion = exportSuggestions[label]; - throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion); + throw this.raise(FlowErrors.UnsupportedDeclareExportKind, { + at: this.state.startLoc + }, label, suggestion); } if (this.match(70) || this.match(64) || this.match(76) || this.isContextual(123)) { @@ -4303,7 +4425,7 @@ var flow = (superClass => class extends superClass { flowParseInterfaceish(node, isClass = false) { node.id = this.flowParseRestrictedIdentifier(!isClass, true); - this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start); + this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.loc.start); if (this.match(45)) { node.typeParameters = this.flowParseTypeParameterDeclaration(); @@ -4366,23 +4488,27 @@ var flow = (superClass => class extends superClass { checkNotUnderscore(word) { if (word === "_") { - this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore); + this.raise(FlowErrors.UnexpectedReservedUnderscore, { + at: this.state.startLoc + }); } } checkReservedType(word, startLoc, declaration) { if (!reservedTypes.has(word)) return; - this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word); + this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, { + at: startLoc + }, word); } flowParseRestrictedIdentifier(liberal, declaration) { - this.checkReservedType(this.state.value, this.state.start, declaration); + this.checkReservedType(this.state.value, this.state.startLoc, declaration); return this.parseIdentifier(liberal); } flowParseTypeAlias(node) { node.id = this.flowParseRestrictedIdentifier(false, true); - this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start); + this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.loc.start); if (this.match(45)) { node.typeParameters = this.flowParseTypeParameterDeclaration(); @@ -4398,7 +4524,7 @@ var flow = (superClass => class extends superClass { flowParseOpaqueType(node, declare) { this.expectContextual(122); node.id = this.flowParseRestrictedIdentifier(true, true); - this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start); + this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.loc.start); if (this.match(45)) { node.typeParameters = this.flowParseTypeParameterDeclaration(); @@ -4423,7 +4549,7 @@ var flow = (superClass => class extends superClass { } flowParseTypeParameter(requireDefault = false) { - const nodeStart = this.state.start; + const nodeStartLoc = this.state.startLoc; const node = this.startNode(); const variance = this.flowParseVariance(); const ident = this.flowParseTypeAnnotatableIdentifier(); @@ -4436,7 +4562,9 @@ var flow = (superClass => class extends superClass { node.default = this.flowParseType(); } else { if (requireDefault) { - this.raise(nodeStart, FlowErrors.MissingTypeParamDefault); + this.raise(FlowErrors.MissingTypeParamDefault, { + at: nodeStartLoc + }); } } @@ -4660,8 +4788,8 @@ var flow = (superClass => class extends superClass { while (!this.match(endDelim)) { let isStatic = false; - let protoStart = null; - let inexactStart = null; + let protoStartLoc = null; + let inexactStartLoc = null; const node = this.startNode(); if (allowProto && this.isContextual(111)) { @@ -4669,7 +4797,7 @@ var flow = (superClass => class extends superClass { if (lookahead.type !== 14 && lookahead.type !== 17) { this.next(); - protoStart = this.state.start; + protoStartLoc = this.state.startLoc; allowStatic = false; } } @@ -4686,13 +4814,13 @@ var flow = (superClass => class extends superClass { const variance = this.flowParseVariance(); if (this.eat(0)) { - if (protoStart != null) { - this.unexpected(protoStart); + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); } if (this.eat(0)) { if (variance) { - this.unexpected(variance.start); + this.unexpected(variance.loc.start); } nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); @@ -4700,12 +4828,12 @@ var flow = (superClass => class extends superClass { nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); } } else if (this.match(10) || this.match(45)) { - if (protoStart != null) { - this.unexpected(protoStart); + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); } if (variance) { - this.unexpected(variance.start); + this.unexpected(variance.loc.start); } nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); @@ -4721,11 +4849,11 @@ var flow = (superClass => class extends superClass { } } - const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); + const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); if (propOrInexact === null) { inexact = true; - inexactStart = this.state.lastTokStart; + inexactStartLoc = this.state.lastTokStartLoc; } else { nodeStart.properties.push(propOrInexact); } @@ -4733,8 +4861,10 @@ var flow = (superClass => class extends superClass { this.flowObjectTypeSemicolon(); - if (inexactStart && !this.match(8) && !this.match(9)) { - this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject); + if (inexactStartLoc && !this.match(8) && !this.match(9)) { + this.raise(FlowErrors.UnexpectedExplicitInexactInObject, { + at: inexactStartLoc + }); } } @@ -4749,34 +4879,44 @@ var flow = (superClass => class extends superClass { return out; } - flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) { + flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) { if (this.eat(21)) { const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9); if (isInexactToken) { if (!allowSpread) { - this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject); + this.raise(FlowErrors.InexactInsideNonObject, { + at: this.state.lastTokStartLoc + }); } else if (!allowInexact) { - this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact); + this.raise(FlowErrors.InexactInsideExact, { + at: this.state.lastTokStartLoc + }); } if (variance) { - this.raise(variance.start, FlowErrors.InexactVariance); + this.raise(FlowErrors.InexactVariance, { + node: variance + }); } return null; } if (!allowSpread) { - this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType); + this.raise(FlowErrors.UnexpectedSpreadType, { + at: this.state.lastTokStartLoc + }); } - if (protoStart != null) { - this.unexpected(protoStart); + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); } if (variance) { - this.raise(variance.start, FlowErrors.SpreadVariance); + this.raise(FlowErrors.SpreadVariance, { + node: variance + }); } node.argument = this.flowParseType(); @@ -4784,19 +4924,19 @@ var flow = (superClass => class extends superClass { } else { node.key = this.flowParseObjectPropertyKey(); node.static = isStatic; - node.proto = protoStart != null; + node.proto = protoStartLoc != null; node.kind = kind; let optional = false; if (this.match(45) || this.match(10)) { node.method = true; - if (protoStart != null) { - this.unexpected(protoStart); + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); } if (variance) { - this.unexpected(variance.start); + this.unexpected(variance.loc.start); } node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start)); @@ -4806,7 +4946,9 @@ var flow = (superClass => class extends superClass { } if (!allowSpread && node.key.name === "constructor" && node.value.this) { - this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor); + this.raise(FlowErrors.ThisParamBannedInConstructor, { + node: node.value.this + }); } } else { if (kind !== "init") this.unexpected(); @@ -4827,23 +4969,24 @@ var flow = (superClass => class extends superClass { flowCheckGetterSetterParams(property) { const paramCount = property.kind === "get" ? 0 : 1; - const start = property.start; const length = property.value.params.length + (property.value.rest ? 1 : 0); if (property.value.this) { - this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam); + this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, { + node: property.value.this + }); } if (length !== paramCount) { - if (property.kind === "get") { - this.raise(start, ErrorMessages.BadGetterArity); - } else { - this.raise(start, ErrorMessages.BadSetterArity); - } + this.raise(property.kind === "get" ? ErrorMessages.BadGetterArity : ErrorMessages.BadSetterArity, { + node: property + }); } if (property.kind === "set" && property.value.rest) { - this.raise(start, ErrorMessages.BadSetterRestParameter); + this.raise(ErrorMessages.BadSetterRestParameter, { + node: property + }); } } @@ -4912,7 +5055,9 @@ var flow = (superClass => class extends superClass { if (lh.type === 14 || lh.type === 17) { if (isThis && !first) { - this.raise(node.start, FlowErrors.ThisParamMustBeFirst); + this.raise(FlowErrors.ThisParamMustBeFirst, { + node + }); } name = this.parseIdentifier(isThis); @@ -4921,7 +5066,9 @@ var flow = (superClass => class extends superClass { optional = true; if (isThis) { - this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional); + this.raise(FlowErrors.ThisParamMayNotBeOptional, { + node + }); } } @@ -5113,7 +5260,9 @@ var flow = (superClass => class extends superClass { return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node); } - throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand); + throw this.raise(FlowErrors.UnexpectedSubtractionOperand, { + at: this.state.startLoc + }); } throw this.unexpected(); @@ -5285,7 +5434,7 @@ var flow = (superClass => class extends superClass { typeCastToParameter(node) { node.expression.typeAnnotation = node.typeAnnotation; - this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); return node.expression; } @@ -5445,7 +5594,9 @@ var flow = (superClass => class extends superClass { } if (failed && valid.length > 1) { - this.raise(state.start, FlowErrors.AmbiguousConditionalArrow); + this.raise(FlowErrors.AmbiguousConditionalArrow, { + at: state.startLoc + }); } if (failed && valid.length === 1) { @@ -5511,7 +5662,7 @@ var flow = (superClass => class extends superClass { finishArrowValidation(node) { var _node$extra; - this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false); + this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false); this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW); super.checkParams(node, false, true); this.scope.exit(); @@ -5614,11 +5765,13 @@ var flow = (superClass => class extends superClass { } maybeParseExportNamespaceSpecifier(node) { - const pos = this.state.start; + const { + startLoc + } = this.state; const hasNamespace = super.maybeParseExportNamespaceSpecifier(node); if (hasNamespace && node.exportKind === "type") { - this.unexpected(pos); + this.unexpected(startLoc); } return hasNamespace; @@ -5633,7 +5786,9 @@ var flow = (superClass => class extends superClass { } parseClassMember(classBody, member, state) { - const pos = this.state.start; + const { + startLoc + } = this.state; if (this.isContextual(117)) { if (this.parseClassMemberFromModifier(classBody, member)) { @@ -5647,9 +5802,13 @@ var flow = (superClass => class extends superClass { if (member.declare) { if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") { - this.raise(pos, FlowErrors.DeclareClassElement); + this.raise(FlowErrors.DeclareClassElement, { + at: startLoc + }); } else if (member.value) { - this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer); + this.raise(FlowErrors.DeclareClassFieldInitializer, { + node: member.value + }); } } } @@ -5663,7 +5822,9 @@ var flow = (superClass => class extends superClass { const fullWord = "@@" + word; if (!this.isIterator(word) || !this.state.inType) { - this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, fullWord); + this.raise(ErrorMessages.InvalidIdentifier, { + at: this.state.curPosition() + }, fullWord); } this.finishToken(124, fullWord); @@ -5706,7 +5867,7 @@ var flow = (superClass => class extends superClass { } } - toAssignableList(exprList, trailingCommaPos, isLHS) { + toAssignableList(exprList, trailingCommaLoc, isLHS) { for (let i = 0; i < exprList.length; i++) { const expr = exprList[i]; @@ -5715,7 +5876,7 @@ var flow = (superClass => class extends superClass { } } - return super.toAssignableList(exprList, trailingCommaPos, isLHS); + return super.toAssignableList(exprList, trailingCommaLoc, isLHS); } toReferencedList(exprList, isParenthesizedExpr) { @@ -5725,7 +5886,9 @@ var flow = (superClass => class extends superClass { const expr = exprList[i]; if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { - this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern); + this.raise(FlowErrors.TypeCastInPattern, { + node: expr.typeAnnotation + }); } } @@ -5778,7 +5941,7 @@ var flow = (superClass => class extends superClass { pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { if (method.variance) { - this.unexpected(method.variance.start); + this.unexpected(method.variance.loc.start); } delete method.variance; @@ -5793,20 +5956,24 @@ var flow = (superClass => class extends superClass { const params = method.params; if (params.length > 0 && this.isThisParam(params[0])) { - this.raise(method.start, FlowErrors.ThisParamBannedInConstructor); + this.raise(FlowErrors.ThisParamBannedInConstructor, { + node: method + }); } } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) { const params = method.value.params; if (params.length > 0 && this.isThisParam(params[0])) { - this.raise(method.start, FlowErrors.ThisParamBannedInConstructor); + this.raise(FlowErrors.ThisParamBannedInConstructor, { + node: method + }); } } } pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { if (method.variance) { - this.unexpected(method.variance.start); + this.unexpected(method.variance.loc.start); } delete method.variance; @@ -5852,9 +6019,13 @@ var flow = (superClass => class extends superClass { const param = params[0]; if (this.isThisParam(param) && method.kind === "get") { - this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam); + this.raise(FlowErrors.GetterMayNotHaveThisParam, { + node: param + }); } else if (this.isThisParam(param)) { - this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam); + this.raise(FlowErrors.SetterMayNotHaveThisParam, { + node: param + }); } } } @@ -5865,7 +6036,7 @@ var flow = (superClass => class extends superClass { parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { if (prop.variance) { - this.unexpected(prop.variance.start); + this.unexpected(prop.variance.loc.start); } delete prop.variance; @@ -5886,11 +6057,15 @@ var flow = (superClass => class extends superClass { parseAssignableListItemTypes(param) { if (this.eat(17)) { if (param.type !== "Identifier") { - this.raise(param.start, FlowErrors.PatternIsOptional); + this.raise(FlowErrors.PatternIsOptional, { + node: param + }); } if (this.isThisParam(param)) { - this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional); + this.raise(FlowErrors.ThisParamMayNotBeOptional, { + node: param + }); } param.optional = true; @@ -5899,11 +6074,15 @@ var flow = (superClass => class extends superClass { if (this.match(14)) { param.typeAnnotation = this.flowParseTypeAnnotation(); } else if (this.isThisParam(param)) { - this.raise(param.start, FlowErrors.ThisParamAnnotationRequired); + this.raise(FlowErrors.ThisParamAnnotationRequired, { + node: param + }); } if (this.match(29) && this.isThisParam(param)) { - this.raise(param.start, FlowErrors.ThisParamNoDefault); + this.raise(FlowErrors.ThisParamNoDefault, { + node: param + }); } this.resetEndLocation(param); @@ -5914,7 +6093,9 @@ var flow = (superClass => class extends superClass { const node = super.parseMaybeDefault(startPos, startLoc, left); if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { - this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer); + this.raise(FlowErrors.TypeBeforeInitializer, { + node: node.typeAnnotation + }); } return node; @@ -5951,7 +6132,7 @@ var flow = (superClass => class extends superClass { } = lh; if (kind === "type" && type === 51) { - this.unexpected(lh.start); + this.unexpected(null, lh.type); } if (isMaybeDefaultImport(type) || type === 5 || type === 51) { @@ -5995,7 +6176,9 @@ var flow = (superClass => class extends superClass { specifier.importKind = specifierTypeKind; } else { if (importedIsString) { - throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value); + throw this.raise(ErrorMessages.ImportBindingIsString, { + node: specifier + }, firstIdent.value); } specifier.imported = firstIdent; @@ -6013,15 +6196,17 @@ var flow = (superClass => class extends superClass { const specifierIsTypeImport = hasTypeImportKind(specifier); if (isInTypeOnlyImport && specifierIsTypeImport) { - this.raise(specifier.start, FlowErrors.ImportTypeShorthandOnlyInPureImport); + this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, { + node: specifier + }); } if (isInTypeOnlyImport || specifierIsTypeImport) { - this.checkReservedType(specifier.local.name, specifier.local.start, true); + this.checkReservedType(specifier.local.name, specifier.local.loc.start, true); } if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) { - this.checkReservedWord(specifier.local.name, specifier.start, true, true); + this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true); } this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL); @@ -6118,7 +6303,9 @@ var flow = (superClass => class extends superClass { if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { if (!arrow.error && !arrow.aborted) { if (arrow.node.async) { - this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction); + this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, { + node: typeParameters + }); } return arrow.node; @@ -6139,7 +6326,9 @@ var flow = (superClass => class extends superClass { if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error; if (arrow.thrown) throw arrow.error; - throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter); + throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, { + node: typeParameters + }); } return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); @@ -6184,7 +6373,9 @@ var flow = (superClass => class extends superClass { for (let i = 0; i < node.params.length; i++) { if (this.isThisParam(node.params[i]) && i > 0) { - this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst); + this.raise(FlowErrors.ThisParamMustBeFirst, { + node: node.params[i] + }); } } @@ -6308,7 +6499,9 @@ var flow = (superClass => class extends superClass { const fileNode = super.parseTopLevel(file, program); if (this.state.hasFlowComment) { - this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment); + this.raise(FlowErrors.UnterminatedFlowComment, { + at: this.state.curPosition() + }); } return fileNode; @@ -6317,7 +6510,9 @@ var flow = (superClass => class extends superClass { skipBlockComment() { if (this.hasPlugin("flowComments") && this.skipFlowComment()) { if (this.state.hasFlowComment) { - this.unexpected(null, FlowErrors.NestedFlowComment); + throw this.raise(FlowErrors.NestedFlowComment, { + at: this.state.startLoc + }); } this.hasFlowCommentCompletion(); @@ -6327,13 +6522,15 @@ var flow = (superClass => class extends superClass { } if (this.state.hasFlowComment) { - const end = this.input.indexOf("*-/", this.state.pos += 2); + const end = this.input.indexOf("*-/", this.state.pos + 2); if (end === -1) { - throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment); + throw this.raise(ErrorMessages.UnterminatedComment, { + at: this.state.curPosition() + }); } - this.state.pos = end + 3; + this.state.pos = end + 2 + 3; return; } @@ -6372,85 +6569,59 @@ var flow = (superClass => class extends superClass { const end = this.input.indexOf("*/", this.state.pos); if (end === -1) { - throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment); + throw this.raise(ErrorMessages.UnterminatedComment, { + at: this.state.curPosition() + }); } } - flowEnumErrorBooleanMemberNotInitialized(pos, { + flowEnumErrorBooleanMemberNotInitialized(loc, { enumName, memberName }) { - this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName); - } - - flowEnumErrorInvalidMemberName(pos, { - enumName, - memberName - }) { - const suggestion = memberName[0].toUpperCase() + memberName.slice(1); - this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName); - } - - flowEnumErrorDuplicateMemberName(pos, { - enumName, - memberName - }) { - this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName); - } - - flowEnumErrorInconsistentMemberValues(pos, { - enumName - }) { - this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName); + this.raise(FlowErrors.EnumBooleanMemberNotInitialized, { + at: loc + }, memberName, enumName); } - flowEnumErrorInvalidExplicitType(pos, { + flowEnumErrorInvalidExplicitType(loc, { enumName, suppliedType }) { - return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType); + return this.raise(suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, { + at: loc + }, enumName, suppliedType); } - flowEnumErrorInvalidMemberInitializer(pos, { + flowEnumErrorInvalidMemberInitializer(loc, { enumName, explicitType, memberName }) { - let message = null; - - switch (explicitType) { - case "boolean": - case "number": - case "string": - message = FlowErrors.EnumInvalidMemberInitializerPrimaryType; - break; - - case "symbol": - message = FlowErrors.EnumInvalidMemberInitializerSymbolType; - break; - - default: - message = FlowErrors.EnumInvalidMemberInitializerUnknownType; - } - - return this.raise(pos, message, enumName, memberName, explicitType); + return this.raise(explicitType === "boolean" || explicitType === "number" || explicitType === "string" ? FlowErrors.EnumInvalidMemberInitializerPrimaryType : explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerUnknownType, { + at: loc + }, enumName, memberName, explicitType); } - flowEnumErrorNumberMemberNotInitialized(pos, { + flowEnumErrorNumberMemberNotInitialized(loc, { enumName, memberName }) { - this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName); + this.raise(FlowErrors.EnumNumberMemberNotInitialized, { + at: loc + }, enumName, memberName); } - flowEnumErrorStringMemberInconsistentlyInitailized(pos, { + flowEnumErrorStringMemberInconsistentlyInitailized(node, { enumName }) { - this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName); + this.raise(FlowErrors.EnumStringMemberInconsistentlyInitailized, { + node + }, enumName); } flowEnumMemberInit() { - const startPos = this.state.start; + const startLoc = this.state.startLoc; const endOfInit = () => this.match(12) || this.match(8); @@ -6462,14 +6633,14 @@ var flow = (superClass => class extends superClass { if (endOfInit()) { return { type: "number", - pos: literal.start, + loc: literal.loc.start, value: literal }; } return { type: "invalid", - pos: startPos + loc: startLoc }; } @@ -6480,14 +6651,14 @@ var flow = (superClass => class extends superClass { if (endOfInit()) { return { type: "string", - pos: literal.start, + loc: literal.loc.start, value: literal }; } return { type: "invalid", - pos: startPos + loc: startLoc }; } @@ -6499,31 +6670,31 @@ var flow = (superClass => class extends superClass { if (endOfInit()) { return { type: "boolean", - pos: literal.start, + loc: literal.loc.start, value: literal }; } return { type: "invalid", - pos: startPos + loc: startLoc }; } default: return { type: "invalid", - pos: startPos + loc: startLoc }; } } flowEnumMemberRaw() { - const pos = this.state.start; + const loc = this.state.startLoc; const id = this.parseIdentifier(true); const init = this.eat(29) ? this.flowEnumMemberInit() : { type: "none", - pos + loc }; return { id, @@ -6531,7 +6702,7 @@ var flow = (superClass => class extends superClass { }; } - flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) { + flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) { const { explicitType } = context; @@ -6541,7 +6712,7 @@ var flow = (superClass => class extends superClass { } if (explicitType !== expectedType) { - this.flowEnumErrorInvalidMemberInitializer(pos, context); + this.flowEnumErrorInvalidMemberInitializer(loc, context); } } @@ -6576,17 +6747,15 @@ var flow = (superClass => class extends superClass { } if (/^[a-z]/.test(memberName)) { - this.flowEnumErrorInvalidMemberName(id.start, { - enumName, - memberName - }); + this.raise(FlowErrors.EnumInvalidMemberName, { + node: id + }, memberName, memberName[0].toUpperCase() + memberName.slice(1), enumName); } if (seenNames.has(memberName)) { - this.flowEnumErrorDuplicateMemberName(id.start, { - enumName, - memberName - }); + this.raise(FlowErrors.EnumDuplicateMemberName, { + node: id + }, memberName, enumName); } seenNames.add(memberName); @@ -6600,7 +6769,7 @@ var flow = (superClass => class extends superClass { switch (init.type) { case "boolean": { - this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean"); + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean"); memberNode.init = init.value; members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); break; @@ -6608,7 +6777,7 @@ var flow = (superClass => class extends superClass { case "number": { - this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number"); + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number"); memberNode.init = init.value; members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); break; @@ -6616,7 +6785,7 @@ var flow = (superClass => class extends superClass { case "string": { - this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string"); + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string"); memberNode.init = init.value; members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); break; @@ -6624,18 +6793,18 @@ var flow = (superClass => class extends superClass { case "invalid": { - throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context); + throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context); } case "none": { switch (explicitType) { case "boolean": - this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context); + this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context); break; case "number": - this.flowEnumErrorNumberMemberNotInitialized(init.pos, context); + this.flowEnumErrorNumberMemberNotInitialized(init.loc, context); break; default: @@ -6664,7 +6833,7 @@ var flow = (superClass => class extends superClass { return initializedMembers; } else if (defaultedMembers.length > initializedMembers.length) { for (const member of initializedMembers) { - this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, { + this.flowEnumErrorStringMemberInconsistentlyInitailized(member, { enumName }); } @@ -6672,7 +6841,7 @@ var flow = (superClass => class extends superClass { return defaultedMembers; } else { for (const member of defaultedMembers) { - this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, { + this.flowEnumErrorStringMemberInconsistentlyInitailized(member, { enumName }); } @@ -6686,7 +6855,7 @@ var flow = (superClass => class extends superClass { }) { if (this.eatContextual(97)) { if (!tokenIsIdentifier(this.state.type)) { - throw this.flowEnumErrorInvalidExplicitType(this.state.start, { + throw this.flowEnumErrorInvalidExplicitType(this.state.startLoc, { enumName, suppliedType: null }); @@ -6698,7 +6867,7 @@ var flow = (superClass => class extends superClass { this.next(); if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { - this.flowEnumErrorInvalidExplicitType(this.state.start, { + this.flowEnumErrorInvalidExplicitType(this.state.startLoc, { enumName, suppliedType: value }); @@ -6710,10 +6879,9 @@ var flow = (superClass => class extends superClass { return null; } - flowEnumBody(node, { - enumName, - nameLoc - }) { + flowEnumBody(node, id) { + const enumName = id.name; + const nameLoc = id.loc.start; const explicitType = this.flowEnumParseExplicitType({ enumName }); @@ -6777,7 +6945,7 @@ var flow = (superClass => class extends superClass { return this.finishNode(node, "EnumStringBody"); } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { for (const member of members.defaultedMembers) { - this.flowEnumErrorBooleanMemberNotInitialized(member.start, { + this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, { enumName, memberName: member.id.name }); @@ -6788,7 +6956,7 @@ var flow = (superClass => class extends superClass { return this.finishNode(node, "EnumBooleanBody"); } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { for (const member of members.defaultedMembers) { - this.flowEnumErrorNumberMemberNotInitialized(member.start, { + this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, { enumName, memberName: member.id.name }); @@ -6798,9 +6966,9 @@ var flow = (superClass => class extends superClass { this.expect(8); return this.finishNode(node, "EnumNumberBody"); } else { - this.flowEnumErrorInconsistentMemberValues(nameLoc, { - enumName - }); + this.raise(FlowErrors.EnumInconsistentMemberValues, { + at: nameLoc + }, enumName); return empty(); } } @@ -6810,10 +6978,7 @@ var flow = (superClass => class extends superClass { flowParseEnumDeclaration(node) { const id = this.parseIdentifier(); node.id = id; - node.body = this.flowEnumBody(this.startNode(), { - enumName: id.name, - nameLoc: id.start - }); + node.body = this.flowEnumBody(this.startNode(), id); return this.finishNode(node, "EnumDeclaration"); } @@ -7129,7 +7294,9 @@ var jsx = (superClass => class extends superClass { for (;;) { if (this.state.pos >= this.length) { - throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent); + throw this.raise(JsxErrors.UnterminatedJsxContent, { + at: this.state.startLoc + }); } const ch = this.input.charCodeAt(this.state.pos); @@ -7194,7 +7361,9 @@ var jsx = (superClass => class extends superClass { for (;;) { if (this.state.pos >= this.length) { - throw this.raise(this.state.start, ErrorMessages.UnterminatedString); + throw this.raise(ErrorMessages.UnterminatedString, { + at: this.state.startLoc + }); } const ch = this.input.charCodeAt(this.state.pos); @@ -7327,7 +7496,9 @@ var jsx = (superClass => class extends superClass { node = this.jsxParseExpressionContainer(node, types.j_oTag); if (node.expression.type === "JSXEmptyExpression") { - this.raise(node.start, JsxErrors.AttributeIsEmpty); + this.raise(JsxErrors.AttributeIsEmpty, { + node + }); } return node; @@ -7337,13 +7508,15 @@ var jsx = (superClass => class extends superClass { return this.parseExprAtom(); default: - throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue); + throw this.raise(JsxErrors.UnsupportedJsxValue, { + at: this.state.startLoc + }); } } jsxParseEmptyExpression() { - const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc); - return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc); + const node = this.startNodeAt(indexes.get(this.state.lastTokEndLoc), this.state.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc); } jsxParseSpreadChild(node) { @@ -7469,13 +7642,19 @@ var jsx = (superClass => class extends superClass { } } - if (isFragment(openingElement) && !isFragment(closingElement)) { - this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment); + if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) { + this.raise(JsxErrors.MissingClosingTagFragment, { + node: closingElement + }); } else if (!isFragment(openingElement) && isFragment(closingElement)) { - this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name)); + this.raise(JsxErrors.MissingClosingTagElement, { + node: closingElement + }, getQualifiedJSXName(openingElement.name)); } else if (!isFragment(openingElement) && !isFragment(closingElement)) { if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { - this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name)); + this.raise(JsxErrors.MissingClosingTagElement, { + node: closingElement + }, getQualifiedJSXName(openingElement.name)); } } } @@ -7491,7 +7670,9 @@ var jsx = (superClass => class extends superClass { node.children = children; if (this.match(45)) { - throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements); + throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, { + at: this.state.startLoc + }); } return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); @@ -7604,7 +7785,7 @@ class TypeScriptScopeHandler extends ScopeHandler { return new TypeScriptScope(flags); } - declareName(name, bindingType, pos) { + declareName(name, bindingType, loc) { const scope = this.currentScope(); if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) { @@ -7617,7 +7798,7 @@ class TypeScriptScopeHandler extends ScopeHandler { if (bindingType & BIND_KIND_TYPE) { if (!(bindingType & BIND_KIND_VALUE)) { - this.checkRedeclarationInScope(scope, name, bindingType, pos); + this.checkRedeclarationInScope(scope, name, bindingType, loc); this.maybeExportDefined(scope, name); } @@ -7818,49 +7999,61 @@ var typescript = (superClass => class extends superClass { } tsParseModifiers(modified, allowedModifiers, disallowedModifiers, errorTemplate, stopOnStartOfClassStaticBlock) { - const enforceOrder = (pos, modifier, before, after) => { + const enforceOrder = (loc, modifier, before, after) => { if (modifier === before && modified[after]) { - this.raise(pos, TSErrors.InvalidModifiersOrder, before, after); + this.raise(TSErrors.InvalidModifiersOrder, { + at: loc + }, before, after); } }; - const incompatible = (pos, modifier, mod1, mod2) => { + const incompatible = (loc, modifier, mod1, mod2) => { if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { - this.raise(pos, TSErrors.IncompatibleModifiers, mod1, mod2); + this.raise(TSErrors.IncompatibleModifiers, { + at: loc + }, mod1, mod2); } }; for (;;) { - const startPos = this.state.start; + const { + startLoc + } = this.state; const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock); if (!modifier) break; if (tsIsAccessModifier(modifier)) { if (modified.accessibility) { - this.raise(startPos, TSErrors.DuplicateAccessibilityModifier); + this.raise(TSErrors.DuplicateAccessibilityModifier, { + at: startLoc + }); } else { - enforceOrder(startPos, modifier, modifier, "override"); - enforceOrder(startPos, modifier, modifier, "static"); - enforceOrder(startPos, modifier, modifier, "readonly"); + enforceOrder(startLoc, modifier, modifier, "override"); + enforceOrder(startLoc, modifier, modifier, "static"); + enforceOrder(startLoc, modifier, modifier, "readonly"); modified.accessibility = modifier; } } else { if (Object.hasOwnProperty.call(modified, modifier)) { - this.raise(startPos, TSErrors.DuplicateModifier, modifier); + this.raise(TSErrors.DuplicateModifier, { + at: startLoc + }, modifier); } else { - enforceOrder(startPos, modifier, "static", "readonly"); - enforceOrder(startPos, modifier, "static", "override"); - enforceOrder(startPos, modifier, "override", "readonly"); - enforceOrder(startPos, modifier, "abstract", "override"); - incompatible(startPos, modifier, "declare", "override"); - incompatible(startPos, modifier, "static", "abstract"); + enforceOrder(startLoc, modifier, "static", "readonly"); + enforceOrder(startLoc, modifier, "static", "override"); + enforceOrder(startLoc, modifier, "override", "readonly"); + enforceOrder(startLoc, modifier, "abstract", "override"); + incompatible(startLoc, modifier, "declare", "override"); + incompatible(startLoc, modifier, "static", "abstract"); } modified[modifier] = true; } if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) { - this.raise(startPos, errorTemplate, modifier); + this.raise(errorTemplate, { + at: startLoc + }, modifier); } } } @@ -7965,7 +8158,9 @@ var typescript = (superClass => class extends superClass { this.expect(10); if (!this.match(125)) { - this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument); + this.raise(TSErrors.UnsupportedImportTypeArgument, { + at: this.state.startLoc + }); } node.argument = this.parseExprAtom(); @@ -8063,7 +8258,9 @@ var typescript = (superClass => class extends superClass { node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true, refTrailingCommaPos); if (node.params.length === 0) { - this.raise(node.start, TSErrors.EmptyTypeParameters); + this.raise(TSErrors.EmptyTypeParameters, { + node + }); } if (refTrailingCommaPos.value !== -1) { @@ -8100,7 +8297,9 @@ var typescript = (superClass => class extends superClass { tsParseBindingListForSignature() { return this.parseBindingList(11, 41).map(pattern => { if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") { - this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type); + this.raise(TSErrors.UnsupportedSignatureParameterKind, { + node: pattern + }, pattern.type); } return pattern; @@ -8153,13 +8352,17 @@ var typescript = (superClass => class extends superClass { if (this.match(10) || this.match(45)) { if (readonly) { - this.raise(node.start, TSErrors.ReadonlyForMethodSignature); + this.raise(TSErrors.ReadonlyForMethodSignature, { + node + }); } const method = nodeAny; if (method.kind && this.match(45)) { - this.raise(this.state.pos, TSErrors.AccesorCannotHaveTypeParameters); + this.raise(TSErrors.AccesorCannotHaveTypeParameters, { + at: this.state.curPosition() + }); } this.tsFillSignature(14, method); @@ -8169,33 +8372,47 @@ var typescript = (superClass => class extends superClass { if (method.kind === "get") { if (method[paramsKey].length > 0) { - this.raise(this.state.pos, ErrorMessages.BadGetterArity); + this.raise(ErrorMessages.BadGetterArity, { + at: this.state.curPosition() + }); if (this.isThisParam(method[paramsKey][0])) { - this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter); + this.raise(TSErrors.AccesorCannotDeclareThisParameter, { + at: this.state.curPosition() + }); } } } else if (method.kind === "set") { if (method[paramsKey].length !== 1) { - this.raise(this.state.pos, ErrorMessages.BadSetterArity); + this.raise(ErrorMessages.BadSetterArity, { + at: this.state.curPosition() + }); } else { const firstParameter = method[paramsKey][0]; if (this.isThisParam(firstParameter)) { - this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter); + this.raise(TSErrors.AccesorCannotDeclareThisParameter, { + at: this.state.curPosition() + }); } if (firstParameter.type === "Identifier" && firstParameter.optional) { - this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveOptionalParameter); + this.raise(TSErrors.SetAccesorCannotHaveOptionalParameter, { + at: this.state.curPosition() + }); } if (firstParameter.type === "RestElement") { - this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveRestParameter); + this.raise(TSErrors.SetAccesorCannotHaveRestParameter, { + at: this.state.curPosition() + }); } } if (method[returnTypeKey]) { - this.raise(method[returnTypeKey].start, TSErrors.SetAccesorCannotHaveReturnType); + this.raise(TSErrors.SetAccesorCannotHaveReturnType, { + node: method[returnTypeKey] + }); } } else { method.kind = "method"; @@ -8337,7 +8554,9 @@ var typescript = (superClass => class extends superClass { } = elementNode; if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { - this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired); + this.raise(TSErrors.OptionalTypeBeforeRequired, { + node: elementNode + }); } seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"; @@ -8351,7 +8570,9 @@ var typescript = (superClass => class extends superClass { labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled; if (labeledElements !== isLabeled) { - this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements); + this.raise(TSErrors.MixedLabeledAndUnlabeledElements, { + node: elementNode + }); } }); return this.finishNode(node, "TSTupleType"); @@ -8374,7 +8595,9 @@ var typescript = (superClass => class extends superClass { if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") { labeledNode.label = type.typeName; } else { - this.raise(type.start, TSErrors.InvalidTupleMemberLabel); + this.raise(TSErrors.InvalidTupleMemberLabel, { + node: type + }); labeledNode.label = type; } @@ -8568,7 +8791,9 @@ var typescript = (superClass => class extends superClass { return; default: - this.raise(node.start, TSErrors.UnexpectedReadonly); + this.raise(TSErrors.UnexpectedReadonly, { + node + }); } } @@ -8767,7 +8992,9 @@ var typescript = (superClass => class extends superClass { } if (containsEsc) { - this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts"); + this.raise(ErrorMessages.InvalidEscapedReservedWord, { + at: this.state.lastTokStartLoc + }, "asserts"); } return true; @@ -8819,7 +9046,9 @@ var typescript = (superClass => class extends superClass { tsParseTypeAssertion() { if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { - this.raise(this.state.start, TSErrors.ReservedTypeAssertion); + this.raise(TSErrors.ReservedTypeAssertion, { + at: this.state.startLoc + }); } const node = this.startNode(); @@ -8833,11 +9062,13 @@ var typescript = (superClass => class extends superClass { } tsParseHeritageClause(descriptor) { - const originalStart = this.state.start; + const originalStartLoc = this.state.startLoc; const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this)); if (!delimitedList.length) { - this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor); + this.raise(TSErrors.EmptyHeritageClauseType, { + at: originalStartLoc + }, descriptor); } return delimitedList; @@ -8860,7 +9091,9 @@ var typescript = (superClass => class extends superClass { this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE); } else { node.id = null; - this.raise(this.state.start, TSErrors.MissingInterfaceName); + this.raise(TSErrors.MissingInterfaceName, { + at: this.state.startLoc + }); } node.typeParameters = this.tsTryParseTypeParameters(); @@ -9018,7 +9251,9 @@ var typescript = (superClass => class extends superClass { const moduleReference = this.tsParseModuleReference(); if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { - this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType); + this.raise(TSErrors.ImportAliasHasImportType, { + node: moduleReference + }); } node.moduleReference = moduleReference; @@ -9252,7 +9487,9 @@ var typescript = (superClass => class extends superClass { })); if (node.params.length === 0) { - this.raise(node.start, TSErrors.EmptyTypeArguments); + this.raise(TSErrors.EmptyTypeArguments, { + node + }); } this.expect(46); @@ -9283,7 +9520,9 @@ var typescript = (superClass => class extends superClass { readonly = modified.readonly; if (allowModifiers === false && (accessibility || readonly || override)) { - this.raise(startPos, TSErrors.UnexpectedParameterModifier); + this.raise(TSErrors.UnexpectedParameterModifier, { + at: startLoc + }); } } @@ -9303,7 +9542,9 @@ var typescript = (superClass => class extends superClass { if (override) pp.override = override; if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { - this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind); + this.raise(TSErrors.UnsupportedParameterPropertyKind, { + node: pp + }); } pp.parameter = elt; @@ -9330,7 +9571,9 @@ var typescript = (superClass => class extends superClass { } if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) { - this.raise(node.start, TSErrors.DeclareFunctionHasImplementation); + this.raise(TSErrors.DeclareFunctionHasImplementation, { + node + }); if (node.declare) { super.parseFunctionBodyAndFinish(node, bodilessType, isMethod); @@ -9352,7 +9595,9 @@ var typescript = (superClass => class extends superClass { tsCheckForInvalidTypeCasts(items) { items.forEach(node => { if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") { - this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation); + this.raise(TSErrors.UnexpectedTypeAnnotation, { + node: node.typeAnnotation + }); } }); } @@ -9394,7 +9639,7 @@ var typescript = (superClass => class extends superClass { } if (this.match(45)) { - let missingParenErrorPos; + let missingParenErrorLoc; const result = this.tsTryParseAndCatch(() => { if (!noCalls && this.atPossibleAsyncArrow(base)) { const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc); @@ -9410,7 +9655,7 @@ var typescript = (superClass => class extends superClass { if (typeArguments) { if (isOptionalCall && !this.match(10)) { - missingParenErrorPos = this.state.pos; + missingParenErrorLoc = this.state.curPosition(); this.unexpected(); } @@ -9434,8 +9679,8 @@ var typescript = (superClass => class extends superClass { this.unexpected(); }); - if (missingParenErrorPos) { - this.unexpected(missingParenErrorPos, 10); + if (missingParenErrorLoc) { + this.unexpected(missingParenErrorLoc, 10); } if (result) return result; @@ -9505,7 +9750,9 @@ var typescript = (superClass => class extends superClass { const importNode = super.parseImport(node); if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { - this.raise(importNode.start, TSErrors.TypeImportCannotSpecifyDefaultAndNamed); + this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, { + node: importNode + }); } return importNode; @@ -9612,7 +9859,9 @@ var typescript = (superClass => class extends superClass { this.next(); if (this.tsHasSomeModifiers(member, modifiers)) { - this.raise(this.state.pos, TSErrors.StaticBlockCannotHaveModifier); + this.raise(TSErrors.StaticBlockCannotHaveModifier, { + at: this.state.curPosition() + }); } this.parseClassStaticBlock(classBody, member); @@ -9635,31 +9884,43 @@ var typescript = (superClass => class extends superClass { classBody.body.push(idx); if (member.abstract) { - this.raise(member.start, TSErrors.IndexSignatureHasAbstract); + this.raise(TSErrors.IndexSignatureHasAbstract, { + node: member + }); } if (member.accessibility) { - this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility); + this.raise(TSErrors.IndexSignatureHasAccessibility, { + node: member + }, member.accessibility); } if (member.declare) { - this.raise(member.start, TSErrors.IndexSignatureHasDeclare); + this.raise(TSErrors.IndexSignatureHasDeclare, { + node: member + }); } if (member.override) { - this.raise(member.start, TSErrors.IndexSignatureHasOverride); + this.raise(TSErrors.IndexSignatureHasOverride, { + node: member + }); } return; } if (!this.state.inAbstractClass && member.abstract) { - this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod); + this.raise(TSErrors.NonAbstractClassHasAbstractMethod, { + node: member + }); } if (member.override) { if (!state.hadSuperClass) { - this.raise(member.start, TSErrors.OverrideNotInSubClass); + this.raise(TSErrors.OverrideNotInSubClass, { + node: member + }); } } @@ -9671,11 +9932,15 @@ var typescript = (superClass => class extends superClass { if (optional) methodOrProp.optional = true; if (methodOrProp.readonly && this.match(10)) { - this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly); + this.raise(TSErrors.ClassMethodHasReadonly, { + node: methodOrProp + }); } if (methodOrProp.declare && this.match(10)) { - this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare); + this.raise(TSErrors.ClassMethodHasDeclare, { + node: methodOrProp + }); } } @@ -9732,7 +9997,9 @@ var typescript = (superClass => class extends superClass { const isDeclare = this.eatContextual(117); if (isDeclare && (this.isContextual(117) || !this.shouldParseExportDeclaration())) { - throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare); + throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, { + at: this.state.startLoc + }); } let declaration; @@ -9780,14 +10047,18 @@ var typescript = (superClass => class extends superClass { this.parseClassPropertyAnnotation(node); if (this.state.isAmbientContext && this.match(29)) { - this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer); + this.raise(TSErrors.DeclareClassFieldHasInitializer, { + at: this.state.startLoc + }); } if (node.abstract && this.match(29)) { const { key } = node; - this.raise(this.state.start, TSErrors.AbstractPropertyHasInitializer, key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`); + this.raise(TSErrors.AbstractPropertyHasInitializer, { + at: this.state.startLoc + }, key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`); } return super.parseClassProperty(node); @@ -9795,11 +10066,15 @@ var typescript = (superClass => class extends superClass { parseClassPrivateProperty(node) { if (node.abstract) { - this.raise(node.start, TSErrors.PrivateElementHasAbstract); + this.raise(TSErrors.PrivateElementHasAbstract, { + node + }); } if (node.accessibility) { - this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility); + this.raise(TSErrors.PrivateElementHasAccessibility, { + node + }, node.accessibility); } this.parseClassPropertyAnnotation(node); @@ -9810,11 +10085,15 @@ var typescript = (superClass => class extends superClass { const typeParameters = this.tsTryParseTypeParameters(); if (typeParameters && isConstructor) { - this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters); + this.raise(TSErrors.ConstructorHasTypeParameters, { + node: typeParameters + }); } if (method.declare && (method.kind === "get" || method.kind === "set")) { - this.raise(method.start, TSErrors.DeclareAccessor, method.kind); + this.raise(TSErrors.DeclareAccessor, { + node: method + }, method.kind); } if (typeParameters) method.typeParameters = typeParameters; @@ -9962,7 +10241,9 @@ var typescript = (superClass => class extends superClass { var _node$extra; if (node.params.length === 1 && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { - this.raise(node.start, TSErrors.ReservedArrowTypeParam); + this.raise(TSErrors.ReservedArrowTypeParam, { + node + }); } } @@ -9995,7 +10276,9 @@ var typescript = (superClass => class extends superClass { parseAssignableListItemTypes(param) { if (this.eat(17)) { if (param.type !== "Identifier" && !this.state.isAmbientContext && !this.state.inType) { - this.raise(param.start, TSErrors.PatternIsOptional); + this.raise(TSErrors.PatternIsOptional, { + node: param + }); } param.optional = true; @@ -10070,7 +10353,9 @@ var typescript = (superClass => class extends superClass { case "TSAsExpression": case "TSTypeAssertion": if (!args[0] && contextDescription !== "parenthesized expression" && !((_expr$extra2 = expr.extra) != null && _expr$extra2.parenthesized)) { - this.raise(expr.start, ErrorMessages.InvalidLhs, contextDescription); + this.raise(ErrorMessages.InvalidLhs, { + node: expr + }, contextDescription); break; } @@ -10107,7 +10392,7 @@ var typescript = (superClass => class extends superClass { return call; } - this.unexpected(this.state.start, 10); + this.unexpected(null, 10); } return super.parseMaybeDecoratorArguments(expr); @@ -10116,8 +10401,9 @@ var typescript = (superClass => class extends superClass { checkCommaAfterRest(close) { if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) { this.next(); + return false; } else { - super.checkCommaAfterRest(close); + return super.checkCommaAfterRest(close); } } @@ -10133,7 +10419,9 @@ var typescript = (superClass => class extends superClass { const node = super.parseMaybeDefault(...args); if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { - this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign); + this.raise(TSErrors.TypeAnnotationAfterAssign, { + node: node.typeAnnotation + }); } return node; @@ -10182,7 +10470,9 @@ var typescript = (superClass => class extends superClass { if (!this.state.maybeInArrowParameters) { exprList[i] = this.typeCastToParameter(expr); } else { - this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter); + this.raise(TSErrors.UnexpectedTypeCastInParameter, { + node: expr + }); } break; @@ -10194,7 +10484,7 @@ var typescript = (superClass => class extends superClass { typeCastToParameter(node) { node.expression.typeAnnotation = node.typeAnnotation; - this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); return node.expression; } @@ -10272,7 +10562,9 @@ var typescript = (superClass => class extends superClass { } else if (this.isContextual(121)) { if (!this.hasFollowingLineBreak()) { node.abstract = true; - this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer); + this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, { + node + }); this.next(); return this.tsParseInterfaceDeclaration(node); } @@ -10291,7 +10583,9 @@ var typescript = (superClass => class extends superClass { const { key } = method; - this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`); + this.raise(TSErrors.AbstractMethodHasImplementation, { + node: method + }, key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`); } } @@ -10350,7 +10644,7 @@ var typescript = (superClass => class extends superClass { let rightOfAs; let hasTypeSpecifier = false; let canParseAsKeyword = true; - const pos = leftOfAs.start; + const loc = leftOfAs.loc.start; if (this.isContextual(89)) { const firstAs = this.parseIdentifier(); @@ -10380,7 +10674,9 @@ var typescript = (superClass => class extends superClass { } if (hasTypeSpecifier && isInTypeOnlyImportExport) { - this.raise(pos, isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports); + this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, { + at: loc + }); } node[leftOfAsKey] = leftOfAs; @@ -10403,9 +10699,9 @@ var typescript = (superClass => class extends superClass { }); -const PlaceHolderErrors = makeErrorTemplates({ +const PlaceholderErrors = makeErrorTemplates({ ClassNameIsRequired: "A class name is required." -}, ErrorCodes.SyntaxError); +}, ErrorCodes.SyntaxError, "placeholders"); var placeholders = (superClass => class extends superClass { parsePlaceholder(expectedNode) { if (this.match(136)) { @@ -10527,7 +10823,9 @@ var placeholders = (superClass => class extends superClass { node.body = this.finishPlaceholder(placeholder, "ClassBody"); return this.finishNode(node, type); } else { - this.unexpected(null, PlaceHolderErrors.ClassNameIsRequired); + throw this.raise(PlaceholderErrors.ClassNameIsRequired, { + at: this.state.startLoc + }); } } else { this.parseClassId(node, isStatement, optionalId); @@ -10627,7 +10925,7 @@ var placeholders = (superClass => class extends superClass { var v8intrinsic = (superClass => class extends superClass { parseV8Intrinsic() { if (this.match(50)) { - const v8IntrinsicStart = this.state.start; + const v8IntrinsicStartLoc = this.state.startLoc; const node = this.startNode(); this.next(); @@ -10641,7 +10939,7 @@ var v8intrinsic = (superClass => class extends superClass { } } - this.unexpected(v8IntrinsicStart); + this.unexpected(v8IntrinsicStartLoc); } } @@ -10829,12 +11127,16 @@ class LValParser extends NodeUtils { if (isLHS) { if (parenthesized.type === "Identifier") { - this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment); + this.expressionScope.recordParenthesizedIdentifierError(ErrorMessages.InvalidParenthesizedAssignment, node.loc.start); } else if (parenthesized.type !== "MemberExpression") { - this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment); + this.raise(ErrorMessages.InvalidParenthesizedAssignment, { + node + }); } } else { - this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment); + this.raise(ErrorMessages.InvalidParenthesizedAssignment, { + node + }); } } @@ -10856,8 +11158,10 @@ class LValParser extends NodeUtils { const isLast = i === last; this.toAssignableObjectExpressionProp(prop, isLast, isLHS); - if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingComma) { - this.raiseRestNotLast(node.extra.trailingComma); + if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) { + this.raise(ErrorMessages.RestTrailingComma, { + at: node.extra.trailingCommaLoc + }); } } @@ -10878,12 +11182,14 @@ class LValParser extends NodeUtils { case "ArrayExpression": node.type = "ArrayPattern"; - this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS); + this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS); break; case "AssignmentExpression": if (node.operator !== "=") { - this.raise(node.left.end, ErrorMessages.MissingEqInAssignment); + this.raise(ErrorMessages.MissingEqInAssignment, { + at: node.left.loc.end + }); } node.type = "AssignmentPattern"; @@ -10901,16 +11207,19 @@ class LValParser extends NodeUtils { toAssignableObjectExpressionProp(prop, isLast, isLHS) { if (prop.type === "ObjectMethod") { - const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod; - this.raise(prop.key.start, error); + this.raise(prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod, { + node: prop.key + }); } else if (prop.type === "SpreadElement" && !isLast) { - this.raiseRestNotLast(prop.start); + this.raise(ErrorMessages.RestTrailingComma, { + node: prop + }); } else { this.toAssignable(prop, isLHS); } } - toAssignableList(exprList, trailingCommaPos, isLHS) { + toAssignableList(exprList, trailingCommaLoc, isLHS) { let end = exprList.length; if (end) { @@ -10928,8 +11237,10 @@ class LValParser extends NodeUtils { this.unexpected(arg.start); } - if (trailingCommaPos) { - this.raiseTrailingCommaAfterRest(trailingCommaPos); + if (trailingCommaLoc) { + this.raise(ErrorMessages.RestTrailingComma, { + at: trailingCommaLoc + }); } --end; @@ -10943,7 +11254,9 @@ class LValParser extends NodeUtils { this.toAssignable(elt, isLHS); if (elt.type === "RestElement") { - this.raiseRestNotLast(elt.start); + this.raise(ErrorMessages.RestTrailingComma, { + node: elt + }); } } } @@ -11054,14 +11367,18 @@ class LValParser extends NodeUtils { break; } else if (this.match(21)) { elts.push(this.parseAssignableListItemTypes(this.parseRestBinding())); - this.checkCommaAfterRest(closeCharCode); - this.expect(close); - break; + + if (!this.checkCommaAfterRest(closeCharCode)) { + this.expect(close); + break; + } } else { const decorators = []; if (this.match(26) && this.hasPlugin("decorators")) { - this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator); + this.raise(ErrorMessages.UnsupportedParameterDecorator, { + at: this.state.startLoc + }); } while (this.match(26)) { @@ -11139,23 +11456,29 @@ class LValParser extends NodeUtils { } = expr; if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) { - this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name); + this.raise(bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, { + node: expr + }, name); } if (checkClashes) { if (checkClashes.has(name)) { - this.raise(expr.start, ErrorMessages.ParamDupe); + this.raise(ErrorMessages.ParamDupe, { + node: expr + }); } else { checkClashes.add(name); } } if (disallowLetBinding && name === "let") { - this.raise(expr.start, ErrorMessages.LetInLexicalBinding); + this.raise(ErrorMessages.LetInLexicalBinding, { + node: expr + }); } if (!(bindingType & BIND_NONE)) { - this.scope.declareName(name, bindingType, expr.start); + this.scope.declareName(name, bindingType, expr.loc.start); } break; @@ -11163,7 +11486,9 @@ class LValParser extends NodeUtils { case "MemberExpression": if (bindingType !== BIND_NONE) { - this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern); + this.raise(ErrorMessages.InvalidPropertyBindingPattern, { + node: expr + }); } break; @@ -11199,33 +11524,30 @@ class LValParser extends NodeUtils { default: { - this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription); + this.raise(bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, { + node: expr + }, contextDescription); } } } checkToRestConversion(node) { if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") { - this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern); + this.raise(ErrorMessages.InvalidRestAssignmentPattern, { + node: node.argument + }); } } checkCommaAfterRest(close) { - if (this.match(12)) { - if (this.lookaheadCharCode() === close) { - this.raiseTrailingCommaAfterRest(this.state.start); - } else { - this.raiseRestNotLast(this.state.start); - } + if (!this.match(12)) { + return false; } - } - raiseRestNotLast(pos) { - throw this.raise(pos, ErrorMessages.ElementAfterRest); - } - - raiseTrailingCommaAfterRest(pos) { - this.raise(pos, ErrorMessages.RestTrailingComma); + this.raise(this.lookaheadCharCode() === close ? ErrorMessages.RestTrailingComma : ErrorMessages.ElementAfterRest, { + at: this.state.startLoc + }); + return true; } } @@ -11242,17 +11564,21 @@ class ExpressionParser extends LValParser { if (name === "__proto__") { if (isRecord) { - this.raise(key.start, ErrorMessages.RecordNoProto); + this.raise(ErrorMessages.RecordNoProto, { + node: key + }); return; } if (protoRef.used) { if (refExpressionErrors) { - if (refExpressionErrors.doubleProto === -1) { - refExpressionErrors.doubleProto = key.start; + if (refExpressionErrors.doubleProtoLoc === null) { + refExpressionErrors.doubleProtoLoc = key.loc.start; } } else { - this.raise(key.start, ErrorMessages.DuplicateProto); + this.raise(ErrorMessages.DuplicateProto, { + node: key + }); } } @@ -11321,9 +11647,9 @@ class ExpressionParser extends LValParser { } setOptionalParametersError(refExpressionErrors, resultError) { - var _resultError$pos; + var _resultError$loc; - refExpressionErrors.optionalParameters = (_resultError$pos = resultError == null ? void 0 : resultError.pos) != null ? _resultError$pos : this.state.start; + refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc; } parseMaybeAssign(refExpressionErrors, afterLeftParse) { @@ -11373,12 +11699,12 @@ class ExpressionParser extends LValParser { if (this.match(29)) { node.left = this.toAssignable(left, true); - if (refExpressionErrors.doubleProto >= startPos) { - refExpressionErrors.doubleProto = -1; + if (refExpressionErrors.doubleProtoLoc != null && indexes.get(refExpressionErrors.doubleProtoLoc) >= startPos) { + refExpressionErrors.doubleProtoLoc = null; } - if (refExpressionErrors.shorthandAssign >= startPos) { - refExpressionErrors.shorthandAssign = -1; + if (refExpressionErrors.shorthandAssignLoc != null && indexes.get(refExpressionErrors.shorthandAssignLoc) >= startPos) { + refExpressionErrors.shorthandAssignLoc = null; } } else { node.left = left; @@ -11441,15 +11767,14 @@ class ExpressionParser extends LValParser { parseExprOp(left, leftStartPos, leftStartLoc, minPrec) { if (this.isPrivateName(left)) { const value = this.getPrivateNameSV(left); - const { - start - } = left; if (minPrec >= tokenOperatorPrecedence(54) || !this.prodParam.hasIn || !this.match(54)) { - this.raise(start, ErrorMessages.PrivateInExpectedIn, value); + this.raise(ErrorMessages.PrivateInExpectedIn, { + node: left + }, value); } - this.classScope.usePrivateName(value, start); + this.classScope.usePrivateName(value, left.loc.start); } const op = this.state.type; @@ -11465,7 +11790,7 @@ class ExpressionParser extends LValParser { return left; } - this.checkPipelineAtInfixOperator(left, leftStartPos); + this.checkPipelineAtInfixOperator(left, leftStartLoc); } const node = this.startNodeAt(leftStartPos, leftStartLoc); @@ -11484,7 +11809,9 @@ class ExpressionParser extends LValParser { proposal: "minimal" }])) { if (this.state.type === 92 && this.prodParam.hasAwait) { - throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody); + throw this.raise(ErrorMessages.UnexpectedAwaitAfterPipelineBody, { + at: this.state.startLoc + }); } } @@ -11493,7 +11820,9 @@ class ExpressionParser extends LValParser { const nextOp = this.state.type; if (coalesce && (nextOp === 39 || nextOp === 40) || logical && nextOp === 38) { - throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical); + throw this.raise(ErrorMessages.MixingCoalesceWithLogical, { + at: this.state.startLoc + }); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec); @@ -11518,7 +11847,9 @@ class ExpressionParser extends LValParser { case "smart": return this.withTopicBindingContext(() => { if (this.prodParam.hasYield && this.isContextual(101)) { - throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, this.state.value); + throw this.raise(ErrorMessages.PipeBodyIsTighter, { + at: this.state.startLoc + }, this.state.value); } return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc); @@ -11545,16 +11876,20 @@ class ExpressionParser extends LValParser { var _body$extra; const { - start + startLoc } = this.state; const body = this.parseMaybeAssign(); if (invalidHackPipeBodies.has(body.type) && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) { - this.raise(start, ErrorMessages.PipeUnparenthesizedBody, invalidHackPipeBodies.get(body.type)); + this.raise(ErrorMessages.PipeUnparenthesizedBody, { + at: startLoc + }, invalidHackPipeBodies.get(body.type)); } if (!this.topicReferenceWasUsedInCurrentContext()) { - this.raise(start, ErrorMessages.PipeTopicUnused); + this.raise(ErrorMessages.PipeTopicUnused, { + at: startLoc + }); } return body; @@ -11562,7 +11897,9 @@ class ExpressionParser extends LValParser { checkExponentialAfterUnary(node) { if (this.match(53)) { - this.raise(node.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation); + this.raise(ErrorMessages.UnexpectedTokenUnaryExponentiation, { + node: node.argument + }); } } @@ -11598,9 +11935,13 @@ class ExpressionParser extends LValParser { const arg = node.argument; if (arg.type === "Identifier") { - this.raise(node.start, ErrorMessages.StrictDelete); + this.raise(ErrorMessages.StrictDelete, { + node + }); } else if (this.hasPropertyAsPrivateName(arg)) { - this.raise(node.start, ErrorMessages.DeletePrivateField); + this.raise(ErrorMessages.DeletePrivateField, { + node + }); } } @@ -11619,7 +11960,7 @@ class ExpressionParser extends LValParser { const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(50); if (startsExpr && !this.isAmbiguousAwait()) { - this.raiseOverwrite(startPos, ErrorMessages.AwaitNotInAsyncContext); + this.raiseOverwrite(startLoc, ErrorMessages.AwaitNotInAsyncContext); return this.parseAwait(startPos, startLoc); } } @@ -11726,10 +12067,12 @@ class ExpressionParser extends LValParser { this.expect(3); } else if (this.match(130)) { if (base.type === "Super") { - this.raise(startPos, ErrorMessages.SuperPrivateField); + this.raise(ErrorMessages.SuperPrivateField, { + at: startLoc + }); } - this.classScope.usePrivateName(this.state.value, this.state.start); + this.classScope.usePrivateName(this.state.value, this.state.startLoc); node.property = this.parsePrivateName(); } else { node.property = this.parseIdentifier(true); @@ -11805,14 +12148,16 @@ class ExpressionParser extends LValParser { node.quasi = this.parseTemplate(true); if (state.optionalChainMember) { - this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate); + this.raise(ErrorMessages.OptionalChainingNoTemplate, { + at: startLoc + }); } return this.finishNode(node, "TaggedTemplateExpression"); } atPossibleAsyncArrow(base) { - return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt; + return base.type === "Identifier" && base.name === "async" && indexes.get(this.state.lastTokEndLoc) === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt; } finishCallExpression(node, optional) { @@ -11826,11 +12171,15 @@ class ExpressionParser extends LValParser { } if (node.arguments.length === 0 || node.arguments.length > 2) { - this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument"); + this.raise(ErrorMessages.ImportCallArity, { + node + }, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument"); } else { for (const arg of node.arguments) { if (arg.type === "SpreadElement") { - this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument); + this.raise(ErrorMessages.ImportCallSpreadArgument, { + node: arg + }); } } } @@ -11853,11 +12202,13 @@ class ExpressionParser extends LValParser { if (this.match(close)) { if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) { - this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma); + this.raise(ErrorMessages.ImportCallArgumentTrailingComma, { + at: this.state.lastTokStartLoc + }); } if (nodeForExtra) { - this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart); + this.addTrailingCommaExtraToNode(nodeForExtra); } this.next(); @@ -11881,7 +12232,7 @@ class ExpressionParser extends LValParser { this.resetPreviousNodeTrailingComments(call); this.expect(19); - this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma); + this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc); if (call.innerComments) { setInnerComments(node, call.innerComments); @@ -11919,7 +12270,9 @@ class ExpressionParser extends LValParser { } if (!this.match(10)) { - this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport); + this.raise(ErrorMessages.UnsupportedImport, { + at: this.state.lastTokStartLoc + }); } return this.finishNode(node, "Import"); @@ -12018,13 +12371,17 @@ class ExpressionParser extends LValParser { if (callee.type === "MemberExpression") { return this.finishNode(node, "BindExpression"); } else { - throw this.raise(callee.start, ErrorMessages.UnsupportedBind); + throw this.raise(ErrorMessages.UnsupportedBind, { + node: callee + }); } } case 130: { - this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, this.state.value); + this.raise(ErrorMessages.PrivateInExpectedIn, { + at: this.state.startLoc + }, this.state.value); return this.parsePrivateName(); } @@ -12115,7 +12472,7 @@ class ExpressionParser extends LValParser { this.state.value = topicTokenValue; this.state.pos--; this.state.end--; - this.state.endLoc.column--; + this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1); return this.parseTopicReference(pipeProposal); } else { throw this.unexpected(); @@ -12124,38 +12481,32 @@ class ExpressionParser extends LValParser { parseTopicReference(pipeProposal) { const node = this.startNode(); - const start = this.state.start; + const startLoc = this.state.startLoc; const tokenType = this.state.type; this.next(); - return this.finishTopicReference(node, start, pipeProposal, tokenType); + return this.finishTopicReference(node, startLoc, pipeProposal, tokenType); } - finishTopicReference(node, start, pipeProposal, tokenType) { - if (this.testTopicReferenceConfiguration(pipeProposal, start, tokenType)) { - let nodeType; - - if (pipeProposal === "smart") { - nodeType = "PipelinePrimaryTopicReference"; - } else { - nodeType = "TopicReference"; - } + finishTopicReference(node, startLoc, pipeProposal, tokenType) { + if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) { + const nodeType = pipeProposal === "smart" ? "PipelinePrimaryTopicReference" : "TopicReference"; if (!this.topicReferenceIsAllowedInCurrentContext()) { - if (pipeProposal === "smart") { - this.raise(start, ErrorMessages.PrimaryTopicNotAllowed); - } else { - this.raise(start, ErrorMessages.PipeTopicUnbound); - } + this.raise(pipeProposal === "smart" ? ErrorMessages.PrimaryTopicNotAllowed : ErrorMessages.PipeTopicUnbound, { + at: startLoc + }); } this.registerTopicReference(); return this.finishNode(node, nodeType); } else { - throw this.raise(start, ErrorMessages.PipeTopicUnconfiguredToken, tokenLabelName(tokenType)); + throw this.raise(ErrorMessages.PipeTopicUnconfiguredToken, { + at: startLoc + }, tokenLabelName(tokenType)); } } - testTopicReferenceConfiguration(pipeProposal, start, tokenType) { + testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) { switch (pipeProposal) { case "hack": { @@ -12168,7 +12519,9 @@ class ExpressionParser extends LValParser { return tokenType === 27; default: - throw this.raise(start, ErrorMessages.PipeTopicRequiresHackPipes); + throw this.raise(ErrorMessages.PipeTopicRequiresHackPipes, { + at: startLoc + }); } } @@ -12178,7 +12531,9 @@ class ExpressionParser extends LValParser { this.prodParam.exit(); if (this.hasPrecedingLineBreak()) { - this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow); + this.raise(ErrorMessages.LineTerminatorBeforeArrow, { + at: this.state.curPosition() + }); } this.expect(19); @@ -12215,13 +12570,19 @@ class ExpressionParser extends LValParser { this.next(); if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { - this.raise(node.start, ErrorMessages.SuperNotAllowed); + this.raise(ErrorMessages.SuperNotAllowed, { + node + }); } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { - this.raise(node.start, ErrorMessages.UnexpectedSuper); + this.raise(ErrorMessages.UnexpectedSuper, { + node + }); } if (!this.match(10) && !this.match(0) && !this.match(16)) { - this.raise(node.start, ErrorMessages.UnsupportedSuper); + this.raise(ErrorMessages.UnsupportedSuper, { + node + }); } return this.finishNode(node, "Super"); @@ -12229,7 +12590,7 @@ class ExpressionParser extends LValParser { parsePrivateName() { const node = this.startNode(); - const id = this.startNodeAt(this.state.start + 1, new Position(this.state.curLine, this.state.start + 1 - this.state.lineStart)); + const id = this.startNodeAt(this.state.start + 1, new Position(this.state.curLine, this.state.start + 1 - this.state.lineStart, this.state.start + 1)); const name = this.state.value; this.next(); node.id = this.createIdentifier(id, name); @@ -12262,7 +12623,9 @@ class ExpressionParser extends LValParser { node.property = this.parseIdentifier(true); if (node.property.name !== propertyName || containsEsc) { - this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName); + this.raise(ErrorMessages.UnsupportedMetaProperty, { + node: node.property + }, meta.name, propertyName); } return this.finishNode(node, "MetaProperty"); @@ -12274,7 +12637,9 @@ class ExpressionParser extends LValParser { if (this.isContextual(96)) { if (!this.inModule) { - this.raise(id.start, SourceTypeModuleErrorMessages.ImportMetaOutsideModule); + this.raise(SourceTypeModuleErrorMessages.ImportMetaOutsideModule, { + node: id + }); } this.sawUnambiguousESM = true; @@ -12347,17 +12712,17 @@ class ExpressionParser extends LValParser { const exprList = []; const refExpressionErrors = new ExpressionErrors(); let first = true; - let spreadStart; - let optionalCommaStart; + let spreadStartLoc; + let optionalCommaStartLoc; while (!this.match(11)) { if (first) { first = false; } else { - this.expect(12, refExpressionErrors.optionalParameters === -1 ? null : refExpressionErrors.optionalParameters); + this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc); if (this.match(11)) { - optionalCommaStart = this.state.start; + optionalCommaStartLoc = this.state.startLoc; break; } } @@ -12365,16 +12730,17 @@ class ExpressionParser extends LValParser { if (this.match(21)) { const spreadNodeStartPos = this.state.start; const spreadNodeStartLoc = this.state.startLoc; - spreadStart = this.state.start; + spreadStartLoc = this.state.startLoc; exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc)); - this.checkCommaAfterRest(41); - break; + + if (!this.checkCommaAfterRest(41)) { + break; + } } else { exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem)); } } - const innerEndPos = this.state.lastTokEnd; const innerEndLoc = this.state.lastTokEndLoc; this.expect(11); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; @@ -12391,11 +12757,11 @@ class ExpressionParser extends LValParser { this.expressionScope.exit(); if (!exprList.length) { - this.unexpected(this.state.lastTokStart); + this.unexpected(this.state.lastTokStartLoc); } - if (optionalCommaStart) this.unexpected(optionalCommaStart); - if (spreadStart) this.unexpected(spreadStart); + if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc); + if (spreadStartLoc) this.unexpected(spreadStartLoc); this.checkExpressionErrors(refExpressionErrors, true); this.toReferencedListDeep(exprList, true); @@ -12403,7 +12769,7 @@ class ExpressionParser extends LValParser { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNode(val, "SequenceExpression"); - this.resetEndLocation(val, innerEndPos, innerEndLoc); + this.resetEndLocation(val, innerEndLoc); } else { val = exprList[0]; } @@ -12411,7 +12777,7 @@ class ExpressionParser extends LValParser { if (!this.options.createParenthesizedExpressions) { this.addExtra(val, "parenthesized", true); this.addExtra(val, "parenStart", startPos); - this.takeSurroundingComments(val, startPos, this.state.lastTokEnd); + this.takeSurroundingComments(val, startPos, indexes.get(this.state.lastTokEndLoc)); return val; } @@ -12445,7 +12811,9 @@ class ExpressionParser extends LValParser { const metaProp = this.parseMetaProperty(node, meta, "target"); if (!this.scope.inNonArrowFunction && !this.scope.inClass) { - this.raise(metaProp.start, ErrorMessages.UnexpectedNewTarget); + this.raise(ErrorMessages.UnexpectedNewTarget, { + node: metaProp + }); } return metaProp; @@ -12458,11 +12826,17 @@ class ExpressionParser extends LValParser { node.callee = this.parseNoCallExpr(); if (node.callee.type === "Import") { - this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression); + this.raise(ErrorMessages.ImportCallNotNewExpression, { + node: node.callee + }); } else if (this.isOptionalChain(node.callee)) { - this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew); + this.raise(ErrorMessages.OptionalChainingNoNew, { + at: this.state.lastTokEndLoc + }); } else if (this.eat(18)) { - this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew); + this.raise(ErrorMessages.OptionalChainingNoNew, { + at: this.state.startLoc + }); } this.parseNewArguments(node); @@ -12482,15 +12856,18 @@ class ExpressionParser extends LValParser { parseTemplateElement(isTagged) { const { start, + startLoc, end, value } = this.state; const elemStart = start + 1; - const elem = this.startNodeAt(elemStart, createPositionWithColumnOffset(this.state.startLoc, 1)); + const elem = this.startNodeAt(elemStart, createPositionWithColumnOffset(startLoc, 1)); if (value === null) { if (!isTagged) { - this.raise(start + 2, ErrorMessages.InvalidEscapeSequenceTemplate); + this.raise(ErrorMessages.InvalidEscapeSequenceTemplate, { + at: createPositionWithColumnOffset(startLoc, 2) + }); } } @@ -12504,7 +12881,7 @@ class ExpressionParser extends LValParser { elem.tail = isTail; this.next(); this.finishNode(elem, "TemplateElement"); - this.resetEndLocation(elem, elemEnd, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset)); + this.resetEndLocation(elem, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset)); return elem; } @@ -12547,7 +12924,7 @@ class ExpressionParser extends LValParser { this.expect(12); if (this.match(close)) { - this.addExtra(node, "trailingComma", this.state.lastTokStart); + this.addTrailingCommaExtraToNode(node); break; } } @@ -12562,7 +12939,9 @@ class ExpressionParser extends LValParser { } if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") { - this.raise(prop.start, ErrorMessages.InvalidRecordProperty); + this.raise(ErrorMessages.InvalidRecordProperty, { + node: prop + }); } if (prop.shorthand) { @@ -12585,6 +12964,11 @@ class ExpressionParser extends LValParser { return this.finishNode(node, type); } + addTrailingCommaExtraToNode(node) { + this.addExtra(node, "trailingComma", this.state.lastTokStart); + this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false); + } + maybeAsyncOrAccessorProp(prop) { return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(51)); } @@ -12594,7 +12978,9 @@ class ExpressionParser extends LValParser { if (this.match(26)) { if (this.hasPlugin("decorators")) { - this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator); + this.raise(ErrorMessages.UnsupportedPropertyDecorator, { + at: this.state.startLoc + }); } while (this.match(26)) { @@ -12647,7 +13033,9 @@ class ExpressionParser extends LValParser { if (this.match(51)) { isGenerator = true; - this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName); + this.raise(ErrorMessages.AccessorIsGenerator, { + at: this.state.curPosition() + }, keyName); this.next(); } @@ -12672,18 +13060,17 @@ class ExpressionParser extends LValParser { const paramCount = this.getGetterSetterExpectedParamCount(method); const params = this.getObjectOrClassMethodParams(method); - const start = method.start; if (params.length !== paramCount) { - if (method.kind === "get") { - this.raise(start, ErrorMessages.BadGetterArity); - } else { - this.raise(start, ErrorMessages.BadSetterArity); - } + this.raise(method.kind === "get" ? ErrorMessages.BadGetterArity : ErrorMessages.BadSetterArity, { + node: method + }); } if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { - this.raise(start, ErrorMessages.BadSetterRestParameter); + this.raise(ErrorMessages.BadSetterRestParameter, { + node: method + }); } } @@ -12711,19 +13098,21 @@ class ExpressionParser extends LValParser { } if (!prop.computed && prop.key.type === "Identifier") { - this.checkReservedWord(prop.key.name, prop.key.start, true, false); + this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false); if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key)); } else if (this.match(29)) { - const shorthandAssign = this.state.start; + const shorthandAssignLoc = this.state.startLoc; if (refExpressionErrors != null) { - if (refExpressionErrors.shorthandAssign === -1) { - refExpressionErrors.shorthandAssign = shorthandAssign; + if (refExpressionErrors.shorthandAssignLoc === null) { + refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc; } } else { - this.raise(shorthandAssign, ErrorMessages.InvalidCoverInitializedName); + this.raise(ErrorMessages.InvalidCoverInitializedName, { + at: shorthandAssignLoc + }); } prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key)); @@ -12776,8 +13165,9 @@ class ExpressionParser extends LValParser { case 130: { - const privateKeyPos = this.state.start + 1; - this.raise(privateKeyPos, ErrorMessages.UnexpectedPrivateField); + this.raise(ErrorMessages.UnexpectedPrivateField, { + at: createPositionWithColumnOffset(this.state.startLoc, 1) + }); key = this.parsePrivateName(); break; } @@ -12830,7 +13220,7 @@ class ExpressionParser extends LValParser { return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression"); } - parseArrowExpression(node, params, isAsync, trailingCommaPos) { + parseArrowExpression(node, params, isAsync, trailingCommaLoc) { this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW); let flags = functionFlags(isAsync, false); @@ -12844,7 +13234,7 @@ class ExpressionParser extends LValParser { if (params) { this.state.maybeInArrowParameters = true; - this.setArrowFunctionParameters(node, params, trailingCommaPos); + this.setArrowFunctionParameters(node, params, trailingCommaLoc); } this.state.maybeInArrowParameters = false; @@ -12855,8 +13245,8 @@ class ExpressionParser extends LValParser { return this.finishNode(node, "ArrowFunctionExpression"); } - setArrowFunctionParameters(node, params, trailingCommaPos) { - node.params = this.toAssignableList(params, trailingCommaPos, false); + setArrowFunctionParameters(node, params, trailingCommaLoc) { + node.params = this.toAssignableList(params, trailingCommaLoc, false); } parseFunctionBodyAndFinish(node, type, isMethod = false) { @@ -12880,8 +13270,12 @@ class ExpressionParser extends LValParser { const nonSimple = !this.isSimpleParamList(node.params); if (hasStrictModeDirective && nonSimple) { - const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start; - this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective); + const errorOrigin = (node.kind === "method" || node.kind === "constructor") && !!node.key ? { + at: node.key.loc.end + } : { + node + }; + this.raise(ErrorMessages.IllegalLanguageModeDirective, errorOrigin); } const strictModeChanged = !oldStrict && this.state.strict; @@ -12926,7 +13320,7 @@ class ExpressionParser extends LValParser { if (this.match(close)) { if (nodeForExtra) { - this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart); + this.addTrailingCommaExtraToNode(nodeForExtra); } this.next(); @@ -12945,7 +13339,9 @@ class ExpressionParser extends LValParser { if (this.match(12)) { if (!allowEmpty) { - this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ","); + this.raise(ErrorMessages.UnexpectedToken, { + at: this.state.curPosition() + }, ","); } elt = null; @@ -12957,7 +13353,9 @@ class ExpressionParser extends LValParser { this.expectPlugin("partialApplication"); if (!allowPlaceholder) { - this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder); + this.raise(ErrorMessages.UnexpectedArgumentPlaceholder, { + at: this.state.startLoc + }); } const node = this.startNode(); @@ -12985,7 +13383,7 @@ class ExpressionParser extends LValParser { parseIdentifierName(pos, liberal) { let name; const { - start, + startLoc, type } = this.state; @@ -13002,7 +13400,7 @@ class ExpressionParser extends LValParser { this.replaceToken(124); } } else { - this.checkReservedWord(name, start, tokenIsKeyword, false); + this.checkReservedWord(name, startLoc, tokenIsKeyword, false); } this.next(); @@ -13020,35 +13418,49 @@ class ExpressionParser extends LValParser { if (word === "yield") { if (this.prodParam.hasYield) { - this.raise(startLoc, ErrorMessages.YieldBindingIdentifier); + this.raise(ErrorMessages.YieldBindingIdentifier, { + at: startLoc + }); return; } } else if (word === "await") { if (this.prodParam.hasAwait) { - this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier); + this.raise(ErrorMessages.AwaitBindingIdentifier, { + at: startLoc + }); return; - } else if (this.scope.inStaticBlock) { - this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock); + } + + if (this.scope.inStaticBlock) { + this.raise(ErrorMessages.AwaitBindingIdentifierInStaticBlock, { + at: startLoc + }); return; - } else { - this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier); } + + this.expressionScope.recordAsyncArrowParametersError(ErrorMessages.AwaitBindingIdentifier, startLoc); } else if (word === "arguments") { if (this.scope.inClassAndNotInNonArrowFunction) { - this.raise(startLoc, ErrorMessages.ArgumentsInClass); + this.raise(ErrorMessages.ArgumentsInClass, { + at: startLoc + }); return; } } if (checkKeywords && isKeyword(word)) { - this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word); + this.raise(ErrorMessages.UnexpectedKeyword, { + at: startLoc + }, word); return; } const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; if (reservedTest(word, this.inModule)) { - this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word); + this.raise(ErrorMessages.UnexpectedReservedWord, { + at: startLoc + }, word); } } @@ -13064,10 +13476,12 @@ class ExpressionParser extends LValParser { parseAwait(startPos, startLoc) { const node = this.startNodeAt(startPos, startLoc); - this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter); + this.expressionScope.recordParameterInitializerError(node.loc.start, ErrorMessages.AwaitExpressionFormalParameter); if (this.eat(51)) { - this.raise(node.start, ErrorMessages.ObsoleteAwaitStar); + this.raise(ErrorMessages.ObsoleteAwaitStar, { + node + }); } if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) { @@ -13095,7 +13509,7 @@ class ExpressionParser extends LValParser { parseYield() { const node = this.startNode(); - this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter); + this.expressionScope.recordParameterInitializerError(node.loc.start, ErrorMessages.YieldInParameter); this.next(); let delegating = false; let argument = null; @@ -13124,22 +13538,18 @@ class ExpressionParser extends LValParser { return this.finishNode(node, "YieldExpression"); } - checkPipelineAtInfixOperator(left, leftStartPos) { + checkPipelineAtInfixOperator(left, leftStartLoc) { if (this.hasPlugin(["pipelineOperator", { proposal: "smart" }])) { if (left.type === "SequenceExpression") { - this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression); + this.raise(ErrorMessages.PipelineHeadSequenceExpression, { + at: leftStartLoc + }); } } } - checkHackPipeBodyEarlyErrors(startPos) { - if (!this.topicReferenceWasUsedInCurrentContext()) { - this.raise(startPos, ErrorMessages.PipeTopicUnused); - } - } - parseSmartPipelineBodyInStyle(childExpr, startPos, startLoc) { const bodyNode = this.startNodeAt(startPos, startLoc); @@ -13147,7 +13557,7 @@ class ExpressionParser extends LValParser { bodyNode.callee = childExpr; return this.finishNode(bodyNode, "PipelineBareFunction"); } else { - this.checkSmartPipeTopicBodyEarlyErrors(startPos); + this.checkSmartPipeTopicBodyEarlyErrors(startLoc); bodyNode.expression = childExpr; return this.finishNode(bodyNode, "PipelineTopicExpression"); } @@ -13166,11 +13576,17 @@ class ExpressionParser extends LValParser { } } - checkSmartPipeTopicBodyEarlyErrors(startPos) { + checkSmartPipeTopicBodyEarlyErrors(startLoc) { if (this.match(19)) { - throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow); - } else if (!this.topicReferenceWasUsedInCurrentContext()) { - this.raise(startPos, ErrorMessages.PipelineTopicUnused); + throw this.raise(ErrorMessages.PipelineBodyNoArrow, { + at: this.state.startLoc + }); + } + + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(ErrorMessages.PipelineTopicUnused, { + at: startLoc + }); } } @@ -13445,9 +13861,10 @@ class StatementParser extends ExpressionParser { this.parseBlockBody(program, true, true, end); if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) { - for (const [name] of Array.from(this.scope.undefinedExports)) { - const pos = this.scope.undefinedExports.get(name); - this.raise(pos, ErrorMessages.ModuleExportUndefined, name); + for (const [name, loc] of Array.from(this.scope.undefinedExports)) { + this.raise(ErrorMessages.ModuleExportUndefined, { + at: loc + }, name); } } @@ -13556,9 +13973,13 @@ class StatementParser extends ExpressionParser { if (context) { if (this.state.strict) { - this.raise(this.state.start, ErrorMessages.StrictFunction); + this.raise(ErrorMessages.StrictFunction, { + at: this.state.startLoc + }); } else if (context !== "if" && context !== "label") { - this.raise(this.state.start, ErrorMessages.SloppyFunction); + this.raise(ErrorMessages.SloppyFunction, { + at: this.state.startLoc + }); } } @@ -13588,7 +14009,9 @@ class StatementParser extends ExpressionParser { kind = kind || this.state.value; if (context && kind !== "var") { - this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration); + this.raise(ErrorMessages.UnexpectedLexicalDeclaration, { + at: this.state.startLoc + }); } return this.parseVarStatement(node, kind); @@ -13617,7 +14040,9 @@ class StatementParser extends ExpressionParser { case 78: { if (!this.options.allowImportExportEverywhere && !topLevel) { - this.raise(this.state.start, ErrorMessages.UnexpectedImportExport); + this.raise(ErrorMessages.UnexpectedImportExport, { + at: this.state.startLoc + }); } this.next(); @@ -13645,7 +14070,9 @@ class StatementParser extends ExpressionParser { { if (this.isAsyncFunction()) { if (context) { - this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext); + this.raise(ErrorMessages.AsyncFunctionInSingleStatementContext, { + at: this.state.startLoc + }); } this.next(); @@ -13666,7 +14093,9 @@ class StatementParser extends ExpressionParser { assertModuleNodeAllowed(node) { if (!this.options.allowImportExportEverywhere && !this.inModule) { - this.raise(node.start, SourceTypeModuleErrorMessages.ImportOutsideModule); + this.raise(SourceTypeModuleErrorMessages.ImportOutsideModule, { + node + }); } } @@ -13698,10 +14127,14 @@ class StatementParser extends ExpressionParser { } if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) { - this.raise(this.state.start, ErrorMessages.DecoratorExportClass); + this.raise(ErrorMessages.DecoratorExportClass, { + at: this.state.startLoc + }); } } else if (!this.canHaveLeadingDecorator()) { - throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator); + throw this.raise(ErrorMessages.UnexpectedLeadingDecorator, { + at: this.state.startLoc + }); } } @@ -13779,7 +14212,9 @@ class StatementParser extends ExpressionParser { } if (i === this.state.labels.length) { - this.raise(node.start, ErrorMessages.IllegalBreakContinue, isBreak ? "break" : "continue"); + this.raise(ErrorMessages.IllegalBreakContinue, { + node + }, isBreak ? "break" : "continue"); } } @@ -13810,17 +14245,17 @@ class StatementParser extends ExpressionParser { parseForStatement(node) { this.next(); this.state.labels.push(loopLabel); - let awaitAt = -1; + let awaitAt = null; if (this.isAwaitAllowed() && this.eatContextual(92)) { - awaitAt = this.state.lastTokStart; + awaitAt = this.state.lastTokStartLoc; } this.scope.enter(SCOPE_OTHER); this.expect(10); if (this.match(13)) { - if (awaitAt > -1) { + if (awaitAt !== null) { this.unexpected(awaitAt); } @@ -13841,7 +14276,7 @@ class StatementParser extends ExpressionParser { return this.parseForIn(node, init, awaitAt); } - if (awaitAt > -1) { + if (awaitAt !== null) { this.unexpected(awaitAt); } @@ -13855,9 +14290,15 @@ class StatementParser extends ExpressionParser { if (isForOf) { if (startsWithLet) { - this.raise(init.start, ErrorMessages.ForOfLet); - } else if (awaitAt === -1 && startsWithAsync && init.type === "Identifier") { - this.raise(init.start, ErrorMessages.ForOfAsync); + this.raise(ErrorMessages.ForOfLet, { + node: init + }); + } + + if (awaitAt === null && startsWithAsync && init.type === "Identifier") { + this.raise(ErrorMessages.ForOfAsync, { + node: init + }); } } @@ -13870,7 +14311,7 @@ class StatementParser extends ExpressionParser { this.checkExpressionErrors(refExpressionErrors, true); } - if (awaitAt > -1) { + if (awaitAt !== null) { this.unexpected(awaitAt); } @@ -13892,7 +14333,9 @@ class StatementParser extends ExpressionParser { parseReturnStatement(node) { if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) { - this.raise(this.state.start, ErrorMessages.IllegalReturn); + this.raise(ErrorMessages.IllegalReturn, { + at: this.state.startLoc + }); } this.next(); @@ -13928,7 +14371,9 @@ class StatementParser extends ExpressionParser { cur.test = this.parseExpression(); } else { if (sawDefault) { - this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch); + this.raise(ErrorMessages.MultipleDefaultsInSwitch, { + at: this.state.lastTokStartLoc + }); } sawDefault = true; @@ -13956,7 +14401,9 @@ class StatementParser extends ExpressionParser { this.next(); if (this.hasPrecedingLineBreak()) { - this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow); + this.raise(ErrorMessages.NewlineAfterThrow, { + at: this.state.lastTokEndLoc + }); } node.argument = this.parseExpression(); @@ -13998,7 +14445,9 @@ class StatementParser extends ExpressionParser { node.finalizer = this.eat(63) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { - this.raise(node.start, ErrorMessages.NoCatchOrFinally); + this.raise(ErrorMessages.NoCatchOrFinally, { + node + }); } return this.finishNode(node, "TryStatement"); @@ -14022,7 +14471,9 @@ class StatementParser extends ExpressionParser { parseWithStatement(node) { if (this.state.strict) { - this.raise(this.state.start, ErrorMessages.StrictWith); + this.raise(ErrorMessages.StrictWith, { + at: this.state.startLoc + }); } this.next(); @@ -14039,7 +14490,9 @@ class StatementParser extends ExpressionParser { parseLabeledStatement(node, maybeName, expr, context) { for (const label of this.state.labels) { if (label.name === maybeName) { - this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName); + this.raise(ErrorMessages.LabelRedeclaration, { + node: expr + }, maybeName); } } @@ -14162,15 +14615,21 @@ class StatementParser extends ExpressionParser { this.next(); if (isForIn) { - if (awaitAt > -1) this.unexpected(awaitAt); + if (awaitAt !== null) this.unexpected(awaitAt); } else { - node.await = awaitAt > -1; + node.await = awaitAt !== null; } if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { - this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of"); - } else if (init.type === "AssignmentPattern") { - this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop"); + this.raise(ErrorMessages.ForInOfLoopInitializer, { + node: init + }, isForIn ? "for-in" : "for-of"); + } + + if (init.type === "AssignmentPattern") { + this.raise(ErrorMessages.InvalidLhs, { + node: init + }, "for-loop"); } node.left = init; @@ -14196,10 +14655,14 @@ class StatementParser extends ExpressionParser { } else { if (kind === "const" && !(this.match(54) || this.isContextual(97))) { if (!isTypescript) { - this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations"); + this.raise(ErrorMessages.DeclarationMissingInitializer, { + at: this.state.lastTokEndLoc + }, "Const declarations"); } } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(54) || this.isContextual(97)))) { - this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns"); + this.raise(ErrorMessages.DeclarationMissingInitializer, { + at: this.state.lastTokEndLoc + }, "Complex binding patterns"); } decl.init = null; @@ -14224,7 +14687,9 @@ class StatementParser extends ExpressionParser { this.initFunction(node, isAsync); if (this.match(51) && isHangingStatement) { - this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext); + this.raise(ErrorMessages.GeneratorInSingleStatementContext, { + at: this.state.startLoc + }); } node.generator = this.eat(51); @@ -14270,7 +14735,7 @@ class StatementParser extends ExpressionParser { registerFunctionStatementId(node) { if (!node.id) return; - this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start); + this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.loc.start); } parseClass(node, isStatement, optionalId) { @@ -14310,7 +14775,9 @@ class StatementParser extends ExpressionParser { while (!this.match(8)) { if (this.eat(13)) { if (decorators.length > 0) { - throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon); + throw this.raise(ErrorMessages.DecoratorSemicolon, { + at: this.state.lastTokEndLoc + }); } continue; @@ -14332,7 +14799,9 @@ class StatementParser extends ExpressionParser { this.parseClassMember(classBody, member, state); if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { - this.raise(member.start, ErrorMessages.DecoratorConstructor); + this.raise(ErrorMessages.DecoratorConstructor, { + node: member + }); } } }); @@ -14340,7 +14809,9 @@ class StatementParser extends ExpressionParser { this.next(); if (decorators.length) { - throw this.raise(this.state.start, ErrorMessages.TrailingDecorator); + throw this.raise(ErrorMessages.TrailingDecorator, { + at: this.state.startLoc + }); } this.classScope.exit(); @@ -14409,7 +14880,9 @@ class StatementParser extends ExpressionParser { } if (this.isNonstaticConstructor(publicMethod)) { - this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator); + this.raise(ErrorMessages.ConstructorIsGenerator, { + node: publicMethod.key + }); } this.pushClassMethod(classBody, publicMethod, true, false, false, false); @@ -14419,7 +14892,7 @@ class StatementParser extends ExpressionParser { const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc; const isPrivate = this.match(130); const key = this.parseClassElementName(member); - const maybeQuestionTokenStart = this.state.start; + const maybeQuestionTokenStartLoc = this.state.startLoc; this.parsePostMemberNameModifiers(publicMember); if (this.isClassMethod()) { @@ -14437,11 +14910,15 @@ class StatementParser extends ExpressionParser { publicMethod.kind = "constructor"; if (state.hadConstructor && !this.hasPlugin("typescript")) { - this.raise(key.start, ErrorMessages.DuplicateConstructor); + this.raise(ErrorMessages.DuplicateConstructor, { + node: key + }); } if (isConstructor && this.hasPlugin("typescript") && member.override) { - this.raise(key.start, ErrorMessages.OverrideOnConstructor); + this.raise(ErrorMessages.OverrideOnConstructor, { + node: key + }); } state.hadConstructor = true; @@ -14460,7 +14937,7 @@ class StatementParser extends ExpressionParser { const isGenerator = this.eat(51); if (publicMember.optional) { - this.unexpected(maybeQuestionTokenStart); + this.unexpected(maybeQuestionTokenStartLoc); } method.kind = "method"; @@ -14472,7 +14949,9 @@ class StatementParser extends ExpressionParser { this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); } else { if (this.isNonstaticConstructor(publicMethod)) { - this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync); + this.raise(ErrorMessages.ConstructorIsAsync, { + node: publicMethod.key + }); } this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); @@ -14487,7 +14966,9 @@ class StatementParser extends ExpressionParser { this.pushClassPrivateMethod(classBody, privateMethod, false, false); } else { if (this.isNonstaticConstructor(publicMethod)) { - this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor); + this.raise(ErrorMessages.ConstructorIsAccessor, { + node: publicMethod.key + }); } this.pushClassMethod(classBody, publicMethod, false, false, false, false); @@ -14508,17 +14989,20 @@ class StatementParser extends ExpressionParser { parseClassElementName(member) { const { type, - value, - start + value } = this.state; if ((type === 124 || type === 125) && member.static && value === "prototype") { - this.raise(start, ErrorMessages.StaticPrototype); + this.raise(ErrorMessages.StaticPrototype, { + at: this.state.startLoc + }); } if (type === 130) { if (value === "constructor") { - this.raise(start, ErrorMessages.ConstructorClassPrivateField); + this.raise(ErrorMessages.ConstructorClassPrivateField, { + at: this.state.startLoc + }); } const key = this.parsePrivateName(); @@ -14544,13 +15028,17 @@ class StatementParser extends ExpressionParser { classBody.body.push(this.finishNode(member, "StaticBlock")); if ((_member$decorators = member.decorators) != null && _member$decorators.length) { - this.raise(member.start, ErrorMessages.DecoratorStaticBlock); + this.raise(ErrorMessages.DecoratorStaticBlock, { + node: member + }); } } pushClassProperty(classBody, prop) { if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) { - this.raise(prop.key.start, ErrorMessages.ConstructorClassField); + this.raise(ErrorMessages.ConstructorClassField, { + node: prop.key + }); } classBody.body.push(this.parseClassProperty(prop)); @@ -14559,7 +15047,7 @@ class StatementParser extends ExpressionParser { pushClassPrivateProperty(classBody, prop) { const node = this.parseClassPrivateProperty(prop); classBody.body.push(node); - this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start); + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.loc.start); } pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { @@ -14574,7 +15062,7 @@ class StatementParser extends ExpressionParser { } declareClassPrivateMethodInScope(node, kind) { - this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start); + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start); } parsePostMemberNameModifiers(methodOrProp) {} @@ -14612,7 +15100,9 @@ class StatementParser extends ExpressionParser { if (optionalId || !isStatement) { node.id = null; } else { - this.unexpected(null, ErrorMessages.MissingClassName); + throw this.raise(ErrorMessages.MissingClassName, { + at: this.state.startLoc + }); } } } @@ -14745,22 +15235,32 @@ class StatementParser extends ExpressionParser { } return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync); - } else if (this.match(76)) { + } + + if (this.match(76)) { return this.parseClass(expr, true, true); - } else if (this.match(26)) { + } + + if (this.match(26)) { if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) { - this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport); + this.raise(ErrorMessages.DecoratorBeforeExport, { + at: this.state.startLoc + }); } this.parseDecorators(false); return this.parseClass(expr, true, true); - } else if (this.match(71) || this.match(70) || this.isLet()) { - throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport); - } else { - const res = this.parseMaybeAssignAllowIn(); - this.semicolon(); - return res; } + + if (this.match(71) || this.match(70) || this.isLet()) { + throw this.raise(ErrorMessages.UnsupportedDefaultExport, { + at: this.state.startLoc + }); + } + + const res = this.parseMaybeAssignAllowIn(); + this.semicolon(); + return res; } parseExportDeclaration(node) { @@ -14832,10 +15332,12 @@ class StatementParser extends ExpressionParser { if (this.hasPlugin("decorators")) { if (this.getPluginOption("decorators", "decoratorsBeforeExport")) { - this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport); - } else { - return true; + throw this.raise(ErrorMessages.DecoratorBeforeExport, { + at: this.state.startLoc + }); } + + return true; } } @@ -14853,7 +15355,9 @@ class StatementParser extends ExpressionParser { const declaration = node.declaration; if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) { - this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier); + this.raise(ErrorMessages.ExportDefaultFromAsIdentifier, { + node: declaration + }); } } } else if (node.specifiers && node.specifiers.length) { @@ -14870,9 +15374,11 @@ class StatementParser extends ExpressionParser { } = specifier; if (local.type !== "Identifier") { - this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName); + this.raise(ErrorMessages.ExportBindingIsString, { + node: specifier + }, local.value, exportedName); } else { - this.checkReservedWord(local.name, local.start, true, false); + this.checkReservedWord(local.name, local.loc.start, true, false); this.scope.checkLocalExport(local); } } @@ -14893,7 +15399,9 @@ class StatementParser extends ExpressionParser { const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; if (currentContextDecorators.length) { - throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport); + throw this.raise(ErrorMessages.UnsupportedDecoratorExport, { + node + }); } } @@ -14921,7 +15429,9 @@ class StatementParser extends ExpressionParser { checkDuplicateExports(node, name) { if (this.exportedIdentifiers.has(name)) { - this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name); + this.raise(name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, { + node + }, name); } this.exportedIdentifiers.add(name); @@ -14968,7 +15478,9 @@ class StatementParser extends ExpressionParser { const surrogate = result.value.match(loneSurrogate); if (surrogate) { - this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16)); + this.raise(ErrorMessages.ModuleExportNameHasLoneSurrogate, { + node: result + }, surrogate[0].charCodeAt(0).toString(16)); } return result; @@ -15033,7 +15545,9 @@ class StatementParser extends ExpressionParser { const keyName = this.state.value; if (attrNames.has(keyName)) { - this.raise(this.state.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName); + this.raise(ErrorMessages.ModuleAttributesWithDuplicateKeys, { + at: this.state.startLoc + }, keyName); } attrNames.add(keyName); @@ -15047,7 +15561,9 @@ class StatementParser extends ExpressionParser { this.expect(14); if (!this.match(125)) { - throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue); + throw this.raise(ErrorMessages.ModuleAttributeInvalidValue, { + at: this.state.startLoc + }); } node.value = this.parseStringLiteral(this.state.value); @@ -15075,18 +15591,24 @@ class StatementParser extends ExpressionParser { node.key = this.parseIdentifier(true); if (node.key.name !== "type") { - this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name); + this.raise(ErrorMessages.ModuleAttributeDifferentFromType, { + node: node.key + }, node.key.name); } if (attributes.has(node.key.name)) { - this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name); + this.raise(ErrorMessages.ModuleAttributesWithDuplicateKeys, { + node: node.key + }, node.key.name); } attributes.add(node.key.name); this.expect(14); if (!this.match(125)) { - throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue); + throw this.raise(ErrorMessages.ModuleAttributeInvalidValue, { + at: this.state.startLoc + }); } node.value = this.parseStringLiteral(this.state.value); @@ -15142,7 +15664,9 @@ class StatementParser extends ExpressionParser { first = false; } else { if (this.eat(14)) { - throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport); + throw this.raise(ErrorMessages.DestructureNamedImport, { + at: this.state.startLoc + }); } this.expect(12); @@ -15167,10 +15691,12 @@ class StatementParser extends ExpressionParser { } = specifier; if (importedIsString) { - throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value); + throw this.raise(ErrorMessages.ImportBindingIsString, { + node: specifier + }, imported.value); } - this.checkReservedWord(imported.name, specifier.start, true, true); + this.checkReservedWord(imported.name, specifier.loc.start, true, true); if (!specifier.local) { specifier.local = cloneIdentifier(imported); diff --git a/node_modules/@babel/parser/lib/index.js.map b/node_modules/@babel/parser/lib/index.js.map index 6feca3ce6..48ff9a1a6 100644 --- a/node_modules/@babel/parser/lib/index.js.map +++ b/node_modules/@babel/parser/lib/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sources":["../src/util/whitespace.js","../src/util/location.js","../src/parser/base.js","../src/parser/comments.js","../src/parser/error-codes.js","../src/parser/error-message.js","../src/parser/error.js","../src/plugins/estree.js","../src/tokenizer/context.js","../src/tokenizer/types.js","../../babel-helper-validator-identifier/src/identifier.ts","../../babel-helper-validator-identifier/src/keyword.ts","../src/util/identifier.js","../src/util/scopeflags.js","../src/util/scope.js","../src/plugins/flow/scope.js","../src/tokenizer/state.js","../src/tokenizer/index.js","../src/util/class-scope.js","../src/util/expression-scope.js","../src/util/production-parameter.js","../src/parser/util.js","../src/parser/node.js","../src/plugins/flow/index.js","../src/plugins/jsx/xhtml.js","../src/plugins/jsx/index.js","../src/plugins/typescript/scope.js","../src/plugins/typescript/index.js","../src/plugins/placeholders.js","../src/plugins/v8intrinsic.js","../src/plugin-utils.js","../src/options.js","../src/parser/lval.js","../src/parser/expression.js","../src/parser/statement.js","../src/parser/index.js","../src/index.js"],"sourcesContent":["// @flow\n\nimport * as charCodes from \"charcodes\";\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\nexport const lineBreak = /\\r\\n?|[\\n\\u2028\\u2029]/;\nexport const lineBreakG = new RegExp(lineBreak.source, \"g\");\n\n// https://tc39.github.io/ecma262/#sec-line-terminators\nexport function isNewLine(code: number): boolean {\n switch (code) {\n case charCodes.lineFeed:\n case charCodes.carriageReturn:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return true;\n\n default:\n return false;\n }\n}\n\nexport const skipWhiteSpace = /(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g;\n\nexport const skipWhiteSpaceInLine =\n /(?:[^\\S\\n\\r\\u2028\\u2029]|\\/\\/.*|\\/\\*.*?\\*\\/)*/y;\n\n// Skip whitespace and single-line comments, including /* no newline here */.\n// After this RegExp matches, its lastIndex points to a line terminator, or\n// the start of multi-line comment (which is effectively a line terminator),\n// or the end of string.\nexport const skipWhiteSpaceToLineBreak = new RegExp(\n // Unfortunately JS doesn't support Perl's atomic /(?>pattern)/ or\n // possessive quantifiers, so we use a trick to prevent backtracking\n // when the look-ahead for line terminator fails.\n \"(?=(\" +\n // Capture the whitespace and comments that should be skipped inside\n // a look-ahead assertion, and then re-match the group as a unit.\n skipWhiteSpaceInLine.source +\n \"))\\\\1\" +\n // Look-ahead for either line terminator, start of multi-line comment,\n // or end of string.\n /(?=[\\n\\r\\u2028\\u2029]|\\/\\*(?!.*?\\*\\/)|$)/.source,\n \"y\", // sticky\n);\n\n// https://tc39.github.io/ecma262/#sec-white-space\nexport function isWhitespace(code: number): boolean {\n switch (code) {\n case 0x0009: // CHARACTER TABULATION\n case 0x000b: // LINE TABULATION\n case 0x000c: // FORM FEED\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.oghamSpaceMark:\n case 0x2000: // EN QUAD\n case 0x2001: // EM QUAD\n case 0x2002: // EN SPACE\n case 0x2003: // EM SPACE\n case 0x2004: // THREE-PER-EM SPACE\n case 0x2005: // FOUR-PER-EM SPACE\n case 0x2006: // SIX-PER-EM SPACE\n case 0x2007: // FIGURE SPACE\n case 0x2008: // PUNCTUATION SPACE\n case 0x2009: // THIN SPACE\n case 0x200a: // HAIR SPACE\n case 0x202f: // NARROW NO-BREAK SPACE\n case 0x205f: // MEDIUM MATHEMATICAL SPACE\n case 0x3000: // IDEOGRAPHIC SPACE\n case 0xfeff: // ZERO WIDTH NO-BREAK SPACE\n return true;\n\n default:\n return false;\n }\n}\n","// @flow\n\nimport { lineBreakG } from \"./whitespace\";\n\nexport type Pos = {\n start: number,\n};\n\n// These are used when `options.locations` is on, for the\n// `startLoc` and `endLoc` properties.\n\nexport class Position {\n line: number;\n column: number;\n\n constructor(line: number, col: number) {\n this.line = line;\n this.column = col;\n }\n}\n\nexport class SourceLocation {\n start: Position;\n end: Position;\n filename: string;\n identifierName: ?string;\n\n constructor(start: Position, end?: Position) {\n this.start = start;\n // $FlowIgnore (may start as null, but initialized later)\n this.end = end;\n }\n}\n\n// The `getLineInfo` function is mostly useful when the\n// `locations` option is off (for performance reasons) and you\n// want to find the line/column position for a given character\n// offset. `input` should be the code string that the offset refers\n// into.\n\nexport function getLineInfo(input: string, offset: number): Position {\n let line = 1;\n let lineStart = 0;\n let match;\n lineBreakG.lastIndex = 0;\n while ((match = lineBreakG.exec(input)) && match.index < offset) {\n line++;\n lineStart = lineBreakG.lastIndex;\n }\n\n return new Position(line, offset - lineStart);\n}\n\n/**\n * creates a new position with a non-zero column offset from the given position.\n * This function should be only be used when we create AST node out of the token\n * boundaries, such as TemplateElement ends before tt.templateNonTail. This\n * function does not skip whitespaces.\n *\n * @export\n * @param {Position} position\n * @param {number} columnOffset\n * @returns {Position}\n */\nexport function createPositionWithColumnOffset(\n position: Position,\n columnOffset: number,\n) {\n const { line, column } = position;\n return new Position(line, column + columnOffset);\n}\n","// @flow\n\nimport type { Options } from \"../options\";\nimport type State from \"../tokenizer/state\";\nimport type { PluginsMap } from \"./index\";\nimport type ScopeHandler from \"../util/scope\";\nimport type ExpressionScopeHandler from \"../util/expression-scope\";\nimport type ClassScopeHandler from \"../util/class-scope\";\nimport type ProductionParameterHandler from \"../util/production-parameter\";\n\nexport default class BaseParser {\n // Properties set by constructor in index.js\n declare options: Options;\n declare inModule: boolean;\n declare scope: ScopeHandler<*>;\n declare classScope: ClassScopeHandler;\n declare prodParam: ProductionParameterHandler;\n declare expressionScope: ExpressionScopeHandler;\n declare plugins: PluginsMap;\n declare filename: ?string;\n // Names of exports store. `default` is stored as a name for both\n // `export default foo;` and `export { foo as default };`.\n declare exportedIdentifiers: Set;\n sawUnambiguousESM: boolean = false;\n ambiguousScriptDifferentAst: boolean = false;\n\n // Initialized by Tokenizer\n declare state: State;\n // input and length are not in state as they are constant and we do\n // not want to ever copy them, which happens if state gets cloned\n declare input: string;\n declare length: number;\n\n // This method accepts either a string (plugin name) or an array pair\n // (plugin name and options object). If an options object is given,\n // then each value is non-recursively checked for identity with that\n // plugin’s actual option value.\n hasPlugin(pluginConfig: PluginConfig): boolean {\n if (typeof pluginConfig === \"string\") {\n return this.plugins.has(pluginConfig);\n } else {\n const [pluginName, pluginOptions] = pluginConfig;\n if (!this.hasPlugin(pluginName)) {\n return false;\n }\n const actualOptions = this.plugins.get(pluginName);\n for (const key of Object.keys(pluginOptions)) {\n if (actualOptions?.[key] !== pluginOptions[key]) {\n return false;\n }\n }\n return true;\n }\n }\n\n getPluginOption(plugin: string, name: string) {\n return this.plugins.get(plugin)?.[name];\n }\n}\n\nexport type PluginConfig = string | [string, { [string]: any }];\n","// @flow\n\n/*:: declare var invariant; */\n\nimport BaseParser from \"./base\";\nimport type { Comment, Node } from \"../types\";\nimport * as charCodes from \"charcodes\";\n\n/**\n * A whitespace token containing comments\n * @typedef CommentWhitespace\n * @type {object}\n * @property {number} start - the start of the whitespace token.\n * @property {number} end - the end of the whitespace token.\n * @property {Array} comments - the containing comments\n * @property {Node | null} leadingNode - the immediately preceding AST node of the whitespace token\n * @property {Node | null} trailingNode - the immediately following AST node of the whitespace token\n * @property {Node | null} containingNode - the innermost AST node containing the whitespace\n * with minimal size (|end - start|)\n */\nexport type CommentWhitespace = {\n start: number,\n end: number,\n comments: Array,\n leadingNode: Node | null,\n trailingNode: Node | null,\n containingNode: Node | null,\n};\n\n/**\n * Merge comments with node's trailingComments or assign comments to be\n * trailingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n *\n * @param {Node} node\n * @param {Array} comments\n */\nfunction setTrailingComments(node: Node, comments: Array) {\n if (node.trailingComments === undefined) {\n node.trailingComments = comments;\n } else {\n node.trailingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's leadingComments or assign comments to be\n * leadingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n *\n * @param {Node} node\n * @param {Array} comments\n */\nfunction setLeadingComments(node: Node, comments: Array) {\n if (node.leadingComments === undefined) {\n node.leadingComments = comments;\n } else {\n node.leadingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's innerComments or assign comments to be\n * innerComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n *\n * @param {Node} node\n * @param {Array} comments\n */\nexport function setInnerComments(node: Node, comments: Array) {\n if (node.innerComments === undefined) {\n node.innerComments = comments;\n } else {\n node.innerComments.unshift(...comments);\n }\n}\n\n/**\n * Given node and elements array, if elements has non-null element,\n * merge comments to its trailingComments, otherwise merge comments\n * to node's innerComments\n *\n * @param {Node} node\n * @param {Array} elements\n * @param {Array} comments\n */\nfunction adjustInnerComments(\n node: Node,\n elements: Array,\n commentWS: CommentWhitespace,\n) {\n let lastElement = null;\n let i = elements.length;\n while (lastElement === null && i > 0) {\n lastElement = elements[--i];\n }\n if (lastElement === null || lastElement.start > commentWS.start) {\n setInnerComments(node, commentWS.comments);\n } else {\n setTrailingComments(lastElement, commentWS.comments);\n }\n}\n\n/** @class CommentsParser */\nexport default class CommentsParser extends BaseParser {\n addComment(comment: Comment): void {\n if (this.filename) comment.loc.filename = this.filename;\n this.state.comments.push(comment);\n }\n\n /**\n * Given a newly created AST node _n_, attach _n_ to a comment whitespace _w_ if applicable\n * {@see {@link CommentWhitespace}}\n *\n * @param {Node} node\n * @returns {void}\n * @memberof CommentsParser\n */\n processComment(node: Node): void {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n const lastCommentWS = commentStack[i];\n\n if (lastCommentWS.start === node.end) {\n lastCommentWS.leadingNode = node;\n i--;\n }\n\n const { start: nodeStart } = node;\n // invariant: for all 0 <= j <= i, let c = commentStack[j], c must satisfy c.end < node.end\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n if (commentEnd > nodeStart) {\n // by definition of commentWhiteSpace, this implies commentWS.start > nodeStart\n // so node can be a containingNode candidate. At this time we can finalize the comment\n // whitespace, because\n // 1) its leadingNode or trailingNode, if exists, will not change\n // 2) its containingNode have been assigned and will not change because it is the\n // innermost minimal-sized AST node\n commentWS.containingNode = node;\n this.finalizeComment(commentWS);\n commentStack.splice(i, 1);\n } else {\n if (commentEnd === nodeStart) {\n commentWS.trailingNode = node;\n }\n // stop the loop when commentEnd <= nodeStart\n break;\n }\n }\n }\n\n /**\n * Assign the comments of comment whitespaces to related AST nodes.\n * Also adjust innerComments following trailing comma.\n *\n * @memberof CommentsParser\n */\n finalizeComment(commentWS: CommentWhitespace) {\n const { comments } = commentWS;\n if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {\n if (commentWS.leadingNode !== null) {\n setTrailingComments(commentWS.leadingNode, comments);\n }\n if (commentWS.trailingNode !== null) {\n setLeadingComments(commentWS.trailingNode, comments);\n }\n } else {\n /*:: invariant(commentWS.containingNode !== null) */\n const { containingNode: node, start: commentStart } = commentWS;\n if (this.input.charCodeAt(commentStart - 1) === charCodes.comma) {\n // If a commentWhitespace follows a comma and the containingNode allows\n // list structures with trailing comma, merge it to the trailingComment\n // of the last non-null list element\n switch (node.type) {\n case \"ObjectExpression\":\n case \"ObjectPattern\":\n case \"RecordExpression\":\n adjustInnerComments(node, node.properties, commentWS);\n break;\n case \"CallExpression\":\n case \"OptionalCallExpression\":\n adjustInnerComments(node, node.arguments, commentWS);\n break;\n case \"FunctionDeclaration\":\n case \"FunctionExpression\":\n case \"ArrowFunctionExpression\":\n case \"ObjectMethod\":\n case \"ClassMethod\":\n case \"ClassPrivateMethod\":\n adjustInnerComments(node, node.params, commentWS);\n break;\n case \"ArrayExpression\":\n case \"ArrayPattern\":\n case \"TupleExpression\":\n adjustInnerComments(node, node.elements, commentWS);\n break;\n case \"ExportNamedDeclaration\":\n case \"ImportDeclaration\":\n adjustInnerComments(node, node.specifiers, commentWS);\n break;\n default: {\n setInnerComments(node, comments);\n }\n }\n } else {\n setInnerComments(node, comments);\n }\n }\n }\n\n /**\n * Drains remaning commentStack and applies finalizeComment\n * to each comment whitespace. Used only in parseExpression\n * where the top level AST node is _not_ Program\n * {@see {@link CommentsParser#finalizeComment}}\n *\n * @memberof CommentsParser\n */\n finalizeRemainingComments() {\n const { commentStack } = this.state;\n for (let i = commentStack.length - 1; i >= 0; i--) {\n this.finalizeComment(commentStack[i]);\n }\n this.state.commentStack = [];\n }\n\n /**\n * Reset previous node trailing comments. Used in object / class\n * property parsing. We parse `async`, `static`, `set` and `get`\n * as an identifier but may reinterepret it into an async/static/accessor\n * method later. In this case the identifier is not part of the AST and we\n * should sync the knowledge to commentStacks\n *\n * For example, when parsing */\n // async /* 1 */ function f() {}\n /*\n * the comment whitespace \"* 1 *\" has leading node Identifier(async). When\n * we see the function token, we create a Function node and mark \"* 1 *\" as\n * inner comments. So \"* 1 *\" should be detached from the Identifier node.\n *\n * @param {N.Node} node the last finished AST node _before_ current token\n * @returns\n * @memberof CommentsParser\n */\n resetPreviousNodeTrailingComments(node: Node) {\n const { commentStack } = this.state;\n const { length } = commentStack;\n if (length === 0) return;\n const commentWS = commentStack[length - 1];\n if (commentWS.leadingNode === node) {\n commentWS.leadingNode = null;\n }\n }\n\n /**\n * Attach a node to the comment whitespaces right before/after\n * the given range.\n *\n * This is used to properly attach comments around parenthesized\n * expressions as leading/trailing comments of the inner expression.\n *\n * @param {Node} node\n * @param {number} start\n * @param {number} end\n */\n takeSurroundingComments(node: Node, start: number, end: number) {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n const commentStart = commentWS.start;\n\n if (commentStart === end) {\n commentWS.leadingNode = node;\n } else if (commentEnd === start) {\n commentWS.trailingNode = node;\n } else if (commentEnd < start) {\n break;\n }\n }\n }\n}\n","// @flow\n\nexport const ErrorCodes = Object.freeze({\n SyntaxError: \"BABEL_PARSER_SYNTAX_ERROR\",\n SourceTypeModuleError: \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\",\n});\n\nexport type ErrorCode = $Values;\n","// @flow\n\nimport { makeErrorTemplates, ErrorCodes } from \"./error\";\n\n/* eslint sort-keys: \"error\" */\n\n/**\n * @module parser/error-message\n */\n\n// The Errors key follows https://cs.chromium.org/chromium/src/v8/src/common/message-template.h unless it does not exist\nexport const ErrorMessages = makeErrorTemplates(\n {\n AccessorIsGenerator: \"A %0ter cannot be a generator.\",\n ArgumentsInClass:\n \"'arguments' is only allowed in functions and class methods.\",\n AsyncFunctionInSingleStatementContext:\n \"Async functions can only be declared at the top level or inside a block.\",\n AwaitBindingIdentifier:\n \"Can not use 'await' as identifier inside an async function.\",\n AwaitBindingIdentifierInStaticBlock:\n \"Can not use 'await' as identifier inside a static block.\",\n AwaitExpressionFormalParameter:\n \"'await' is not allowed in async function parameters.\",\n AwaitNotInAsyncContext:\n \"'await' is only allowed within async functions and at the top levels of modules.\",\n AwaitNotInAsyncFunction: \"'await' is only allowed within async functions.\",\n BadGetterArity: \"A 'get' accesor must not have any formal parameters.\",\n BadSetterArity: \"A 'set' accesor must have exactly one formal parameter.\",\n BadSetterRestParameter:\n \"A 'set' accesor function argument must not be a rest parameter.\",\n ConstructorClassField: \"Classes may not have a field named 'constructor'.\",\n ConstructorClassPrivateField:\n \"Classes may not have a private field named '#constructor'.\",\n ConstructorIsAccessor: \"Class constructor may not be an accessor.\",\n ConstructorIsAsync: \"Constructor can't be an async function.\",\n ConstructorIsGenerator: \"Constructor can't be a generator.\",\n DeclarationMissingInitializer: \"'%0' require an initialization value.\",\n DecoratorBeforeExport:\n \"Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax.\",\n DecoratorConstructor:\n \"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?\",\n DecoratorExportClass:\n \"Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.\",\n DecoratorSemicolon: \"Decorators must not be followed by a semicolon.\",\n DecoratorStaticBlock: \"Decorators can't be used with a static block.\",\n DeletePrivateField: \"Deleting a private field is not allowed.\",\n DestructureNamedImport:\n \"ES2015 named imports do not destructure. Use another statement for destructuring after the import.\",\n DuplicateConstructor: \"Duplicate constructor in the same class.\",\n DuplicateDefaultExport: \"Only one default export allowed per module.\",\n DuplicateExport:\n \"`%0` has already been exported. Exported identifiers must be unique.\",\n DuplicateProto: \"Redefinition of __proto__ property.\",\n DuplicateRegExpFlags: \"Duplicate regular expression flag.\",\n ElementAfterRest: \"Rest element must be last element.\",\n EscapedCharNotAnIdentifier: \"Invalid Unicode escape.\",\n ExportBindingIsString:\n \"A string literal cannot be used as an exported binding without `from`.\\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?\",\n ExportDefaultFromAsIdentifier:\n \"'from' is not allowed as an identifier after 'export default'.\",\n ForInOfLoopInitializer:\n \"'%0' loop variable declaration may not have an initializer.\",\n ForOfAsync: \"The left-hand side of a for-of loop may not be 'async'.\",\n ForOfLet: \"The left-hand side of a for-of loop may not start with 'let'.\",\n GeneratorInSingleStatementContext:\n \"Generators can only be declared at the top level or inside a block.\",\n IllegalBreakContinue: \"Unsyntactic %0.\",\n IllegalLanguageModeDirective:\n \"Illegal 'use strict' directive in function with non-simple parameter list.\",\n IllegalReturn: \"'return' outside of function.\",\n ImportBindingIsString:\n 'A string literal cannot be used as an imported binding.\\n- Did you mean `import { \"%0\" as foo }`?',\n ImportCallArgumentTrailingComma:\n \"Trailing comma is disallowed inside import(...) arguments.\",\n ImportCallArity: \"`import()` requires exactly %0.\",\n ImportCallNotNewExpression: \"Cannot use new with import(...).\",\n ImportCallSpreadArgument: \"`...` is not allowed in `import()`.\",\n InvalidBigIntLiteral: \"Invalid BigIntLiteral.\",\n InvalidCodePoint: \"Code point out of bounds.\",\n InvalidCoverInitializedName: \"Invalid shorthand property initializer.\",\n InvalidDecimal: \"Invalid decimal.\",\n InvalidDigit: \"Expected number in radix %0.\",\n InvalidEscapeSequence: \"Bad character escape sequence.\",\n InvalidEscapeSequenceTemplate: \"Invalid escape sequence in template.\",\n InvalidEscapedReservedWord: \"Escape sequence in keyword %0.\",\n InvalidIdentifier: \"Invalid identifier %0.\",\n InvalidLhs: \"Invalid left-hand side in %0.\",\n InvalidLhsBinding: \"Binding invalid left-hand side in %0.\",\n InvalidNumber: \"Invalid number.\",\n InvalidOrMissingExponent:\n \"Floating-point numbers require a valid exponent after the 'e'.\",\n InvalidOrUnexpectedToken: \"Unexpected character '%0'.\",\n InvalidParenthesizedAssignment: \"Invalid parenthesized assignment pattern.\",\n InvalidPrivateFieldResolution: \"Private name #%0 is not defined.\",\n InvalidPropertyBindingPattern: \"Binding member expression.\",\n InvalidRecordProperty:\n \"Only properties and spread elements are allowed in record definitions.\",\n InvalidRestAssignmentPattern: \"Invalid rest operator's argument.\",\n LabelRedeclaration: \"Label '%0' is already declared.\",\n LetInLexicalBinding:\n \"'let' is not allowed to be used as a name in 'let' or 'const' declarations.\",\n LineTerminatorBeforeArrow: \"No line break is allowed before '=>'.\",\n MalformedRegExpFlags: \"Invalid regular expression flag.\",\n MissingClassName: \"A class name is required.\",\n MissingEqInAssignment:\n \"Only '=' operator can be used for specifying default value.\",\n MissingSemicolon: \"Missing semicolon.\",\n MissingUnicodeEscape: \"Expecting Unicode escape sequence \\\\uXXXX.\",\n MixingCoalesceWithLogical:\n \"Nullish coalescing operator(??) requires parens when mixing with logical operators.\",\n ModuleAttributeDifferentFromType:\n \"The only accepted module attribute is `type`.\",\n ModuleAttributeInvalidValue:\n \"Only string literals are allowed as module attribute values.\",\n ModuleAttributesWithDuplicateKeys:\n 'Duplicate key \"%0\" is not allowed in module attributes.',\n ModuleExportNameHasLoneSurrogate:\n \"An export name cannot include a lone surrogate, found '\\\\u%0'.\",\n ModuleExportUndefined: \"Export '%0' is not defined.\",\n MultipleDefaultsInSwitch: \"Multiple default clauses.\",\n NewlineAfterThrow: \"Illegal newline after throw.\",\n NoCatchOrFinally: \"Missing catch or finally clause.\",\n NumberIdentifier: \"Identifier directly after number.\",\n NumericSeparatorInEscapeSequence:\n \"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.\",\n ObsoleteAwaitStar:\n \"'await*' has been removed from the async functions proposal. Use Promise.all() instead.\",\n OptionalChainingNoNew:\n \"Constructors in/after an Optional Chain are not allowed.\",\n OptionalChainingNoTemplate:\n \"Tagged Template Literals are not allowed in optionalChain.\",\n OverrideOnConstructor:\n \"'override' modifier cannot appear on a constructor declaration.\",\n ParamDupe: \"Argument name clash.\",\n PatternHasAccessor: \"Object pattern can't contain getter or setter.\",\n PatternHasMethod: \"Object pattern can't contain methods.\",\n // This error is only used by the smart-mix proposal\n PipeBodyIsTighter:\n \"Unexpected %0 after pipeline body; any %0 expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.\",\n PipeTopicRequiresHackPipes:\n 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n PipeTopicUnbound:\n \"Topic reference is unbound; it must be inside a pipe body.\",\n PipeTopicUnconfiguredToken:\n 'Invalid topic token %0. In order to use %0 as a topic reference, the pipelineOperator plugin must be configured with { \"proposal\": \"hack\", \"topicToken\": \"%0\" }.',\n PipeTopicUnused:\n \"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.\",\n PipeUnparenthesizedBody:\n \"Hack-style pipe body cannot be an unparenthesized %0 expression; please wrap it in parentheses.\",\n\n // Messages whose codes start with “Pipeline” or “PrimaryTopic”\n // are retained for backwards compatibility\n // with the deprecated smart-mix pipe operator proposal plugin.\n // They are subject to removal in a future major version.\n PipelineBodyNoArrow:\n 'Unexpected arrow \"=>\" after pipeline body; arrow function in pipeline body must be parenthesized.',\n PipelineBodySequenceExpression:\n \"Pipeline body may not be a comma-separated sequence expression.\",\n PipelineHeadSequenceExpression:\n \"Pipeline head should not be a comma-separated sequence expression.\",\n PipelineTopicUnused:\n \"Pipeline is in topic style but does not use topic reference.\",\n PrimaryTopicNotAllowed:\n \"Topic reference was used in a lexical context without topic binding.\",\n PrimaryTopicRequiresSmartPipeline:\n 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n\n PrivateInExpectedIn:\n \"Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`).\",\n PrivateNameRedeclaration: \"Duplicate private name #%0.\",\n RecordExpressionBarIncorrectEndSyntaxType:\n \"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionBarIncorrectStartSyntaxType:\n \"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionHashIncorrectStartSyntaxType:\n \"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n RecordNoProto: \"'__proto__' is not allowed in Record expressions.\",\n RestTrailingComma: \"Unexpected trailing comma after rest element.\",\n SloppyFunction:\n \"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.\",\n StaticPrototype: \"Classes may not have static property named prototype.\",\n StrictDelete: \"Deleting local variable in strict mode.\",\n StrictEvalArguments: \"Assigning to '%0' in strict mode.\",\n StrictEvalArgumentsBinding: \"Binding '%0' in strict mode.\",\n StrictFunction:\n \"In strict mode code, functions can only be declared at top level or inside a block.\",\n StrictNumericEscape:\n \"The only valid numeric escape in strict mode is '\\\\0'.\",\n StrictOctalLiteral: \"Legacy octal literals are not allowed in strict mode.\",\n StrictWith: \"'with' in strict mode.\",\n SuperNotAllowed:\n \"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?\",\n SuperPrivateField: \"Private fields can't be accessed on super.\",\n TrailingDecorator: \"Decorators must be attached to a class element.\",\n TupleExpressionBarIncorrectEndSyntaxType:\n \"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionBarIncorrectStartSyntaxType:\n \"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionHashIncorrectStartSyntaxType:\n \"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n UnexpectedArgumentPlaceholder: \"Unexpected argument placeholder.\",\n UnexpectedAwaitAfterPipelineBody:\n 'Unexpected \"await\" after pipeline body; await must have parentheses in minimal proposal.',\n UnexpectedDigitAfterHash: \"Unexpected digit after hash token.\",\n UnexpectedImportExport:\n \"'import' and 'export' may only appear at the top level.\",\n UnexpectedKeyword: \"Unexpected keyword '%0'.\",\n UnexpectedLeadingDecorator:\n \"Leading decorators must be attached to a class declaration.\",\n UnexpectedLexicalDeclaration:\n \"Lexical declaration cannot appear in a single-statement context.\",\n UnexpectedNewTarget:\n \"`new.target` can only be used in functions or class properties.\",\n UnexpectedNumericSeparator:\n \"A numeric separator is only allowed between two digits.\",\n UnexpectedPrivateField: \"Unexpected private name.\",\n UnexpectedReservedWord: \"Unexpected reserved word '%0'.\",\n UnexpectedSuper: \"'super' is only allowed in object methods and classes.\",\n UnexpectedToken: \"Unexpected token '%0'.\",\n UnexpectedTokenUnaryExponentiation:\n \"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.\",\n UnsupportedBind: \"Binding should be performed on object property.\",\n UnsupportedDecoratorExport:\n \"A decorated export must export a class declaration.\",\n UnsupportedDefaultExport:\n \"Only expressions, functions or classes are allowed as the `default` export.\",\n UnsupportedImport:\n \"`import` can only be used in `import()` or `import.meta`.\",\n UnsupportedMetaProperty: \"The only valid meta property for %0 is %0.%1.\",\n UnsupportedParameterDecorator:\n \"Decorators cannot be used to decorate parameters.\",\n UnsupportedPropertyDecorator:\n \"Decorators cannot be used to decorate object literal properties.\",\n UnsupportedSuper:\n \"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).\",\n UnterminatedComment: \"Unterminated comment.\",\n UnterminatedRegExp: \"Unterminated regular expression.\",\n UnterminatedString: \"Unterminated string constant.\",\n UnterminatedTemplate: \"Unterminated template.\",\n VarRedeclaration: \"Identifier '%0' has already been declared.\",\n YieldBindingIdentifier:\n \"Can not use 'yield' as identifier inside a generator.\",\n YieldInParameter: \"Yield expression is not allowed in formal parameters.\",\n ZeroDigitNumericSeparator:\n \"Numeric separator can not be used after leading 0.\",\n },\n /* code */ ErrorCodes.SyntaxError,\n);\n\nexport const SourceTypeModuleErrorMessages = makeErrorTemplates(\n {\n ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: \"module\"'`,\n ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: \"module\"'`,\n },\n /* code */ ErrorCodes.SourceTypeModuleError,\n);\n","// @flow\n/* eslint sort-keys: \"error\" */\nimport { getLineInfo, type Position } from \"../util/location\";\nimport CommentsParser from \"./comments\";\nimport { type ErrorCode, ErrorCodes } from \"./error-codes\";\n\n// This function is used to raise exceptions on parse errors. It\n// takes an offset integer (into the current `input`) to indicate\n// the location of the error, attaches the position to the end\n// of the error message, and then raises a `SyntaxError` with that\n// message.\n\ntype ErrorContext = {\n pos: number,\n loc: Position,\n missingPlugin?: Array,\n code?: string,\n reasonCode?: String,\n};\nexport type ParsingError = SyntaxError & ErrorContext;\n\nexport type ErrorTemplate = {\n code: ErrorCode,\n template: string,\n reasonCode: string,\n};\nexport type ErrorTemplates = {\n [key: string]: ErrorTemplate,\n};\n\ntype SyntaxPlugin = \"flow\" | \"typescript\" | \"jsx\" | typeof undefined;\n\nfunction keepReasonCodeCompat(reasonCode: string, syntaxPlugin: SyntaxPlugin) {\n if (!process.env.BABEL_8_BREAKING) {\n // For consistency in TypeScript and Flow error codes\n if (syntaxPlugin === \"flow\" && reasonCode === \"PatternIsOptional\") {\n return \"OptionalBindingPattern\";\n }\n }\n return reasonCode;\n}\n\nexport function makeErrorTemplates(\n messages: {\n [key: string]: string,\n },\n code: ErrorCode,\n syntaxPlugin?: SyntaxPlugin,\n): ErrorTemplates {\n const templates: ErrorTemplates = {};\n Object.keys(messages).forEach(reasonCode => {\n templates[reasonCode] = Object.freeze({\n code,\n reasonCode: keepReasonCodeCompat(reasonCode, syntaxPlugin),\n template: messages[reasonCode],\n });\n });\n return Object.freeze(templates);\n}\n\nexport { ErrorCodes };\nexport {\n ErrorMessages as Errors,\n SourceTypeModuleErrorMessages as SourceTypeModuleErrors,\n} from \"./error-message\";\n\nexport type raiseFunction = (number, ErrorTemplate, ...any) => void;\n\nexport default class ParserError extends CommentsParser {\n // Forward-declaration: defined in tokenizer/index.js\n /*::\n +isLookahead: boolean;\n */\n\n getLocationForPosition(pos: number): Position {\n let loc;\n if (pos === this.state.start) loc = this.state.startLoc;\n else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;\n else if (pos === this.state.end) loc = this.state.endLoc;\n else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;\n else loc = getLineInfo(this.input, pos);\n\n return loc;\n }\n\n raise(\n pos: number,\n { code, reasonCode, template }: ErrorTemplate,\n ...params: any\n ): Error | empty {\n return this.raiseWithData(pos, { code, reasonCode }, template, ...params);\n }\n\n /**\n * Raise a parsing error on given position pos. If errorRecovery is true,\n * it will first search current errors and overwrite the error thrown on the exact\n * position before with the new error message. If errorRecovery is false, it\n * fallbacks to `raise`.\n *\n * @param {number} pos\n * @param {string} errorTemplate\n * @param {...any} params\n * @returns {(Error | empty)}\n * @memberof ParserError\n */\n raiseOverwrite(\n pos: number,\n { code, template }: ErrorTemplate,\n ...params: any\n ): Error | empty {\n const loc = this.getLocationForPosition(pos);\n const message =\n template.replace(/%(\\d+)/g, (_, i: number) => params[i]) +\n ` (${loc.line}:${loc.column})`;\n if (this.options.errorRecovery) {\n const errors = this.state.errors;\n for (let i = errors.length - 1; i >= 0; i--) {\n const error = errors[i];\n if (error.pos === pos) {\n return Object.assign(error, { message });\n } else if (error.pos < pos) {\n break;\n }\n }\n }\n return this._raise({ code, loc, pos }, message);\n }\n\n raiseWithData(\n pos: number,\n data?: {\n missingPlugin?: Array,\n code?: string,\n },\n errorTemplate: string,\n ...params: any\n ): Error | empty {\n const loc = this.getLocationForPosition(pos);\n const message =\n errorTemplate.replace(/%(\\d+)/g, (_, i: number) => params[i]) +\n ` (${loc.line}:${loc.column})`;\n return this._raise(Object.assign(({ loc, pos }: Object), data), message);\n }\n\n _raise(errorContext: ErrorContext, message: string): Error | empty {\n // $FlowIgnore\n const err: SyntaxError & ErrorContext = new SyntaxError(message);\n Object.assign(err, errorContext);\n if (this.options.errorRecovery) {\n if (!this.isLookahead) this.state.errors.push(err);\n return err;\n } else {\n throw err;\n }\n }\n}\n","// @flow\n\nimport { type TokenType } from \"../tokenizer/types\";\nimport type Parser from \"../parser\";\nimport type { ExpressionErrors } from \"../parser/util\";\nimport * as N from \"../types\";\nimport type { Position } from \"../util/location\";\nimport { Errors } from \"../parser/error\";\n\nexport default (superClass: Class): Class =>\n class extends superClass {\n parseRegExpLiteral({ pattern, flags }): N.Node {\n let regex = null;\n try {\n regex = new RegExp(pattern, flags);\n } catch (e) {\n // In environments that don't support these flags value will\n // be null as the regex can't be represented natively.\n }\n const node = this.estreeParseLiteral(regex);\n node.regex = { pattern, flags };\n\n return node;\n }\n\n parseBigIntLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/es2020.md#bigintliteral\n let bigInt;\n try {\n // $FlowIgnore\n bigInt = BigInt(value);\n } catch {\n bigInt = null;\n }\n const node = this.estreeParseLiteral(bigInt);\n node.bigint = String(node.value || value);\n\n return node;\n }\n\n parseDecimalLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/experimental/decimal.md\n // todo: use BigDecimal when node supports it.\n const decimal = null;\n const node = this.estreeParseLiteral(decimal);\n node.decimal = String(node.value || value);\n\n return node;\n }\n\n estreeParseLiteral(value: any) {\n return this.parseLiteral(value, \"Literal\");\n }\n\n parseStringLiteral(value: any): N.Node {\n return this.estreeParseLiteral(value);\n }\n\n parseNumericLiteral(value: any): any {\n return this.estreeParseLiteral(value);\n }\n\n parseNullLiteral(): N.Node {\n return this.estreeParseLiteral(null);\n }\n\n parseBooleanLiteral(value: boolean): N.BooleanLiteral {\n return this.estreeParseLiteral(value);\n }\n\n directiveToStmt(directive: N.Directive): N.ExpressionStatement {\n const directiveLiteral = directive.value;\n\n const stmt = this.startNodeAt(directive.start, directive.loc.start);\n const expression = this.startNodeAt(\n directiveLiteral.start,\n directiveLiteral.loc.start,\n );\n\n expression.value = directiveLiteral.extra.expressionValue;\n expression.raw = directiveLiteral.extra.raw;\n\n stmt.expression = this.finishNodeAt(\n expression,\n \"Literal\",\n directiveLiteral.end,\n directiveLiteral.loc.end,\n );\n stmt.directive = directiveLiteral.extra.raw.slice(1, -1);\n\n return this.finishNodeAt(\n stmt,\n \"ExpressionStatement\",\n directive.end,\n directive.loc.end,\n );\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n initFunction(\n node: N.BodilessFunctionOrMethodBase,\n isAsync: ?boolean,\n ): void {\n super.initFunction(node, isAsync);\n node.expression = false;\n }\n\n checkDeclaration(node: N.Pattern | N.ObjectProperty): void {\n if (node != null && this.isObjectProperty(node)) {\n this.checkDeclaration(((node: any): N.EstreeProperty).value);\n } else {\n super.checkDeclaration(node);\n }\n }\n\n getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {\n return ((method: any): N.EstreeProperty | N.EstreeMethodDefinition).value\n .params;\n }\n\n isValidDirective(stmt: N.Statement): boolean {\n return (\n stmt.type === \"ExpressionStatement\" &&\n stmt.expression.type === \"Literal\" &&\n typeof stmt.expression.value === \"string\" &&\n !stmt.expression.extra?.parenthesized\n );\n }\n\n parseBlockBody(\n node: N.BlockStatementLike,\n ...args: [?boolean, boolean, TokenType, void | (boolean => void)]\n ): void {\n super.parseBlockBody(node, ...args);\n\n const directiveStatements = node.directives.map(d =>\n this.directiveToStmt(d),\n );\n node.body = directiveStatements.concat(node.body);\n // $FlowIgnore - directives isn't optional in the type definition\n delete node.directives;\n }\n\n pushClassMethod(\n classBody: N.ClassBody,\n method: N.ClassMethod,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowsDirectSuper: boolean,\n ): void {\n this.parseMethod(\n method,\n isGenerator,\n isAsync,\n isConstructor,\n allowsDirectSuper,\n \"ClassMethod\",\n true,\n );\n if (method.typeParameters) {\n // $FlowIgnore\n method.value.typeParameters = method.typeParameters;\n delete method.typeParameters;\n }\n classBody.body.push(method);\n }\n\n parsePrivateName(): any {\n const node = super.parsePrivateName();\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return node;\n }\n }\n return this.convertPrivateNameToPrivateIdentifier(node);\n }\n\n convertPrivateNameToPrivateIdentifier(\n node: N.PrivateName,\n ): N.EstreePrivateIdentifier {\n const name = super.getPrivateNameSV(node);\n node = (node: any);\n delete node.id;\n node.name = name;\n node.type = \"PrivateIdentifier\";\n return node;\n }\n\n isPrivateName(node: N.Node): boolean {\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.isPrivateName(node);\n }\n }\n return node.type === \"PrivateIdentifier\";\n }\n\n getPrivateNameSV(node: N.Node): string {\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.getPrivateNameSV(node);\n }\n }\n return node.name;\n }\n\n parseLiteral(value: any, type: $ElementType): T {\n const node = super.parseLiteral(value, type);\n node.raw = node.extra.raw;\n delete node.extra;\n\n return node;\n }\n\n parseFunctionBody(\n node: N.Function,\n allowExpression: ?boolean,\n isMethod?: boolean = false,\n ): void {\n super.parseFunctionBody(node, allowExpression, isMethod);\n node.expression = node.body.type !== \"BlockStatement\";\n }\n\n parseMethod(\n node: T,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowDirectSuper: boolean,\n type: string,\n inClassScope: boolean = false,\n ): T {\n let funcNode = this.startNode();\n funcNode.kind = node.kind; // provide kind, so super method correctly sets state\n funcNode = super.parseMethod(\n funcNode,\n isGenerator,\n isAsync,\n isConstructor,\n allowDirectSuper,\n type,\n inClassScope,\n );\n funcNode.type = \"FunctionExpression\";\n delete funcNode.kind;\n // $FlowIgnore\n node.value = funcNode;\n if (type === \"ClassPrivateMethod\") {\n // $FlowIgnore\n node.computed = false;\n }\n type = \"MethodDefinition\";\n return this.finishNode(node, type);\n }\n\n parseClassProperty(...args: [N.ClassProperty]): any {\n const propertyNode = (super.parseClassProperty(...args): any);\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return (propertyNode: N.EstreePropertyDefinition);\n }\n }\n propertyNode.type = \"PropertyDefinition\";\n return (propertyNode: N.EstreePropertyDefinition);\n }\n\n parseClassPrivateProperty(...args: [N.ClassPrivateProperty]): any {\n const propertyNode = (super.parseClassPrivateProperty(...args): any);\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return (propertyNode: N.EstreePropertyDefinition);\n }\n }\n propertyNode.type = \"PropertyDefinition\";\n propertyNode.computed = false;\n return (propertyNode: N.EstreePropertyDefinition);\n }\n\n parseObjectMethod(\n prop: N.ObjectMethod,\n isGenerator: boolean,\n isAsync: boolean,\n isPattern: boolean,\n isAccessor: boolean,\n ): ?N.ObjectMethod {\n const node: N.EstreeProperty = (super.parseObjectMethod(\n prop,\n isGenerator,\n isAsync,\n isPattern,\n isAccessor,\n ): any);\n\n if (node) {\n node.type = \"Property\";\n if (((node: any): N.ClassMethod).kind === \"method\") node.kind = \"init\";\n node.shorthand = false;\n }\n\n return (node: any);\n }\n\n parseObjectProperty(\n prop: N.ObjectProperty,\n startPos: ?number,\n startLoc: ?Position,\n isPattern: boolean,\n refExpressionErrors: ?ExpressionErrors,\n ): ?N.ObjectProperty {\n const node: N.EstreeProperty = (super.parseObjectProperty(\n prop,\n startPos,\n startLoc,\n isPattern,\n refExpressionErrors,\n ): any);\n\n if (node) {\n node.kind = \"init\";\n node.type = \"Property\";\n }\n\n return (node: any);\n }\n\n isAssignable(node: N.Node, isBinding?: boolean): boolean {\n if (node != null && this.isObjectProperty(node)) {\n return this.isAssignable(node.value, isBinding);\n }\n return super.isAssignable(node, isBinding);\n }\n\n toAssignable(node: N.Node, isLHS: boolean = false): N.Node {\n if (node != null && this.isObjectProperty(node)) {\n this.toAssignable(node.value, isLHS);\n\n return node;\n }\n\n return super.toAssignable(node, isLHS);\n }\n\n toAssignableObjectExpressionProp(prop: N.Node, ...args) {\n if (prop.kind === \"get\" || prop.kind === \"set\") {\n this.raise(prop.key.start, Errors.PatternHasAccessor);\n } else if (prop.method) {\n this.raise(prop.key.start, Errors.PatternHasMethod);\n } else {\n super.toAssignableObjectExpressionProp(prop, ...args);\n }\n }\n\n finishCallExpression(\n node: T,\n optional: boolean,\n ): N.Expression {\n super.finishCallExpression(node, optional);\n\n if (node.callee.type === \"Import\") {\n ((node: N.Node): N.EstreeImportExpression).type = \"ImportExpression\";\n ((node: N.Node): N.EstreeImportExpression).source = node.arguments[0];\n if (this.hasPlugin(\"importAssertions\")) {\n ((node: N.Node): N.EstreeImportExpression).attributes =\n node.arguments[1] ?? null;\n }\n // $FlowIgnore - arguments isn't optional in the type definition\n delete node.arguments;\n // $FlowIgnore - callee isn't optional in the type definition\n delete node.callee;\n }\n\n return node;\n }\n\n toReferencedArguments(\n node:\n | N.CallExpression\n | N.OptionalCallExpression\n | N.EstreeImportExpression,\n /* isParenthesizedExpr?: boolean, */\n ) {\n // ImportExpressions do not have an arguments array.\n if (node.type === \"ImportExpression\") {\n return;\n }\n\n super.toReferencedArguments(node);\n }\n\n parseExport(node: N.Node) {\n super.parseExport(node);\n\n switch (node.type) {\n case \"ExportAllDeclaration\":\n node.exported = null;\n break;\n\n case \"ExportNamedDeclaration\":\n if (\n node.specifiers.length === 1 &&\n node.specifiers[0].type === \"ExportNamespaceSpecifier\"\n ) {\n node.type = \"ExportAllDeclaration\";\n node.exported = node.specifiers[0].exported;\n delete node.specifiers;\n }\n\n break;\n }\n\n return node;\n }\n\n parseSubscript(\n base: N.Expression,\n startPos: number,\n startLoc: Position,\n noCalls: ?boolean,\n state: N.ParseSubscriptState,\n ) {\n const node = super.parseSubscript(\n base,\n startPos,\n startLoc,\n noCalls,\n state,\n );\n\n if (state.optionalChainMember) {\n // https://github.com/estree/estree/blob/master/es2020.md#chainexpression\n if (\n node.type === \"OptionalMemberExpression\" ||\n node.type === \"OptionalCallExpression\"\n ) {\n node.type = node.type.substring(8); // strip Optional prefix\n }\n if (state.stop) {\n const chain = this.startNodeAtNode(node);\n chain.expression = node;\n return this.finishNode(chain, \"ChainExpression\");\n }\n } else if (\n node.type === \"MemberExpression\" ||\n node.type === \"CallExpression\"\n ) {\n node.optional = false;\n }\n\n return node;\n }\n\n hasPropertyAsPrivateName(node: N.Node): boolean {\n if (node.type === \"ChainExpression\") {\n node = node.expression;\n }\n return super.hasPropertyAsPrivateName(node);\n }\n\n isOptionalChain(node: N.Node): boolean {\n return node.type === \"ChainExpression\";\n }\n\n isObjectProperty(node: N.Node): boolean {\n return node.type === \"Property\" && node.kind === \"init\" && !node.method;\n }\n\n isObjectMethod(node: N.Node): boolean {\n return node.method || node.kind === \"get\" || node.kind === \"set\";\n }\n };\n","// @flow\n\n// The token context is used in JSX plugin to track\n// jsx tag / jsx text / normal JavaScript expression\n\nexport class TokContext {\n constructor(token: string, preserveSpace?: boolean) {\n this.token = token;\n this.preserveSpace = !!preserveSpace;\n }\n\n token: string;\n preserveSpace: boolean;\n}\n\nconst types: {\n [key: string]: TokContext,\n} = {\n brace: new TokContext(\"{\"), // normal JavaScript expression\n j_oTag: new TokContext(\"...\", true), // JSX expressions\n};\n\nif (!process.env.BABEL_8_BREAKING) {\n types.template = new TokContext(\"`\", true);\n}\n\nexport { types };\n","// @flow\nimport { types as tc, type TokContext } from \"./context\";\n// ## Token types\n\n// The assignment of fine-grained, information-carrying type objects\n// allows the tokenizer to store the information it has about a\n// token in a way that is very cheap for the parser to look up.\n\n// All token type variables start with an underscore, to make them\n// easy to recognize.\n\n// The `beforeExpr` property is used to disambiguate between 1) binary\n// expression (<) and JSX Tag start (); 2) object literal and JSX\n// texts. It is set on the `updateContext` function in the JSX plugin.\n\n// The `startsExpr` property is used to determine whether an expression\n// may be the “argument” subexpression of a `yield` expression or\n// `yield` statement. It is set on all token types that may be at the\n// start of a subexpression.\n\n// `isLoop` marks a keyword as starting a loop, which is important\n// to know when parsing a label, in order to allow or disallow\n// continue jumps to that label.\n\nconst beforeExpr = true;\nconst startsExpr = true;\nconst isLoop = true;\nconst isAssign = true;\nconst prefix = true;\nconst postfix = true;\n\ntype TokenOptions = {\n keyword?: string,\n beforeExpr?: boolean,\n startsExpr?: boolean,\n rightAssociative?: boolean,\n isLoop?: boolean,\n isAssign?: boolean,\n prefix?: boolean,\n postfix?: boolean,\n binop?: ?number,\n};\n\n// Internally the tokenizer stores token as a number\nexport opaque type TokenType = number;\n\n// The `ExportedTokenType` is exported via `tokTypes` and accessible\n// when `tokens: true` is enabled. Unlike internal token type, it provides\n// metadata of the tokens.\nexport class ExportedTokenType {\n label: string;\n keyword: ?string;\n beforeExpr: boolean;\n startsExpr: boolean;\n rightAssociative: boolean;\n isLoop: boolean;\n isAssign: boolean;\n prefix: boolean;\n postfix: boolean;\n binop: ?number;\n // todo(Babel 8): remove updateContext from exposed token layout\n declare updateContext: ?(context: Array) => void;\n\n constructor(label: string, conf: TokenOptions = {}) {\n this.label = label;\n this.keyword = conf.keyword;\n this.beforeExpr = !!conf.beforeExpr;\n this.startsExpr = !!conf.startsExpr;\n this.rightAssociative = !!conf.rightAssociative;\n this.isLoop = !!conf.isLoop;\n this.isAssign = !!conf.isAssign;\n this.prefix = !!conf.prefix;\n this.postfix = !!conf.postfix;\n this.binop = conf.binop != null ? conf.binop : null;\n if (!process.env.BABEL_8_BREAKING) {\n this.updateContext = null;\n }\n }\n}\n\n// A map from keyword/keyword-like string value to the token type\nexport const keywords = new Map();\n\nfunction createKeyword(name: string, options: TokenOptions = {}): TokenType {\n options.keyword = name;\n const token = createToken(name, options);\n keywords.set(name, token);\n return token;\n}\n\nfunction createBinop(name: string, binop: number) {\n return createToken(name, { beforeExpr, binop });\n}\n\nlet tokenTypeCounter = -1;\nexport const tokenTypes: ExportedTokenType[] = [];\nconst tokenLabels: string[] = [];\nconst tokenBinops: number[] = [];\nconst tokenBeforeExprs: boolean[] = [];\nconst tokenStartsExprs: boolean[] = [];\nconst tokenPrefixes: boolean[] = [];\n\nfunction createToken(name: string, options: TokenOptions = {}): TokenType {\n ++tokenTypeCounter;\n tokenLabels.push(name);\n tokenBinops.push(options.binop ?? -1);\n tokenBeforeExprs.push(options.beforeExpr ?? false);\n tokenStartsExprs.push(options.startsExpr ?? false);\n tokenPrefixes.push(options.prefix ?? false);\n tokenTypes.push(new ExportedTokenType(name, options));\n\n return tokenTypeCounter;\n}\n\nfunction createKeywordLike(\n name: string,\n options: TokenOptions = {},\n): TokenType {\n ++tokenTypeCounter;\n keywords.set(name, tokenTypeCounter);\n tokenLabels.push(name);\n tokenBinops.push(options.binop ?? -1);\n tokenBeforeExprs.push(options.beforeExpr ?? false);\n tokenStartsExprs.push(options.startsExpr ?? false);\n tokenPrefixes.push(options.prefix ?? false);\n // In the exported token type, we set the label as \"name\" for backward compatibility with Babel 7\n tokenTypes.push(new ExportedTokenType(\"name\", options));\n\n return tokenTypeCounter;\n}\n\n// For performance the token type helpers depend on the following declarations order.\n// When adding new token types, please also check if the token helpers need update.\n\nexport const tt: { [name: string]: TokenType } = {\n // Punctuation token types.\n bracketL: createToken(\"[\", { beforeExpr, startsExpr }),\n bracketHashL: createToken(\"#[\", { beforeExpr, startsExpr }),\n bracketBarL: createToken(\"[|\", { beforeExpr, startsExpr }),\n bracketR: createToken(\"]\"),\n bracketBarR: createToken(\"|]\"),\n braceL: createToken(\"{\", { beforeExpr, startsExpr }),\n braceBarL: createToken(\"{|\", { beforeExpr, startsExpr }),\n braceHashL: createToken(\"#{\", { beforeExpr, startsExpr }),\n braceR: createToken(\"}\", { beforeExpr }),\n braceBarR: createToken(\"|}\"),\n parenL: createToken(\"(\", { beforeExpr, startsExpr }),\n parenR: createToken(\")\"),\n comma: createToken(\",\", { beforeExpr }),\n semi: createToken(\";\", { beforeExpr }),\n colon: createToken(\":\", { beforeExpr }),\n doubleColon: createToken(\"::\", { beforeExpr }),\n dot: createToken(\".\"),\n question: createToken(\"?\", { beforeExpr }),\n questionDot: createToken(\"?.\"),\n arrow: createToken(\"=>\", { beforeExpr }),\n template: createToken(\"template\"),\n ellipsis: createToken(\"...\", { beforeExpr }),\n backQuote: createToken(\"`\", { startsExpr }),\n dollarBraceL: createToken(\"${\", { beforeExpr, startsExpr }),\n // start: isTemplate\n templateTail: createToken(\"...`\", { startsExpr }),\n templateNonTail: createToken(\"...${\", { beforeExpr, startsExpr }),\n // end: isTemplate\n at: createToken(\"@\"),\n hash: createToken(\"#\", { startsExpr }),\n\n // Special hashbang token.\n interpreterDirective: createToken(\"#!...\"),\n\n // Operators. These carry several kinds of properties to help the\n // parser use them properly (the presence of these properties is\n // what categorizes them as operators).\n //\n // `binop`, when present, specifies that this operator is a binary\n // operator, and will refer to its precedence.\n //\n // `prefix` and `postfix` mark the operator as a prefix or postfix\n // unary operator.\n //\n // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as\n // binary operators with a very low precedence, that should result\n // in AssignmentExpression nodes.\n\n // start: isAssign\n eq: createToken(\"=\", { beforeExpr, isAssign }),\n assign: createToken(\"_=\", { beforeExpr, isAssign }),\n slashAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n // These are only needed to support % and ^ as a Hack-pipe topic token. When the\n // proposal settles on a token, the others can be merged with tt.assign.\n xorAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n moduloAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n // end: isAssign\n\n incDec: createToken(\"++/--\", { prefix, postfix, startsExpr }),\n bang: createToken(\"!\", { beforeExpr, prefix, startsExpr }),\n tilde: createToken(\"~\", { beforeExpr, prefix, startsExpr }),\n // start: isBinop\n pipeline: createBinop(\"|>\", 0),\n nullishCoalescing: createBinop(\"??\", 1),\n logicalOR: createBinop(\"||\", 1),\n logicalAND: createBinop(\"&&\", 2),\n bitwiseOR: createBinop(\"|\", 3),\n bitwiseXOR: createBinop(\"^\", 4),\n bitwiseAND: createBinop(\"&\", 5),\n equality: createBinop(\"==/!=/===/!==\", 6),\n lt: createBinop(\"/<=/>=\", 7),\n gt: createBinop(\"/<=/>=\", 7),\n relational: createBinop(\"/<=/>=\", 7),\n bitShift: createBinop(\"<>/>>>\", 8),\n plusMin: createToken(\"+/-\", { beforeExpr, binop: 9, prefix, startsExpr }),\n // startsExpr: required by v8intrinsic plugin\n modulo: createToken(\"%\", { binop: 10, startsExpr }),\n // unset `beforeExpr` as it can be `function *`\n star: createToken(\"*\", { binop: 10 }),\n slash: createBinop(\"/\", 10),\n exponent: createToken(\"**\", {\n beforeExpr,\n binop: 11,\n rightAssociative: true,\n }),\n\n // Keywords\n // Don't forget to update packages/babel-helper-validator-identifier/src/keyword.js\n // when new keywords are added\n // start: isLiteralPropertyName\n // start: isKeyword\n _in: createKeyword(\"in\", { beforeExpr, binop: 7 }),\n _instanceof: createKeyword(\"instanceof\", { beforeExpr, binop: 7 }),\n // end: isBinop\n _break: createKeyword(\"break\"),\n _case: createKeyword(\"case\", { beforeExpr }),\n _catch: createKeyword(\"catch\"),\n _continue: createKeyword(\"continue\"),\n _debugger: createKeyword(\"debugger\"),\n _default: createKeyword(\"default\", { beforeExpr }),\n _else: createKeyword(\"else\", { beforeExpr }),\n _finally: createKeyword(\"finally\"),\n _function: createKeyword(\"function\", { startsExpr }),\n _if: createKeyword(\"if\"),\n _return: createKeyword(\"return\", { beforeExpr }),\n _switch: createKeyword(\"switch\"),\n _throw: createKeyword(\"throw\", { beforeExpr, prefix, startsExpr }),\n _try: createKeyword(\"try\"),\n _var: createKeyword(\"var\"),\n _const: createKeyword(\"const\"),\n _with: createKeyword(\"with\"),\n _new: createKeyword(\"new\", { beforeExpr, startsExpr }),\n _this: createKeyword(\"this\", { startsExpr }),\n _super: createKeyword(\"super\", { startsExpr }),\n _class: createKeyword(\"class\", { startsExpr }),\n _extends: createKeyword(\"extends\", { beforeExpr }),\n _export: createKeyword(\"export\"),\n _import: createKeyword(\"import\", { startsExpr }),\n _null: createKeyword(\"null\", { startsExpr }),\n _true: createKeyword(\"true\", { startsExpr }),\n _false: createKeyword(\"false\", { startsExpr }),\n _typeof: createKeyword(\"typeof\", { beforeExpr, prefix, startsExpr }),\n _void: createKeyword(\"void\", { beforeExpr, prefix, startsExpr }),\n _delete: createKeyword(\"delete\", { beforeExpr, prefix, startsExpr }),\n // start: isLoop\n _do: createKeyword(\"do\", { isLoop, beforeExpr }),\n _for: createKeyword(\"for\", { isLoop }),\n _while: createKeyword(\"while\", { isLoop }),\n // end: isLoop\n // end: isKeyword\n\n // Primary literals\n // start: isIdentifier\n _as: createKeywordLike(\"as\", { startsExpr }),\n _assert: createKeywordLike(\"assert\", { startsExpr }),\n _async: createKeywordLike(\"async\", { startsExpr }),\n _await: createKeywordLike(\"await\", { startsExpr }),\n _from: createKeywordLike(\"from\", { startsExpr }),\n _get: createKeywordLike(\"get\", { startsExpr }),\n _let: createKeywordLike(\"let\", { startsExpr }),\n _meta: createKeywordLike(\"meta\", { startsExpr }),\n _of: createKeywordLike(\"of\", { startsExpr }),\n _sent: createKeywordLike(\"sent\", { startsExpr }),\n _set: createKeywordLike(\"set\", { startsExpr }),\n _static: createKeywordLike(\"static\", { startsExpr }),\n _yield: createKeywordLike(\"yield\", { startsExpr }),\n\n // Flow and TypeScript Keywordlike\n _asserts: createKeywordLike(\"asserts\", { startsExpr }),\n _checks: createKeywordLike(\"checks\", { startsExpr }),\n _exports: createKeywordLike(\"exports\", { startsExpr }),\n _global: createKeywordLike(\"global\", { startsExpr }),\n _implements: createKeywordLike(\"implements\", { startsExpr }),\n _intrinsic: createKeywordLike(\"intrinsic\", { startsExpr }),\n _infer: createKeywordLike(\"infer\", { startsExpr }),\n _is: createKeywordLike(\"is\", { startsExpr }),\n _mixins: createKeywordLike(\"mixins\", { startsExpr }),\n _proto: createKeywordLike(\"proto\", { startsExpr }),\n _require: createKeywordLike(\"require\", { startsExpr }),\n // start: isTSTypeOperator\n _keyof: createKeywordLike(\"keyof\", { startsExpr }),\n _readonly: createKeywordLike(\"readonly\", { startsExpr }),\n _unique: createKeywordLike(\"unique\", { startsExpr }),\n // end: isTSTypeOperator\n // start: isTSDeclarationStart\n _abstract: createKeywordLike(\"abstract\", { startsExpr }),\n _declare: createKeywordLike(\"declare\", { startsExpr }),\n _enum: createKeywordLike(\"enum\", { startsExpr }),\n _module: createKeywordLike(\"module\", { startsExpr }),\n _namespace: createKeywordLike(\"namespace\", { startsExpr }),\n // start: isFlowInterfaceOrTypeOrOpaque\n _interface: createKeywordLike(\"interface\", { startsExpr }),\n _type: createKeywordLike(\"type\", { startsExpr }),\n // end: isTSDeclarationStart\n _opaque: createKeywordLike(\"opaque\", { startsExpr }),\n // end: isFlowInterfaceOrTypeOrOpaque\n name: createToken(\"name\", { startsExpr }),\n // end: isIdentifier\n\n string: createToken(\"string\", { startsExpr }),\n num: createToken(\"num\", { startsExpr }),\n bigint: createToken(\"bigint\", { startsExpr }),\n decimal: createToken(\"decimal\", { startsExpr }),\n // end: isLiteralPropertyName\n regexp: createToken(\"regexp\", { startsExpr }),\n privateName: createToken(\"#name\", { startsExpr }),\n eof: createToken(\"eof\"),\n\n // jsx plugin\n jsxName: createToken(\"jsxName\"),\n jsxText: createToken(\"jsxText\", { beforeExpr: true }),\n jsxTagStart: createToken(\"jsxTagStart\", { startsExpr: true }),\n jsxTagEnd: createToken(\"jsxTagEnd\"),\n\n // placeholder plugin\n placeholder: createToken(\"%%\", { startsExpr: true }),\n};\n\nexport function tokenIsIdentifier(token: TokenType): boolean {\n return token >= tt._as && token <= tt.name;\n}\n\nexport function tokenKeywordOrIdentifierIsKeyword(token: TokenType): boolean {\n // we can remove the token >= tt._in check when we\n // know a token is either keyword or identifier\n return token <= tt._while;\n}\n\nexport function tokenIsKeywordOrIdentifier(token: TokenType): boolean {\n return token >= tt._in && token <= tt.name;\n}\n\nexport function tokenIsLiteralPropertyName(token: TokenType): boolean {\n return token >= tt._in && token <= tt.decimal;\n}\n\nexport function tokenComesBeforeExpression(token: TokenType): boolean {\n return tokenBeforeExprs[token];\n}\n\nexport function tokenCanStartExpression(token: TokenType): boolean {\n return tokenStartsExprs[token];\n}\n\nexport function tokenIsAssignment(token: TokenType): boolean {\n return token >= tt.eq && token <= tt.moduloAssign;\n}\n\nexport function tokenIsFlowInterfaceOrTypeOrOpaque(token: TokenType): boolean {\n return token >= tt._interface && token <= tt._opaque;\n}\n\nexport function tokenIsLoop(token: TokenType): boolean {\n return token >= tt._do && token <= tt._while;\n}\n\nexport function tokenIsKeyword(token: TokenType): boolean {\n return token >= tt._in && token <= tt._while;\n}\n\nexport function tokenIsOperator(token: TokenType): boolean {\n return token >= tt.pipeline && token <= tt._instanceof;\n}\n\nexport function tokenIsPostfix(token: TokenType): boolean {\n return token === tt.incDec;\n}\n\nexport function tokenIsPrefix(token: TokenType): boolean {\n return tokenPrefixes[token];\n}\n\nexport function tokenIsTSTypeOperator(token: TokenType): boolean {\n return token >= tt._keyof && token <= tt._unique;\n}\n\nexport function tokenIsTSDeclarationStart(token: TokenType): boolean {\n return token >= tt._abstract && token <= tt._type;\n}\n\nexport function tokenLabelName(token: TokenType): string {\n return tokenLabels[token];\n}\n\nexport function tokenOperatorPrecedence(token: TokenType): number {\n return tokenBinops[token];\n}\n\nexport function tokenIsRightAssociative(token: TokenType): boolean {\n return token === tt.exponent;\n}\n\nexport function tokenIsTemplate(token: TokenType): boolean {\n return token >= tt.templateTail && token <= tt.templateNonTail;\n}\n\nexport function getExportedToken(token: TokenType): ExportedTokenType {\n return tokenTypes[token];\n}\n\nexport function isTokenType(obj: any): boolean {\n return typeof obj === \"number\";\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n tokenTypes[tt.braceR].updateContext = context => {\n context.pop();\n };\n\n tokenTypes[tt.braceL].updateContext =\n tokenTypes[tt.braceHashL].updateContext =\n tokenTypes[tt.dollarBraceL].updateContext =\n context => {\n context.push(tc.brace);\n };\n\n tokenTypes[tt.backQuote].updateContext = context => {\n if (context[context.length - 1] === tc.template) {\n context.pop();\n } else {\n context.push(tc.template);\n }\n };\n\n tokenTypes[tt.jsxTagStart].updateContext = context => {\n context.push(tc.j_expr, tc.j_oTag);\n };\n}\n","import * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.js`.\n\n/* prettier-ignore */\nlet 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\";\n/* prettier-ignore */\nlet 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\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.js`.\n/* prettier-ignore */\nconst 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];\n/* prettier-ignore */\nconst 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];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n","const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n","/* eslint max-len: 0 */\n\n// @flow\n\nimport * as charCodes from \"charcodes\";\n\nexport {\n isIdentifierStart,\n isIdentifierChar,\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"@babel/helper-validator-identifier\";\n\nexport const keywordRelationalOperator = /^in(stanceof)?$/;\n\n// Test whether a current state character code and next character code is @\n\nexport function isIteratorStart(current: number, next: number): boolean {\n return current === charCodes.atSign && next === charCodes.atSign;\n}\n\n// This is the comprehensive set of JavaScript reserved words\n// If a word is in this set, it could be a reserved word,\n// depending on sourceType/strictMode/binding info. In other words\n// if a word is not in this set, it is not a reserved word under\n// any circumstance.\nconst reservedWordLikeSet = new Set([\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n // strict\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n // strictBind\n \"eval\",\n \"arguments\",\n // reservedWorkLike\n \"enum\",\n \"await\",\n]);\n\nexport function canBeReservedWord(word: string): boolean {\n return reservedWordLikeSet.has(word);\n}\n","// @flow\n\n// Each scope gets a bitset that may contain these flags\n// prettier-ignore\nexport const SCOPE_OTHER = 0b000000000,\n SCOPE_PROGRAM = 0b000000001,\n SCOPE_FUNCTION = 0b000000010,\n SCOPE_ARROW = 0b000000100,\n SCOPE_SIMPLE_CATCH = 0b000001000,\n SCOPE_SUPER = 0b000010000,\n SCOPE_DIRECT_SUPER = 0b000100000,\n SCOPE_CLASS = 0b001000000,\n SCOPE_STATIC_BLOCK = 0b010000000,\n SCOPE_TS_MODULE = 0b100000000,\n SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;\n\nexport type ScopeFlags =\n | typeof SCOPE_OTHER\n | typeof SCOPE_PROGRAM\n | typeof SCOPE_FUNCTION\n | typeof SCOPE_VAR\n | typeof SCOPE_ARROW\n | typeof SCOPE_SIMPLE_CATCH\n | typeof SCOPE_SUPER\n | typeof SCOPE_DIRECT_SUPER\n | typeof SCOPE_CLASS\n | typeof SCOPE_STATIC_BLOCK;\n\n// These flags are meant to be _only_ used inside the Scope class (or subclasses).\n// prettier-ignore\nexport const BIND_KIND_VALUE = 0b000000_0000_01,\n BIND_KIND_TYPE = 0b000000_0000_10,\n // Used in checkLVal and declareName to determine the type of a binding\n BIND_SCOPE_VAR = 0b000000_0001_00, // Var-style binding\n BIND_SCOPE_LEXICAL = 0b000000_0010_00, // Let- or const-style binding\n BIND_SCOPE_FUNCTION = 0b000000_0100_00, // Function declaration\n BIND_SCOPE_OUTSIDE = 0b000000_1000_00, // Special case for function names as\n // bound inside the function\n // Misc flags\n BIND_FLAGS_NONE = 0b000001_0000_00,\n BIND_FLAGS_CLASS = 0b000010_0000_00,\n BIND_FLAGS_TS_ENUM = 0b000100_0000_00,\n BIND_FLAGS_TS_CONST_ENUM = 0b001000_0000_00,\n BIND_FLAGS_TS_EXPORT_ONLY = 0b010000_0000_00,\n BIND_FLAGS_FLOW_DECLARE_FN = 0b100000_0000_00;\n\n// These flags are meant to be _only_ used by Scope consumers\n// prettier-ignore\n/* = is value? | is type? | scope | misc flags */\nexport const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS ,\n BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0 ,\n BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0 ,\n BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0 ,\n BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS ,\n BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0 ,\n BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,\n BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,\n // These bindings don't introduce anything in the scope. They are used for assignments and\n // function expressions IDs.\n BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE ,\n BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE ,\n\n BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,\n BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,\n\n BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;\n\nexport type BindingTypes =\n | typeof BIND_NONE\n | typeof BIND_OUTSIDE\n | typeof BIND_VAR\n | typeof BIND_LEXICAL\n | typeof BIND_CLASS\n | typeof BIND_FUNCTION\n | typeof BIND_TS_INTERFACE\n | typeof BIND_TS_TYPE\n | typeof BIND_TS_ENUM\n | typeof BIND_TS_AMBIENT\n | typeof BIND_TS_NAMESPACE;\n\n// prettier-ignore\nexport const CLASS_ELEMENT_FLAG_STATIC = 0b1_00,\n CLASS_ELEMENT_KIND_GETTER = 0b0_10,\n CLASS_ELEMENT_KIND_SETTER = 0b0_01,\n CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;\n\n// prettier-ignore\nexport const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,\n CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,\n CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,\n CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,\n CLASS_ELEMENT_OTHER = 0;\n\nexport type ClassElementTypes =\n | typeof CLASS_ELEMENT_STATIC_GETTER\n | typeof CLASS_ELEMENT_STATIC_SETTER\n | typeof CLASS_ELEMENT_INSTANCE_GETTER\n | typeof CLASS_ELEMENT_INSTANCE_SETTER\n | typeof CLASS_ELEMENT_OTHER;\n","// @flow\nimport {\n SCOPE_ARROW,\n SCOPE_DIRECT_SUPER,\n SCOPE_FUNCTION,\n SCOPE_SIMPLE_CATCH,\n SCOPE_SUPER,\n SCOPE_PROGRAM,\n SCOPE_VAR,\n SCOPE_CLASS,\n SCOPE_STATIC_BLOCK,\n BIND_SCOPE_FUNCTION,\n BIND_SCOPE_VAR,\n BIND_SCOPE_LEXICAL,\n BIND_KIND_VALUE,\n type ScopeFlags,\n type BindingTypes,\n} from \"./scopeflags\";\nimport * as N from \"../types\";\nimport { Errors, type raiseFunction } from \"../parser/error\";\n\n// Start an AST node, attaching a start offset.\nexport class Scope {\n declare flags: ScopeFlags;\n // A set of var-declared names in the current lexical scope\n var: Set = new Set();\n // A set of lexically-declared names in the current lexical scope\n lexical: Set = new Set();\n // A set of lexically-declared FunctionDeclaration names in the current lexical scope\n functions: Set = new Set();\n\n constructor(flags: ScopeFlags) {\n this.flags = flags;\n }\n}\n\n// The functions in this module keep track of declared variables in the\n// current scope in order to detect duplicate variable names.\nexport default class ScopeHandler {\n scopeStack: Array = [];\n declare raise: raiseFunction;\n declare inModule: boolean;\n undefinedExports: Map = new Map();\n undefinedPrivateNames: Map = new Map();\n\n constructor(raise: raiseFunction, inModule: boolean) {\n this.raise = raise;\n this.inModule = inModule;\n }\n\n get inFunction() {\n return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;\n }\n get allowSuper() {\n return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;\n }\n get allowDirectSuper() {\n return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;\n }\n get inClass() {\n return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;\n }\n get inClassAndNotInNonArrowFunction() {\n const flags = this.currentThisScopeFlags();\n return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;\n }\n get inStaticBlock() {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & SCOPE_STATIC_BLOCK) {\n return true;\n }\n if (flags & (SCOPE_VAR | SCOPE_CLASS)) {\n // function body, module body, class property initializers\n return false;\n }\n }\n }\n get inNonArrowFunction() {\n return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;\n }\n get treatFunctionsAsVar() {\n return this.treatFunctionsAsVarInScope(this.currentScope());\n }\n\n createScope(flags: ScopeFlags): Scope {\n return new Scope(flags);\n }\n // This method will be overwritten by subclasses\n /*:: +createScope: (flags: ScopeFlags) => IScope; */\n\n enter(flags: ScopeFlags) {\n this.scopeStack.push(this.createScope(flags));\n }\n\n exit() {\n this.scopeStack.pop();\n }\n\n // The spec says:\n // > At the top level of a function, or script, function declarations are\n // > treated like var declarations rather than like lexical declarations.\n treatFunctionsAsVarInScope(scope: IScope): boolean {\n return !!(\n scope.flags & SCOPE_FUNCTION ||\n (!this.inModule && scope.flags & SCOPE_PROGRAM)\n );\n }\n\n declareName(name: string, bindingType: BindingTypes, pos: number) {\n let scope = this.currentScope();\n if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {\n this.checkRedeclarationInScope(scope, name, bindingType, pos);\n\n if (bindingType & BIND_SCOPE_FUNCTION) {\n scope.functions.add(name);\n } else {\n scope.lexical.add(name);\n }\n\n if (bindingType & BIND_SCOPE_LEXICAL) {\n this.maybeExportDefined(scope, name);\n }\n } else if (bindingType & BIND_SCOPE_VAR) {\n for (let i = this.scopeStack.length - 1; i >= 0; --i) {\n scope = this.scopeStack[i];\n this.checkRedeclarationInScope(scope, name, bindingType, pos);\n scope.var.add(name);\n this.maybeExportDefined(scope, name);\n\n if (scope.flags & SCOPE_VAR) break;\n }\n }\n if (this.inModule && scope.flags & SCOPE_PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n maybeExportDefined(scope: IScope, name: string) {\n if (this.inModule && scope.flags & SCOPE_PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n checkRedeclarationInScope(\n scope: IScope,\n name: string,\n bindingType: BindingTypes,\n pos: number,\n ) {\n if (this.isRedeclaredInScope(scope, name, bindingType)) {\n this.raise(pos, Errors.VarRedeclaration, name);\n }\n }\n\n isRedeclaredInScope(\n scope: IScope,\n name: string,\n bindingType: BindingTypes,\n ): boolean {\n if (!(bindingType & BIND_KIND_VALUE)) return false;\n\n if (bindingType & BIND_SCOPE_LEXICAL) {\n return (\n scope.lexical.has(name) ||\n scope.functions.has(name) ||\n scope.var.has(name)\n );\n }\n\n if (bindingType & BIND_SCOPE_FUNCTION) {\n return (\n scope.lexical.has(name) ||\n (!this.treatFunctionsAsVarInScope(scope) && scope.var.has(name))\n );\n }\n\n return (\n (scope.lexical.has(name) &&\n !(\n scope.flags & SCOPE_SIMPLE_CATCH &&\n scope.lexical.values().next().value === name\n )) ||\n (!this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name))\n );\n }\n\n checkLocalExport(id: N.Identifier) {\n const { name } = id;\n const topLevelScope = this.scopeStack[0];\n if (\n !topLevelScope.lexical.has(name) &&\n !topLevelScope.var.has(name) &&\n // In strict mode, scope.functions will always be empty.\n // Modules are strict by default, but the `scriptMode` option\n // can overwrite this behavior.\n !topLevelScope.functions.has(name)\n ) {\n this.undefinedExports.set(name, id.start);\n }\n }\n\n currentScope(): IScope {\n return this.scopeStack[this.scopeStack.length - 1];\n }\n\n // $FlowIgnore\n currentVarScopeFlags(): ScopeFlags {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & SCOPE_VAR) {\n return flags;\n }\n }\n }\n\n // Could be useful for `arguments`, `this`, `new.target`, `super()`, `super.property`, and `super[property]`.\n // $FlowIgnore\n currentThisScopeFlags(): ScopeFlags {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {\n return flags;\n }\n }\n }\n}\n","// @flow\n\nimport ScopeHandler, { Scope } from \"../../util/scope\";\nimport {\n BIND_FLAGS_FLOW_DECLARE_FN,\n type ScopeFlags,\n type BindingTypes,\n} from \"../../util/scopeflags\";\nimport * as N from \"../../types\";\n\n// Reference implementation: https://github.com/facebook/flow/blob/23aeb2a2ef6eb4241ce178fde5d8f17c5f747fb5/src/typing/env.ml#L536-L584\nclass FlowScope extends Scope {\n // declare function foo(): type;\n declareFunctions: Set = new Set();\n}\n\nexport default class FlowScopeHandler extends ScopeHandler {\n createScope(flags: ScopeFlags): FlowScope {\n return new FlowScope(flags);\n }\n\n declareName(name: string, bindingType: BindingTypes, pos: number) {\n const scope = this.currentScope();\n if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {\n this.checkRedeclarationInScope(scope, name, bindingType, pos);\n this.maybeExportDefined(scope, name);\n scope.declareFunctions.add(name);\n return;\n }\n\n super.declareName(...arguments);\n }\n\n isRedeclaredInScope(\n scope: FlowScope,\n name: string,\n bindingType: BindingTypes,\n ): boolean {\n if (super.isRedeclaredInScope(...arguments)) return true;\n\n if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {\n return (\n !scope.declareFunctions.has(name) &&\n (scope.lexical.has(name) || scope.functions.has(name))\n );\n }\n\n return false;\n }\n\n checkLocalExport(id: N.Identifier) {\n if (!this.scopeStack[0].declareFunctions.has(id.name)) {\n super.checkLocalExport(id);\n }\n }\n}\n","// @flow\n\nimport type { Options } from \"../options\";\nimport * as N from \"../types\";\nimport type { CommentWhitespace } from \"../parser/comments\";\nimport { Position } from \"../util/location\";\n\nimport { types as ct, type TokContext } from \"./context\";\nimport { tt, type TokenType } from \"./types\";\nimport type { ParsingError, ErrorTemplate } from \"../parser/error\";\n\ntype TopicContextState = {\n // When a topic binding has been currently established,\n // then this is 1. Otherwise, it is 0. This is forwards compatible\n // with a future plugin for multiple lexical topics.\n maxNumOfResolvableTopics: number,\n\n // When a topic binding has been currently established, and if that binding\n // has been used as a topic reference `#`, then this is 0. Otherwise, it is\n // `null`. This is forwards compatible with a future plugin for multiple\n // lexical topics.\n maxTopicIndex: null | 0,\n};\n\nexport default class State {\n strict: boolean;\n curLine: number;\n lineStart: number;\n\n // And, if locations are used, the {line, column} object\n // corresponding to those offsets\n startLoc: Position;\n endLoc: Position;\n\n init({ strictMode, sourceType, startLine, startColumn }: Options): void {\n this.strict =\n strictMode === false\n ? false\n : strictMode === true\n ? true\n : sourceType === \"module\";\n\n this.curLine = startLine;\n this.lineStart = -startColumn;\n this.startLoc = this.endLoc = new Position(startLine, startColumn);\n }\n\n errors: ParsingError[] = [];\n\n // Used to signify the start of a potential arrow function\n potentialArrowAt: number = -1;\n\n // Used to signify the start of an expression which looks like a\n // typed arrow function, but it isn't\n // e.g. a ? (b) : c => d\n // ^\n noArrowAt: number[] = [];\n\n // Used to signify the start of an expression whose params, if it looks like\n // an arrow function, shouldn't be converted to assignable nodes.\n // This is used to defer the validation of typed arrow functions inside\n // conditional expressions.\n // e.g. a ? (b) : c => d\n // ^\n noArrowParamsConversionAt: number[] = [];\n\n // Flags to track\n maybeInArrowParameters: boolean = false;\n inType: boolean = false;\n noAnonFunctionType: boolean = false;\n hasFlowComment: boolean = false;\n isAmbientContext: boolean = false;\n inAbstractClass: boolean = false;\n\n // For the Hack-style pipelines plugin\n topicContext: TopicContextState = {\n maxNumOfResolvableTopics: 0,\n maxTopicIndex: null,\n };\n\n // For the F#-style pipelines plugin\n soloAwait: boolean = false;\n inFSharpPipelineDirectBody: boolean = false;\n\n // Labels in scope.\n labels: Array<{\n kind: ?(\"loop\" | \"switch\"),\n name?: ?string,\n statementStart?: number,\n }> = [];\n\n // Leading decorators. Last element of the stack represents the decorators in current context.\n // Supports nesting of decorators, e.g. @foo(@bar class inner {}) class outer {}\n // where @foo belongs to the outer class and @bar to the inner\n decoratorStack: Array> = [[]];\n\n // Comment store for Program.comments\n comments: Array = [];\n\n // Comment attachment store\n commentStack: Array = [];\n\n // The current position of the tokenizer in the input.\n pos: number = 0;\n\n // Properties of the current token:\n // Its type\n type: TokenType = tt.eof;\n\n // For tokens that include more information than their type, the value\n value: any = null;\n\n // Its start and end offset\n start: number = 0;\n end: number = 0;\n\n // Position information for the previous token\n // $FlowIgnore this is initialized when generating the second token.\n lastTokEndLoc: Position = null;\n // $FlowIgnore this is initialized when generating the second token.\n lastTokStartLoc: Position = null;\n lastTokStart: number = 0;\n lastTokEnd: number = 0;\n\n // The context stack is used to track whether the apostrophe \"`\" starts\n // or ends a string template\n context: Array = [ct.brace];\n // Used to track whether a JSX element is allowed to form\n canStartJSXElement: boolean = true;\n\n // Used to signal to callers of `readWord1` whether the word\n // contained any escape sequences. This is needed because words with\n // escape sequences must not be interpreted as keywords.\n containsEsc: boolean = false;\n\n // This property is used to track the following errors\n // - StrictNumericEscape\n // - StrictOctalLiteral\n //\n // in a literal that occurs prior to/immediately after a \"use strict\" directive.\n\n // todo(JLHwung): set strictErrors to null and avoid recording string errors\n // after a non-directive is parsed\n strictErrors: Map = new Map();\n\n // Tokens length in token store\n tokensLength: number = 0;\n\n curPosition(): Position {\n return new Position(this.curLine, this.pos - this.lineStart);\n }\n\n clone(skipArrays?: boolean): State {\n const state = new State();\n const keys = Object.keys(this);\n for (let i = 0, length = keys.length; i < length; i++) {\n const key = keys[i];\n // $FlowIgnore\n let val = this[key];\n\n if (!skipArrays && Array.isArray(val)) {\n val = val.slice();\n }\n\n // $FlowIgnore\n state[key] = val;\n }\n\n return state;\n }\n}\n\nexport type LookaheadState = {\n pos: number,\n value: any,\n type: TokenType,\n start: number,\n end: number,\n /* Used only in readToken_mult_modulo */\n inType: boolean,\n};\n","// @flow\n\n/*:: declare var invariant; */\n\nimport type { Options } from \"../options\";\nimport * as N from \"../types\";\nimport * as charCodes from \"charcodes\";\nimport { isIdentifierStart, isIdentifierChar } from \"../util/identifier\";\nimport {\n tokenIsKeyword,\n tokenLabelName,\n tt,\n keywords as keywordTypes,\n type TokenType,\n} from \"./types\";\nimport { type TokContext } from \"./context\";\nimport ParserErrors, { Errors, type ErrorTemplate } from \"../parser/error\";\nimport { SourceLocation } from \"../util/location\";\nimport {\n lineBreakG,\n isNewLine,\n isWhitespace,\n skipWhiteSpace,\n} from \"../util/whitespace\";\nimport State from \"./state\";\nimport type { LookaheadState } from \"./state\";\n\nconst VALID_REGEX_FLAGS = new Set([\n charCodes.lowercaseG,\n charCodes.lowercaseM,\n charCodes.lowercaseS,\n charCodes.lowercaseI,\n charCodes.lowercaseY,\n charCodes.lowercaseU,\n charCodes.lowercaseD,\n]);\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\n\nconst forbiddenNumericSeparatorSiblings = {\n decBinOct: [\n charCodes.dot,\n charCodes.uppercaseB,\n charCodes.uppercaseE,\n charCodes.uppercaseO,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseB,\n charCodes.lowercaseE,\n charCodes.lowercaseO,\n ],\n hex: [\n charCodes.dot,\n charCodes.uppercaseX,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseX,\n ],\n};\n\nconst allowedNumericSeparatorSiblings = {};\nallowedNumericSeparatorSiblings.bin = [\n // 0 - 1\n charCodes.digit0,\n charCodes.digit1,\n];\nallowedNumericSeparatorSiblings.oct = [\n // 0 - 7\n ...allowedNumericSeparatorSiblings.bin,\n\n charCodes.digit2,\n charCodes.digit3,\n charCodes.digit4,\n charCodes.digit5,\n charCodes.digit6,\n charCodes.digit7,\n];\nallowedNumericSeparatorSiblings.dec = [\n // 0 - 9\n ...allowedNumericSeparatorSiblings.oct,\n\n charCodes.digit8,\n charCodes.digit9,\n];\n\nallowedNumericSeparatorSiblings.hex = [\n // 0 - 9, A - F, a - f,\n ...allowedNumericSeparatorSiblings.dec,\n\n charCodes.uppercaseA,\n charCodes.uppercaseB,\n charCodes.uppercaseC,\n charCodes.uppercaseD,\n charCodes.uppercaseE,\n charCodes.uppercaseF,\n\n charCodes.lowercaseA,\n charCodes.lowercaseB,\n charCodes.lowercaseC,\n charCodes.lowercaseD,\n charCodes.lowercaseE,\n charCodes.lowercaseF,\n];\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nexport class Token {\n constructor(state: State) {\n this.type = state.type;\n this.value = state.value;\n this.start = state.start;\n this.end = state.end;\n this.loc = new SourceLocation(state.startLoc, state.endLoc);\n }\n\n declare type: TokenType;\n declare value: any;\n declare start: number;\n declare end: number;\n declare loc: SourceLocation;\n}\n\n// ## Tokenizer\n\nexport default class Tokenizer extends ParserErrors {\n // Forward-declarations\n // parser/util.js\n /*::\n +hasPrecedingLineBreak: () => boolean;\n +unexpected: (pos?: ?number, messageOrType?: ErrorTemplate | TokenType) => empty;\n +expectPlugin: (name: string, pos?: ?number) => true;\n */\n\n isLookahead: boolean;\n\n // Token store.\n tokens: Array = [];\n\n constructor(options: Options, input: string) {\n super();\n this.state = new State();\n this.state.init(options);\n this.input = input;\n this.length = input.length;\n this.isLookahead = false;\n }\n\n pushToken(token: Token | N.Comment) {\n // Pop out invalid tokens trapped by try-catch parsing.\n // Those parsing branches are mainly created by typescript and flow plugins.\n this.tokens.length = this.state.tokensLength;\n this.tokens.push(token);\n ++this.state.tokensLength;\n }\n\n // Move to the next token\n\n next(): void {\n this.checkKeywordEscapes();\n if (this.options.tokens) {\n this.pushToken(new Token(this.state));\n }\n\n this.state.lastTokEnd = this.state.end;\n this.state.lastTokStart = this.state.start;\n this.state.lastTokEndLoc = this.state.endLoc;\n this.state.lastTokStartLoc = this.state.startLoc;\n this.nextToken();\n }\n\n // TODO\n\n eat(type: TokenType): boolean {\n if (this.match(type)) {\n this.next();\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Whether current token matches given type\n *\n * @param {TokenType} type\n * @returns {boolean}\n * @memberof Tokenizer\n */\n match(type: TokenType): boolean {\n return this.state.type === type;\n }\n\n /**\n * Create a LookaheadState from current parser state\n *\n * @param {State} state\n * @returns {LookaheadState}\n * @memberof Tokenizer\n */\n createLookaheadState(state: State): LookaheadState {\n return {\n pos: state.pos,\n value: null,\n type: state.type,\n start: state.start,\n end: state.end,\n lastTokEnd: state.end,\n context: [this.curContext()],\n inType: state.inType,\n };\n }\n\n /**\n * lookahead peeks the next token, skipping changes to token context and\n * comment stack. For performance it returns a limited LookaheadState\n * instead of full parser state.\n *\n * The { column, line } Loc info is not included in lookahead since such usage\n * is rare. Although it may return other location properties e.g. `curLine` and\n * `lineStart`, these properties are not listed in the LookaheadState interface\n * and thus the returned value is _NOT_ reliable.\n *\n * The tokenizer should make best efforts to avoid using any parser state\n * other than those defined in LookaheadState\n *\n * @returns {LookaheadState}\n * @memberof Tokenizer\n */\n lookahead(): LookaheadState {\n const old = this.state;\n // For performance we use a simpified tokenizer state structure\n // $FlowIgnore\n this.state = this.createLookaheadState(old);\n\n this.isLookahead = true;\n this.nextToken();\n this.isLookahead = false;\n\n const curr = this.state;\n this.state = old;\n return curr;\n }\n\n nextTokenStart(): number {\n return this.nextTokenStartSince(this.state.pos);\n }\n\n nextTokenStartSince(pos: number): number {\n skipWhiteSpace.lastIndex = pos;\n return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;\n }\n\n lookaheadCharCode(): number {\n return this.input.charCodeAt(this.nextTokenStart());\n }\n\n codePointAtPos(pos: number): number {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `input` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = this.input.charCodeAt(pos);\n if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {\n const trail = this.input.charCodeAt(pos);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n return cp;\n }\n\n // Toggle strict mode. Re-reads the next number or string to please\n // pedantic tests (`\"use strict\"; 010;` should fail).\n\n setStrict(strict: boolean): void {\n this.state.strict = strict;\n if (strict) {\n // Throw an error for any string decimal escape found before/immediately\n // after a \"use strict\" directive. Strict mode will be set at parse\n // time for any literals that occur after the next node of the strict\n // directive.\n this.state.strictErrors.forEach((message, pos) =>\n /* eslint-disable @babel/development-internal/dry-error-messages */\n this.raise(pos, message),\n );\n this.state.strictErrors.clear();\n }\n }\n\n curContext(): TokContext {\n return this.state.context[this.state.context.length - 1];\n }\n\n // Read a single token, updating the parser object's token-related\n // properties.\n\n nextToken(): void {\n this.skipSpace();\n this.state.start = this.state.pos;\n if (!this.isLookahead) this.state.startLoc = this.state.curPosition();\n if (this.state.pos >= this.length) {\n this.finishToken(tt.eof);\n return;\n }\n\n this.getTokenFromCode(this.codePointAtPos(this.state.pos));\n }\n\n skipBlockComment(): N.CommentBlock | void {\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n const start = this.state.pos;\n const end = this.input.indexOf(\"*/\", start + 2);\n if (end === -1) throw this.raise(start, Errors.UnterminatedComment);\n\n this.state.pos = end + 2;\n lineBreakG.lastIndex = start + 2;\n while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {\n ++this.state.curLine;\n this.state.lineStart = lineBreakG.lastIndex;\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n /*:: invariant(startLoc) */\n\n const comment = {\n type: \"CommentBlock\",\n value: this.input.slice(start + 2, end),\n start,\n end: end + 2,\n loc: new SourceLocation(startLoc, this.state.curPosition()),\n };\n if (this.options.tokens) this.pushToken(comment);\n return comment;\n }\n\n skipLineComment(startSkip: number): N.CommentLine | void {\n const start = this.state.pos;\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n let ch = this.input.charCodeAt((this.state.pos += startSkip));\n if (this.state.pos < this.length) {\n while (!isNewLine(ch) && ++this.state.pos < this.length) {\n ch = this.input.charCodeAt(this.state.pos);\n }\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n /*:: invariant(startLoc) */\n\n const end = this.state.pos;\n const value = this.input.slice(start + startSkip, end);\n\n const comment = {\n type: \"CommentLine\",\n value,\n start,\n end,\n loc: new SourceLocation(startLoc, this.state.curPosition()),\n };\n if (this.options.tokens) this.pushToken(comment);\n return comment;\n }\n\n // Called at the start of the parse and after every token. Skips\n // whitespace and comments, and.\n\n skipSpace(): void {\n const spaceStart = this.state.pos;\n const comments = [];\n loop: while (this.state.pos < this.length) {\n const ch = this.input.charCodeAt(this.state.pos);\n switch (ch) {\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.tab:\n ++this.state.pos;\n break;\n case charCodes.carriageReturn:\n if (\n this.input.charCodeAt(this.state.pos + 1) === charCodes.lineFeed\n ) {\n ++this.state.pos;\n }\n // fall through\n case charCodes.lineFeed:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n ++this.state.pos;\n ++this.state.curLine;\n this.state.lineStart = this.state.pos;\n break;\n\n case charCodes.slash:\n switch (this.input.charCodeAt(this.state.pos + 1)) {\n case charCodes.asterisk: {\n const comment = this.skipBlockComment();\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n break;\n }\n\n case charCodes.slash: {\n const comment = this.skipLineComment(2);\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n break;\n }\n\n default:\n break loop;\n }\n break;\n\n default:\n if (isWhitespace(ch)) {\n ++this.state.pos;\n } else if (ch === charCodes.dash && !this.inModule) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.dash &&\n this.input.charCodeAt(pos + 2) === charCodes.greaterThan &&\n (spaceStart === 0 || this.state.lineStart > spaceStart)\n ) {\n // A `-->` line comment\n const comment = this.skipLineComment(3);\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n } else {\n break loop;\n }\n } else if (ch === charCodes.lessThan && !this.inModule) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.exclamationMark &&\n this.input.charCodeAt(pos + 2) === charCodes.dash &&\n this.input.charCodeAt(pos + 3) === charCodes.dash\n ) {\n // `` line comment\n const comment = this.skipLineComment(3);\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n } else {\n break loop;\n }\n } else if (ch === charCodes.lessThan && !this.inModule) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.exclamationMark &&\n this.input.charCodeAt(pos + 2) === charCodes.dash &&\n this.input.charCodeAt(pos + 3) === charCodes.dash\n ) {\n // `