You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

14204 lines
479 KiB

1 month ago
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. function _objectWithoutPropertiesLoose(r, e) {
  6. if (null == r) return {};
  7. var t = {};
  8. for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
  9. if (e.includes(n)) continue;
  10. t[n] = r[n];
  11. }
  12. return t;
  13. }
  14. class Position {
  15. constructor(line, col, index) {
  16. this.line = void 0;
  17. this.column = void 0;
  18. this.index = void 0;
  19. this.line = line;
  20. this.column = col;
  21. this.index = index;
  22. }
  23. }
  24. class SourceLocation {
  25. constructor(start, end) {
  26. this.start = void 0;
  27. this.end = void 0;
  28. this.filename = void 0;
  29. this.identifierName = void 0;
  30. this.start = start;
  31. this.end = end;
  32. }
  33. }
  34. function createPositionWithColumnOffset(position, columnOffset) {
  35. const {
  36. line,
  37. column,
  38. index
  39. } = position;
  40. return new Position(line, column + columnOffset, index + columnOffset);
  41. }
  42. const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";
  43. var ModuleErrors = {
  44. ImportMetaOutsideModule: {
  45. message: `import.meta may appear only with 'sourceType: "module"'`,
  46. code
  47. },
  48. ImportOutsideModule: {
  49. message: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  50. code
  51. }
  52. };
  53. const NodeDescriptions = {
  54. ArrayPattern: "array destructuring pattern",
  55. AssignmentExpression: "assignment expression",
  56. AssignmentPattern: "assignment expression",
  57. ArrowFunctionExpression: "arrow function expression",
  58. ConditionalExpression: "conditional expression",
  59. CatchClause: "catch clause",
  60. ForOfStatement: "for-of statement",
  61. ForInStatement: "for-in statement",
  62. ForStatement: "for-loop",
  63. FormalParameters: "function parameter list",
  64. Identifier: "identifier",
  65. ImportSpecifier: "import specifier",
  66. ImportDefaultSpecifier: "import default specifier",
  67. ImportNamespaceSpecifier: "import namespace specifier",
  68. ObjectPattern: "object destructuring pattern",
  69. ParenthesizedExpression: "parenthesized expression",
  70. RestElement: "rest element",
  71. UpdateExpression: {
  72. true: "prefix operation",
  73. false: "postfix operation"
  74. },
  75. VariableDeclarator: "variable declaration",
  76. YieldExpression: "yield expression"
  77. };
  78. const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type];
  79. var StandardErrors = {
  80. AccessorIsGenerator: ({
  81. kind
  82. }) => `A ${kind}ter cannot be a generator.`,
  83. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  84. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  85. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  86. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  87. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  88. AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.",
  89. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  90. AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
  91. BadGetterArity: "A 'get' accessor must not have any formal parameters.",
  92. BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
  93. BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
  94. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  95. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  96. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  97. ConstructorIsAsync: "Constructor can't be an async function.",
  98. ConstructorIsGenerator: "Constructor can't be a generator.",
  99. DeclarationMissingInitializer: ({
  100. kind
  101. }) => `Missing initializer in ${kind} declaration.`,
  102. DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
  103. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",
  104. DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",
  105. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  106. DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",
  107. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  108. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  109. DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.',
  110. DeletePrivateField: "Deleting a private field is not allowed.",
  111. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  112. DuplicateConstructor: "Duplicate constructor in the same class.",
  113. DuplicateDefaultExport: "Only one default export allowed per module.",
  114. DuplicateExport: ({
  115. exportName
  116. }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
  117. DuplicateProto: "Redefinition of __proto__ property.",
  118. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  119. DynamicImportPhaseRequiresImportExpressions: ({
  120. phase
  121. }) => `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`,
  122. ElementAfterRest: "Rest element must be last element.",
  123. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  124. ExportBindingIsString: ({
  125. localName,
  126. exportName
  127. }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
  128. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  129. ForInOfLoopInitializer: ({
  130. type
  131. }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
  132. ForInUsing: "For-in loop may not start with 'using' declaration.",
  133. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  134. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  135. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  136. IllegalBreakContinue: ({
  137. type
  138. }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
  139. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  140. IllegalReturn: "'return' outside of function.",
  141. ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.",
  142. ImportBindingIsString: ({
  143. importName
  144. }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`,
  145. ImportCallArity: `\`import()\` requires exactly one or two arguments.`,
  146. ImportCallNotNewExpression: "Cannot use new with import(...).",
  147. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  148. ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
  149. ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
  150. ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
  151. IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
  152. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  153. InvalidCodePoint: "Code point out of bounds.",
  154. InvalidCoverInitializedName: "Invalid shorthand property initializer.",
  155. InvalidDecimal: "Invalid decimal.",
  156. InvalidDigit: ({
  157. radix
  158. }) => `Expected number in radix ${radix}.`,
  159. InvalidEscapeSequence: "Bad character escape sequence.",
  160. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  161. InvalidEscapedReservedWord: ({
  162. reservedWord
  163. }) => `Escape sequence in keyword ${reservedWord}.`,
  164. InvalidIdentifier: ({
  165. identifierName
  166. }) => `Invalid identifier ${identifierName}.`,
  167. InvalidLhs: ({
  168. ancestor
  169. }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  170. InvalidLhsBinding: ({
  171. ancestor
  172. }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  173. InvalidLhsOptionalChaining: ({
  174. ancestor
  175. }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`,
  176. InvalidNumber: "Invalid number.",
  177. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  178. InvalidOrUnexpectedToken: ({
  179. unexpected
  180. }) => `Unexpected character '${unexpected}'.`,
  181. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  182. InvalidPrivateFieldResolution: ({
  183. identifierName
  184. }) => `Private name #${identifierName} is not defined.`,
  185. InvalidPropertyBindingPattern: "Binding member expression.",
  186. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  187. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  188. LabelRedeclaration: ({
  189. labelName
  190. }) => `Label '${labelName}' is already declared.`,
  191. LetInLexicalBinding: "'let' is disallowed as a lexically bound name.",
  192. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  193. MalformedRegExpFlags: "Invalid regular expression flag.",
  194. MissingClassName: "A class name is required.",
  195. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  196. MissingSemicolon: "Missing semicolon.",
  197. MissingPlugin: ({
  198. missingPlugin
  199. }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  200. MissingOneOfPlugins: ({
  201. missingPlugin
  202. }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  203. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  204. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  205. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  206. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  207. ModuleAttributesWithDuplicateKeys: ({
  208. key
  209. }) => `Duplicate key "${key}" is not allowed in module attributes.`,
  210. ModuleExportNameHasLoneSurrogate: ({
  211. surrogateCharCode
  212. }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
  213. ModuleExportUndefined: ({
  214. localName
  215. }) => `Export '${localName}' is not defined.`,
  216. MultipleDefaultsInSwitch: "Multiple default clauses.",
  217. NewlineAfterThrow: "Illegal newline after throw.",
  218. NoCatchOrFinally: "Missing catch or finally clause.",
  219. NumberIdentifier: "Identifier directly after number.",
  220. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  221. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  222. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  223. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  224. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  225. ParamDupe: "Argument name clash.",
  226. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  227. PatternHasMethod: "Object pattern can't contain methods.",
  228. PrivateInExpectedIn: ({
  229. identifierName
  230. }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,
  231. PrivateNameRedeclaration: ({
  232. identifierName
  233. }) => `Duplicate private name #${identifierName}.`,
  234. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  235. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  236. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  237. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  238. RestTrailingComma: "Unexpected trailing comma after rest element.",
  239. SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.",
  240. 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.",
  241. SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.',
  242. StaticPrototype: "Classes may not have static property named prototype.",
  243. 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?",
  244. SuperPrivateField: "Private fields can't be accessed on super.",
  245. TrailingDecorator: "Decorators must be attached to a class element.",
  246. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  247. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  248. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  249. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  250. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  251. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  252. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  253. UnexpectedKeyword: ({
  254. keyword
  255. }) => `Unexpected keyword '${keyword}'.`,
  256. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  257. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  258. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  259. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  260. UnexpectedPrivateField: "Unexpected private name.",
  261. UnexpectedReservedWord: ({
  262. reservedWord
  263. }) => `Unexpected reserved word '${reservedWord}'.`,
  264. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  265. UnexpectedToken: ({
  266. expected,
  267. unexpected
  268. }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`,
  269. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  270. UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.",
  271. UnsupportedBind: "Binding should be performed on object property.",
  272. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  273. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  274. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  275. UnsupportedMetaProperty: ({
  276. target,
  277. onlyValidPropertyName
  278. }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,
  279. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  280. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  281. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  282. UnterminatedComment: "Unterminated comment.",
  283. UnterminatedRegExp: "Unterminated regular expression.",
  284. UnterminatedString: "Unterminated string constant.",
  285. UnterminatedTemplate: "Unterminated template.",
  286. UsingDeclarationExport: "Using declaration cannot be exported.",
  287. UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.",
  288. VarRedeclaration: ({
  289. identifierName
  290. }) => `Identifier '${identifierName}' has already been declared.`,
  291. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  292. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  293. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  294. };
  295. var StrictModeErrors = {
  296. StrictDelete: "Deleting local variable in strict mode.",
  297. StrictEvalArguments: ({
  298. referenceName
  299. }) => `Assigning to '${referenceName}' in strict mode.`,
  300. StrictEvalArgumentsBinding: ({
  301. bindingName
  302. }) => `Binding '${bindingName}' in strict mode.`,
  303. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  304. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  305. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  306. StrictWith: "'with' in strict mode."
  307. };
  308. const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]);
  309. var PipelineOperatorErrors = Object.assign({
  310. PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  311. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  312. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  313. PipeTopicUnconfiguredToken: ({
  314. token
  315. }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`,
  316. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  317. PipeUnparenthesizedBody: ({
  318. type
  319. }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({
  320. type
  321. })}; please wrap it in parentheses.`
  322. }, {
  323. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  324. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  325. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  326. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  327. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  328. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'
  329. });
  330. const _excluded = ["message"];
  331. function defineHidden(obj, key, value) {
  332. Object.defineProperty(obj, key, {
  333. enumerable: false,
  334. configurable: true,
  335. value
  336. });
  337. }
  338. function toParseErrorConstructor({
  339. toMessage,
  340. code,
  341. reasonCode,
  342. syntaxPlugin
  343. }) {
  344. const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins";
  345. {
  346. const oldReasonCodes = {
  347. AccessorCannotDeclareThisParameter: "AccesorCannotDeclareThisParameter",
  348. AccessorCannotHaveTypeParameters: "AccesorCannotHaveTypeParameters",
  349. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",
  350. SetAccessorCannotHaveOptionalParameter: "SetAccesorCannotHaveOptionalParameter",
  351. SetAccessorCannotHaveRestParameter: "SetAccesorCannotHaveRestParameter",
  352. SetAccessorCannotHaveReturnType: "SetAccesorCannotHaveReturnType"
  353. };
  354. if (oldReasonCodes[reasonCode]) {
  355. reasonCode = oldReasonCodes[reasonCode];
  356. }
  357. }
  358. return function constructor(loc, details) {
  359. const error = new SyntaxError();
  360. error.code = code;
  361. error.reasonCode = reasonCode;
  362. error.loc = loc;
  363. error.pos = loc.index;
  364. error.syntaxPlugin = syntaxPlugin;
  365. if (hasMissingPlugin) {
  366. error.missingPlugin = details.missingPlugin;
  367. }
  368. defineHidden(error, "clone", function clone(overrides = {}) {
  369. var _overrides$loc;
  370. const {
  371. line,
  372. column,
  373. index
  374. } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc;
  375. return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details));
  376. });
  377. defineHidden(error, "details", details);
  378. Object.defineProperty(error, "message", {
  379. configurable: true,
  380. get() {
  381. const message = `${toMessage(details)} (${loc.line}:${loc.column})`;
  382. this.message = message;
  383. return message;
  384. },
  385. set(value) {
  386. Object.defineProperty(this, "message", {
  387. value,
  388. writable: true
  389. });
  390. }
  391. });
  392. return error;
  393. };
  394. }
  395. function ParseErrorEnum(argument, syntaxPlugin) {
  396. if (Array.isArray(argument)) {
  397. return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]);
  398. }
  399. const ParseErrorConstructors = {};
  400. for (const reasonCode of Object.keys(argument)) {
  401. const template = argument[reasonCode];
  402. const _ref = typeof template === "string" ? {
  403. message: () => template
  404. } : typeof template === "function" ? {
  405. message: template
  406. } : template,
  407. {
  408. message
  409. } = _ref,
  410. rest = _objectWithoutPropertiesLoose(_ref, _excluded);
  411. const toMessage = typeof message === "string" ? () => message : message;
  412. ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({
  413. code: "BABEL_PARSER_SYNTAX_ERROR",
  414. reasonCode,
  415. toMessage
  416. }, syntaxPlugin ? {
  417. syntaxPlugin
  418. } : {}, rest));
  419. }
  420. return ParseErrorConstructors;
  421. }
  422. const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors));
  423. function createDefaultOptions() {
  424. return {
  425. sourceType: "script",
  426. sourceFilename: undefined,
  427. startIndex: 0,
  428. startColumn: 0,
  429. startLine: 1,
  430. allowAwaitOutsideFunction: false,
  431. allowReturnOutsideFunction: false,
  432. allowNewTargetOutsideFunction: false,
  433. allowImportExportEverywhere: false,
  434. allowSuperOutsideMethod: false,
  435. allowUndeclaredExports: false,
  436. plugins: [],
  437. strictMode: null,
  438. ranges: false,
  439. tokens: false,
  440. createImportExpressions: false,
  441. createParenthesizedExpressions: false,
  442. errorRecovery: false,
  443. attachComment: true,
  444. annexB: true
  445. };
  446. }
  447. function getOptions(opts) {
  448. const options = createDefaultOptions();
  449. if (opts == null) {
  450. return options;
  451. }
  452. if (opts.annexB != null && opts.annexB !== false) {
  453. throw new Error("The `annexB` option can only be set to `false`.");
  454. }
  455. for (const key of Object.keys(options)) {
  456. if (opts[key] != null) options[key] = opts[key];
  457. }
  458. if (options.startLine === 1) {
  459. if (opts.startIndex == null && options.startColumn > 0) {
  460. options.startIndex = options.startColumn;
  461. } else if (opts.startColumn == null && options.startIndex > 0) {
  462. options.startColumn = options.startIndex;
  463. }
  464. } else if (opts.startColumn == null || opts.startIndex == null) {
  465. if (opts.startIndex != null) {
  466. throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");
  467. }
  468. }
  469. return options;
  470. }
  471. const {
  472. defineProperty
  473. } = Object;
  474. const toUnenumerable = (object, key) => {
  475. if (object) {
  476. defineProperty(object, key, {
  477. enumerable: false,
  478. value: object[key]
  479. });
  480. }
  481. };
  482. function toESTreeLocation(node) {
  483. toUnenumerable(node.loc.start, "index");
  484. toUnenumerable(node.loc.end, "index");
  485. return node;
  486. }
  487. var estree = superClass => class ESTreeParserMixin extends superClass {
  488. parse() {
  489. const file = toESTreeLocation(super.parse());
  490. if (this.optionFlags & 128) {
  491. file.tokens = file.tokens.map(toESTreeLocation);
  492. }
  493. return file;
  494. }
  495. parseRegExpLiteral({
  496. pattern,
  497. flags
  498. }) {
  499. let regex = null;
  500. try {
  501. regex = new RegExp(pattern, flags);
  502. } catch (_) {}
  503. const node = this.estreeParseLiteral(regex);
  504. node.regex = {
  505. pattern,
  506. flags
  507. };
  508. return node;
  509. }
  510. parseBigIntLiteral(value) {
  511. let bigInt;
  512. try {
  513. bigInt = BigInt(value);
  514. } catch (_unused) {
  515. bigInt = null;
  516. }
  517. const node = this.estreeParseLiteral(bigInt);
  518. node.bigint = String(node.value || value);
  519. return node;
  520. }
  521. parseDecimalLiteral(value) {
  522. const decimal = null;
  523. const node = this.estreeParseLiteral(decimal);
  524. node.decimal = String(node.value || value);
  525. return node;
  526. }
  527. estreeParseLiteral(value) {
  528. return this.parseLiteral(value, "Literal");
  529. }
  530. parseStringLiteral(value) {
  531. return this.estreeParseLiteral(value);
  532. }
  533. parseNumericLiteral(value) {
  534. return this.estreeParseLiteral(value);
  535. }
  536. parseNullLiteral() {
  537. return this.estreeParseLiteral(null);
  538. }
  539. parseBooleanLiteral(value) {
  540. return this.estreeParseLiteral(value);
  541. }
  542. directiveToStmt(directive) {
  543. const expression = directive.value;
  544. delete directive.value;
  545. expression.type = "Literal";
  546. expression.raw = expression.extra.raw;
  547. expression.value = expression.extra.expressionValue;
  548. const stmt = directive;
  549. stmt.type = "ExpressionStatement";
  550. stmt.expression = expression;
  551. stmt.directive = expression.extra.rawValue;
  552. delete expression.extra;
  553. return stmt;
  554. }
  555. initFunction(node, isAsync) {
  556. super.initFunction(node, isAsync);
  557. node.expression = false;
  558. }
  559. checkDeclaration(node) {
  560. if (node != null && this.isObjectProperty(node)) {
  561. this.checkDeclaration(node.value);
  562. } else {
  563. super.checkDeclaration(node);
  564. }
  565. }
  566. getObjectOrClassMethodParams(method) {
  567. return method.value.params;
  568. }
  569. isValidDirective(stmt) {
  570. var _stmt$expression$extr;
  571. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  572. }
  573. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  574. super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse);
  575. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  576. node.body = directiveStatements.concat(node.body);
  577. delete node.directives;
  578. }
  579. parsePrivateName() {
  580. const node = super.parsePrivateName();
  581. {
  582. if (!this.getPluginOption("estree", "classFeatures")) {
  583. return node;
  584. }
  585. }
  586. return this.convertPrivateNameToPrivateIdentifier(node);
  587. }
  588. convertPrivateNameToPrivateIdentifier(node) {
  589. const name = super.getPrivateNameSV(node);
  590. node = node;
  591. delete node.id;
  592. node.name = name;
  593. node.type = "PrivateIdentifier";
  594. return node;
  595. }
  596. isPrivateName(node) {
  597. {
  598. if (!this.getPluginOption("estree", "classFeatures")) {
  599. return super.isPrivateName(node);
  600. }
  601. }
  602. return node.type === "PrivateIdentifier";
  603. }
  604. getPrivateNameSV(node) {
  605. {
  606. if (!this.getPluginOption("estree", "classFeatures")) {
  607. return super.getPrivateNameSV(node);
  608. }
  609. }
  610. return node.name;
  611. }
  612. parseLiteral(value, type) {
  613. const node = super.parseLiteral(value, type);
  614. node.raw = node.extra.raw;
  615. delete node.extra;
  616. return node;
  617. }
  618. parseFunctionBody(node, allowExpression, isMethod = false) {
  619. super.parseFunctionBody(node, allowExpression, isMethod);
  620. node.expression = node.body.type !== "BlockStatement";
  621. }
  622. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  623. let funcNode = this.startNode();
  624. funcNode.kind = node.kind;
  625. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  626. funcNode.type = "FunctionExpression";
  627. delete funcNode.kind;
  628. node.value = funcNode;
  629. const {
  630. typeParameters
  631. } = node;
  632. if (typeParameters) {
  633. delete node.typeParameters;
  634. funcNode.typeParameters = typeParameters;
  635. this.resetStartLocationFromNode(funcNode, typeParameters);
  636. }
  637. if (type === "ClassPrivateMethod") {
  638. node.computed = false;
  639. }
  640. return this.finishNode(node, "MethodDefinition");
  641. }
  642. nameIsConstructor(key) {
  643. if (key.type === "Literal") return key.value === "constructor";
  644. return super.nameIsConstructor(key);
  645. }
  646. parseClassProperty(...args) {
  647. const propertyNode = super.parseClassProperty(...args);
  648. {
  649. if (!this.getPluginOption("estree", "classFeatures")) {
  650. return propertyNode;
  651. }
  652. }
  653. {
  654. propertyNode.type = "PropertyDefinition";
  655. }
  656. return propertyNode;
  657. }
  658. parseClassPrivateProperty(...args) {
  659. const propertyNode = super.parseClassPrivateProperty(...args);
  660. {
  661. if (!this.getPluginOption("estree", "classFeatures")) {
  662. return propertyNode;
  663. }
  664. }
  665. {
  666. propertyNode.type = "PropertyDefinition";
  667. }
  668. propertyNode.computed = false;
  669. return propertyNode;
  670. }
  671. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  672. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  673. if (node) {
  674. node.type = "Property";
  675. if (node.kind === "method") {
  676. node.kind = "init";
  677. }
  678. node.shorthand = false;
  679. }
  680. return node;
  681. }
  682. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  683. const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  684. if (node) {
  685. node.kind = "init";
  686. node.type = "Property";
  687. }
  688. return node;
  689. }
  690. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  691. return type === "Property" ? "value" : super.isValidLVal(type, isUnparenthesizedInAssign, binding);
  692. }
  693. isAssignable(node, isBinding) {
  694. if (node != null && this.isObjectProperty(node)) {
  695. return this.isAssignable(node.value, isBinding);
  696. }
  697. return super.isAssignable(node, isBinding);
  698. }
  699. toAssignable(node, isLHS = false) {
  700. if (node != null && this.isObjectProperty(node)) {
  701. const {
  702. key,
  703. value
  704. } = node;
  705. if (this.isPrivateName(key)) {
  706. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  707. }
  708. this.toAssignable(value, isLHS);
  709. } else {
  710. super.toAssignable(node, isLHS);
  711. }
  712. }
  713. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  714. if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) {
  715. this.raise(Errors.PatternHasAccessor, prop.key);
  716. } else if (prop.type === "Property" && prop.method) {
  717. this.raise(Errors.PatternHasMethod, prop.key);
  718. } else {
  719. super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  720. }
  721. }
  722. finishCallExpression(unfinished, optional) {
  723. const node = super.finishCallExpression(unfinished, optional);
  724. if (node.callee.type === "Import") {
  725. var _ref, _ref2;
  726. node.type = "ImportExpression";
  727. node.source = node.arguments[0];
  728. node.options = (_ref = node.arguments[1]) != null ? _ref : null;
  729. node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null;
  730. delete node.arguments;
  731. delete node.callee;
  732. }
  733. return node;
  734. }
  735. toReferencedArguments(node) {
  736. if (node.type === "ImportExpression") {
  737. return;
  738. }
  739. super.toReferencedArguments(node);
  740. }
  741. parseExport(unfinished, decorators) {
  742. const exportStartLoc = this.state.lastTokStartLoc;
  743. const node = super.parseExport(unfinished, decorators);
  744. switch (node.type) {
  745. case "ExportAllDeclaration":
  746. node.exported = null;
  747. break;
  748. case "ExportNamedDeclaration":
  749. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  750. node.type = "ExportAllDeclaration";
  751. node.exported = node.specifiers[0].exported;
  752. delete node.specifiers;
  753. }
  754. case "ExportDefaultDeclaration":
  755. {
  756. var _declaration$decorato;
  757. const {
  758. declaration
  759. } = node;
  760. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) {
  761. this.resetStartLocation(node, exportStartLoc);
  762. }
  763. }
  764. break;
  765. }
  766. return node;
  767. }
  768. parseSubscript(base, startLoc, noCalls, state) {
  769. const node = super.parseSubscript(base, startLoc, noCalls, state);
  770. if (state.optionalChainMember) {
  771. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  772. node.type = node.type.substring(8);
  773. }
  774. if (state.stop) {
  775. const chain = this.startNodeAtNode(node);
  776. chain.expression = node;
  777. return this.finishNode(chain, "ChainExpression");
  778. }
  779. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  780. node.optional = false;
  781. }
  782. return node;
  783. }
  784. isOptionalMemberExpression(node) {
  785. if (node.type === "ChainExpression") {
  786. return node.expression.type === "MemberExpression";
  787. }
  788. return super.isOptionalMemberExpression(node);
  789. }
  790. hasPropertyAsPrivateName(node) {
  791. if (node.type === "ChainExpression") {
  792. node = node.expression;
  793. }
  794. return super.hasPropertyAsPrivateName(node);
  795. }
  796. isObjectProperty(node) {
  797. return node.type === "Property" && node.kind === "init" && !node.method;
  798. }
  799. isObjectMethod(node) {
  800. return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set");
  801. }
  802. finishNodeAt(node, type, endLoc) {
  803. return toESTreeLocation(super.finishNodeAt(node, type, endLoc));
  804. }
  805. resetStartLocation(node, startLoc) {
  806. super.resetStartLocation(node, startLoc);
  807. toESTreeLocation(node);
  808. }
  809. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  810. super.resetEndLocation(node, endLoc);
  811. toESTreeLocation(node);
  812. }
  813. };
  814. class TokContext {
  815. constructor(token, preserveSpace) {
  816. this.token = void 0;
  817. this.preserveSpace = void 0;
  818. this.token = token;
  819. this.preserveSpace = !!preserveSpace;
  820. }
  821. }
  822. const types = {
  823. brace: new TokContext("{"),
  824. j_oTag: new TokContext("<tag"),
  825. j_cTag: new TokContext("</tag"),
  826. j_expr: new TokContext("<tag>...</tag>", true)
  827. };
  828. {
  829. types.template = new TokContext("`", true);
  830. }
  831. const beforeExpr = true;
  832. const startsExpr = true;
  833. const isLoop = true;
  834. const isAssign = true;
  835. const prefix = true;
  836. const postfix = true;
  837. class ExportedTokenType {
  838. constructor(label, conf = {}) {
  839. this.label = void 0;
  840. this.keyword = void 0;
  841. this.beforeExpr = void 0;
  842. this.startsExpr = void 0;
  843. this.rightAssociative = void 0;
  844. this.isLoop = void 0;
  845. this.isAssign = void 0;
  846. this.prefix = void 0;
  847. this.postfix = void 0;
  848. this.binop = void 0;
  849. this.label = label;
  850. this.keyword = conf.keyword;
  851. this.beforeExpr = !!conf.beforeExpr;
  852. this.startsExpr = !!conf.startsExpr;
  853. this.rightAssociative = !!conf.rightAssociative;
  854. this.isLoop = !!conf.isLoop;
  855. this.isAssign = !!conf.isAssign;
  856. this.prefix = !!conf.prefix;
  857. this.postfix = !!conf.postfix;
  858. this.binop = conf.binop != null ? conf.binop : null;
  859. {
  860. this.updateContext = null;
  861. }
  862. }
  863. }
  864. const keywords$1 = new Map();
  865. function createKeyword(name, options = {}) {
  866. options.keyword = name;
  867. const token = createToken(name, options);
  868. keywords$1.set(name, token);
  869. return token;
  870. }
  871. function createBinop(name, binop) {
  872. return createToken(name, {
  873. beforeExpr,
  874. binop
  875. });
  876. }
  877. let tokenTypeCounter = -1;
  878. const tokenTypes = [];
  879. const tokenLabels = [];
  880. const tokenBinops = [];
  881. const tokenBeforeExprs = [];
  882. const tokenStartsExprs = [];
  883. const tokenPrefixes = [];
  884. function createToken(name, options = {}) {
  885. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  886. ++tokenTypeCounter;
  887. tokenLabels.push(name);
  888. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  889. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  890. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  891. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  892. tokenTypes.push(new ExportedTokenType(name, options));
  893. return tokenTypeCounter;
  894. }
  895. function createKeywordLike(name, options = {}) {
  896. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  897. ++tokenTypeCounter;
  898. keywords$1.set(name, tokenTypeCounter);
  899. tokenLabels.push(name);
  900. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  901. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  902. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  903. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  904. tokenTypes.push(new ExportedTokenType("name", options));
  905. return tokenTypeCounter;
  906. }
  907. const tt = {
  908. bracketL: createToken("[", {
  909. beforeExpr,
  910. startsExpr
  911. }),
  912. bracketHashL: createToken("#[", {
  913. beforeExpr,
  914. startsExpr
  915. }),
  916. bracketBarL: createToken("[|", {
  917. beforeExpr,
  918. startsExpr
  919. }),
  920. bracketR: createToken("]"),
  921. bracketBarR: createToken("|]"),
  922. braceL: createToken("{", {
  923. beforeExpr,
  924. startsExpr
  925. }),
  926. braceBarL: createToken("{|", {
  927. beforeExpr,
  928. startsExpr
  929. }),
  930. braceHashL: createToken("#{", {
  931. beforeExpr,
  932. startsExpr
  933. }),
  934. braceR: createToken("}"),
  935. braceBarR: createToken("|}"),
  936. parenL: createToken("(", {
  937. beforeExpr,
  938. startsExpr
  939. }),
  940. parenR: createToken(")"),
  941. comma: createToken(",", {
  942. beforeExpr
  943. }),
  944. semi: createToken(";", {
  945. beforeExpr
  946. }),
  947. colon: createToken(":", {
  948. beforeExpr
  949. }),
  950. doubleColon: createToken("::", {
  951. beforeExpr
  952. }),
  953. dot: createToken("."),
  954. question: createToken("?", {
  955. beforeExpr
  956. }),
  957. questionDot: createToken("?."),
  958. arrow: createToken("=>", {
  959. beforeExpr
  960. }),
  961. template: createToken("template"),
  962. ellipsis: createToken("...", {
  963. beforeExpr
  964. }),
  965. backQuote: createToken("`", {
  966. startsExpr
  967. }),
  968. dollarBraceL: createToken("${", {
  969. beforeExpr,
  970. startsExpr
  971. }),
  972. templateTail: createToken("...`", {
  973. startsExpr
  974. }),
  975. templateNonTail: createToken("...${", {
  976. beforeExpr,
  977. startsExpr
  978. }),
  979. at: createToken("@"),
  980. hash: createToken("#", {
  981. startsExpr
  982. }),
  983. interpreterDirective: createToken("#!..."),
  984. eq: createToken("=", {
  985. beforeExpr,
  986. isAssign
  987. }),
  988. assign: createToken("_=", {
  989. beforeExpr,
  990. isAssign
  991. }),
  992. slashAssign: createToken("_=", {
  993. beforeExpr,
  994. isAssign
  995. }),
  996. xorAssign: createToken("_=", {
  997. beforeExpr,
  998. isAssign
  999. }),
  1000. moduloAssign: createToken("_=", {
  1001. beforeExpr,
  1002. isAssign
  1003. }),
  1004. incDec: createToken("++/--", {
  1005. prefix,
  1006. postfix,
  1007. startsExpr
  1008. }),
  1009. bang: createToken("!", {
  1010. beforeExpr,
  1011. prefix,
  1012. startsExpr
  1013. }),
  1014. tilde: createToken("~", {
  1015. beforeExpr,
  1016. prefix,
  1017. startsExpr
  1018. }),
  1019. doubleCaret: createToken("^^", {
  1020. startsExpr
  1021. }),
  1022. doubleAt: createToken("@@", {
  1023. startsExpr
  1024. }),
  1025. pipeline: createBinop("|>", 0),
  1026. nullishCoalescing: createBinop("??", 1),
  1027. logicalOR: createBinop("||", 1),
  1028. logicalAND: createBinop("&&", 2),
  1029. bitwiseOR: createBinop("|", 3),
  1030. bitwiseXOR: createBinop("^", 4),
  1031. bitwiseAND: createBinop("&", 5),
  1032. equality: createBinop("==/!=/===/!==", 6),
  1033. lt: createBinop("</>/<=/>=", 7),
  1034. gt: createBinop("</>/<=/>=", 7),
  1035. relational: createBinop("</>/<=/>=", 7),
  1036. bitShift: createBinop("<</>>/>>>", 8),
  1037. bitShiftL: createBinop("<</>>/>>>", 8),
  1038. bitShiftR: createBinop("<</>>/>>>", 8),
  1039. plusMin: createToken("+/-", {
  1040. beforeExpr,
  1041. binop: 9,
  1042. prefix,
  1043. startsExpr
  1044. }),
  1045. modulo: createToken("%", {
  1046. binop: 10,
  1047. startsExpr
  1048. }),
  1049. star: createToken("*", {
  1050. binop: 10
  1051. }),
  1052. slash: createBinop("/", 10),
  1053. exponent: createToken("**", {
  1054. beforeExpr,
  1055. binop: 11,
  1056. rightAssociative: true
  1057. }),
  1058. _in: createKeyword("in", {
  1059. beforeExpr,
  1060. binop: 7
  1061. }),
  1062. _instanceof: createKeyword("instanceof", {
  1063. beforeExpr,
  1064. binop: 7
  1065. }),
  1066. _break: createKeyword("break"),
  1067. _case: createKeyword("case", {
  1068. beforeExpr
  1069. }),
  1070. _catch: createKeyword("catch"),
  1071. _continue: createKeyword("continue"),
  1072. _debugger: createKeyword("debugger"),
  1073. _default: createKeyword("default", {
  1074. beforeExpr
  1075. }),
  1076. _else: createKeyword("else", {
  1077. beforeExpr
  1078. }),
  1079. _finally: createKeyword("finally"),
  1080. _function: createKeyword("function", {
  1081. startsExpr
  1082. }),
  1083. _if: createKeyword("if"),
  1084. _return: createKeyword("return", {
  1085. beforeExpr
  1086. }),
  1087. _switch: createKeyword("switch"),
  1088. _throw: createKeyword("throw", {
  1089. beforeExpr,
  1090. prefix,
  1091. startsExpr
  1092. }),
  1093. _try: createKeyword("try"),
  1094. _var: createKeyword("var"),
  1095. _const: createKeyword("const"),
  1096. _with: createKeyword("with"),
  1097. _new: createKeyword("new", {
  1098. beforeExpr,
  1099. startsExpr
  1100. }),
  1101. _this: createKeyword("this", {
  1102. startsExpr
  1103. }),
  1104. _super: createKeyword("super", {
  1105. startsExpr
  1106. }),
  1107. _class: createKeyword("class", {
  1108. startsExpr
  1109. }),
  1110. _extends: createKeyword("extends", {
  1111. beforeExpr
  1112. }),
  1113. _export: createKeyword("export"),
  1114. _import: createKeyword("import", {
  1115. startsExpr
  1116. }),
  1117. _null: createKeyword("null", {
  1118. startsExpr
  1119. }),
  1120. _true: createKeyword("true", {
  1121. startsExpr
  1122. }),
  1123. _false: createKeyword("false", {
  1124. startsExpr
  1125. }),
  1126. _typeof: createKeyword("typeof", {
  1127. beforeExpr,
  1128. prefix,
  1129. startsExpr
  1130. }),
  1131. _void: createKeyword("void", {
  1132. beforeExpr,
  1133. prefix,
  1134. startsExpr
  1135. }),
  1136. _delete: createKeyword("delete", {
  1137. beforeExpr,
  1138. prefix,
  1139. startsExpr
  1140. }),
  1141. _do: createKeyword("do", {
  1142. isLoop,
  1143. beforeExpr
  1144. }),
  1145. _for: createKeyword("for", {
  1146. isLoop
  1147. }),
  1148. _while: createKeyword("while", {
  1149. isLoop
  1150. }),
  1151. _as: createKeywordLike("as", {
  1152. startsExpr
  1153. }),
  1154. _assert: createKeywordLike("assert", {
  1155. startsExpr
  1156. }),
  1157. _async: createKeywordLike("async", {
  1158. startsExpr
  1159. }),
  1160. _await: createKeywordLike("await", {
  1161. startsExpr
  1162. }),
  1163. _defer: createKeywordLike("defer", {
  1164. startsExpr
  1165. }),
  1166. _from: createKeywordLike("from", {
  1167. startsExpr
  1168. }),
  1169. _get: createKeywordLike("get", {
  1170. startsExpr
  1171. }),
  1172. _let: createKeywordLike("let", {
  1173. startsExpr
  1174. }),
  1175. _meta: createKeywordLike("meta", {
  1176. startsExpr
  1177. }),
  1178. _of: createKeywordLike("of", {
  1179. startsExpr
  1180. }),
  1181. _sent: createKeywordLike("sent", {
  1182. startsExpr
  1183. }),
  1184. _set: createKeywordLike("set", {
  1185. startsExpr
  1186. }),
  1187. _source: createKeywordLike("source", {
  1188. startsExpr
  1189. }),
  1190. _static: createKeywordLike("static", {
  1191. startsExpr
  1192. }),
  1193. _using: createKeywordLike("using", {
  1194. startsExpr
  1195. }),
  1196. _yield: createKeywordLike("yield", {
  1197. startsExpr
  1198. }),
  1199. _asserts: createKeywordLike("asserts", {
  1200. startsExpr
  1201. }),
  1202. _checks: createKeywordLike("checks", {
  1203. startsExpr
  1204. }),
  1205. _exports: createKeywordLike("exports", {
  1206. startsExpr
  1207. }),
  1208. _global: createKeywordLike("global", {
  1209. startsExpr
  1210. }),
  1211. _implements: createKeywordLike("implements", {
  1212. startsExpr
  1213. }),
  1214. _intrinsic: createKeywordLike("intrinsic", {
  1215. startsExpr
  1216. }),
  1217. _infer: createKeywordLike("infer", {
  1218. startsExpr
  1219. }),
  1220. _is: createKeywordLike("is", {
  1221. startsExpr
  1222. }),
  1223. _mixins: createKeywordLike("mixins", {
  1224. startsExpr
  1225. }),
  1226. _proto: createKeywordLike("proto", {
  1227. startsExpr
  1228. }),
  1229. _require: createKeywordLike("require", {
  1230. startsExpr
  1231. }),
  1232. _satisfies: createKeywordLike("satisfies", {
  1233. startsExpr
  1234. }),
  1235. _keyof: createKeywordLike("keyof", {
  1236. startsExpr
  1237. }),
  1238. _readonly: createKeywordLike("readonly", {
  1239. startsExpr
  1240. }),
  1241. _unique: createKeywordLike("unique", {
  1242. startsExpr
  1243. }),
  1244. _abstract: createKeywordLike("abstract", {
  1245. startsExpr
  1246. }),
  1247. _declare: createKeywordLike("declare", {
  1248. startsExpr
  1249. }),
  1250. _enum: createKeywordLike("enum", {
  1251. startsExpr
  1252. }),
  1253. _module: createKeywordLike("module", {
  1254. startsExpr
  1255. }),
  1256. _namespace: createKeywordLike("namespace", {
  1257. startsExpr
  1258. }),
  1259. _interface: createKeywordLike("interface", {
  1260. startsExpr
  1261. }),
  1262. _type: createKeywordLike("type", {
  1263. startsExpr
  1264. }),
  1265. _opaque: createKeywordLike("opaque", {
  1266. startsExpr
  1267. }),
  1268. name: createToken("name", {
  1269. startsExpr
  1270. }),
  1271. placeholder: createToken("%%", {
  1272. startsExpr: true
  1273. }),
  1274. string: createToken("string", {
  1275. startsExpr
  1276. }),
  1277. num: createToken("num", {
  1278. startsExpr
  1279. }),
  1280. bigint: createToken("bigint", {
  1281. startsExpr
  1282. }),
  1283. decimal: createToken("decimal", {
  1284. startsExpr
  1285. }),
  1286. regexp: createToken("regexp", {
  1287. startsExpr
  1288. }),
  1289. privateName: createToken("#name", {
  1290. startsExpr
  1291. }),
  1292. eof: createToken("eof"),
  1293. jsxName: createToken("jsxName"),
  1294. jsxText: createToken("jsxText", {
  1295. beforeExpr: true
  1296. }),
  1297. jsxTagStart: createToken("jsxTagStart", {
  1298. startsExpr: true
  1299. }),
  1300. jsxTagEnd: createToken("jsxTagEnd")
  1301. };
  1302. function tokenIsIdentifier(token) {
  1303. return token >= 93 && token <= 133;
  1304. }
  1305. function tokenKeywordOrIdentifierIsKeyword(token) {
  1306. return token <= 92;
  1307. }
  1308. function tokenIsKeywordOrIdentifier(token) {
  1309. return token >= 58 && token <= 133;
  1310. }
  1311. function tokenIsLiteralPropertyName(token) {
  1312. return token >= 58 && token <= 137;
  1313. }
  1314. function tokenComesBeforeExpression(token) {
  1315. return tokenBeforeExprs[token];
  1316. }
  1317. function tokenCanStartExpression(token) {
  1318. return tokenStartsExprs[token];
  1319. }
  1320. function tokenIsAssignment(token) {
  1321. return token >= 29 && token <= 33;
  1322. }
  1323. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  1324. return token >= 129 && token <= 131;
  1325. }
  1326. function tokenIsLoop(token) {
  1327. return token >= 90 && token <= 92;
  1328. }
  1329. function tokenIsKeyword(token) {
  1330. return token >= 58 && token <= 92;
  1331. }
  1332. function tokenIsOperator(token) {
  1333. return token >= 39 && token <= 59;
  1334. }
  1335. function tokenIsPostfix(token) {
  1336. return token === 34;
  1337. }
  1338. function tokenIsPrefix(token) {
  1339. return tokenPrefixes[token];
  1340. }
  1341. function tokenIsTSTypeOperator(token) {
  1342. return token >= 121 && token <= 123;
  1343. }
  1344. function tokenIsTSDeclarationStart(token) {
  1345. return token >= 124 && token <= 130;
  1346. }
  1347. function tokenLabelName(token) {
  1348. return tokenLabels[token];
  1349. }
  1350. function tokenOperatorPrecedence(token) {
  1351. return tokenBinops[token];
  1352. }
  1353. function tokenIsRightAssociative(token) {
  1354. return token === 57;
  1355. }
  1356. function tokenIsTemplate(token) {
  1357. return token >= 24 && token <= 25;
  1358. }
  1359. function getExportedToken(token) {
  1360. return tokenTypes[token];
  1361. }
  1362. {
  1363. tokenTypes[8].updateContext = context => {
  1364. context.pop();
  1365. };
  1366. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  1367. context.push(types.brace);
  1368. };
  1369. tokenTypes[22].updateContext = context => {
  1370. if (context[context.length - 1] === types.template) {
  1371. context.pop();
  1372. } else {
  1373. context.push(types.template);
  1374. }
  1375. };
  1376. tokenTypes[143].updateContext = context => {
  1377. context.push(types.j_expr, types.j_oTag);
  1378. };
  1379. }
  1380. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\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-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\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\uf
  1381. let nonASCIIidentifierChars = "\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\u0897-\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\u0cf3\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-\u0ece\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\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\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\uff65";
  1382. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1383. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1384. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1385. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 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, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 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, 20, 1, 64, 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, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 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, 200, 32, 32, 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, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 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, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 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, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
  1386. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 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, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 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, 343, 9, 54, 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, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 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, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  1387. function isInAstralSet(code, set) {
  1388. let pos = 0x10000;
  1389. for (let i = 0, length = set.length; i < length; i += 2) {
  1390. pos += set[i];
  1391. if (pos > code) return false;
  1392. pos += set[i + 1];
  1393. if (pos >= code) return true;
  1394. }
  1395. return false;
  1396. }
  1397. function isIdentifierStart(code) {
  1398. if (code < 65) return code === 36;
  1399. if (code <= 90) return true;
  1400. if (code < 97) return code === 95;
  1401. if (code <= 122) return true;
  1402. if (code <= 0xffff) {
  1403. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1404. }
  1405. return isInAstralSet(code, astralIdentifierStartCodes);
  1406. }
  1407. function isIdentifierChar(code) {
  1408. if (code < 48) return code === 36;
  1409. if (code < 58) return true;
  1410. if (code < 65) return false;
  1411. if (code <= 90) return true;
  1412. if (code < 97) return code === 95;
  1413. if (code <= 122) return true;
  1414. if (code <= 0xffff) {
  1415. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1416. }
  1417. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1418. }
  1419. const reservedWords = {
  1420. 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"],
  1421. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1422. strictBind: ["eval", "arguments"]
  1423. };
  1424. const keywords = new Set(reservedWords.keyword);
  1425. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1426. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1427. function isReservedWord(word, inModule) {
  1428. return inModule && word === "await" || word === "enum";
  1429. }
  1430. function isStrictReservedWord(word, inModule) {
  1431. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1432. }
  1433. function isStrictBindOnlyReservedWord(word) {
  1434. return reservedWordsStrictBindSet.has(word);
  1435. }
  1436. function isStrictBindReservedWord(word, inModule) {
  1437. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1438. }
  1439. function isKeyword(word) {
  1440. return keywords.has(word);
  1441. }
  1442. function isIteratorStart(current, next, next2) {
  1443. return current === 64 && next === 64 && isIdentifierStart(next2);
  1444. }
  1445. 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"]);
  1446. function canBeReservedWord(word) {
  1447. return reservedWordLikeSet.has(word);
  1448. }
  1449. class Scope {
  1450. constructor(flags) {
  1451. this.flags = 0;
  1452. this.names = new Map();
  1453. this.firstLexicalName = "";
  1454. this.flags = flags;
  1455. }
  1456. }
  1457. class ScopeHandler {
  1458. constructor(parser, inModule) {
  1459. this.parser = void 0;
  1460. this.scopeStack = [];
  1461. this.inModule = void 0;
  1462. this.undefinedExports = new Map();
  1463. this.parser = parser;
  1464. this.inModule = inModule;
  1465. }
  1466. get inTopLevel() {
  1467. return (this.currentScope().flags & 1) > 0;
  1468. }
  1469. get inFunction() {
  1470. return (this.currentVarScopeFlags() & 2) > 0;
  1471. }
  1472. get allowSuper() {
  1473. return (this.currentThisScopeFlags() & 16) > 0;
  1474. }
  1475. get allowDirectSuper() {
  1476. return (this.currentThisScopeFlags() & 32) > 0;
  1477. }
  1478. get inClass() {
  1479. return (this.currentThisScopeFlags() & 64) > 0;
  1480. }
  1481. get inClassAndNotInNonArrowFunction() {
  1482. const flags = this.currentThisScopeFlags();
  1483. return (flags & 64) > 0 && (flags & 2) === 0;
  1484. }
  1485. get inStaticBlock() {
  1486. for (let i = this.scopeStack.length - 1;; i--) {
  1487. const {
  1488. flags
  1489. } = this.scopeStack[i];
  1490. if (flags & 128) {
  1491. return true;
  1492. }
  1493. if (flags & (387 | 64)) {
  1494. return false;
  1495. }
  1496. }
  1497. }
  1498. get inNonArrowFunction() {
  1499. return (this.currentThisScopeFlags() & 2) > 0;
  1500. }
  1501. get treatFunctionsAsVar() {
  1502. return this.treatFunctionsAsVarInScope(this.currentScope());
  1503. }
  1504. createScope(flags) {
  1505. return new Scope(flags);
  1506. }
  1507. enter(flags) {
  1508. this.scopeStack.push(this.createScope(flags));
  1509. }
  1510. exit() {
  1511. const scope = this.scopeStack.pop();
  1512. return scope.flags;
  1513. }
  1514. treatFunctionsAsVarInScope(scope) {
  1515. return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1);
  1516. }
  1517. declareName(name, bindingType, loc) {
  1518. let scope = this.currentScope();
  1519. if (bindingType & 8 || bindingType & 16) {
  1520. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1521. let type = scope.names.get(name) || 0;
  1522. if (bindingType & 16) {
  1523. type = type | 4;
  1524. } else {
  1525. if (!scope.firstLexicalName) {
  1526. scope.firstLexicalName = name;
  1527. }
  1528. type = type | 2;
  1529. }
  1530. scope.names.set(name, type);
  1531. if (bindingType & 8) {
  1532. this.maybeExportDefined(scope, name);
  1533. }
  1534. } else if (bindingType & 4) {
  1535. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  1536. scope = this.scopeStack[i];
  1537. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1538. scope.names.set(name, (scope.names.get(name) || 0) | 1);
  1539. this.maybeExportDefined(scope, name);
  1540. if (scope.flags & 387) break;
  1541. }
  1542. }
  1543. if (this.parser.inModule && scope.flags & 1) {
  1544. this.undefinedExports.delete(name);
  1545. }
  1546. }
  1547. maybeExportDefined(scope, name) {
  1548. if (this.parser.inModule && scope.flags & 1) {
  1549. this.undefinedExports.delete(name);
  1550. }
  1551. }
  1552. checkRedeclarationInScope(scope, name, bindingType, loc) {
  1553. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  1554. this.parser.raise(Errors.VarRedeclaration, loc, {
  1555. identifierName: name
  1556. });
  1557. }
  1558. }
  1559. isRedeclaredInScope(scope, name, bindingType) {
  1560. if (!(bindingType & 1)) return false;
  1561. if (bindingType & 8) {
  1562. return scope.names.has(name);
  1563. }
  1564. const type = scope.names.get(name);
  1565. if (bindingType & 16) {
  1566. return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0;
  1567. }
  1568. return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0;
  1569. }
  1570. checkLocalExport(id) {
  1571. const {
  1572. name
  1573. } = id;
  1574. const topLevelScope = this.scopeStack[0];
  1575. if (!topLevelScope.names.has(name)) {
  1576. this.undefinedExports.set(name, id.loc.start);
  1577. }
  1578. }
  1579. currentScope() {
  1580. return this.scopeStack[this.scopeStack.length - 1];
  1581. }
  1582. currentVarScopeFlags() {
  1583. for (let i = this.scopeStack.length - 1;; i--) {
  1584. const {
  1585. flags
  1586. } = this.scopeStack[i];
  1587. if (flags & 387) {
  1588. return flags;
  1589. }
  1590. }
  1591. }
  1592. currentThisScopeFlags() {
  1593. for (let i = this.scopeStack.length - 1;; i--) {
  1594. const {
  1595. flags
  1596. } = this.scopeStack[i];
  1597. if (flags & (387 | 64) && !(flags & 4)) {
  1598. return flags;
  1599. }
  1600. }
  1601. }
  1602. }
  1603. class FlowScope extends Scope {
  1604. constructor(...args) {
  1605. super(...args);
  1606. this.declareFunctions = new Set();
  1607. }
  1608. }
  1609. class FlowScopeHandler extends ScopeHandler {
  1610. createScope(flags) {
  1611. return new FlowScope(flags);
  1612. }
  1613. declareName(name, bindingType, loc) {
  1614. const scope = this.currentScope();
  1615. if (bindingType & 2048) {
  1616. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1617. this.maybeExportDefined(scope, name);
  1618. scope.declareFunctions.add(name);
  1619. return;
  1620. }
  1621. super.declareName(name, bindingType, loc);
  1622. }
  1623. isRedeclaredInScope(scope, name, bindingType) {
  1624. if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
  1625. if (bindingType & 2048 && !scope.declareFunctions.has(name)) {
  1626. const type = scope.names.get(name);
  1627. return (type & 4) > 0 || (type & 2) > 0;
  1628. }
  1629. return false;
  1630. }
  1631. checkLocalExport(id) {
  1632. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  1633. super.checkLocalExport(id);
  1634. }
  1635. }
  1636. }
  1637. class BaseParser {
  1638. constructor() {
  1639. this.sawUnambiguousESM = false;
  1640. this.ambiguousScriptDifferentAst = false;
  1641. }
  1642. sourceToOffsetPos(sourcePos) {
  1643. return sourcePos + this.startIndex;
  1644. }
  1645. offsetToSourcePos(offsetPos) {
  1646. return offsetPos - this.startIndex;
  1647. }
  1648. hasPlugin(pluginConfig) {
  1649. if (typeof pluginConfig === "string") {
  1650. return this.plugins.has(pluginConfig);
  1651. } else {
  1652. const [pluginName, pluginOptions] = pluginConfig;
  1653. if (!this.hasPlugin(pluginName)) {
  1654. return false;
  1655. }
  1656. const actualOptions = this.plugins.get(pluginName);
  1657. for (const key of Object.keys(pluginOptions)) {
  1658. if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) {
  1659. return false;
  1660. }
  1661. }
  1662. return true;
  1663. }
  1664. }
  1665. getPluginOption(plugin, name) {
  1666. var _this$plugins$get;
  1667. return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name];
  1668. }
  1669. }
  1670. function setTrailingComments(node, comments) {
  1671. if (node.trailingComments === undefined) {
  1672. node.trailingComments = comments;
  1673. } else {
  1674. node.trailingComments.unshift(...comments);
  1675. }
  1676. }
  1677. function setLeadingComments(node, comments) {
  1678. if (node.leadingComments === undefined) {
  1679. node.leadingComments = comments;
  1680. } else {
  1681. node.leadingComments.unshift(...comments);
  1682. }
  1683. }
  1684. function setInnerComments(node, comments) {
  1685. if (node.innerComments === undefined) {
  1686. node.innerComments = comments;
  1687. } else {
  1688. node.innerComments.unshift(...comments);
  1689. }
  1690. }
  1691. function adjustInnerComments(node, elements, commentWS) {
  1692. let lastElement = null;
  1693. let i = elements.length;
  1694. while (lastElement === null && i > 0) {
  1695. lastElement = elements[--i];
  1696. }
  1697. if (lastElement === null || lastElement.start > commentWS.start) {
  1698. setInnerComments(node, commentWS.comments);
  1699. } else {
  1700. setTrailingComments(lastElement, commentWS.comments);
  1701. }
  1702. }
  1703. class CommentsParser extends BaseParser {
  1704. addComment(comment) {
  1705. if (this.filename) comment.loc.filename = this.filename;
  1706. const {
  1707. commentsLen
  1708. } = this.state;
  1709. if (this.comments.length !== commentsLen) {
  1710. this.comments.length = commentsLen;
  1711. }
  1712. this.comments.push(comment);
  1713. this.state.commentsLen++;
  1714. }
  1715. processComment(node) {
  1716. const {
  1717. commentStack
  1718. } = this.state;
  1719. const commentStackLength = commentStack.length;
  1720. if (commentStackLength === 0) return;
  1721. let i = commentStackLength - 1;
  1722. const lastCommentWS = commentStack[i];
  1723. if (lastCommentWS.start === node.end) {
  1724. lastCommentWS.leadingNode = node;
  1725. i--;
  1726. }
  1727. const {
  1728. start: nodeStart
  1729. } = node;
  1730. for (; i >= 0; i--) {
  1731. const commentWS = commentStack[i];
  1732. const commentEnd = commentWS.end;
  1733. if (commentEnd > nodeStart) {
  1734. commentWS.containingNode = node;
  1735. this.finalizeComment(commentWS);
  1736. commentStack.splice(i, 1);
  1737. } else {
  1738. if (commentEnd === nodeStart) {
  1739. commentWS.trailingNode = node;
  1740. }
  1741. break;
  1742. }
  1743. }
  1744. }
  1745. finalizeComment(commentWS) {
  1746. const {
  1747. comments
  1748. } = commentWS;
  1749. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  1750. if (commentWS.leadingNode !== null) {
  1751. setTrailingComments(commentWS.leadingNode, comments);
  1752. }
  1753. if (commentWS.trailingNode !== null) {
  1754. setLeadingComments(commentWS.trailingNode, comments);
  1755. }
  1756. } else {
  1757. const {
  1758. containingNode: node,
  1759. start: commentStart
  1760. } = commentWS;
  1761. if (this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) === 44) {
  1762. switch (node.type) {
  1763. case "ObjectExpression":
  1764. case "ObjectPattern":
  1765. case "RecordExpression":
  1766. adjustInnerComments(node, node.properties, commentWS);
  1767. break;
  1768. case "CallExpression":
  1769. case "OptionalCallExpression":
  1770. adjustInnerComments(node, node.arguments, commentWS);
  1771. break;
  1772. case "FunctionDeclaration":
  1773. case "FunctionExpression":
  1774. case "ArrowFunctionExpression":
  1775. case "ObjectMethod":
  1776. case "ClassMethod":
  1777. case "ClassPrivateMethod":
  1778. adjustInnerComments(node, node.params, commentWS);
  1779. break;
  1780. case "ArrayExpression":
  1781. case "ArrayPattern":
  1782. case "TupleExpression":
  1783. adjustInnerComments(node, node.elements, commentWS);
  1784. break;
  1785. case "ExportNamedDeclaration":
  1786. case "ImportDeclaration":
  1787. adjustInnerComments(node, node.specifiers, commentWS);
  1788. break;
  1789. case "TSEnumDeclaration":
  1790. {
  1791. adjustInnerComments(node, node.members, commentWS);
  1792. }
  1793. break;
  1794. case "TSEnumBody":
  1795. adjustInnerComments(node, node.members, commentWS);
  1796. break;
  1797. default:
  1798. {
  1799. setInnerComments(node, comments);
  1800. }
  1801. }
  1802. } else {
  1803. setInnerComments(node, comments);
  1804. }
  1805. }
  1806. }
  1807. finalizeRemainingComments() {
  1808. const {
  1809. commentStack
  1810. } = this.state;
  1811. for (let i = commentStack.length - 1; i >= 0; i--) {
  1812. this.finalizeComment(commentStack[i]);
  1813. }
  1814. this.state.commentStack = [];
  1815. }
  1816. resetPreviousNodeTrailingComments(node) {
  1817. const {
  1818. commentStack
  1819. } = this.state;
  1820. const {
  1821. length
  1822. } = commentStack;
  1823. if (length === 0) return;
  1824. const commentWS = commentStack[length - 1];
  1825. if (commentWS.leadingNode === node) {
  1826. commentWS.leadingNode = null;
  1827. }
  1828. }
  1829. resetPreviousIdentifierLeadingComments(node) {
  1830. const {
  1831. commentStack
  1832. } = this.state;
  1833. const {
  1834. length
  1835. } = commentStack;
  1836. if (length === 0) return;
  1837. if (commentStack[length - 1].trailingNode === node) {
  1838. commentStack[length - 1].trailingNode = null;
  1839. } else if (length >= 2 && commentStack[length - 2].trailingNode === node) {
  1840. commentStack[length - 2].trailingNode = null;
  1841. }
  1842. }
  1843. takeSurroundingComments(node, start, end) {
  1844. const {
  1845. commentStack
  1846. } = this.state;
  1847. const commentStackLength = commentStack.length;
  1848. if (commentStackLength === 0) return;
  1849. let i = commentStackLength - 1;
  1850. for (; i >= 0; i--) {
  1851. const commentWS = commentStack[i];
  1852. const commentEnd = commentWS.end;
  1853. const commentStart = commentWS.start;
  1854. if (commentStart === end) {
  1855. commentWS.leadingNode = node;
  1856. } else if (commentEnd === start) {
  1857. commentWS.trailingNode = node;
  1858. } else if (commentEnd < start) {
  1859. break;
  1860. }
  1861. }
  1862. }
  1863. }
  1864. const lineBreak = /\r\n|[\r\n\u2028\u2029]/;
  1865. const lineBreakG = new RegExp(lineBreak.source, "g");
  1866. function isNewLine(code) {
  1867. switch (code) {
  1868. case 10:
  1869. case 13:
  1870. case 8232:
  1871. case 8233:
  1872. return true;
  1873. default:
  1874. return false;
  1875. }
  1876. }
  1877. function hasNewLine(input, start, end) {
  1878. for (let i = start; i < end; i++) {
  1879. if (isNewLine(input.charCodeAt(i))) {
  1880. return true;
  1881. }
  1882. }
  1883. return false;
  1884. }
  1885. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  1886. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;
  1887. function isWhitespace(code) {
  1888. switch (code) {
  1889. case 0x0009:
  1890. case 0x000b:
  1891. case 0x000c:
  1892. case 32:
  1893. case 160:
  1894. case 5760:
  1895. case 0x2000:
  1896. case 0x2001:
  1897. case 0x2002:
  1898. case 0x2003:
  1899. case 0x2004:
  1900. case 0x2005:
  1901. case 0x2006:
  1902. case 0x2007:
  1903. case 0x2008:
  1904. case 0x2009:
  1905. case 0x200a:
  1906. case 0x202f:
  1907. case 0x205f:
  1908. case 0x3000:
  1909. case 0xfeff:
  1910. return true;
  1911. default:
  1912. return false;
  1913. }
  1914. }
  1915. class State {
  1916. constructor() {
  1917. this.flags = 1024;
  1918. this.startIndex = void 0;
  1919. this.curLine = void 0;
  1920. this.lineStart = void 0;
  1921. this.startLoc = void 0;
  1922. this.endLoc = void 0;
  1923. this.errors = [];
  1924. this.potentialArrowAt = -1;
  1925. this.noArrowAt = [];
  1926. this.noArrowParamsConversionAt = [];
  1927. this.topicContext = {
  1928. maxNumOfResolvableTopics: 0,
  1929. maxTopicIndex: null
  1930. };
  1931. this.labels = [];
  1932. this.commentsLen = 0;
  1933. this.commentStack = [];
  1934. this.pos = 0;
  1935. this.type = 140;
  1936. this.value = null;
  1937. this.start = 0;
  1938. this.end = 0;
  1939. this.lastTokEndLoc = null;
  1940. this.lastTokStartLoc = null;
  1941. this.context = [types.brace];
  1942. this.firstInvalidTemplateEscapePos = null;
  1943. this.strictErrors = new Map();
  1944. this.tokensLength = 0;
  1945. }
  1946. get strict() {
  1947. return (this.flags & 1) > 0;
  1948. }
  1949. set strict(v) {
  1950. if (v) this.flags |= 1;else this.flags &= -2;
  1951. }
  1952. init({
  1953. strictMode,
  1954. sourceType,
  1955. startIndex,
  1956. startLine,
  1957. startColumn
  1958. }) {
  1959. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  1960. this.startIndex = startIndex;
  1961. this.curLine = startLine;
  1962. this.lineStart = -startColumn;
  1963. this.startLoc = this.endLoc = new Position(startLine, startColumn, startIndex);
  1964. }
  1965. get maybeInArrowParameters() {
  1966. return (this.flags & 2) > 0;
  1967. }
  1968. set maybeInArrowParameters(v) {
  1969. if (v) this.flags |= 2;else this.flags &= -3;
  1970. }
  1971. get inType() {
  1972. return (this.flags & 4) > 0;
  1973. }
  1974. set inType(v) {
  1975. if (v) this.flags |= 4;else this.flags &= -5;
  1976. }
  1977. get noAnonFunctionType() {
  1978. return (this.flags & 8) > 0;
  1979. }
  1980. set noAnonFunctionType(v) {
  1981. if (v) this.flags |= 8;else this.flags &= -9;
  1982. }
  1983. get hasFlowComment() {
  1984. return (this.flags & 16) > 0;
  1985. }
  1986. set hasFlowComment(v) {
  1987. if (v) this.flags |= 16;else this.flags &= -17;
  1988. }
  1989. get isAmbientContext() {
  1990. return (this.flags & 32) > 0;
  1991. }
  1992. set isAmbientContext(v) {
  1993. if (v) this.flags |= 32;else this.flags &= -33;
  1994. }
  1995. get inAbstractClass() {
  1996. return (this.flags & 64) > 0;
  1997. }
  1998. set inAbstractClass(v) {
  1999. if (v) this.flags |= 64;else this.flags &= -65;
  2000. }
  2001. get inDisallowConditionalTypesContext() {
  2002. return (this.flags & 128) > 0;
  2003. }
  2004. set inDisallowConditionalTypesContext(v) {
  2005. if (v) this.flags |= 128;else this.flags &= -129;
  2006. }
  2007. get soloAwait() {
  2008. return (this.flags & 256) > 0;
  2009. }
  2010. set soloAwait(v) {
  2011. if (v) this.flags |= 256;else this.flags &= -257;
  2012. }
  2013. get inFSharpPipelineDirectBody() {
  2014. return (this.flags & 512) > 0;
  2015. }
  2016. set inFSharpPipelineDirectBody(v) {
  2017. if (v) this.flags |= 512;else this.flags &= -513;
  2018. }
  2019. get canStartJSXElement() {
  2020. return (this.flags & 1024) > 0;
  2021. }
  2022. set canStartJSXElement(v) {
  2023. if (v) this.flags |= 1024;else this.flags &= -1025;
  2024. }
  2025. get containsEsc() {
  2026. return (this.flags & 2048) > 0;
  2027. }
  2028. set containsEsc(v) {
  2029. if (v) this.flags |= 2048;else this.flags &= -2049;
  2030. }
  2031. get hasTopLevelAwait() {
  2032. return (this.flags & 4096) > 0;
  2033. }
  2034. set hasTopLevelAwait(v) {
  2035. if (v) this.flags |= 4096;else this.flags &= -4097;
  2036. }
  2037. curPosition() {
  2038. return new Position(this.curLine, this.pos - this.lineStart, this.pos + this.startIndex);
  2039. }
  2040. clone() {
  2041. const state = new State();
  2042. state.flags = this.flags;
  2043. state.startIndex = this.startIndex;
  2044. state.curLine = this.curLine;
  2045. state.lineStart = this.lineStart;
  2046. state.startLoc = this.startLoc;
  2047. state.endLoc = this.endLoc;
  2048. state.errors = this.errors.slice();
  2049. state.potentialArrowAt = this.potentialArrowAt;
  2050. state.noArrowAt = this.noArrowAt.slice();
  2051. state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();
  2052. state.topicContext = this.topicContext;
  2053. state.labels = this.labels.slice();
  2054. state.commentsLen = this.commentsLen;
  2055. state.commentStack = this.commentStack.slice();
  2056. state.pos = this.pos;
  2057. state.type = this.type;
  2058. state.value = this.value;
  2059. state.start = this.start;
  2060. state.end = this.end;
  2061. state.lastTokEndLoc = this.lastTokEndLoc;
  2062. state.lastTokStartLoc = this.lastTokStartLoc;
  2063. state.context = this.context.slice();
  2064. state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;
  2065. state.strictErrors = this.strictErrors;
  2066. state.tokensLength = this.tokensLength;
  2067. return state;
  2068. }
  2069. }
  2070. var _isDigit = function isDigit(code) {
  2071. return code >= 48 && code <= 57;
  2072. };
  2073. const forbiddenNumericSeparatorSiblings = {
  2074. decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]),
  2075. hex: new Set([46, 88, 95, 120])
  2076. };
  2077. const isAllowedNumericSeparatorSibling = {
  2078. bin: ch => ch === 48 || ch === 49,
  2079. oct: ch => ch >= 48 && ch <= 55,
  2080. dec: ch => ch >= 48 && ch <= 57,
  2081. hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102
  2082. };
  2083. function readStringContents(type, input, pos, lineStart, curLine, errors) {
  2084. const initialPos = pos;
  2085. const initialLineStart = lineStart;
  2086. const initialCurLine = curLine;
  2087. let out = "";
  2088. let firstInvalidLoc = null;
  2089. let chunkStart = pos;
  2090. const {
  2091. length
  2092. } = input;
  2093. for (;;) {
  2094. if (pos >= length) {
  2095. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  2096. out += input.slice(chunkStart, pos);
  2097. break;
  2098. }
  2099. const ch = input.charCodeAt(pos);
  2100. if (isStringEnd(type, ch, input, pos)) {
  2101. out += input.slice(chunkStart, pos);
  2102. break;
  2103. }
  2104. if (ch === 92) {
  2105. out += input.slice(chunkStart, pos);
  2106. const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors);
  2107. if (res.ch === null && !firstInvalidLoc) {
  2108. firstInvalidLoc = {
  2109. pos,
  2110. lineStart,
  2111. curLine
  2112. };
  2113. } else {
  2114. out += res.ch;
  2115. }
  2116. ({
  2117. pos,
  2118. lineStart,
  2119. curLine
  2120. } = res);
  2121. chunkStart = pos;
  2122. } else if (ch === 8232 || ch === 8233) {
  2123. ++pos;
  2124. ++curLine;
  2125. lineStart = pos;
  2126. } else if (ch === 10 || ch === 13) {
  2127. if (type === "template") {
  2128. out += input.slice(chunkStart, pos) + "\n";
  2129. ++pos;
  2130. if (ch === 13 && input.charCodeAt(pos) === 10) {
  2131. ++pos;
  2132. }
  2133. ++curLine;
  2134. chunkStart = lineStart = pos;
  2135. } else {
  2136. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  2137. }
  2138. } else {
  2139. ++pos;
  2140. }
  2141. }
  2142. return {
  2143. pos,
  2144. str: out,
  2145. firstInvalidLoc,
  2146. lineStart,
  2147. curLine,
  2148. containsInvalid: !!firstInvalidLoc
  2149. };
  2150. }
  2151. function isStringEnd(type, ch, input, pos) {
  2152. if (type === "template") {
  2153. return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123;
  2154. }
  2155. return ch === (type === "double" ? 34 : 39);
  2156. }
  2157. function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
  2158. const throwOnInvalid = !inTemplate;
  2159. pos++;
  2160. const res = ch => ({
  2161. pos,
  2162. ch,
  2163. lineStart,
  2164. curLine
  2165. });
  2166. const ch = input.charCodeAt(pos++);
  2167. switch (ch) {
  2168. case 110:
  2169. return res("\n");
  2170. case 114:
  2171. return res("\r");
  2172. case 120:
  2173. {
  2174. let code;
  2175. ({
  2176. code,
  2177. pos
  2178. } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors));
  2179. return res(code === null ? null : String.fromCharCode(code));
  2180. }
  2181. case 117:
  2182. {
  2183. let code;
  2184. ({
  2185. code,
  2186. pos
  2187. } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors));
  2188. return res(code === null ? null : String.fromCodePoint(code));
  2189. }
  2190. case 116:
  2191. return res("\t");
  2192. case 98:
  2193. return res("\b");
  2194. case 118:
  2195. return res("\u000b");
  2196. case 102:
  2197. return res("\f");
  2198. case 13:
  2199. if (input.charCodeAt(pos) === 10) {
  2200. ++pos;
  2201. }
  2202. case 10:
  2203. lineStart = pos;
  2204. ++curLine;
  2205. case 8232:
  2206. case 8233:
  2207. return res("");
  2208. case 56:
  2209. case 57:
  2210. if (inTemplate) {
  2211. return res(null);
  2212. } else {
  2213. errors.strictNumericEscape(pos - 1, lineStart, curLine);
  2214. }
  2215. default:
  2216. if (ch >= 48 && ch <= 55) {
  2217. const startPos = pos - 1;
  2218. const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));
  2219. let octalStr = match[0];
  2220. let octal = parseInt(octalStr, 8);
  2221. if (octal > 255) {
  2222. octalStr = octalStr.slice(0, -1);
  2223. octal = parseInt(octalStr, 8);
  2224. }
  2225. pos += octalStr.length - 1;
  2226. const next = input.charCodeAt(pos);
  2227. if (octalStr !== "0" || next === 56 || next === 57) {
  2228. if (inTemplate) {
  2229. return res(null);
  2230. } else {
  2231. errors.strictNumericEscape(startPos, lineStart, curLine);
  2232. }
  2233. }
  2234. return res(String.fromCharCode(octal));
  2235. }
  2236. return res(String.fromCharCode(ch));
  2237. }
  2238. }
  2239. function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) {
  2240. const initialPos = pos;
  2241. let n;
  2242. ({
  2243. n,
  2244. pos
  2245. } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid));
  2246. if (n === null) {
  2247. if (throwOnInvalid) {
  2248. errors.invalidEscapeSequence(initialPos, lineStart, curLine);
  2249. } else {
  2250. pos = initialPos - 1;
  2251. }
  2252. }
  2253. return {
  2254. code: n,
  2255. pos
  2256. };
  2257. }
  2258. function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) {
  2259. const start = pos;
  2260. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  2261. const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin;
  2262. let invalid = false;
  2263. let total = 0;
  2264. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  2265. const code = input.charCodeAt(pos);
  2266. let val;
  2267. if (code === 95 && allowNumSeparator !== "bail") {
  2268. const prev = input.charCodeAt(pos - 1);
  2269. const next = input.charCodeAt(pos + 1);
  2270. if (!allowNumSeparator) {
  2271. if (bailOnError) return {
  2272. n: null,
  2273. pos
  2274. };
  2275. errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
  2276. } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
  2277. if (bailOnError) return {
  2278. n: null,
  2279. pos
  2280. };
  2281. errors.unexpectedNumericSeparator(pos, lineStart, curLine);
  2282. }
  2283. ++pos;
  2284. continue;
  2285. }
  2286. if (code >= 97) {
  2287. val = code - 97 + 10;
  2288. } else if (code >= 65) {
  2289. val = code - 65 + 10;
  2290. } else if (_isDigit(code)) {
  2291. val = code - 48;
  2292. } else {
  2293. val = Infinity;
  2294. }
  2295. if (val >= radix) {
  2296. if (val <= 9 && bailOnError) {
  2297. return {
  2298. n: null,
  2299. pos
  2300. };
  2301. } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) {
  2302. val = 0;
  2303. } else if (forceLen) {
  2304. val = 0;
  2305. invalid = true;
  2306. } else {
  2307. break;
  2308. }
  2309. }
  2310. ++pos;
  2311. total = total * radix + val;
  2312. }
  2313. if (pos === start || len != null && pos - start !== len || invalid) {
  2314. return {
  2315. n: null,
  2316. pos
  2317. };
  2318. }
  2319. return {
  2320. n: total,
  2321. pos
  2322. };
  2323. }
  2324. function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) {
  2325. const ch = input.charCodeAt(pos);
  2326. let code;
  2327. if (ch === 123) {
  2328. ++pos;
  2329. ({
  2330. code,
  2331. pos
  2332. } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors));
  2333. ++pos;
  2334. if (code !== null && code > 0x10ffff) {
  2335. if (throwOnInvalid) {
  2336. errors.invalidCodePoint(pos, lineStart, curLine);
  2337. } else {
  2338. return {
  2339. code: null,
  2340. pos
  2341. };
  2342. }
  2343. }
  2344. } else {
  2345. ({
  2346. code,
  2347. pos
  2348. } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors));
  2349. }
  2350. return {
  2351. code,
  2352. pos
  2353. };
  2354. }
  2355. function buildPosition(pos, lineStart, curLine) {
  2356. return new Position(curLine, pos - lineStart, pos);
  2357. }
  2358. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]);
  2359. class Token {
  2360. constructor(state) {
  2361. const startIndex = state.startIndex || 0;
  2362. this.type = state.type;
  2363. this.value = state.value;
  2364. this.start = startIndex + state.start;
  2365. this.end = startIndex + state.end;
  2366. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  2367. }
  2368. }
  2369. class Tokenizer extends CommentsParser {
  2370. constructor(options, input) {
  2371. super();
  2372. this.isLookahead = void 0;
  2373. this.tokens = [];
  2374. this.errorHandlers_readInt = {
  2375. invalidDigit: (pos, lineStart, curLine, radix) => {
  2376. if (!(this.optionFlags & 1024)) return false;
  2377. this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), {
  2378. radix
  2379. });
  2380. return true;
  2381. },
  2382. numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),
  2383. unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator)
  2384. };
  2385. this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, {
  2386. invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),
  2387. invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint)
  2388. });
  2389. this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, {
  2390. strictNumericEscape: (pos, lineStart, curLine) => {
  2391. this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine));
  2392. },
  2393. unterminated: (pos, lineStart, curLine) => {
  2394. throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine));
  2395. }
  2396. });
  2397. this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, {
  2398. strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),
  2399. unterminated: (pos, lineStart, curLine) => {
  2400. throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine));
  2401. }
  2402. });
  2403. this.state = new State();
  2404. this.state.init(options);
  2405. this.input = input;
  2406. this.length = input.length;
  2407. this.comments = [];
  2408. this.isLookahead = false;
  2409. }
  2410. pushToken(token) {
  2411. this.tokens.length = this.state.tokensLength;
  2412. this.tokens.push(token);
  2413. ++this.state.tokensLength;
  2414. }
  2415. next() {
  2416. this.checkKeywordEscapes();
  2417. if (this.optionFlags & 128) {
  2418. this.pushToken(new Token(this.state));
  2419. }
  2420. this.state.lastTokEndLoc = this.state.endLoc;
  2421. this.state.lastTokStartLoc = this.state.startLoc;
  2422. this.nextToken();
  2423. }
  2424. eat(type) {
  2425. if (this.match(type)) {
  2426. this.next();
  2427. return true;
  2428. } else {
  2429. return false;
  2430. }
  2431. }
  2432. match(type) {
  2433. return this.state.type === type;
  2434. }
  2435. createLookaheadState(state) {
  2436. return {
  2437. pos: state.pos,
  2438. value: null,
  2439. type: state.type,
  2440. start: state.start,
  2441. end: state.end,
  2442. context: [this.curContext()],
  2443. inType: state.inType,
  2444. startLoc: state.startLoc,
  2445. lastTokEndLoc: state.lastTokEndLoc,
  2446. curLine: state.curLine,
  2447. lineStart: state.lineStart,
  2448. curPosition: state.curPosition
  2449. };
  2450. }
  2451. lookahead() {
  2452. const old = this.state;
  2453. this.state = this.createLookaheadState(old);
  2454. this.isLookahead = true;
  2455. this.nextToken();
  2456. this.isLookahead = false;
  2457. const curr = this.state;
  2458. this.state = old;
  2459. return curr;
  2460. }
  2461. nextTokenStart() {
  2462. return this.nextTokenStartSince(this.state.pos);
  2463. }
  2464. nextTokenStartSince(pos) {
  2465. skipWhiteSpace.lastIndex = pos;
  2466. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  2467. }
  2468. lookaheadCharCode() {
  2469. return this.input.charCodeAt(this.nextTokenStart());
  2470. }
  2471. nextTokenInLineStart() {
  2472. return this.nextTokenInLineStartSince(this.state.pos);
  2473. }
  2474. nextTokenInLineStartSince(pos) {
  2475. skipWhiteSpaceInLine.lastIndex = pos;
  2476. return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos;
  2477. }
  2478. lookaheadInLineCharCode() {
  2479. return this.input.charCodeAt(this.nextTokenInLineStart());
  2480. }
  2481. codePointAtPos(pos) {
  2482. let cp = this.input.charCodeAt(pos);
  2483. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  2484. const trail = this.input.charCodeAt(pos);
  2485. if ((trail & 0xfc00) === 0xdc00) {
  2486. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  2487. }
  2488. }
  2489. return cp;
  2490. }
  2491. setStrict(strict) {
  2492. this.state.strict = strict;
  2493. if (strict) {
  2494. this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at));
  2495. this.state.strictErrors.clear();
  2496. }
  2497. }
  2498. curContext() {
  2499. return this.state.context[this.state.context.length - 1];
  2500. }
  2501. nextToken() {
  2502. this.skipSpace();
  2503. this.state.start = this.state.pos;
  2504. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  2505. if (this.state.pos >= this.length) {
  2506. this.finishToken(140);
  2507. return;
  2508. }
  2509. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  2510. }
  2511. skipBlockComment(commentEnd) {
  2512. let startLoc;
  2513. if (!this.isLookahead) startLoc = this.state.curPosition();
  2514. const start = this.state.pos;
  2515. const end = this.input.indexOf(commentEnd, start + 2);
  2516. if (end === -1) {
  2517. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  2518. }
  2519. this.state.pos = end + commentEnd.length;
  2520. lineBreakG.lastIndex = start + 2;
  2521. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  2522. ++this.state.curLine;
  2523. this.state.lineStart = lineBreakG.lastIndex;
  2524. }
  2525. if (this.isLookahead) return;
  2526. const comment = {
  2527. type: "CommentBlock",
  2528. value: this.input.slice(start + 2, end),
  2529. start: this.sourceToOffsetPos(start),
  2530. end: this.sourceToOffsetPos(end + commentEnd.length),
  2531. loc: new SourceLocation(startLoc, this.state.curPosition())
  2532. };
  2533. if (this.optionFlags & 128) this.pushToken(comment);
  2534. return comment;
  2535. }
  2536. skipLineComment(startSkip) {
  2537. const start = this.state.pos;
  2538. let startLoc;
  2539. if (!this.isLookahead) startLoc = this.state.curPosition();
  2540. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  2541. if (this.state.pos < this.length) {
  2542. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2543. ch = this.input.charCodeAt(this.state.pos);
  2544. }
  2545. }
  2546. if (this.isLookahead) return;
  2547. const end = this.state.pos;
  2548. const value = this.input.slice(start + startSkip, end);
  2549. const comment = {
  2550. type: "CommentLine",
  2551. value,
  2552. start: this.sourceToOffsetPos(start),
  2553. end: this.sourceToOffsetPos(end),
  2554. loc: new SourceLocation(startLoc, this.state.curPosition())
  2555. };
  2556. if (this.optionFlags & 128) this.pushToken(comment);
  2557. return comment;
  2558. }
  2559. skipSpace() {
  2560. const spaceStart = this.state.pos;
  2561. const comments = this.optionFlags & 2048 ? [] : null;
  2562. loop: while (this.state.pos < this.length) {
  2563. const ch = this.input.charCodeAt(this.state.pos);
  2564. switch (ch) {
  2565. case 32:
  2566. case 160:
  2567. case 9:
  2568. ++this.state.pos;
  2569. break;
  2570. case 13:
  2571. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  2572. ++this.state.pos;
  2573. }
  2574. case 10:
  2575. case 8232:
  2576. case 8233:
  2577. ++this.state.pos;
  2578. ++this.state.curLine;
  2579. this.state.lineStart = this.state.pos;
  2580. break;
  2581. case 47:
  2582. switch (this.input.charCodeAt(this.state.pos + 1)) {
  2583. case 42:
  2584. {
  2585. const comment = this.skipBlockComment("*/");
  2586. if (comment !== undefined) {
  2587. this.addComment(comment);
  2588. comments == null || comments.push(comment);
  2589. }
  2590. break;
  2591. }
  2592. case 47:
  2593. {
  2594. const comment = this.skipLineComment(2);
  2595. if (comment !== undefined) {
  2596. this.addComment(comment);
  2597. comments == null || comments.push(comment);
  2598. }
  2599. break;
  2600. }
  2601. default:
  2602. break loop;
  2603. }
  2604. break;
  2605. default:
  2606. if (isWhitespace(ch)) {
  2607. ++this.state.pos;
  2608. } else if (ch === 45 && !this.inModule && this.optionFlags & 4096) {
  2609. const pos = this.state.pos;
  2610. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  2611. const comment = this.skipLineComment(3);
  2612. if (comment !== undefined) {
  2613. this.addComment(comment);
  2614. comments == null || comments.push(comment);
  2615. }
  2616. } else {
  2617. break loop;
  2618. }
  2619. } else if (ch === 60 && !this.inModule && this.optionFlags & 4096) {
  2620. const pos = this.state.pos;
  2621. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  2622. const comment = this.skipLineComment(4);
  2623. if (comment !== undefined) {
  2624. this.addComment(comment);
  2625. comments == null || comments.push(comment);
  2626. }
  2627. } else {
  2628. break loop;
  2629. }
  2630. } else {
  2631. break loop;
  2632. }
  2633. }
  2634. }
  2635. if ((comments == null ? void 0 : comments.length) > 0) {
  2636. const end = this.state.pos;
  2637. const commentWhitespace = {
  2638. start: this.sourceToOffsetPos(spaceStart),
  2639. end: this.sourceToOffsetPos(end),
  2640. comments,
  2641. leadingNode: null,
  2642. trailingNode: null,
  2643. containingNode: null
  2644. };
  2645. this.state.commentStack.push(commentWhitespace);
  2646. }
  2647. }
  2648. finishToken(type, val) {
  2649. this.state.end = this.state.pos;
  2650. this.state.endLoc = this.state.curPosition();
  2651. const prevType = this.state.type;
  2652. this.state.type = type;
  2653. this.state.value = val;
  2654. if (!this.isLookahead) {
  2655. this.updateContext(prevType);
  2656. }
  2657. }
  2658. replaceToken(type) {
  2659. this.state.type = type;
  2660. this.updateContext();
  2661. }
  2662. readToken_numberSign() {
  2663. if (this.state.pos === 0 && this.readToken_interpreter()) {
  2664. return;
  2665. }
  2666. const nextPos = this.state.pos + 1;
  2667. const next = this.codePointAtPos(nextPos);
  2668. if (next >= 48 && next <= 57) {
  2669. throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition());
  2670. }
  2671. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  2672. this.expectPlugin("recordAndTuple");
  2673. if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") {
  2674. throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition());
  2675. }
  2676. this.state.pos += 2;
  2677. if (next === 123) {
  2678. this.finishToken(7);
  2679. } else {
  2680. this.finishToken(1);
  2681. }
  2682. } else if (isIdentifierStart(next)) {
  2683. ++this.state.pos;
  2684. this.finishToken(139, this.readWord1(next));
  2685. } else if (next === 92) {
  2686. ++this.state.pos;
  2687. this.finishToken(139, this.readWord1());
  2688. } else {
  2689. this.finishOp(27, 1);
  2690. }
  2691. }
  2692. readToken_dot() {
  2693. const next = this.input.charCodeAt(this.state.pos + 1);
  2694. if (next >= 48 && next <= 57) {
  2695. this.readNumber(true);
  2696. return;
  2697. }
  2698. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  2699. this.state.pos += 3;
  2700. this.finishToken(21);
  2701. } else {
  2702. ++this.state.pos;
  2703. this.finishToken(16);
  2704. }
  2705. }
  2706. readToken_slash() {
  2707. const next = this.input.charCodeAt(this.state.pos + 1);
  2708. if (next === 61) {
  2709. this.finishOp(31, 2);
  2710. } else {
  2711. this.finishOp(56, 1);
  2712. }
  2713. }
  2714. readToken_interpreter() {
  2715. if (this.state.pos !== 0 || this.length < 2) return false;
  2716. let ch = this.input.charCodeAt(this.state.pos + 1);
  2717. if (ch !== 33) return false;
  2718. const start = this.state.pos;
  2719. this.state.pos += 1;
  2720. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2721. ch = this.input.charCodeAt(this.state.pos);
  2722. }
  2723. const value = this.input.slice(start + 2, this.state.pos);
  2724. this.finishToken(28, value);
  2725. return true;
  2726. }
  2727. readToken_mult_modulo(code) {
  2728. let type = code === 42 ? 55 : 54;
  2729. let width = 1;
  2730. let next = this.input.charCodeAt(this.state.pos + 1);
  2731. if (code === 42 && next === 42) {
  2732. width++;
  2733. next = this.input.charCodeAt(this.state.pos + 2);
  2734. type = 57;
  2735. }
  2736. if (next === 61 && !this.state.inType) {
  2737. width++;
  2738. type = code === 37 ? 33 : 30;
  2739. }
  2740. this.finishOp(type, width);
  2741. }
  2742. readToken_pipe_amp(code) {
  2743. const next = this.input.charCodeAt(this.state.pos + 1);
  2744. if (next === code) {
  2745. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  2746. this.finishOp(30, 3);
  2747. } else {
  2748. this.finishOp(code === 124 ? 41 : 42, 2);
  2749. }
  2750. return;
  2751. }
  2752. if (code === 124) {
  2753. if (next === 62) {
  2754. this.finishOp(39, 2);
  2755. return;
  2756. }
  2757. if (this.hasPlugin("recordAndTuple") && next === 125) {
  2758. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2759. throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  2760. }
  2761. this.state.pos += 2;
  2762. this.finishToken(9);
  2763. return;
  2764. }
  2765. if (this.hasPlugin("recordAndTuple") && next === 93) {
  2766. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2767. throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  2768. }
  2769. this.state.pos += 2;
  2770. this.finishToken(4);
  2771. return;
  2772. }
  2773. }
  2774. if (next === 61) {
  2775. this.finishOp(30, 2);
  2776. return;
  2777. }
  2778. this.finishOp(code === 124 ? 43 : 45, 1);
  2779. }
  2780. readToken_caret() {
  2781. const next = this.input.charCodeAt(this.state.pos + 1);
  2782. if (next === 61 && !this.state.inType) {
  2783. this.finishOp(32, 2);
  2784. } else if (next === 94 && this.hasPlugin(["pipelineOperator", {
  2785. proposal: "hack",
  2786. topicToken: "^^"
  2787. }])) {
  2788. this.finishOp(37, 2);
  2789. const lookaheadCh = this.input.codePointAt(this.state.pos);
  2790. if (lookaheadCh === 94) {
  2791. this.unexpected();
  2792. }
  2793. } else {
  2794. this.finishOp(44, 1);
  2795. }
  2796. }
  2797. readToken_atSign() {
  2798. const next = this.input.charCodeAt(this.state.pos + 1);
  2799. if (next === 64 && this.hasPlugin(["pipelineOperator", {
  2800. proposal: "hack",
  2801. topicToken: "@@"
  2802. }])) {
  2803. this.finishOp(38, 2);
  2804. } else {
  2805. this.finishOp(26, 1);
  2806. }
  2807. }
  2808. readToken_plus_min(code) {
  2809. const next = this.input.charCodeAt(this.state.pos + 1);
  2810. if (next === code) {
  2811. this.finishOp(34, 2);
  2812. return;
  2813. }
  2814. if (next === 61) {
  2815. this.finishOp(30, 2);
  2816. } else {
  2817. this.finishOp(53, 1);
  2818. }
  2819. }
  2820. readToken_lt() {
  2821. const {
  2822. pos
  2823. } = this.state;
  2824. const next = this.input.charCodeAt(pos + 1);
  2825. if (next === 60) {
  2826. if (this.input.charCodeAt(pos + 2) === 61) {
  2827. this.finishOp(30, 3);
  2828. return;
  2829. }
  2830. this.finishOp(51, 2);
  2831. return;
  2832. }
  2833. if (next === 61) {
  2834. this.finishOp(49, 2);
  2835. return;
  2836. }
  2837. this.finishOp(47, 1);
  2838. }
  2839. readToken_gt() {
  2840. const {
  2841. pos
  2842. } = this.state;
  2843. const next = this.input.charCodeAt(pos + 1);
  2844. if (next === 62) {
  2845. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  2846. if (this.input.charCodeAt(pos + size) === 61) {
  2847. this.finishOp(30, size + 1);
  2848. return;
  2849. }
  2850. this.finishOp(52, size);
  2851. return;
  2852. }
  2853. if (next === 61) {
  2854. this.finishOp(49, 2);
  2855. return;
  2856. }
  2857. this.finishOp(48, 1);
  2858. }
  2859. readToken_eq_excl(code) {
  2860. const next = this.input.charCodeAt(this.state.pos + 1);
  2861. if (next === 61) {
  2862. this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  2863. return;
  2864. }
  2865. if (code === 61 && next === 62) {
  2866. this.state.pos += 2;
  2867. this.finishToken(19);
  2868. return;
  2869. }
  2870. this.finishOp(code === 61 ? 29 : 35, 1);
  2871. }
  2872. readToken_question() {
  2873. const next = this.input.charCodeAt(this.state.pos + 1);
  2874. const next2 = this.input.charCodeAt(this.state.pos + 2);
  2875. if (next === 63) {
  2876. if (next2 === 61) {
  2877. this.finishOp(30, 3);
  2878. } else {
  2879. this.finishOp(40, 2);
  2880. }
  2881. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  2882. this.state.pos += 2;
  2883. this.finishToken(18);
  2884. } else {
  2885. ++this.state.pos;
  2886. this.finishToken(17);
  2887. }
  2888. }
  2889. getTokenFromCode(code) {
  2890. switch (code) {
  2891. case 46:
  2892. this.readToken_dot();
  2893. return;
  2894. case 40:
  2895. ++this.state.pos;
  2896. this.finishToken(10);
  2897. return;
  2898. case 41:
  2899. ++this.state.pos;
  2900. this.finishToken(11);
  2901. return;
  2902. case 59:
  2903. ++this.state.pos;
  2904. this.finishToken(13);
  2905. return;
  2906. case 44:
  2907. ++this.state.pos;
  2908. this.finishToken(12);
  2909. return;
  2910. case 91:
  2911. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2912. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2913. throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  2914. }
  2915. this.state.pos += 2;
  2916. this.finishToken(2);
  2917. } else {
  2918. ++this.state.pos;
  2919. this.finishToken(0);
  2920. }
  2921. return;
  2922. case 93:
  2923. ++this.state.pos;
  2924. this.finishToken(3);
  2925. return;
  2926. case 123:
  2927. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2928. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2929. throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  2930. }
  2931. this.state.pos += 2;
  2932. this.finishToken(6);
  2933. } else {
  2934. ++this.state.pos;
  2935. this.finishToken(5);
  2936. }
  2937. return;
  2938. case 125:
  2939. ++this.state.pos;
  2940. this.finishToken(8);
  2941. return;
  2942. case 58:
  2943. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  2944. this.finishOp(15, 2);
  2945. } else {
  2946. ++this.state.pos;
  2947. this.finishToken(14);
  2948. }
  2949. return;
  2950. case 63:
  2951. this.readToken_question();
  2952. return;
  2953. case 96:
  2954. this.readTemplateToken();
  2955. return;
  2956. case 48:
  2957. {
  2958. const next = this.input.charCodeAt(this.state.pos + 1);
  2959. if (next === 120 || next === 88) {
  2960. this.readRadixNumber(16);
  2961. return;
  2962. }
  2963. if (next === 111 || next === 79) {
  2964. this.readRadixNumber(8);
  2965. return;
  2966. }
  2967. if (next === 98 || next === 66) {
  2968. this.readRadixNumber(2);
  2969. return;
  2970. }
  2971. }
  2972. case 49:
  2973. case 50:
  2974. case 51:
  2975. case 52:
  2976. case 53:
  2977. case 54:
  2978. case 55:
  2979. case 56:
  2980. case 57:
  2981. this.readNumber(false);
  2982. return;
  2983. case 34:
  2984. case 39:
  2985. this.readString(code);
  2986. return;
  2987. case 47:
  2988. this.readToken_slash();
  2989. return;
  2990. case 37:
  2991. case 42:
  2992. this.readToken_mult_modulo(code);
  2993. return;
  2994. case 124:
  2995. case 38:
  2996. this.readToken_pipe_amp(code);
  2997. return;
  2998. case 94:
  2999. this.readToken_caret();
  3000. return;
  3001. case 43:
  3002. case 45:
  3003. this.readToken_plus_min(code);
  3004. return;
  3005. case 60:
  3006. this.readToken_lt();
  3007. return;
  3008. case 62:
  3009. this.readToken_gt();
  3010. return;
  3011. case 61:
  3012. case 33:
  3013. this.readToken_eq_excl(code);
  3014. return;
  3015. case 126:
  3016. this.finishOp(36, 1);
  3017. return;
  3018. case 64:
  3019. this.readToken_atSign();
  3020. return;
  3021. case 35:
  3022. this.readToken_numberSign();
  3023. return;
  3024. case 92:
  3025. this.readWord();
  3026. return;
  3027. default:
  3028. if (isIdentifierStart(code)) {
  3029. this.readWord(code);
  3030. return;
  3031. }
  3032. }
  3033. throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), {
  3034. unexpected: String.fromCodePoint(code)
  3035. });
  3036. }
  3037. finishOp(type, size) {
  3038. const str = this.input.slice(this.state.pos, this.state.pos + size);
  3039. this.state.pos += size;
  3040. this.finishToken(type, str);
  3041. }
  3042. readRegexp() {
  3043. const startLoc = this.state.startLoc;
  3044. const start = this.state.start + 1;
  3045. let escaped, inClass;
  3046. let {
  3047. pos
  3048. } = this.state;
  3049. for (;; ++pos) {
  3050. if (pos >= this.length) {
  3051. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  3052. }
  3053. const ch = this.input.charCodeAt(pos);
  3054. if (isNewLine(ch)) {
  3055. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  3056. }
  3057. if (escaped) {
  3058. escaped = false;
  3059. } else {
  3060. if (ch === 91) {
  3061. inClass = true;
  3062. } else if (ch === 93 && inClass) {
  3063. inClass = false;
  3064. } else if (ch === 47 && !inClass) {
  3065. break;
  3066. }
  3067. escaped = ch === 92;
  3068. }
  3069. }
  3070. const content = this.input.slice(start, pos);
  3071. ++pos;
  3072. let mods = "";
  3073. const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start);
  3074. while (pos < this.length) {
  3075. const cp = this.codePointAtPos(pos);
  3076. const char = String.fromCharCode(cp);
  3077. if (VALID_REGEX_FLAGS.has(cp)) {
  3078. if (cp === 118) {
  3079. if (mods.includes("u")) {
  3080. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  3081. }
  3082. } else if (cp === 117) {
  3083. if (mods.includes("v")) {
  3084. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  3085. }
  3086. }
  3087. if (mods.includes(char)) {
  3088. this.raise(Errors.DuplicateRegExpFlags, nextPos());
  3089. }
  3090. } else if (isIdentifierChar(cp) || cp === 92) {
  3091. this.raise(Errors.MalformedRegExpFlags, nextPos());
  3092. } else {
  3093. break;
  3094. }
  3095. ++pos;
  3096. mods += char;
  3097. }
  3098. this.state.pos = pos;
  3099. this.finishToken(138, {
  3100. pattern: content,
  3101. flags: mods
  3102. });
  3103. }
  3104. readInt(radix, len, forceLen = false, allowNumSeparator = true) {
  3105. const {
  3106. n,
  3107. pos
  3108. } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false);
  3109. this.state.pos = pos;
  3110. return n;
  3111. }
  3112. readRadixNumber(radix) {
  3113. const start = this.state.pos;
  3114. const startLoc = this.state.curPosition();
  3115. let isBigInt = false;
  3116. this.state.pos += 2;
  3117. const val = this.readInt(radix);
  3118. if (val == null) {
  3119. this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), {
  3120. radix
  3121. });
  3122. }
  3123. const next = this.input.charCodeAt(this.state.pos);
  3124. if (next === 110) {
  3125. ++this.state.pos;
  3126. isBigInt = true;
  3127. } else if (next === 109) {
  3128. throw this.raise(Errors.InvalidDecimal, startLoc);
  3129. }
  3130. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3131. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  3132. }
  3133. if (isBigInt) {
  3134. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  3135. this.finishToken(136, str);
  3136. return;
  3137. }
  3138. this.finishToken(135, val);
  3139. }
  3140. readNumber(startsWithDot) {
  3141. const start = this.state.pos;
  3142. const startLoc = this.state.curPosition();
  3143. let isFloat = false;
  3144. let isBigInt = false;
  3145. let hasExponent = false;
  3146. let isOctal = false;
  3147. if (!startsWithDot && this.readInt(10) === null) {
  3148. this.raise(Errors.InvalidNumber, this.state.curPosition());
  3149. }
  3150. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  3151. if (hasLeadingZero) {
  3152. const integer = this.input.slice(start, this.state.pos);
  3153. this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc);
  3154. if (!this.state.strict) {
  3155. const underscorePos = integer.indexOf("_");
  3156. if (underscorePos > 0) {
  3157. this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos));
  3158. }
  3159. }
  3160. isOctal = hasLeadingZero && !/[89]/.test(integer);
  3161. }
  3162. let next = this.input.charCodeAt(this.state.pos);
  3163. if (next === 46 && !isOctal) {
  3164. ++this.state.pos;
  3165. this.readInt(10);
  3166. isFloat = true;
  3167. next = this.input.charCodeAt(this.state.pos);
  3168. }
  3169. if ((next === 69 || next === 101) && !isOctal) {
  3170. next = this.input.charCodeAt(++this.state.pos);
  3171. if (next === 43 || next === 45) {
  3172. ++this.state.pos;
  3173. }
  3174. if (this.readInt(10) === null) {
  3175. this.raise(Errors.InvalidOrMissingExponent, startLoc);
  3176. }
  3177. isFloat = true;
  3178. hasExponent = true;
  3179. next = this.input.charCodeAt(this.state.pos);
  3180. }
  3181. if (next === 110) {
  3182. if (isFloat || hasLeadingZero) {
  3183. this.raise(Errors.InvalidBigIntLiteral, startLoc);
  3184. }
  3185. ++this.state.pos;
  3186. isBigInt = true;
  3187. }
  3188. if (next === 109) {
  3189. this.expectPlugin("decimal", this.state.curPosition());
  3190. if (hasExponent || hasLeadingZero) {
  3191. this.raise(Errors.InvalidDecimal, startLoc);
  3192. }
  3193. ++this.state.pos;
  3194. var isDecimal = true;
  3195. }
  3196. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3197. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  3198. }
  3199. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  3200. if (isBigInt) {
  3201. this.finishToken(136, str);
  3202. return;
  3203. }
  3204. if (isDecimal) {
  3205. this.finishToken(137, str);
  3206. return;
  3207. }
  3208. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  3209. this.finishToken(135, val);
  3210. }
  3211. readCodePoint(throwOnInvalid) {
  3212. const {
  3213. code,
  3214. pos
  3215. } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint);
  3216. this.state.pos = pos;
  3217. return code;
  3218. }
  3219. readString(quote) {
  3220. const {
  3221. str,
  3222. pos,
  3223. curLine,
  3224. lineStart
  3225. } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string);
  3226. this.state.pos = pos + 1;
  3227. this.state.lineStart = lineStart;
  3228. this.state.curLine = curLine;
  3229. this.finishToken(134, str);
  3230. }
  3231. readTemplateContinuation() {
  3232. if (!this.match(8)) {
  3233. this.unexpected(null, 8);
  3234. }
  3235. this.state.pos--;
  3236. this.readTemplateToken();
  3237. }
  3238. readTemplateToken() {
  3239. const opening = this.input[this.state.pos];
  3240. const {
  3241. str,
  3242. firstInvalidLoc,
  3243. pos,
  3244. curLine,
  3245. lineStart
  3246. } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template);
  3247. this.state.pos = pos + 1;
  3248. this.state.lineStart = lineStart;
  3249. this.state.curLine = curLine;
  3250. if (firstInvalidLoc) {
  3251. this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, this.sourceToOffsetPos(firstInvalidLoc.pos));
  3252. }
  3253. if (this.input.codePointAt(pos) === 96) {
  3254. this.finishToken(24, firstInvalidLoc ? null : opening + str + "`");
  3255. } else {
  3256. this.state.pos++;
  3257. this.finishToken(25, firstInvalidLoc ? null : opening + str + "${");
  3258. }
  3259. }
  3260. recordStrictModeErrors(toParseError, at) {
  3261. const index = at.index;
  3262. if (this.state.strict && !this.state.strictErrors.has(index)) {
  3263. this.raise(toParseError, at);
  3264. } else {
  3265. this.state.strictErrors.set(index, [toParseError, at]);
  3266. }
  3267. }
  3268. readWord1(firstCode) {
  3269. this.state.containsEsc = false;
  3270. let word = "";
  3271. const start = this.state.pos;
  3272. let chunkStart = this.state.pos;
  3273. if (firstCode !== undefined) {
  3274. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  3275. }
  3276. while (this.state.pos < this.length) {
  3277. const ch = this.codePointAtPos(this.state.pos);
  3278. if (isIdentifierChar(ch)) {
  3279. this.state.pos += ch <= 0xffff ? 1 : 2;
  3280. } else if (ch === 92) {
  3281. this.state.containsEsc = true;
  3282. word += this.input.slice(chunkStart, this.state.pos);
  3283. const escStart = this.state.curPosition();
  3284. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  3285. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  3286. this.raise(Errors.MissingUnicodeEscape, this.state.curPosition());
  3287. chunkStart = this.state.pos - 1;
  3288. continue;
  3289. }
  3290. ++this.state.pos;
  3291. const esc = this.readCodePoint(true);
  3292. if (esc !== null) {
  3293. if (!identifierCheck(esc)) {
  3294. this.raise(Errors.EscapedCharNotAnIdentifier, escStart);
  3295. }
  3296. word += String.fromCodePoint(esc);
  3297. }
  3298. chunkStart = this.state.pos;
  3299. } else {
  3300. break;
  3301. }
  3302. }
  3303. return word + this.input.slice(chunkStart, this.state.pos);
  3304. }
  3305. readWord(firstCode) {
  3306. const word = this.readWord1(firstCode);
  3307. const type = keywords$1.get(word);
  3308. if (type !== undefined) {
  3309. this.finishToken(type, tokenLabelName(type));
  3310. } else {
  3311. this.finishToken(132, word);
  3312. }
  3313. }
  3314. checkKeywordEscapes() {
  3315. const {
  3316. type
  3317. } = this.state;
  3318. if (tokenIsKeyword(type) && this.state.containsEsc) {
  3319. this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, {
  3320. reservedWord: tokenLabelName(type)
  3321. });
  3322. }
  3323. }
  3324. raise(toParseError, at, details = {}) {
  3325. const loc = at instanceof Position ? at : at.loc.start;
  3326. const error = toParseError(loc, details);
  3327. if (!(this.optionFlags & 1024)) throw error;
  3328. if (!this.isLookahead) this.state.errors.push(error);
  3329. return error;
  3330. }
  3331. raiseOverwrite(toParseError, at, details = {}) {
  3332. const loc = at instanceof Position ? at : at.loc.start;
  3333. const pos = loc.index;
  3334. const errors = this.state.errors;
  3335. for (let i = errors.length - 1; i >= 0; i--) {
  3336. const error = errors[i];
  3337. if (error.loc.index === pos) {
  3338. return errors[i] = toParseError(loc, details);
  3339. }
  3340. if (error.loc.index < pos) break;
  3341. }
  3342. return this.raise(toParseError, at, details);
  3343. }
  3344. updateContext(prevType) {}
  3345. unexpected(loc, type) {
  3346. throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, {
  3347. expected: type ? tokenLabelName(type) : null
  3348. });
  3349. }
  3350. expectPlugin(pluginName, loc) {
  3351. if (this.hasPlugin(pluginName)) {
  3352. return true;
  3353. }
  3354. throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, {
  3355. missingPlugin: [pluginName]
  3356. });
  3357. }
  3358. expectOnePlugin(pluginNames) {
  3359. if (!pluginNames.some(name => this.hasPlugin(name))) {
  3360. throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, {
  3361. missingPlugin: pluginNames
  3362. });
  3363. }
  3364. }
  3365. errorBuilder(error) {
  3366. return (pos, lineStart, curLine) => {
  3367. this.raise(error, buildPosition(pos, lineStart, curLine));
  3368. };
  3369. }
  3370. }
  3371. class ClassScope {
  3372. constructor() {
  3373. this.privateNames = new Set();
  3374. this.loneAccessors = new Map();
  3375. this.undefinedPrivateNames = new Map();
  3376. }
  3377. }
  3378. class ClassScopeHandler {
  3379. constructor(parser) {
  3380. this.parser = void 0;
  3381. this.stack = [];
  3382. this.undefinedPrivateNames = new Map();
  3383. this.parser = parser;
  3384. }
  3385. current() {
  3386. return this.stack[this.stack.length - 1];
  3387. }
  3388. enter() {
  3389. this.stack.push(new ClassScope());
  3390. }
  3391. exit() {
  3392. const oldClassScope = this.stack.pop();
  3393. const current = this.current();
  3394. for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {
  3395. if (current) {
  3396. if (!current.undefinedPrivateNames.has(name)) {
  3397. current.undefinedPrivateNames.set(name, loc);
  3398. }
  3399. } else {
  3400. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  3401. identifierName: name
  3402. });
  3403. }
  3404. }
  3405. }
  3406. declarePrivateName(name, elementType, loc) {
  3407. const {
  3408. privateNames,
  3409. loneAccessors,
  3410. undefinedPrivateNames
  3411. } = this.current();
  3412. let redefined = privateNames.has(name);
  3413. if (elementType & 3) {
  3414. const accessor = redefined && loneAccessors.get(name);
  3415. if (accessor) {
  3416. const oldStatic = accessor & 4;
  3417. const newStatic = elementType & 4;
  3418. const oldKind = accessor & 3;
  3419. const newKind = elementType & 3;
  3420. redefined = oldKind === newKind || oldStatic !== newStatic;
  3421. if (!redefined) loneAccessors.delete(name);
  3422. } else if (!redefined) {
  3423. loneAccessors.set(name, elementType);
  3424. }
  3425. }
  3426. if (redefined) {
  3427. this.parser.raise(Errors.PrivateNameRedeclaration, loc, {
  3428. identifierName: name
  3429. });
  3430. }
  3431. privateNames.add(name);
  3432. undefinedPrivateNames.delete(name);
  3433. }
  3434. usePrivateName(name, loc) {
  3435. let classScope;
  3436. for (classScope of this.stack) {
  3437. if (classScope.privateNames.has(name)) return;
  3438. }
  3439. if (classScope) {
  3440. classScope.undefinedPrivateNames.set(name, loc);
  3441. } else {
  3442. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  3443. identifierName: name
  3444. });
  3445. }
  3446. }
  3447. }
  3448. class ExpressionScope {
  3449. constructor(type = 0) {
  3450. this.type = type;
  3451. }
  3452. canBeArrowParameterDeclaration() {
  3453. return this.type === 2 || this.type === 1;
  3454. }
  3455. isCertainlyParameterDeclaration() {
  3456. return this.type === 3;
  3457. }
  3458. }
  3459. class ArrowHeadParsingScope extends ExpressionScope {
  3460. constructor(type) {
  3461. super(type);
  3462. this.declarationErrors = new Map();
  3463. }
  3464. recordDeclarationError(ParsingErrorClass, at) {
  3465. const index = at.index;
  3466. this.declarationErrors.set(index, [ParsingErrorClass, at]);
  3467. }
  3468. clearDeclarationError(index) {
  3469. this.declarationErrors.delete(index);
  3470. }
  3471. iterateErrors(iterator) {
  3472. this.declarationErrors.forEach(iterator);
  3473. }
  3474. }
  3475. class ExpressionScopeHandler {
  3476. constructor(parser) {
  3477. this.parser = void 0;
  3478. this.stack = [new ExpressionScope()];
  3479. this.parser = parser;
  3480. }
  3481. enter(scope) {
  3482. this.stack.push(scope);
  3483. }
  3484. exit() {
  3485. this.stack.pop();
  3486. }
  3487. recordParameterInitializerError(toParseError, node) {
  3488. const origin = node.loc.start;
  3489. const {
  3490. stack
  3491. } = this;
  3492. let i = stack.length - 1;
  3493. let scope = stack[i];
  3494. while (!scope.isCertainlyParameterDeclaration()) {
  3495. if (scope.canBeArrowParameterDeclaration()) {
  3496. scope.recordDeclarationError(toParseError, origin);
  3497. } else {
  3498. return;
  3499. }
  3500. scope = stack[--i];
  3501. }
  3502. this.parser.raise(toParseError, origin);
  3503. }
  3504. recordArrowParameterBindingError(error, node) {
  3505. const {
  3506. stack
  3507. } = this;
  3508. const scope = stack[stack.length - 1];
  3509. const origin = node.loc.start;
  3510. if (scope.isCertainlyParameterDeclaration()) {
  3511. this.parser.raise(error, origin);
  3512. } else if (scope.canBeArrowParameterDeclaration()) {
  3513. scope.recordDeclarationError(error, origin);
  3514. } else {
  3515. return;
  3516. }
  3517. }
  3518. recordAsyncArrowParametersError(at) {
  3519. const {
  3520. stack
  3521. } = this;
  3522. let i = stack.length - 1;
  3523. let scope = stack[i];
  3524. while (scope.canBeArrowParameterDeclaration()) {
  3525. if (scope.type === 2) {
  3526. scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at);
  3527. }
  3528. scope = stack[--i];
  3529. }
  3530. }
  3531. validateAsPattern() {
  3532. const {
  3533. stack
  3534. } = this;
  3535. const currentScope = stack[stack.length - 1];
  3536. if (!currentScope.canBeArrowParameterDeclaration()) return;
  3537. currentScope.iterateErrors(([toParseError, loc]) => {
  3538. this.parser.raise(toParseError, loc);
  3539. let i = stack.length - 2;
  3540. let scope = stack[i];
  3541. while (scope.canBeArrowParameterDeclaration()) {
  3542. scope.clearDeclarationError(loc.index);
  3543. scope = stack[--i];
  3544. }
  3545. });
  3546. }
  3547. }
  3548. function newParameterDeclarationScope() {
  3549. return new ExpressionScope(3);
  3550. }
  3551. function newArrowHeadScope() {
  3552. return new ArrowHeadParsingScope(1);
  3553. }
  3554. function newAsyncArrowScope() {
  3555. return new ArrowHeadParsingScope(2);
  3556. }
  3557. function newExpressionScope() {
  3558. return new ExpressionScope();
  3559. }
  3560. class ProductionParameterHandler {
  3561. constructor() {
  3562. this.stacks = [];
  3563. }
  3564. enter(flags) {
  3565. this.stacks.push(flags);
  3566. }
  3567. exit() {
  3568. this.stacks.pop();
  3569. }
  3570. currentFlags() {
  3571. return this.stacks[this.stacks.length - 1];
  3572. }
  3573. get hasAwait() {
  3574. return (this.currentFlags() & 2) > 0;
  3575. }
  3576. get hasYield() {
  3577. return (this.currentFlags() & 1) > 0;
  3578. }
  3579. get hasReturn() {
  3580. return (this.currentFlags() & 4) > 0;
  3581. }
  3582. get hasIn() {
  3583. return (this.currentFlags() & 8) > 0;
  3584. }
  3585. }
  3586. function functionFlags(isAsync, isGenerator) {
  3587. return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0);
  3588. }
  3589. class UtilParser extends Tokenizer {
  3590. addExtra(node, key, value, enumerable = true) {
  3591. if (!node) return;
  3592. let {
  3593. extra
  3594. } = node;
  3595. if (extra == null) {
  3596. extra = {};
  3597. node.extra = extra;
  3598. }
  3599. if (enumerable) {
  3600. extra[key] = value;
  3601. } else {
  3602. Object.defineProperty(extra, key, {
  3603. enumerable,
  3604. value
  3605. });
  3606. }
  3607. }
  3608. isContextual(token) {
  3609. return this.state.type === token && !this.state.containsEsc;
  3610. }
  3611. isUnparsedContextual(nameStart, name) {
  3612. const nameEnd = nameStart + name.length;
  3613. if (this.input.slice(nameStart, nameEnd) === name) {
  3614. const nextCh = this.input.charCodeAt(nameEnd);
  3615. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  3616. }
  3617. return false;
  3618. }
  3619. isLookaheadContextual(name) {
  3620. const next = this.nextTokenStart();
  3621. return this.isUnparsedContextual(next, name);
  3622. }
  3623. eatContextual(token) {
  3624. if (this.isContextual(token)) {
  3625. this.next();
  3626. return true;
  3627. }
  3628. return false;
  3629. }
  3630. expectContextual(token, toParseError) {
  3631. if (!this.eatContextual(token)) {
  3632. if (toParseError != null) {
  3633. throw this.raise(toParseError, this.state.startLoc);
  3634. }
  3635. this.unexpected(null, token);
  3636. }
  3637. }
  3638. canInsertSemicolon() {
  3639. return this.match(140) || this.match(8) || this.hasPrecedingLineBreak();
  3640. }
  3641. hasPrecedingLineBreak() {
  3642. return hasNewLine(this.input, this.offsetToSourcePos(this.state.lastTokEndLoc.index), this.state.start);
  3643. }
  3644. hasFollowingLineBreak() {
  3645. return hasNewLine(this.input, this.state.end, this.nextTokenStart());
  3646. }
  3647. isLineTerminator() {
  3648. return this.eat(13) || this.canInsertSemicolon();
  3649. }
  3650. semicolon(allowAsi = true) {
  3651. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  3652. this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc);
  3653. }
  3654. expect(type, loc) {
  3655. if (!this.eat(type)) {
  3656. this.unexpected(loc, type);
  3657. }
  3658. }
  3659. tryParse(fn, oldState = this.state.clone()) {
  3660. const abortSignal = {
  3661. node: null
  3662. };
  3663. try {
  3664. const node = fn((node = null) => {
  3665. abortSignal.node = node;
  3666. throw abortSignal;
  3667. });
  3668. if (this.state.errors.length > oldState.errors.length) {
  3669. const failState = this.state;
  3670. this.state = oldState;
  3671. this.state.tokensLength = failState.tokensLength;
  3672. return {
  3673. node,
  3674. error: failState.errors[oldState.errors.length],
  3675. thrown: false,
  3676. aborted: false,
  3677. failState
  3678. };
  3679. }
  3680. return {
  3681. node,
  3682. error: null,
  3683. thrown: false,
  3684. aborted: false,
  3685. failState: null
  3686. };
  3687. } catch (error) {
  3688. const failState = this.state;
  3689. this.state = oldState;
  3690. if (error instanceof SyntaxError) {
  3691. return {
  3692. node: null,
  3693. error,
  3694. thrown: true,
  3695. aborted: false,
  3696. failState
  3697. };
  3698. }
  3699. if (error === abortSignal) {
  3700. return {
  3701. node: abortSignal.node,
  3702. error: null,
  3703. thrown: false,
  3704. aborted: true,
  3705. failState
  3706. };
  3707. }
  3708. throw error;
  3709. }
  3710. }
  3711. checkExpressionErrors(refExpressionErrors, andThrow) {
  3712. if (!refExpressionErrors) return false;
  3713. const {
  3714. shorthandAssignLoc,
  3715. doubleProtoLoc,
  3716. privateKeyLoc,
  3717. optionalParametersLoc
  3718. } = refExpressionErrors;
  3719. const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc;
  3720. if (!andThrow) {
  3721. return hasErrors;
  3722. }
  3723. if (shorthandAssignLoc != null) {
  3724. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  3725. }
  3726. if (doubleProtoLoc != null) {
  3727. this.raise(Errors.DuplicateProto, doubleProtoLoc);
  3728. }
  3729. if (privateKeyLoc != null) {
  3730. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  3731. }
  3732. if (optionalParametersLoc != null) {
  3733. this.unexpected(optionalParametersLoc);
  3734. }
  3735. }
  3736. isLiteralPropertyName() {
  3737. return tokenIsLiteralPropertyName(this.state.type);
  3738. }
  3739. isPrivateName(node) {
  3740. return node.type === "PrivateName";
  3741. }
  3742. getPrivateNameSV(node) {
  3743. return node.id.name;
  3744. }
  3745. hasPropertyAsPrivateName(node) {
  3746. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  3747. }
  3748. isObjectProperty(node) {
  3749. return node.type === "ObjectProperty";
  3750. }
  3751. isObjectMethod(node) {
  3752. return node.type === "ObjectMethod";
  3753. }
  3754. initializeScopes(inModule = this.options.sourceType === "module") {
  3755. const oldLabels = this.state.labels;
  3756. this.state.labels = [];
  3757. const oldExportedIdentifiers = this.exportedIdentifiers;
  3758. this.exportedIdentifiers = new Set();
  3759. const oldInModule = this.inModule;
  3760. this.inModule = inModule;
  3761. const oldScope = this.scope;
  3762. const ScopeHandler = this.getScopeHandler();
  3763. this.scope = new ScopeHandler(this, inModule);
  3764. const oldProdParam = this.prodParam;
  3765. this.prodParam = new ProductionParameterHandler();
  3766. const oldClassScope = this.classScope;
  3767. this.classScope = new ClassScopeHandler(this);
  3768. const oldExpressionScope = this.expressionScope;
  3769. this.expressionScope = new ExpressionScopeHandler(this);
  3770. return () => {
  3771. this.state.labels = oldLabels;
  3772. this.exportedIdentifiers = oldExportedIdentifiers;
  3773. this.inModule = oldInModule;
  3774. this.scope = oldScope;
  3775. this.prodParam = oldProdParam;
  3776. this.classScope = oldClassScope;
  3777. this.expressionScope = oldExpressionScope;
  3778. };
  3779. }
  3780. enterInitialScopes() {
  3781. let paramFlags = 0;
  3782. if (this.inModule) {
  3783. paramFlags |= 2;
  3784. }
  3785. this.scope.enter(1);
  3786. this.prodParam.enter(paramFlags);
  3787. }
  3788. checkDestructuringPrivate(refExpressionErrors) {
  3789. const {
  3790. privateKeyLoc
  3791. } = refExpressionErrors;
  3792. if (privateKeyLoc !== null) {
  3793. this.expectPlugin("destructuringPrivate", privateKeyLoc);
  3794. }
  3795. }
  3796. }
  3797. class ExpressionErrors {
  3798. constructor() {
  3799. this.shorthandAssignLoc = null;
  3800. this.doubleProtoLoc = null;
  3801. this.privateKeyLoc = null;
  3802. this.optionalParametersLoc = null;
  3803. }
  3804. }
  3805. class Node {
  3806. constructor(parser, pos, loc) {
  3807. this.type = "";
  3808. this.start = pos;
  3809. this.end = 0;
  3810. this.loc = new SourceLocation(loc);
  3811. if ((parser == null ? void 0 : parser.optionFlags) & 64) this.range = [pos, 0];
  3812. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  3813. }
  3814. }
  3815. const NodePrototype = Node.prototype;
  3816. {
  3817. NodePrototype.__clone = function () {
  3818. const newNode = new Node(undefined, this.start, this.loc.start);
  3819. const keys = Object.keys(this);
  3820. for (let i = 0, length = keys.length; i < length; i++) {
  3821. const key = keys[i];
  3822. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  3823. newNode[key] = this[key];
  3824. }
  3825. }
  3826. return newNode;
  3827. };
  3828. }
  3829. function clonePlaceholder(node) {
  3830. return cloneIdentifier(node);
  3831. }
  3832. function cloneIdentifier(node) {
  3833. const {
  3834. type,
  3835. start,
  3836. end,
  3837. loc,
  3838. range,
  3839. extra,
  3840. name
  3841. } = node;
  3842. const cloned = Object.create(NodePrototype);
  3843. cloned.type = type;
  3844. cloned.start = start;
  3845. cloned.end = end;
  3846. cloned.loc = loc;
  3847. cloned.range = range;
  3848. cloned.extra = extra;
  3849. cloned.name = name;
  3850. if (type === "Placeholder") {
  3851. cloned.expectedNode = node.expectedNode;
  3852. }
  3853. return cloned;
  3854. }
  3855. function cloneStringLiteral(node) {
  3856. const {
  3857. type,
  3858. start,
  3859. end,
  3860. loc,
  3861. range,
  3862. extra
  3863. } = node;
  3864. if (type === "Placeholder") {
  3865. return clonePlaceholder(node);
  3866. }
  3867. const cloned = Object.create(NodePrototype);
  3868. cloned.type = type;
  3869. cloned.start = start;
  3870. cloned.end = end;
  3871. cloned.loc = loc;
  3872. cloned.range = range;
  3873. if (node.raw !== undefined) {
  3874. cloned.raw = node.raw;
  3875. } else {
  3876. cloned.extra = extra;
  3877. }
  3878. cloned.value = node.value;
  3879. return cloned;
  3880. }
  3881. class NodeUtils extends UtilParser {
  3882. startNode() {
  3883. const loc = this.state.startLoc;
  3884. return new Node(this, loc.index, loc);
  3885. }
  3886. startNodeAt(loc) {
  3887. return new Node(this, loc.index, loc);
  3888. }
  3889. startNodeAtNode(type) {
  3890. return this.startNodeAt(type.loc.start);
  3891. }
  3892. finishNode(node, type) {
  3893. return this.finishNodeAt(node, type, this.state.lastTokEndLoc);
  3894. }
  3895. finishNodeAt(node, type, endLoc) {
  3896. node.type = type;
  3897. node.end = endLoc.index;
  3898. node.loc.end = endLoc;
  3899. if (this.optionFlags & 64) node.range[1] = endLoc.index;
  3900. if (this.optionFlags & 2048) {
  3901. this.processComment(node);
  3902. }
  3903. return node;
  3904. }
  3905. resetStartLocation(node, startLoc) {
  3906. node.start = startLoc.index;
  3907. node.loc.start = startLoc;
  3908. if (this.optionFlags & 64) node.range[0] = startLoc.index;
  3909. }
  3910. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  3911. node.end = endLoc.index;
  3912. node.loc.end = endLoc;
  3913. if (this.optionFlags & 64) node.range[1] = endLoc.index;
  3914. }
  3915. resetStartLocationFromNode(node, locationNode) {
  3916. this.resetStartLocation(node, locationNode.loc.start);
  3917. }
  3918. }
  3919. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  3920. const FlowErrors = ParseErrorEnum`flow`({
  3921. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  3922. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",
  3923. AssignReservedType: ({
  3924. reservedType
  3925. }) => `Cannot overwrite reserved type ${reservedType}.`,
  3926. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  3927. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  3928. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  3929. EnumBooleanMemberNotInitialized: ({
  3930. memberName,
  3931. enumName
  3932. }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,
  3933. EnumDuplicateMemberName: ({
  3934. memberName,
  3935. enumName
  3936. }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,
  3937. EnumInconsistentMemberValues: ({
  3938. enumName
  3939. }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,
  3940. EnumInvalidExplicitType: ({
  3941. invalidEnumType,
  3942. enumName
  3943. }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  3944. EnumInvalidExplicitTypeUnknownSupplied: ({
  3945. enumName
  3946. }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  3947. EnumInvalidMemberInitializerPrimaryType: ({
  3948. enumName,
  3949. memberName,
  3950. explicitType
  3951. }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,
  3952. EnumInvalidMemberInitializerSymbolType: ({
  3953. enumName,
  3954. memberName
  3955. }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,
  3956. EnumInvalidMemberInitializerUnknownType: ({
  3957. enumName,
  3958. memberName
  3959. }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,
  3960. EnumInvalidMemberName: ({
  3961. enumName,
  3962. memberName,
  3963. suggestion
  3964. }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,
  3965. EnumNumberMemberNotInitialized: ({
  3966. enumName,
  3967. memberName
  3968. }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,
  3969. EnumStringMemberInconsistentlyInitialized: ({
  3970. enumName
  3971. }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,
  3972. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  3973. ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.",
  3974. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",
  3975. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  3976. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  3977. InexactVariance: "Explicit inexact syntax cannot have variance.",
  3978. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  3979. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  3980. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  3981. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  3982. PatternIsOptional: Object.assign({
  3983. message: "A binding pattern parameter cannot be optional in an implementation signature."
  3984. }, {
  3985. reasonCode: "OptionalBindingPattern"
  3986. }),
  3987. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  3988. SpreadVariance: "Spread properties cannot have variance.",
  3989. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  3990. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  3991. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  3992. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  3993. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  3994. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  3995. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  3996. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  3997. UnexpectedReservedType: ({
  3998. reservedType
  3999. }) => `Unexpected reserved type ${reservedType}.`,
  4000. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  4001. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  4002. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  4003. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  4004. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  4005. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  4006. UnsupportedDeclareExportKind: ({
  4007. unsupportedExportKind,
  4008. suggestion
  4009. }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,
  4010. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  4011. UnterminatedFlowComment: "Unterminated flow-comment."
  4012. });
  4013. function isEsModuleType(bodyElement) {
  4014. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  4015. }
  4016. function hasTypeImportKind(node) {
  4017. return node.importKind === "type" || node.importKind === "typeof";
  4018. }
  4019. const exportSuggestions = {
  4020. const: "declare export var",
  4021. let: "declare export var",
  4022. type: "export type",
  4023. interface: "export interface"
  4024. };
  4025. function partition(list, test) {
  4026. const list1 = [];
  4027. const list2 = [];
  4028. for (let i = 0; i < list.length; i++) {
  4029. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  4030. }
  4031. return [list1, list2];
  4032. }
  4033. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  4034. var flow = superClass => class FlowParserMixin extends superClass {
  4035. constructor(...args) {
  4036. super(...args);
  4037. this.flowPragma = undefined;
  4038. }
  4039. getScopeHandler() {
  4040. return FlowScopeHandler;
  4041. }
  4042. shouldParseTypes() {
  4043. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  4044. }
  4045. finishToken(type, val) {
  4046. if (type !== 134 && type !== 13 && type !== 28) {
  4047. if (this.flowPragma === undefined) {
  4048. this.flowPragma = null;
  4049. }
  4050. }
  4051. super.finishToken(type, val);
  4052. }
  4053. addComment(comment) {
  4054. if (this.flowPragma === undefined) {
  4055. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  4056. if (!matches) ;else if (matches[1] === "flow") {
  4057. this.flowPragma = "flow";
  4058. } else if (matches[1] === "noflow") {
  4059. this.flowPragma = "noflow";
  4060. } else {
  4061. throw new Error("Unexpected flow pragma");
  4062. }
  4063. }
  4064. super.addComment(comment);
  4065. }
  4066. flowParseTypeInitialiser(tok) {
  4067. const oldInType = this.state.inType;
  4068. this.state.inType = true;
  4069. this.expect(tok || 14);
  4070. const type = this.flowParseType();
  4071. this.state.inType = oldInType;
  4072. return type;
  4073. }
  4074. flowParsePredicate() {
  4075. const node = this.startNode();
  4076. const moduloLoc = this.state.startLoc;
  4077. this.next();
  4078. this.expectContextual(110);
  4079. if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) {
  4080. this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);
  4081. }
  4082. if (this.eat(10)) {
  4083. node.value = super.parseExpression();
  4084. this.expect(11);
  4085. return this.finishNode(node, "DeclaredPredicate");
  4086. } else {
  4087. return this.finishNode(node, "InferredPredicate");
  4088. }
  4089. }
  4090. flowParseTypeAndPredicateInitialiser() {
  4091. const oldInType = this.state.inType;
  4092. this.state.inType = true;
  4093. this.expect(14);
  4094. let type = null;
  4095. let predicate = null;
  4096. if (this.match(54)) {
  4097. this.state.inType = oldInType;
  4098. predicate = this.flowParsePredicate();
  4099. } else {
  4100. type = this.flowParseType();
  4101. this.state.inType = oldInType;
  4102. if (this.match(54)) {
  4103. predicate = this.flowParsePredicate();
  4104. }
  4105. }
  4106. return [type, predicate];
  4107. }
  4108. flowParseDeclareClass(node) {
  4109. this.next();
  4110. this.flowParseInterfaceish(node, true);
  4111. return this.finishNode(node, "DeclareClass");
  4112. }
  4113. flowParseDeclareFunction(node) {
  4114. this.next();
  4115. const id = node.id = this.parseIdentifier();
  4116. const typeNode = this.startNode();
  4117. const typeContainer = this.startNode();
  4118. if (this.match(47)) {
  4119. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4120. } else {
  4121. typeNode.typeParameters = null;
  4122. }
  4123. this.expect(10);
  4124. const tmp = this.flowParseFunctionTypeParams();
  4125. typeNode.params = tmp.params;
  4126. typeNode.rest = tmp.rest;
  4127. typeNode.this = tmp._this;
  4128. this.expect(11);
  4129. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  4130. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4131. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4132. this.resetEndLocation(id);
  4133. this.semicolon();
  4134. this.scope.declareName(node.id.name, 2048, node.id.loc.start);
  4135. return this.finishNode(node, "DeclareFunction");
  4136. }
  4137. flowParseDeclare(node, insideModule) {
  4138. if (this.match(80)) {
  4139. return this.flowParseDeclareClass(node);
  4140. } else if (this.match(68)) {
  4141. return this.flowParseDeclareFunction(node);
  4142. } else if (this.match(74)) {
  4143. return this.flowParseDeclareVariable(node);
  4144. } else if (this.eatContextual(127)) {
  4145. if (this.match(16)) {
  4146. return this.flowParseDeclareModuleExports(node);
  4147. } else {
  4148. if (insideModule) {
  4149. this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc);
  4150. }
  4151. return this.flowParseDeclareModule(node);
  4152. }
  4153. } else if (this.isContextual(130)) {
  4154. return this.flowParseDeclareTypeAlias(node);
  4155. } else if (this.isContextual(131)) {
  4156. return this.flowParseDeclareOpaqueType(node);
  4157. } else if (this.isContextual(129)) {
  4158. return this.flowParseDeclareInterface(node);
  4159. } else if (this.match(82)) {
  4160. return this.flowParseDeclareExportDeclaration(node, insideModule);
  4161. } else {
  4162. this.unexpected();
  4163. }
  4164. }
  4165. flowParseDeclareVariable(node) {
  4166. this.next();
  4167. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  4168. this.scope.declareName(node.id.name, 5, node.id.loc.start);
  4169. this.semicolon();
  4170. return this.finishNode(node, "DeclareVariable");
  4171. }
  4172. flowParseDeclareModule(node) {
  4173. this.scope.enter(0);
  4174. if (this.match(134)) {
  4175. node.id = super.parseExprAtom();
  4176. } else {
  4177. node.id = this.parseIdentifier();
  4178. }
  4179. const bodyNode = node.body = this.startNode();
  4180. const body = bodyNode.body = [];
  4181. this.expect(5);
  4182. while (!this.match(8)) {
  4183. let bodyNode = this.startNode();
  4184. if (this.match(83)) {
  4185. this.next();
  4186. if (!this.isContextual(130) && !this.match(87)) {
  4187. this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc);
  4188. }
  4189. super.parseImport(bodyNode);
  4190. } else {
  4191. this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule);
  4192. bodyNode = this.flowParseDeclare(bodyNode, true);
  4193. }
  4194. body.push(bodyNode);
  4195. }
  4196. this.scope.exit();
  4197. this.expect(8);
  4198. this.finishNode(bodyNode, "BlockStatement");
  4199. let kind = null;
  4200. let hasModuleExport = false;
  4201. body.forEach(bodyElement => {
  4202. if (isEsModuleType(bodyElement)) {
  4203. if (kind === "CommonJS") {
  4204. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  4205. }
  4206. kind = "ES";
  4207. } else if (bodyElement.type === "DeclareModuleExports") {
  4208. if (hasModuleExport) {
  4209. this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);
  4210. }
  4211. if (kind === "ES") {
  4212. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  4213. }
  4214. kind = "CommonJS";
  4215. hasModuleExport = true;
  4216. }
  4217. });
  4218. node.kind = kind || "CommonJS";
  4219. return this.finishNode(node, "DeclareModule");
  4220. }
  4221. flowParseDeclareExportDeclaration(node, insideModule) {
  4222. this.expect(82);
  4223. if (this.eat(65)) {
  4224. if (this.match(68) || this.match(80)) {
  4225. node.declaration = this.flowParseDeclare(this.startNode());
  4226. } else {
  4227. node.declaration = this.flowParseType();
  4228. this.semicolon();
  4229. }
  4230. node.default = true;
  4231. return this.finishNode(node, "DeclareExportDeclaration");
  4232. } else {
  4233. if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) {
  4234. const label = this.state.value;
  4235. throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, {
  4236. unsupportedExportKind: label,
  4237. suggestion: exportSuggestions[label]
  4238. });
  4239. }
  4240. if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) {
  4241. node.declaration = this.flowParseDeclare(this.startNode());
  4242. node.default = false;
  4243. return this.finishNode(node, "DeclareExportDeclaration");
  4244. } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) {
  4245. node = this.parseExport(node, null);
  4246. if (node.type === "ExportNamedDeclaration") {
  4247. node.type = "ExportDeclaration";
  4248. node.default = false;
  4249. delete node.exportKind;
  4250. }
  4251. node.type = "Declare" + node.type;
  4252. return node;
  4253. }
  4254. }
  4255. this.unexpected();
  4256. }
  4257. flowParseDeclareModuleExports(node) {
  4258. this.next();
  4259. this.expectContextual(111);
  4260. node.typeAnnotation = this.flowParseTypeAnnotation();
  4261. this.semicolon();
  4262. return this.finishNode(node, "DeclareModuleExports");
  4263. }
  4264. flowParseDeclareTypeAlias(node) {
  4265. this.next();
  4266. const finished = this.flowParseTypeAlias(node);
  4267. finished.type = "DeclareTypeAlias";
  4268. return finished;
  4269. }
  4270. flowParseDeclareOpaqueType(node) {
  4271. this.next();
  4272. const finished = this.flowParseOpaqueType(node, true);
  4273. finished.type = "DeclareOpaqueType";
  4274. return finished;
  4275. }
  4276. flowParseDeclareInterface(node) {
  4277. this.next();
  4278. this.flowParseInterfaceish(node, false);
  4279. return this.finishNode(node, "DeclareInterface");
  4280. }
  4281. flowParseInterfaceish(node, isClass) {
  4282. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  4283. this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start);
  4284. if (this.match(47)) {
  4285. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4286. } else {
  4287. node.typeParameters = null;
  4288. }
  4289. node.extends = [];
  4290. if (this.eat(81)) {
  4291. do {
  4292. node.extends.push(this.flowParseInterfaceExtends());
  4293. } while (!isClass && this.eat(12));
  4294. }
  4295. if (isClass) {
  4296. node.implements = [];
  4297. node.mixins = [];
  4298. if (this.eatContextual(117)) {
  4299. do {
  4300. node.mixins.push(this.flowParseInterfaceExtends());
  4301. } while (this.eat(12));
  4302. }
  4303. if (this.eatContextual(113)) {
  4304. do {
  4305. node.implements.push(this.flowParseInterfaceExtends());
  4306. } while (this.eat(12));
  4307. }
  4308. }
  4309. node.body = this.flowParseObjectType({
  4310. allowStatic: isClass,
  4311. allowExact: false,
  4312. allowSpread: false,
  4313. allowProto: isClass,
  4314. allowInexact: false
  4315. });
  4316. }
  4317. flowParseInterfaceExtends() {
  4318. const node = this.startNode();
  4319. node.id = this.flowParseQualifiedTypeIdentifier();
  4320. if (this.match(47)) {
  4321. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4322. } else {
  4323. node.typeParameters = null;
  4324. }
  4325. return this.finishNode(node, "InterfaceExtends");
  4326. }
  4327. flowParseInterface(node) {
  4328. this.flowParseInterfaceish(node, false);
  4329. return this.finishNode(node, "InterfaceDeclaration");
  4330. }
  4331. checkNotUnderscore(word) {
  4332. if (word === "_") {
  4333. this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc);
  4334. }
  4335. }
  4336. checkReservedType(word, startLoc, declaration) {
  4337. if (!reservedTypes.has(word)) return;
  4338. this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, {
  4339. reservedType: word
  4340. });
  4341. }
  4342. flowParseRestrictedIdentifier(liberal, declaration) {
  4343. this.checkReservedType(this.state.value, this.state.startLoc, declaration);
  4344. return this.parseIdentifier(liberal);
  4345. }
  4346. flowParseTypeAlias(node) {
  4347. node.id = this.flowParseRestrictedIdentifier(false, true);
  4348. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  4349. if (this.match(47)) {
  4350. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4351. } else {
  4352. node.typeParameters = null;
  4353. }
  4354. node.right = this.flowParseTypeInitialiser(29);
  4355. this.semicolon();
  4356. return this.finishNode(node, "TypeAlias");
  4357. }
  4358. flowParseOpaqueType(node, declare) {
  4359. this.expectContextual(130);
  4360. node.id = this.flowParseRestrictedIdentifier(true, true);
  4361. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  4362. if (this.match(47)) {
  4363. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4364. } else {
  4365. node.typeParameters = null;
  4366. }
  4367. node.supertype = null;
  4368. if (this.match(14)) {
  4369. node.supertype = this.flowParseTypeInitialiser(14);
  4370. }
  4371. node.impltype = null;
  4372. if (!declare) {
  4373. node.impltype = this.flowParseTypeInitialiser(29);
  4374. }
  4375. this.semicolon();
  4376. return this.finishNode(node, "OpaqueType");
  4377. }
  4378. flowParseTypeParameter(requireDefault = false) {
  4379. const nodeStartLoc = this.state.startLoc;
  4380. const node = this.startNode();
  4381. const variance = this.flowParseVariance();
  4382. const ident = this.flowParseTypeAnnotatableIdentifier();
  4383. node.name = ident.name;
  4384. node.variance = variance;
  4385. node.bound = ident.typeAnnotation;
  4386. if (this.match(29)) {
  4387. this.eat(29);
  4388. node.default = this.flowParseType();
  4389. } else {
  4390. if (requireDefault) {
  4391. this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);
  4392. }
  4393. }
  4394. return this.finishNode(node, "TypeParameter");
  4395. }
  4396. flowParseTypeParameterDeclaration() {
  4397. const oldInType = this.state.inType;
  4398. const node = this.startNode();
  4399. node.params = [];
  4400. this.state.inType = true;
  4401. if (this.match(47) || this.match(143)) {
  4402. this.next();
  4403. } else {
  4404. this.unexpected();
  4405. }
  4406. let defaultRequired = false;
  4407. do {
  4408. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  4409. node.params.push(typeParameter);
  4410. if (typeParameter.default) {
  4411. defaultRequired = true;
  4412. }
  4413. if (!this.match(48)) {
  4414. this.expect(12);
  4415. }
  4416. } while (!this.match(48));
  4417. this.expect(48);
  4418. this.state.inType = oldInType;
  4419. return this.finishNode(node, "TypeParameterDeclaration");
  4420. }
  4421. flowInTopLevelContext(cb) {
  4422. if (this.curContext() !== types.brace) {
  4423. const oldContext = this.state.context;
  4424. this.state.context = [oldContext[0]];
  4425. try {
  4426. return cb();
  4427. } finally {
  4428. this.state.context = oldContext;
  4429. }
  4430. } else {
  4431. return cb();
  4432. }
  4433. }
  4434. flowParseTypeParameterInstantiationInExpression() {
  4435. if (this.reScan_lt() !== 47) return;
  4436. return this.flowParseTypeParameterInstantiation();
  4437. }
  4438. flowParseTypeParameterInstantiation() {
  4439. const node = this.startNode();
  4440. const oldInType = this.state.inType;
  4441. this.state.inType = true;
  4442. node.params = [];
  4443. this.flowInTopLevelContext(() => {
  4444. this.expect(47);
  4445. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4446. this.state.noAnonFunctionType = false;
  4447. while (!this.match(48)) {
  4448. node.params.push(this.flowParseType());
  4449. if (!this.match(48)) {
  4450. this.expect(12);
  4451. }
  4452. }
  4453. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4454. });
  4455. this.state.inType = oldInType;
  4456. if (!this.state.inType && this.curContext() === types.brace) {
  4457. this.reScan_lt_gt();
  4458. }
  4459. this.expect(48);
  4460. return this.finishNode(node, "TypeParameterInstantiation");
  4461. }
  4462. flowParseTypeParameterInstantiationCallOrNew() {
  4463. if (this.reScan_lt() !== 47) return;
  4464. const node = this.startNode();
  4465. const oldInType = this.state.inType;
  4466. node.params = [];
  4467. this.state.inType = true;
  4468. this.expect(47);
  4469. while (!this.match(48)) {
  4470. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  4471. if (!this.match(48)) {
  4472. this.expect(12);
  4473. }
  4474. }
  4475. this.expect(48);
  4476. this.state.inType = oldInType;
  4477. return this.finishNode(node, "TypeParameterInstantiation");
  4478. }
  4479. flowParseInterfaceType() {
  4480. const node = this.startNode();
  4481. this.expectContextual(129);
  4482. node.extends = [];
  4483. if (this.eat(81)) {
  4484. do {
  4485. node.extends.push(this.flowParseInterfaceExtends());
  4486. } while (this.eat(12));
  4487. }
  4488. node.body = this.flowParseObjectType({
  4489. allowStatic: false,
  4490. allowExact: false,
  4491. allowSpread: false,
  4492. allowProto: false,
  4493. allowInexact: false
  4494. });
  4495. return this.finishNode(node, "InterfaceTypeAnnotation");
  4496. }
  4497. flowParseObjectPropertyKey() {
  4498. return this.match(135) || this.match(134) ? super.parseExprAtom() : this.parseIdentifier(true);
  4499. }
  4500. flowParseObjectTypeIndexer(node, isStatic, variance) {
  4501. node.static = isStatic;
  4502. if (this.lookahead().type === 14) {
  4503. node.id = this.flowParseObjectPropertyKey();
  4504. node.key = this.flowParseTypeInitialiser();
  4505. } else {
  4506. node.id = null;
  4507. node.key = this.flowParseType();
  4508. }
  4509. this.expect(3);
  4510. node.value = this.flowParseTypeInitialiser();
  4511. node.variance = variance;
  4512. return this.finishNode(node, "ObjectTypeIndexer");
  4513. }
  4514. flowParseObjectTypeInternalSlot(node, isStatic) {
  4515. node.static = isStatic;
  4516. node.id = this.flowParseObjectPropertyKey();
  4517. this.expect(3);
  4518. this.expect(3);
  4519. if (this.match(47) || this.match(10)) {
  4520. node.method = true;
  4521. node.optional = false;
  4522. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  4523. } else {
  4524. node.method = false;
  4525. if (this.eat(17)) {
  4526. node.optional = true;
  4527. }
  4528. node.value = this.flowParseTypeInitialiser();
  4529. }
  4530. return this.finishNode(node, "ObjectTypeInternalSlot");
  4531. }
  4532. flowParseObjectTypeMethodish(node) {
  4533. node.params = [];
  4534. node.rest = null;
  4535. node.typeParameters = null;
  4536. node.this = null;
  4537. if (this.match(47)) {
  4538. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4539. }
  4540. this.expect(10);
  4541. if (this.match(78)) {
  4542. node.this = this.flowParseFunctionTypeParam(true);
  4543. node.this.name = null;
  4544. if (!this.match(11)) {
  4545. this.expect(12);
  4546. }
  4547. }
  4548. while (!this.match(11) && !this.match(21)) {
  4549. node.params.push(this.flowParseFunctionTypeParam(false));
  4550. if (!this.match(11)) {
  4551. this.expect(12);
  4552. }
  4553. }
  4554. if (this.eat(21)) {
  4555. node.rest = this.flowParseFunctionTypeParam(false);
  4556. }
  4557. this.expect(11);
  4558. node.returnType = this.flowParseTypeInitialiser();
  4559. return this.finishNode(node, "FunctionTypeAnnotation");
  4560. }
  4561. flowParseObjectTypeCallProperty(node, isStatic) {
  4562. const valueNode = this.startNode();
  4563. node.static = isStatic;
  4564. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4565. return this.finishNode(node, "ObjectTypeCallProperty");
  4566. }
  4567. flowParseObjectType({
  4568. allowStatic,
  4569. allowExact,
  4570. allowSpread,
  4571. allowProto,
  4572. allowInexact
  4573. }) {
  4574. const oldInType = this.state.inType;
  4575. this.state.inType = true;
  4576. const nodeStart = this.startNode();
  4577. nodeStart.callProperties = [];
  4578. nodeStart.properties = [];
  4579. nodeStart.indexers = [];
  4580. nodeStart.internalSlots = [];
  4581. let endDelim;
  4582. let exact;
  4583. let inexact = false;
  4584. if (allowExact && this.match(6)) {
  4585. this.expect(6);
  4586. endDelim = 9;
  4587. exact = true;
  4588. } else {
  4589. this.expect(5);
  4590. endDelim = 8;
  4591. exact = false;
  4592. }
  4593. nodeStart.exact = exact;
  4594. while (!this.match(endDelim)) {
  4595. let isStatic = false;
  4596. let protoStartLoc = null;
  4597. let inexactStartLoc = null;
  4598. const node = this.startNode();
  4599. if (allowProto && this.isContextual(118)) {
  4600. const lookahead = this.lookahead();
  4601. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4602. this.next();
  4603. protoStartLoc = this.state.startLoc;
  4604. allowStatic = false;
  4605. }
  4606. }
  4607. if (allowStatic && this.isContextual(106)) {
  4608. const lookahead = this.lookahead();
  4609. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4610. this.next();
  4611. isStatic = true;
  4612. }
  4613. }
  4614. const variance = this.flowParseVariance();
  4615. if (this.eat(0)) {
  4616. if (protoStartLoc != null) {
  4617. this.unexpected(protoStartLoc);
  4618. }
  4619. if (this.eat(0)) {
  4620. if (variance) {
  4621. this.unexpected(variance.loc.start);
  4622. }
  4623. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  4624. } else {
  4625. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4626. }
  4627. } else if (this.match(10) || this.match(47)) {
  4628. if (protoStartLoc != null) {
  4629. this.unexpected(protoStartLoc);
  4630. }
  4631. if (variance) {
  4632. this.unexpected(variance.loc.start);
  4633. }
  4634. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4635. } else {
  4636. let kind = "init";
  4637. if (this.isContextual(99) || this.isContextual(104)) {
  4638. const lookahead = this.lookahead();
  4639. if (tokenIsLiteralPropertyName(lookahead.type)) {
  4640. kind = this.state.value;
  4641. this.next();
  4642. }
  4643. }
  4644. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  4645. if (propOrInexact === null) {
  4646. inexact = true;
  4647. inexactStartLoc = this.state.lastTokStartLoc;
  4648. } else {
  4649. nodeStart.properties.push(propOrInexact);
  4650. }
  4651. }
  4652. this.flowObjectTypeSemicolon();
  4653. if (inexactStartLoc && !this.match(8) && !this.match(9)) {
  4654. this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc);
  4655. }
  4656. }
  4657. this.expect(endDelim);
  4658. if (allowSpread) {
  4659. nodeStart.inexact = inexact;
  4660. }
  4661. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4662. this.state.inType = oldInType;
  4663. return out;
  4664. }
  4665. flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) {
  4666. if (this.eat(21)) {
  4667. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  4668. if (isInexactToken) {
  4669. if (!allowSpread) {
  4670. this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc);
  4671. } else if (!allowInexact) {
  4672. this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc);
  4673. }
  4674. if (variance) {
  4675. this.raise(FlowErrors.InexactVariance, variance);
  4676. }
  4677. return null;
  4678. }
  4679. if (!allowSpread) {
  4680. this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc);
  4681. }
  4682. if (protoStartLoc != null) {
  4683. this.unexpected(protoStartLoc);
  4684. }
  4685. if (variance) {
  4686. this.raise(FlowErrors.SpreadVariance, variance);
  4687. }
  4688. node.argument = this.flowParseType();
  4689. return this.finishNode(node, "ObjectTypeSpreadProperty");
  4690. } else {
  4691. node.key = this.flowParseObjectPropertyKey();
  4692. node.static = isStatic;
  4693. node.proto = protoStartLoc != null;
  4694. node.kind = kind;
  4695. let optional = false;
  4696. if (this.match(47) || this.match(10)) {
  4697. node.method = true;
  4698. if (protoStartLoc != null) {
  4699. this.unexpected(protoStartLoc);
  4700. }
  4701. if (variance) {
  4702. this.unexpected(variance.loc.start);
  4703. }
  4704. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  4705. if (kind === "get" || kind === "set") {
  4706. this.flowCheckGetterSetterParams(node);
  4707. }
  4708. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  4709. this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this);
  4710. }
  4711. } else {
  4712. if (kind !== "init") this.unexpected();
  4713. node.method = false;
  4714. if (this.eat(17)) {
  4715. optional = true;
  4716. }
  4717. node.value = this.flowParseTypeInitialiser();
  4718. node.variance = variance;
  4719. }
  4720. node.optional = optional;
  4721. return this.finishNode(node, "ObjectTypeProperty");
  4722. }
  4723. }
  4724. flowCheckGetterSetterParams(property) {
  4725. const paramCount = property.kind === "get" ? 0 : 1;
  4726. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  4727. if (property.value.this) {
  4728. this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this);
  4729. }
  4730. if (length !== paramCount) {
  4731. this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property);
  4732. }
  4733. if (property.kind === "set" && property.value.rest) {
  4734. this.raise(Errors.BadSetterRestParameter, property);
  4735. }
  4736. }
  4737. flowObjectTypeSemicolon() {
  4738. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  4739. this.unexpected();
  4740. }
  4741. }
  4742. flowParseQualifiedTypeIdentifier(startLoc, id) {
  4743. var _startLoc;
  4744. (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc;
  4745. let node = id || this.flowParseRestrictedIdentifier(true);
  4746. while (this.eat(16)) {
  4747. const node2 = this.startNodeAt(startLoc);
  4748. node2.qualification = node;
  4749. node2.id = this.flowParseRestrictedIdentifier(true);
  4750. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4751. }
  4752. return node;
  4753. }
  4754. flowParseGenericType(startLoc, id) {
  4755. const node = this.startNodeAt(startLoc);
  4756. node.typeParameters = null;
  4757. node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);
  4758. if (this.match(47)) {
  4759. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4760. }
  4761. return this.finishNode(node, "GenericTypeAnnotation");
  4762. }
  4763. flowParseTypeofType() {
  4764. const node = this.startNode();
  4765. this.expect(87);
  4766. node.argument = this.flowParsePrimaryType();
  4767. return this.finishNode(node, "TypeofTypeAnnotation");
  4768. }
  4769. flowParseTupleType() {
  4770. const node = this.startNode();
  4771. node.types = [];
  4772. this.expect(0);
  4773. while (this.state.pos < this.length && !this.match(3)) {
  4774. node.types.push(this.flowParseType());
  4775. if (this.match(3)) break;
  4776. this.expect(12);
  4777. }
  4778. this.expect(3);
  4779. return this.finishNode(node, "TupleTypeAnnotation");
  4780. }
  4781. flowParseFunctionTypeParam(first) {
  4782. let name = null;
  4783. let optional = false;
  4784. let typeAnnotation = null;
  4785. const node = this.startNode();
  4786. const lh = this.lookahead();
  4787. const isThis = this.state.type === 78;
  4788. if (lh.type === 14 || lh.type === 17) {
  4789. if (isThis && !first) {
  4790. this.raise(FlowErrors.ThisParamMustBeFirst, node);
  4791. }
  4792. name = this.parseIdentifier(isThis);
  4793. if (this.eat(17)) {
  4794. optional = true;
  4795. if (isThis) {
  4796. this.raise(FlowErrors.ThisParamMayNotBeOptional, node);
  4797. }
  4798. }
  4799. typeAnnotation = this.flowParseTypeInitialiser();
  4800. } else {
  4801. typeAnnotation = this.flowParseType();
  4802. }
  4803. node.name = name;
  4804. node.optional = optional;
  4805. node.typeAnnotation = typeAnnotation;
  4806. return this.finishNode(node, "FunctionTypeParam");
  4807. }
  4808. reinterpretTypeAsFunctionTypeParam(type) {
  4809. const node = this.startNodeAt(type.loc.start);
  4810. node.name = null;
  4811. node.optional = false;
  4812. node.typeAnnotation = type;
  4813. return this.finishNode(node, "FunctionTypeParam");
  4814. }
  4815. flowParseFunctionTypeParams(params = []) {
  4816. let rest = null;
  4817. let _this = null;
  4818. if (this.match(78)) {
  4819. _this = this.flowParseFunctionTypeParam(true);
  4820. _this.name = null;
  4821. if (!this.match(11)) {
  4822. this.expect(12);
  4823. }
  4824. }
  4825. while (!this.match(11) && !this.match(21)) {
  4826. params.push(this.flowParseFunctionTypeParam(false));
  4827. if (!this.match(11)) {
  4828. this.expect(12);
  4829. }
  4830. }
  4831. if (this.eat(21)) {
  4832. rest = this.flowParseFunctionTypeParam(false);
  4833. }
  4834. return {
  4835. params,
  4836. rest,
  4837. _this
  4838. };
  4839. }
  4840. flowIdentToTypeAnnotation(startLoc, node, id) {
  4841. switch (id.name) {
  4842. case "any":
  4843. return this.finishNode(node, "AnyTypeAnnotation");
  4844. case "bool":
  4845. case "boolean":
  4846. return this.finishNode(node, "BooleanTypeAnnotation");
  4847. case "mixed":
  4848. return this.finishNode(node, "MixedTypeAnnotation");
  4849. case "empty":
  4850. return this.finishNode(node, "EmptyTypeAnnotation");
  4851. case "number":
  4852. return this.finishNode(node, "NumberTypeAnnotation");
  4853. case "string":
  4854. return this.finishNode(node, "StringTypeAnnotation");
  4855. case "symbol":
  4856. return this.finishNode(node, "SymbolTypeAnnotation");
  4857. default:
  4858. this.checkNotUnderscore(id.name);
  4859. return this.flowParseGenericType(startLoc, id);
  4860. }
  4861. }
  4862. flowParsePrimaryType() {
  4863. const startLoc = this.state.startLoc;
  4864. const node = this.startNode();
  4865. let tmp;
  4866. let type;
  4867. let isGroupedType = false;
  4868. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4869. switch (this.state.type) {
  4870. case 5:
  4871. return this.flowParseObjectType({
  4872. allowStatic: false,
  4873. allowExact: false,
  4874. allowSpread: true,
  4875. allowProto: false,
  4876. allowInexact: true
  4877. });
  4878. case 6:
  4879. return this.flowParseObjectType({
  4880. allowStatic: false,
  4881. allowExact: true,
  4882. allowSpread: true,
  4883. allowProto: false,
  4884. allowInexact: false
  4885. });
  4886. case 0:
  4887. this.state.noAnonFunctionType = false;
  4888. type = this.flowParseTupleType();
  4889. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4890. return type;
  4891. case 47:
  4892. {
  4893. const node = this.startNode();
  4894. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4895. this.expect(10);
  4896. tmp = this.flowParseFunctionTypeParams();
  4897. node.params = tmp.params;
  4898. node.rest = tmp.rest;
  4899. node.this = tmp._this;
  4900. this.expect(11);
  4901. this.expect(19);
  4902. node.returnType = this.flowParseType();
  4903. return this.finishNode(node, "FunctionTypeAnnotation");
  4904. }
  4905. case 10:
  4906. {
  4907. const node = this.startNode();
  4908. this.next();
  4909. if (!this.match(11) && !this.match(21)) {
  4910. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  4911. const token = this.lookahead().type;
  4912. isGroupedType = token !== 17 && token !== 14;
  4913. } else {
  4914. isGroupedType = true;
  4915. }
  4916. }
  4917. if (isGroupedType) {
  4918. this.state.noAnonFunctionType = false;
  4919. type = this.flowParseType();
  4920. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4921. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  4922. this.expect(11);
  4923. return type;
  4924. } else {
  4925. this.eat(12);
  4926. }
  4927. }
  4928. if (type) {
  4929. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  4930. } else {
  4931. tmp = this.flowParseFunctionTypeParams();
  4932. }
  4933. node.params = tmp.params;
  4934. node.rest = tmp.rest;
  4935. node.this = tmp._this;
  4936. this.expect(11);
  4937. this.expect(19);
  4938. node.returnType = this.flowParseType();
  4939. node.typeParameters = null;
  4940. return this.finishNode(node, "FunctionTypeAnnotation");
  4941. }
  4942. case 134:
  4943. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  4944. case 85:
  4945. case 86:
  4946. node.value = this.match(85);
  4947. this.next();
  4948. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  4949. case 53:
  4950. if (this.state.value === "-") {
  4951. this.next();
  4952. if (this.match(135)) {
  4953. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  4954. }
  4955. if (this.match(136)) {
  4956. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  4957. }
  4958. throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc);
  4959. }
  4960. this.unexpected();
  4961. return;
  4962. case 135:
  4963. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  4964. case 136:
  4965. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  4966. case 88:
  4967. this.next();
  4968. return this.finishNode(node, "VoidTypeAnnotation");
  4969. case 84:
  4970. this.next();
  4971. return this.finishNode(node, "NullLiteralTypeAnnotation");
  4972. case 78:
  4973. this.next();
  4974. return this.finishNode(node, "ThisTypeAnnotation");
  4975. case 55:
  4976. this.next();
  4977. return this.finishNode(node, "ExistsTypeAnnotation");
  4978. case 87:
  4979. return this.flowParseTypeofType();
  4980. default:
  4981. if (tokenIsKeyword(this.state.type)) {
  4982. const label = tokenLabelName(this.state.type);
  4983. this.next();
  4984. return super.createIdentifier(node, label);
  4985. } else if (tokenIsIdentifier(this.state.type)) {
  4986. if (this.isContextual(129)) {
  4987. return this.flowParseInterfaceType();
  4988. }
  4989. return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier());
  4990. }
  4991. }
  4992. this.unexpected();
  4993. }
  4994. flowParsePostfixType() {
  4995. const startLoc = this.state.startLoc;
  4996. let type = this.flowParsePrimaryType();
  4997. let seenOptionalIndexedAccess = false;
  4998. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  4999. const node = this.startNodeAt(startLoc);
  5000. const optional = this.eat(18);
  5001. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  5002. this.expect(0);
  5003. if (!optional && this.match(3)) {
  5004. node.elementType = type;
  5005. this.next();
  5006. type = this.finishNode(node, "ArrayTypeAnnotation");
  5007. } else {
  5008. node.objectType = type;
  5009. node.indexType = this.flowParseType();
  5010. this.expect(3);
  5011. if (seenOptionalIndexedAccess) {
  5012. node.optional = optional;
  5013. type = this.finishNode(node, "OptionalIndexedAccessType");
  5014. } else {
  5015. type = this.finishNode(node, "IndexedAccessType");
  5016. }
  5017. }
  5018. }
  5019. return type;
  5020. }
  5021. flowParsePrefixType() {
  5022. const node = this.startNode();
  5023. if (this.eat(17)) {
  5024. node.typeAnnotation = this.flowParsePrefixType();
  5025. return this.finishNode(node, "NullableTypeAnnotation");
  5026. } else {
  5027. return this.flowParsePostfixType();
  5028. }
  5029. }
  5030. flowParseAnonFunctionWithoutParens() {
  5031. const param = this.flowParsePrefixType();
  5032. if (!this.state.noAnonFunctionType && this.eat(19)) {
  5033. const node = this.startNodeAt(param.loc.start);
  5034. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  5035. node.rest = null;
  5036. node.this = null;
  5037. node.returnType = this.flowParseType();
  5038. node.typeParameters = null;
  5039. return this.finishNode(node, "FunctionTypeAnnotation");
  5040. }
  5041. return param;
  5042. }
  5043. flowParseIntersectionType() {
  5044. const node = this.startNode();
  5045. this.eat(45);
  5046. const type = this.flowParseAnonFunctionWithoutParens();
  5047. node.types = [type];
  5048. while (this.eat(45)) {
  5049. node.types.push(this.flowParseAnonFunctionWithoutParens());
  5050. }
  5051. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  5052. }
  5053. flowParseUnionType() {
  5054. const node = this.startNode();
  5055. this.eat(43);
  5056. const type = this.flowParseIntersectionType();
  5057. node.types = [type];
  5058. while (this.eat(43)) {
  5059. node.types.push(this.flowParseIntersectionType());
  5060. }
  5061. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  5062. }
  5063. flowParseType() {
  5064. const oldInType = this.state.inType;
  5065. this.state.inType = true;
  5066. const type = this.flowParseUnionType();
  5067. this.state.inType = oldInType;
  5068. return type;
  5069. }
  5070. flowParseTypeOrImplicitInstantiation() {
  5071. if (this.state.type === 132 && this.state.value === "_") {
  5072. const startLoc = this.state.startLoc;
  5073. const node = this.parseIdentifier();
  5074. return this.flowParseGenericType(startLoc, node);
  5075. } else {
  5076. return this.flowParseType();
  5077. }
  5078. }
  5079. flowParseTypeAnnotation() {
  5080. const node = this.startNode();
  5081. node.typeAnnotation = this.flowParseTypeInitialiser();
  5082. return this.finishNode(node, "TypeAnnotation");
  5083. }
  5084. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  5085. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  5086. if (this.match(14)) {
  5087. ident.typeAnnotation = this.flowParseTypeAnnotation();
  5088. this.resetEndLocation(ident);
  5089. }
  5090. return ident;
  5091. }
  5092. typeCastToParameter(node) {
  5093. node.expression.typeAnnotation = node.typeAnnotation;
  5094. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  5095. return node.expression;
  5096. }
  5097. flowParseVariance() {
  5098. let variance = null;
  5099. if (this.match(53)) {
  5100. variance = this.startNode();
  5101. if (this.state.value === "+") {
  5102. variance.kind = "plus";
  5103. } else {
  5104. variance.kind = "minus";
  5105. }
  5106. this.next();
  5107. return this.finishNode(variance, "Variance");
  5108. }
  5109. return variance;
  5110. }
  5111. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  5112. if (allowExpressionBody) {
  5113. this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  5114. return;
  5115. }
  5116. super.parseFunctionBody(node, false, isMethod);
  5117. }
  5118. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5119. if (this.match(14)) {
  5120. const typeNode = this.startNode();
  5121. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5122. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  5123. }
  5124. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  5125. }
  5126. parseStatementLike(flags) {
  5127. if (this.state.strict && this.isContextual(129)) {
  5128. const lookahead = this.lookahead();
  5129. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  5130. const node = this.startNode();
  5131. this.next();
  5132. return this.flowParseInterface(node);
  5133. }
  5134. } else if (this.isContextual(126)) {
  5135. const node = this.startNode();
  5136. this.next();
  5137. return this.flowParseEnumDeclaration(node);
  5138. }
  5139. const stmt = super.parseStatementLike(flags);
  5140. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  5141. this.flowPragma = null;
  5142. }
  5143. return stmt;
  5144. }
  5145. parseExpressionStatement(node, expr, decorators) {
  5146. if (expr.type === "Identifier") {
  5147. if (expr.name === "declare") {
  5148. if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) {
  5149. return this.flowParseDeclare(node);
  5150. }
  5151. } else if (tokenIsIdentifier(this.state.type)) {
  5152. if (expr.name === "interface") {
  5153. return this.flowParseInterface(node);
  5154. } else if (expr.name === "type") {
  5155. return this.flowParseTypeAlias(node);
  5156. } else if (expr.name === "opaque") {
  5157. return this.flowParseOpaqueType(node, false);
  5158. }
  5159. }
  5160. }
  5161. return super.parseExpressionStatement(node, expr, decorators);
  5162. }
  5163. shouldParseExportDeclaration() {
  5164. const {
  5165. type
  5166. } = this.state;
  5167. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  5168. return !this.state.containsEsc;
  5169. }
  5170. return super.shouldParseExportDeclaration();
  5171. }
  5172. isExportDefaultSpecifier() {
  5173. const {
  5174. type
  5175. } = this.state;
  5176. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  5177. return this.state.containsEsc;
  5178. }
  5179. return super.isExportDefaultSpecifier();
  5180. }
  5181. parseExportDefaultExpression() {
  5182. if (this.isContextual(126)) {
  5183. const node = this.startNode();
  5184. this.next();
  5185. return this.flowParseEnumDeclaration(node);
  5186. }
  5187. return super.parseExportDefaultExpression();
  5188. }
  5189. parseConditional(expr, startLoc, refExpressionErrors) {
  5190. if (!this.match(17)) return expr;
  5191. if (this.state.maybeInArrowParameters) {
  5192. const nextCh = this.lookaheadCharCode();
  5193. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  5194. this.setOptionalParametersError(refExpressionErrors);
  5195. return expr;
  5196. }
  5197. }
  5198. this.expect(17);
  5199. const state = this.state.clone();
  5200. const originalNoArrowAt = this.state.noArrowAt;
  5201. const node = this.startNodeAt(startLoc);
  5202. let {
  5203. consequent,
  5204. failed
  5205. } = this.tryParseConditionalConsequent();
  5206. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5207. if (failed || invalid.length > 0) {
  5208. const noArrowAt = [...originalNoArrowAt];
  5209. if (invalid.length > 0) {
  5210. this.state = state;
  5211. this.state.noArrowAt = noArrowAt;
  5212. for (let i = 0; i < invalid.length; i++) {
  5213. noArrowAt.push(invalid[i].start);
  5214. }
  5215. ({
  5216. consequent,
  5217. failed
  5218. } = this.tryParseConditionalConsequent());
  5219. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5220. }
  5221. if (failed && valid.length > 1) {
  5222. this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);
  5223. }
  5224. if (failed && valid.length === 1) {
  5225. this.state = state;
  5226. noArrowAt.push(valid[0].start);
  5227. this.state.noArrowAt = noArrowAt;
  5228. ({
  5229. consequent,
  5230. failed
  5231. } = this.tryParseConditionalConsequent());
  5232. }
  5233. }
  5234. this.getArrowLikeExpressions(consequent, true);
  5235. this.state.noArrowAt = originalNoArrowAt;
  5236. this.expect(14);
  5237. node.test = expr;
  5238. node.consequent = consequent;
  5239. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  5240. return this.finishNode(node, "ConditionalExpression");
  5241. }
  5242. tryParseConditionalConsequent() {
  5243. this.state.noArrowParamsConversionAt.push(this.state.start);
  5244. const consequent = this.parseMaybeAssignAllowIn();
  5245. const failed = !this.match(14);
  5246. this.state.noArrowParamsConversionAt.pop();
  5247. return {
  5248. consequent,
  5249. failed
  5250. };
  5251. }
  5252. getArrowLikeExpressions(node, disallowInvalid) {
  5253. const stack = [node];
  5254. const arrows = [];
  5255. while (stack.length !== 0) {
  5256. const node = stack.pop();
  5257. if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
  5258. if (node.typeParameters || !node.returnType) {
  5259. this.finishArrowValidation(node);
  5260. } else {
  5261. arrows.push(node);
  5262. }
  5263. stack.push(node.body);
  5264. } else if (node.type === "ConditionalExpression") {
  5265. stack.push(node.consequent);
  5266. stack.push(node.alternate);
  5267. }
  5268. }
  5269. if (disallowInvalid) {
  5270. arrows.forEach(node => this.finishArrowValidation(node));
  5271. return [arrows, []];
  5272. }
  5273. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  5274. }
  5275. finishArrowValidation(node) {
  5276. var _node$extra;
  5277. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
  5278. this.scope.enter(2 | 4);
  5279. super.checkParams(node, false, true);
  5280. this.scope.exit();
  5281. }
  5282. forwardNoArrowParamsConversionAt(node, parse) {
  5283. let result;
  5284. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  5285. this.state.noArrowParamsConversionAt.push(this.state.start);
  5286. result = parse();
  5287. this.state.noArrowParamsConversionAt.pop();
  5288. } else {
  5289. result = parse();
  5290. }
  5291. return result;
  5292. }
  5293. parseParenItem(node, startLoc) {
  5294. const newNode = super.parseParenItem(node, startLoc);
  5295. if (this.eat(17)) {
  5296. newNode.optional = true;
  5297. this.resetEndLocation(node);
  5298. }
  5299. if (this.match(14)) {
  5300. const typeCastNode = this.startNodeAt(startLoc);
  5301. typeCastNode.expression = newNode;
  5302. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  5303. return this.finishNode(typeCastNode, "TypeCastExpression");
  5304. }
  5305. return newNode;
  5306. }
  5307. assertModuleNodeAllowed(node) {
  5308. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  5309. return;
  5310. }
  5311. super.assertModuleNodeAllowed(node);
  5312. }
  5313. parseExportDeclaration(node) {
  5314. if (this.isContextual(130)) {
  5315. node.exportKind = "type";
  5316. const declarationNode = this.startNode();
  5317. this.next();
  5318. if (this.match(5)) {
  5319. node.specifiers = this.parseExportSpecifiers(true);
  5320. super.parseExportFrom(node);
  5321. return null;
  5322. } else {
  5323. return this.flowParseTypeAlias(declarationNode);
  5324. }
  5325. } else if (this.isContextual(131)) {
  5326. node.exportKind = "type";
  5327. const declarationNode = this.startNode();
  5328. this.next();
  5329. return this.flowParseOpaqueType(declarationNode, false);
  5330. } else if (this.isContextual(129)) {
  5331. node.exportKind = "type";
  5332. const declarationNode = this.startNode();
  5333. this.next();
  5334. return this.flowParseInterface(declarationNode);
  5335. } else if (this.isContextual(126)) {
  5336. node.exportKind = "value";
  5337. const declarationNode = this.startNode();
  5338. this.next();
  5339. return this.flowParseEnumDeclaration(declarationNode);
  5340. } else {
  5341. return super.parseExportDeclaration(node);
  5342. }
  5343. }
  5344. eatExportStar(node) {
  5345. if (super.eatExportStar(node)) return true;
  5346. if (this.isContextual(130) && this.lookahead().type === 55) {
  5347. node.exportKind = "type";
  5348. this.next();
  5349. this.next();
  5350. return true;
  5351. }
  5352. return false;
  5353. }
  5354. maybeParseExportNamespaceSpecifier(node) {
  5355. const {
  5356. startLoc
  5357. } = this.state;
  5358. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  5359. if (hasNamespace && node.exportKind === "type") {
  5360. this.unexpected(startLoc);
  5361. }
  5362. return hasNamespace;
  5363. }
  5364. parseClassId(node, isStatement, optionalId) {
  5365. super.parseClassId(node, isStatement, optionalId);
  5366. if (this.match(47)) {
  5367. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5368. }
  5369. }
  5370. parseClassMember(classBody, member, state) {
  5371. const {
  5372. startLoc
  5373. } = this.state;
  5374. if (this.isContextual(125)) {
  5375. if (super.parseClassMemberFromModifier(classBody, member)) {
  5376. return;
  5377. }
  5378. member.declare = true;
  5379. }
  5380. super.parseClassMember(classBody, member, state);
  5381. if (member.declare) {
  5382. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  5383. this.raise(FlowErrors.DeclareClassElement, startLoc);
  5384. } else if (member.value) {
  5385. this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);
  5386. }
  5387. }
  5388. }
  5389. isIterator(word) {
  5390. return word === "iterator" || word === "asyncIterator";
  5391. }
  5392. readIterator() {
  5393. const word = super.readWord1();
  5394. const fullWord = "@@" + word;
  5395. if (!this.isIterator(word) || !this.state.inType) {
  5396. this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {
  5397. identifierName: fullWord
  5398. });
  5399. }
  5400. this.finishToken(132, fullWord);
  5401. }
  5402. getTokenFromCode(code) {
  5403. const next = this.input.charCodeAt(this.state.pos + 1);
  5404. if (code === 123 && next === 124) {
  5405. this.finishOp(6, 2);
  5406. } else if (this.state.inType && (code === 62 || code === 60)) {
  5407. this.finishOp(code === 62 ? 48 : 47, 1);
  5408. } else if (this.state.inType && code === 63) {
  5409. if (next === 46) {
  5410. this.finishOp(18, 2);
  5411. } else {
  5412. this.finishOp(17, 1);
  5413. }
  5414. } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) {
  5415. this.state.pos += 2;
  5416. this.readIterator();
  5417. } else {
  5418. super.getTokenFromCode(code);
  5419. }
  5420. }
  5421. isAssignable(node, isBinding) {
  5422. if (node.type === "TypeCastExpression") {
  5423. return this.isAssignable(node.expression, isBinding);
  5424. } else {
  5425. return super.isAssignable(node, isBinding);
  5426. }
  5427. }
  5428. toAssignable(node, isLHS = false) {
  5429. if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") {
  5430. node.left = this.typeCastToParameter(node.left);
  5431. }
  5432. super.toAssignable(node, isLHS);
  5433. }
  5434. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  5435. for (let i = 0; i < exprList.length; i++) {
  5436. const expr = exprList[i];
  5437. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  5438. exprList[i] = this.typeCastToParameter(expr);
  5439. }
  5440. }
  5441. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  5442. }
  5443. toReferencedList(exprList, isParenthesizedExpr) {
  5444. for (let i = 0; i < exprList.length; i++) {
  5445. var _expr$extra;
  5446. const expr = exprList[i];
  5447. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  5448. this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);
  5449. }
  5450. }
  5451. return exprList;
  5452. }
  5453. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  5454. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  5455. if (canBePattern && !this.state.maybeInArrowParameters) {
  5456. this.toReferencedList(node.elements);
  5457. }
  5458. return node;
  5459. }
  5460. isValidLVal(type, isParenthesized, binding) {
  5461. return type === "TypeCastExpression" || super.isValidLVal(type, isParenthesized, binding);
  5462. }
  5463. parseClassProperty(node) {
  5464. if (this.match(14)) {
  5465. node.typeAnnotation = this.flowParseTypeAnnotation();
  5466. }
  5467. return super.parseClassProperty(node);
  5468. }
  5469. parseClassPrivateProperty(node) {
  5470. if (this.match(14)) {
  5471. node.typeAnnotation = this.flowParseTypeAnnotation();
  5472. }
  5473. return super.parseClassPrivateProperty(node);
  5474. }
  5475. isClassMethod() {
  5476. return this.match(47) || super.isClassMethod();
  5477. }
  5478. isClassProperty() {
  5479. return this.match(14) || super.isClassProperty();
  5480. }
  5481. isNonstaticConstructor(method) {
  5482. return !this.match(14) && super.isNonstaticConstructor(method);
  5483. }
  5484. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5485. if (method.variance) {
  5486. this.unexpected(method.variance.loc.start);
  5487. }
  5488. delete method.variance;
  5489. if (this.match(47)) {
  5490. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5491. }
  5492. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5493. if (method.params && isConstructor) {
  5494. const params = method.params;
  5495. if (params.length > 0 && this.isThisParam(params[0])) {
  5496. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  5497. }
  5498. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  5499. const params = method.value.params;
  5500. if (params.length > 0 && this.isThisParam(params[0])) {
  5501. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  5502. }
  5503. }
  5504. }
  5505. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5506. if (method.variance) {
  5507. this.unexpected(method.variance.loc.start);
  5508. }
  5509. delete method.variance;
  5510. if (this.match(47)) {
  5511. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5512. }
  5513. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5514. }
  5515. parseClassSuper(node) {
  5516. super.parseClassSuper(node);
  5517. if (node.superClass && (this.match(47) || this.match(51))) {
  5518. {
  5519. node.superTypeParameters = this.flowParseTypeParameterInstantiationInExpression();
  5520. }
  5521. }
  5522. if (this.isContextual(113)) {
  5523. this.next();
  5524. const implemented = node.implements = [];
  5525. do {
  5526. const node = this.startNode();
  5527. node.id = this.flowParseRestrictedIdentifier(true);
  5528. if (this.match(47)) {
  5529. node.typeParameters = this.flowParseTypeParameterInstantiation();
  5530. } else {
  5531. node.typeParameters = null;
  5532. }
  5533. implemented.push(this.finishNode(node, "ClassImplements"));
  5534. } while (this.eat(12));
  5535. }
  5536. }
  5537. checkGetterSetterParams(method) {
  5538. super.checkGetterSetterParams(method);
  5539. const params = this.getObjectOrClassMethodParams(method);
  5540. if (params.length > 0) {
  5541. const param = params[0];
  5542. if (this.isThisParam(param) && method.kind === "get") {
  5543. this.raise(FlowErrors.GetterMayNotHaveThisParam, param);
  5544. } else if (this.isThisParam(param)) {
  5545. this.raise(FlowErrors.SetterMayNotHaveThisParam, param);
  5546. }
  5547. }
  5548. }
  5549. parsePropertyNamePrefixOperator(node) {
  5550. node.variance = this.flowParseVariance();
  5551. }
  5552. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  5553. if (prop.variance) {
  5554. this.unexpected(prop.variance.loc.start);
  5555. }
  5556. delete prop.variance;
  5557. let typeParameters;
  5558. if (this.match(47) && !isAccessor) {
  5559. typeParameters = this.flowParseTypeParameterDeclaration();
  5560. if (!this.match(10)) this.unexpected();
  5561. }
  5562. const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  5563. if (typeParameters) {
  5564. (result.value || result).typeParameters = typeParameters;
  5565. }
  5566. return result;
  5567. }
  5568. parseFunctionParamType(param) {
  5569. if (this.eat(17)) {
  5570. if (param.type !== "Identifier") {
  5571. this.raise(FlowErrors.PatternIsOptional, param);
  5572. }
  5573. if (this.isThisParam(param)) {
  5574. this.raise(FlowErrors.ThisParamMayNotBeOptional, param);
  5575. }
  5576. param.optional = true;
  5577. }
  5578. if (this.match(14)) {
  5579. param.typeAnnotation = this.flowParseTypeAnnotation();
  5580. } else if (this.isThisParam(param)) {
  5581. this.raise(FlowErrors.ThisParamAnnotationRequired, param);
  5582. }
  5583. if (this.match(29) && this.isThisParam(param)) {
  5584. this.raise(FlowErrors.ThisParamNoDefault, param);
  5585. }
  5586. this.resetEndLocation(param);
  5587. return param;
  5588. }
  5589. parseMaybeDefault(startLoc, left) {
  5590. const node = super.parseMaybeDefault(startLoc, left);
  5591. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5592. this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);
  5593. }
  5594. return node;
  5595. }
  5596. checkImportReflection(node) {
  5597. super.checkImportReflection(node);
  5598. if (node.module && node.importKind !== "value") {
  5599. this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  5600. }
  5601. }
  5602. parseImportSpecifierLocal(node, specifier, type) {
  5603. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  5604. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  5605. }
  5606. isPotentialImportPhase(isExport) {
  5607. if (super.isPotentialImportPhase(isExport)) return true;
  5608. if (this.isContextual(130)) {
  5609. if (!isExport) return true;
  5610. const ch = this.lookaheadCharCode();
  5611. return ch === 123 || ch === 42;
  5612. }
  5613. return !isExport && this.isContextual(87);
  5614. }
  5615. applyImportPhase(node, isExport, phase, loc) {
  5616. super.applyImportPhase(node, isExport, phase, loc);
  5617. if (isExport) {
  5618. if (!phase && this.match(65)) {
  5619. return;
  5620. }
  5621. node.exportKind = phase === "type" ? phase : "value";
  5622. } else {
  5623. if (phase === "type" && this.match(55)) this.unexpected();
  5624. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  5625. }
  5626. }
  5627. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  5628. const firstIdent = specifier.imported;
  5629. let specifierTypeKind = null;
  5630. if (firstIdent.type === "Identifier") {
  5631. if (firstIdent.name === "type") {
  5632. specifierTypeKind = "type";
  5633. } else if (firstIdent.name === "typeof") {
  5634. specifierTypeKind = "typeof";
  5635. }
  5636. }
  5637. let isBinding = false;
  5638. if (this.isContextual(93) && !this.isLookaheadContextual("as")) {
  5639. const as_ident = this.parseIdentifier(true);
  5640. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  5641. specifier.imported = as_ident;
  5642. specifier.importKind = specifierTypeKind;
  5643. specifier.local = cloneIdentifier(as_ident);
  5644. } else {
  5645. specifier.imported = firstIdent;
  5646. specifier.importKind = null;
  5647. specifier.local = this.parseIdentifier();
  5648. }
  5649. } else {
  5650. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  5651. specifier.imported = this.parseIdentifier(true);
  5652. specifier.importKind = specifierTypeKind;
  5653. } else {
  5654. if (importedIsString) {
  5655. throw this.raise(Errors.ImportBindingIsString, specifier, {
  5656. importName: firstIdent.value
  5657. });
  5658. }
  5659. specifier.imported = firstIdent;
  5660. specifier.importKind = null;
  5661. }
  5662. if (this.eatContextual(93)) {
  5663. specifier.local = this.parseIdentifier();
  5664. } else {
  5665. isBinding = true;
  5666. specifier.local = cloneIdentifier(specifier.imported);
  5667. }
  5668. }
  5669. const specifierIsTypeImport = hasTypeImportKind(specifier);
  5670. if (isInTypeOnlyImport && specifierIsTypeImport) {
  5671. this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);
  5672. }
  5673. if (isInTypeOnlyImport || specifierIsTypeImport) {
  5674. this.checkReservedType(specifier.local.name, specifier.local.loc.start, true);
  5675. }
  5676. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  5677. this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true);
  5678. }
  5679. return this.finishImportSpecifier(specifier, "ImportSpecifier");
  5680. }
  5681. parseBindingAtom() {
  5682. switch (this.state.type) {
  5683. case 78:
  5684. return this.parseIdentifier(true);
  5685. default:
  5686. return super.parseBindingAtom();
  5687. }
  5688. }
  5689. parseFunctionParams(node, isConstructor) {
  5690. const kind = node.kind;
  5691. if (kind !== "get" && kind !== "set" && this.match(47)) {
  5692. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5693. }
  5694. super.parseFunctionParams(node, isConstructor);
  5695. }
  5696. parseVarId(decl, kind) {
  5697. super.parseVarId(decl, kind);
  5698. if (this.match(14)) {
  5699. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5700. this.resetEndLocation(decl.id);
  5701. }
  5702. }
  5703. parseAsyncArrowFromCallExpression(node, call) {
  5704. if (this.match(14)) {
  5705. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5706. this.state.noAnonFunctionType = true;
  5707. node.returnType = this.flowParseTypeAnnotation();
  5708. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5709. }
  5710. return super.parseAsyncArrowFromCallExpression(node, call);
  5711. }
  5712. shouldParseAsyncArrow() {
  5713. return this.match(14) || super.shouldParseAsyncArrow();
  5714. }
  5715. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  5716. var _jsx;
  5717. let state = null;
  5718. let jsx;
  5719. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  5720. state = this.state.clone();
  5721. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  5722. if (!jsx.error) return jsx.node;
  5723. const {
  5724. context
  5725. } = this.state;
  5726. const currentContext = context[context.length - 1];
  5727. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  5728. context.pop();
  5729. }
  5730. }
  5731. if ((_jsx = jsx) != null && _jsx.error || this.match(47)) {
  5732. var _jsx2, _jsx3;
  5733. state = state || this.state.clone();
  5734. let typeParameters;
  5735. const arrow = this.tryParse(abort => {
  5736. var _arrowExpression$extr;
  5737. typeParameters = this.flowParseTypeParameterDeclaration();
  5738. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  5739. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5740. this.resetStartLocationFromNode(result, typeParameters);
  5741. return result;
  5742. });
  5743. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  5744. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  5745. if (expr.type !== "ArrowFunctionExpression") abort();
  5746. expr.typeParameters = typeParameters;
  5747. this.resetStartLocationFromNode(expr, typeParameters);
  5748. return arrowExpression;
  5749. }, state);
  5750. let arrowExpression = null;
  5751. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  5752. if (!arrow.error && !arrow.aborted) {
  5753. if (arrow.node.async) {
  5754. this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters);
  5755. }
  5756. return arrow.node;
  5757. }
  5758. arrowExpression = arrow.node;
  5759. }
  5760. if ((_jsx2 = jsx) != null && _jsx2.node) {
  5761. this.state = jsx.failState;
  5762. return jsx.node;
  5763. }
  5764. if (arrowExpression) {
  5765. this.state = arrow.failState;
  5766. return arrowExpression;
  5767. }
  5768. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  5769. if (arrow.thrown) throw arrow.error;
  5770. throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters);
  5771. }
  5772. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5773. }
  5774. parseArrow(node) {
  5775. if (this.match(14)) {
  5776. const result = this.tryParse(() => {
  5777. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5778. this.state.noAnonFunctionType = true;
  5779. const typeNode = this.startNode();
  5780. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5781. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5782. if (this.canInsertSemicolon()) this.unexpected();
  5783. if (!this.match(19)) this.unexpected();
  5784. return typeNode;
  5785. });
  5786. if (result.thrown) return null;
  5787. if (result.error) this.state = result.failState;
  5788. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  5789. }
  5790. return super.parseArrow(node);
  5791. }
  5792. shouldParseArrow(params) {
  5793. return this.match(14) || super.shouldParseArrow(params);
  5794. }
  5795. setArrowFunctionParameters(node, params) {
  5796. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  5797. node.params = params;
  5798. } else {
  5799. super.setArrowFunctionParameters(node, params);
  5800. }
  5801. }
  5802. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  5803. if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  5804. return;
  5805. }
  5806. for (let i = 0; i < node.params.length; i++) {
  5807. if (this.isThisParam(node.params[i]) && i > 0) {
  5808. this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);
  5809. }
  5810. }
  5811. super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged);
  5812. }
  5813. parseParenAndDistinguishExpression(canBeArrow) {
  5814. return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)));
  5815. }
  5816. parseSubscripts(base, startLoc, noCalls) {
  5817. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) {
  5818. this.next();
  5819. const node = this.startNodeAt(startLoc);
  5820. node.callee = base;
  5821. node.arguments = super.parseCallExpressionArguments(11);
  5822. base = this.finishNode(node, "CallExpression");
  5823. } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) {
  5824. const state = this.state.clone();
  5825. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state);
  5826. if (!arrow.error && !arrow.aborted) return arrow.node;
  5827. const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state);
  5828. if (result.node && !result.error) return result.node;
  5829. if (arrow.node) {
  5830. this.state = arrow.failState;
  5831. return arrow.node;
  5832. }
  5833. if (result.node) {
  5834. this.state = result.failState;
  5835. return result.node;
  5836. }
  5837. throw arrow.error || result.error;
  5838. }
  5839. return super.parseSubscripts(base, startLoc, noCalls);
  5840. }
  5841. parseSubscript(base, startLoc, noCalls, subscriptState) {
  5842. if (this.match(18) && this.isLookaheadToken_lt()) {
  5843. subscriptState.optionalChainMember = true;
  5844. if (noCalls) {
  5845. subscriptState.stop = true;
  5846. return base;
  5847. }
  5848. this.next();
  5849. const node = this.startNodeAt(startLoc);
  5850. node.callee = base;
  5851. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  5852. this.expect(10);
  5853. node.arguments = this.parseCallExpressionArguments(11);
  5854. node.optional = true;
  5855. return this.finishCallExpression(node, true);
  5856. } else if (!noCalls && this.shouldParseTypes() && (this.match(47) || this.match(51))) {
  5857. const node = this.startNodeAt(startLoc);
  5858. node.callee = base;
  5859. const result = this.tryParse(() => {
  5860. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  5861. this.expect(10);
  5862. node.arguments = super.parseCallExpressionArguments(11);
  5863. if (subscriptState.optionalChainMember) {
  5864. node.optional = false;
  5865. }
  5866. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  5867. });
  5868. if (result.node) {
  5869. if (result.error) this.state = result.failState;
  5870. return result.node;
  5871. }
  5872. }
  5873. return super.parseSubscript(base, startLoc, noCalls, subscriptState);
  5874. }
  5875. parseNewCallee(node) {
  5876. super.parseNewCallee(node);
  5877. let targs = null;
  5878. if (this.shouldParseTypes() && this.match(47)) {
  5879. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  5880. }
  5881. node.typeArguments = targs;
  5882. }
  5883. parseAsyncArrowWithTypeParameters(startLoc) {
  5884. const node = this.startNodeAt(startLoc);
  5885. this.parseFunctionParams(node, false);
  5886. if (!this.parseArrow(node)) return;
  5887. return super.parseArrowExpression(node, undefined, true);
  5888. }
  5889. readToken_mult_modulo(code) {
  5890. const next = this.input.charCodeAt(this.state.pos + 1);
  5891. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  5892. this.state.hasFlowComment = false;
  5893. this.state.pos += 2;
  5894. this.nextToken();
  5895. return;
  5896. }
  5897. super.readToken_mult_modulo(code);
  5898. }
  5899. readToken_pipe_amp(code) {
  5900. const next = this.input.charCodeAt(this.state.pos + 1);
  5901. if (code === 124 && next === 125) {
  5902. this.finishOp(9, 2);
  5903. return;
  5904. }
  5905. super.readToken_pipe_amp(code);
  5906. }
  5907. parseTopLevel(file, program) {
  5908. const fileNode = super.parseTopLevel(file, program);
  5909. if (this.state.hasFlowComment) {
  5910. this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition());
  5911. }
  5912. return fileNode;
  5913. }
  5914. skipBlockComment() {
  5915. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  5916. if (this.state.hasFlowComment) {
  5917. throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);
  5918. }
  5919. this.hasFlowCommentCompletion();
  5920. const commentSkip = this.skipFlowComment();
  5921. if (commentSkip) {
  5922. this.state.pos += commentSkip;
  5923. this.state.hasFlowComment = true;
  5924. }
  5925. return;
  5926. }
  5927. return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/");
  5928. }
  5929. skipFlowComment() {
  5930. const {
  5931. pos
  5932. } = this.state;
  5933. let shiftToFirstNonWhiteSpace = 2;
  5934. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  5935. shiftToFirstNonWhiteSpace++;
  5936. }
  5937. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  5938. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  5939. if (ch2 === 58 && ch3 === 58) {
  5940. return shiftToFirstNonWhiteSpace + 2;
  5941. }
  5942. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  5943. return shiftToFirstNonWhiteSpace + 12;
  5944. }
  5945. if (ch2 === 58 && ch3 !== 58) {
  5946. return shiftToFirstNonWhiteSpace;
  5947. }
  5948. return false;
  5949. }
  5950. hasFlowCommentCompletion() {
  5951. const end = this.input.indexOf("*/", this.state.pos);
  5952. if (end === -1) {
  5953. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  5954. }
  5955. }
  5956. flowEnumErrorBooleanMemberNotInitialized(loc, {
  5957. enumName,
  5958. memberName
  5959. }) {
  5960. this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {
  5961. memberName,
  5962. enumName
  5963. });
  5964. }
  5965. flowEnumErrorInvalidMemberInitializer(loc, enumContext) {
  5966. return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext);
  5967. }
  5968. flowEnumErrorNumberMemberNotInitialized(loc, details) {
  5969. this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);
  5970. }
  5971. flowEnumErrorStringMemberInconsistentlyInitialized(node, details) {
  5972. this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details);
  5973. }
  5974. flowEnumMemberInit() {
  5975. const startLoc = this.state.startLoc;
  5976. const endOfInit = () => this.match(12) || this.match(8);
  5977. switch (this.state.type) {
  5978. case 135:
  5979. {
  5980. const literal = this.parseNumericLiteral(this.state.value);
  5981. if (endOfInit()) {
  5982. return {
  5983. type: "number",
  5984. loc: literal.loc.start,
  5985. value: literal
  5986. };
  5987. }
  5988. return {
  5989. type: "invalid",
  5990. loc: startLoc
  5991. };
  5992. }
  5993. case 134:
  5994. {
  5995. const literal = this.parseStringLiteral(this.state.value);
  5996. if (endOfInit()) {
  5997. return {
  5998. type: "string",
  5999. loc: literal.loc.start,
  6000. value: literal
  6001. };
  6002. }
  6003. return {
  6004. type: "invalid",
  6005. loc: startLoc
  6006. };
  6007. }
  6008. case 85:
  6009. case 86:
  6010. {
  6011. const literal = this.parseBooleanLiteral(this.match(85));
  6012. if (endOfInit()) {
  6013. return {
  6014. type: "boolean",
  6015. loc: literal.loc.start,
  6016. value: literal
  6017. };
  6018. }
  6019. return {
  6020. type: "invalid",
  6021. loc: startLoc
  6022. };
  6023. }
  6024. default:
  6025. return {
  6026. type: "invalid",
  6027. loc: startLoc
  6028. };
  6029. }
  6030. }
  6031. flowEnumMemberRaw() {
  6032. const loc = this.state.startLoc;
  6033. const id = this.parseIdentifier(true);
  6034. const init = this.eat(29) ? this.flowEnumMemberInit() : {
  6035. type: "none",
  6036. loc
  6037. };
  6038. return {
  6039. id,
  6040. init
  6041. };
  6042. }
  6043. flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) {
  6044. const {
  6045. explicitType
  6046. } = context;
  6047. if (explicitType === null) {
  6048. return;
  6049. }
  6050. if (explicitType !== expectedType) {
  6051. this.flowEnumErrorInvalidMemberInitializer(loc, context);
  6052. }
  6053. }
  6054. flowEnumMembers({
  6055. enumName,
  6056. explicitType
  6057. }) {
  6058. const seenNames = new Set();
  6059. const members = {
  6060. booleanMembers: [],
  6061. numberMembers: [],
  6062. stringMembers: [],
  6063. defaultedMembers: []
  6064. };
  6065. let hasUnknownMembers = false;
  6066. while (!this.match(8)) {
  6067. if (this.eat(21)) {
  6068. hasUnknownMembers = true;
  6069. break;
  6070. }
  6071. const memberNode = this.startNode();
  6072. const {
  6073. id,
  6074. init
  6075. } = this.flowEnumMemberRaw();
  6076. const memberName = id.name;
  6077. if (memberName === "") {
  6078. continue;
  6079. }
  6080. if (/^[a-z]/.test(memberName)) {
  6081. this.raise(FlowErrors.EnumInvalidMemberName, id, {
  6082. memberName,
  6083. suggestion: memberName[0].toUpperCase() + memberName.slice(1),
  6084. enumName
  6085. });
  6086. }
  6087. if (seenNames.has(memberName)) {
  6088. this.raise(FlowErrors.EnumDuplicateMemberName, id, {
  6089. memberName,
  6090. enumName
  6091. });
  6092. }
  6093. seenNames.add(memberName);
  6094. const context = {
  6095. enumName,
  6096. explicitType,
  6097. memberName
  6098. };
  6099. memberNode.id = id;
  6100. switch (init.type) {
  6101. case "boolean":
  6102. {
  6103. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean");
  6104. memberNode.init = init.value;
  6105. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  6106. break;
  6107. }
  6108. case "number":
  6109. {
  6110. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number");
  6111. memberNode.init = init.value;
  6112. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  6113. break;
  6114. }
  6115. case "string":
  6116. {
  6117. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string");
  6118. memberNode.init = init.value;
  6119. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  6120. break;
  6121. }
  6122. case "invalid":
  6123. {
  6124. throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);
  6125. }
  6126. case "none":
  6127. {
  6128. switch (explicitType) {
  6129. case "boolean":
  6130. this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context);
  6131. break;
  6132. case "number":
  6133. this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);
  6134. break;
  6135. default:
  6136. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  6137. }
  6138. }
  6139. }
  6140. if (!this.match(8)) {
  6141. this.expect(12);
  6142. }
  6143. }
  6144. return {
  6145. members,
  6146. hasUnknownMembers
  6147. };
  6148. }
  6149. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  6150. enumName
  6151. }) {
  6152. if (initializedMembers.length === 0) {
  6153. return defaultedMembers;
  6154. } else if (defaultedMembers.length === 0) {
  6155. return initializedMembers;
  6156. } else if (defaultedMembers.length > initializedMembers.length) {
  6157. for (const member of initializedMembers) {
  6158. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  6159. enumName
  6160. });
  6161. }
  6162. return defaultedMembers;
  6163. } else {
  6164. for (const member of defaultedMembers) {
  6165. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  6166. enumName
  6167. });
  6168. }
  6169. return initializedMembers;
  6170. }
  6171. }
  6172. flowEnumParseExplicitType({
  6173. enumName
  6174. }) {
  6175. if (!this.eatContextual(102)) return null;
  6176. if (!tokenIsIdentifier(this.state.type)) {
  6177. throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, {
  6178. enumName
  6179. });
  6180. }
  6181. const {
  6182. value
  6183. } = this.state;
  6184. this.next();
  6185. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  6186. this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {
  6187. enumName,
  6188. invalidEnumType: value
  6189. });
  6190. }
  6191. return value;
  6192. }
  6193. flowEnumBody(node, id) {
  6194. const enumName = id.name;
  6195. const nameLoc = id.loc.start;
  6196. const explicitType = this.flowEnumParseExplicitType({
  6197. enumName
  6198. });
  6199. this.expect(5);
  6200. const {
  6201. members,
  6202. hasUnknownMembers
  6203. } = this.flowEnumMembers({
  6204. enumName,
  6205. explicitType
  6206. });
  6207. node.hasUnknownMembers = hasUnknownMembers;
  6208. switch (explicitType) {
  6209. case "boolean":
  6210. node.explicitType = true;
  6211. node.members = members.booleanMembers;
  6212. this.expect(8);
  6213. return this.finishNode(node, "EnumBooleanBody");
  6214. case "number":
  6215. node.explicitType = true;
  6216. node.members = members.numberMembers;
  6217. this.expect(8);
  6218. return this.finishNode(node, "EnumNumberBody");
  6219. case "string":
  6220. node.explicitType = true;
  6221. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6222. enumName
  6223. });
  6224. this.expect(8);
  6225. return this.finishNode(node, "EnumStringBody");
  6226. case "symbol":
  6227. node.members = members.defaultedMembers;
  6228. this.expect(8);
  6229. return this.finishNode(node, "EnumSymbolBody");
  6230. default:
  6231. {
  6232. const empty = () => {
  6233. node.members = [];
  6234. this.expect(8);
  6235. return this.finishNode(node, "EnumStringBody");
  6236. };
  6237. node.explicitType = false;
  6238. const boolsLen = members.booleanMembers.length;
  6239. const numsLen = members.numberMembers.length;
  6240. const strsLen = members.stringMembers.length;
  6241. const defaultedLen = members.defaultedMembers.length;
  6242. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  6243. return empty();
  6244. } else if (!boolsLen && !numsLen) {
  6245. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6246. enumName
  6247. });
  6248. this.expect(8);
  6249. return this.finishNode(node, "EnumStringBody");
  6250. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  6251. for (const member of members.defaultedMembers) {
  6252. this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {
  6253. enumName,
  6254. memberName: member.id.name
  6255. });
  6256. }
  6257. node.members = members.booleanMembers;
  6258. this.expect(8);
  6259. return this.finishNode(node, "EnumBooleanBody");
  6260. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  6261. for (const member of members.defaultedMembers) {
  6262. this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {
  6263. enumName,
  6264. memberName: member.id.name
  6265. });
  6266. }
  6267. node.members = members.numberMembers;
  6268. this.expect(8);
  6269. return this.finishNode(node, "EnumNumberBody");
  6270. } else {
  6271. this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {
  6272. enumName
  6273. });
  6274. return empty();
  6275. }
  6276. }
  6277. }
  6278. }
  6279. flowParseEnumDeclaration(node) {
  6280. const id = this.parseIdentifier();
  6281. node.id = id;
  6282. node.body = this.flowEnumBody(this.startNode(), id);
  6283. return this.finishNode(node, "EnumDeclaration");
  6284. }
  6285. jsxParseOpeningElementAfterName(node) {
  6286. if (this.shouldParseTypes()) {
  6287. if (this.match(47) || this.match(51)) {
  6288. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  6289. }
  6290. }
  6291. return super.jsxParseOpeningElementAfterName(node);
  6292. }
  6293. isLookaheadToken_lt() {
  6294. const next = this.nextTokenStart();
  6295. if (this.input.charCodeAt(next) === 60) {
  6296. const afterNext = this.input.charCodeAt(next + 1);
  6297. return afterNext !== 60 && afterNext !== 61;
  6298. }
  6299. return false;
  6300. }
  6301. reScan_lt_gt() {
  6302. const {
  6303. type
  6304. } = this.state;
  6305. if (type === 47) {
  6306. this.state.pos -= 1;
  6307. this.readToken_lt();
  6308. } else if (type === 48) {
  6309. this.state.pos -= 1;
  6310. this.readToken_gt();
  6311. }
  6312. }
  6313. reScan_lt() {
  6314. const {
  6315. type
  6316. } = this.state;
  6317. if (type === 51) {
  6318. this.state.pos -= 2;
  6319. this.finishOp(47, 1);
  6320. return 47;
  6321. }
  6322. return type;
  6323. }
  6324. maybeUnwrapTypeCastExpression(node) {
  6325. return node.type === "TypeCastExpression" ? node.expression : node;
  6326. }
  6327. };
  6328. const entities = {
  6329. __proto__: null,
  6330. quot: "\u0022",
  6331. amp: "&",
  6332. apos: "\u0027",
  6333. lt: "<",
  6334. gt: ">",
  6335. nbsp: "\u00A0",
  6336. iexcl: "\u00A1",
  6337. cent: "\u00A2",
  6338. pound: "\u00A3",
  6339. curren: "\u00A4",
  6340. yen: "\u00A5",
  6341. brvbar: "\u00A6",
  6342. sect: "\u00A7",
  6343. uml: "\u00A8",
  6344. copy: "\u00A9",
  6345. ordf: "\u00AA",
  6346. laquo: "\u00AB",
  6347. not: "\u00AC",
  6348. shy: "\u00AD",
  6349. reg: "\u00AE",
  6350. macr: "\u00AF",
  6351. deg: "\u00B0",
  6352. plusmn: "\u00B1",
  6353. sup2: "\u00B2",
  6354. sup3: "\u00B3",
  6355. acute: "\u00B4",
  6356. micro: "\u00B5",
  6357. para: "\u00B6",
  6358. middot: "\u00B7",
  6359. cedil: "\u00B8",
  6360. sup1: "\u00B9",
  6361. ordm: "\u00BA",
  6362. raquo: "\u00BB",
  6363. frac14: "\u00BC",
  6364. frac12: "\u00BD",
  6365. frac34: "\u00BE",
  6366. iquest: "\u00BF",
  6367. Agrave: "\u00C0",
  6368. Aacute: "\u00C1",
  6369. Acirc: "\u00C2",
  6370. Atilde: "\u00C3",
  6371. Auml: "\u00C4",
  6372. Aring: "\u00C5",
  6373. AElig: "\u00C6",
  6374. Ccedil: "\u00C7",
  6375. Egrave: "\u00C8",
  6376. Eacute: "\u00C9",
  6377. Ecirc: "\u00CA",
  6378. Euml: "\u00CB",
  6379. Igrave: "\u00CC",
  6380. Iacute: "\u00CD",
  6381. Icirc: "\u00CE",
  6382. Iuml: "\u00CF",
  6383. ETH: "\u00D0",
  6384. Ntilde: "\u00D1",
  6385. Ograve: "\u00D2",
  6386. Oacute: "\u00D3",
  6387. Ocirc: "\u00D4",
  6388. Otilde: "\u00D5",
  6389. Ouml: "\u00D6",
  6390. times: "\u00D7",
  6391. Oslash: "\u00D8",
  6392. Ugrave: "\u00D9",
  6393. Uacute: "\u00DA",
  6394. Ucirc: "\u00DB",
  6395. Uuml: "\u00DC",
  6396. Yacute: "\u00DD",
  6397. THORN: "\u00DE",
  6398. szlig: "\u00DF",
  6399. agrave: "\u00E0",
  6400. aacute: "\u00E1",
  6401. acirc: "\u00E2",
  6402. atilde: "\u00E3",
  6403. auml: "\u00E4",
  6404. aring: "\u00E5",
  6405. aelig: "\u00E6",
  6406. ccedil: "\u00E7",
  6407. egrave: "\u00E8",
  6408. eacute: "\u00E9",
  6409. ecirc: "\u00EA",
  6410. euml: "\u00EB",
  6411. igrave: "\u00EC",
  6412. iacute: "\u00ED",
  6413. icirc: "\u00EE",
  6414. iuml: "\u00EF",
  6415. eth: "\u00F0",
  6416. ntilde: "\u00F1",
  6417. ograve: "\u00F2",
  6418. oacute: "\u00F3",
  6419. ocirc: "\u00F4",
  6420. otilde: "\u00F5",
  6421. ouml: "\u00F6",
  6422. divide: "\u00F7",
  6423. oslash: "\u00F8",
  6424. ugrave: "\u00F9",
  6425. uacute: "\u00FA",
  6426. ucirc: "\u00FB",
  6427. uuml: "\u00FC",
  6428. yacute: "\u00FD",
  6429. thorn: "\u00FE",
  6430. yuml: "\u00FF",
  6431. OElig: "\u0152",
  6432. oelig: "\u0153",
  6433. Scaron: "\u0160",
  6434. scaron: "\u0161",
  6435. Yuml: "\u0178",
  6436. fnof: "\u0192",
  6437. circ: "\u02C6",
  6438. tilde: "\u02DC",
  6439. Alpha: "\u0391",
  6440. Beta: "\u0392",
  6441. Gamma: "\u0393",
  6442. Delta: "\u0394",
  6443. Epsilon: "\u0395",
  6444. Zeta: "\u0396",
  6445. Eta: "\u0397",
  6446. Theta: "\u0398",
  6447. Iota: "\u0399",
  6448. Kappa: "\u039A",
  6449. Lambda: "\u039B",
  6450. Mu: "\u039C",
  6451. Nu: "\u039D",
  6452. Xi: "\u039E",
  6453. Omicron: "\u039F",
  6454. Pi: "\u03A0",
  6455. Rho: "\u03A1",
  6456. Sigma: "\u03A3",
  6457. Tau: "\u03A4",
  6458. Upsilon: "\u03A5",
  6459. Phi: "\u03A6",
  6460. Chi: "\u03A7",
  6461. Psi: "\u03A8",
  6462. Omega: "\u03A9",
  6463. alpha: "\u03B1",
  6464. beta: "\u03B2",
  6465. gamma: "\u03B3",
  6466. delta: "\u03B4",
  6467. epsilon: "\u03B5",
  6468. zeta: "\u03B6",
  6469. eta: "\u03B7",
  6470. theta: "\u03B8",
  6471. iota: "\u03B9",
  6472. kappa: "\u03BA",
  6473. lambda: "\u03BB",
  6474. mu: "\u03BC",
  6475. nu: "\u03BD",
  6476. xi: "\u03BE",
  6477. omicron: "\u03BF",
  6478. pi: "\u03C0",
  6479. rho: "\u03C1",
  6480. sigmaf: "\u03C2",
  6481. sigma: "\u03C3",
  6482. tau: "\u03C4",
  6483. upsilon: "\u03C5",
  6484. phi: "\u03C6",
  6485. chi: "\u03C7",
  6486. psi: "\u03C8",
  6487. omega: "\u03C9",
  6488. thetasym: "\u03D1",
  6489. upsih: "\u03D2",
  6490. piv: "\u03D6",
  6491. ensp: "\u2002",
  6492. emsp: "\u2003",
  6493. thinsp: "\u2009",
  6494. zwnj: "\u200C",
  6495. zwj: "\u200D",
  6496. lrm: "\u200E",
  6497. rlm: "\u200F",
  6498. ndash: "\u2013",
  6499. mdash: "\u2014",
  6500. lsquo: "\u2018",
  6501. rsquo: "\u2019",
  6502. sbquo: "\u201A",
  6503. ldquo: "\u201C",
  6504. rdquo: "\u201D",
  6505. bdquo: "\u201E",
  6506. dagger: "\u2020",
  6507. Dagger: "\u2021",
  6508. bull: "\u2022",
  6509. hellip: "\u2026",
  6510. permil: "\u2030",
  6511. prime: "\u2032",
  6512. Prime: "\u2033",
  6513. lsaquo: "\u2039",
  6514. rsaquo: "\u203A",
  6515. oline: "\u203E",
  6516. frasl: "\u2044",
  6517. euro: "\u20AC",
  6518. image: "\u2111",
  6519. weierp: "\u2118",
  6520. real: "\u211C",
  6521. trade: "\u2122",
  6522. alefsym: "\u2135",
  6523. larr: "\u2190",
  6524. uarr: "\u2191",
  6525. rarr: "\u2192",
  6526. darr: "\u2193",
  6527. harr: "\u2194",
  6528. crarr: "\u21B5",
  6529. lArr: "\u21D0",
  6530. uArr: "\u21D1",
  6531. rArr: "\u21D2",
  6532. dArr: "\u21D3",
  6533. hArr: "\u21D4",
  6534. forall: "\u2200",
  6535. part: "\u2202",
  6536. exist: "\u2203",
  6537. empty: "\u2205",
  6538. nabla: "\u2207",
  6539. isin: "\u2208",
  6540. notin: "\u2209",
  6541. ni: "\u220B",
  6542. prod: "\u220F",
  6543. sum: "\u2211",
  6544. minus: "\u2212",
  6545. lowast: "\u2217",
  6546. radic: "\u221A",
  6547. prop: "\u221D",
  6548. infin: "\u221E",
  6549. ang: "\u2220",
  6550. and: "\u2227",
  6551. or: "\u2228",
  6552. cap: "\u2229",
  6553. cup: "\u222A",
  6554. int: "\u222B",
  6555. there4: "\u2234",
  6556. sim: "\u223C",
  6557. cong: "\u2245",
  6558. asymp: "\u2248",
  6559. ne: "\u2260",
  6560. equiv: "\u2261",
  6561. le: "\u2264",
  6562. ge: "\u2265",
  6563. sub: "\u2282",
  6564. sup: "\u2283",
  6565. nsub: "\u2284",
  6566. sube: "\u2286",
  6567. supe: "\u2287",
  6568. oplus: "\u2295",
  6569. otimes: "\u2297",
  6570. perp: "\u22A5",
  6571. sdot: "\u22C5",
  6572. lceil: "\u2308",
  6573. rceil: "\u2309",
  6574. lfloor: "\u230A",
  6575. rfloor: "\u230B",
  6576. lang: "\u2329",
  6577. rang: "\u232A",
  6578. loz: "\u25CA",
  6579. spades: "\u2660",
  6580. clubs: "\u2663",
  6581. hearts: "\u2665",
  6582. diams: "\u2666"
  6583. };
  6584. const JsxErrors = ParseErrorEnum`jsx`({
  6585. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  6586. MissingClosingTagElement: ({
  6587. openingTagName
  6588. }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`,
  6589. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  6590. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  6591. UnexpectedToken: ({
  6592. unexpected,
  6593. HTMLEntity
  6594. }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,
  6595. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  6596. UnterminatedJsxContent: "Unterminated JSX contents.",
  6597. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  6598. });
  6599. function isFragment(object) {
  6600. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  6601. }
  6602. function getQualifiedJSXName(object) {
  6603. if (object.type === "JSXIdentifier") {
  6604. return object.name;
  6605. }
  6606. if (object.type === "JSXNamespacedName") {
  6607. return object.namespace.name + ":" + object.name.name;
  6608. }
  6609. if (object.type === "JSXMemberExpression") {
  6610. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  6611. }
  6612. throw new Error("Node had unexpected type: " + object.type);
  6613. }
  6614. var jsx = superClass => class JSXParserMixin extends superClass {
  6615. jsxReadToken() {
  6616. let out = "";
  6617. let chunkStart = this.state.pos;
  6618. for (;;) {
  6619. if (this.state.pos >= this.length) {
  6620. throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc);
  6621. }
  6622. const ch = this.input.charCodeAt(this.state.pos);
  6623. switch (ch) {
  6624. case 60:
  6625. case 123:
  6626. if (this.state.pos === this.state.start) {
  6627. if (ch === 60 && this.state.canStartJSXElement) {
  6628. ++this.state.pos;
  6629. this.finishToken(143);
  6630. } else {
  6631. super.getTokenFromCode(ch);
  6632. }
  6633. return;
  6634. }
  6635. out += this.input.slice(chunkStart, this.state.pos);
  6636. this.finishToken(142, out);
  6637. return;
  6638. case 38:
  6639. out += this.input.slice(chunkStart, this.state.pos);
  6640. out += this.jsxReadEntity();
  6641. chunkStart = this.state.pos;
  6642. break;
  6643. case 62:
  6644. case 125:
  6645. default:
  6646. if (isNewLine(ch)) {
  6647. out += this.input.slice(chunkStart, this.state.pos);
  6648. out += this.jsxReadNewLine(true);
  6649. chunkStart = this.state.pos;
  6650. } else {
  6651. ++this.state.pos;
  6652. }
  6653. }
  6654. }
  6655. }
  6656. jsxReadNewLine(normalizeCRLF) {
  6657. const ch = this.input.charCodeAt(this.state.pos);
  6658. let out;
  6659. ++this.state.pos;
  6660. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  6661. ++this.state.pos;
  6662. out = normalizeCRLF ? "\n" : "\r\n";
  6663. } else {
  6664. out = String.fromCharCode(ch);
  6665. }
  6666. ++this.state.curLine;
  6667. this.state.lineStart = this.state.pos;
  6668. return out;
  6669. }
  6670. jsxReadString(quote) {
  6671. let out = "";
  6672. let chunkStart = ++this.state.pos;
  6673. for (;;) {
  6674. if (this.state.pos >= this.length) {
  6675. throw this.raise(Errors.UnterminatedString, this.state.startLoc);
  6676. }
  6677. const ch = this.input.charCodeAt(this.state.pos);
  6678. if (ch === quote) break;
  6679. if (ch === 38) {
  6680. out += this.input.slice(chunkStart, this.state.pos);
  6681. out += this.jsxReadEntity();
  6682. chunkStart = this.state.pos;
  6683. } else if (isNewLine(ch)) {
  6684. out += this.input.slice(chunkStart, this.state.pos);
  6685. out += this.jsxReadNewLine(false);
  6686. chunkStart = this.state.pos;
  6687. } else {
  6688. ++this.state.pos;
  6689. }
  6690. }
  6691. out += this.input.slice(chunkStart, this.state.pos++);
  6692. this.finishToken(134, out);
  6693. }
  6694. jsxReadEntity() {
  6695. const startPos = ++this.state.pos;
  6696. if (this.codePointAtPos(this.state.pos) === 35) {
  6697. ++this.state.pos;
  6698. let radix = 10;
  6699. if (this.codePointAtPos(this.state.pos) === 120) {
  6700. radix = 16;
  6701. ++this.state.pos;
  6702. }
  6703. const codePoint = this.readInt(radix, undefined, false, "bail");
  6704. if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) {
  6705. ++this.state.pos;
  6706. return String.fromCodePoint(codePoint);
  6707. }
  6708. } else {
  6709. let count = 0;
  6710. let semi = false;
  6711. while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) {
  6712. ++this.state.pos;
  6713. }
  6714. if (semi) {
  6715. const desc = this.input.slice(startPos, this.state.pos);
  6716. const entity = entities[desc];
  6717. ++this.state.pos;
  6718. if (entity) {
  6719. return entity;
  6720. }
  6721. }
  6722. }
  6723. this.state.pos = startPos;
  6724. return "&";
  6725. }
  6726. jsxReadWord() {
  6727. let ch;
  6728. const start = this.state.pos;
  6729. do {
  6730. ch = this.input.charCodeAt(++this.state.pos);
  6731. } while (isIdentifierChar(ch) || ch === 45);
  6732. this.finishToken(141, this.input.slice(start, this.state.pos));
  6733. }
  6734. jsxParseIdentifier() {
  6735. const node = this.startNode();
  6736. if (this.match(141)) {
  6737. node.name = this.state.value;
  6738. } else if (tokenIsKeyword(this.state.type)) {
  6739. node.name = tokenLabelName(this.state.type);
  6740. } else {
  6741. this.unexpected();
  6742. }
  6743. this.next();
  6744. return this.finishNode(node, "JSXIdentifier");
  6745. }
  6746. jsxParseNamespacedName() {
  6747. const startLoc = this.state.startLoc;
  6748. const name = this.jsxParseIdentifier();
  6749. if (!this.eat(14)) return name;
  6750. const node = this.startNodeAt(startLoc);
  6751. node.namespace = name;
  6752. node.name = this.jsxParseIdentifier();
  6753. return this.finishNode(node, "JSXNamespacedName");
  6754. }
  6755. jsxParseElementName() {
  6756. const startLoc = this.state.startLoc;
  6757. let node = this.jsxParseNamespacedName();
  6758. if (node.type === "JSXNamespacedName") {
  6759. return node;
  6760. }
  6761. while (this.eat(16)) {
  6762. const newNode = this.startNodeAt(startLoc);
  6763. newNode.object = node;
  6764. newNode.property = this.jsxParseIdentifier();
  6765. node = this.finishNode(newNode, "JSXMemberExpression");
  6766. }
  6767. return node;
  6768. }
  6769. jsxParseAttributeValue() {
  6770. let node;
  6771. switch (this.state.type) {
  6772. case 5:
  6773. node = this.startNode();
  6774. this.setContext(types.brace);
  6775. this.next();
  6776. node = this.jsxParseExpressionContainer(node, types.j_oTag);
  6777. if (node.expression.type === "JSXEmptyExpression") {
  6778. this.raise(JsxErrors.AttributeIsEmpty, node);
  6779. }
  6780. return node;
  6781. case 143:
  6782. case 134:
  6783. return this.parseExprAtom();
  6784. default:
  6785. throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);
  6786. }
  6787. }
  6788. jsxParseEmptyExpression() {
  6789. const node = this.startNodeAt(this.state.lastTokEndLoc);
  6790. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc);
  6791. }
  6792. jsxParseSpreadChild(node) {
  6793. this.next();
  6794. node.expression = this.parseExpression();
  6795. this.setContext(types.j_expr);
  6796. this.state.canStartJSXElement = true;
  6797. this.expect(8);
  6798. return this.finishNode(node, "JSXSpreadChild");
  6799. }
  6800. jsxParseExpressionContainer(node, previousContext) {
  6801. if (this.match(8)) {
  6802. node.expression = this.jsxParseEmptyExpression();
  6803. } else {
  6804. const expression = this.parseExpression();
  6805. node.expression = expression;
  6806. }
  6807. this.setContext(previousContext);
  6808. this.state.canStartJSXElement = true;
  6809. this.expect(8);
  6810. return this.finishNode(node, "JSXExpressionContainer");
  6811. }
  6812. jsxParseAttribute() {
  6813. const node = this.startNode();
  6814. if (this.match(5)) {
  6815. this.setContext(types.brace);
  6816. this.next();
  6817. this.expect(21);
  6818. node.argument = this.parseMaybeAssignAllowIn();
  6819. this.setContext(types.j_oTag);
  6820. this.state.canStartJSXElement = true;
  6821. this.expect(8);
  6822. return this.finishNode(node, "JSXSpreadAttribute");
  6823. }
  6824. node.name = this.jsxParseNamespacedName();
  6825. node.value = this.eat(29) ? this.jsxParseAttributeValue() : null;
  6826. return this.finishNode(node, "JSXAttribute");
  6827. }
  6828. jsxParseOpeningElementAt(startLoc) {
  6829. const node = this.startNodeAt(startLoc);
  6830. if (this.eat(144)) {
  6831. return this.finishNode(node, "JSXOpeningFragment");
  6832. }
  6833. node.name = this.jsxParseElementName();
  6834. return this.jsxParseOpeningElementAfterName(node);
  6835. }
  6836. jsxParseOpeningElementAfterName(node) {
  6837. const attributes = [];
  6838. while (!this.match(56) && !this.match(144)) {
  6839. attributes.push(this.jsxParseAttribute());
  6840. }
  6841. node.attributes = attributes;
  6842. node.selfClosing = this.eat(56);
  6843. this.expect(144);
  6844. return this.finishNode(node, "JSXOpeningElement");
  6845. }
  6846. jsxParseClosingElementAt(startLoc) {
  6847. const node = this.startNodeAt(startLoc);
  6848. if (this.eat(144)) {
  6849. return this.finishNode(node, "JSXClosingFragment");
  6850. }
  6851. node.name = this.jsxParseElementName();
  6852. this.expect(144);
  6853. return this.finishNode(node, "JSXClosingElement");
  6854. }
  6855. jsxParseElementAt(startLoc) {
  6856. const node = this.startNodeAt(startLoc);
  6857. const children = [];
  6858. const openingElement = this.jsxParseOpeningElementAt(startLoc);
  6859. let closingElement = null;
  6860. if (!openingElement.selfClosing) {
  6861. contents: for (;;) {
  6862. switch (this.state.type) {
  6863. case 143:
  6864. startLoc = this.state.startLoc;
  6865. this.next();
  6866. if (this.eat(56)) {
  6867. closingElement = this.jsxParseClosingElementAt(startLoc);
  6868. break contents;
  6869. }
  6870. children.push(this.jsxParseElementAt(startLoc));
  6871. break;
  6872. case 142:
  6873. children.push(this.parseLiteral(this.state.value, "JSXText"));
  6874. break;
  6875. case 5:
  6876. {
  6877. const node = this.startNode();
  6878. this.setContext(types.brace);
  6879. this.next();
  6880. if (this.match(21)) {
  6881. children.push(this.jsxParseSpreadChild(node));
  6882. } else {
  6883. children.push(this.jsxParseExpressionContainer(node, types.j_expr));
  6884. }
  6885. break;
  6886. }
  6887. default:
  6888. this.unexpected();
  6889. }
  6890. }
  6891. if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) {
  6892. this.raise(JsxErrors.MissingClosingTagFragment, closingElement);
  6893. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  6894. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  6895. openingTagName: getQualifiedJSXName(openingElement.name)
  6896. });
  6897. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  6898. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  6899. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  6900. openingTagName: getQualifiedJSXName(openingElement.name)
  6901. });
  6902. }
  6903. }
  6904. }
  6905. if (isFragment(openingElement)) {
  6906. node.openingFragment = openingElement;
  6907. node.closingFragment = closingElement;
  6908. } else {
  6909. node.openingElement = openingElement;
  6910. node.closingElement = closingElement;
  6911. }
  6912. node.children = children;
  6913. if (this.match(47)) {
  6914. throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc);
  6915. }
  6916. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  6917. }
  6918. jsxParseElement() {
  6919. const startLoc = this.state.startLoc;
  6920. this.next();
  6921. return this.jsxParseElementAt(startLoc);
  6922. }
  6923. setContext(newContext) {
  6924. const {
  6925. context
  6926. } = this.state;
  6927. context[context.length - 1] = newContext;
  6928. }
  6929. parseExprAtom(refExpressionErrors) {
  6930. if (this.match(143)) {
  6931. return this.jsxParseElement();
  6932. } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) {
  6933. this.replaceToken(143);
  6934. return this.jsxParseElement();
  6935. } else {
  6936. return super.parseExprAtom(refExpressionErrors);
  6937. }
  6938. }
  6939. skipSpace() {
  6940. const curContext = this.curContext();
  6941. if (!curContext.preserveSpace) super.skipSpace();
  6942. }
  6943. getTokenFromCode(code) {
  6944. const context = this.curContext();
  6945. if (context === types.j_expr) {
  6946. this.jsxReadToken();
  6947. return;
  6948. }
  6949. if (context === types.j_oTag || context === types.j_cTag) {
  6950. if (isIdentifierStart(code)) {
  6951. this.jsxReadWord();
  6952. return;
  6953. }
  6954. if (code === 62) {
  6955. ++this.state.pos;
  6956. this.finishToken(144);
  6957. return;
  6958. }
  6959. if ((code === 34 || code === 39) && context === types.j_oTag) {
  6960. this.jsxReadString(code);
  6961. return;
  6962. }
  6963. }
  6964. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  6965. ++this.state.pos;
  6966. this.finishToken(143);
  6967. return;
  6968. }
  6969. super.getTokenFromCode(code);
  6970. }
  6971. updateContext(prevType) {
  6972. const {
  6973. context,
  6974. type
  6975. } = this.state;
  6976. if (type === 56 && prevType === 143) {
  6977. context.splice(-2, 2, types.j_cTag);
  6978. this.state.canStartJSXElement = false;
  6979. } else if (type === 143) {
  6980. context.push(types.j_oTag);
  6981. } else if (type === 144) {
  6982. const out = context[context.length - 1];
  6983. if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) {
  6984. context.pop();
  6985. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  6986. } else {
  6987. this.setContext(types.j_expr);
  6988. this.state.canStartJSXElement = true;
  6989. }
  6990. } else {
  6991. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  6992. }
  6993. }
  6994. };
  6995. class TypeScriptScope extends Scope {
  6996. constructor(...args) {
  6997. super(...args);
  6998. this.tsNames = new Map();
  6999. }
  7000. }
  7001. class TypeScriptScopeHandler extends ScopeHandler {
  7002. constructor(...args) {
  7003. super(...args);
  7004. this.importsStack = [];
  7005. }
  7006. createScope(flags) {
  7007. this.importsStack.push(new Set());
  7008. return new TypeScriptScope(flags);
  7009. }
  7010. enter(flags) {
  7011. if (flags === 256) {
  7012. this.importsStack.push(new Set());
  7013. }
  7014. super.enter(flags);
  7015. }
  7016. exit() {
  7017. const flags = super.exit();
  7018. if (flags === 256) {
  7019. this.importsStack.pop();
  7020. }
  7021. return flags;
  7022. }
  7023. hasImport(name, allowShadow) {
  7024. const len = this.importsStack.length;
  7025. if (this.importsStack[len - 1].has(name)) {
  7026. return true;
  7027. }
  7028. if (!allowShadow && len > 1) {
  7029. for (let i = 0; i < len - 1; i++) {
  7030. if (this.importsStack[i].has(name)) return true;
  7031. }
  7032. }
  7033. return false;
  7034. }
  7035. declareName(name, bindingType, loc) {
  7036. if (bindingType & 4096) {
  7037. if (this.hasImport(name, true)) {
  7038. this.parser.raise(Errors.VarRedeclaration, loc, {
  7039. identifierName: name
  7040. });
  7041. }
  7042. this.importsStack[this.importsStack.length - 1].add(name);
  7043. return;
  7044. }
  7045. const scope = this.currentScope();
  7046. let type = scope.tsNames.get(name) || 0;
  7047. if (bindingType & 1024) {
  7048. this.maybeExportDefined(scope, name);
  7049. scope.tsNames.set(name, type | 16);
  7050. return;
  7051. }
  7052. super.declareName(name, bindingType, loc);
  7053. if (bindingType & 2) {
  7054. if (!(bindingType & 1)) {
  7055. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  7056. this.maybeExportDefined(scope, name);
  7057. }
  7058. type = type | 1;
  7059. }
  7060. if (bindingType & 256) {
  7061. type = type | 2;
  7062. }
  7063. if (bindingType & 512) {
  7064. type = type | 4;
  7065. }
  7066. if (bindingType & 128) {
  7067. type = type | 8;
  7068. }
  7069. if (type) scope.tsNames.set(name, type);
  7070. }
  7071. isRedeclaredInScope(scope, name, bindingType) {
  7072. const type = scope.tsNames.get(name);
  7073. if ((type & 2) > 0) {
  7074. if (bindingType & 256) {
  7075. const isConst = !!(bindingType & 512);
  7076. const wasConst = (type & 4) > 0;
  7077. return isConst !== wasConst;
  7078. }
  7079. return true;
  7080. }
  7081. if (bindingType & 128 && (type & 8) > 0) {
  7082. if (scope.names.get(name) & 2) {
  7083. return !!(bindingType & 1);
  7084. } else {
  7085. return false;
  7086. }
  7087. }
  7088. if (bindingType & 2 && (type & 1) > 0) {
  7089. return true;
  7090. }
  7091. return super.isRedeclaredInScope(scope, name, bindingType);
  7092. }
  7093. checkLocalExport(id) {
  7094. const {
  7095. name
  7096. } = id;
  7097. if (this.hasImport(name)) return;
  7098. const len = this.scopeStack.length;
  7099. for (let i = len - 1; i >= 0; i--) {
  7100. const scope = this.scopeStack[i];
  7101. const type = scope.tsNames.get(name);
  7102. if ((type & 1) > 0 || (type & 16) > 0) {
  7103. return;
  7104. }
  7105. }
  7106. super.checkLocalExport(id);
  7107. }
  7108. }
  7109. const unwrapParenthesizedExpression = node => {
  7110. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7111. };
  7112. class LValParser extends NodeUtils {
  7113. toAssignable(node, isLHS = false) {
  7114. var _node$extra, _node$extra3;
  7115. let parenthesized = undefined;
  7116. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  7117. parenthesized = unwrapParenthesizedExpression(node);
  7118. if (isLHS) {
  7119. if (parenthesized.type === "Identifier") {
  7120. this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node);
  7121. } else if (parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) {
  7122. this.raise(Errors.InvalidParenthesizedAssignment, node);
  7123. }
  7124. } else {
  7125. this.raise(Errors.InvalidParenthesizedAssignment, node);
  7126. }
  7127. }
  7128. switch (node.type) {
  7129. case "Identifier":
  7130. case "ObjectPattern":
  7131. case "ArrayPattern":
  7132. case "AssignmentPattern":
  7133. case "RestElement":
  7134. break;
  7135. case "ObjectExpression":
  7136. node.type = "ObjectPattern";
  7137. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7138. var _node$extra2;
  7139. const prop = node.properties[i];
  7140. const isLast = i === last;
  7141. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  7142. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) {
  7143. this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc);
  7144. }
  7145. }
  7146. break;
  7147. case "ObjectProperty":
  7148. {
  7149. const {
  7150. key,
  7151. value
  7152. } = node;
  7153. if (this.isPrivateName(key)) {
  7154. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  7155. }
  7156. this.toAssignable(value, isLHS);
  7157. break;
  7158. }
  7159. case "SpreadElement":
  7160. {
  7161. throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller.");
  7162. }
  7163. case "ArrayExpression":
  7164. node.type = "ArrayPattern";
  7165. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS);
  7166. break;
  7167. case "AssignmentExpression":
  7168. if (node.operator !== "=") {
  7169. this.raise(Errors.MissingEqInAssignment, node.left.loc.end);
  7170. }
  7171. node.type = "AssignmentPattern";
  7172. delete node.operator;
  7173. this.toAssignable(node.left, isLHS);
  7174. break;
  7175. case "ParenthesizedExpression":
  7176. this.toAssignable(parenthesized, isLHS);
  7177. break;
  7178. }
  7179. }
  7180. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  7181. if (prop.type === "ObjectMethod") {
  7182. this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key);
  7183. } else if (prop.type === "SpreadElement") {
  7184. prop.type = "RestElement";
  7185. const arg = prop.argument;
  7186. this.checkToRestConversion(arg, false);
  7187. this.toAssignable(arg, isLHS);
  7188. if (!isLast) {
  7189. this.raise(Errors.RestTrailingComma, prop);
  7190. }
  7191. } else {
  7192. this.toAssignable(prop, isLHS);
  7193. }
  7194. }
  7195. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  7196. const end = exprList.length - 1;
  7197. for (let i = 0; i <= end; i++) {
  7198. const elt = exprList[i];
  7199. if (!elt) continue;
  7200. if (elt.type === "SpreadElement") {
  7201. elt.type = "RestElement";
  7202. const arg = elt.argument;
  7203. this.checkToRestConversion(arg, true);
  7204. this.toAssignable(arg, isLHS);
  7205. } else {
  7206. this.toAssignable(elt, isLHS);
  7207. }
  7208. if (elt.type === "RestElement") {
  7209. if (i < end) {
  7210. this.raise(Errors.RestTrailingComma, elt);
  7211. } else if (trailingCommaLoc) {
  7212. this.raise(Errors.RestTrailingComma, trailingCommaLoc);
  7213. }
  7214. }
  7215. }
  7216. }
  7217. isAssignable(node, isBinding) {
  7218. switch (node.type) {
  7219. case "Identifier":
  7220. case "ObjectPattern":
  7221. case "ArrayPattern":
  7222. case "AssignmentPattern":
  7223. case "RestElement":
  7224. return true;
  7225. case "ObjectExpression":
  7226. {
  7227. const last = node.properties.length - 1;
  7228. return node.properties.every((prop, i) => {
  7229. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  7230. });
  7231. }
  7232. case "ObjectProperty":
  7233. return this.isAssignable(node.value);
  7234. case "SpreadElement":
  7235. return this.isAssignable(node.argument);
  7236. case "ArrayExpression":
  7237. return node.elements.every(element => element === null || this.isAssignable(element));
  7238. case "AssignmentExpression":
  7239. return node.operator === "=";
  7240. case "ParenthesizedExpression":
  7241. return this.isAssignable(node.expression);
  7242. case "MemberExpression":
  7243. case "OptionalMemberExpression":
  7244. return !isBinding;
  7245. default:
  7246. return false;
  7247. }
  7248. }
  7249. toReferencedList(exprList, isParenthesizedExpr) {
  7250. return exprList;
  7251. }
  7252. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7253. this.toReferencedList(exprList, isParenthesizedExpr);
  7254. for (const expr of exprList) {
  7255. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  7256. this.toReferencedListDeep(expr.elements);
  7257. }
  7258. }
  7259. }
  7260. parseSpread(refExpressionErrors) {
  7261. const node = this.startNode();
  7262. this.next();
  7263. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined);
  7264. return this.finishNode(node, "SpreadElement");
  7265. }
  7266. parseRestBinding() {
  7267. const node = this.startNode();
  7268. this.next();
  7269. node.argument = this.parseBindingAtom();
  7270. return this.finishNode(node, "RestElement");
  7271. }
  7272. parseBindingAtom() {
  7273. switch (this.state.type) {
  7274. case 0:
  7275. {
  7276. const node = this.startNode();
  7277. this.next();
  7278. node.elements = this.parseBindingList(3, 93, 1);
  7279. return this.finishNode(node, "ArrayPattern");
  7280. }
  7281. case 5:
  7282. return this.parseObjectLike(8, true);
  7283. }
  7284. return this.parseIdentifier();
  7285. }
  7286. parseBindingList(close, closeCharCode, flags) {
  7287. const allowEmpty = flags & 1;
  7288. const elts = [];
  7289. let first = true;
  7290. while (!this.eat(close)) {
  7291. if (first) {
  7292. first = false;
  7293. } else {
  7294. this.expect(12);
  7295. }
  7296. if (allowEmpty && this.match(12)) {
  7297. elts.push(null);
  7298. } else if (this.eat(close)) {
  7299. break;
  7300. } else if (this.match(21)) {
  7301. let rest = this.parseRestBinding();
  7302. if (this.hasPlugin("flow") || flags & 2) {
  7303. rest = this.parseFunctionParamType(rest);
  7304. }
  7305. elts.push(rest);
  7306. if (!this.checkCommaAfterRest(closeCharCode)) {
  7307. this.expect(close);
  7308. break;
  7309. }
  7310. } else {
  7311. const decorators = [];
  7312. if (this.match(26) && this.hasPlugin("decorators")) {
  7313. this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc);
  7314. }
  7315. while (this.match(26)) {
  7316. decorators.push(this.parseDecorator());
  7317. }
  7318. elts.push(this.parseAssignableListItem(flags, decorators));
  7319. }
  7320. }
  7321. return elts;
  7322. }
  7323. parseBindingRestProperty(prop) {
  7324. this.next();
  7325. prop.argument = this.parseIdentifier();
  7326. this.checkCommaAfterRest(125);
  7327. return this.finishNode(prop, "RestElement");
  7328. }
  7329. parseBindingProperty() {
  7330. const {
  7331. type,
  7332. startLoc
  7333. } = this.state;
  7334. if (type === 21) {
  7335. return this.parseBindingRestProperty(this.startNode());
  7336. }
  7337. const prop = this.startNode();
  7338. if (type === 139) {
  7339. this.expectPlugin("destructuringPrivate", startLoc);
  7340. this.classScope.usePrivateName(this.state.value, startLoc);
  7341. prop.key = this.parsePrivateName();
  7342. } else {
  7343. this.parsePropertyName(prop);
  7344. }
  7345. prop.method = false;
  7346. return this.parseObjPropValue(prop, startLoc, false, false, true, false);
  7347. }
  7348. parseAssignableListItem(flags, decorators) {
  7349. const left = this.parseMaybeDefault();
  7350. if (this.hasPlugin("flow") || flags & 2) {
  7351. this.parseFunctionParamType(left);
  7352. }
  7353. const elt = this.parseMaybeDefault(left.loc.start, left);
  7354. if (decorators.length) {
  7355. left.decorators = decorators;
  7356. }
  7357. return elt;
  7358. }
  7359. parseFunctionParamType(param) {
  7360. return param;
  7361. }
  7362. parseMaybeDefault(startLoc, left) {
  7363. var _startLoc, _left;
  7364. (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc;
  7365. left = (_left = left) != null ? _left : this.parseBindingAtom();
  7366. if (!this.eat(29)) return left;
  7367. const node = this.startNodeAt(startLoc);
  7368. node.left = left;
  7369. node.right = this.parseMaybeAssignAllowIn();
  7370. return this.finishNode(node, "AssignmentPattern");
  7371. }
  7372. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  7373. switch (type) {
  7374. case "AssignmentPattern":
  7375. return "left";
  7376. case "RestElement":
  7377. return "argument";
  7378. case "ObjectProperty":
  7379. return "value";
  7380. case "ParenthesizedExpression":
  7381. return "expression";
  7382. case "ArrayPattern":
  7383. return "elements";
  7384. case "ObjectPattern":
  7385. return "properties";
  7386. }
  7387. return false;
  7388. }
  7389. isOptionalMemberExpression(expression) {
  7390. return expression.type === "OptionalMemberExpression";
  7391. }
  7392. checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false) {
  7393. var _expression$extra;
  7394. const type = expression.type;
  7395. if (this.isObjectMethod(expression)) return;
  7396. const isOptionalMemberExpression = this.isOptionalMemberExpression(expression);
  7397. if (isOptionalMemberExpression || type === "MemberExpression") {
  7398. if (isOptionalMemberExpression) {
  7399. this.expectPlugin("optionalChainingAssign", expression.loc.start);
  7400. if (ancestor.type !== "AssignmentExpression") {
  7401. this.raise(Errors.InvalidLhsOptionalChaining, expression, {
  7402. ancestor
  7403. });
  7404. }
  7405. }
  7406. if (binding !== 64) {
  7407. this.raise(Errors.InvalidPropertyBindingPattern, expression);
  7408. }
  7409. return;
  7410. }
  7411. if (type === "Identifier") {
  7412. this.checkIdentifier(expression, binding, strictModeChanged);
  7413. const {
  7414. name
  7415. } = expression;
  7416. if (checkClashes) {
  7417. if (checkClashes.has(name)) {
  7418. this.raise(Errors.ParamDupe, expression);
  7419. } else {
  7420. checkClashes.add(name);
  7421. }
  7422. }
  7423. return;
  7424. }
  7425. const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
  7426. if (validity === true) return;
  7427. if (validity === false) {
  7428. const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
  7429. this.raise(ParseErrorClass, expression, {
  7430. ancestor
  7431. });
  7432. return;
  7433. }
  7434. let key, isParenthesizedExpression;
  7435. if (typeof validity === "string") {
  7436. key = validity;
  7437. isParenthesizedExpression = type === "ParenthesizedExpression";
  7438. } else {
  7439. [key, isParenthesizedExpression] = validity;
  7440. }
  7441. const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? {
  7442. type
  7443. } : ancestor;
  7444. const val = expression[key];
  7445. if (Array.isArray(val)) {
  7446. for (const child of val) {
  7447. if (child) {
  7448. this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression);
  7449. }
  7450. }
  7451. } else if (val) {
  7452. this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression);
  7453. }
  7454. }
  7455. checkIdentifier(at, bindingType, strictModeChanged = false) {
  7456. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) {
  7457. if (bindingType === 64) {
  7458. this.raise(Errors.StrictEvalArguments, at, {
  7459. referenceName: at.name
  7460. });
  7461. } else {
  7462. this.raise(Errors.StrictEvalArgumentsBinding, at, {
  7463. bindingName: at.name
  7464. });
  7465. }
  7466. }
  7467. if (bindingType & 8192 && at.name === "let") {
  7468. this.raise(Errors.LetInLexicalBinding, at);
  7469. }
  7470. if (!(bindingType & 64)) {
  7471. this.declareNameFromIdentifier(at, bindingType);
  7472. }
  7473. }
  7474. declareNameFromIdentifier(identifier, binding) {
  7475. this.scope.declareName(identifier.name, binding, identifier.loc.start);
  7476. }
  7477. checkToRestConversion(node, allowPattern) {
  7478. switch (node.type) {
  7479. case "ParenthesizedExpression":
  7480. this.checkToRestConversion(node.expression, allowPattern);
  7481. break;
  7482. case "Identifier":
  7483. case "MemberExpression":
  7484. break;
  7485. case "ArrayExpression":
  7486. case "ObjectExpression":
  7487. if (allowPattern) break;
  7488. default:
  7489. this.raise(Errors.InvalidRestAssignmentPattern, node);
  7490. }
  7491. }
  7492. checkCommaAfterRest(close) {
  7493. if (!this.match(12)) {
  7494. return false;
  7495. }
  7496. this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc);
  7497. return true;
  7498. }
  7499. }
  7500. function nonNull(x) {
  7501. if (x == null) {
  7502. throw new Error(`Unexpected ${x} value.`);
  7503. }
  7504. return x;
  7505. }
  7506. function assert(x) {
  7507. if (!x) {
  7508. throw new Error("Assert fail");
  7509. }
  7510. }
  7511. const TSErrors = ParseErrorEnum`typescript`({
  7512. AbstractMethodHasImplementation: ({
  7513. methodName
  7514. }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`,
  7515. AbstractPropertyHasInitializer: ({
  7516. propertyName
  7517. }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
  7518. AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.",
  7519. AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  7520. AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  7521. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  7522. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  7523. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
  7524. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  7525. DeclareAccessor: ({
  7526. kind
  7527. }) => `'declare' is not allowed in ${kind}ters.`,
  7528. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  7529. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  7530. DuplicateAccessibilityModifier: ({
  7531. modifier
  7532. }) => `Accessibility modifier already seen.`,
  7533. DuplicateModifier: ({
  7534. modifier
  7535. }) => `Duplicate modifier: '${modifier}'.`,
  7536. EmptyHeritageClauseType: ({
  7537. token
  7538. }) => `'${token}' list cannot be empty.`,
  7539. EmptyTypeArguments: "Type argument list cannot be empty.",
  7540. EmptyTypeParameters: "Type parameter list cannot be empty.",
  7541. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  7542. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  7543. ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier",
  7544. IncompatibleModifiers: ({
  7545. modifiers
  7546. }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,
  7547. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  7548. IndexSignatureHasAccessibility: ({
  7549. modifier
  7550. }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`,
  7551. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  7552. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  7553. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  7554. InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.",
  7555. InvalidModifierOnTypeMember: ({
  7556. modifier
  7557. }) => `'${modifier}' modifier cannot appear on a type member.`,
  7558. InvalidModifierOnTypeParameter: ({
  7559. modifier
  7560. }) => `'${modifier}' modifier cannot appear on a type parameter.`,
  7561. InvalidModifierOnTypeParameterPositions: ({
  7562. modifier
  7563. }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,
  7564. InvalidModifiersOrder: ({
  7565. orderedModifiers
  7566. }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,
  7567. InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.",
  7568. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  7569. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  7570. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  7571. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  7572. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  7573. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  7574. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  7575. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  7576. PrivateElementHasAccessibility: ({
  7577. modifier
  7578. }) => `Private elements cannot have an accessibility modifier ('${modifier}').`,
  7579. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  7580. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  7581. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  7582. SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  7583. SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  7584. SetAccessorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  7585. SingleTypeParameterWithoutTrailingComma: ({
  7586. typeParameterName
  7587. }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,
  7588. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  7589. TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",
  7590. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  7591. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  7592. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  7593. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  7594. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  7595. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  7596. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  7597. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  7598. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  7599. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  7600. UnsupportedSignatureParameterKind: ({
  7601. type
  7602. }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`
  7603. });
  7604. function keywordTypeFromName(value) {
  7605. switch (value) {
  7606. case "any":
  7607. return "TSAnyKeyword";
  7608. case "boolean":
  7609. return "TSBooleanKeyword";
  7610. case "bigint":
  7611. return "TSBigIntKeyword";
  7612. case "never":
  7613. return "TSNeverKeyword";
  7614. case "number":
  7615. return "TSNumberKeyword";
  7616. case "object":
  7617. return "TSObjectKeyword";
  7618. case "string":
  7619. return "TSStringKeyword";
  7620. case "symbol":
  7621. return "TSSymbolKeyword";
  7622. case "undefined":
  7623. return "TSUndefinedKeyword";
  7624. case "unknown":
  7625. return "TSUnknownKeyword";
  7626. default:
  7627. return undefined;
  7628. }
  7629. }
  7630. function tsIsAccessModifier(modifier) {
  7631. return modifier === "private" || modifier === "public" || modifier === "protected";
  7632. }
  7633. function tsIsVarianceAnnotations(modifier) {
  7634. return modifier === "in" || modifier === "out";
  7635. }
  7636. var typescript = superClass => class TypeScriptParserMixin extends superClass {
  7637. constructor(...args) {
  7638. super(...args);
  7639. this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, {
  7640. allowedModifiers: ["in", "out"],
  7641. disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"],
  7642. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  7643. });
  7644. this.tsParseConstModifier = this.tsParseModifiers.bind(this, {
  7645. allowedModifiers: ["const"],
  7646. disallowedModifiers: ["in", "out"],
  7647. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  7648. });
  7649. this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, {
  7650. allowedModifiers: ["in", "out", "const"],
  7651. disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"],
  7652. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  7653. });
  7654. }
  7655. getScopeHandler() {
  7656. return TypeScriptScopeHandler;
  7657. }
  7658. tsIsIdentifier() {
  7659. return tokenIsIdentifier(this.state.type);
  7660. }
  7661. tsTokenCanFollowModifier() {
  7662. return this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(139) || this.isLiteralPropertyName();
  7663. }
  7664. tsNextTokenOnSameLineAndCanFollowModifier() {
  7665. this.next();
  7666. if (this.hasPrecedingLineBreak()) {
  7667. return false;
  7668. }
  7669. return this.tsTokenCanFollowModifier();
  7670. }
  7671. tsNextTokenCanFollowModifier() {
  7672. if (this.match(106)) {
  7673. this.next();
  7674. return this.tsTokenCanFollowModifier();
  7675. }
  7676. return this.tsNextTokenOnSameLineAndCanFollowModifier();
  7677. }
  7678. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
  7679. if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) {
  7680. return undefined;
  7681. }
  7682. const modifier = this.state.value;
  7683. if (allowedModifiers.includes(modifier)) {
  7684. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  7685. return undefined;
  7686. }
  7687. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  7688. return modifier;
  7689. }
  7690. }
  7691. return undefined;
  7692. }
  7693. tsParseModifiers({
  7694. allowedModifiers,
  7695. disallowedModifiers,
  7696. stopOnStartOfClassStaticBlock,
  7697. errorTemplate = TSErrors.InvalidModifierOnTypeMember
  7698. }, modified) {
  7699. const enforceOrder = (loc, modifier, before, after) => {
  7700. if (modifier === before && modified[after]) {
  7701. this.raise(TSErrors.InvalidModifiersOrder, loc, {
  7702. orderedModifiers: [before, after]
  7703. });
  7704. }
  7705. };
  7706. const incompatible = (loc, modifier, mod1, mod2) => {
  7707. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  7708. this.raise(TSErrors.IncompatibleModifiers, loc, {
  7709. modifiers: [mod1, mod2]
  7710. });
  7711. }
  7712. };
  7713. for (;;) {
  7714. const {
  7715. startLoc
  7716. } = this.state;
  7717. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
  7718. if (!modifier) break;
  7719. if (tsIsAccessModifier(modifier)) {
  7720. if (modified.accessibility) {
  7721. this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, {
  7722. modifier
  7723. });
  7724. } else {
  7725. enforceOrder(startLoc, modifier, modifier, "override");
  7726. enforceOrder(startLoc, modifier, modifier, "static");
  7727. enforceOrder(startLoc, modifier, modifier, "readonly");
  7728. modified.accessibility = modifier;
  7729. }
  7730. } else if (tsIsVarianceAnnotations(modifier)) {
  7731. if (modified[modifier]) {
  7732. this.raise(TSErrors.DuplicateModifier, startLoc, {
  7733. modifier
  7734. });
  7735. }
  7736. modified[modifier] = true;
  7737. enforceOrder(startLoc, modifier, "in", "out");
  7738. } else {
  7739. if (hasOwnProperty.call(modified, modifier)) {
  7740. this.raise(TSErrors.DuplicateModifier, startLoc, {
  7741. modifier
  7742. });
  7743. } else {
  7744. enforceOrder(startLoc, modifier, "static", "readonly");
  7745. enforceOrder(startLoc, modifier, "static", "override");
  7746. enforceOrder(startLoc, modifier, "override", "readonly");
  7747. enforceOrder(startLoc, modifier, "abstract", "override");
  7748. incompatible(startLoc, modifier, "declare", "override");
  7749. incompatible(startLoc, modifier, "static", "abstract");
  7750. }
  7751. modified[modifier] = true;
  7752. }
  7753. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  7754. this.raise(errorTemplate, startLoc, {
  7755. modifier
  7756. });
  7757. }
  7758. }
  7759. }
  7760. tsIsListTerminator(kind) {
  7761. switch (kind) {
  7762. case "EnumMembers":
  7763. case "TypeMembers":
  7764. return this.match(8);
  7765. case "HeritageClauseElement":
  7766. return this.match(5);
  7767. case "TupleElementTypes":
  7768. return this.match(3);
  7769. case "TypeParametersOrArguments":
  7770. return this.match(48);
  7771. }
  7772. }
  7773. tsParseList(kind, parseElement) {
  7774. const result = [];
  7775. while (!this.tsIsListTerminator(kind)) {
  7776. result.push(parseElement());
  7777. }
  7778. return result;
  7779. }
  7780. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  7781. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  7782. }
  7783. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  7784. const result = [];
  7785. let trailingCommaPos = -1;
  7786. for (;;) {
  7787. if (this.tsIsListTerminator(kind)) {
  7788. break;
  7789. }
  7790. trailingCommaPos = -1;
  7791. const element = parseElement();
  7792. if (element == null) {
  7793. return undefined;
  7794. }
  7795. result.push(element);
  7796. if (this.eat(12)) {
  7797. trailingCommaPos = this.state.lastTokStartLoc.index;
  7798. continue;
  7799. }
  7800. if (this.tsIsListTerminator(kind)) {
  7801. break;
  7802. }
  7803. if (expectSuccess) {
  7804. this.expect(12);
  7805. }
  7806. return undefined;
  7807. }
  7808. if (refTrailingCommaPos) {
  7809. refTrailingCommaPos.value = trailingCommaPos;
  7810. }
  7811. return result;
  7812. }
  7813. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  7814. if (!skipFirstToken) {
  7815. if (bracket) {
  7816. this.expect(0);
  7817. } else {
  7818. this.expect(47);
  7819. }
  7820. }
  7821. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  7822. if (bracket) {
  7823. this.expect(3);
  7824. } else {
  7825. this.expect(48);
  7826. }
  7827. return result;
  7828. }
  7829. tsParseImportType() {
  7830. const node = this.startNode();
  7831. this.expect(83);
  7832. this.expect(10);
  7833. if (!this.match(134)) {
  7834. this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc);
  7835. {
  7836. node.argument = super.parseExprAtom();
  7837. }
  7838. } else {
  7839. {
  7840. node.argument = this.parseStringLiteral(this.state.value);
  7841. }
  7842. }
  7843. if (this.eat(12) && !this.match(11)) {
  7844. node.options = super.parseMaybeAssignAllowIn();
  7845. this.eat(12);
  7846. } else {
  7847. node.options = null;
  7848. }
  7849. this.expect(11);
  7850. if (this.eat(16)) {
  7851. node.qualifier = this.tsParseEntityName(1 | 2);
  7852. }
  7853. if (this.match(47)) {
  7854. {
  7855. node.typeParameters = this.tsParseTypeArguments();
  7856. }
  7857. }
  7858. return this.finishNode(node, "TSImportType");
  7859. }
  7860. tsParseEntityName(flags) {
  7861. let entity;
  7862. if (flags & 1 && this.match(78)) {
  7863. if (flags & 2) {
  7864. entity = this.parseIdentifier(true);
  7865. } else {
  7866. const node = this.startNode();
  7867. this.next();
  7868. entity = this.finishNode(node, "ThisExpression");
  7869. }
  7870. } else {
  7871. entity = this.parseIdentifier(!!(flags & 1));
  7872. }
  7873. while (this.eat(16)) {
  7874. const node = this.startNodeAtNode(entity);
  7875. node.left = entity;
  7876. node.right = this.parseIdentifier(!!(flags & 1));
  7877. entity = this.finishNode(node, "TSQualifiedName");
  7878. }
  7879. return entity;
  7880. }
  7881. tsParseTypeReference() {
  7882. const node = this.startNode();
  7883. node.typeName = this.tsParseEntityName(1);
  7884. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  7885. {
  7886. node.typeParameters = this.tsParseTypeArguments();
  7887. }
  7888. }
  7889. return this.finishNode(node, "TSTypeReference");
  7890. }
  7891. tsParseThisTypePredicate(lhs) {
  7892. this.next();
  7893. const node = this.startNodeAtNode(lhs);
  7894. node.parameterName = lhs;
  7895. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  7896. node.asserts = false;
  7897. return this.finishNode(node, "TSTypePredicate");
  7898. }
  7899. tsParseThisTypeNode() {
  7900. const node = this.startNode();
  7901. this.next();
  7902. return this.finishNode(node, "TSThisType");
  7903. }
  7904. tsParseTypeQuery() {
  7905. const node = this.startNode();
  7906. this.expect(87);
  7907. if (this.match(83)) {
  7908. node.exprName = this.tsParseImportType();
  7909. } else {
  7910. {
  7911. node.exprName = this.tsParseEntityName(1 | 2);
  7912. }
  7913. }
  7914. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  7915. {
  7916. node.typeParameters = this.tsParseTypeArguments();
  7917. }
  7918. }
  7919. return this.finishNode(node, "TSTypeQuery");
  7920. }
  7921. tsParseTypeParameter(parseModifiers) {
  7922. const node = this.startNode();
  7923. parseModifiers(node);
  7924. node.name = this.tsParseTypeParameterName();
  7925. node.constraint = this.tsEatThenParseType(81);
  7926. node.default = this.tsEatThenParseType(29);
  7927. return this.finishNode(node, "TSTypeParameter");
  7928. }
  7929. tsTryParseTypeParameters(parseModifiers) {
  7930. if (this.match(47)) {
  7931. return this.tsParseTypeParameters(parseModifiers);
  7932. }
  7933. }
  7934. tsParseTypeParameters(parseModifiers) {
  7935. const node = this.startNode();
  7936. if (this.match(47) || this.match(143)) {
  7937. this.next();
  7938. } else {
  7939. this.unexpected();
  7940. }
  7941. const refTrailingCommaPos = {
  7942. value: -1
  7943. };
  7944. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos);
  7945. if (node.params.length === 0) {
  7946. this.raise(TSErrors.EmptyTypeParameters, node);
  7947. }
  7948. if (refTrailingCommaPos.value !== -1) {
  7949. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  7950. }
  7951. return this.finishNode(node, "TSTypeParameterDeclaration");
  7952. }
  7953. tsFillSignature(returnToken, signature) {
  7954. const returnTokenRequired = returnToken === 19;
  7955. const paramsKey = "parameters";
  7956. const returnTypeKey = "typeAnnotation";
  7957. signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  7958. this.expect(10);
  7959. signature[paramsKey] = this.tsParseBindingListForSignature();
  7960. if (returnTokenRequired) {
  7961. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7962. } else if (this.match(returnToken)) {
  7963. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7964. }
  7965. }
  7966. tsParseBindingListForSignature() {
  7967. const list = super.parseBindingList(11, 41, 2);
  7968. for (const pattern of list) {
  7969. const {
  7970. type
  7971. } = pattern;
  7972. if (type === "AssignmentPattern" || type === "TSParameterProperty") {
  7973. this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, {
  7974. type
  7975. });
  7976. }
  7977. }
  7978. return list;
  7979. }
  7980. tsParseTypeMemberSemicolon() {
  7981. if (!this.eat(12) && !this.isLineTerminator()) {
  7982. this.expect(13);
  7983. }
  7984. }
  7985. tsParseSignatureMember(kind, node) {
  7986. this.tsFillSignature(14, node);
  7987. this.tsParseTypeMemberSemicolon();
  7988. return this.finishNode(node, kind);
  7989. }
  7990. tsIsUnambiguouslyIndexSignature() {
  7991. this.next();
  7992. if (tokenIsIdentifier(this.state.type)) {
  7993. this.next();
  7994. return this.match(14);
  7995. }
  7996. return false;
  7997. }
  7998. tsTryParseIndexSignature(node) {
  7999. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  8000. return;
  8001. }
  8002. this.expect(0);
  8003. const id = this.parseIdentifier();
  8004. id.typeAnnotation = this.tsParseTypeAnnotation();
  8005. this.resetEndLocation(id);
  8006. this.expect(3);
  8007. node.parameters = [id];
  8008. const type = this.tsTryParseTypeAnnotation();
  8009. if (type) node.typeAnnotation = type;
  8010. this.tsParseTypeMemberSemicolon();
  8011. return this.finishNode(node, "TSIndexSignature");
  8012. }
  8013. tsParsePropertyOrMethodSignature(node, readonly) {
  8014. if (this.eat(17)) node.optional = true;
  8015. const nodeAny = node;
  8016. if (this.match(10) || this.match(47)) {
  8017. if (readonly) {
  8018. this.raise(TSErrors.ReadonlyForMethodSignature, node);
  8019. }
  8020. const method = nodeAny;
  8021. if (method.kind && this.match(47)) {
  8022. this.raise(TSErrors.AccessorCannotHaveTypeParameters, this.state.curPosition());
  8023. }
  8024. this.tsFillSignature(14, method);
  8025. this.tsParseTypeMemberSemicolon();
  8026. const paramsKey = "parameters";
  8027. const returnTypeKey = "typeAnnotation";
  8028. if (method.kind === "get") {
  8029. if (method[paramsKey].length > 0) {
  8030. this.raise(Errors.BadGetterArity, this.state.curPosition());
  8031. if (this.isThisParam(method[paramsKey][0])) {
  8032. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  8033. }
  8034. }
  8035. } else if (method.kind === "set") {
  8036. if (method[paramsKey].length !== 1) {
  8037. this.raise(Errors.BadSetterArity, this.state.curPosition());
  8038. } else {
  8039. const firstParameter = method[paramsKey][0];
  8040. if (this.isThisParam(firstParameter)) {
  8041. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  8042. }
  8043. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  8044. this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition());
  8045. }
  8046. if (firstParameter.type === "RestElement") {
  8047. this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition());
  8048. }
  8049. }
  8050. if (method[returnTypeKey]) {
  8051. this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]);
  8052. }
  8053. } else {
  8054. method.kind = "method";
  8055. }
  8056. return this.finishNode(method, "TSMethodSignature");
  8057. } else {
  8058. const property = nodeAny;
  8059. if (readonly) property.readonly = true;
  8060. const type = this.tsTryParseTypeAnnotation();
  8061. if (type) property.typeAnnotation = type;
  8062. this.tsParseTypeMemberSemicolon();
  8063. return this.finishNode(property, "TSPropertySignature");
  8064. }
  8065. }
  8066. tsParseTypeMember() {
  8067. const node = this.startNode();
  8068. if (this.match(10) || this.match(47)) {
  8069. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  8070. }
  8071. if (this.match(77)) {
  8072. const id = this.startNode();
  8073. this.next();
  8074. if (this.match(10) || this.match(47)) {
  8075. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  8076. } else {
  8077. node.key = this.createIdentifier(id, "new");
  8078. return this.tsParsePropertyOrMethodSignature(node, false);
  8079. }
  8080. }
  8081. this.tsParseModifiers({
  8082. allowedModifiers: ["readonly"],
  8083. disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"]
  8084. }, node);
  8085. const idx = this.tsTryParseIndexSignature(node);
  8086. if (idx) {
  8087. return idx;
  8088. }
  8089. super.parsePropertyName(node);
  8090. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  8091. node.kind = node.key.name;
  8092. super.parsePropertyName(node);
  8093. }
  8094. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  8095. }
  8096. tsParseTypeLiteral() {
  8097. const node = this.startNode();
  8098. node.members = this.tsParseObjectTypeMembers();
  8099. return this.finishNode(node, "TSTypeLiteral");
  8100. }
  8101. tsParseObjectTypeMembers() {
  8102. this.expect(5);
  8103. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  8104. this.expect(8);
  8105. return members;
  8106. }
  8107. tsIsStartOfMappedType() {
  8108. this.next();
  8109. if (this.eat(53)) {
  8110. return this.isContextual(122);
  8111. }
  8112. if (this.isContextual(122)) {
  8113. this.next();
  8114. }
  8115. if (!this.match(0)) {
  8116. return false;
  8117. }
  8118. this.next();
  8119. if (!this.tsIsIdentifier()) {
  8120. return false;
  8121. }
  8122. this.next();
  8123. return this.match(58);
  8124. }
  8125. tsParseMappedType() {
  8126. const node = this.startNode();
  8127. this.expect(5);
  8128. if (this.match(53)) {
  8129. node.readonly = this.state.value;
  8130. this.next();
  8131. this.expectContextual(122);
  8132. } else if (this.eatContextual(122)) {
  8133. node.readonly = true;
  8134. }
  8135. this.expect(0);
  8136. {
  8137. const typeParameter = this.startNode();
  8138. typeParameter.name = this.tsParseTypeParameterName();
  8139. typeParameter.constraint = this.tsExpectThenParseType(58);
  8140. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  8141. }
  8142. node.nameType = this.eatContextual(93) ? this.tsParseType() : null;
  8143. this.expect(3);
  8144. if (this.match(53)) {
  8145. node.optional = this.state.value;
  8146. this.next();
  8147. this.expect(17);
  8148. } else if (this.eat(17)) {
  8149. node.optional = true;
  8150. }
  8151. node.typeAnnotation = this.tsTryParseType();
  8152. this.semicolon();
  8153. this.expect(8);
  8154. return this.finishNode(node, "TSMappedType");
  8155. }
  8156. tsParseTupleType() {
  8157. const node = this.startNode();
  8158. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  8159. let seenOptionalElement = false;
  8160. node.elementTypes.forEach(elementNode => {
  8161. const {
  8162. type
  8163. } = elementNode;
  8164. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  8165. this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode);
  8166. }
  8167. seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType");
  8168. });
  8169. return this.finishNode(node, "TSTupleType");
  8170. }
  8171. tsParseTupleElementType() {
  8172. const {
  8173. startLoc
  8174. } = this.state;
  8175. const rest = this.eat(21);
  8176. let labeled;
  8177. let label;
  8178. let optional;
  8179. let type;
  8180. const isWord = tokenIsKeywordOrIdentifier(this.state.type);
  8181. const chAfterWord = isWord ? this.lookaheadCharCode() : null;
  8182. if (chAfterWord === 58) {
  8183. labeled = true;
  8184. optional = false;
  8185. label = this.parseIdentifier(true);
  8186. this.expect(14);
  8187. type = this.tsParseType();
  8188. } else if (chAfterWord === 63) {
  8189. optional = true;
  8190. const startLoc = this.state.startLoc;
  8191. const wordName = this.state.value;
  8192. const typeOrLabel = this.tsParseNonArrayType();
  8193. if (this.lookaheadCharCode() === 58) {
  8194. labeled = true;
  8195. label = this.createIdentifier(this.startNodeAt(startLoc), wordName);
  8196. this.expect(17);
  8197. this.expect(14);
  8198. type = this.tsParseType();
  8199. } else {
  8200. labeled = false;
  8201. type = typeOrLabel;
  8202. this.expect(17);
  8203. }
  8204. } else {
  8205. type = this.tsParseType();
  8206. optional = this.eat(17);
  8207. labeled = this.eat(14);
  8208. }
  8209. if (labeled) {
  8210. let labeledNode;
  8211. if (label) {
  8212. labeledNode = this.startNodeAtNode(label);
  8213. labeledNode.optional = optional;
  8214. labeledNode.label = label;
  8215. labeledNode.elementType = type;
  8216. if (this.eat(17)) {
  8217. labeledNode.optional = true;
  8218. this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc);
  8219. }
  8220. } else {
  8221. labeledNode = this.startNodeAtNode(type);
  8222. labeledNode.optional = optional;
  8223. this.raise(TSErrors.InvalidTupleMemberLabel, type);
  8224. labeledNode.label = type;
  8225. labeledNode.elementType = this.tsParseType();
  8226. }
  8227. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  8228. } else if (optional) {
  8229. const optionalTypeNode = this.startNodeAtNode(type);
  8230. optionalTypeNode.typeAnnotation = type;
  8231. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  8232. }
  8233. if (rest) {
  8234. const restNode = this.startNodeAt(startLoc);
  8235. restNode.typeAnnotation = type;
  8236. type = this.finishNode(restNode, "TSRestType");
  8237. }
  8238. return type;
  8239. }
  8240. tsParseParenthesizedType() {
  8241. const node = this.startNode();
  8242. this.expect(10);
  8243. node.typeAnnotation = this.tsParseType();
  8244. this.expect(11);
  8245. return this.finishNode(node, "TSParenthesizedType");
  8246. }
  8247. tsParseFunctionOrConstructorType(type, abstract) {
  8248. const node = this.startNode();
  8249. if (type === "TSConstructorType") {
  8250. node.abstract = !!abstract;
  8251. if (abstract) this.next();
  8252. this.next();
  8253. }
  8254. this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node));
  8255. return this.finishNode(node, type);
  8256. }
  8257. tsParseLiteralTypeNode() {
  8258. const node = this.startNode();
  8259. switch (this.state.type) {
  8260. case 135:
  8261. case 136:
  8262. case 134:
  8263. case 85:
  8264. case 86:
  8265. node.literal = super.parseExprAtom();
  8266. break;
  8267. default:
  8268. this.unexpected();
  8269. }
  8270. return this.finishNode(node, "TSLiteralType");
  8271. }
  8272. tsParseTemplateLiteralType() {
  8273. const node = this.startNode();
  8274. node.literal = super.parseTemplate(false);
  8275. return this.finishNode(node, "TSLiteralType");
  8276. }
  8277. parseTemplateSubstitution() {
  8278. if (this.state.inType) return this.tsParseType();
  8279. return super.parseTemplateSubstitution();
  8280. }
  8281. tsParseThisTypeOrThisTypePredicate() {
  8282. const thisKeyword = this.tsParseThisTypeNode();
  8283. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  8284. return this.tsParseThisTypePredicate(thisKeyword);
  8285. } else {
  8286. return thisKeyword;
  8287. }
  8288. }
  8289. tsParseNonArrayType() {
  8290. switch (this.state.type) {
  8291. case 134:
  8292. case 135:
  8293. case 136:
  8294. case 85:
  8295. case 86:
  8296. return this.tsParseLiteralTypeNode();
  8297. case 53:
  8298. if (this.state.value === "-") {
  8299. const node = this.startNode();
  8300. const nextToken = this.lookahead();
  8301. if (nextToken.type !== 135 && nextToken.type !== 136) {
  8302. this.unexpected();
  8303. }
  8304. node.literal = this.parseMaybeUnary();
  8305. return this.finishNode(node, "TSLiteralType");
  8306. }
  8307. break;
  8308. case 78:
  8309. return this.tsParseThisTypeOrThisTypePredicate();
  8310. case 87:
  8311. return this.tsParseTypeQuery();
  8312. case 83:
  8313. return this.tsParseImportType();
  8314. case 5:
  8315. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  8316. case 0:
  8317. return this.tsParseTupleType();
  8318. case 10:
  8319. return this.tsParseParenthesizedType();
  8320. case 25:
  8321. case 24:
  8322. return this.tsParseTemplateLiteralType();
  8323. default:
  8324. {
  8325. const {
  8326. type
  8327. } = this.state;
  8328. if (tokenIsIdentifier(type) || type === 88 || type === 84) {
  8329. const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  8330. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  8331. const node = this.startNode();
  8332. this.next();
  8333. return this.finishNode(node, nodeType);
  8334. }
  8335. return this.tsParseTypeReference();
  8336. }
  8337. }
  8338. }
  8339. this.unexpected();
  8340. }
  8341. tsParseArrayTypeOrHigher() {
  8342. let type = this.tsParseNonArrayType();
  8343. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  8344. if (this.match(3)) {
  8345. const node = this.startNodeAtNode(type);
  8346. node.elementType = type;
  8347. this.expect(3);
  8348. type = this.finishNode(node, "TSArrayType");
  8349. } else {
  8350. const node = this.startNodeAtNode(type);
  8351. node.objectType = type;
  8352. node.indexType = this.tsParseType();
  8353. this.expect(3);
  8354. type = this.finishNode(node, "TSIndexedAccessType");
  8355. }
  8356. }
  8357. return type;
  8358. }
  8359. tsParseTypeOperator() {
  8360. const node = this.startNode();
  8361. const operator = this.state.value;
  8362. this.next();
  8363. node.operator = operator;
  8364. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  8365. if (operator === "readonly") {
  8366. this.tsCheckTypeAnnotationForReadOnly(node);
  8367. }
  8368. return this.finishNode(node, "TSTypeOperator");
  8369. }
  8370. tsCheckTypeAnnotationForReadOnly(node) {
  8371. switch (node.typeAnnotation.type) {
  8372. case "TSTupleType":
  8373. case "TSArrayType":
  8374. return;
  8375. default:
  8376. this.raise(TSErrors.UnexpectedReadonly, node);
  8377. }
  8378. }
  8379. tsParseInferType() {
  8380. const node = this.startNode();
  8381. this.expectContextual(115);
  8382. const typeParameter = this.startNode();
  8383. typeParameter.name = this.tsParseTypeParameterName();
  8384. typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType());
  8385. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  8386. return this.finishNode(node, "TSInferType");
  8387. }
  8388. tsParseConstraintForInferType() {
  8389. if (this.eat(81)) {
  8390. const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType());
  8391. if (this.state.inDisallowConditionalTypesContext || !this.match(17)) {
  8392. return constraint;
  8393. }
  8394. }
  8395. }
  8396. tsParseTypeOperatorOrHigher() {
  8397. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  8398. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher());
  8399. }
  8400. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  8401. const node = this.startNode();
  8402. const hasLeadingOperator = this.eat(operator);
  8403. const types = [];
  8404. do {
  8405. types.push(parseConstituentType());
  8406. } while (this.eat(operator));
  8407. if (types.length === 1 && !hasLeadingOperator) {
  8408. return types[0];
  8409. }
  8410. node.types = types;
  8411. return this.finishNode(node, kind);
  8412. }
  8413. tsParseIntersectionTypeOrHigher() {
  8414. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45);
  8415. }
  8416. tsParseUnionTypeOrHigher() {
  8417. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43);
  8418. }
  8419. tsIsStartOfFunctionType() {
  8420. if (this.match(47)) {
  8421. return true;
  8422. }
  8423. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  8424. }
  8425. tsSkipParameterStart() {
  8426. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  8427. this.next();
  8428. return true;
  8429. }
  8430. if (this.match(5)) {
  8431. const {
  8432. errors
  8433. } = this.state;
  8434. const previousErrorCount = errors.length;
  8435. try {
  8436. this.parseObjectLike(8, true);
  8437. return errors.length === previousErrorCount;
  8438. } catch (_unused) {
  8439. return false;
  8440. }
  8441. }
  8442. if (this.match(0)) {
  8443. this.next();
  8444. const {
  8445. errors
  8446. } = this.state;
  8447. const previousErrorCount = errors.length;
  8448. try {
  8449. super.parseBindingList(3, 93, 1);
  8450. return errors.length === previousErrorCount;
  8451. } catch (_unused2) {
  8452. return false;
  8453. }
  8454. }
  8455. return false;
  8456. }
  8457. tsIsUnambiguouslyStartOfFunctionType() {
  8458. this.next();
  8459. if (this.match(11) || this.match(21)) {
  8460. return true;
  8461. }
  8462. if (this.tsSkipParameterStart()) {
  8463. if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) {
  8464. return true;
  8465. }
  8466. if (this.match(11)) {
  8467. this.next();
  8468. if (this.match(19)) {
  8469. return true;
  8470. }
  8471. }
  8472. }
  8473. return false;
  8474. }
  8475. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  8476. return this.tsInType(() => {
  8477. const t = this.startNode();
  8478. this.expect(returnToken);
  8479. const node = this.startNode();
  8480. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  8481. if (asserts && this.match(78)) {
  8482. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  8483. if (thisTypePredicate.type === "TSThisType") {
  8484. node.parameterName = thisTypePredicate;
  8485. node.asserts = true;
  8486. node.typeAnnotation = null;
  8487. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  8488. } else {
  8489. this.resetStartLocationFromNode(thisTypePredicate, node);
  8490. thisTypePredicate.asserts = true;
  8491. }
  8492. t.typeAnnotation = thisTypePredicate;
  8493. return this.finishNode(t, "TSTypeAnnotation");
  8494. }
  8495. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  8496. if (!typePredicateVariable) {
  8497. if (!asserts) {
  8498. return this.tsParseTypeAnnotation(false, t);
  8499. }
  8500. node.parameterName = this.parseIdentifier();
  8501. node.asserts = asserts;
  8502. node.typeAnnotation = null;
  8503. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8504. return this.finishNode(t, "TSTypeAnnotation");
  8505. }
  8506. const type = this.tsParseTypeAnnotation(false);
  8507. node.parameterName = typePredicateVariable;
  8508. node.typeAnnotation = type;
  8509. node.asserts = asserts;
  8510. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8511. return this.finishNode(t, "TSTypeAnnotation");
  8512. });
  8513. }
  8514. tsTryParseTypeOrTypePredicateAnnotation() {
  8515. if (this.match(14)) {
  8516. return this.tsParseTypeOrTypePredicateAnnotation(14);
  8517. }
  8518. }
  8519. tsTryParseTypeAnnotation() {
  8520. if (this.match(14)) {
  8521. return this.tsParseTypeAnnotation();
  8522. }
  8523. }
  8524. tsTryParseType() {
  8525. return this.tsEatThenParseType(14);
  8526. }
  8527. tsParseTypePredicatePrefix() {
  8528. const id = this.parseIdentifier();
  8529. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  8530. this.next();
  8531. return id;
  8532. }
  8533. }
  8534. tsParseTypePredicateAsserts() {
  8535. if (this.state.type !== 109) {
  8536. return false;
  8537. }
  8538. const containsEsc = this.state.containsEsc;
  8539. this.next();
  8540. if (!tokenIsIdentifier(this.state.type) && !this.match(78)) {
  8541. return false;
  8542. }
  8543. if (containsEsc) {
  8544. this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, {
  8545. reservedWord: "asserts"
  8546. });
  8547. }
  8548. return true;
  8549. }
  8550. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  8551. this.tsInType(() => {
  8552. if (eatColon) this.expect(14);
  8553. t.typeAnnotation = this.tsParseType();
  8554. });
  8555. return this.finishNode(t, "TSTypeAnnotation");
  8556. }
  8557. tsParseType() {
  8558. assert(this.state.inType);
  8559. const type = this.tsParseNonConditionalType();
  8560. if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) {
  8561. return type;
  8562. }
  8563. const node = this.startNodeAtNode(type);
  8564. node.checkType = type;
  8565. node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType());
  8566. this.expect(17);
  8567. node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  8568. this.expect(14);
  8569. node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  8570. return this.finishNode(node, "TSConditionalType");
  8571. }
  8572. isAbstractConstructorSignature() {
  8573. return this.isContextual(124) && this.lookahead().type === 77;
  8574. }
  8575. tsParseNonConditionalType() {
  8576. if (this.tsIsStartOfFunctionType()) {
  8577. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  8578. }
  8579. if (this.match(77)) {
  8580. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  8581. } else if (this.isAbstractConstructorSignature()) {
  8582. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  8583. }
  8584. return this.tsParseUnionTypeOrHigher();
  8585. }
  8586. tsParseTypeAssertion() {
  8587. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8588. this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc);
  8589. }
  8590. const node = this.startNode();
  8591. node.typeAnnotation = this.tsInType(() => {
  8592. this.next();
  8593. return this.match(75) ? this.tsParseTypeReference() : this.tsParseType();
  8594. });
  8595. this.expect(48);
  8596. node.expression = this.parseMaybeUnary();
  8597. return this.finishNode(node, "TSTypeAssertion");
  8598. }
  8599. tsParseHeritageClause(token) {
  8600. const originalStartLoc = this.state.startLoc;
  8601. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => {
  8602. const node = this.startNode();
  8603. {
  8604. node.expression = this.tsParseEntityName(1 | 2);
  8605. if (this.match(47)) {
  8606. node.typeParameters = this.tsParseTypeArguments();
  8607. }
  8608. return this.finishNode(node, "TSExpressionWithTypeArguments");
  8609. }
  8610. });
  8611. if (!delimitedList.length) {
  8612. this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, {
  8613. token
  8614. });
  8615. }
  8616. return delimitedList;
  8617. }
  8618. tsParseInterfaceDeclaration(node, properties = {}) {
  8619. if (this.hasFollowingLineBreak()) return null;
  8620. this.expectContextual(129);
  8621. if (properties.declare) node.declare = true;
  8622. if (tokenIsIdentifier(this.state.type)) {
  8623. node.id = this.parseIdentifier();
  8624. this.checkIdentifier(node.id, 130);
  8625. } else {
  8626. node.id = null;
  8627. this.raise(TSErrors.MissingInterfaceName, this.state.startLoc);
  8628. }
  8629. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  8630. if (this.eat(81)) {
  8631. node.extends = this.tsParseHeritageClause("extends");
  8632. }
  8633. const body = this.startNode();
  8634. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  8635. node.body = this.finishNode(body, "TSInterfaceBody");
  8636. return this.finishNode(node, "TSInterfaceDeclaration");
  8637. }
  8638. tsParseTypeAliasDeclaration(node) {
  8639. node.id = this.parseIdentifier();
  8640. this.checkIdentifier(node.id, 2);
  8641. node.typeAnnotation = this.tsInType(() => {
  8642. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
  8643. this.expect(29);
  8644. if (this.isContextual(114) && this.lookahead().type !== 16) {
  8645. const node = this.startNode();
  8646. this.next();
  8647. return this.finishNode(node, "TSIntrinsicKeyword");
  8648. }
  8649. return this.tsParseType();
  8650. });
  8651. this.semicolon();
  8652. return this.finishNode(node, "TSTypeAliasDeclaration");
  8653. }
  8654. tsInTopLevelContext(cb) {
  8655. if (this.curContext() !== types.brace) {
  8656. const oldContext = this.state.context;
  8657. this.state.context = [oldContext[0]];
  8658. try {
  8659. return cb();
  8660. } finally {
  8661. this.state.context = oldContext;
  8662. }
  8663. } else {
  8664. return cb();
  8665. }
  8666. }
  8667. tsInType(cb) {
  8668. const oldInType = this.state.inType;
  8669. this.state.inType = true;
  8670. try {
  8671. return cb();
  8672. } finally {
  8673. this.state.inType = oldInType;
  8674. }
  8675. }
  8676. tsInDisallowConditionalTypesContext(cb) {
  8677. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  8678. this.state.inDisallowConditionalTypesContext = true;
  8679. try {
  8680. return cb();
  8681. } finally {
  8682. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  8683. }
  8684. }
  8685. tsInAllowConditionalTypesContext(cb) {
  8686. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  8687. this.state.inDisallowConditionalTypesContext = false;
  8688. try {
  8689. return cb();
  8690. } finally {
  8691. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  8692. }
  8693. }
  8694. tsEatThenParseType(token) {
  8695. if (this.match(token)) {
  8696. return this.tsNextThenParseType();
  8697. }
  8698. }
  8699. tsExpectThenParseType(token) {
  8700. return this.tsInType(() => {
  8701. this.expect(token);
  8702. return this.tsParseType();
  8703. });
  8704. }
  8705. tsNextThenParseType() {
  8706. return this.tsInType(() => {
  8707. this.next();
  8708. return this.tsParseType();
  8709. });
  8710. }
  8711. tsParseEnumMember() {
  8712. const node = this.startNode();
  8713. node.id = this.match(134) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true);
  8714. if (this.eat(29)) {
  8715. node.initializer = super.parseMaybeAssignAllowIn();
  8716. }
  8717. return this.finishNode(node, "TSEnumMember");
  8718. }
  8719. tsParseEnumDeclaration(node, properties = {}) {
  8720. if (properties.const) node.const = true;
  8721. if (properties.declare) node.declare = true;
  8722. this.expectContextual(126);
  8723. node.id = this.parseIdentifier();
  8724. this.checkIdentifier(node.id, node.const ? 8971 : 8459);
  8725. {
  8726. this.expect(5);
  8727. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8728. this.expect(8);
  8729. }
  8730. return this.finishNode(node, "TSEnumDeclaration");
  8731. }
  8732. tsParseEnumBody() {
  8733. const node = this.startNode();
  8734. this.expect(5);
  8735. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8736. this.expect(8);
  8737. return this.finishNode(node, "TSEnumBody");
  8738. }
  8739. tsParseModuleBlock() {
  8740. const node = this.startNode();
  8741. this.scope.enter(0);
  8742. this.expect(5);
  8743. super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  8744. this.scope.exit();
  8745. return this.finishNode(node, "TSModuleBlock");
  8746. }
  8747. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  8748. node.id = this.parseIdentifier();
  8749. if (!nested) {
  8750. this.checkIdentifier(node.id, 1024);
  8751. }
  8752. if (this.eat(16)) {
  8753. const inner = this.startNode();
  8754. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  8755. node.body = inner;
  8756. } else {
  8757. this.scope.enter(256);
  8758. this.prodParam.enter(0);
  8759. node.body = this.tsParseModuleBlock();
  8760. this.prodParam.exit();
  8761. this.scope.exit();
  8762. }
  8763. return this.finishNode(node, "TSModuleDeclaration");
  8764. }
  8765. tsParseAmbientExternalModuleDeclaration(node) {
  8766. if (this.isContextual(112)) {
  8767. node.kind = "global";
  8768. {
  8769. node.global = true;
  8770. }
  8771. node.id = this.parseIdentifier();
  8772. } else if (this.match(134)) {
  8773. node.kind = "module";
  8774. node.id = super.parseStringLiteral(this.state.value);
  8775. } else {
  8776. this.unexpected();
  8777. }
  8778. if (this.match(5)) {
  8779. this.scope.enter(256);
  8780. this.prodParam.enter(0);
  8781. node.body = this.tsParseModuleBlock();
  8782. this.prodParam.exit();
  8783. this.scope.exit();
  8784. } else {
  8785. this.semicolon();
  8786. }
  8787. return this.finishNode(node, "TSModuleDeclaration");
  8788. }
  8789. tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) {
  8790. node.isExport = isExport || false;
  8791. node.id = maybeDefaultIdentifier || this.parseIdentifier();
  8792. this.checkIdentifier(node.id, 4096);
  8793. this.expect(29);
  8794. const moduleReference = this.tsParseModuleReference();
  8795. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  8796. this.raise(TSErrors.ImportAliasHasImportType, moduleReference);
  8797. }
  8798. node.moduleReference = moduleReference;
  8799. this.semicolon();
  8800. return this.finishNode(node, "TSImportEqualsDeclaration");
  8801. }
  8802. tsIsExternalModuleReference() {
  8803. return this.isContextual(119) && this.lookaheadCharCode() === 40;
  8804. }
  8805. tsParseModuleReference() {
  8806. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(0);
  8807. }
  8808. tsParseExternalModuleReference() {
  8809. const node = this.startNode();
  8810. this.expectContextual(119);
  8811. this.expect(10);
  8812. if (!this.match(134)) {
  8813. this.unexpected();
  8814. }
  8815. node.expression = super.parseExprAtom();
  8816. this.expect(11);
  8817. this.sawUnambiguousESM = true;
  8818. return this.finishNode(node, "TSExternalModuleReference");
  8819. }
  8820. tsLookAhead(f) {
  8821. const state = this.state.clone();
  8822. const res = f();
  8823. this.state = state;
  8824. return res;
  8825. }
  8826. tsTryParseAndCatch(f) {
  8827. const result = this.tryParse(abort => f() || abort());
  8828. if (result.aborted || !result.node) return;
  8829. if (result.error) this.state = result.failState;
  8830. return result.node;
  8831. }
  8832. tsTryParse(f) {
  8833. const state = this.state.clone();
  8834. const result = f();
  8835. if (result !== undefined && result !== false) {
  8836. return result;
  8837. }
  8838. this.state = state;
  8839. }
  8840. tsTryParseDeclare(nany) {
  8841. if (this.isLineTerminator()) {
  8842. return;
  8843. }
  8844. let startType = this.state.type;
  8845. let kind;
  8846. if (this.isContextual(100)) {
  8847. startType = 74;
  8848. kind = "let";
  8849. }
  8850. return this.tsInAmbientContext(() => {
  8851. switch (startType) {
  8852. case 68:
  8853. nany.declare = true;
  8854. return super.parseFunctionStatement(nany, false, false);
  8855. case 80:
  8856. nany.declare = true;
  8857. return this.parseClass(nany, true, false);
  8858. case 126:
  8859. return this.tsParseEnumDeclaration(nany, {
  8860. declare: true
  8861. });
  8862. case 112:
  8863. return this.tsParseAmbientExternalModuleDeclaration(nany);
  8864. case 75:
  8865. case 74:
  8866. if (!this.match(75) || !this.isLookaheadContextual("enum")) {
  8867. nany.declare = true;
  8868. return this.parseVarStatement(nany, kind || this.state.value, true);
  8869. }
  8870. this.expect(75);
  8871. return this.tsParseEnumDeclaration(nany, {
  8872. const: true,
  8873. declare: true
  8874. });
  8875. case 129:
  8876. {
  8877. const result = this.tsParseInterfaceDeclaration(nany, {
  8878. declare: true
  8879. });
  8880. if (result) return result;
  8881. }
  8882. default:
  8883. if (tokenIsIdentifier(startType)) {
  8884. return this.tsParseDeclaration(nany, this.state.value, true, null);
  8885. }
  8886. }
  8887. });
  8888. }
  8889. tsTryParseExportDeclaration() {
  8890. return this.tsParseDeclaration(this.startNode(), this.state.value, true, null);
  8891. }
  8892. tsParseExpressionStatement(node, expr, decorators) {
  8893. switch (expr.name) {
  8894. case "declare":
  8895. {
  8896. const declaration = this.tsTryParseDeclare(node);
  8897. if (declaration) {
  8898. declaration.declare = true;
  8899. }
  8900. return declaration;
  8901. }
  8902. case "global":
  8903. if (this.match(5)) {
  8904. this.scope.enter(256);
  8905. this.prodParam.enter(0);
  8906. const mod = node;
  8907. mod.kind = "global";
  8908. {
  8909. node.global = true;
  8910. }
  8911. mod.id = expr;
  8912. mod.body = this.tsParseModuleBlock();
  8913. this.scope.exit();
  8914. this.prodParam.exit();
  8915. return this.finishNode(mod, "TSModuleDeclaration");
  8916. }
  8917. break;
  8918. default:
  8919. return this.tsParseDeclaration(node, expr.name, false, decorators);
  8920. }
  8921. }
  8922. tsParseDeclaration(node, value, next, decorators) {
  8923. switch (value) {
  8924. case "abstract":
  8925. if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) {
  8926. return this.tsParseAbstractDeclaration(node, decorators);
  8927. }
  8928. break;
  8929. case "module":
  8930. if (this.tsCheckLineTerminator(next)) {
  8931. if (this.match(134)) {
  8932. return this.tsParseAmbientExternalModuleDeclaration(node);
  8933. } else if (tokenIsIdentifier(this.state.type)) {
  8934. node.kind = "module";
  8935. return this.tsParseModuleOrNamespaceDeclaration(node);
  8936. }
  8937. }
  8938. break;
  8939. case "namespace":
  8940. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8941. node.kind = "namespace";
  8942. return this.tsParseModuleOrNamespaceDeclaration(node);
  8943. }
  8944. break;
  8945. case "type":
  8946. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8947. return this.tsParseTypeAliasDeclaration(node);
  8948. }
  8949. break;
  8950. }
  8951. }
  8952. tsCheckLineTerminator(next) {
  8953. if (next) {
  8954. if (this.hasFollowingLineBreak()) return false;
  8955. this.next();
  8956. return true;
  8957. }
  8958. return !this.isLineTerminator();
  8959. }
  8960. tsTryParseGenericAsyncArrowFunction(startLoc) {
  8961. if (!this.match(47)) return;
  8962. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8963. this.state.maybeInArrowParameters = true;
  8964. const res = this.tsTryParseAndCatch(() => {
  8965. const node = this.startNodeAt(startLoc);
  8966. node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  8967. super.parseFunctionParams(node);
  8968. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  8969. this.expect(19);
  8970. return node;
  8971. });
  8972. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8973. if (!res) return;
  8974. return super.parseArrowExpression(res, null, true);
  8975. }
  8976. tsParseTypeArgumentsInExpression() {
  8977. if (this.reScan_lt() !== 47) return;
  8978. return this.tsParseTypeArguments();
  8979. }
  8980. tsParseTypeArguments() {
  8981. const node = this.startNode();
  8982. node.params = this.tsInType(() => this.tsInTopLevelContext(() => {
  8983. this.expect(47);
  8984. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  8985. }));
  8986. if (node.params.length === 0) {
  8987. this.raise(TSErrors.EmptyTypeArguments, node);
  8988. } else if (!this.state.inType && this.curContext() === types.brace) {
  8989. this.reScan_lt_gt();
  8990. }
  8991. this.expect(48);
  8992. return this.finishNode(node, "TSTypeParameterInstantiation");
  8993. }
  8994. tsIsDeclarationStart() {
  8995. return tokenIsTSDeclarationStart(this.state.type);
  8996. }
  8997. isExportDefaultSpecifier() {
  8998. if (this.tsIsDeclarationStart()) return false;
  8999. return super.isExportDefaultSpecifier();
  9000. }
  9001. parseAssignableListItem(flags, decorators) {
  9002. const startLoc = this.state.startLoc;
  9003. const modified = {};
  9004. this.tsParseModifiers({
  9005. allowedModifiers: ["public", "private", "protected", "override", "readonly"]
  9006. }, modified);
  9007. const accessibility = modified.accessibility;
  9008. const override = modified.override;
  9009. const readonly = modified.readonly;
  9010. if (!(flags & 4) && (accessibility || readonly || override)) {
  9011. this.raise(TSErrors.UnexpectedParameterModifier, startLoc);
  9012. }
  9013. const left = this.parseMaybeDefault();
  9014. if (flags & 2) {
  9015. this.parseFunctionParamType(left);
  9016. }
  9017. const elt = this.parseMaybeDefault(left.loc.start, left);
  9018. if (accessibility || readonly || override) {
  9019. const pp = this.startNodeAt(startLoc);
  9020. if (decorators.length) {
  9021. pp.decorators = decorators;
  9022. }
  9023. if (accessibility) pp.accessibility = accessibility;
  9024. if (readonly) pp.readonly = readonly;
  9025. if (override) pp.override = override;
  9026. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  9027. this.raise(TSErrors.UnsupportedParameterPropertyKind, pp);
  9028. }
  9029. pp.parameter = elt;
  9030. return this.finishNode(pp, "TSParameterProperty");
  9031. }
  9032. if (decorators.length) {
  9033. left.decorators = decorators;
  9034. }
  9035. return elt;
  9036. }
  9037. isSimpleParameter(node) {
  9038. return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node);
  9039. }
  9040. tsDisallowOptionalPattern(node) {
  9041. for (const param of node.params) {
  9042. if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) {
  9043. this.raise(TSErrors.PatternIsOptional, param);
  9044. }
  9045. }
  9046. }
  9047. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  9048. super.setArrowFunctionParameters(node, params, trailingCommaLoc);
  9049. this.tsDisallowOptionalPattern(node);
  9050. }
  9051. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  9052. if (this.match(14)) {
  9053. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9054. }
  9055. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  9056. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  9057. return this.finishNode(node, bodilessType);
  9058. }
  9059. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  9060. this.raise(TSErrors.DeclareFunctionHasImplementation, node);
  9061. if (node.declare) {
  9062. return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  9063. }
  9064. }
  9065. this.tsDisallowOptionalPattern(node);
  9066. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  9067. }
  9068. registerFunctionStatementId(node) {
  9069. if (!node.body && node.id) {
  9070. this.checkIdentifier(node.id, 1024);
  9071. } else {
  9072. super.registerFunctionStatementId(node);
  9073. }
  9074. }
  9075. tsCheckForInvalidTypeCasts(items) {
  9076. items.forEach(node => {
  9077. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  9078. this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation);
  9079. }
  9080. });
  9081. }
  9082. toReferencedList(exprList, isInParens) {
  9083. this.tsCheckForInvalidTypeCasts(exprList);
  9084. return exprList;
  9085. }
  9086. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  9087. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  9088. if (node.type === "ArrayExpression") {
  9089. this.tsCheckForInvalidTypeCasts(node.elements);
  9090. }
  9091. return node;
  9092. }
  9093. parseSubscript(base, startLoc, noCalls, state) {
  9094. if (!this.hasPrecedingLineBreak() && this.match(35)) {
  9095. this.state.canStartJSXElement = false;
  9096. this.next();
  9097. const nonNullExpression = this.startNodeAt(startLoc);
  9098. nonNullExpression.expression = base;
  9099. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  9100. }
  9101. let isOptionalCall = false;
  9102. if (this.match(18) && this.lookaheadCharCode() === 60) {
  9103. if (noCalls) {
  9104. state.stop = true;
  9105. return base;
  9106. }
  9107. state.optionalChainMember = isOptionalCall = true;
  9108. this.next();
  9109. }
  9110. if (this.match(47) || this.match(51)) {
  9111. let missingParenErrorLoc;
  9112. const result = this.tsTryParseAndCatch(() => {
  9113. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  9114. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc);
  9115. if (asyncArrowFn) {
  9116. return asyncArrowFn;
  9117. }
  9118. }
  9119. const typeArguments = this.tsParseTypeArgumentsInExpression();
  9120. if (!typeArguments) return;
  9121. if (isOptionalCall && !this.match(10)) {
  9122. missingParenErrorLoc = this.state.curPosition();
  9123. return;
  9124. }
  9125. if (tokenIsTemplate(this.state.type)) {
  9126. const result = super.parseTaggedTemplateExpression(base, startLoc, state);
  9127. {
  9128. result.typeParameters = typeArguments;
  9129. }
  9130. return result;
  9131. }
  9132. if (!noCalls && this.eat(10)) {
  9133. const node = this.startNodeAt(startLoc);
  9134. node.callee = base;
  9135. node.arguments = this.parseCallExpressionArguments(11);
  9136. this.tsCheckForInvalidTypeCasts(node.arguments);
  9137. {
  9138. node.typeParameters = typeArguments;
  9139. }
  9140. if (state.optionalChainMember) {
  9141. node.optional = isOptionalCall;
  9142. }
  9143. return this.finishCallExpression(node, state.optionalChainMember);
  9144. }
  9145. const tokenType = this.state.type;
  9146. if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) {
  9147. return;
  9148. }
  9149. const node = this.startNodeAt(startLoc);
  9150. node.expression = base;
  9151. {
  9152. node.typeParameters = typeArguments;
  9153. }
  9154. return this.finishNode(node, "TSInstantiationExpression");
  9155. });
  9156. if (missingParenErrorLoc) {
  9157. this.unexpected(missingParenErrorLoc, 10);
  9158. }
  9159. if (result) {
  9160. if (result.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) {
  9161. this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc);
  9162. }
  9163. return result;
  9164. }
  9165. }
  9166. return super.parseSubscript(base, startLoc, noCalls, state);
  9167. }
  9168. parseNewCallee(node) {
  9169. var _callee$extra;
  9170. super.parseNewCallee(node);
  9171. const {
  9172. callee
  9173. } = node;
  9174. if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) {
  9175. {
  9176. node.typeParameters = callee.typeParameters;
  9177. }
  9178. node.callee = callee.expression;
  9179. }
  9180. }
  9181. parseExprOp(left, leftStartLoc, minPrec) {
  9182. let isSatisfies;
  9183. if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) {
  9184. const node = this.startNodeAt(leftStartLoc);
  9185. node.expression = left;
  9186. node.typeAnnotation = this.tsInType(() => {
  9187. this.next();
  9188. if (this.match(75)) {
  9189. if (isSatisfies) {
  9190. this.raise(Errors.UnexpectedKeyword, this.state.startLoc, {
  9191. keyword: "const"
  9192. });
  9193. }
  9194. return this.tsParseTypeReference();
  9195. }
  9196. return this.tsParseType();
  9197. });
  9198. this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression");
  9199. this.reScan_lt_gt();
  9200. return this.parseExprOp(node, leftStartLoc, minPrec);
  9201. }
  9202. return super.parseExprOp(left, leftStartLoc, minPrec);
  9203. }
  9204. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9205. if (!this.state.isAmbientContext) {
  9206. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  9207. }
  9208. }
  9209. checkImportReflection(node) {
  9210. super.checkImportReflection(node);
  9211. if (node.module && node.importKind !== "value") {
  9212. this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  9213. }
  9214. }
  9215. checkDuplicateExports() {}
  9216. isPotentialImportPhase(isExport) {
  9217. if (super.isPotentialImportPhase(isExport)) return true;
  9218. if (this.isContextual(130)) {
  9219. const ch = this.lookaheadCharCode();
  9220. return isExport ? ch === 123 || ch === 42 : ch !== 61;
  9221. }
  9222. return !isExport && this.isContextual(87);
  9223. }
  9224. applyImportPhase(node, isExport, phase, loc) {
  9225. super.applyImportPhase(node, isExport, phase, loc);
  9226. if (isExport) {
  9227. node.exportKind = phase === "type" ? "type" : "value";
  9228. } else {
  9229. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  9230. }
  9231. }
  9232. parseImport(node) {
  9233. if (this.match(134)) {
  9234. node.importKind = "value";
  9235. return super.parseImport(node);
  9236. }
  9237. let importNode;
  9238. if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) {
  9239. node.importKind = "value";
  9240. return this.tsParseImportEqualsDeclaration(node);
  9241. } else if (this.isContextual(130)) {
  9242. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false);
  9243. if (this.lookaheadCharCode() === 61) {
  9244. return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier);
  9245. } else {
  9246. importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier);
  9247. }
  9248. } else {
  9249. importNode = super.parseImport(node);
  9250. }
  9251. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  9252. this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode);
  9253. }
  9254. return importNode;
  9255. }
  9256. parseExport(node, decorators) {
  9257. if (this.match(83)) {
  9258. this.next();
  9259. const nodeImportEquals = node;
  9260. let maybeDefaultIdentifier = null;
  9261. if (this.isContextual(130) && this.isPotentialImportPhase(false)) {
  9262. maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false);
  9263. } else {
  9264. nodeImportEquals.importKind = "value";
  9265. }
  9266. return this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true);
  9267. } else if (this.eat(29)) {
  9268. const assign = node;
  9269. assign.expression = super.parseExpression();
  9270. this.semicolon();
  9271. this.sawUnambiguousESM = true;
  9272. return this.finishNode(assign, "TSExportAssignment");
  9273. } else if (this.eatContextual(93)) {
  9274. const decl = node;
  9275. this.expectContextual(128);
  9276. decl.id = this.parseIdentifier();
  9277. this.semicolon();
  9278. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  9279. } else {
  9280. return super.parseExport(node, decorators);
  9281. }
  9282. }
  9283. isAbstractClass() {
  9284. return this.isContextual(124) && this.lookahead().type === 80;
  9285. }
  9286. parseExportDefaultExpression() {
  9287. if (this.isAbstractClass()) {
  9288. const cls = this.startNode();
  9289. this.next();
  9290. cls.abstract = true;
  9291. return this.parseClass(cls, true, true);
  9292. }
  9293. if (this.match(129)) {
  9294. const result = this.tsParseInterfaceDeclaration(this.startNode());
  9295. if (result) return result;
  9296. }
  9297. return super.parseExportDefaultExpression();
  9298. }
  9299. parseVarStatement(node, kind, allowMissingInitializer = false) {
  9300. const {
  9301. isAmbientContext
  9302. } = this.state;
  9303. const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext);
  9304. if (!isAmbientContext) return declaration;
  9305. for (const {
  9306. id,
  9307. init
  9308. } of declaration.declarations) {
  9309. if (!init) continue;
  9310. if (kind !== "const" || !!id.typeAnnotation) {
  9311. this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init);
  9312. } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) {
  9313. this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init);
  9314. }
  9315. }
  9316. return declaration;
  9317. }
  9318. parseStatementContent(flags, decorators) {
  9319. if (this.match(75) && this.isLookaheadContextual("enum")) {
  9320. const node = this.startNode();
  9321. this.expect(75);
  9322. return this.tsParseEnumDeclaration(node, {
  9323. const: true
  9324. });
  9325. }
  9326. if (this.isContextual(126)) {
  9327. return this.tsParseEnumDeclaration(this.startNode());
  9328. }
  9329. if (this.isContextual(129)) {
  9330. const result = this.tsParseInterfaceDeclaration(this.startNode());
  9331. if (result) return result;
  9332. }
  9333. return super.parseStatementContent(flags, decorators);
  9334. }
  9335. parseAccessModifier() {
  9336. return this.tsParseModifier(["public", "protected", "private"]);
  9337. }
  9338. tsHasSomeModifiers(member, modifiers) {
  9339. return modifiers.some(modifier => {
  9340. if (tsIsAccessModifier(modifier)) {
  9341. return member.accessibility === modifier;
  9342. }
  9343. return !!member[modifier];
  9344. });
  9345. }
  9346. tsIsStartOfStaticBlocks() {
  9347. return this.isContextual(106) && this.lookaheadCharCode() === 123;
  9348. }
  9349. parseClassMember(classBody, member, state) {
  9350. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  9351. this.tsParseModifiers({
  9352. allowedModifiers: modifiers,
  9353. disallowedModifiers: ["in", "out"],
  9354. stopOnStartOfClassStaticBlock: true,
  9355. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  9356. }, member);
  9357. const callParseClassMemberWithIsStatic = () => {
  9358. if (this.tsIsStartOfStaticBlocks()) {
  9359. this.next();
  9360. this.next();
  9361. if (this.tsHasSomeModifiers(member, modifiers)) {
  9362. this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition());
  9363. }
  9364. super.parseClassStaticBlock(classBody, member);
  9365. } else {
  9366. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  9367. }
  9368. };
  9369. if (member.declare) {
  9370. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  9371. } else {
  9372. callParseClassMemberWithIsStatic();
  9373. }
  9374. }
  9375. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  9376. const idx = this.tsTryParseIndexSignature(member);
  9377. if (idx) {
  9378. classBody.body.push(idx);
  9379. if (member.abstract) {
  9380. this.raise(TSErrors.IndexSignatureHasAbstract, member);
  9381. }
  9382. if (member.accessibility) {
  9383. this.raise(TSErrors.IndexSignatureHasAccessibility, member, {
  9384. modifier: member.accessibility
  9385. });
  9386. }
  9387. if (member.declare) {
  9388. this.raise(TSErrors.IndexSignatureHasDeclare, member);
  9389. }
  9390. if (member.override) {
  9391. this.raise(TSErrors.IndexSignatureHasOverride, member);
  9392. }
  9393. return;
  9394. }
  9395. if (!this.state.inAbstractClass && member.abstract) {
  9396. this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member);
  9397. }
  9398. if (member.override) {
  9399. if (!state.hadSuperClass) {
  9400. this.raise(TSErrors.OverrideNotInSubClass, member);
  9401. }
  9402. }
  9403. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  9404. }
  9405. parsePostMemberNameModifiers(methodOrProp) {
  9406. const optional = this.eat(17);
  9407. if (optional) methodOrProp.optional = true;
  9408. if (methodOrProp.readonly && this.match(10)) {
  9409. this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp);
  9410. }
  9411. if (methodOrProp.declare && this.match(10)) {
  9412. this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp);
  9413. }
  9414. }
  9415. parseExpressionStatement(node, expr, decorators) {
  9416. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr, decorators) : undefined;
  9417. return decl || super.parseExpressionStatement(node, expr, decorators);
  9418. }
  9419. shouldParseExportDeclaration() {
  9420. if (this.tsIsDeclarationStart()) return true;
  9421. return super.shouldParseExportDeclaration();
  9422. }
  9423. parseConditional(expr, startLoc, refExpressionErrors) {
  9424. if (!this.state.maybeInArrowParameters || !this.match(17)) {
  9425. return super.parseConditional(expr, startLoc, refExpressionErrors);
  9426. }
  9427. const result = this.tryParse(() => super.parseConditional(expr, startLoc));
  9428. if (!result.node) {
  9429. if (result.error) {
  9430. super.setOptionalParametersError(refExpressionErrors, result.error);
  9431. }
  9432. return expr;
  9433. }
  9434. if (result.error) this.state = result.failState;
  9435. return result.node;
  9436. }
  9437. parseParenItem(node, startLoc) {
  9438. const newNode = super.parseParenItem(node, startLoc);
  9439. if (this.eat(17)) {
  9440. newNode.optional = true;
  9441. this.resetEndLocation(node);
  9442. }
  9443. if (this.match(14)) {
  9444. const typeCastNode = this.startNodeAt(startLoc);
  9445. typeCastNode.expression = node;
  9446. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  9447. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  9448. }
  9449. return node;
  9450. }
  9451. parseExportDeclaration(node) {
  9452. if (!this.state.isAmbientContext && this.isContextual(125)) {
  9453. return this.tsInAmbientContext(() => this.parseExportDeclaration(node));
  9454. }
  9455. const startLoc = this.state.startLoc;
  9456. const isDeclare = this.eatContextual(125);
  9457. if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) {
  9458. throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc);
  9459. }
  9460. const isIdentifier = tokenIsIdentifier(this.state.type);
  9461. const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node);
  9462. if (!declaration) return null;
  9463. if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) {
  9464. node.exportKind = "type";
  9465. }
  9466. if (isDeclare) {
  9467. this.resetStartLocation(declaration, startLoc);
  9468. declaration.declare = true;
  9469. }
  9470. return declaration;
  9471. }
  9472. parseClassId(node, isStatement, optionalId, bindingType) {
  9473. if ((!isStatement || optionalId) && this.isContextual(113)) {
  9474. return;
  9475. }
  9476. super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331);
  9477. const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  9478. if (typeParameters) node.typeParameters = typeParameters;
  9479. }
  9480. parseClassPropertyAnnotation(node) {
  9481. if (!node.optional) {
  9482. if (this.eat(35)) {
  9483. node.definite = true;
  9484. } else if (this.eat(17)) {
  9485. node.optional = true;
  9486. }
  9487. }
  9488. const type = this.tsTryParseTypeAnnotation();
  9489. if (type) node.typeAnnotation = type;
  9490. }
  9491. parseClassProperty(node) {
  9492. this.parseClassPropertyAnnotation(node);
  9493. if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) {
  9494. this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc);
  9495. }
  9496. if (node.abstract && this.match(29)) {
  9497. const {
  9498. key
  9499. } = node;
  9500. this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, {
  9501. propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  9502. });
  9503. }
  9504. return super.parseClassProperty(node);
  9505. }
  9506. parseClassPrivateProperty(node) {
  9507. if (node.abstract) {
  9508. this.raise(TSErrors.PrivateElementHasAbstract, node);
  9509. }
  9510. if (node.accessibility) {
  9511. this.raise(TSErrors.PrivateElementHasAccessibility, node, {
  9512. modifier: node.accessibility
  9513. });
  9514. }
  9515. this.parseClassPropertyAnnotation(node);
  9516. return super.parseClassPrivateProperty(node);
  9517. }
  9518. parseClassAccessorProperty(node) {
  9519. this.parseClassPropertyAnnotation(node);
  9520. if (node.optional) {
  9521. this.raise(TSErrors.AccessorCannotBeOptional, node);
  9522. }
  9523. return super.parseClassAccessorProperty(node);
  9524. }
  9525. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9526. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9527. if (typeParameters && isConstructor) {
  9528. this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters);
  9529. }
  9530. const {
  9531. declare = false,
  9532. kind
  9533. } = method;
  9534. if (declare && (kind === "get" || kind === "set")) {
  9535. this.raise(TSErrors.DeclareAccessor, method, {
  9536. kind
  9537. });
  9538. }
  9539. if (typeParameters) method.typeParameters = typeParameters;
  9540. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  9541. }
  9542. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9543. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9544. if (typeParameters) method.typeParameters = typeParameters;
  9545. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  9546. }
  9547. declareClassPrivateMethodInScope(node, kind) {
  9548. if (node.type === "TSDeclareMethod") return;
  9549. if (node.type === "MethodDefinition" && !hasOwnProperty.call(node.value, "body")) {
  9550. return;
  9551. }
  9552. super.declareClassPrivateMethodInScope(node, kind);
  9553. }
  9554. parseClassSuper(node) {
  9555. super.parseClassSuper(node);
  9556. if (node.superClass && (this.match(47) || this.match(51))) {
  9557. {
  9558. node.superTypeParameters = this.tsParseTypeArgumentsInExpression();
  9559. }
  9560. }
  9561. if (this.eatContextual(113)) {
  9562. node.implements = this.tsParseHeritageClause("implements");
  9563. }
  9564. }
  9565. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  9566. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9567. if (typeParameters) prop.typeParameters = typeParameters;
  9568. return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  9569. }
  9570. parseFunctionParams(node, isConstructor) {
  9571. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9572. if (typeParameters) node.typeParameters = typeParameters;
  9573. super.parseFunctionParams(node, isConstructor);
  9574. }
  9575. parseVarId(decl, kind) {
  9576. super.parseVarId(decl, kind);
  9577. if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) {
  9578. decl.definite = true;
  9579. }
  9580. const type = this.tsTryParseTypeAnnotation();
  9581. if (type) {
  9582. decl.id.typeAnnotation = type;
  9583. this.resetEndLocation(decl.id);
  9584. }
  9585. }
  9586. parseAsyncArrowFromCallExpression(node, call) {
  9587. if (this.match(14)) {
  9588. node.returnType = this.tsParseTypeAnnotation();
  9589. }
  9590. return super.parseAsyncArrowFromCallExpression(node, call);
  9591. }
  9592. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  9593. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2;
  9594. let state;
  9595. let jsx;
  9596. let typeCast;
  9597. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  9598. state = this.state.clone();
  9599. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  9600. if (!jsx.error) return jsx.node;
  9601. const {
  9602. context
  9603. } = this.state;
  9604. const currentContext = context[context.length - 1];
  9605. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  9606. context.pop();
  9607. }
  9608. }
  9609. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) {
  9610. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  9611. }
  9612. if (!state || state === this.state) state = this.state.clone();
  9613. let typeParameters;
  9614. const arrow = this.tryParse(abort => {
  9615. var _expr$extra, _typeParameters;
  9616. typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  9617. const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  9618. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  9619. abort();
  9620. }
  9621. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  9622. this.resetStartLocationFromNode(expr, typeParameters);
  9623. }
  9624. expr.typeParameters = typeParameters;
  9625. return expr;
  9626. }, state);
  9627. if (!arrow.error && !arrow.aborted) {
  9628. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  9629. return arrow.node;
  9630. }
  9631. if (!jsx) {
  9632. assert(!this.hasPlugin("jsx"));
  9633. typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  9634. if (!typeCast.error) return typeCast.node;
  9635. }
  9636. if ((_jsx2 = jsx) != null && _jsx2.node) {
  9637. this.state = jsx.failState;
  9638. return jsx.node;
  9639. }
  9640. if (arrow.node) {
  9641. this.state = arrow.failState;
  9642. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  9643. return arrow.node;
  9644. }
  9645. if ((_typeCast = typeCast) != null && _typeCast.node) {
  9646. this.state = typeCast.failState;
  9647. return typeCast.node;
  9648. }
  9649. throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error);
  9650. }
  9651. reportReservedArrowTypeParam(node) {
  9652. var _node$extra;
  9653. if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  9654. this.raise(TSErrors.ReservedArrowTypeParam, node);
  9655. }
  9656. }
  9657. parseMaybeUnary(refExpressionErrors, sawUnary) {
  9658. if (!this.hasPlugin("jsx") && this.match(47)) {
  9659. return this.tsParseTypeAssertion();
  9660. }
  9661. return super.parseMaybeUnary(refExpressionErrors, sawUnary);
  9662. }
  9663. parseArrow(node) {
  9664. if (this.match(14)) {
  9665. const result = this.tryParse(abort => {
  9666. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9667. if (this.canInsertSemicolon() || !this.match(19)) abort();
  9668. return returnType;
  9669. });
  9670. if (result.aborted) return;
  9671. if (!result.thrown) {
  9672. if (result.error) this.state = result.failState;
  9673. node.returnType = result.node;
  9674. }
  9675. }
  9676. return super.parseArrow(node);
  9677. }
  9678. parseFunctionParamType(param) {
  9679. if (this.eat(17)) {
  9680. param.optional = true;
  9681. }
  9682. const type = this.tsTryParseTypeAnnotation();
  9683. if (type) param.typeAnnotation = type;
  9684. this.resetEndLocation(param);
  9685. return param;
  9686. }
  9687. isAssignable(node, isBinding) {
  9688. switch (node.type) {
  9689. case "TSTypeCastExpression":
  9690. return this.isAssignable(node.expression, isBinding);
  9691. case "TSParameterProperty":
  9692. return true;
  9693. default:
  9694. return super.isAssignable(node, isBinding);
  9695. }
  9696. }
  9697. toAssignable(node, isLHS = false) {
  9698. switch (node.type) {
  9699. case "ParenthesizedExpression":
  9700. this.toAssignableParenthesizedExpression(node, isLHS);
  9701. break;
  9702. case "TSAsExpression":
  9703. case "TSSatisfiesExpression":
  9704. case "TSNonNullExpression":
  9705. case "TSTypeAssertion":
  9706. if (isLHS) {
  9707. this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node);
  9708. } else {
  9709. this.raise(TSErrors.UnexpectedTypeCastInParameter, node);
  9710. }
  9711. this.toAssignable(node.expression, isLHS);
  9712. break;
  9713. case "AssignmentExpression":
  9714. if (!isLHS && node.left.type === "TSTypeCastExpression") {
  9715. node.left = this.typeCastToParameter(node.left);
  9716. }
  9717. default:
  9718. super.toAssignable(node, isLHS);
  9719. }
  9720. }
  9721. toAssignableParenthesizedExpression(node, isLHS) {
  9722. switch (node.expression.type) {
  9723. case "TSAsExpression":
  9724. case "TSSatisfiesExpression":
  9725. case "TSNonNullExpression":
  9726. case "TSTypeAssertion":
  9727. case "ParenthesizedExpression":
  9728. this.toAssignable(node.expression, isLHS);
  9729. break;
  9730. default:
  9731. super.toAssignable(node, isLHS);
  9732. }
  9733. }
  9734. checkToRestConversion(node, allowPattern) {
  9735. switch (node.type) {
  9736. case "TSAsExpression":
  9737. case "TSSatisfiesExpression":
  9738. case "TSTypeAssertion":
  9739. case "TSNonNullExpression":
  9740. this.checkToRestConversion(node.expression, false);
  9741. break;
  9742. default:
  9743. super.checkToRestConversion(node, allowPattern);
  9744. }
  9745. }
  9746. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  9747. switch (type) {
  9748. case "TSTypeCastExpression":
  9749. return true;
  9750. case "TSParameterProperty":
  9751. return "parameter";
  9752. case "TSNonNullExpression":
  9753. case "TSInstantiationExpression":
  9754. return "expression";
  9755. case "TSAsExpression":
  9756. case "TSSatisfiesExpression":
  9757. case "TSTypeAssertion":
  9758. return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true];
  9759. default:
  9760. return super.isValidLVal(type, isUnparenthesizedInAssign, binding);
  9761. }
  9762. }
  9763. parseBindingAtom() {
  9764. if (this.state.type === 78) {
  9765. return this.parseIdentifier(true);
  9766. }
  9767. return super.parseBindingAtom();
  9768. }
  9769. parseMaybeDecoratorArguments(expr, startLoc) {
  9770. if (this.match(47) || this.match(51)) {
  9771. const typeArguments = this.tsParseTypeArgumentsInExpression();
  9772. if (this.match(10)) {
  9773. const call = super.parseMaybeDecoratorArguments(expr, startLoc);
  9774. {
  9775. call.typeParameters = typeArguments;
  9776. }
  9777. return call;
  9778. }
  9779. this.unexpected(null, 10);
  9780. }
  9781. return super.parseMaybeDecoratorArguments(expr, startLoc);
  9782. }
  9783. checkCommaAfterRest(close) {
  9784. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  9785. this.next();
  9786. return false;
  9787. }
  9788. return super.checkCommaAfterRest(close);
  9789. }
  9790. isClassMethod() {
  9791. return this.match(47) || super.isClassMethod();
  9792. }
  9793. isClassProperty() {
  9794. return this.match(35) || this.match(14) || super.isClassProperty();
  9795. }
  9796. parseMaybeDefault(startLoc, left) {
  9797. const node = super.parseMaybeDefault(startLoc, left);
  9798. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  9799. this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation);
  9800. }
  9801. return node;
  9802. }
  9803. getTokenFromCode(code) {
  9804. if (this.state.inType) {
  9805. if (code === 62) {
  9806. this.finishOp(48, 1);
  9807. return;
  9808. }
  9809. if (code === 60) {
  9810. this.finishOp(47, 1);
  9811. return;
  9812. }
  9813. }
  9814. super.getTokenFromCode(code);
  9815. }
  9816. reScan_lt_gt() {
  9817. const {
  9818. type
  9819. } = this.state;
  9820. if (type === 47) {
  9821. this.state.pos -= 1;
  9822. this.readToken_lt();
  9823. } else if (type === 48) {
  9824. this.state.pos -= 1;
  9825. this.readToken_gt();
  9826. }
  9827. }
  9828. reScan_lt() {
  9829. const {
  9830. type
  9831. } = this.state;
  9832. if (type === 51) {
  9833. this.state.pos -= 2;
  9834. this.finishOp(47, 1);
  9835. return 47;
  9836. }
  9837. return type;
  9838. }
  9839. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  9840. for (let i = 0; i < exprList.length; i++) {
  9841. const expr = exprList[i];
  9842. if ((expr == null ? void 0 : expr.type) === "TSTypeCastExpression") {
  9843. exprList[i] = this.typeCastToParameter(expr);
  9844. }
  9845. }
  9846. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  9847. }
  9848. typeCastToParameter(node) {
  9849. node.expression.typeAnnotation = node.typeAnnotation;
  9850. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  9851. return node.expression;
  9852. }
  9853. shouldParseArrow(params) {
  9854. if (this.match(14)) {
  9855. return params.every(expr => this.isAssignable(expr, true));
  9856. }
  9857. return super.shouldParseArrow(params);
  9858. }
  9859. shouldParseAsyncArrow() {
  9860. return this.match(14) || super.shouldParseAsyncArrow();
  9861. }
  9862. canHaveLeadingDecorator() {
  9863. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  9864. }
  9865. jsxParseOpeningElementAfterName(node) {
  9866. if (this.match(47) || this.match(51)) {
  9867. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression());
  9868. if (typeArguments) {
  9869. {
  9870. node.typeParameters = typeArguments;
  9871. }
  9872. }
  9873. }
  9874. return super.jsxParseOpeningElementAfterName(node);
  9875. }
  9876. getGetterSetterExpectedParamCount(method) {
  9877. const baseCount = super.getGetterSetterExpectedParamCount(method);
  9878. const params = this.getObjectOrClassMethodParams(method);
  9879. const firstParam = params[0];
  9880. const hasContextParam = firstParam && this.isThisParam(firstParam);
  9881. return hasContextParam ? baseCount + 1 : baseCount;
  9882. }
  9883. parseCatchClauseParam() {
  9884. const param = super.parseCatchClauseParam();
  9885. const type = this.tsTryParseTypeAnnotation();
  9886. if (type) {
  9887. param.typeAnnotation = type;
  9888. this.resetEndLocation(param);
  9889. }
  9890. return param;
  9891. }
  9892. tsInAmbientContext(cb) {
  9893. const {
  9894. isAmbientContext: oldIsAmbientContext,
  9895. strict: oldStrict
  9896. } = this.state;
  9897. this.state.isAmbientContext = true;
  9898. this.state.strict = false;
  9899. try {
  9900. return cb();
  9901. } finally {
  9902. this.state.isAmbientContext = oldIsAmbientContext;
  9903. this.state.strict = oldStrict;
  9904. }
  9905. }
  9906. parseClass(node, isStatement, optionalId) {
  9907. const oldInAbstractClass = this.state.inAbstractClass;
  9908. this.state.inAbstractClass = !!node.abstract;
  9909. try {
  9910. return super.parseClass(node, isStatement, optionalId);
  9911. } finally {
  9912. this.state.inAbstractClass = oldInAbstractClass;
  9913. }
  9914. }
  9915. tsParseAbstractDeclaration(node, decorators) {
  9916. if (this.match(80)) {
  9917. node.abstract = true;
  9918. return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false));
  9919. } else if (this.isContextual(129)) {
  9920. if (!this.hasFollowingLineBreak()) {
  9921. node.abstract = true;
  9922. this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, node);
  9923. return this.tsParseInterfaceDeclaration(node);
  9924. }
  9925. } else {
  9926. this.unexpected(null, 80);
  9927. }
  9928. }
  9929. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) {
  9930. const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  9931. if (method.abstract) {
  9932. const hasEstreePlugin = this.hasPlugin("estree");
  9933. const methodFn = hasEstreePlugin ? method.value : method;
  9934. if (methodFn.body) {
  9935. const {
  9936. key
  9937. } = method;
  9938. this.raise(TSErrors.AbstractMethodHasImplementation, method, {
  9939. methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  9940. });
  9941. }
  9942. }
  9943. return method;
  9944. }
  9945. tsParseTypeParameterName() {
  9946. const typeName = this.parseIdentifier();
  9947. return typeName.name;
  9948. }
  9949. shouldParseAsAmbientContext() {
  9950. return !!this.getPluginOption("typescript", "dts");
  9951. }
  9952. parse() {
  9953. if (this.shouldParseAsAmbientContext()) {
  9954. this.state.isAmbientContext = true;
  9955. }
  9956. return super.parse();
  9957. }
  9958. getExpression() {
  9959. if (this.shouldParseAsAmbientContext()) {
  9960. this.state.isAmbientContext = true;
  9961. }
  9962. return super.getExpression();
  9963. }
  9964. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  9965. if (!isString && isMaybeTypeOnly) {
  9966. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  9967. return this.finishNode(node, "ExportSpecifier");
  9968. }
  9969. node.exportKind = "value";
  9970. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  9971. }
  9972. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  9973. if (!importedIsString && isMaybeTypeOnly) {
  9974. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  9975. return this.finishNode(specifier, "ImportSpecifier");
  9976. }
  9977. specifier.importKind = "value";
  9978. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096);
  9979. }
  9980. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  9981. const leftOfAsKey = isImport ? "imported" : "local";
  9982. const rightOfAsKey = isImport ? "local" : "exported";
  9983. let leftOfAs = node[leftOfAsKey];
  9984. let rightOfAs;
  9985. let hasTypeSpecifier = false;
  9986. let canParseAsKeyword = true;
  9987. const loc = leftOfAs.loc.start;
  9988. if (this.isContextual(93)) {
  9989. const firstAs = this.parseIdentifier();
  9990. if (this.isContextual(93)) {
  9991. const secondAs = this.parseIdentifier();
  9992. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9993. hasTypeSpecifier = true;
  9994. leftOfAs = firstAs;
  9995. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9996. canParseAsKeyword = false;
  9997. } else {
  9998. rightOfAs = secondAs;
  9999. canParseAsKeyword = false;
  10000. }
  10001. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  10002. canParseAsKeyword = false;
  10003. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  10004. } else {
  10005. hasTypeSpecifier = true;
  10006. leftOfAs = firstAs;
  10007. }
  10008. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  10009. hasTypeSpecifier = true;
  10010. if (isImport) {
  10011. leftOfAs = this.parseIdentifier(true);
  10012. if (!this.isContextual(93)) {
  10013. this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true);
  10014. }
  10015. } else {
  10016. leftOfAs = this.parseModuleExportName();
  10017. }
  10018. }
  10019. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  10020. this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc);
  10021. }
  10022. node[leftOfAsKey] = leftOfAs;
  10023. node[rightOfAsKey] = rightOfAs;
  10024. const kindKey = isImport ? "importKind" : "exportKind";
  10025. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  10026. if (canParseAsKeyword && this.eatContextual(93)) {
  10027. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  10028. }
  10029. if (!node[rightOfAsKey]) {
  10030. node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
  10031. }
  10032. if (isImport) {
  10033. this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096);
  10034. }
  10035. }
  10036. };
  10037. function isPossiblyLiteralEnum(expression) {
  10038. if (expression.type !== "MemberExpression") return false;
  10039. const {
  10040. computed,
  10041. property
  10042. } = expression;
  10043. if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) {
  10044. return false;
  10045. }
  10046. return isUncomputedMemberExpressionChain(expression.object);
  10047. }
  10048. function isValidAmbientConstInitializer(expression, estree) {
  10049. var _expression$extra;
  10050. const {
  10051. type
  10052. } = expression;
  10053. if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) {
  10054. return false;
  10055. }
  10056. if (estree) {
  10057. if (type === "Literal") {
  10058. const {
  10059. value
  10060. } = expression;
  10061. if (typeof value === "string" || typeof value === "boolean") {
  10062. return true;
  10063. }
  10064. }
  10065. } else {
  10066. if (type === "StringLiteral" || type === "BooleanLiteral") {
  10067. return true;
  10068. }
  10069. }
  10070. if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) {
  10071. return true;
  10072. }
  10073. if (type === "TemplateLiteral" && expression.expressions.length === 0) {
  10074. return true;
  10075. }
  10076. if (isPossiblyLiteralEnum(expression)) {
  10077. return true;
  10078. }
  10079. return false;
  10080. }
  10081. function isNumber(expression, estree) {
  10082. if (estree) {
  10083. return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression);
  10084. }
  10085. return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral";
  10086. }
  10087. function isNegativeNumber(expression, estree) {
  10088. if (expression.type === "UnaryExpression") {
  10089. const {
  10090. operator,
  10091. argument
  10092. } = expression;
  10093. if (operator === "-" && isNumber(argument, estree)) {
  10094. return true;
  10095. }
  10096. }
  10097. return false;
  10098. }
  10099. function isUncomputedMemberExpressionChain(expression) {
  10100. if (expression.type === "Identifier") return true;
  10101. if (expression.type !== "MemberExpression" || expression.computed) {
  10102. return false;
  10103. }
  10104. return isUncomputedMemberExpressionChain(expression.object);
  10105. }
  10106. const PlaceholderErrors = ParseErrorEnum`placeholders`({
  10107. ClassNameIsRequired: "A class name is required.",
  10108. UnexpectedSpace: "Unexpected space in placeholder."
  10109. });
  10110. var placeholders = superClass => class PlaceholdersParserMixin extends superClass {
  10111. parsePlaceholder(expectedNode) {
  10112. if (this.match(133)) {
  10113. const node = this.startNode();
  10114. this.next();
  10115. this.assertNoSpace();
  10116. node.name = super.parseIdentifier(true);
  10117. this.assertNoSpace();
  10118. this.expect(133);
  10119. return this.finishPlaceholder(node, expectedNode);
  10120. }
  10121. }
  10122. finishPlaceholder(node, expectedNode) {
  10123. let placeholder = node;
  10124. if (!placeholder.expectedNode || !placeholder.type) {
  10125. placeholder = this.finishNode(placeholder, "Placeholder");
  10126. }
  10127. placeholder.expectedNode = expectedNode;
  10128. return placeholder;
  10129. }
  10130. getTokenFromCode(code) {
  10131. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  10132. this.finishOp(133, 2);
  10133. } else {
  10134. super.getTokenFromCode(code);
  10135. }
  10136. }
  10137. parseExprAtom(refExpressionErrors) {
  10138. return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors);
  10139. }
  10140. parseIdentifier(liberal) {
  10141. return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal);
  10142. }
  10143. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  10144. if (word !== undefined) {
  10145. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  10146. }
  10147. }
  10148. parseBindingAtom() {
  10149. return this.parsePlaceholder("Pattern") || super.parseBindingAtom();
  10150. }
  10151. isValidLVal(type, isParenthesized, binding) {
  10152. return type === "Placeholder" || super.isValidLVal(type, isParenthesized, binding);
  10153. }
  10154. toAssignable(node, isLHS) {
  10155. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  10156. node.expectedNode = "Pattern";
  10157. } else {
  10158. super.toAssignable(node, isLHS);
  10159. }
  10160. }
  10161. chStartsBindingIdentifier(ch, pos) {
  10162. if (super.chStartsBindingIdentifier(ch, pos)) {
  10163. return true;
  10164. }
  10165. const nextToken = this.lookahead();
  10166. if (nextToken.type === 133) {
  10167. return true;
  10168. }
  10169. return false;
  10170. }
  10171. verifyBreakContinue(node, isBreak) {
  10172. if (node.label && node.label.type === "Placeholder") return;
  10173. super.verifyBreakContinue(node, isBreak);
  10174. }
  10175. parseExpressionStatement(node, expr) {
  10176. var _expr$extra;
  10177. if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  10178. return super.parseExpressionStatement(node, expr);
  10179. }
  10180. if (this.match(14)) {
  10181. const stmt = node;
  10182. stmt.label = this.finishPlaceholder(expr, "Identifier");
  10183. this.next();
  10184. stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration();
  10185. return this.finishNode(stmt, "LabeledStatement");
  10186. }
  10187. this.semicolon();
  10188. const stmtPlaceholder = node;
  10189. stmtPlaceholder.name = expr.name;
  10190. return this.finishPlaceholder(stmtPlaceholder, "Statement");
  10191. }
  10192. parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) {
  10193. return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse);
  10194. }
  10195. parseFunctionId(requireId) {
  10196. return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId);
  10197. }
  10198. parseClass(node, isStatement, optionalId) {
  10199. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  10200. this.next();
  10201. const oldStrict = this.state.strict;
  10202. const placeholder = this.parsePlaceholder("Identifier");
  10203. if (placeholder) {
  10204. if (this.match(81) || this.match(133) || this.match(5)) {
  10205. node.id = placeholder;
  10206. } else if (optionalId || !isStatement) {
  10207. node.id = null;
  10208. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  10209. return this.finishNode(node, type);
  10210. } else {
  10211. throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc);
  10212. }
  10213. } else {
  10214. this.parseClassId(node, isStatement, optionalId);
  10215. }
  10216. super.parseClassSuper(node);
  10217. node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict);
  10218. return this.finishNode(node, type);
  10219. }
  10220. parseExport(node, decorators) {
  10221. const placeholder = this.parsePlaceholder("Identifier");
  10222. if (!placeholder) return super.parseExport(node, decorators);
  10223. const node2 = node;
  10224. if (!this.isContextual(98) && !this.match(12)) {
  10225. node2.specifiers = [];
  10226. node2.source = null;
  10227. node2.declaration = this.finishPlaceholder(placeholder, "Declaration");
  10228. return this.finishNode(node2, "ExportNamedDeclaration");
  10229. }
  10230. this.expectPlugin("exportDefaultFrom");
  10231. const specifier = this.startNode();
  10232. specifier.exported = placeholder;
  10233. node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  10234. return super.parseExport(node2, decorators);
  10235. }
  10236. isExportDefaultSpecifier() {
  10237. if (this.match(65)) {
  10238. const next = this.nextTokenStart();
  10239. if (this.isUnparsedContextual(next, "from")) {
  10240. if (this.input.startsWith(tokenLabelName(133), this.nextTokenStartSince(next + 4))) {
  10241. return true;
  10242. }
  10243. }
  10244. }
  10245. return super.isExportDefaultSpecifier();
  10246. }
  10247. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  10248. var _specifiers;
  10249. if ((_specifiers = node.specifiers) != null && _specifiers.length) {
  10250. return true;
  10251. }
  10252. return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  10253. }
  10254. checkExport(node) {
  10255. const {
  10256. specifiers
  10257. } = node;
  10258. if (specifiers != null && specifiers.length) {
  10259. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  10260. }
  10261. super.checkExport(node);
  10262. node.specifiers = specifiers;
  10263. }
  10264. parseImport(node) {
  10265. const placeholder = this.parsePlaceholder("Identifier");
  10266. if (!placeholder) return super.parseImport(node);
  10267. node.specifiers = [];
  10268. if (!this.isContextual(98) && !this.match(12)) {
  10269. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  10270. this.semicolon();
  10271. return this.finishNode(node, "ImportDeclaration");
  10272. }
  10273. const specifier = this.startNodeAtNode(placeholder);
  10274. specifier.local = placeholder;
  10275. node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier"));
  10276. if (this.eat(12)) {
  10277. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  10278. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  10279. }
  10280. this.expectContextual(98);
  10281. node.source = this.parseImportSource();
  10282. this.semicolon();
  10283. return this.finishNode(node, "ImportDeclaration");
  10284. }
  10285. parseImportSource() {
  10286. return this.parsePlaceholder("StringLiteral") || super.parseImportSource();
  10287. }
  10288. assertNoSpace() {
  10289. if (this.state.start > this.offsetToSourcePos(this.state.lastTokEndLoc.index)) {
  10290. this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc);
  10291. }
  10292. }
  10293. };
  10294. var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass {
  10295. parseV8Intrinsic() {
  10296. if (this.match(54)) {
  10297. const v8IntrinsicStartLoc = this.state.startLoc;
  10298. const node = this.startNode();
  10299. this.next();
  10300. if (tokenIsIdentifier(this.state.type)) {
  10301. const name = this.parseIdentifierName();
  10302. const identifier = this.createIdentifier(node, name);
  10303. identifier.type = "V8IntrinsicIdentifier";
  10304. if (this.match(10)) {
  10305. return identifier;
  10306. }
  10307. }
  10308. this.unexpected(v8IntrinsicStartLoc);
  10309. }
  10310. }
  10311. parseExprAtom(refExpressionErrors) {
  10312. return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors);
  10313. }
  10314. };
  10315. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  10316. const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"];
  10317. function validatePlugins(pluginsMap) {
  10318. if (pluginsMap.has("decorators")) {
  10319. if (pluginsMap.has("decorators-legacy")) {
  10320. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  10321. }
  10322. const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport;
  10323. if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") {
  10324. throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");
  10325. }
  10326. const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized;
  10327. if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") {
  10328. throw new Error("'allowCallParenthesized' must be a boolean.");
  10329. }
  10330. }
  10331. if (pluginsMap.has("flow") && pluginsMap.has("typescript")) {
  10332. throw new Error("Cannot combine flow and typescript plugins.");
  10333. }
  10334. if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) {
  10335. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  10336. }
  10337. if (pluginsMap.has("pipelineOperator")) {
  10338. var _pluginsMap$get;
  10339. const proposal = pluginsMap.get("pipelineOperator").proposal;
  10340. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  10341. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  10342. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  10343. }
  10344. const tupleSyntaxIsHash = ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash";
  10345. if (proposal === "hack") {
  10346. if (pluginsMap.has("placeholders")) {
  10347. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  10348. }
  10349. if (pluginsMap.has("v8intrinsic")) {
  10350. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  10351. }
  10352. const topicToken = pluginsMap.get("pipelineOperator").topicToken;
  10353. if (!TOPIC_TOKENS.includes(topicToken)) {
  10354. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  10355. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  10356. }
  10357. if (topicToken === "#" && tupleSyntaxIsHash) {
  10358. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  10359. }
  10360. } else if (proposal === "smart" && tupleSyntaxIsHash) {
  10361. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  10362. }
  10363. }
  10364. if (pluginsMap.has("moduleAttributes")) {
  10365. {
  10366. if (pluginsMap.has("deprecatedImportAssert") || pluginsMap.has("importAssertions")) {
  10367. throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");
  10368. }
  10369. const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version;
  10370. if (moduleAttributesVersionPluginOption !== "may-2020") {
  10371. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  10372. }
  10373. }
  10374. }
  10375. if (pluginsMap.has("importAssertions")) {
  10376. if (pluginsMap.has("deprecatedImportAssert")) {
  10377. throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");
  10378. }
  10379. }
  10380. if (!pluginsMap.has("deprecatedImportAssert") && pluginsMap.has("importAttributes") && pluginsMap.get("importAttributes").deprecatedAssertSyntax) {
  10381. {
  10382. pluginsMap.set("deprecatedImportAssert", {});
  10383. }
  10384. }
  10385. if (pluginsMap.has("recordAndTuple")) {
  10386. const syntaxType = pluginsMap.get("recordAndTuple").syntaxType;
  10387. if (syntaxType != null) {
  10388. {
  10389. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  10390. if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) {
  10391. throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  10392. }
  10393. }
  10394. }
  10395. }
  10396. if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) {
  10397. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  10398. error.missingPlugins = "doExpressions";
  10399. throw error;
  10400. }
  10401. if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") {
  10402. throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'.");
  10403. }
  10404. }
  10405. const mixinPlugins = {
  10406. estree,
  10407. jsx,
  10408. flow,
  10409. typescript,
  10410. v8intrinsic,
  10411. placeholders
  10412. };
  10413. const mixinPluginNames = Object.keys(mixinPlugins);
  10414. class ExpressionParser extends LValParser {
  10415. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  10416. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  10417. return;
  10418. }
  10419. const key = prop.key;
  10420. const name = key.type === "Identifier" ? key.name : key.value;
  10421. if (name === "__proto__") {
  10422. if (isRecord) {
  10423. this.raise(Errors.RecordNoProto, key);
  10424. return;
  10425. }
  10426. if (protoRef.used) {
  10427. if (refExpressionErrors) {
  10428. if (refExpressionErrors.doubleProtoLoc === null) {
  10429. refExpressionErrors.doubleProtoLoc = key.loc.start;
  10430. }
  10431. } else {
  10432. this.raise(Errors.DuplicateProto, key);
  10433. }
  10434. }
  10435. protoRef.used = true;
  10436. }
  10437. }
  10438. shouldExitDescending(expr, potentialArrowAt) {
  10439. return expr.type === "ArrowFunctionExpression" && this.offsetToSourcePos(expr.start) === potentialArrowAt;
  10440. }
  10441. getExpression() {
  10442. this.enterInitialScopes();
  10443. this.nextToken();
  10444. const expr = this.parseExpression();
  10445. if (!this.match(140)) {
  10446. this.unexpected();
  10447. }
  10448. this.finalizeRemainingComments();
  10449. expr.comments = this.comments;
  10450. expr.errors = this.state.errors;
  10451. if (this.optionFlags & 128) {
  10452. expr.tokens = this.tokens;
  10453. }
  10454. return expr;
  10455. }
  10456. parseExpression(disallowIn, refExpressionErrors) {
  10457. if (disallowIn) {
  10458. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10459. }
  10460. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10461. }
  10462. parseExpressionBase(refExpressionErrors) {
  10463. const startLoc = this.state.startLoc;
  10464. const expr = this.parseMaybeAssign(refExpressionErrors);
  10465. if (this.match(12)) {
  10466. const node = this.startNodeAt(startLoc);
  10467. node.expressions = [expr];
  10468. while (this.eat(12)) {
  10469. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  10470. }
  10471. this.toReferencedList(node.expressions);
  10472. return this.finishNode(node, "SequenceExpression");
  10473. }
  10474. return expr;
  10475. }
  10476. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  10477. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10478. }
  10479. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  10480. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10481. }
  10482. setOptionalParametersError(refExpressionErrors, resultError) {
  10483. var _resultError$loc;
  10484. refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc;
  10485. }
  10486. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  10487. const startLoc = this.state.startLoc;
  10488. if (this.isContextual(108)) {
  10489. if (this.prodParam.hasYield) {
  10490. let left = this.parseYield();
  10491. if (afterLeftParse) {
  10492. left = afterLeftParse.call(this, left, startLoc);
  10493. }
  10494. return left;
  10495. }
  10496. }
  10497. let ownExpressionErrors;
  10498. if (refExpressionErrors) {
  10499. ownExpressionErrors = false;
  10500. } else {
  10501. refExpressionErrors = new ExpressionErrors();
  10502. ownExpressionErrors = true;
  10503. }
  10504. const {
  10505. type
  10506. } = this.state;
  10507. if (type === 10 || tokenIsIdentifier(type)) {
  10508. this.state.potentialArrowAt = this.state.start;
  10509. }
  10510. let left = this.parseMaybeConditional(refExpressionErrors);
  10511. if (afterLeftParse) {
  10512. left = afterLeftParse.call(this, left, startLoc);
  10513. }
  10514. if (tokenIsAssignment(this.state.type)) {
  10515. const node = this.startNodeAt(startLoc);
  10516. const operator = this.state.value;
  10517. node.operator = operator;
  10518. if (this.match(29)) {
  10519. this.toAssignable(left, true);
  10520. node.left = left;
  10521. const startIndex = startLoc.index;
  10522. if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) {
  10523. refExpressionErrors.doubleProtoLoc = null;
  10524. }
  10525. if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) {
  10526. refExpressionErrors.shorthandAssignLoc = null;
  10527. }
  10528. if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) {
  10529. this.checkDestructuringPrivate(refExpressionErrors);
  10530. refExpressionErrors.privateKeyLoc = null;
  10531. }
  10532. } else {
  10533. node.left = left;
  10534. }
  10535. this.next();
  10536. node.right = this.parseMaybeAssign();
  10537. this.checkLVal(left, this.finishNode(node, "AssignmentExpression"));
  10538. return node;
  10539. } else if (ownExpressionErrors) {
  10540. this.checkExpressionErrors(refExpressionErrors, true);
  10541. }
  10542. return left;
  10543. }
  10544. parseMaybeConditional(refExpressionErrors) {
  10545. const startLoc = this.state.startLoc;
  10546. const potentialArrowAt = this.state.potentialArrowAt;
  10547. const expr = this.parseExprOps(refExpressionErrors);
  10548. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10549. return expr;
  10550. }
  10551. return this.parseConditional(expr, startLoc, refExpressionErrors);
  10552. }
  10553. parseConditional(expr, startLoc, refExpressionErrors) {
  10554. if (this.eat(17)) {
  10555. const node = this.startNodeAt(startLoc);
  10556. node.test = expr;
  10557. node.consequent = this.parseMaybeAssignAllowIn();
  10558. this.expect(14);
  10559. node.alternate = this.parseMaybeAssign();
  10560. return this.finishNode(node, "ConditionalExpression");
  10561. }
  10562. return expr;
  10563. }
  10564. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  10565. return this.match(139) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  10566. }
  10567. parseExprOps(refExpressionErrors) {
  10568. const startLoc = this.state.startLoc;
  10569. const potentialArrowAt = this.state.potentialArrowAt;
  10570. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  10571. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10572. return expr;
  10573. }
  10574. return this.parseExprOp(expr, startLoc, -1);
  10575. }
  10576. parseExprOp(left, leftStartLoc, minPrec) {
  10577. if (this.isPrivateName(left)) {
  10578. const value = this.getPrivateNameSV(left);
  10579. if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) {
  10580. this.raise(Errors.PrivateInExpectedIn, left, {
  10581. identifierName: value
  10582. });
  10583. }
  10584. this.classScope.usePrivateName(value, left.loc.start);
  10585. }
  10586. const op = this.state.type;
  10587. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) {
  10588. let prec = tokenOperatorPrecedence(op);
  10589. if (prec > minPrec) {
  10590. if (op === 39) {
  10591. this.expectPlugin("pipelineOperator");
  10592. if (this.state.inFSharpPipelineDirectBody) {
  10593. return left;
  10594. }
  10595. this.checkPipelineAtInfixOperator(left, leftStartLoc);
  10596. }
  10597. const node = this.startNodeAt(leftStartLoc);
  10598. node.left = left;
  10599. node.operator = this.state.value;
  10600. const logical = op === 41 || op === 42;
  10601. const coalesce = op === 40;
  10602. if (coalesce) {
  10603. prec = tokenOperatorPrecedence(42);
  10604. }
  10605. this.next();
  10606. if (op === 39 && this.hasPlugin(["pipelineOperator", {
  10607. proposal: "minimal"
  10608. }])) {
  10609. if (this.state.type === 96 && this.prodParam.hasAwait) {
  10610. throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc);
  10611. }
  10612. }
  10613. node.right = this.parseExprOpRightExpr(op, prec);
  10614. const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  10615. const nextOp = this.state.type;
  10616. if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) {
  10617. throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc);
  10618. }
  10619. return this.parseExprOp(finishedNode, leftStartLoc, minPrec);
  10620. }
  10621. }
  10622. return left;
  10623. }
  10624. parseExprOpRightExpr(op, prec) {
  10625. const startLoc = this.state.startLoc;
  10626. switch (op) {
  10627. case 39:
  10628. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  10629. case "hack":
  10630. return this.withTopicBindingContext(() => {
  10631. return this.parseHackPipeBody();
  10632. });
  10633. case "fsharp":
  10634. return this.withSoloAwaitPermittingContext(() => {
  10635. return this.parseFSharpPipelineBody(prec);
  10636. });
  10637. }
  10638. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  10639. return this.withTopicBindingContext(() => {
  10640. if (this.prodParam.hasYield && this.isContextual(108)) {
  10641. throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc);
  10642. }
  10643. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc);
  10644. });
  10645. }
  10646. default:
  10647. return this.parseExprOpBaseRightExpr(op, prec);
  10648. }
  10649. }
  10650. parseExprOpBaseRightExpr(op, prec) {
  10651. const startLoc = this.state.startLoc;
  10652. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  10653. }
  10654. parseHackPipeBody() {
  10655. var _body$extra;
  10656. const {
  10657. startLoc
  10658. } = this.state;
  10659. const body = this.parseMaybeAssign();
  10660. const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type);
  10661. if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  10662. this.raise(Errors.PipeUnparenthesizedBody, startLoc, {
  10663. type: body.type
  10664. });
  10665. }
  10666. if (!this.topicReferenceWasUsedInCurrentContext()) {
  10667. this.raise(Errors.PipeTopicUnused, startLoc);
  10668. }
  10669. return body;
  10670. }
  10671. checkExponentialAfterUnary(node) {
  10672. if (this.match(57)) {
  10673. this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument);
  10674. }
  10675. }
  10676. parseMaybeUnary(refExpressionErrors, sawUnary) {
  10677. const startLoc = this.state.startLoc;
  10678. const isAwait = this.isContextual(96);
  10679. if (isAwait && this.recordAwaitIfAllowed()) {
  10680. this.next();
  10681. const expr = this.parseAwait(startLoc);
  10682. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  10683. return expr;
  10684. }
  10685. const update = this.match(34);
  10686. const node = this.startNode();
  10687. if (tokenIsPrefix(this.state.type)) {
  10688. node.operator = this.state.value;
  10689. node.prefix = true;
  10690. if (this.match(72)) {
  10691. this.expectPlugin("throwExpressions");
  10692. }
  10693. const isDelete = this.match(89);
  10694. this.next();
  10695. node.argument = this.parseMaybeUnary(null, true);
  10696. this.checkExpressionErrors(refExpressionErrors, true);
  10697. if (this.state.strict && isDelete) {
  10698. const arg = node.argument;
  10699. if (arg.type === "Identifier") {
  10700. this.raise(Errors.StrictDelete, node);
  10701. } else if (this.hasPropertyAsPrivateName(arg)) {
  10702. this.raise(Errors.DeletePrivateField, node);
  10703. }
  10704. }
  10705. if (!update) {
  10706. if (!sawUnary) {
  10707. this.checkExponentialAfterUnary(node);
  10708. }
  10709. return this.finishNode(node, "UnaryExpression");
  10710. }
  10711. }
  10712. const expr = this.parseUpdate(node, update, refExpressionErrors);
  10713. if (isAwait) {
  10714. const {
  10715. type
  10716. } = this.state;
  10717. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  10718. if (startsExpr && !this.isAmbiguousAwait()) {
  10719. this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc);
  10720. return this.parseAwait(startLoc);
  10721. }
  10722. }
  10723. return expr;
  10724. }
  10725. parseUpdate(node, update, refExpressionErrors) {
  10726. if (update) {
  10727. const updateExpressionNode = node;
  10728. this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression"));
  10729. return node;
  10730. }
  10731. const startLoc = this.state.startLoc;
  10732. let expr = this.parseExprSubscripts(refExpressionErrors);
  10733. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  10734. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  10735. const node = this.startNodeAt(startLoc);
  10736. node.operator = this.state.value;
  10737. node.prefix = false;
  10738. node.argument = expr;
  10739. this.next();
  10740. this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression"));
  10741. }
  10742. return expr;
  10743. }
  10744. parseExprSubscripts(refExpressionErrors) {
  10745. const startLoc = this.state.startLoc;
  10746. const potentialArrowAt = this.state.potentialArrowAt;
  10747. const expr = this.parseExprAtom(refExpressionErrors);
  10748. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10749. return expr;
  10750. }
  10751. return this.parseSubscripts(expr, startLoc);
  10752. }
  10753. parseSubscripts(base, startLoc, noCalls) {
  10754. const state = {
  10755. optionalChainMember: false,
  10756. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  10757. stop: false
  10758. };
  10759. do {
  10760. base = this.parseSubscript(base, startLoc, noCalls, state);
  10761. state.maybeAsyncArrow = false;
  10762. } while (!state.stop);
  10763. return base;
  10764. }
  10765. parseSubscript(base, startLoc, noCalls, state) {
  10766. const {
  10767. type
  10768. } = this.state;
  10769. if (!noCalls && type === 15) {
  10770. return this.parseBind(base, startLoc, noCalls, state);
  10771. } else if (tokenIsTemplate(type)) {
  10772. return this.parseTaggedTemplateExpression(base, startLoc, state);
  10773. }
  10774. let optional = false;
  10775. if (type === 18) {
  10776. if (noCalls) {
  10777. this.raise(Errors.OptionalChainingNoNew, this.state.startLoc);
  10778. if (this.lookaheadCharCode() === 40) {
  10779. state.stop = true;
  10780. return base;
  10781. }
  10782. }
  10783. state.optionalChainMember = optional = true;
  10784. this.next();
  10785. }
  10786. if (!noCalls && this.match(10)) {
  10787. return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional);
  10788. } else {
  10789. const computed = this.eat(0);
  10790. if (computed || optional || this.eat(16)) {
  10791. return this.parseMember(base, startLoc, state, computed, optional);
  10792. } else {
  10793. state.stop = true;
  10794. return base;
  10795. }
  10796. }
  10797. }
  10798. parseMember(base, startLoc, state, computed, optional) {
  10799. const node = this.startNodeAt(startLoc);
  10800. node.object = base;
  10801. node.computed = computed;
  10802. if (computed) {
  10803. node.property = this.parseExpression();
  10804. this.expect(3);
  10805. } else if (this.match(139)) {
  10806. if (base.type === "Super") {
  10807. this.raise(Errors.SuperPrivateField, startLoc);
  10808. }
  10809. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  10810. node.property = this.parsePrivateName();
  10811. } else {
  10812. node.property = this.parseIdentifier(true);
  10813. }
  10814. if (state.optionalChainMember) {
  10815. node.optional = optional;
  10816. return this.finishNode(node, "OptionalMemberExpression");
  10817. } else {
  10818. return this.finishNode(node, "MemberExpression");
  10819. }
  10820. }
  10821. parseBind(base, startLoc, noCalls, state) {
  10822. const node = this.startNodeAt(startLoc);
  10823. node.object = base;
  10824. this.next();
  10825. node.callee = this.parseNoCallExpr();
  10826. state.stop = true;
  10827. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls);
  10828. }
  10829. parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) {
  10830. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10831. let refExpressionErrors = null;
  10832. this.state.maybeInArrowParameters = true;
  10833. this.next();
  10834. const node = this.startNodeAt(startLoc);
  10835. node.callee = base;
  10836. const {
  10837. maybeAsyncArrow,
  10838. optionalChainMember
  10839. } = state;
  10840. if (maybeAsyncArrow) {
  10841. this.expressionScope.enter(newAsyncArrowScope());
  10842. refExpressionErrors = new ExpressionErrors();
  10843. }
  10844. if (optionalChainMember) {
  10845. node.optional = optional;
  10846. }
  10847. if (optional) {
  10848. node.arguments = this.parseCallExpressionArguments(11);
  10849. } else {
  10850. node.arguments = this.parseCallExpressionArguments(11, base.type !== "Super", node, refExpressionErrors);
  10851. }
  10852. let finishedNode = this.finishCallExpression(node, optionalChainMember);
  10853. if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  10854. state.stop = true;
  10855. this.checkDestructuringPrivate(refExpressionErrors);
  10856. this.expressionScope.validateAsPattern();
  10857. this.expressionScope.exit();
  10858. finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode);
  10859. } else {
  10860. if (maybeAsyncArrow) {
  10861. this.checkExpressionErrors(refExpressionErrors, true);
  10862. this.expressionScope.exit();
  10863. }
  10864. this.toReferencedArguments(finishedNode);
  10865. }
  10866. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10867. return finishedNode;
  10868. }
  10869. toReferencedArguments(node, isParenthesizedExpr) {
  10870. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  10871. }
  10872. parseTaggedTemplateExpression(base, startLoc, state) {
  10873. const node = this.startNodeAt(startLoc);
  10874. node.tag = base;
  10875. node.quasi = this.parseTemplate(true);
  10876. if (state.optionalChainMember) {
  10877. this.raise(Errors.OptionalChainingNoTemplate, startLoc);
  10878. }
  10879. return this.finishNode(node, "TaggedTemplateExpression");
  10880. }
  10881. atPossibleAsyncArrow(base) {
  10882. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.offsetToSourcePos(base.start) === this.state.potentialArrowAt;
  10883. }
  10884. finishCallExpression(node, optional) {
  10885. if (node.callee.type === "Import") {
  10886. if (node.arguments.length === 0 || node.arguments.length > 2) {
  10887. this.raise(Errors.ImportCallArity, node);
  10888. } else {
  10889. for (const arg of node.arguments) {
  10890. if (arg.type === "SpreadElement") {
  10891. this.raise(Errors.ImportCallSpreadArgument, arg);
  10892. }
  10893. }
  10894. }
  10895. }
  10896. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  10897. }
  10898. parseCallExpressionArguments(close, allowPlaceholder, nodeForExtra, refExpressionErrors) {
  10899. const elts = [];
  10900. let first = true;
  10901. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10902. this.state.inFSharpPipelineDirectBody = false;
  10903. while (!this.eat(close)) {
  10904. if (first) {
  10905. first = false;
  10906. } else {
  10907. this.expect(12);
  10908. if (this.match(close)) {
  10909. if (nodeForExtra) {
  10910. this.addTrailingCommaExtraToNode(nodeForExtra);
  10911. }
  10912. this.next();
  10913. break;
  10914. }
  10915. }
  10916. elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
  10917. }
  10918. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10919. return elts;
  10920. }
  10921. shouldParseAsyncArrow() {
  10922. return this.match(19) && !this.canInsertSemicolon();
  10923. }
  10924. parseAsyncArrowFromCallExpression(node, call) {
  10925. var _call$extra;
  10926. this.resetPreviousNodeTrailingComments(call);
  10927. this.expect(19);
  10928. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc);
  10929. if (call.innerComments) {
  10930. setInnerComments(node, call.innerComments);
  10931. }
  10932. if (call.callee.trailingComments) {
  10933. setInnerComments(node, call.callee.trailingComments);
  10934. }
  10935. return node;
  10936. }
  10937. parseNoCallExpr() {
  10938. const startLoc = this.state.startLoc;
  10939. return this.parseSubscripts(this.parseExprAtom(), startLoc, true);
  10940. }
  10941. parseExprAtom(refExpressionErrors) {
  10942. let node;
  10943. let decorators = null;
  10944. const {
  10945. type
  10946. } = this.state;
  10947. switch (type) {
  10948. case 79:
  10949. return this.parseSuper();
  10950. case 83:
  10951. node = this.startNode();
  10952. this.next();
  10953. if (this.match(16)) {
  10954. return this.parseImportMetaProperty(node);
  10955. }
  10956. if (this.match(10)) {
  10957. if (this.optionFlags & 256) {
  10958. return this.parseImportCall(node);
  10959. } else {
  10960. return this.finishNode(node, "Import");
  10961. }
  10962. } else {
  10963. this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc);
  10964. return this.finishNode(node, "Import");
  10965. }
  10966. case 78:
  10967. node = this.startNode();
  10968. this.next();
  10969. return this.finishNode(node, "ThisExpression");
  10970. case 90:
  10971. {
  10972. return this.parseDo(this.startNode(), false);
  10973. }
  10974. case 56:
  10975. case 31:
  10976. {
  10977. this.readRegexp();
  10978. return this.parseRegExpLiteral(this.state.value);
  10979. }
  10980. case 135:
  10981. return this.parseNumericLiteral(this.state.value);
  10982. case 136:
  10983. return this.parseBigIntLiteral(this.state.value);
  10984. case 134:
  10985. return this.parseStringLiteral(this.state.value);
  10986. case 84:
  10987. return this.parseNullLiteral();
  10988. case 85:
  10989. return this.parseBooleanLiteral(true);
  10990. case 86:
  10991. return this.parseBooleanLiteral(false);
  10992. case 10:
  10993. {
  10994. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10995. return this.parseParenAndDistinguishExpression(canBeArrow);
  10996. }
  10997. case 2:
  10998. case 1:
  10999. {
  11000. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
  11001. }
  11002. case 0:
  11003. {
  11004. return this.parseArrayLike(3, true, false, refExpressionErrors);
  11005. }
  11006. case 6:
  11007. case 7:
  11008. {
  11009. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  11010. }
  11011. case 5:
  11012. {
  11013. return this.parseObjectLike(8, false, false, refExpressionErrors);
  11014. }
  11015. case 68:
  11016. return this.parseFunctionOrFunctionSent();
  11017. case 26:
  11018. decorators = this.parseDecorators();
  11019. case 80:
  11020. return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false);
  11021. case 77:
  11022. return this.parseNewOrNewTarget();
  11023. case 25:
  11024. case 24:
  11025. return this.parseTemplate(false);
  11026. case 15:
  11027. {
  11028. node = this.startNode();
  11029. this.next();
  11030. node.object = null;
  11031. const callee = node.callee = this.parseNoCallExpr();
  11032. if (callee.type === "MemberExpression") {
  11033. return this.finishNode(node, "BindExpression");
  11034. } else {
  11035. throw this.raise(Errors.UnsupportedBind, callee);
  11036. }
  11037. }
  11038. case 139:
  11039. {
  11040. this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, {
  11041. identifierName: this.state.value
  11042. });
  11043. return this.parsePrivateName();
  11044. }
  11045. case 33:
  11046. {
  11047. return this.parseTopicReferenceThenEqualsSign(54, "%");
  11048. }
  11049. case 32:
  11050. {
  11051. return this.parseTopicReferenceThenEqualsSign(44, "^");
  11052. }
  11053. case 37:
  11054. case 38:
  11055. {
  11056. return this.parseTopicReference("hack");
  11057. }
  11058. case 44:
  11059. case 54:
  11060. case 27:
  11061. {
  11062. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  11063. if (pipeProposal) {
  11064. return this.parseTopicReference(pipeProposal);
  11065. }
  11066. this.unexpected();
  11067. break;
  11068. }
  11069. case 47:
  11070. {
  11071. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  11072. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  11073. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  11074. } else {
  11075. this.unexpected();
  11076. }
  11077. break;
  11078. }
  11079. default:
  11080. if (type === 137) {
  11081. return this.parseDecimalLiteral(this.state.value);
  11082. }
  11083. if (tokenIsIdentifier(type)) {
  11084. if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) {
  11085. return this.parseModuleExpression();
  11086. }
  11087. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  11088. const containsEsc = this.state.containsEsc;
  11089. const id = this.parseIdentifier();
  11090. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  11091. const {
  11092. type
  11093. } = this.state;
  11094. if (type === 68) {
  11095. this.resetPreviousNodeTrailingComments(id);
  11096. this.next();
  11097. return this.parseAsyncFunctionExpression(this.startNodeAtNode(id));
  11098. } else if (tokenIsIdentifier(type)) {
  11099. if (this.lookaheadCharCode() === 61) {
  11100. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  11101. } else {
  11102. return id;
  11103. }
  11104. } else if (type === 90) {
  11105. this.resetPreviousNodeTrailingComments(id);
  11106. return this.parseDo(this.startNodeAtNode(id), true);
  11107. }
  11108. }
  11109. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  11110. this.next();
  11111. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  11112. }
  11113. return id;
  11114. } else {
  11115. this.unexpected();
  11116. }
  11117. }
  11118. }
  11119. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  11120. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  11121. if (pipeProposal) {
  11122. this.state.type = topicTokenType;
  11123. this.state.value = topicTokenValue;
  11124. this.state.pos--;
  11125. this.state.end--;
  11126. this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);
  11127. return this.parseTopicReference(pipeProposal);
  11128. } else {
  11129. this.unexpected();
  11130. }
  11131. }
  11132. parseTopicReference(pipeProposal) {
  11133. const node = this.startNode();
  11134. const startLoc = this.state.startLoc;
  11135. const tokenType = this.state.type;
  11136. this.next();
  11137. return this.finishTopicReference(node, startLoc, pipeProposal, tokenType);
  11138. }
  11139. finishTopicReference(node, startLoc, pipeProposal, tokenType) {
  11140. if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) {
  11141. if (pipeProposal === "hack") {
  11142. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  11143. this.raise(Errors.PipeTopicUnbound, startLoc);
  11144. }
  11145. this.registerTopicReference();
  11146. return this.finishNode(node, "TopicReference");
  11147. } else {
  11148. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  11149. this.raise(Errors.PrimaryTopicNotAllowed, startLoc);
  11150. }
  11151. this.registerTopicReference();
  11152. return this.finishNode(node, "PipelinePrimaryTopicReference");
  11153. }
  11154. } else {
  11155. throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, {
  11156. token: tokenLabelName(tokenType)
  11157. });
  11158. }
  11159. }
  11160. testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) {
  11161. switch (pipeProposal) {
  11162. case "hack":
  11163. {
  11164. return this.hasPlugin(["pipelineOperator", {
  11165. topicToken: tokenLabelName(tokenType)
  11166. }]);
  11167. }
  11168. case "smart":
  11169. return tokenType === 27;
  11170. default:
  11171. throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc);
  11172. }
  11173. }
  11174. parseAsyncArrowUnaryFunction(node) {
  11175. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  11176. const params = [this.parseIdentifier()];
  11177. this.prodParam.exit();
  11178. if (this.hasPrecedingLineBreak()) {
  11179. this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition());
  11180. }
  11181. this.expect(19);
  11182. return this.parseArrowExpression(node, params, true);
  11183. }
  11184. parseDo(node, isAsync) {
  11185. this.expectPlugin("doExpressions");
  11186. if (isAsync) {
  11187. this.expectPlugin("asyncDoExpressions");
  11188. }
  11189. node.async = isAsync;
  11190. this.next();
  11191. const oldLabels = this.state.labels;
  11192. this.state.labels = [];
  11193. if (isAsync) {
  11194. this.prodParam.enter(2);
  11195. node.body = this.parseBlock();
  11196. this.prodParam.exit();
  11197. } else {
  11198. node.body = this.parseBlock();
  11199. }
  11200. this.state.labels = oldLabels;
  11201. return this.finishNode(node, "DoExpression");
  11202. }
  11203. parseSuper() {
  11204. const node = this.startNode();
  11205. this.next();
  11206. if (this.match(10) && !this.scope.allowDirectSuper && !(this.optionFlags & 16)) {
  11207. this.raise(Errors.SuperNotAllowed, node);
  11208. } else if (!this.scope.allowSuper && !(this.optionFlags & 16)) {
  11209. this.raise(Errors.UnexpectedSuper, node);
  11210. }
  11211. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  11212. this.raise(Errors.UnsupportedSuper, node);
  11213. }
  11214. return this.finishNode(node, "Super");
  11215. }
  11216. parsePrivateName() {
  11217. const node = this.startNode();
  11218. const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1));
  11219. const name = this.state.value;
  11220. this.next();
  11221. node.id = this.createIdentifier(id, name);
  11222. return this.finishNode(node, "PrivateName");
  11223. }
  11224. parseFunctionOrFunctionSent() {
  11225. const node = this.startNode();
  11226. this.next();
  11227. if (this.prodParam.hasYield && this.match(16)) {
  11228. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  11229. this.next();
  11230. if (this.match(103)) {
  11231. this.expectPlugin("functionSent");
  11232. } else if (!this.hasPlugin("functionSent")) {
  11233. this.unexpected();
  11234. }
  11235. return this.parseMetaProperty(node, meta, "sent");
  11236. }
  11237. return this.parseFunction(node);
  11238. }
  11239. parseMetaProperty(node, meta, propertyName) {
  11240. node.meta = meta;
  11241. const containsEsc = this.state.containsEsc;
  11242. node.property = this.parseIdentifier(true);
  11243. if (node.property.name !== propertyName || containsEsc) {
  11244. this.raise(Errors.UnsupportedMetaProperty, node.property, {
  11245. target: meta.name,
  11246. onlyValidPropertyName: propertyName
  11247. });
  11248. }
  11249. return this.finishNode(node, "MetaProperty");
  11250. }
  11251. parseImportMetaProperty(node) {
  11252. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  11253. this.next();
  11254. if (this.isContextual(101)) {
  11255. if (!this.inModule) {
  11256. this.raise(Errors.ImportMetaOutsideModule, id);
  11257. }
  11258. this.sawUnambiguousESM = true;
  11259. } else if (this.isContextual(105) || this.isContextual(97)) {
  11260. const isSource = this.isContextual(105);
  11261. this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation");
  11262. if (!(this.optionFlags & 256)) {
  11263. throw this.raise(Errors.DynamicImportPhaseRequiresImportExpressions, this.state.startLoc, {
  11264. phase: this.state.value
  11265. });
  11266. }
  11267. this.next();
  11268. node.phase = isSource ? "source" : "defer";
  11269. return this.parseImportCall(node);
  11270. }
  11271. return this.parseMetaProperty(node, id, "meta");
  11272. }
  11273. parseLiteralAtNode(value, type, node) {
  11274. this.addExtra(node, "rawValue", value);
  11275. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  11276. node.value = value;
  11277. this.next();
  11278. return this.finishNode(node, type);
  11279. }
  11280. parseLiteral(value, type) {
  11281. const node = this.startNode();
  11282. return this.parseLiteralAtNode(value, type, node);
  11283. }
  11284. parseStringLiteral(value) {
  11285. return this.parseLiteral(value, "StringLiteral");
  11286. }
  11287. parseNumericLiteral(value) {
  11288. return this.parseLiteral(value, "NumericLiteral");
  11289. }
  11290. parseBigIntLiteral(value) {
  11291. return this.parseLiteral(value, "BigIntLiteral");
  11292. }
  11293. parseDecimalLiteral(value) {
  11294. return this.parseLiteral(value, "DecimalLiteral");
  11295. }
  11296. parseRegExpLiteral(value) {
  11297. const node = this.startNode();
  11298. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  11299. node.pattern = value.pattern;
  11300. node.flags = value.flags;
  11301. this.next();
  11302. return this.finishNode(node, "RegExpLiteral");
  11303. }
  11304. parseBooleanLiteral(value) {
  11305. const node = this.startNode();
  11306. node.value = value;
  11307. this.next();
  11308. return this.finishNode(node, "BooleanLiteral");
  11309. }
  11310. parseNullLiteral() {
  11311. const node = this.startNode();
  11312. this.next();
  11313. return this.finishNode(node, "NullLiteral");
  11314. }
  11315. parseParenAndDistinguishExpression(canBeArrow) {
  11316. const startLoc = this.state.startLoc;
  11317. let val;
  11318. this.next();
  11319. this.expressionScope.enter(newArrowHeadScope());
  11320. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11321. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11322. this.state.maybeInArrowParameters = true;
  11323. this.state.inFSharpPipelineDirectBody = false;
  11324. const innerStartLoc = this.state.startLoc;
  11325. const exprList = [];
  11326. const refExpressionErrors = new ExpressionErrors();
  11327. let first = true;
  11328. let spreadStartLoc;
  11329. let optionalCommaStartLoc;
  11330. while (!this.match(11)) {
  11331. if (first) {
  11332. first = false;
  11333. } else {
  11334. this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc);
  11335. if (this.match(11)) {
  11336. optionalCommaStartLoc = this.state.startLoc;
  11337. break;
  11338. }
  11339. }
  11340. if (this.match(21)) {
  11341. const spreadNodeStartLoc = this.state.startLoc;
  11342. spreadStartLoc = this.state.startLoc;
  11343. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc));
  11344. if (!this.checkCommaAfterRest(41)) {
  11345. break;
  11346. }
  11347. } else {
  11348. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
  11349. }
  11350. }
  11351. const innerEndLoc = this.state.lastTokEndLoc;
  11352. this.expect(11);
  11353. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11354. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11355. let arrowNode = this.startNodeAt(startLoc);
  11356. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  11357. this.checkDestructuringPrivate(refExpressionErrors);
  11358. this.expressionScope.validateAsPattern();
  11359. this.expressionScope.exit();
  11360. this.parseArrowExpression(arrowNode, exprList, false);
  11361. return arrowNode;
  11362. }
  11363. this.expressionScope.exit();
  11364. if (!exprList.length) {
  11365. this.unexpected(this.state.lastTokStartLoc);
  11366. }
  11367. if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc);
  11368. if (spreadStartLoc) this.unexpected(spreadStartLoc);
  11369. this.checkExpressionErrors(refExpressionErrors, true);
  11370. this.toReferencedListDeep(exprList, true);
  11371. if (exprList.length > 1) {
  11372. val = this.startNodeAt(innerStartLoc);
  11373. val.expressions = exprList;
  11374. this.finishNode(val, "SequenceExpression");
  11375. this.resetEndLocation(val, innerEndLoc);
  11376. } else {
  11377. val = exprList[0];
  11378. }
  11379. return this.wrapParenthesis(startLoc, val);
  11380. }
  11381. wrapParenthesis(startLoc, expression) {
  11382. if (!(this.optionFlags & 512)) {
  11383. this.addExtra(expression, "parenthesized", true);
  11384. this.addExtra(expression, "parenStart", startLoc.index);
  11385. this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index);
  11386. return expression;
  11387. }
  11388. const parenExpression = this.startNodeAt(startLoc);
  11389. parenExpression.expression = expression;
  11390. return this.finishNode(parenExpression, "ParenthesizedExpression");
  11391. }
  11392. shouldParseArrow(params) {
  11393. return !this.canInsertSemicolon();
  11394. }
  11395. parseArrow(node) {
  11396. if (this.eat(19)) {
  11397. return node;
  11398. }
  11399. }
  11400. parseParenItem(node, startLoc) {
  11401. return node;
  11402. }
  11403. parseNewOrNewTarget() {
  11404. const node = this.startNode();
  11405. this.next();
  11406. if (this.match(16)) {
  11407. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  11408. this.next();
  11409. const metaProp = this.parseMetaProperty(node, meta, "target");
  11410. if (!this.scope.inNonArrowFunction && !this.scope.inClass && !(this.optionFlags & 4)) {
  11411. this.raise(Errors.UnexpectedNewTarget, metaProp);
  11412. }
  11413. return metaProp;
  11414. }
  11415. return this.parseNew(node);
  11416. }
  11417. parseNew(node) {
  11418. this.parseNewCallee(node);
  11419. if (this.eat(10)) {
  11420. const args = this.parseExprList(11);
  11421. this.toReferencedList(args);
  11422. node.arguments = args;
  11423. } else {
  11424. node.arguments = [];
  11425. }
  11426. return this.finishNode(node, "NewExpression");
  11427. }
  11428. parseNewCallee(node) {
  11429. const isImport = this.match(83);
  11430. const callee = this.parseNoCallExpr();
  11431. node.callee = callee;
  11432. if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) {
  11433. this.raise(Errors.ImportCallNotNewExpression, callee);
  11434. }
  11435. }
  11436. parseTemplateElement(isTagged) {
  11437. const {
  11438. start,
  11439. startLoc,
  11440. end,
  11441. value
  11442. } = this.state;
  11443. const elemStart = start + 1;
  11444. const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1));
  11445. if (value === null) {
  11446. if (!isTagged) {
  11447. this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1));
  11448. }
  11449. }
  11450. const isTail = this.match(24);
  11451. const endOffset = isTail ? -1 : -2;
  11452. const elemEnd = end + endOffset;
  11453. elem.value = {
  11454. raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"),
  11455. cooked: value === null ? null : value.slice(1, endOffset)
  11456. };
  11457. elem.tail = isTail;
  11458. this.next();
  11459. const finishedNode = this.finishNode(elem, "TemplateElement");
  11460. this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset));
  11461. return finishedNode;
  11462. }
  11463. parseTemplate(isTagged) {
  11464. const node = this.startNode();
  11465. let curElt = this.parseTemplateElement(isTagged);
  11466. const quasis = [curElt];
  11467. const substitutions = [];
  11468. while (!curElt.tail) {
  11469. substitutions.push(this.parseTemplateSubstitution());
  11470. this.readTemplateContinuation();
  11471. quasis.push(curElt = this.parseTemplateElement(isTagged));
  11472. }
  11473. node.expressions = substitutions;
  11474. node.quasis = quasis;
  11475. return this.finishNode(node, "TemplateLiteral");
  11476. }
  11477. parseTemplateSubstitution() {
  11478. return this.parseExpression();
  11479. }
  11480. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  11481. if (isRecord) {
  11482. this.expectPlugin("recordAndTuple");
  11483. }
  11484. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11485. this.state.inFSharpPipelineDirectBody = false;
  11486. const propHash = Object.create(null);
  11487. let first = true;
  11488. const node = this.startNode();
  11489. node.properties = [];
  11490. this.next();
  11491. while (!this.match(close)) {
  11492. if (first) {
  11493. first = false;
  11494. } else {
  11495. this.expect(12);
  11496. if (this.match(close)) {
  11497. this.addTrailingCommaExtraToNode(node);
  11498. break;
  11499. }
  11500. }
  11501. let prop;
  11502. if (isPattern) {
  11503. prop = this.parseBindingProperty();
  11504. } else {
  11505. prop = this.parsePropertyDefinition(refExpressionErrors);
  11506. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  11507. }
  11508. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  11509. this.raise(Errors.InvalidRecordProperty, prop);
  11510. }
  11511. {
  11512. if (prop.shorthand) {
  11513. this.addExtra(prop, "shorthand", true);
  11514. }
  11515. }
  11516. node.properties.push(prop);
  11517. }
  11518. this.next();
  11519. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11520. let type = "ObjectExpression";
  11521. if (isPattern) {
  11522. type = "ObjectPattern";
  11523. } else if (isRecord) {
  11524. type = "RecordExpression";
  11525. }
  11526. return this.finishNode(node, type);
  11527. }
  11528. addTrailingCommaExtraToNode(node) {
  11529. this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index);
  11530. this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false);
  11531. }
  11532. maybeAsyncOrAccessorProp(prop) {
  11533. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55));
  11534. }
  11535. parsePropertyDefinition(refExpressionErrors) {
  11536. let decorators = [];
  11537. if (this.match(26)) {
  11538. if (this.hasPlugin("decorators")) {
  11539. this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc);
  11540. }
  11541. while (this.match(26)) {
  11542. decorators.push(this.parseDecorator());
  11543. }
  11544. }
  11545. const prop = this.startNode();
  11546. let isAsync = false;
  11547. let isAccessor = false;
  11548. let startLoc;
  11549. if (this.match(21)) {
  11550. if (decorators.length) this.unexpected();
  11551. return this.parseSpread();
  11552. }
  11553. if (decorators.length) {
  11554. prop.decorators = decorators;
  11555. decorators = [];
  11556. }
  11557. prop.method = false;
  11558. if (refExpressionErrors) {
  11559. startLoc = this.state.startLoc;
  11560. }
  11561. let isGenerator = this.eat(55);
  11562. this.parsePropertyNamePrefixOperator(prop);
  11563. const containsEsc = this.state.containsEsc;
  11564. this.parsePropertyName(prop, refExpressionErrors);
  11565. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  11566. const {
  11567. key
  11568. } = prop;
  11569. const keyName = key.name;
  11570. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  11571. isAsync = true;
  11572. this.resetPreviousNodeTrailingComments(key);
  11573. isGenerator = this.eat(55);
  11574. this.parsePropertyName(prop);
  11575. }
  11576. if (keyName === "get" || keyName === "set") {
  11577. isAccessor = true;
  11578. this.resetPreviousNodeTrailingComments(key);
  11579. prop.kind = keyName;
  11580. if (this.match(55)) {
  11581. isGenerator = true;
  11582. this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), {
  11583. kind: keyName
  11584. });
  11585. this.next();
  11586. }
  11587. this.parsePropertyName(prop);
  11588. }
  11589. }
  11590. return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  11591. }
  11592. getGetterSetterExpectedParamCount(method) {
  11593. return method.kind === "get" ? 0 : 1;
  11594. }
  11595. getObjectOrClassMethodParams(method) {
  11596. return method.params;
  11597. }
  11598. checkGetterSetterParams(method) {
  11599. var _params;
  11600. const paramCount = this.getGetterSetterExpectedParamCount(method);
  11601. const params = this.getObjectOrClassMethodParams(method);
  11602. if (params.length !== paramCount) {
  11603. this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method);
  11604. }
  11605. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  11606. this.raise(Errors.BadSetterRestParameter, method);
  11607. }
  11608. }
  11609. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  11610. if (isAccessor) {
  11611. const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  11612. this.checkGetterSetterParams(finishedProp);
  11613. return finishedProp;
  11614. }
  11615. if (isAsync || isGenerator || this.match(10)) {
  11616. if (isPattern) this.unexpected();
  11617. prop.kind = "method";
  11618. prop.method = true;
  11619. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  11620. }
  11621. }
  11622. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  11623. prop.shorthand = false;
  11624. if (this.eat(14)) {
  11625. prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  11626. return this.finishNode(prop, "ObjectProperty");
  11627. }
  11628. if (!prop.computed && prop.key.type === "Identifier") {
  11629. this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);
  11630. if (isPattern) {
  11631. prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
  11632. } else if (this.match(29)) {
  11633. const shorthandAssignLoc = this.state.startLoc;
  11634. if (refExpressionErrors != null) {
  11635. if (refExpressionErrors.shorthandAssignLoc === null) {
  11636. refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;
  11637. }
  11638. } else {
  11639. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  11640. }
  11641. prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
  11642. } else {
  11643. prop.value = cloneIdentifier(prop.key);
  11644. }
  11645. prop.shorthand = true;
  11646. return this.finishNode(prop, "ObjectProperty");
  11647. }
  11648. }
  11649. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  11650. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  11651. if (!node) this.unexpected();
  11652. return node;
  11653. }
  11654. parsePropertyName(prop, refExpressionErrors) {
  11655. if (this.eat(0)) {
  11656. prop.computed = true;
  11657. prop.key = this.parseMaybeAssignAllowIn();
  11658. this.expect(3);
  11659. } else {
  11660. const {
  11661. type,
  11662. value
  11663. } = this.state;
  11664. let key;
  11665. if (tokenIsKeywordOrIdentifier(type)) {
  11666. key = this.parseIdentifier(true);
  11667. } else {
  11668. switch (type) {
  11669. case 135:
  11670. key = this.parseNumericLiteral(value);
  11671. break;
  11672. case 134:
  11673. key = this.parseStringLiteral(value);
  11674. break;
  11675. case 136:
  11676. key = this.parseBigIntLiteral(value);
  11677. break;
  11678. case 139:
  11679. {
  11680. const privateKeyLoc = this.state.startLoc;
  11681. if (refExpressionErrors != null) {
  11682. if (refExpressionErrors.privateKeyLoc === null) {
  11683. refExpressionErrors.privateKeyLoc = privateKeyLoc;
  11684. }
  11685. } else {
  11686. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  11687. }
  11688. key = this.parsePrivateName();
  11689. break;
  11690. }
  11691. default:
  11692. if (type === 137) {
  11693. key = this.parseDecimalLiteral(value);
  11694. break;
  11695. }
  11696. this.unexpected();
  11697. }
  11698. }
  11699. prop.key = key;
  11700. if (type !== 139) {
  11701. prop.computed = false;
  11702. }
  11703. }
  11704. }
  11705. initFunction(node, isAsync) {
  11706. node.id = null;
  11707. node.generator = false;
  11708. node.async = isAsync;
  11709. }
  11710. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  11711. this.initFunction(node, isAsync);
  11712. node.generator = isGenerator;
  11713. this.scope.enter(2 | 16 | (inClassScope ? 64 : 0) | (allowDirectSuper ? 32 : 0));
  11714. this.prodParam.enter(functionFlags(isAsync, node.generator));
  11715. this.parseFunctionParams(node, isConstructor);
  11716. const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
  11717. this.prodParam.exit();
  11718. this.scope.exit();
  11719. return finishedNode;
  11720. }
  11721. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  11722. if (isTuple) {
  11723. this.expectPlugin("recordAndTuple");
  11724. }
  11725. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11726. this.state.inFSharpPipelineDirectBody = false;
  11727. const node = this.startNode();
  11728. this.next();
  11729. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  11730. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11731. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  11732. }
  11733. parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
  11734. this.scope.enter(2 | 4);
  11735. let flags = functionFlags(isAsync, false);
  11736. if (!this.match(5) && this.prodParam.hasIn) {
  11737. flags |= 8;
  11738. }
  11739. this.prodParam.enter(flags);
  11740. this.initFunction(node, isAsync);
  11741. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11742. if (params) {
  11743. this.state.maybeInArrowParameters = true;
  11744. this.setArrowFunctionParameters(node, params, trailingCommaLoc);
  11745. }
  11746. this.state.maybeInArrowParameters = false;
  11747. this.parseFunctionBody(node, true);
  11748. this.prodParam.exit();
  11749. this.scope.exit();
  11750. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11751. return this.finishNode(node, "ArrowFunctionExpression");
  11752. }
  11753. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  11754. this.toAssignableList(params, trailingCommaLoc, false);
  11755. node.params = params;
  11756. }
  11757. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11758. this.parseFunctionBody(node, false, isMethod);
  11759. return this.finishNode(node, type);
  11760. }
  11761. parseFunctionBody(node, allowExpression, isMethod = false) {
  11762. const isExpression = allowExpression && !this.match(5);
  11763. this.expressionScope.enter(newExpressionScope());
  11764. if (isExpression) {
  11765. node.body = this.parseMaybeAssign();
  11766. this.checkParams(node, false, allowExpression, false);
  11767. } else {
  11768. const oldStrict = this.state.strict;
  11769. const oldLabels = this.state.labels;
  11770. this.state.labels = [];
  11771. this.prodParam.enter(this.prodParam.currentFlags() | 4);
  11772. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  11773. const nonSimple = !this.isSimpleParamList(node.params);
  11774. if (hasStrictModeDirective && nonSimple) {
  11775. this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node);
  11776. }
  11777. const strictModeChanged = !oldStrict && this.state.strict;
  11778. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  11779. if (this.state.strict && node.id) {
  11780. this.checkIdentifier(node.id, 65, strictModeChanged);
  11781. }
  11782. });
  11783. this.prodParam.exit();
  11784. this.state.labels = oldLabels;
  11785. }
  11786. this.expressionScope.exit();
  11787. }
  11788. isSimpleParameter(node) {
  11789. return node.type === "Identifier";
  11790. }
  11791. isSimpleParamList(params) {
  11792. for (let i = 0, len = params.length; i < len; i++) {
  11793. if (!this.isSimpleParameter(params[i])) return false;
  11794. }
  11795. return true;
  11796. }
  11797. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  11798. const checkClashes = !allowDuplicates && new Set();
  11799. const formalParameters = {
  11800. type: "FormalParameters"
  11801. };
  11802. for (const param of node.params) {
  11803. this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged);
  11804. }
  11805. }
  11806. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  11807. const elts = [];
  11808. let first = true;
  11809. while (!this.eat(close)) {
  11810. if (first) {
  11811. first = false;
  11812. } else {
  11813. this.expect(12);
  11814. if (this.match(close)) {
  11815. if (nodeForExtra) {
  11816. this.addTrailingCommaExtraToNode(nodeForExtra);
  11817. }
  11818. this.next();
  11819. break;
  11820. }
  11821. }
  11822. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  11823. }
  11824. return elts;
  11825. }
  11826. parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
  11827. let elt;
  11828. if (this.match(12)) {
  11829. if (!allowEmpty) {
  11830. this.raise(Errors.UnexpectedToken, this.state.curPosition(), {
  11831. unexpected: ","
  11832. });
  11833. }
  11834. elt = null;
  11835. } else if (this.match(21)) {
  11836. const spreadNodeStartLoc = this.state.startLoc;
  11837. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc);
  11838. } else if (this.match(17)) {
  11839. this.expectPlugin("partialApplication");
  11840. if (!allowPlaceholder) {
  11841. this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc);
  11842. }
  11843. const node = this.startNode();
  11844. this.next();
  11845. elt = this.finishNode(node, "ArgumentPlaceholder");
  11846. } else {
  11847. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
  11848. }
  11849. return elt;
  11850. }
  11851. parseIdentifier(liberal) {
  11852. const node = this.startNode();
  11853. const name = this.parseIdentifierName(liberal);
  11854. return this.createIdentifier(node, name);
  11855. }
  11856. createIdentifier(node, name) {
  11857. node.name = name;
  11858. node.loc.identifierName = name;
  11859. return this.finishNode(node, "Identifier");
  11860. }
  11861. parseIdentifierName(liberal) {
  11862. let name;
  11863. const {
  11864. startLoc,
  11865. type
  11866. } = this.state;
  11867. if (tokenIsKeywordOrIdentifier(type)) {
  11868. name = this.state.value;
  11869. } else {
  11870. this.unexpected();
  11871. }
  11872. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  11873. if (liberal) {
  11874. if (tokenIsKeyword) {
  11875. this.replaceToken(132);
  11876. }
  11877. } else {
  11878. this.checkReservedWord(name, startLoc, tokenIsKeyword, false);
  11879. }
  11880. this.next();
  11881. return name;
  11882. }
  11883. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  11884. if (word.length > 10) {
  11885. return;
  11886. }
  11887. if (!canBeReservedWord(word)) {
  11888. return;
  11889. }
  11890. if (checkKeywords && isKeyword(word)) {
  11891. this.raise(Errors.UnexpectedKeyword, startLoc, {
  11892. keyword: word
  11893. });
  11894. return;
  11895. }
  11896. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  11897. if (reservedTest(word, this.inModule)) {
  11898. this.raise(Errors.UnexpectedReservedWord, startLoc, {
  11899. reservedWord: word
  11900. });
  11901. return;
  11902. } else if (word === "yield") {
  11903. if (this.prodParam.hasYield) {
  11904. this.raise(Errors.YieldBindingIdentifier, startLoc);
  11905. return;
  11906. }
  11907. } else if (word === "await") {
  11908. if (this.prodParam.hasAwait) {
  11909. this.raise(Errors.AwaitBindingIdentifier, startLoc);
  11910. return;
  11911. }
  11912. if (this.scope.inStaticBlock) {
  11913. this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc);
  11914. return;
  11915. }
  11916. this.expressionScope.recordAsyncArrowParametersError(startLoc);
  11917. } else if (word === "arguments") {
  11918. if (this.scope.inClassAndNotInNonArrowFunction) {
  11919. this.raise(Errors.ArgumentsInClass, startLoc);
  11920. return;
  11921. }
  11922. }
  11923. }
  11924. recordAwaitIfAllowed() {
  11925. const isAwaitAllowed = this.prodParam.hasAwait || this.optionFlags & 1 && !this.scope.inFunction;
  11926. if (isAwaitAllowed && !this.scope.inFunction) {
  11927. this.state.hasTopLevelAwait = true;
  11928. }
  11929. return isAwaitAllowed;
  11930. }
  11931. parseAwait(startLoc) {
  11932. const node = this.startNodeAt(startLoc);
  11933. this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node);
  11934. if (this.eat(55)) {
  11935. this.raise(Errors.ObsoleteAwaitStar, node);
  11936. }
  11937. if (!this.scope.inFunction && !(this.optionFlags & 1)) {
  11938. if (this.isAmbiguousAwait()) {
  11939. this.ambiguousScriptDifferentAst = true;
  11940. } else {
  11941. this.sawUnambiguousESM = true;
  11942. }
  11943. }
  11944. if (!this.state.soloAwait) {
  11945. node.argument = this.parseMaybeUnary(null, true);
  11946. }
  11947. return this.finishNode(node, "AwaitExpression");
  11948. }
  11949. isAmbiguousAwait() {
  11950. if (this.hasPrecedingLineBreak()) return true;
  11951. const {
  11952. type
  11953. } = this.state;
  11954. return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 138 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54;
  11955. }
  11956. parseYield() {
  11957. const node = this.startNode();
  11958. this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node);
  11959. this.next();
  11960. let delegating = false;
  11961. let argument = null;
  11962. if (!this.hasPrecedingLineBreak()) {
  11963. delegating = this.eat(55);
  11964. switch (this.state.type) {
  11965. case 13:
  11966. case 140:
  11967. case 8:
  11968. case 11:
  11969. case 3:
  11970. case 9:
  11971. case 14:
  11972. case 12:
  11973. if (!delegating) break;
  11974. default:
  11975. argument = this.parseMaybeAssign();
  11976. }
  11977. }
  11978. node.delegate = delegating;
  11979. node.argument = argument;
  11980. return this.finishNode(node, "YieldExpression");
  11981. }
  11982. parseImportCall(node) {
  11983. this.next();
  11984. node.source = this.parseMaybeAssignAllowIn();
  11985. node.options = null;
  11986. if (this.eat(12)) {
  11987. if (!this.match(11)) {
  11988. node.options = this.parseMaybeAssignAllowIn();
  11989. if (this.eat(12) && !this.match(11)) {
  11990. do {
  11991. this.parseMaybeAssignAllowIn();
  11992. } while (this.eat(12) && !this.match(11));
  11993. this.raise(Errors.ImportCallArity, node);
  11994. }
  11995. }
  11996. }
  11997. this.expect(11);
  11998. return this.finishNode(node, "ImportExpression");
  11999. }
  12000. checkPipelineAtInfixOperator(left, leftStartLoc) {
  12001. if (this.hasPlugin(["pipelineOperator", {
  12002. proposal: "smart"
  12003. }])) {
  12004. if (left.type === "SequenceExpression") {
  12005. this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc);
  12006. }
  12007. }
  12008. }
  12009. parseSmartPipelineBodyInStyle(childExpr, startLoc) {
  12010. if (this.isSimpleReference(childExpr)) {
  12011. const bodyNode = this.startNodeAt(startLoc);
  12012. bodyNode.callee = childExpr;
  12013. return this.finishNode(bodyNode, "PipelineBareFunction");
  12014. } else {
  12015. const bodyNode = this.startNodeAt(startLoc);
  12016. this.checkSmartPipeTopicBodyEarlyErrors(startLoc);
  12017. bodyNode.expression = childExpr;
  12018. return this.finishNode(bodyNode, "PipelineTopicExpression");
  12019. }
  12020. }
  12021. isSimpleReference(expression) {
  12022. switch (expression.type) {
  12023. case "MemberExpression":
  12024. return !expression.computed && this.isSimpleReference(expression.object);
  12025. case "Identifier":
  12026. return true;
  12027. default:
  12028. return false;
  12029. }
  12030. }
  12031. checkSmartPipeTopicBodyEarlyErrors(startLoc) {
  12032. if (this.match(19)) {
  12033. throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc);
  12034. }
  12035. if (!this.topicReferenceWasUsedInCurrentContext()) {
  12036. this.raise(Errors.PipelineTopicUnused, startLoc);
  12037. }
  12038. }
  12039. withTopicBindingContext(callback) {
  12040. const outerContextTopicState = this.state.topicContext;
  12041. this.state.topicContext = {
  12042. maxNumOfResolvableTopics: 1,
  12043. maxTopicIndex: null
  12044. };
  12045. try {
  12046. return callback();
  12047. } finally {
  12048. this.state.topicContext = outerContextTopicState;
  12049. }
  12050. }
  12051. withSmartMixTopicForbiddingContext(callback) {
  12052. if (this.hasPlugin(["pipelineOperator", {
  12053. proposal: "smart"
  12054. }])) {
  12055. const outerContextTopicState = this.state.topicContext;
  12056. this.state.topicContext = {
  12057. maxNumOfResolvableTopics: 0,
  12058. maxTopicIndex: null
  12059. };
  12060. try {
  12061. return callback();
  12062. } finally {
  12063. this.state.topicContext = outerContextTopicState;
  12064. }
  12065. } else {
  12066. return callback();
  12067. }
  12068. }
  12069. withSoloAwaitPermittingContext(callback) {
  12070. const outerContextSoloAwaitState = this.state.soloAwait;
  12071. this.state.soloAwait = true;
  12072. try {
  12073. return callback();
  12074. } finally {
  12075. this.state.soloAwait = outerContextSoloAwaitState;
  12076. }
  12077. }
  12078. allowInAnd(callback) {
  12079. const flags = this.prodParam.currentFlags();
  12080. const prodParamToSet = 8 & ~flags;
  12081. if (prodParamToSet) {
  12082. this.prodParam.enter(flags | 8);
  12083. try {
  12084. return callback();
  12085. } finally {
  12086. this.prodParam.exit();
  12087. }
  12088. }
  12089. return callback();
  12090. }
  12091. disallowInAnd(callback) {
  12092. const flags = this.prodParam.currentFlags();
  12093. const prodParamToClear = 8 & flags;
  12094. if (prodParamToClear) {
  12095. this.prodParam.enter(flags & ~8);
  12096. try {
  12097. return callback();
  12098. } finally {
  12099. this.prodParam.exit();
  12100. }
  12101. }
  12102. return callback();
  12103. }
  12104. registerTopicReference() {
  12105. this.state.topicContext.maxTopicIndex = 0;
  12106. }
  12107. topicReferenceIsAllowedInCurrentContext() {
  12108. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  12109. }
  12110. topicReferenceWasUsedInCurrentContext() {
  12111. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  12112. }
  12113. parseFSharpPipelineBody(prec) {
  12114. const startLoc = this.state.startLoc;
  12115. this.state.potentialArrowAt = this.state.start;
  12116. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  12117. this.state.inFSharpPipelineDirectBody = true;
  12118. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec);
  12119. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  12120. return ret;
  12121. }
  12122. parseModuleExpression() {
  12123. this.expectPlugin("moduleBlocks");
  12124. const node = this.startNode();
  12125. this.next();
  12126. if (!this.match(5)) {
  12127. this.unexpected(null, 5);
  12128. }
  12129. const program = this.startNodeAt(this.state.endLoc);
  12130. this.next();
  12131. const revertScopes = this.initializeScopes(true);
  12132. this.enterInitialScopes();
  12133. try {
  12134. node.body = this.parseProgram(program, 8, "module");
  12135. } finally {
  12136. revertScopes();
  12137. }
  12138. return this.finishNode(node, "ModuleExpression");
  12139. }
  12140. parsePropertyNamePrefixOperator(prop) {}
  12141. }
  12142. const loopLabel = {
  12143. kind: 1
  12144. },
  12145. switchLabel = {
  12146. kind: 2
  12147. };
  12148. const loneSurrogate = /[\uD800-\uDFFF]/u;
  12149. const keywordRelationalOperator = /in(?:stanceof)?/y;
  12150. function babel7CompatTokens(tokens, input, startIndex) {
  12151. for (let i = 0; i < tokens.length; i++) {
  12152. const token = tokens[i];
  12153. const {
  12154. type
  12155. } = token;
  12156. if (typeof type === "number") {
  12157. {
  12158. if (type === 139) {
  12159. const {
  12160. loc,
  12161. start,
  12162. value,
  12163. end
  12164. } = token;
  12165. const hashEndPos = start + 1;
  12166. const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);
  12167. tokens.splice(i, 1, new Token({
  12168. type: getExportedToken(27),
  12169. value: "#",
  12170. start: start,
  12171. end: hashEndPos,
  12172. startLoc: loc.start,
  12173. endLoc: hashEndLoc
  12174. }), new Token({
  12175. type: getExportedToken(132),
  12176. value: value,
  12177. start: hashEndPos,
  12178. end: end,
  12179. startLoc: hashEndLoc,
  12180. endLoc: loc.end
  12181. }));
  12182. i++;
  12183. continue;
  12184. }
  12185. if (tokenIsTemplate(type)) {
  12186. const {
  12187. loc,
  12188. start,
  12189. value,
  12190. end
  12191. } = token;
  12192. const backquoteEnd = start + 1;
  12193. const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);
  12194. let startToken;
  12195. if (input.charCodeAt(start - startIndex) === 96) {
  12196. startToken = new Token({
  12197. type: getExportedToken(22),
  12198. value: "`",
  12199. start: start,
  12200. end: backquoteEnd,
  12201. startLoc: loc.start,
  12202. endLoc: backquoteEndLoc
  12203. });
  12204. } else {
  12205. startToken = new Token({
  12206. type: getExportedToken(8),
  12207. value: "}",
  12208. start: start,
  12209. end: backquoteEnd,
  12210. startLoc: loc.start,
  12211. endLoc: backquoteEndLoc
  12212. });
  12213. }
  12214. let templateValue, templateElementEnd, templateElementEndLoc, endToken;
  12215. if (type === 24) {
  12216. templateElementEnd = end - 1;
  12217. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);
  12218. templateValue = value === null ? null : value.slice(1, -1);
  12219. endToken = new Token({
  12220. type: getExportedToken(22),
  12221. value: "`",
  12222. start: templateElementEnd,
  12223. end: end,
  12224. startLoc: templateElementEndLoc,
  12225. endLoc: loc.end
  12226. });
  12227. } else {
  12228. templateElementEnd = end - 2;
  12229. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);
  12230. templateValue = value === null ? null : value.slice(1, -2);
  12231. endToken = new Token({
  12232. type: getExportedToken(23),
  12233. value: "${",
  12234. start: templateElementEnd,
  12235. end: end,
  12236. startLoc: templateElementEndLoc,
  12237. endLoc: loc.end
  12238. });
  12239. }
  12240. tokens.splice(i, 1, startToken, new Token({
  12241. type: getExportedToken(20),
  12242. value: templateValue,
  12243. start: backquoteEnd,
  12244. end: templateElementEnd,
  12245. startLoc: backquoteEndLoc,
  12246. endLoc: templateElementEndLoc
  12247. }), endToken);
  12248. i += 2;
  12249. continue;
  12250. }
  12251. }
  12252. token.type = getExportedToken(type);
  12253. }
  12254. }
  12255. return tokens;
  12256. }
  12257. class StatementParser extends ExpressionParser {
  12258. parseTopLevel(file, program) {
  12259. file.program = this.parseProgram(program);
  12260. file.comments = this.comments;
  12261. if (this.optionFlags & 128) {
  12262. file.tokens = babel7CompatTokens(this.tokens, this.input, this.startIndex);
  12263. }
  12264. return this.finishNode(file, "File");
  12265. }
  12266. parseProgram(program, end = 140, sourceType = this.options.sourceType) {
  12267. program.sourceType = sourceType;
  12268. program.interpreter = this.parseInterpreterDirective();
  12269. this.parseBlockBody(program, true, true, end);
  12270. if (this.inModule) {
  12271. if (!(this.optionFlags & 32) && this.scope.undefinedExports.size > 0) {
  12272. for (const [localName, at] of Array.from(this.scope.undefinedExports)) {
  12273. this.raise(Errors.ModuleExportUndefined, at, {
  12274. localName
  12275. });
  12276. }
  12277. }
  12278. this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait);
  12279. }
  12280. let finishedProgram;
  12281. if (end === 140) {
  12282. finishedProgram = this.finishNode(program, "Program");
  12283. } else {
  12284. finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1));
  12285. }
  12286. return finishedProgram;
  12287. }
  12288. stmtToDirective(stmt) {
  12289. const directive = stmt;
  12290. directive.type = "Directive";
  12291. directive.value = directive.expression;
  12292. delete directive.expression;
  12293. const directiveLiteral = directive.value;
  12294. const expressionValue = directiveLiteral.value;
  12295. const raw = this.input.slice(this.offsetToSourcePos(directiveLiteral.start), this.offsetToSourcePos(directiveLiteral.end));
  12296. const val = directiveLiteral.value = raw.slice(1, -1);
  12297. this.addExtra(directiveLiteral, "raw", raw);
  12298. this.addExtra(directiveLiteral, "rawValue", val);
  12299. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  12300. directiveLiteral.type = "DirectiveLiteral";
  12301. return directive;
  12302. }
  12303. parseInterpreterDirective() {
  12304. if (!this.match(28)) {
  12305. return null;
  12306. }
  12307. const node = this.startNode();
  12308. node.value = this.state.value;
  12309. this.next();
  12310. return this.finishNode(node, "InterpreterDirective");
  12311. }
  12312. isLet() {
  12313. if (!this.isContextual(100)) {
  12314. return false;
  12315. }
  12316. return this.hasFollowingBindingAtom();
  12317. }
  12318. chStartsBindingIdentifier(ch, pos) {
  12319. if (isIdentifierStart(ch)) {
  12320. keywordRelationalOperator.lastIndex = pos;
  12321. if (keywordRelationalOperator.test(this.input)) {
  12322. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  12323. if (!isIdentifierChar(endCh) && endCh !== 92) {
  12324. return false;
  12325. }
  12326. }
  12327. return true;
  12328. } else if (ch === 92) {
  12329. return true;
  12330. } else {
  12331. return false;
  12332. }
  12333. }
  12334. chStartsBindingPattern(ch) {
  12335. return ch === 91 || ch === 123;
  12336. }
  12337. hasFollowingBindingAtom() {
  12338. const next = this.nextTokenStart();
  12339. const nextCh = this.codePointAtPos(next);
  12340. return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
  12341. }
  12342. hasInLineFollowingBindingIdentifierOrBrace() {
  12343. const next = this.nextTokenInLineStart();
  12344. const nextCh = this.codePointAtPos(next);
  12345. return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next);
  12346. }
  12347. startsUsingForOf() {
  12348. const {
  12349. type,
  12350. containsEsc
  12351. } = this.lookahead();
  12352. if (type === 102 && !containsEsc) {
  12353. return false;
  12354. } else if (tokenIsIdentifier(type) && !this.hasFollowingLineBreak()) {
  12355. this.expectPlugin("explicitResourceManagement");
  12356. return true;
  12357. }
  12358. }
  12359. startsAwaitUsing() {
  12360. let next = this.nextTokenInLineStart();
  12361. if (this.isUnparsedContextual(next, "using")) {
  12362. next = this.nextTokenInLineStartSince(next + 5);
  12363. const nextCh = this.codePointAtPos(next);
  12364. if (this.chStartsBindingIdentifier(nextCh, next)) {
  12365. this.expectPlugin("explicitResourceManagement");
  12366. return true;
  12367. }
  12368. }
  12369. return false;
  12370. }
  12371. parseModuleItem() {
  12372. return this.parseStatementLike(1 | 2 | 4 | 8);
  12373. }
  12374. parseStatementListItem() {
  12375. return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8));
  12376. }
  12377. parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) {
  12378. let flags = 0;
  12379. if (this.options.annexB && !this.state.strict) {
  12380. flags |= 4;
  12381. if (allowLabeledFunction) {
  12382. flags |= 8;
  12383. }
  12384. }
  12385. return this.parseStatementLike(flags);
  12386. }
  12387. parseStatement() {
  12388. return this.parseStatementLike(0);
  12389. }
  12390. parseStatementLike(flags) {
  12391. let decorators = null;
  12392. if (this.match(26)) {
  12393. decorators = this.parseDecorators(true);
  12394. }
  12395. return this.parseStatementContent(flags, decorators);
  12396. }
  12397. parseStatementContent(flags, decorators) {
  12398. const startType = this.state.type;
  12399. const node = this.startNode();
  12400. const allowDeclaration = !!(flags & 2);
  12401. const allowFunctionDeclaration = !!(flags & 4);
  12402. const topLevel = flags & 1;
  12403. switch (startType) {
  12404. case 60:
  12405. return this.parseBreakContinueStatement(node, true);
  12406. case 63:
  12407. return this.parseBreakContinueStatement(node, false);
  12408. case 64:
  12409. return this.parseDebuggerStatement(node);
  12410. case 90:
  12411. return this.parseDoWhileStatement(node);
  12412. case 91:
  12413. return this.parseForStatement(node);
  12414. case 68:
  12415. if (this.lookaheadCharCode() === 46) break;
  12416. if (!allowFunctionDeclaration) {
  12417. this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc);
  12418. }
  12419. return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration);
  12420. case 80:
  12421. if (!allowDeclaration) this.unexpected();
  12422. return this.parseClass(this.maybeTakeDecorators(decorators, node), true);
  12423. case 69:
  12424. return this.parseIfStatement(node);
  12425. case 70:
  12426. return this.parseReturnStatement(node);
  12427. case 71:
  12428. return this.parseSwitchStatement(node);
  12429. case 72:
  12430. return this.parseThrowStatement(node);
  12431. case 73:
  12432. return this.parseTryStatement(node);
  12433. case 96:
  12434. if (!this.state.containsEsc && this.startsAwaitUsing()) {
  12435. if (!this.recordAwaitIfAllowed()) {
  12436. this.raise(Errors.AwaitUsingNotInAsyncContext, node);
  12437. } else if (!allowDeclaration) {
  12438. this.raise(Errors.UnexpectedLexicalDeclaration, node);
  12439. }
  12440. this.next();
  12441. return this.parseVarStatement(node, "await using");
  12442. }
  12443. break;
  12444. case 107:
  12445. if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) {
  12446. break;
  12447. }
  12448. this.expectPlugin("explicitResourceManagement");
  12449. if (!this.scope.inModule && this.scope.inTopLevel) {
  12450. this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc);
  12451. } else if (!allowDeclaration) {
  12452. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  12453. }
  12454. return this.parseVarStatement(node, "using");
  12455. case 100:
  12456. {
  12457. if (this.state.containsEsc) {
  12458. break;
  12459. }
  12460. const next = this.nextTokenStart();
  12461. const nextCh = this.codePointAtPos(next);
  12462. if (nextCh !== 91) {
  12463. if (!allowDeclaration && this.hasFollowingLineBreak()) break;
  12464. if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) {
  12465. break;
  12466. }
  12467. }
  12468. }
  12469. case 75:
  12470. {
  12471. if (!allowDeclaration) {
  12472. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  12473. }
  12474. }
  12475. case 74:
  12476. {
  12477. const kind = this.state.value;
  12478. return this.parseVarStatement(node, kind);
  12479. }
  12480. case 92:
  12481. return this.parseWhileStatement(node);
  12482. case 76:
  12483. return this.parseWithStatement(node);
  12484. case 5:
  12485. return this.parseBlock();
  12486. case 13:
  12487. return this.parseEmptyStatement(node);
  12488. case 83:
  12489. {
  12490. const nextTokenCharCode = this.lookaheadCharCode();
  12491. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  12492. break;
  12493. }
  12494. }
  12495. case 82:
  12496. {
  12497. if (!(this.optionFlags & 8) && !topLevel) {
  12498. this.raise(Errors.UnexpectedImportExport, this.state.startLoc);
  12499. }
  12500. this.next();
  12501. let result;
  12502. if (startType === 83) {
  12503. result = this.parseImport(node);
  12504. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  12505. this.sawUnambiguousESM = true;
  12506. }
  12507. } else {
  12508. result = this.parseExport(node, decorators);
  12509. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  12510. this.sawUnambiguousESM = true;
  12511. }
  12512. }
  12513. this.assertModuleNodeAllowed(result);
  12514. return result;
  12515. }
  12516. default:
  12517. {
  12518. if (this.isAsyncFunction()) {
  12519. if (!allowDeclaration) {
  12520. this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc);
  12521. }
  12522. this.next();
  12523. return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration);
  12524. }
  12525. }
  12526. }
  12527. const maybeName = this.state.value;
  12528. const expr = this.parseExpression();
  12529. if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) {
  12530. return this.parseLabeledStatement(node, maybeName, expr, flags);
  12531. } else {
  12532. return this.parseExpressionStatement(node, expr, decorators);
  12533. }
  12534. }
  12535. assertModuleNodeAllowed(node) {
  12536. if (!(this.optionFlags & 8) && !this.inModule) {
  12537. this.raise(Errors.ImportOutsideModule, node);
  12538. }
  12539. }
  12540. decoratorsEnabledBeforeExport() {
  12541. if (this.hasPlugin("decorators-legacy")) return true;
  12542. return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false;
  12543. }
  12544. maybeTakeDecorators(maybeDecorators, classNode, exportNode) {
  12545. if (maybeDecorators) {
  12546. var _classNode$decorators;
  12547. if ((_classNode$decorators = classNode.decorators) != null && _classNode$decorators.length) {
  12548. if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") {
  12549. this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]);
  12550. }
  12551. classNode.decorators.unshift(...maybeDecorators);
  12552. } else {
  12553. classNode.decorators = maybeDecorators;
  12554. }
  12555. this.resetStartLocationFromNode(classNode, maybeDecorators[0]);
  12556. if (exportNode) this.resetStartLocationFromNode(exportNode, classNode);
  12557. }
  12558. return classNode;
  12559. }
  12560. canHaveLeadingDecorator() {
  12561. return this.match(80);
  12562. }
  12563. parseDecorators(allowExport) {
  12564. const decorators = [];
  12565. do {
  12566. decorators.push(this.parseDecorator());
  12567. } while (this.match(26));
  12568. if (this.match(82)) {
  12569. if (!allowExport) {
  12570. this.unexpected();
  12571. }
  12572. if (!this.decoratorsEnabledBeforeExport()) {
  12573. this.raise(Errors.DecoratorExportClass, this.state.startLoc);
  12574. }
  12575. } else if (!this.canHaveLeadingDecorator()) {
  12576. throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc);
  12577. }
  12578. return decorators;
  12579. }
  12580. parseDecorator() {
  12581. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  12582. const node = this.startNode();
  12583. this.next();
  12584. if (this.hasPlugin("decorators")) {
  12585. const startLoc = this.state.startLoc;
  12586. let expr;
  12587. if (this.match(10)) {
  12588. const startLoc = this.state.startLoc;
  12589. this.next();
  12590. expr = this.parseExpression();
  12591. this.expect(11);
  12592. expr = this.wrapParenthesis(startLoc, expr);
  12593. const paramsStartLoc = this.state.startLoc;
  12594. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  12595. if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) {
  12596. this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc);
  12597. }
  12598. } else {
  12599. expr = this.parseIdentifier(false);
  12600. while (this.eat(16)) {
  12601. const node = this.startNodeAt(startLoc);
  12602. node.object = expr;
  12603. if (this.match(139)) {
  12604. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  12605. node.property = this.parsePrivateName();
  12606. } else {
  12607. node.property = this.parseIdentifier(true);
  12608. }
  12609. node.computed = false;
  12610. expr = this.finishNode(node, "MemberExpression");
  12611. }
  12612. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  12613. }
  12614. } else {
  12615. node.expression = this.parseExprSubscripts();
  12616. }
  12617. return this.finishNode(node, "Decorator");
  12618. }
  12619. parseMaybeDecoratorArguments(expr, startLoc) {
  12620. if (this.eat(10)) {
  12621. const node = this.startNodeAt(startLoc);
  12622. node.callee = expr;
  12623. node.arguments = this.parseCallExpressionArguments(11);
  12624. this.toReferencedList(node.arguments);
  12625. return this.finishNode(node, "CallExpression");
  12626. }
  12627. return expr;
  12628. }
  12629. parseBreakContinueStatement(node, isBreak) {
  12630. this.next();
  12631. if (this.isLineTerminator()) {
  12632. node.label = null;
  12633. } else {
  12634. node.label = this.parseIdentifier();
  12635. this.semicolon();
  12636. }
  12637. this.verifyBreakContinue(node, isBreak);
  12638. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  12639. }
  12640. verifyBreakContinue(node, isBreak) {
  12641. let i;
  12642. for (i = 0; i < this.state.labels.length; ++i) {
  12643. const lab = this.state.labels[i];
  12644. if (node.label == null || lab.name === node.label.name) {
  12645. if (lab.kind != null && (isBreak || lab.kind === 1)) {
  12646. break;
  12647. }
  12648. if (node.label && isBreak) break;
  12649. }
  12650. }
  12651. if (i === this.state.labels.length) {
  12652. const type = isBreak ? "BreakStatement" : "ContinueStatement";
  12653. this.raise(Errors.IllegalBreakContinue, node, {
  12654. type
  12655. });
  12656. }
  12657. }
  12658. parseDebuggerStatement(node) {
  12659. this.next();
  12660. this.semicolon();
  12661. return this.finishNode(node, "DebuggerStatement");
  12662. }
  12663. parseHeaderExpression() {
  12664. this.expect(10);
  12665. const val = this.parseExpression();
  12666. this.expect(11);
  12667. return val;
  12668. }
  12669. parseDoWhileStatement(node) {
  12670. this.next();
  12671. this.state.labels.push(loopLabel);
  12672. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12673. this.state.labels.pop();
  12674. this.expect(92);
  12675. node.test = this.parseHeaderExpression();
  12676. this.eat(13);
  12677. return this.finishNode(node, "DoWhileStatement");
  12678. }
  12679. parseForStatement(node) {
  12680. this.next();
  12681. this.state.labels.push(loopLabel);
  12682. let awaitAt = null;
  12683. if (this.isContextual(96) && this.recordAwaitIfAllowed()) {
  12684. awaitAt = this.state.startLoc;
  12685. this.next();
  12686. }
  12687. this.scope.enter(0);
  12688. this.expect(10);
  12689. if (this.match(13)) {
  12690. if (awaitAt !== null) {
  12691. this.unexpected(awaitAt);
  12692. }
  12693. return this.parseFor(node, null);
  12694. }
  12695. const startsWithLet = this.isContextual(100);
  12696. {
  12697. const startsWithAwaitUsing = this.isContextual(96) && this.startsAwaitUsing();
  12698. const starsWithUsingDeclaration = startsWithAwaitUsing || this.isContextual(107) && this.startsUsingForOf();
  12699. const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration;
  12700. if (this.match(74) || this.match(75) || isLetOrUsing) {
  12701. const initNode = this.startNode();
  12702. let kind;
  12703. if (startsWithAwaitUsing) {
  12704. kind = "await using";
  12705. if (!this.recordAwaitIfAllowed()) {
  12706. this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc);
  12707. }
  12708. this.next();
  12709. } else {
  12710. kind = this.state.value;
  12711. }
  12712. this.next();
  12713. this.parseVar(initNode, true, kind);
  12714. const init = this.finishNode(initNode, "VariableDeclaration");
  12715. const isForIn = this.match(58);
  12716. if (isForIn && starsWithUsingDeclaration) {
  12717. this.raise(Errors.ForInUsing, init);
  12718. }
  12719. if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) {
  12720. return this.parseForIn(node, init, awaitAt);
  12721. }
  12722. if (awaitAt !== null) {
  12723. this.unexpected(awaitAt);
  12724. }
  12725. return this.parseFor(node, init);
  12726. }
  12727. }
  12728. const startsWithAsync = this.isContextual(95);
  12729. const refExpressionErrors = new ExpressionErrors();
  12730. const init = this.parseExpression(true, refExpressionErrors);
  12731. const isForOf = this.isContextual(102);
  12732. if (isForOf) {
  12733. if (startsWithLet) {
  12734. this.raise(Errors.ForOfLet, init);
  12735. }
  12736. if (awaitAt === null && startsWithAsync && init.type === "Identifier") {
  12737. this.raise(Errors.ForOfAsync, init);
  12738. }
  12739. }
  12740. if (isForOf || this.match(58)) {
  12741. this.checkDestructuringPrivate(refExpressionErrors);
  12742. this.toAssignable(init, true);
  12743. const type = isForOf ? "ForOfStatement" : "ForInStatement";
  12744. this.checkLVal(init, {
  12745. type
  12746. });
  12747. return this.parseForIn(node, init, awaitAt);
  12748. } else {
  12749. this.checkExpressionErrors(refExpressionErrors, true);
  12750. }
  12751. if (awaitAt !== null) {
  12752. this.unexpected(awaitAt);
  12753. }
  12754. return this.parseFor(node, init);
  12755. }
  12756. parseFunctionStatement(node, isAsync, isHangingDeclaration) {
  12757. this.next();
  12758. return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0));
  12759. }
  12760. parseIfStatement(node) {
  12761. this.next();
  12762. node.test = this.parseHeaderExpression();
  12763. node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration();
  12764. node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null;
  12765. return this.finishNode(node, "IfStatement");
  12766. }
  12767. parseReturnStatement(node) {
  12768. if (!this.prodParam.hasReturn && !(this.optionFlags & 2)) {
  12769. this.raise(Errors.IllegalReturn, this.state.startLoc);
  12770. }
  12771. this.next();
  12772. if (this.isLineTerminator()) {
  12773. node.argument = null;
  12774. } else {
  12775. node.argument = this.parseExpression();
  12776. this.semicolon();
  12777. }
  12778. return this.finishNode(node, "ReturnStatement");
  12779. }
  12780. parseSwitchStatement(node) {
  12781. this.next();
  12782. node.discriminant = this.parseHeaderExpression();
  12783. const cases = node.cases = [];
  12784. this.expect(5);
  12785. this.state.labels.push(switchLabel);
  12786. this.scope.enter(0);
  12787. let cur;
  12788. for (let sawDefault; !this.match(8);) {
  12789. if (this.match(61) || this.match(65)) {
  12790. const isCase = this.match(61);
  12791. if (cur) this.finishNode(cur, "SwitchCase");
  12792. cases.push(cur = this.startNode());
  12793. cur.consequent = [];
  12794. this.next();
  12795. if (isCase) {
  12796. cur.test = this.parseExpression();
  12797. } else {
  12798. if (sawDefault) {
  12799. this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc);
  12800. }
  12801. sawDefault = true;
  12802. cur.test = null;
  12803. }
  12804. this.expect(14);
  12805. } else {
  12806. if (cur) {
  12807. cur.consequent.push(this.parseStatementListItem());
  12808. } else {
  12809. this.unexpected();
  12810. }
  12811. }
  12812. }
  12813. this.scope.exit();
  12814. if (cur) this.finishNode(cur, "SwitchCase");
  12815. this.next();
  12816. this.state.labels.pop();
  12817. return this.finishNode(node, "SwitchStatement");
  12818. }
  12819. parseThrowStatement(node) {
  12820. this.next();
  12821. if (this.hasPrecedingLineBreak()) {
  12822. this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc);
  12823. }
  12824. node.argument = this.parseExpression();
  12825. this.semicolon();
  12826. return this.finishNode(node, "ThrowStatement");
  12827. }
  12828. parseCatchClauseParam() {
  12829. const param = this.parseBindingAtom();
  12830. this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0);
  12831. this.checkLVal(param, {
  12832. type: "CatchClause"
  12833. }, 9);
  12834. return param;
  12835. }
  12836. parseTryStatement(node) {
  12837. this.next();
  12838. node.block = this.parseBlock();
  12839. node.handler = null;
  12840. if (this.match(62)) {
  12841. const clause = this.startNode();
  12842. this.next();
  12843. if (this.match(10)) {
  12844. this.expect(10);
  12845. clause.param = this.parseCatchClauseParam();
  12846. this.expect(11);
  12847. } else {
  12848. clause.param = null;
  12849. this.scope.enter(0);
  12850. }
  12851. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  12852. this.scope.exit();
  12853. node.handler = this.finishNode(clause, "CatchClause");
  12854. }
  12855. node.finalizer = this.eat(67) ? this.parseBlock() : null;
  12856. if (!node.handler && !node.finalizer) {
  12857. this.raise(Errors.NoCatchOrFinally, node);
  12858. }
  12859. return this.finishNode(node, "TryStatement");
  12860. }
  12861. parseVarStatement(node, kind, allowMissingInitializer = false) {
  12862. this.next();
  12863. this.parseVar(node, false, kind, allowMissingInitializer);
  12864. this.semicolon();
  12865. return this.finishNode(node, "VariableDeclaration");
  12866. }
  12867. parseWhileStatement(node) {
  12868. this.next();
  12869. node.test = this.parseHeaderExpression();
  12870. this.state.labels.push(loopLabel);
  12871. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12872. this.state.labels.pop();
  12873. return this.finishNode(node, "WhileStatement");
  12874. }
  12875. parseWithStatement(node) {
  12876. if (this.state.strict) {
  12877. this.raise(Errors.StrictWith, this.state.startLoc);
  12878. }
  12879. this.next();
  12880. node.object = this.parseHeaderExpression();
  12881. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12882. return this.finishNode(node, "WithStatement");
  12883. }
  12884. parseEmptyStatement(node) {
  12885. this.next();
  12886. return this.finishNode(node, "EmptyStatement");
  12887. }
  12888. parseLabeledStatement(node, maybeName, expr, flags) {
  12889. for (const label of this.state.labels) {
  12890. if (label.name === maybeName) {
  12891. this.raise(Errors.LabelRedeclaration, expr, {
  12892. labelName: maybeName
  12893. });
  12894. }
  12895. }
  12896. const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null;
  12897. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  12898. const label = this.state.labels[i];
  12899. if (label.statementStart === node.start) {
  12900. label.statementStart = this.sourceToOffsetPos(this.state.start);
  12901. label.kind = kind;
  12902. } else {
  12903. break;
  12904. }
  12905. }
  12906. this.state.labels.push({
  12907. name: maybeName,
  12908. kind: kind,
  12909. statementStart: this.sourceToOffsetPos(this.state.start)
  12910. });
  12911. node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement();
  12912. this.state.labels.pop();
  12913. node.label = expr;
  12914. return this.finishNode(node, "LabeledStatement");
  12915. }
  12916. parseExpressionStatement(node, expr, decorators) {
  12917. node.expression = expr;
  12918. this.semicolon();
  12919. return this.finishNode(node, "ExpressionStatement");
  12920. }
  12921. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  12922. const node = this.startNode();
  12923. if (allowDirectives) {
  12924. this.state.strictErrors.clear();
  12925. }
  12926. this.expect(5);
  12927. if (createNewLexicalScope) {
  12928. this.scope.enter(0);
  12929. }
  12930. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  12931. if (createNewLexicalScope) {
  12932. this.scope.exit();
  12933. }
  12934. return this.finishNode(node, "BlockStatement");
  12935. }
  12936. isValidDirective(stmt) {
  12937. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  12938. }
  12939. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  12940. const body = node.body = [];
  12941. const directives = node.directives = [];
  12942. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  12943. }
  12944. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  12945. const oldStrict = this.state.strict;
  12946. let hasStrictModeDirective = false;
  12947. let parsedNonDirective = false;
  12948. while (!this.match(end)) {
  12949. const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem();
  12950. if (directives && !parsedNonDirective) {
  12951. if (this.isValidDirective(stmt)) {
  12952. const directive = this.stmtToDirective(stmt);
  12953. directives.push(directive);
  12954. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  12955. hasStrictModeDirective = true;
  12956. this.setStrict(true);
  12957. }
  12958. continue;
  12959. }
  12960. parsedNonDirective = true;
  12961. this.state.strictErrors.clear();
  12962. }
  12963. body.push(stmt);
  12964. }
  12965. afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective);
  12966. if (!oldStrict) {
  12967. this.setStrict(false);
  12968. }
  12969. this.next();
  12970. }
  12971. parseFor(node, init) {
  12972. node.init = init;
  12973. this.semicolon(false);
  12974. node.test = this.match(13) ? null : this.parseExpression();
  12975. this.semicolon(false);
  12976. node.update = this.match(11) ? null : this.parseExpression();
  12977. this.expect(11);
  12978. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12979. this.scope.exit();
  12980. this.state.labels.pop();
  12981. return this.finishNode(node, "ForStatement");
  12982. }
  12983. parseForIn(node, init, awaitAt) {
  12984. const isForIn = this.match(58);
  12985. this.next();
  12986. if (isForIn) {
  12987. if (awaitAt !== null) this.unexpected(awaitAt);
  12988. } else {
  12989. node.await = awaitAt !== null;
  12990. }
  12991. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  12992. this.raise(Errors.ForInOfLoopInitializer, init, {
  12993. type: isForIn ? "ForInStatement" : "ForOfStatement"
  12994. });
  12995. }
  12996. if (init.type === "AssignmentPattern") {
  12997. this.raise(Errors.InvalidLhs, init, {
  12998. ancestor: {
  12999. type: "ForStatement"
  13000. }
  13001. });
  13002. }
  13003. node.left = init;
  13004. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  13005. this.expect(11);
  13006. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  13007. this.scope.exit();
  13008. this.state.labels.pop();
  13009. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  13010. }
  13011. parseVar(node, isFor, kind, allowMissingInitializer = false) {
  13012. const declarations = node.declarations = [];
  13013. node.kind = kind;
  13014. for (;;) {
  13015. const decl = this.startNode();
  13016. this.parseVarId(decl, kind);
  13017. decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  13018. if (decl.init === null && !allowMissingInitializer) {
  13019. if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) {
  13020. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  13021. kind: "destructuring"
  13022. });
  13023. } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) {
  13024. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  13025. kind
  13026. });
  13027. }
  13028. }
  13029. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  13030. if (!this.eat(12)) break;
  13031. }
  13032. return node;
  13033. }
  13034. parseVarId(decl, kind) {
  13035. const id = this.parseBindingAtom();
  13036. if (kind === "using" || kind === "await using") {
  13037. if (id.type === "ArrayPattern" || id.type === "ObjectPattern") {
  13038. this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start);
  13039. }
  13040. }
  13041. this.checkLVal(id, {
  13042. type: "VariableDeclarator"
  13043. }, kind === "var" ? 5 : 8201);
  13044. decl.id = id;
  13045. }
  13046. parseAsyncFunctionExpression(node) {
  13047. return this.parseFunction(node, 8);
  13048. }
  13049. parseFunction(node, flags = 0) {
  13050. const hangingDeclaration = flags & 2;
  13051. const isDeclaration = !!(flags & 1);
  13052. const requireId = isDeclaration && !(flags & 4);
  13053. const isAsync = !!(flags & 8);
  13054. this.initFunction(node, isAsync);
  13055. if (this.match(55)) {
  13056. if (hangingDeclaration) {
  13057. this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc);
  13058. }
  13059. this.next();
  13060. node.generator = true;
  13061. }
  13062. if (isDeclaration) {
  13063. node.id = this.parseFunctionId(requireId);
  13064. }
  13065. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  13066. this.state.maybeInArrowParameters = false;
  13067. this.scope.enter(2);
  13068. this.prodParam.enter(functionFlags(isAsync, node.generator));
  13069. if (!isDeclaration) {
  13070. node.id = this.parseFunctionId();
  13071. }
  13072. this.parseFunctionParams(node, false);
  13073. this.withSmartMixTopicForbiddingContext(() => {
  13074. this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression");
  13075. });
  13076. this.prodParam.exit();
  13077. this.scope.exit();
  13078. if (isDeclaration && !hangingDeclaration) {
  13079. this.registerFunctionStatementId(node);
  13080. }
  13081. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  13082. return node;
  13083. }
  13084. parseFunctionId(requireId) {
  13085. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  13086. }
  13087. parseFunctionParams(node, isConstructor) {
  13088. this.expect(10);
  13089. this.expressionScope.enter(newParameterDeclarationScope());
  13090. node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0));
  13091. this.expressionScope.exit();
  13092. }
  13093. registerFunctionStatementId(node) {
  13094. if (!node.id) return;
  13095. this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start);
  13096. }
  13097. parseClass(node, isStatement, optionalId) {
  13098. this.next();
  13099. const oldStrict = this.state.strict;
  13100. this.state.strict = true;
  13101. this.parseClassId(node, isStatement, optionalId);
  13102. this.parseClassSuper(node);
  13103. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  13104. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  13105. }
  13106. isClassProperty() {
  13107. return this.match(29) || this.match(13) || this.match(8);
  13108. }
  13109. isClassMethod() {
  13110. return this.match(10);
  13111. }
  13112. nameIsConstructor(key) {
  13113. return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor";
  13114. }
  13115. isNonstaticConstructor(method) {
  13116. return !method.computed && !method.static && this.nameIsConstructor(method.key);
  13117. }
  13118. parseClassBody(hadSuperClass, oldStrict) {
  13119. this.classScope.enter();
  13120. const state = {
  13121. hadConstructor: false,
  13122. hadSuperClass
  13123. };
  13124. let decorators = [];
  13125. const classBody = this.startNode();
  13126. classBody.body = [];
  13127. this.expect(5);
  13128. this.withSmartMixTopicForbiddingContext(() => {
  13129. while (!this.match(8)) {
  13130. if (this.eat(13)) {
  13131. if (decorators.length > 0) {
  13132. throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc);
  13133. }
  13134. continue;
  13135. }
  13136. if (this.match(26)) {
  13137. decorators.push(this.parseDecorator());
  13138. continue;
  13139. }
  13140. const member = this.startNode();
  13141. if (decorators.length) {
  13142. member.decorators = decorators;
  13143. this.resetStartLocationFromNode(member, decorators[0]);
  13144. decorators = [];
  13145. }
  13146. this.parseClassMember(classBody, member, state);
  13147. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  13148. this.raise(Errors.DecoratorConstructor, member);
  13149. }
  13150. }
  13151. });
  13152. this.state.strict = oldStrict;
  13153. this.next();
  13154. if (decorators.length) {
  13155. throw this.raise(Errors.TrailingDecorator, this.state.startLoc);
  13156. }
  13157. this.classScope.exit();
  13158. return this.finishNode(classBody, "ClassBody");
  13159. }
  13160. parseClassMemberFromModifier(classBody, member) {
  13161. const key = this.parseIdentifier(true);
  13162. if (this.isClassMethod()) {
  13163. const method = member;
  13164. method.kind = "method";
  13165. method.computed = false;
  13166. method.key = key;
  13167. method.static = false;
  13168. this.pushClassMethod(classBody, method, false, false, false, false);
  13169. return true;
  13170. } else if (this.isClassProperty()) {
  13171. const prop = member;
  13172. prop.computed = false;
  13173. prop.key = key;
  13174. prop.static = false;
  13175. classBody.body.push(this.parseClassProperty(prop));
  13176. return true;
  13177. }
  13178. this.resetPreviousNodeTrailingComments(key);
  13179. return false;
  13180. }
  13181. parseClassMember(classBody, member, state) {
  13182. const isStatic = this.isContextual(106);
  13183. if (isStatic) {
  13184. if (this.parseClassMemberFromModifier(classBody, member)) {
  13185. return;
  13186. }
  13187. if (this.eat(5)) {
  13188. this.parseClassStaticBlock(classBody, member);
  13189. return;
  13190. }
  13191. }
  13192. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  13193. }
  13194. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  13195. const publicMethod = member;
  13196. const privateMethod = member;
  13197. const publicProp = member;
  13198. const privateProp = member;
  13199. const accessorProp = member;
  13200. const method = publicMethod;
  13201. const publicMember = publicMethod;
  13202. member.static = isStatic;
  13203. this.parsePropertyNamePrefixOperator(member);
  13204. if (this.eat(55)) {
  13205. method.kind = "method";
  13206. const isPrivateName = this.match(139);
  13207. this.parseClassElementName(method);
  13208. if (isPrivateName) {
  13209. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  13210. return;
  13211. }
  13212. if (this.isNonstaticConstructor(publicMethod)) {
  13213. this.raise(Errors.ConstructorIsGenerator, publicMethod.key);
  13214. }
  13215. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  13216. return;
  13217. }
  13218. const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type);
  13219. const key = this.parseClassElementName(member);
  13220. const maybeContextualKw = isContextual ? key.name : null;
  13221. const isPrivate = this.isPrivateName(key);
  13222. const maybeQuestionTokenStartLoc = this.state.startLoc;
  13223. this.parsePostMemberNameModifiers(publicMember);
  13224. if (this.isClassMethod()) {
  13225. method.kind = "method";
  13226. if (isPrivate) {
  13227. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  13228. return;
  13229. }
  13230. const isConstructor = this.isNonstaticConstructor(publicMethod);
  13231. let allowsDirectSuper = false;
  13232. if (isConstructor) {
  13233. publicMethod.kind = "constructor";
  13234. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  13235. this.raise(Errors.DuplicateConstructor, key);
  13236. }
  13237. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  13238. this.raise(Errors.OverrideOnConstructor, key);
  13239. }
  13240. state.hadConstructor = true;
  13241. allowsDirectSuper = state.hadSuperClass;
  13242. }
  13243. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  13244. } else if (this.isClassProperty()) {
  13245. if (isPrivate) {
  13246. this.pushClassPrivateProperty(classBody, privateProp);
  13247. } else {
  13248. this.pushClassProperty(classBody, publicProp);
  13249. }
  13250. } else if (maybeContextualKw === "async" && !this.isLineTerminator()) {
  13251. this.resetPreviousNodeTrailingComments(key);
  13252. const isGenerator = this.eat(55);
  13253. if (publicMember.optional) {
  13254. this.unexpected(maybeQuestionTokenStartLoc);
  13255. }
  13256. method.kind = "method";
  13257. const isPrivate = this.match(139);
  13258. this.parseClassElementName(method);
  13259. this.parsePostMemberNameModifiers(publicMember);
  13260. if (isPrivate) {
  13261. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  13262. } else {
  13263. if (this.isNonstaticConstructor(publicMethod)) {
  13264. this.raise(Errors.ConstructorIsAsync, publicMethod.key);
  13265. }
  13266. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  13267. }
  13268. } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) {
  13269. this.resetPreviousNodeTrailingComments(key);
  13270. method.kind = maybeContextualKw;
  13271. const isPrivate = this.match(139);
  13272. this.parseClassElementName(publicMethod);
  13273. if (isPrivate) {
  13274. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  13275. } else {
  13276. if (this.isNonstaticConstructor(publicMethod)) {
  13277. this.raise(Errors.ConstructorIsAccessor, publicMethod.key);
  13278. }
  13279. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  13280. }
  13281. this.checkGetterSetterParams(publicMethod);
  13282. } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) {
  13283. this.expectPlugin("decoratorAutoAccessors");
  13284. this.resetPreviousNodeTrailingComments(key);
  13285. const isPrivate = this.match(139);
  13286. this.parseClassElementName(publicProp);
  13287. this.pushClassAccessorProperty(classBody, accessorProp, isPrivate);
  13288. } else if (this.isLineTerminator()) {
  13289. if (isPrivate) {
  13290. this.pushClassPrivateProperty(classBody, privateProp);
  13291. } else {
  13292. this.pushClassProperty(classBody, publicProp);
  13293. }
  13294. } else {
  13295. this.unexpected();
  13296. }
  13297. }
  13298. parseClassElementName(member) {
  13299. const {
  13300. type,
  13301. value
  13302. } = this.state;
  13303. if ((type === 132 || type === 134) && member.static && value === "prototype") {
  13304. this.raise(Errors.StaticPrototype, this.state.startLoc);
  13305. }
  13306. if (type === 139) {
  13307. if (value === "constructor") {
  13308. this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc);
  13309. }
  13310. const key = this.parsePrivateName();
  13311. member.key = key;
  13312. return key;
  13313. }
  13314. this.parsePropertyName(member);
  13315. return member.key;
  13316. }
  13317. parseClassStaticBlock(classBody, member) {
  13318. var _member$decorators;
  13319. this.scope.enter(64 | 128 | 16);
  13320. const oldLabels = this.state.labels;
  13321. this.state.labels = [];
  13322. this.prodParam.enter(0);
  13323. const body = member.body = [];
  13324. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  13325. this.prodParam.exit();
  13326. this.scope.exit();
  13327. this.state.labels = oldLabels;
  13328. classBody.body.push(this.finishNode(member, "StaticBlock"));
  13329. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  13330. this.raise(Errors.DecoratorStaticBlock, member);
  13331. }
  13332. }
  13333. pushClassProperty(classBody, prop) {
  13334. if (!prop.computed && this.nameIsConstructor(prop.key)) {
  13335. this.raise(Errors.ConstructorClassField, prop.key);
  13336. }
  13337. classBody.body.push(this.parseClassProperty(prop));
  13338. }
  13339. pushClassPrivateProperty(classBody, prop) {
  13340. const node = this.parseClassPrivateProperty(prop);
  13341. classBody.body.push(node);
  13342. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  13343. }
  13344. pushClassAccessorProperty(classBody, prop, isPrivate) {
  13345. if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) {
  13346. this.raise(Errors.ConstructorClassField, prop.key);
  13347. }
  13348. const node = this.parseClassAccessorProperty(prop);
  13349. classBody.body.push(node);
  13350. if (isPrivate) {
  13351. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  13352. }
  13353. }
  13354. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  13355. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  13356. }
  13357. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  13358. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  13359. classBody.body.push(node);
  13360. const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0;
  13361. this.declareClassPrivateMethodInScope(node, kind);
  13362. }
  13363. declareClassPrivateMethodInScope(node, kind) {
  13364. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start);
  13365. }
  13366. parsePostMemberNameModifiers(methodOrProp) {}
  13367. parseClassPrivateProperty(node) {
  13368. this.parseInitializer(node);
  13369. this.semicolon();
  13370. return this.finishNode(node, "ClassPrivateProperty");
  13371. }
  13372. parseClassProperty(node) {
  13373. this.parseInitializer(node);
  13374. this.semicolon();
  13375. return this.finishNode(node, "ClassProperty");
  13376. }
  13377. parseClassAccessorProperty(node) {
  13378. this.parseInitializer(node);
  13379. this.semicolon();
  13380. return this.finishNode(node, "ClassAccessorProperty");
  13381. }
  13382. parseInitializer(node) {
  13383. this.scope.enter(64 | 16);
  13384. this.expressionScope.enter(newExpressionScope());
  13385. this.prodParam.enter(0);
  13386. node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
  13387. this.expressionScope.exit();
  13388. this.prodParam.exit();
  13389. this.scope.exit();
  13390. }
  13391. parseClassId(node, isStatement, optionalId, bindingType = 8331) {
  13392. if (tokenIsIdentifier(this.state.type)) {
  13393. node.id = this.parseIdentifier();
  13394. if (isStatement) {
  13395. this.declareNameFromIdentifier(node.id, bindingType);
  13396. }
  13397. } else {
  13398. if (optionalId || !isStatement) {
  13399. node.id = null;
  13400. } else {
  13401. throw this.raise(Errors.MissingClassName, this.state.startLoc);
  13402. }
  13403. }
  13404. }
  13405. parseClassSuper(node) {
  13406. node.superClass = this.eat(81) ? this.parseExprSubscripts() : null;
  13407. }
  13408. parseExport(node, decorators) {
  13409. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true);
  13410. const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  13411. const parseAfterDefault = !hasDefault || this.eat(12);
  13412. const hasStar = parseAfterDefault && this.eatExportStar(node);
  13413. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  13414. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  13415. const isFromRequired = hasDefault || hasStar;
  13416. if (hasStar && !hasNamespace) {
  13417. if (hasDefault) this.unexpected();
  13418. if (decorators) {
  13419. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13420. }
  13421. this.parseExportFrom(node, true);
  13422. return this.finishNode(node, "ExportAllDeclaration");
  13423. }
  13424. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  13425. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) {
  13426. this.unexpected(null, 5);
  13427. }
  13428. if (hasNamespace && parseAfterNamespace) {
  13429. this.unexpected(null, 98);
  13430. }
  13431. let hasDeclaration;
  13432. if (isFromRequired || hasSpecifiers) {
  13433. hasDeclaration = false;
  13434. if (decorators) {
  13435. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13436. }
  13437. this.parseExportFrom(node, isFromRequired);
  13438. } else {
  13439. hasDeclaration = this.maybeParseExportDeclaration(node);
  13440. }
  13441. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  13442. var _node2$declaration;
  13443. const node2 = node;
  13444. this.checkExport(node2, true, false, !!node2.source);
  13445. if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") {
  13446. this.maybeTakeDecorators(decorators, node2.declaration, node2);
  13447. } else if (decorators) {
  13448. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13449. }
  13450. return this.finishNode(node2, "ExportNamedDeclaration");
  13451. }
  13452. if (this.eat(65)) {
  13453. const node2 = node;
  13454. const decl = this.parseExportDefaultExpression();
  13455. node2.declaration = decl;
  13456. if (decl.type === "ClassDeclaration") {
  13457. this.maybeTakeDecorators(decorators, decl, node2);
  13458. } else if (decorators) {
  13459. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13460. }
  13461. this.checkExport(node2, true, true);
  13462. return this.finishNode(node2, "ExportDefaultDeclaration");
  13463. }
  13464. this.unexpected(null, 5);
  13465. }
  13466. eatExportStar(node) {
  13467. return this.eat(55);
  13468. }
  13469. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  13470. if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) {
  13471. this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start);
  13472. const id = maybeDefaultIdentifier || this.parseIdentifier(true);
  13473. const specifier = this.startNodeAtNode(id);
  13474. specifier.exported = id;
  13475. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  13476. return true;
  13477. }
  13478. return false;
  13479. }
  13480. maybeParseExportNamespaceSpecifier(node) {
  13481. if (this.isContextual(93)) {
  13482. var _ref, _ref$specifiers;
  13483. (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = [];
  13484. const specifier = this.startNodeAt(this.state.lastTokStartLoc);
  13485. this.next();
  13486. specifier.exported = this.parseModuleExportName();
  13487. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  13488. return true;
  13489. }
  13490. return false;
  13491. }
  13492. maybeParseExportNamedSpecifiers(node) {
  13493. if (this.match(5)) {
  13494. const node2 = node;
  13495. if (!node2.specifiers) node2.specifiers = [];
  13496. const isTypeExport = node2.exportKind === "type";
  13497. node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  13498. node2.source = null;
  13499. node2.declaration = null;
  13500. if (this.hasPlugin("importAssertions")) {
  13501. node2.assertions = [];
  13502. }
  13503. return true;
  13504. }
  13505. return false;
  13506. }
  13507. maybeParseExportDeclaration(node) {
  13508. if (this.shouldParseExportDeclaration()) {
  13509. node.specifiers = [];
  13510. node.source = null;
  13511. if (this.hasPlugin("importAssertions")) {
  13512. node.assertions = [];
  13513. }
  13514. node.declaration = this.parseExportDeclaration(node);
  13515. return true;
  13516. }
  13517. return false;
  13518. }
  13519. isAsyncFunction() {
  13520. if (!this.isContextual(95)) return false;
  13521. const next = this.nextTokenInLineStart();
  13522. return this.isUnparsedContextual(next, "function");
  13523. }
  13524. parseExportDefaultExpression() {
  13525. const expr = this.startNode();
  13526. if (this.match(68)) {
  13527. this.next();
  13528. return this.parseFunction(expr, 1 | 4);
  13529. } else if (this.isAsyncFunction()) {
  13530. this.next();
  13531. this.next();
  13532. return this.parseFunction(expr, 1 | 4 | 8);
  13533. }
  13534. if (this.match(80)) {
  13535. return this.parseClass(expr, true, true);
  13536. }
  13537. if (this.match(26)) {
  13538. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  13539. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  13540. }
  13541. return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true);
  13542. }
  13543. if (this.match(75) || this.match(74) || this.isLet()) {
  13544. throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc);
  13545. }
  13546. const res = this.parseMaybeAssignAllowIn();
  13547. this.semicolon();
  13548. return res;
  13549. }
  13550. parseExportDeclaration(node) {
  13551. if (this.match(80)) {
  13552. const node = this.parseClass(this.startNode(), true, false);
  13553. return node;
  13554. }
  13555. return this.parseStatementListItem();
  13556. }
  13557. isExportDefaultSpecifier() {
  13558. const {
  13559. type
  13560. } = this.state;
  13561. if (tokenIsIdentifier(type)) {
  13562. if (type === 95 && !this.state.containsEsc || type === 100) {
  13563. return false;
  13564. }
  13565. if ((type === 130 || type === 129) && !this.state.containsEsc) {
  13566. const {
  13567. type: nextType
  13568. } = this.lookahead();
  13569. if (tokenIsIdentifier(nextType) && nextType !== 98 || nextType === 5) {
  13570. this.expectOnePlugin(["flow", "typescript"]);
  13571. return false;
  13572. }
  13573. }
  13574. } else if (!this.match(65)) {
  13575. return false;
  13576. }
  13577. const next = this.nextTokenStart();
  13578. const hasFrom = this.isUnparsedContextual(next, "from");
  13579. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  13580. return true;
  13581. }
  13582. if (this.match(65) && hasFrom) {
  13583. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  13584. return nextAfterFrom === 34 || nextAfterFrom === 39;
  13585. }
  13586. return false;
  13587. }
  13588. parseExportFrom(node, expect) {
  13589. if (this.eatContextual(98)) {
  13590. node.source = this.parseImportSource();
  13591. this.checkExport(node);
  13592. this.maybeParseImportAttributes(node);
  13593. this.checkJSONModuleImport(node);
  13594. } else if (expect) {
  13595. this.unexpected();
  13596. }
  13597. this.semicolon();
  13598. }
  13599. shouldParseExportDeclaration() {
  13600. const {
  13601. type
  13602. } = this.state;
  13603. if (type === 26) {
  13604. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  13605. if (this.hasPlugin("decorators")) {
  13606. if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  13607. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  13608. }
  13609. return true;
  13610. }
  13611. }
  13612. if (this.isContextual(107)) {
  13613. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  13614. return true;
  13615. }
  13616. if (this.isContextual(96) && this.startsAwaitUsing()) {
  13617. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  13618. return true;
  13619. }
  13620. return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction();
  13621. }
  13622. checkExport(node, checkNames, isDefault, isFrom) {
  13623. if (checkNames) {
  13624. var _node$specifiers;
  13625. if (isDefault) {
  13626. this.checkDuplicateExports(node, "default");
  13627. if (this.hasPlugin("exportDefaultFrom")) {
  13628. var _declaration$extra;
  13629. const declaration = node.declaration;
  13630. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  13631. this.raise(Errors.ExportDefaultFromAsIdentifier, declaration);
  13632. }
  13633. }
  13634. } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
  13635. for (const specifier of node.specifiers) {
  13636. const {
  13637. exported
  13638. } = specifier;
  13639. const exportName = exported.type === "Identifier" ? exported.name : exported.value;
  13640. this.checkDuplicateExports(specifier, exportName);
  13641. if (!isFrom && specifier.local) {
  13642. const {
  13643. local
  13644. } = specifier;
  13645. if (local.type !== "Identifier") {
  13646. this.raise(Errors.ExportBindingIsString, specifier, {
  13647. localName: local.value,
  13648. exportName
  13649. });
  13650. } else {
  13651. this.checkReservedWord(local.name, local.loc.start, true, false);
  13652. this.scope.checkLocalExport(local);
  13653. }
  13654. }
  13655. }
  13656. } else if (node.declaration) {
  13657. const decl = node.declaration;
  13658. if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
  13659. const {
  13660. id
  13661. } = decl;
  13662. if (!id) throw new Error("Assertion failure");
  13663. this.checkDuplicateExports(node, id.name);
  13664. } else if (decl.type === "VariableDeclaration") {
  13665. for (const declaration of decl.declarations) {
  13666. this.checkDeclaration(declaration.id);
  13667. }
  13668. }
  13669. }
  13670. }
  13671. }
  13672. checkDeclaration(node) {
  13673. if (node.type === "Identifier") {
  13674. this.checkDuplicateExports(node, node.name);
  13675. } else if (node.type === "ObjectPattern") {
  13676. for (const prop of node.properties) {
  13677. this.checkDeclaration(prop);
  13678. }
  13679. } else if (node.type === "ArrayPattern") {
  13680. for (const elem of node.elements) {
  13681. if (elem) {
  13682. this.checkDeclaration(elem);
  13683. }
  13684. }
  13685. } else if (node.type === "ObjectProperty") {
  13686. this.checkDeclaration(node.value);
  13687. } else if (node.type === "RestElement") {
  13688. this.checkDeclaration(node.argument);
  13689. } else if (node.type === "AssignmentPattern") {
  13690. this.checkDeclaration(node.left);
  13691. }
  13692. }
  13693. checkDuplicateExports(node, exportName) {
  13694. if (this.exportedIdentifiers.has(exportName)) {
  13695. if (exportName === "default") {
  13696. this.raise(Errors.DuplicateDefaultExport, node);
  13697. } else {
  13698. this.raise(Errors.DuplicateExport, node, {
  13699. exportName
  13700. });
  13701. }
  13702. }
  13703. this.exportedIdentifiers.add(exportName);
  13704. }
  13705. parseExportSpecifiers(isInTypeExport) {
  13706. const nodes = [];
  13707. let first = true;
  13708. this.expect(5);
  13709. while (!this.eat(8)) {
  13710. if (first) {
  13711. first = false;
  13712. } else {
  13713. this.expect(12);
  13714. if (this.eat(8)) break;
  13715. }
  13716. const isMaybeTypeOnly = this.isContextual(130);
  13717. const isString = this.match(134);
  13718. const node = this.startNode();
  13719. node.local = this.parseModuleExportName();
  13720. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  13721. }
  13722. return nodes;
  13723. }
  13724. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  13725. if (this.eatContextual(93)) {
  13726. node.exported = this.parseModuleExportName();
  13727. } else if (isString) {
  13728. node.exported = cloneStringLiteral(node.local);
  13729. } else if (!node.exported) {
  13730. node.exported = cloneIdentifier(node.local);
  13731. }
  13732. return this.finishNode(node, "ExportSpecifier");
  13733. }
  13734. parseModuleExportName() {
  13735. if (this.match(134)) {
  13736. const result = this.parseStringLiteral(this.state.value);
  13737. const surrogate = loneSurrogate.exec(result.value);
  13738. if (surrogate) {
  13739. this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, {
  13740. surrogateCharCode: surrogate[0].charCodeAt(0)
  13741. });
  13742. }
  13743. return result;
  13744. }
  13745. return this.parseIdentifier(true);
  13746. }
  13747. isJSONModuleImport(node) {
  13748. if (node.assertions != null) {
  13749. return node.assertions.some(({
  13750. key,
  13751. value
  13752. }) => {
  13753. return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type");
  13754. });
  13755. }
  13756. return false;
  13757. }
  13758. checkImportReflection(node) {
  13759. const {
  13760. specifiers
  13761. } = node;
  13762. const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null;
  13763. if (node.phase === "source") {
  13764. if (singleBindingType !== "ImportDefaultSpecifier") {
  13765. this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start);
  13766. }
  13767. } else if (node.phase === "defer") {
  13768. if (singleBindingType !== "ImportNamespaceSpecifier") {
  13769. this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start);
  13770. }
  13771. } else if (node.module) {
  13772. var _node$assertions;
  13773. if (singleBindingType !== "ImportDefaultSpecifier") {
  13774. this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start);
  13775. }
  13776. if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) {
  13777. this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start);
  13778. }
  13779. }
  13780. }
  13781. checkJSONModuleImport(node) {
  13782. if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") {
  13783. const {
  13784. specifiers
  13785. } = node;
  13786. if (specifiers != null) {
  13787. const nonDefaultNamedSpecifier = specifiers.find(specifier => {
  13788. let imported;
  13789. if (specifier.type === "ExportSpecifier") {
  13790. imported = specifier.local;
  13791. } else if (specifier.type === "ImportSpecifier") {
  13792. imported = specifier.imported;
  13793. }
  13794. if (imported !== undefined) {
  13795. return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default";
  13796. }
  13797. });
  13798. if (nonDefaultNamedSpecifier !== undefined) {
  13799. this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start);
  13800. }
  13801. }
  13802. }
  13803. }
  13804. isPotentialImportPhase(isExport) {
  13805. if (isExport) return false;
  13806. return this.isContextual(105) || this.isContextual(97) || this.isContextual(127);
  13807. }
  13808. applyImportPhase(node, isExport, phase, loc) {
  13809. if (isExport) {
  13810. return;
  13811. }
  13812. if (phase === "module") {
  13813. this.expectPlugin("importReflection", loc);
  13814. node.module = true;
  13815. } else if (this.hasPlugin("importReflection")) {
  13816. node.module = false;
  13817. }
  13818. if (phase === "source") {
  13819. this.expectPlugin("sourcePhaseImports", loc);
  13820. node.phase = "source";
  13821. } else if (phase === "defer") {
  13822. this.expectPlugin("deferredImportEvaluation", loc);
  13823. node.phase = "defer";
  13824. } else if (this.hasPlugin("sourcePhaseImports")) {
  13825. node.phase = null;
  13826. }
  13827. }
  13828. parseMaybeImportPhase(node, isExport) {
  13829. if (!this.isPotentialImportPhase(isExport)) {
  13830. this.applyImportPhase(node, isExport, null);
  13831. return null;
  13832. }
  13833. const phaseIdentifier = this.parseIdentifier(true);
  13834. const {
  13835. type
  13836. } = this.state;
  13837. const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  13838. if (isImportPhase) {
  13839. this.resetPreviousIdentifierLeadingComments(phaseIdentifier);
  13840. this.applyImportPhase(node, isExport, phaseIdentifier.name, phaseIdentifier.loc.start);
  13841. return null;
  13842. } else {
  13843. this.applyImportPhase(node, isExport, null);
  13844. return phaseIdentifier;
  13845. }
  13846. }
  13847. isPrecedingIdImportPhase(phase) {
  13848. const {
  13849. type
  13850. } = this.state;
  13851. return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  13852. }
  13853. parseImport(node) {
  13854. if (this.match(134)) {
  13855. return this.parseImportSourceAndAttributes(node);
  13856. }
  13857. return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false));
  13858. }
  13859. parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) {
  13860. node.specifiers = [];
  13861. const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier);
  13862. const parseNext = !hasDefault || this.eat(12);
  13863. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  13864. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  13865. this.expectContextual(98);
  13866. return this.parseImportSourceAndAttributes(node);
  13867. }
  13868. parseImportSourceAndAttributes(node) {
  13869. var _node$specifiers2;
  13870. (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = [];
  13871. node.source = this.parseImportSource();
  13872. this.maybeParseImportAttributes(node);
  13873. this.checkImportReflection(node);
  13874. this.checkJSONModuleImport(node);
  13875. this.semicolon();
  13876. return this.finishNode(node, "ImportDeclaration");
  13877. }
  13878. parseImportSource() {
  13879. if (!this.match(134)) this.unexpected();
  13880. return this.parseExprAtom();
  13881. }
  13882. parseImportSpecifierLocal(node, specifier, type) {
  13883. specifier.local = this.parseIdentifier();
  13884. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  13885. }
  13886. finishImportSpecifier(specifier, type, bindingType = 8201) {
  13887. this.checkLVal(specifier.local, {
  13888. type
  13889. }, bindingType);
  13890. return this.finishNode(specifier, type);
  13891. }
  13892. parseImportAttributes() {
  13893. this.expect(5);
  13894. const attrs = [];
  13895. const attrNames = new Set();
  13896. do {
  13897. if (this.match(8)) {
  13898. break;
  13899. }
  13900. const node = this.startNode();
  13901. const keyName = this.state.value;
  13902. if (attrNames.has(keyName)) {
  13903. this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, {
  13904. key: keyName
  13905. });
  13906. }
  13907. attrNames.add(keyName);
  13908. if (this.match(134)) {
  13909. node.key = this.parseStringLiteral(keyName);
  13910. } else {
  13911. node.key = this.parseIdentifier(true);
  13912. }
  13913. this.expect(14);
  13914. if (!this.match(134)) {
  13915. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  13916. }
  13917. node.value = this.parseStringLiteral(this.state.value);
  13918. attrs.push(this.finishNode(node, "ImportAttribute"));
  13919. } while (this.eat(12));
  13920. this.expect(8);
  13921. return attrs;
  13922. }
  13923. parseModuleAttributes() {
  13924. const attrs = [];
  13925. const attributes = new Set();
  13926. do {
  13927. const node = this.startNode();
  13928. node.key = this.parseIdentifier(true);
  13929. if (node.key.name !== "type") {
  13930. this.raise(Errors.ModuleAttributeDifferentFromType, node.key);
  13931. }
  13932. if (attributes.has(node.key.name)) {
  13933. this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, {
  13934. key: node.key.name
  13935. });
  13936. }
  13937. attributes.add(node.key.name);
  13938. this.expect(14);
  13939. if (!this.match(134)) {
  13940. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  13941. }
  13942. node.value = this.parseStringLiteral(this.state.value);
  13943. attrs.push(this.finishNode(node, "ImportAttribute"));
  13944. } while (this.eat(12));
  13945. return attrs;
  13946. }
  13947. maybeParseImportAttributes(node) {
  13948. let attributes;
  13949. {
  13950. var useWith = false;
  13951. }
  13952. if (this.match(76)) {
  13953. if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) {
  13954. return;
  13955. }
  13956. this.next();
  13957. if (this.hasPlugin("moduleAttributes")) {
  13958. attributes = this.parseModuleAttributes();
  13959. } else {
  13960. attributes = this.parseImportAttributes();
  13961. }
  13962. {
  13963. useWith = true;
  13964. }
  13965. } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) {
  13966. if (!this.hasPlugin("deprecatedImportAssert") && !this.hasPlugin("importAssertions")) {
  13967. this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc);
  13968. }
  13969. if (!this.hasPlugin("importAssertions")) {
  13970. this.addExtra(node, "deprecatedAssertSyntax", true);
  13971. }
  13972. this.next();
  13973. attributes = this.parseImportAttributes();
  13974. } else {
  13975. attributes = [];
  13976. }
  13977. if (!useWith && this.hasPlugin("importAssertions")) {
  13978. node.assertions = attributes;
  13979. } else {
  13980. node.attributes = attributes;
  13981. }
  13982. }
  13983. maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) {
  13984. if (maybeDefaultIdentifier) {
  13985. const specifier = this.startNodeAtNode(maybeDefaultIdentifier);
  13986. specifier.local = maybeDefaultIdentifier;
  13987. node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier"));
  13988. return true;
  13989. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  13990. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier");
  13991. return true;
  13992. }
  13993. return false;
  13994. }
  13995. maybeParseStarImportSpecifier(node) {
  13996. if (this.match(55)) {
  13997. const specifier = this.startNode();
  13998. this.next();
  13999. this.expectContextual(93);
  14000. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier");
  14001. return true;
  14002. }
  14003. return false;
  14004. }
  14005. parseNamedImportSpecifiers(node) {
  14006. let first = true;
  14007. this.expect(5);
  14008. while (!this.eat(8)) {
  14009. if (first) {
  14010. first = false;
  14011. } else {
  14012. if (this.eat(14)) {
  14013. throw this.raise(Errors.DestructureNamedImport, this.state.startLoc);
  14014. }
  14015. this.expect(12);
  14016. if (this.eat(8)) break;
  14017. }
  14018. const specifier = this.startNode();
  14019. const importedIsString = this.match(134);
  14020. const isMaybeTypeOnly = this.isContextual(130);
  14021. specifier.imported = this.parseModuleExportName();
  14022. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined);
  14023. node.specifiers.push(importSpecifier);
  14024. }
  14025. }
  14026. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  14027. if (this.eatContextual(93)) {
  14028. specifier.local = this.parseIdentifier();
  14029. } else {
  14030. const {
  14031. imported
  14032. } = specifier;
  14033. if (importedIsString) {
  14034. throw this.raise(Errors.ImportBindingIsString, specifier, {
  14035. importName: imported.value
  14036. });
  14037. }
  14038. this.checkReservedWord(imported.name, specifier.loc.start, true, true);
  14039. if (!specifier.local) {
  14040. specifier.local = cloneIdentifier(imported);
  14041. }
  14042. }
  14043. return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType);
  14044. }
  14045. isThisParam(param) {
  14046. return param.type === "Identifier" && param.name === "this";
  14047. }
  14048. }
  14049. class Parser extends StatementParser {
  14050. constructor(options, input, pluginsMap) {
  14051. options = getOptions(options);
  14052. super(options, input);
  14053. this.options = options;
  14054. this.initializeScopes();
  14055. this.plugins = pluginsMap;
  14056. this.filename = options.sourceFilename;
  14057. this.startIndex = options.startIndex;
  14058. let optionFlags = 0;
  14059. if (options.allowAwaitOutsideFunction) {
  14060. optionFlags |= 1;
  14061. }
  14062. if (options.allowReturnOutsideFunction) {
  14063. optionFlags |= 2;
  14064. }
  14065. if (options.allowImportExportEverywhere) {
  14066. optionFlags |= 8;
  14067. }
  14068. if (options.allowSuperOutsideMethod) {
  14069. optionFlags |= 16;
  14070. }
  14071. if (options.allowUndeclaredExports) {
  14072. optionFlags |= 32;
  14073. }
  14074. if (options.allowNewTargetOutsideFunction) {
  14075. optionFlags |= 4;
  14076. }
  14077. if (options.ranges) {
  14078. optionFlags |= 64;
  14079. }
  14080. if (options.tokens) {
  14081. optionFlags |= 128;
  14082. }
  14083. if (options.createImportExpressions) {
  14084. optionFlags |= 256;
  14085. }
  14086. if (options.createParenthesizedExpressions) {
  14087. optionFlags |= 512;
  14088. }
  14089. if (options.errorRecovery) {
  14090. optionFlags |= 1024;
  14091. }
  14092. if (options.attachComment) {
  14093. optionFlags |= 2048;
  14094. }
  14095. if (options.annexB) {
  14096. optionFlags |= 4096;
  14097. }
  14098. this.optionFlags = optionFlags;
  14099. }
  14100. getScopeHandler() {
  14101. return ScopeHandler;
  14102. }
  14103. parse() {
  14104. this.enterInitialScopes();
  14105. const file = this.startNode();
  14106. const program = this.startNode();
  14107. this.nextToken();
  14108. file.errors = null;
  14109. this.parseTopLevel(file, program);
  14110. file.errors = this.state.errors;
  14111. file.comments.length = this.state.commentsLen;
  14112. return file;
  14113. }
  14114. }
  14115. function parse(input, options) {
  14116. var _options;
  14117. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  14118. options = Object.assign({}, options);
  14119. try {
  14120. options.sourceType = "module";
  14121. const parser = getParser(options, input);
  14122. const ast = parser.parse();
  14123. if (parser.sawUnambiguousESM) {
  14124. return ast;
  14125. }
  14126. if (parser.ambiguousScriptDifferentAst) {
  14127. try {
  14128. options.sourceType = "script";
  14129. return getParser(options, input).parse();
  14130. } catch (_unused) {}
  14131. } else {
  14132. ast.program.sourceType = "script";
  14133. }
  14134. return ast;
  14135. } catch (moduleError) {
  14136. try {
  14137. options.sourceType = "script";
  14138. return getParser(options, input).parse();
  14139. } catch (_unused2) {}
  14140. throw moduleError;
  14141. }
  14142. } else {
  14143. return getParser(options, input).parse();
  14144. }
  14145. }
  14146. function parseExpression(input, options) {
  14147. const parser = getParser(options, input);
  14148. if (parser.options.strictMode) {
  14149. parser.state.strict = true;
  14150. }
  14151. return parser.getExpression();
  14152. }
  14153. function generateExportedTokenTypes(internalTokenTypes) {
  14154. const tokenTypes = {};
  14155. for (const typeName of Object.keys(internalTokenTypes)) {
  14156. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  14157. }
  14158. return tokenTypes;
  14159. }
  14160. const tokTypes = generateExportedTokenTypes(tt);
  14161. function getParser(options, input) {
  14162. let cls = Parser;
  14163. const pluginsMap = new Map();
  14164. if (options != null && options.plugins) {
  14165. for (const plugin of options.plugins) {
  14166. let name, opts;
  14167. if (typeof plugin === "string") {
  14168. name = plugin;
  14169. } else {
  14170. [name, opts] = plugin;
  14171. }
  14172. if (!pluginsMap.has(name)) {
  14173. pluginsMap.set(name, opts || {});
  14174. }
  14175. }
  14176. validatePlugins(pluginsMap);
  14177. cls = getParserClass(pluginsMap);
  14178. }
  14179. return new cls(options, input, pluginsMap);
  14180. }
  14181. const parserClassCache = new Map();
  14182. function getParserClass(pluginsMap) {
  14183. const pluginList = [];
  14184. for (const name of mixinPluginNames) {
  14185. if (pluginsMap.has(name)) {
  14186. pluginList.push(name);
  14187. }
  14188. }
  14189. const key = pluginList.join("|");
  14190. let cls = parserClassCache.get(key);
  14191. if (!cls) {
  14192. cls = Parser;
  14193. for (const plugin of pluginList) {
  14194. cls = mixinPlugins[plugin](cls);
  14195. }
  14196. parserClassCache.set(key, cls);
  14197. }
  14198. return cls;
  14199. }
  14200. exports.parse = parse;
  14201. exports.parseExpression = parseExpression;
  14202. exports.tokTypes = tokTypes;
  14203. //# sourceMappingURL=index.js.map