UNPKG

@babel/parser

Version:
1,460 lines (1,459 loc) 481 kB
class Position { constructor(line, col, index) { this.line = undefined; this.column = undefined; if (index !== undefined) this.index = undefined; this.line = line; this.column = col; if (index !== undefined) this.index = index; } } class SourceLocation { start; end; filename; identifierName; constructor(start, end) { this.start = start; this.end = end; } } function createPositionWithColumnOffset(position, columnOffset) { const { line, column, index } = position; return new Position(line, column + columnOffset, index + columnOffset); } const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"; const ModuleErrors = { ImportMetaOutsideModule: { message: `import.meta may appear only with 'sourceType: "module"'`, code }, ImportOutsideModule: { message: `'import' and 'export' may appear only with 'sourceType: "module"'`, code } }; const NodeDescriptions = { ArrayPattern: "array destructuring pattern", AssignmentExpression: "assignment expression", AssignmentPattern: "assignment expression", ArrowFunctionExpression: "arrow function expression", ConditionalExpression: "conditional expression", CatchClause: "catch clause", ForOfStatement: "for-of statement", ForInStatement: "for-in statement", ForStatement: "for-loop", FormalParameters: "function parameter list", Identifier: "identifier", ImportSpecifier: "import specifier", ImportDefaultSpecifier: "import default specifier", ImportNamespaceSpecifier: "import namespace specifier", ObjectPattern: "object destructuring pattern", ParenthesizedExpression: "parenthesized expression", RestElement: "rest element", UpdateExpression: { true: "prefix operation", false: "postfix operation" }, VariableDeclarator: "variable declaration", YieldExpression: "yield expression" }; const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type]; const StandardErrors = { AccessorIsGenerator: ({ kind }) => `A ${kind}ter cannot be a generator.`, ArgumentsInClass: "'arguments' is only allowed in functions and class methods.", AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.", AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.", AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.", AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.", AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.", AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.", BadGetterArity: "A 'get' accessor must not have any formal parameters.", BadSetterArity: "A 'set' accessor must have exactly one formal parameter.", BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.", ConstructorClassField: "Classes may not have a field named 'constructor'.", ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.", ConstructorIsAccessor: "Class constructor may not be an accessor.", ConstructorIsAsync: "Constructor can't be an async function.", ConstructorIsGenerator: "Constructor can't be a generator.", DeclarationMissingInitializer: ({ kind }) => `Missing initializer in ${kind} declaration.`, DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.", DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.", DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", DecoratorSemicolon: "Decorators must not be followed by a semicolon.", DecoratorStaticBlock: "Decorators can't be used with a static block.", DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.', DeletePrivateField: "Deleting a private field is not allowed.", DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", DuplicateConstructor: "Duplicate constructor in the same class.", DuplicateDefaultExport: "Only one default export allowed per module.", DuplicateExport: ({ exportName }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`, DuplicateProto: "Redefinition of __proto__ property.", DuplicateRegExpFlags: "Duplicate regular expression flag.", ElementAfterRest: "Rest element must be last element.", EscapedCharNotAnIdentifier: "Invalid Unicode escape.", ExportBindingIsString: ({ localName, exportName }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`, ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.", ForInOfLoopInitializer: ({ type }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`, ForInUsing: "For-in loop may not start with 'using' declaration.", ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.", ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.", GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.", IllegalBreakContinue: ({ type }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`, IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.", IllegalReturn: "'return' outside of function.", ImportBindingIsString: ({ importName }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`, ImportCallArity: ({ phase }) => `\`import${phase ? `.${phase}` : ""}()\` requires exactly one or two arguments.`, ImportCallNotNewExpression: ({ phase }) => `Cannot use new with import${phase ? `.${phase}` : ""}().`, ImportCallSpreadArgument: ({ phase }) => `\`...\` is not allowed in \`import${phase ? `.${phase}` : ""}()\`.`, IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.", InvalidBigIntLiteral: "Invalid BigIntLiteral.", InvalidCodePoint: "Code point out of bounds.", InvalidCoverDiscardElement: "'void' must be followed by an expression when not used in a binding position.", InvalidCoverInitializedName: "Invalid shorthand property initializer.", InvalidDigit: ({ radix }) => `Expected number in radix ${radix}.`, InvalidEscapeSequence: "Bad character escape sequence.", InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.", InvalidEscapedReservedWord: ({ reservedWord }) => `Escape sequence in keyword ${reservedWord}.`, InvalidIdentifier: ({ identifierName }) => `Invalid identifier ${identifierName}.`, InvalidLhs: ({ ancestor }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`, InvalidLhsBinding: ({ ancestor }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`, InvalidLhsOptionalChaining: ({ ancestor }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`, InvalidNumber: "Invalid number.", InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.", InvalidOrUnexpectedToken: ({ unexpected }) => `Unexpected character '${unexpected}'.`, InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.", InvalidPrivateFieldResolution: ({ identifierName }) => `Private name #${identifierName} is not defined.`, InvalidPropertyBindingPattern: "Binding member expression.", InvalidRestAssignmentPattern: "Invalid rest operator's argument.", LabelRedeclaration: ({ labelName }) => `Label '${labelName}' is already declared.`, LetInLexicalBinding: "'let' is disallowed as a lexically bound name.", LineTerminatorBeforeArrow: "No line break is allowed before '=>'.", MalformedRegExpFlags: "Invalid regular expression flag.", MissingClassName: "A class name is required.", MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", MissingSemicolon: "Missing semicolon.", MissingPlugin: ({ missingPlugin }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, MissingOneOfPlugins: ({ missingPlugin }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.", MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.", ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.", ModuleAttributesWithDuplicateKeys: ({ key }) => `Duplicate key "${key}" is not allowed in module attributes.`, ModuleExportNameHasLoneSurrogate: ({ surrogateCharCode }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`, ModuleExportUndefined: ({ localName }) => `Export '${localName}' is not defined.`, MultipleDefaultsInSwitch: "Multiple default clauses.", NewlineAfterThrow: "Illegal newline after throw.", NoCatchOrFinally: "Missing catch or finally clause.", NumberIdentifier: "Identifier directly after number.", NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.", ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.", OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.", OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.", OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.", ParamDupe: "Argument name clash.", PatternHasAccessor: "Object pattern can't contain getter or setter.", PatternHasMethod: "Object pattern can't contain methods.", PrivateInExpectedIn: ({ identifierName }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`, PrivateNameRedeclaration: ({ identifierName }) => `Duplicate private name #${identifierName}.`, RestTrailingComma: "Unexpected trailing comma after rest element.", SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.", SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.", SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.', StaticPrototype: "Classes may not have static property named prototype.", SuperCallNotNewExpression: "Cannot use new with super(...).", SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", SuperPrivateField: "Private fields can't be accessed on super.", TrailingDecorator: "Decorators must be attached to a class element.", UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.", UnexpectedDigitAfterHash: "Unexpected digit after hash token.", UnexpectedImportExport: "'import' and 'export' may only appear at the top level.", UnexpectedKeyword: ({ keyword }) => `Unexpected keyword '${keyword}'.`, UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.", UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.", UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.", UnexpectedPrivateField: "Unexpected private name.", UnexpectedReservedWord: ({ reservedWord }) => `Unexpected reserved word '${reservedWord}'.`, UnexpectedSuper: "'super' is only allowed in object methods and classes.", UnexpectedToken: ({ expected, unexpected }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`, UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.", UnexpectedVoidPattern: "Unexpected void binding.", UnsupportedDecoratorExport: "A decorated export must export a class declaration.", UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.", UnsupportedMetaProperty: ({ target, onlyValidPropertyName }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`, UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.", UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.", UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).", UnterminatedComment: "Unterminated comment.", UnterminatedRegExp: "Unterminated regular expression.", UnterminatedString: "Unterminated string constant.", UnterminatedTemplate: "Unterminated template.", UsingDeclarationExport: "Using declaration cannot be exported.", UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.", VarRedeclaration: ({ identifierName }) => `Identifier '${identifierName}' has already been declared.`, VoidPatternCatchClauseParam: "A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.", VoidPatternInitializer: "A void binding may not have an initializer.", YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", YieldInParameter: "Yield expression is not allowed in formal parameters.", YieldNotInGeneratorFunction: "'yield' is only allowed within generator functions.", ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0." }; const StrictModeErrors = { StrictDelete: "Deleting local variable in strict mode.", StrictEvalArguments: ({ referenceName }) => `Assigning to '${referenceName}' in strict mode.`, StrictEvalArgumentsBinding: ({ bindingName }) => `Binding '${bindingName}' in strict mode.`, StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.", StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.", StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.", StrictWith: "'with' in strict mode." }; const ParseExpressionErrors = { ParseExpressionEmptyInput: "Unexpected parseExpression() input: The input is empty or contains only comments.", ParseExpressionExpectsEOF: ({ unexpected }) => `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(unexpected)}\`.` }; const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]); const PipelineOperatorErrors = { PipeTopicRequiresHackPipes: 'Topic references are only supported when using the `"proposal": "hack"` version of the pipeline proposal.', PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.", PipeTopicUnconfiguredToken: ({ token }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`, PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.", PipeUnparenthesizedBody: ({ type }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({ type })}; please wrap it in parentheses.`, PipelineUnparenthesized: "Cannot mix binary operator with solo-await F#-style pipeline. Please wrap the pipeline in parentheses." }; const FunctionBindErrors = { UnsupportedBind: "Binding should be performed on object property.", UnsupportedBindRHS: "The right-hand side of binding can not be super or import." }; function defineHidden(obj, key, value) { Object.defineProperty(obj, key, { enumerable: false, configurable: true, value }); } function toParseErrorConstructor({ toMessage, code, reasonCode, syntaxPlugin }) { const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins"; return function constructor(loc, pos, details) { const error = new SyntaxError(); error.code = code; error.reasonCode = reasonCode; error.loc = loc; error.pos = pos; error.syntaxPlugin = syntaxPlugin; if (hasMissingPlugin) { error.missingPlugin = details.missingPlugin; } defineHidden(error, "clone", function clone(overrides = {}) { const { line, column, index = pos } = overrides.loc ?? loc; return constructor(new Position(line, column), index, { ...details, ...overrides.details }); }); defineHidden(error, "details", details); Object.defineProperty(error, "message", { configurable: true, get() { const message = `${toMessage(details)} (${loc.line}:${loc.column})`; this.message = message; return message; }, set(value) { Object.defineProperty(this, "message", { value, writable: true }); } }); return error; }; } function ParseErrorEnum(argument, syntaxPlugin) { if (Array.isArray(argument)) { return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]); } const ParseErrorConstructors = {}; for (const reasonCode of Object.keys(argument)) { const template = argument[reasonCode]; const { message, ...rest } = typeof template === "string" ? { message: () => template } : typeof template === "function" ? { message: template } : template; const toMessage = typeof message === "string" ? () => message : message; ParseErrorConstructors[reasonCode] = toParseErrorConstructor({ code: "BABEL_PARSER_SYNTAX_ERROR", reasonCode, toMessage, ...(syntaxPlugin ? { syntaxPlugin } : {}), ...rest }); } return ParseErrorConstructors; } const Errors = { ...ParseErrorEnum(ModuleErrors), ...ParseErrorEnum(StandardErrors), ...ParseErrorEnum(StrictModeErrors), ...ParseErrorEnum(ParseExpressionErrors), ...ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors), ...ParseErrorEnum`functionBind`(FunctionBindErrors) }; function createDefaultOptions() { return { sourceType: "script", sourceFilename: undefined, startIndex: 0, startColumn: 0, startLine: 1, allowAwaitOutsideFunction: false, allowReturnOutsideFunction: false, allowNewTargetOutsideFunction: false, allowImportExportEverywhere: false, allowSuperOutsideMethod: false, allowUndeclaredExports: false, allowYieldOutsideFunction: false, plugins: [], strictMode: undefined, ranges: false, locations: true, tokens: false, createImportExpressions: true, createParenthesizedExpressions: false, errorRecovery: false, attachComment: true, annexB: true }; } function getOptions(opts) { const options = createDefaultOptions(); if (opts == null) { return options; } if (opts.annexB != null && opts.annexB !== false) { throw new Error("The `annexB` option can only be set to `false`."); } for (const key of Object.keys(options)) { if (opts[key] != null) options[key] = opts[key]; } if (options.startLine === 1) { if (opts.startIndex == null && options.startColumn > 0) { options.startIndex = options.startColumn; } else if (opts.startColumn == null && options.startIndex > 0) { options.startColumn = options.startIndex; } } else if (opts.startColumn == null || opts.startIndex == null) { throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`."); } if (options.sourceType === "commonjs") { if (opts.allowAwaitOutsideFunction != null) { throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`."); } if (opts.allowReturnOutsideFunction != null) { throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`."); } if (opts.allowNewTargetOutsideFunction != null) { throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`."); } } return options; } function toESTreeLocation(node) { const { start, end } = node.loc; node.loc.start = new Position(start.line, start.column); node.loc.end = new Position(end.line, end.column); return node; } const estree = superClass => class ESTreeParserMixin extends superClass { createPosition(loc) { return new Position(loc.line, loc.column); } parse() { const file = super.parse(); if (this.optionFlags & 512) { file.tokens = file.tokens.map(toESTreeLocation); } return toESTreeLocation(file); } parseRegExpLiteral({ pattern, flags }) { let regex = null; try { regex = new RegExp(pattern, flags); } catch (_) {} const node = this.estreeParseLiteral(regex); node.regex = { pattern, flags }; return node; } parseBigIntLiteral(value) { let bigInt; try { bigInt = BigInt(value); } catch { bigInt = null; } const node = this.estreeParseLiteral(bigInt); node.bigint = String(node.value || value); return node; } estreeParseLiteral(value) { return this.parseLiteral(value, "Literal"); } parseStringLiteral(value) { return this.estreeParseLiteral(value); } parseNumericLiteral(value) { return this.estreeParseLiteral(value); } parseNullLiteral() { return this.estreeParseLiteral(null); } parseBooleanLiteral(value) { return this.estreeParseLiteral(value); } estreeParseChainExpression(node, endNode) { const chain = this.startNodeAtNode(node); chain.expression = node; return this.finishNodeAtNode(chain, "ChainExpression", endNode); } directiveToStmt(directive) { const expression = directive.value; delete directive.value; this.castNodeTo(expression, "Literal"); expression.raw = expression.extra.raw; expression.value = expression.extra.expressionValue; const stmt = this.castNodeTo(directive, "ExpressionStatement"); stmt.expression = expression; stmt.directive = expression.extra.rawValue; delete expression.extra; return stmt; } fillOptionalPropertiesForTSESLint(node) {} cloneEstreeStringLiteral(node) { const { start, end, loc, range, raw, value } = node; const cloned = Object.create(node.constructor.prototype); cloned.type = "Literal"; cloned.start = start; cloned.end = end; cloned.loc = loc; cloned.range = range; cloned.raw = raw; cloned.value = value; return cloned; } initFunction(node, isAsync) { super.initFunction(node, isAsync); node.expression = false; } checkDeclaration(node) { if (node != null && this.isObjectProperty(node)) { this.checkDeclaration(node.value); } else { super.checkDeclaration(node); } } getObjectOrClassMethodParams(method) { return method.value.params; } isValidDirective(stmt) { return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !stmt.expression.extra?.parenthesized; } parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse); const directiveStatements = node.directives.map(d => this.directiveToStmt(d)); node.body = directiveStatements.concat(node.body); delete node.directives; } parsePrivateName() { const node = super.parsePrivateName(); return this.convertPrivateNameToPrivateIdentifier(node); } convertPrivateNameToPrivateIdentifier(node) { const name = super.getPrivateNameSV(node); delete node.id; node.name = name; return this.castNodeTo(node, "PrivateIdentifier"); } isPrivateName(node) { return node.type === "PrivateIdentifier"; } getPrivateNameSV(node) { return node.name; } parseLiteral(value, type) { const node = super.parseLiteral(value, type); node.raw = node.extra.raw; delete node.extra; return node; } parseFunctionBody(node, allowExpression, isMethod = false) { super.parseFunctionBody(node, allowExpression, isMethod); node.expression = node.body.type !== "BlockStatement"; } parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { let funcNode = this.startNode(); funcNode.kind = node.kind; funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); delete funcNode.kind; const { typeParameters } = node; if (typeParameters) { delete node.typeParameters; funcNode.typeParameters = typeParameters; this.resetStartLocationFromNode(funcNode, typeParameters); } const valueNode = this.castNodeTo(funcNode, this.hasPlugin("typescript") && !funcNode.body ? "TSEmptyBodyFunctionExpression" : "FunctionExpression"); node.value = valueNode; if (type === "ClassPrivateMethod") { node.computed = false; } if (this.hasPlugin("typescript")) { if (node.abstract) { delete node.abstract; return this.finishNode(node, "TSAbstractMethodDefinition"); } } if (type === "ObjectMethod") { if (node.kind === "method") { node.kind = "init"; } node.shorthand = false; return this.finishNode(node, "Property"); } else { return this.finishNode(node, "MethodDefinition"); } } nameIsConstructor(key) { if (key.type === "Literal") return key.value === "constructor"; return super.nameIsConstructor(key); } parseClassProperty(...args) { const propertyNode = super.parseClassProperty(...args); if (propertyNode.abstract && this.hasPlugin("typescript")) { delete propertyNode.abstract; this.castNodeTo(propertyNode, "TSAbstractPropertyDefinition"); } else { this.castNodeTo(propertyNode, "PropertyDefinition"); } return propertyNode; } parseClassPrivateProperty(...args) { const propertyNode = super.parseClassPrivateProperty(...args); if (propertyNode.abstract && this.hasPlugin("typescript")) { this.castNodeTo(propertyNode, "TSAbstractPropertyDefinition"); } else { this.castNodeTo(propertyNode, "PropertyDefinition"); } propertyNode.computed = false; return propertyNode; } parseClassAccessorProperty(node) { const accessorPropertyNode = super.parseClassAccessorProperty(node); if (accessorPropertyNode.abstract && this.hasPlugin("typescript")) { delete accessorPropertyNode.abstract; this.castNodeTo(accessorPropertyNode, "TSAbstractAccessorProperty"); } else { this.castNodeTo(accessorPropertyNode, "AccessorProperty"); } return accessorPropertyNode; } parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); if (node) { node.kind = "init"; this.castNodeTo(node, "Property"); } return node; } finishObjectProperty(node) { node.kind = "init"; return this.finishNode(node, "Property"); } isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { return type === "Property" ? "value" : super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding); } isAssignable(node, isBinding) { if (node != null && this.isObjectProperty(node)) { return this.isAssignable(node.value, isBinding); } return super.isAssignable(node, isBinding); } toAssignable(node, isLHS = false) { if (node != null && this.isObjectProperty(node)) { const { key, value } = node; if (this.isPrivateName(key)) { this.classScope.usePrivateName(this.getPrivateNameSV(key), key.start); } this.toAssignable(value, isLHS); } else { super.toAssignable(node, isLHS); } } toAssignableObjectExpressionProp(prop, isLast, isLHS) { if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) { this.raise(Errors.PatternHasAccessor, prop.key); } else if (prop.type === "Property" && prop.method) { this.raise(Errors.PatternHasMethod, prop.key); } else { super.toAssignableObjectExpressionProp(prop, isLast, isLHS); } } finishCallExpression(unfinished, optional) { const node = super.finishCallExpression(unfinished, optional); if (node.callee.type === "Import") { this.castNodeTo(node, "ImportExpression"); node.source = node.arguments[0]; node.options = node.arguments[1] ?? null; delete node.arguments; delete node.callee; } else if (node.type === "OptionalCallExpression") { this.castNodeTo(node, "CallExpression"); } else { node.optional = false; } return node; } parseExport(unfinished, decorators) { const exportStartLoc = this.state.lastTokStartLoc; const node = super.parseExport(unfinished, decorators); switch (node.type) { case "ExportAllDeclaration": node.exported = null; break; case "ExportNamedDeclaration": if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") { this.castNodeTo(node, "ExportAllDeclaration"); node.exported = node.specifiers[0].exported; delete node.specifiers; } case "ExportDefaultDeclaration": { const { declaration } = node; if (declaration?.type === "ClassDeclaration" && declaration.decorators?.length > 0 && declaration.start === node.start) { this.resetStartLocation(node, exportStartLoc); } } break; } return node; } stopParseSubscript(base, state) { const node = super.stopParseSubscript(base, state); if (state.optionalChainMember) { return this.estreeParseChainExpression(node, base); } return node; } parseMember(base, startLoc, state, computed, optional) { const node = super.parseMember(base, startLoc, state, computed, optional); if (node.type === "OptionalMemberExpression") { this.castNodeTo(node, "MemberExpression"); } else { node.optional = false; } return node; } isOptionalMemberExpression(node) { if (node.type === "ChainExpression") { return node.expression.type === "MemberExpression"; } return super.isOptionalMemberExpression(node); } hasPropertyAsPrivateName(node) { if (node.type === "ChainExpression") { node = node.expression; } return super.hasPropertyAsPrivateName(node); } isObjectProperty(node) { return node.type === "Property" && node.kind === "init" && !node.method; } isObjectMethod(node) { return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set"); } castNodeTo(node, type) { const result = super.castNodeTo(node, type); this.fillOptionalPropertiesForTSESLint(result); return result; } cloneIdentifier(node) { const cloned = super.cloneIdentifier(node); this.fillOptionalPropertiesForTSESLint(cloned); return cloned; } cloneStringLiteral(node) { if (node.type === "Literal") { return this.cloneEstreeStringLiteral(node); } return super.cloneStringLiteral(node); } finishNodeAt(node, type, endLoc) { return toESTreeLocation(super.finishNodeAt(node, type, endLoc)); } finishNodeAtNode(node, type, endNode) { return toESTreeLocation(super.finishNodeAtNode(node, type, endNode)); } finishNode(node, type) { const result = super.finishNode(node, type); this.fillOptionalPropertiesForTSESLint(result); return result; } resetStartLocation(node, startLoc) { super.resetStartLocation(node, startLoc); toESTreeLocation(node); } resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { super.resetEndLocation(node, endLoc); toESTreeLocation(node); } }; const beforeExpr = true; const startsExpr = true; const isLoop = true; const isAssign = true; const prefix = true; const postfix = true; class ExportedTokenType { label; keyword; beforeExpr; startsExpr; rightAssociative; isLoop; isAssign; prefix; postfix; binop; constructor(label, conf = {}) { this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.rightAssociative = !!conf.rightAssociative; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop != null ? conf.binop : null; } } const keywords$1 = new Map(); function createKeyword(name, options = {}) { options.keyword = name; const token = createToken(name, options); keywords$1.set(name, token); return token; } function createBinop(name, binop) { return createToken(name, { beforeExpr, binop }); } let tokenTypeCounter = -1; const tokenTypes = []; const tokenLabels = []; const tokenBinops = []; const tokenBeforeExprs = []; const tokenStartsExprs = []; const tokenPrefixes = []; function createToken(name, options = {}) { ++tokenTypeCounter; tokenLabels.push(name); tokenBinops.push(options.binop ?? -1); tokenBeforeExprs.push(options.beforeExpr ?? false); tokenStartsExprs.push(options.startsExpr ?? false); tokenPrefixes.push(options.prefix ?? false); tokenTypes.push(new ExportedTokenType(name, options)); return tokenTypeCounter; } function createKeywordLike(name, options = {}) { ++tokenTypeCounter; keywords$1.set(name, tokenTypeCounter); tokenLabels.push(name); tokenBinops.push(options.binop ?? -1); tokenBeforeExprs.push(options.beforeExpr ?? false); tokenStartsExprs.push(options.startsExpr ?? false); tokenPrefixes.push(options.prefix ?? false); tokenTypes.push(new ExportedTokenType("name", options)); return tokenTypeCounter; } const tt = { bracketL: createToken("[", { beforeExpr, startsExpr }), bracketR: createToken("]"), braceL: createToken("{", { beforeExpr, startsExpr }), braceBarL: createToken("{|", { beforeExpr, startsExpr }), braceR: createToken("}"), braceBarR: createToken("|}"), parenL: createToken("(", { beforeExpr, startsExpr }), parenR: createToken(")"), comma: createToken(",", { beforeExpr }), semi: createToken(";", { beforeExpr }), colon: createToken(":", { beforeExpr }), doubleColon: createToken("::", { beforeExpr }), dot: createToken("."), question: createToken("?", { beforeExpr }), questionDot: createToken("?."), arrow: createToken("=>", { beforeExpr }), template: createToken("template"), ellipsis: createToken("...", { beforeExpr }), backQuote: createToken("`", { startsExpr }), dollarBraceL: createToken("${", { beforeExpr, startsExpr }), templateTail: createToken("...`", { startsExpr }), templateNonTail: createToken("...${", { beforeExpr, startsExpr }), at: createToken("@"), hash: createToken("#", { startsExpr }), interpreterDirective: createToken("#!..."), eq: createToken("=", { beforeExpr, isAssign }), assign: createToken("_=", { beforeExpr, isAssign }), slashAssign: createToken("_=", { beforeExpr, isAssign }), xorAssign: createToken("_=", { beforeExpr, isAssign }), moduloAssign: createToken("_=", { beforeExpr, isAssign }), incDec: createToken("++/--", { prefix, postfix, startsExpr }), bang: createToken("!", { beforeExpr, prefix, startsExpr }), tilde: createToken("~", { beforeExpr, prefix, startsExpr }), doubleCaret: createToken("^^", { startsExpr }), doubleAt: createToken("@@", { startsExpr }), pipeline: createBinop("|>", 0), nullishCoalescing: createBinop("??", 1), logicalOR: createBinop("||", 1), logicalAND: createBinop("&&", 2), bitwiseOR: createBinop("|", 3), bitwiseXOR: createBinop("^", 4), bitwiseAND: createBinop("&", 5), equality: createBinop("==/!=/===/!==", 6), lt: createBinop("</>/<=/>=", 7), gt: createBinop("</>/<=/>=", 7), relational: createBinop("</>/<=/>=", 7), bitShift: createBinop("<</>>/>>>", 8), bitShiftL: createBinop("<</>>/>>>", 8), bitShiftR: createBinop("<</>>/>>>", 8), plusMin: createToken("+/-", { beforeExpr, binop: 9, prefix, startsExpr }), modulo: createToken("%", { binop: 10, startsExpr }), star: createToken("*", { binop: 10 }), slash: createBinop("/", 10), exponent: createToken("**", { beforeExpr, binop: 11, rightAssociative: true }), _in: createKeyword("in", { beforeExpr, binop: 7 }), _instanceof: createKeyword("instanceof", { beforeExpr, binop: 7 }), _break: createKeyword("break"), _case: createKeyword("case", { beforeExpr }), _catch: createKeyword("catch"), _continue: createKeyword("continue"), _debugger: createKeyword("debugger"), _default: createKeyword("default", { beforeExpr }), _else: createKeyword("else", { beforeExpr }), _finally: createKeyword("finally"), _function: createKeyword("function", { startsExpr }), _if: createKeyword("if"), _return: createKeyword("return", { beforeExpr }), _switch: createKeyword("switch"), _throw: createKeyword("throw", { beforeExpr, prefix, startsExpr }), _try: createKeyword("try"), _var: createKeyword("var"), _const: createKeyword("const"), _with: createKeyword("with"), _new: createKeyword("new", { beforeExpr, startsExpr }), _this: createKeyword("this", { startsExpr }), _super: createKeyword("super", { startsExpr }), _class: createKeyword("class", { startsExpr }), _extends: createKeyword("extends", { beforeExpr }), _export: createKeyword("export"), _import: createKeyword("import", { startsExpr }), _null: createKeyword("null", { startsExpr }), _true: createKeyword("true", { startsExpr }), _false: createKeyword("false", { startsExpr }), _typeof: createKeyword("typeof", { beforeExpr, prefix, startsExpr }), _void: createKeyword("void", { beforeExpr, prefix, startsExpr }), _delete: createKeyword("delete", { beforeExpr, prefix, startsExpr }), _do: createKeyword("do", { isLoop, beforeExpr }), _for: createKeyword("for", { isLoop }), _while: createKeyword("while", { isLoop }), _as: createKeywordLike("as", { startsExpr }), _assert: createKeywordLike("assert", { startsExpr }), _async: createKeywordLike("async", { startsExpr }), _await: createKeywordLike("await", { startsExpr }), _defer: createKeywordLike("defer", { startsExpr }), _from: createKeywordLike("from", { startsExpr }), _get: createKeywordLike("get", { startsExpr }), _let: createKeywordLike("let", { startsExpr }), _meta: createKeywordLike("meta", { startsExpr }), _of: createKeywordLike("of", { startsExpr }), _sent: createKeywordLike("sent", { startsExpr }), _set: createKeywordLike("set", { startsExpr }), _source: createKeywordLike("source", { startsExpr }), _static: createKeywordLike("static", { startsExpr }), _using: createKeywordLike("using", { startsExpr }), _yield: createKeywordLike("yield", { startsExpr }), _asserts: createKeywordLike("asserts", { startsExpr }), _checks: createKeywordLike("checks", { startsExpr }), _exports: createKeywordLike("exports", { startsExpr }), _global: createKeywordLike("global", { startsExpr }), _implements: createKeywordLike("implements", { startsExpr }), _intrinsic: createKeywordLike("intrinsic", { startsExpr }), _infer: createKeywordLike("infer", { startsExpr }), _is: createKeywordLike("is", { startsExpr }), _mixins: createKeywordLike("mixins", { startsExpr }), _proto: createKeywordLike("proto", { startsExpr }), _require: createKeywordLike("require", { startsExpr }), _satisfies: createKeywordLike("satisfies", { startsExpr }), _keyof: createKeywordLike("keyof", { startsExpr }), _readonly: createKeywordLike("readonly", { startsExpr }), _unique: createKeywordLike("unique", { startsExpr }), _abstract: createKeywordLike("abstract", { startsExpr }), _declare: createKeywordLike("declare", { startsExpr }), _enum: createKeywordLike("enum", { startsExpr }), _module: createKeywordLike("module", { startsExpr }), _namespace: createKeywordLike("namespace", { startsExpr }), _interface: createKeywordLike("interface", { startsExpr }), _type: createKeywordLike("type", { startsExpr }), _opaque: createKeywordLike("opaque", { startsExpr }), name: createToken("name", { startsExpr }), placeholder: createToken("%%", { startsExpr }), string: createToken("string", { startsExpr }), num: createToken("num", { startsExpr }), bigint: createToken("bigint", { startsExpr }), regexp: createToken("regexp", { startsExpr }), privateName: createToken("#name", { startsExpr }), eof: createToken("eof"), jsxName: createToken("jsxName"), jsxText: createToken("jsxText", { beforeExpr }), jsxTagStart: createToken("jsxTagStart", { startsExpr }), jsxTagEnd: createToken("jsxTagEnd") }; function tokenIsIdentifier(token) { return token >= 89 && token <= 129; } function tokenKeywordOrIdentifierIsKeyword(token) { return token <= 88; } function tokenIsKeywordOrIdentifier(token) { return token >= 54 && token <= 129; } function tokenIsLiteralPropertyName(token) { return token >= 54 && token <= 132; } function tokenComesBeforeExpression(token) { return tokenBeforeExprs[token]; } function tokenCanStartExpression(token) { return tokenStartsExprs[token]; } function tokenIsAssignment(token) { return token >= 25 && token <= 29; } function tokenIsFlowInterfaceOrTypeOrOpaque(token) { return token >= 125 && token <= 127; } function tokenIsLoop(token) { return token >= 86 && token <= 88; } function tokenIsKeyword(token) { return token >= 54 && token <= 88; } function tokenIsOperator(token) { return token >= 35 && token <= 55; } function tokenIsPostfix(token) { return token === 30; } function tokenIsPrefix(token) { return tokenPrefixes[token]; } function tokenIsTSTypeOperator(token) { return token >= 117 && token <= 119; } function tokenIsTSDeclarationStart(token) { return token >= 120 && token <= 126; } function tokenLabelName(token) { return tokenLabels[token]; } function tokenOperatorPrecedence(token) { return tokenBinops[token]; } function tokenIsRightAssociative(token) { return token === 53; } function tokenIsTemplate(token) { return token >= 20 && token <= 21; } function getExportedToken(token) { return tokenTypes[token]; } class TokContext { constructor(token, preserveSpace) { this.token = token; this.preserveSpace = !!preserveSpace; } token; preserveSpace; } const types = { brace: new TokContext("{"), j_oTag: new TokContext("<tag"), j_cTag: new TokContext("</tag"), j_expr: new TokContext("<tag>...</tag>", true) }; const bmpIdentifierStart = /[\p{ID_Start}\u088f\u0c5c\u0cdc\ua7ce\ua7cf\ua7d2\ua7d4\ua7f1]/u; const bmpIdentifier = /[\p{ID_Continue}\u088f\u0c5c\u0cdc\ua7ce\ua7cf\ua7d2\ua7d4\ua7f1\u1acf-\u1add\u1ae0-\u1aeb]/u; const supplementaryIdentifierStartCodes = [2368, 25, 1388, 2, 3817, 43, 20677, 24, 3, 24, 287, 4, 6146, 7, 1290, 21, 98, 114, 22734, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 53307, 5, 5987, 11, 21763, 4297]; const supplementaryIdentifierCodes = [3834, 1, 3173, 7, 633, 9, 51450, 0, 3, 0, 8, 1, 6, 0]; function isInSupplementarySet(code, set) { let pos = 0x10000; for (let i = 0, length = set.length; i < length; i += 2) { pos += set[i]; if (pos > code) return false; pos += set[i + 1]; if (pos >= code) return true; } return false; } function isIdentifierStart(code) { if (code < 65) return code === 36; if (code <= 90) return true; if (code < 97) return code === 95; if (code <= 122) return true; if (code <= 0xffff) { return code >= 0xaa && bmpIdentifierStart.test(String.fromCharCode(code)); } return !isNaN(code) && code <= 0x10ffff && (bmpIdentifierStart.test(String.fromCodePoint(code)) || isInSupplementarySet(code, supplementaryIdentifierStartCodes)); } function isIdentifierChar(code) { if (code < 48) return code === 36; if (code < 58) return true; if (code < 65) return false; if (code <= 90) return true; if (code < 97) return code === 95; if (code <= 122) return true; if (code <= 0xffff) { return code >= 0xaa && bmpIdentifier.test(String.fromCharCode(code)); } return !isNaN(code) && code <= 0x10ffff && (bmpIdentifier.test(String.fromCodePoint(code)) || isInSupplementarySet(code, supplementaryIdentifierStartCodes) || isInSupplementarySet(code, supplementaryIdentifierCodes)); } const reservedWords = { keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], strictBind: ["eval", "arguments"] }; const keywords = new Set(reservedWords.keyword); const reservedWordsStrictSet = new Set(reservedWords.strict); const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); function isReservedWord(word, inModule) { return inModule && word === "await" || word === "enum"; } function isStrictReservedWord(word, inModule) { return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); } function isStrictBindOnlyReservedWord(word) { return reservedWordsStrictBindSet.has(word); } function isStrictBindReservedWord(word, inModule) { return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); } function isKeyword(word) { return keywords.has(word); } function isIteratorStart(current, next, next2) { return current === 64 && next === 64 && isIdentifierStart(next2); } const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]); function canBeReservedWord(word) { return reservedWordLikeSet.has(word); } class Scope { flags = 0; names = new Map(); firstLexicalName = ""; constructor(flags) { this.flags = flags; } } class ScopeHandler { parser; scopeStack = []; inModule; undefinedExports = new Map(); constructor(parser, inModule) { this.parser = parser; this.inModule = inModule; } get inTopLevel() { return (this.currentScope().flags & 1) > 0; } get inFunction() { return (this.currentVarScopeFlags() & 2) > 0; } get allowSuper() { return (this.currentThisScopeFlags() & 16) > 0; } get allowDirectSuper() { return (this.currentThisScopeFlags() & 32) > 0; } get allowNewTarget() { return (this.currentThisScopeFlags() & 512) > 0; } get inClass() { return (this.currentThisScopeFlags() & 64) > 0; } get inClassAndNotInNonArrowFunction() { const flags = this.currentThisScopeFlags(); return (flags & 64) > 0 && (flags & 2) === 0; } get inStaticBlock() { for (let i = this.scopeStack.length - 1;; i--) { const {