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.

14246 lines
480 KiB

  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 (-1 !== e.indexOf(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. BadGetterArity: "A 'get' accessor must not have any formal parameters.",
  91. BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
  92. BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
  93. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  94. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  95. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  96. ConstructorIsAsync: "Constructor can't be an async function.",
  97. ConstructorIsGenerator: "Constructor can't be a generator.",
  98. DeclarationMissingInitializer: ({
  99. kind
  100. }) => `Missing initializer in ${kind} declaration.`,
  101. DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
  102. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",
  103. DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",
  104. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  105. DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",
  106. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  107. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  108. DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.',
  109. DeletePrivateField: "Deleting a private field is not allowed.",
  110. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  111. DuplicateConstructor: "Duplicate constructor in the same class.",
  112. DuplicateDefaultExport: "Only one default export allowed per module.",
  113. DuplicateExport: ({
  114. exportName
  115. }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
  116. DuplicateProto: "Redefinition of __proto__ property.",
  117. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  118. DynamicImportPhaseRequiresImportExpressions: ({
  119. phase
  120. }) => `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`,
  121. ElementAfterRest: "Rest element must be last element.",
  122. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  123. ExportBindingIsString: ({
  124. localName,
  125. exportName
  126. }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
  127. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  128. ForInOfLoopInitializer: ({
  129. type
  130. }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
  131. ForInUsing: "For-in loop may not start with 'using' declaration.",
  132. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  133. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  134. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  135. IllegalBreakContinue: ({
  136. type
  137. }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
  138. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  139. IllegalReturn: "'return' outside of function.",
  140. 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.",
  141. ImportBindingIsString: ({
  142. importName
  143. }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`,
  144. ImportCallArity: `\`import()\` requires exactly one or two arguments.`,
  145. ImportCallNotNewExpression: "Cannot use new with import(...).",
  146. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  147. ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
  148. ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
  149. ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
  150. IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
  151. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  152. InvalidCodePoint: "Code point out of bounds.",
  153. InvalidCoverInitializedName: "Invalid shorthand property initializer.",
  154. InvalidDecimal: "Invalid decimal.",
  155. InvalidDigit: ({
  156. radix
  157. }) => `Expected number in radix ${radix}.`,
  158. InvalidEscapeSequence: "Bad character escape sequence.",
  159. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  160. InvalidEscapedReservedWord: ({
  161. reservedWord
  162. }) => `Escape sequence in keyword ${reservedWord}.`,
  163. InvalidIdentifier: ({
  164. identifierName
  165. }) => `Invalid identifier ${identifierName}.`,
  166. InvalidLhs: ({
  167. ancestor
  168. }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  169. InvalidLhsBinding: ({
  170. ancestor
  171. }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  172. InvalidLhsOptionalChaining: ({
  173. ancestor
  174. }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`,
  175. InvalidNumber: "Invalid number.",
  176. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  177. InvalidOrUnexpectedToken: ({
  178. unexpected
  179. }) => `Unexpected character '${unexpected}'.`,
  180. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  181. InvalidPrivateFieldResolution: ({
  182. identifierName
  183. }) => `Private name #${identifierName} is not defined.`,
  184. InvalidPropertyBindingPattern: "Binding member expression.",
  185. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  186. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  187. LabelRedeclaration: ({
  188. labelName
  189. }) => `Label '${labelName}' is already declared.`,
  190. LetInLexicalBinding: "'let' is disallowed as a lexically bound name.",
  191. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  192. MalformedRegExpFlags: "Invalid regular expression flag.",
  193. MissingClassName: "A class name is required.",
  194. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  195. MissingSemicolon: "Missing semicolon.",
  196. MissingPlugin: ({
  197. missingPlugin
  198. }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  199. MissingOneOfPlugins: ({
  200. missingPlugin
  201. }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  202. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  203. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  204. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  205. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  206. ModuleAttributesWithDuplicateKeys: ({
  207. key
  208. }) => `Duplicate key "${key}" is not allowed in module attributes.`,
  209. ModuleExportNameHasLoneSurrogate: ({
  210. surrogateCharCode
  211. }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
  212. ModuleExportUndefined: ({
  213. localName
  214. }) => `Export '${localName}' is not defined.`,
  215. MultipleDefaultsInSwitch: "Multiple default clauses.",
  216. NewlineAfterThrow: "Illegal newline after throw.",
  217. NoCatchOrFinally: "Missing catch or finally clause.",
  218. NumberIdentifier: "Identifier directly after number.",
  219. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  220. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  221. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  222. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  223. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  224. ParamDupe: "Argument name clash.",
  225. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  226. PatternHasMethod: "Object pattern can't contain methods.",
  227. PrivateInExpectedIn: ({
  228. identifierName
  229. }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,
  230. PrivateNameRedeclaration: ({
  231. identifierName
  232. }) => `Duplicate private name #${identifierName}.`,
  233. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  234. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  235. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  236. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  237. RestTrailingComma: "Unexpected trailing comma after rest element.",
  238. SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.",
  239. 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.",
  240. SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.',
  241. StaticPrototype: "Classes may not have static property named prototype.",
  242. 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?",
  243. SuperPrivateField: "Private fields can't be accessed on super.",
  244. TrailingDecorator: "Decorators must be attached to a class element.",
  245. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  246. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  247. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  248. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  249. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  250. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  251. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  252. UnexpectedKeyword: ({
  253. keyword
  254. }) => `Unexpected keyword '${keyword}'.`,
  255. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  256. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  257. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  258. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  259. UnexpectedPrivateField: "Unexpected private name.",
  260. UnexpectedReservedWord: ({
  261. reservedWord
  262. }) => `Unexpected reserved word '${reservedWord}'.`,
  263. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  264. UnexpectedToken: ({
  265. expected,
  266. unexpected
  267. }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`,
  268. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  269. UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.",
  270. UnsupportedBind: "Binding should be performed on object property.",
  271. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  272. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  273. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  274. UnsupportedMetaProperty: ({
  275. target,
  276. onlyValidPropertyName
  277. }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,
  278. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  279. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  280. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  281. UnterminatedComment: "Unterminated comment.",
  282. UnterminatedRegExp: "Unterminated regular expression.",
  283. UnterminatedString: "Unterminated string constant.",
  284. UnterminatedTemplate: "Unterminated template.",
  285. UsingDeclarationExport: "Using declaration cannot be exported.",
  286. UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.",
  287. VarRedeclaration: ({
  288. identifierName
  289. }) => `Identifier '${identifierName}' has already been declared.`,
  290. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  291. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  292. YieldNotInGeneratorFunction: "'yield' is only allowed within generator functions.",
  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. allowYieldOutsideFunction: false,
  437. plugins: [],
  438. strictMode: null,
  439. ranges: false,
  440. tokens: false,
  441. createImportExpressions: false,
  442. createParenthesizedExpressions: false,
  443. errorRecovery: false,
  444. attachComment: true,
  445. annexB: true
  446. };
  447. }
  448. function getOptions(opts) {
  449. const options = createDefaultOptions();
  450. if (opts == null) {
  451. return options;
  452. }
  453. if (opts.annexB != null && opts.annexB !== false) {
  454. throw new Error("The `annexB` option can only be set to `false`.");
  455. }
  456. for (const key of Object.keys(options)) {
  457. if (opts[key] != null) options[key] = opts[key];
  458. }
  459. if (options.startLine === 1) {
  460. if (opts.startIndex == null && options.startColumn > 0) {
  461. options.startIndex = options.startColumn;
  462. } else if (opts.startColumn == null && options.startIndex > 0) {
  463. options.startColumn = options.startIndex;
  464. }
  465. } else if (opts.startColumn == null || opts.startIndex == null) {
  466. if (opts.startIndex != null) {
  467. throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");
  468. }
  469. }
  470. return options;
  471. }
  472. const {
  473. defineProperty
  474. } = Object;
  475. const toUnenumerable = (object, key) => {
  476. if (object) {
  477. defineProperty(object, key, {
  478. enumerable: false,
  479. value: object[key]
  480. });
  481. }
  482. };
  483. function toESTreeLocation(node) {
  484. toUnenumerable(node.loc.start, "index");
  485. toUnenumerable(node.loc.end, "index");
  486. return node;
  487. }
  488. var estree = superClass => class ESTreeParserMixin extends superClass {
  489. parse() {
  490. const file = toESTreeLocation(super.parse());
  491. if (this.optionFlags & 256) {
  492. file.tokens = file.tokens.map(toESTreeLocation);
  493. }
  494. return file;
  495. }
  496. parseRegExpLiteral({
  497. pattern,
  498. flags
  499. }) {
  500. let regex = null;
  501. try {
  502. regex = new RegExp(pattern, flags);
  503. } catch (_) {}
  504. const node = this.estreeParseLiteral(regex);
  505. node.regex = {
  506. pattern,
  507. flags
  508. };
  509. return node;
  510. }
  511. parseBigIntLiteral(value) {
  512. let bigInt;
  513. try {
  514. bigInt = BigInt(value);
  515. } catch (_unused) {
  516. bigInt = null;
  517. }
  518. const node = this.estreeParseLiteral(bigInt);
  519. node.bigint = String(node.value || value);
  520. return node;
  521. }
  522. parseDecimalLiteral(value) {
  523. const decimal = null;
  524. const node = this.estreeParseLiteral(decimal);
  525. node.decimal = String(node.value || value);
  526. return node;
  527. }
  528. estreeParseLiteral(value) {
  529. return this.parseLiteral(value, "Literal");
  530. }
  531. parseStringLiteral(value) {
  532. return this.estreeParseLiteral(value);
  533. }
  534. parseNumericLiteral(value) {
  535. return this.estreeParseLiteral(value);
  536. }
  537. parseNullLiteral() {
  538. return this.estreeParseLiteral(null);
  539. }
  540. parseBooleanLiteral(value) {
  541. return this.estreeParseLiteral(value);
  542. }
  543. directiveToStmt(directive) {
  544. const expression = directive.value;
  545. delete directive.value;
  546. expression.type = "Literal";
  547. expression.raw = expression.extra.raw;
  548. expression.value = expression.extra.expressionValue;
  549. const stmt = directive;
  550. stmt.type = "ExpressionStatement";
  551. stmt.expression = expression;
  552. stmt.directive = expression.extra.rawValue;
  553. delete expression.extra;
  554. return stmt;
  555. }
  556. initFunction(node, isAsync) {
  557. super.initFunction(node, isAsync);
  558. node.expression = false;
  559. }
  560. checkDeclaration(node) {
  561. if (node != null && this.isObjectProperty(node)) {
  562. this.checkDeclaration(node.value);
  563. } else {
  564. super.checkDeclaration(node);
  565. }
  566. }
  567. getObjectOrClassMethodParams(method) {
  568. return method.value.params;
  569. }
  570. isValidDirective(stmt) {
  571. var _stmt$expression$extr;
  572. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  573. }
  574. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  575. super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse);
  576. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  577. node.body = directiveStatements.concat(node.body);
  578. delete node.directives;
  579. }
  580. parsePrivateName() {
  581. const node = super.parsePrivateName();
  582. {
  583. if (!this.getPluginOption("estree", "classFeatures")) {
  584. return node;
  585. }
  586. }
  587. return this.convertPrivateNameToPrivateIdentifier(node);
  588. }
  589. convertPrivateNameToPrivateIdentifier(node) {
  590. const name = super.getPrivateNameSV(node);
  591. node = node;
  592. delete node.id;
  593. node.name = name;
  594. node.type = "PrivateIdentifier";
  595. return node;
  596. }
  597. isPrivateName(node) {
  598. {
  599. if (!this.getPluginOption("estree", "classFeatures")) {
  600. return super.isPrivateName(node);
  601. }
  602. }
  603. return node.type === "PrivateIdentifier";
  604. }
  605. getPrivateNameSV(node) {
  606. {
  607. if (!this.getPluginOption("estree", "classFeatures")) {
  608. return super.getPrivateNameSV(node);
  609. }
  610. }
  611. return node.name;
  612. }
  613. parseLiteral(value, type) {
  614. const node = super.parseLiteral(value, type);
  615. node.raw = node.extra.raw;
  616. delete node.extra;
  617. return node;
  618. }
  619. parseFunctionBody(node, allowExpression, isMethod = false) {
  620. super.parseFunctionBody(node, allowExpression, isMethod);
  621. node.expression = node.body.type !== "BlockStatement";
  622. }
  623. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  624. let funcNode = this.startNode();
  625. funcNode.kind = node.kind;
  626. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  627. funcNode.type = "FunctionExpression";
  628. delete funcNode.kind;
  629. node.value = funcNode;
  630. const {
  631. typeParameters
  632. } = node;
  633. if (typeParameters) {
  634. delete node.typeParameters;
  635. funcNode.typeParameters = typeParameters;
  636. this.resetStartLocationFromNode(funcNode, typeParameters);
  637. }
  638. if (type === "ClassPrivateMethod") {
  639. node.computed = false;
  640. }
  641. return this.finishNode(node, "MethodDefinition");
  642. }
  643. nameIsConstructor(key) {
  644. if (key.type === "Literal") return key.value === "constructor";
  645. return super.nameIsConstructor(key);
  646. }
  647. parseClassProperty(...args) {
  648. const propertyNode = super.parseClassProperty(...args);
  649. {
  650. if (!this.getPluginOption("estree", "classFeatures")) {
  651. return propertyNode;
  652. }
  653. }
  654. {
  655. propertyNode.type = "PropertyDefinition";
  656. }
  657. return propertyNode;
  658. }
  659. parseClassPrivateProperty(...args) {
  660. const propertyNode = super.parseClassPrivateProperty(...args);
  661. {
  662. if (!this.getPluginOption("estree", "classFeatures")) {
  663. return propertyNode;
  664. }
  665. }
  666. {
  667. propertyNode.type = "PropertyDefinition";
  668. }
  669. propertyNode.computed = false;
  670. return propertyNode;
  671. }
  672. parseClassAccessorProperty(node) {
  673. const accessorPropertyNode = super.parseClassAccessorProperty(node);
  674. {
  675. if (!this.getPluginOption("estree", "classFeatures")) {
  676. return accessorPropertyNode;
  677. }
  678. }
  679. accessorPropertyNode.type = "AccessorProperty";
  680. return accessorPropertyNode;
  681. }
  682. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  683. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  684. if (node) {
  685. node.type = "Property";
  686. if (node.kind === "method") {
  687. node.kind = "init";
  688. }
  689. node.shorthand = false;
  690. }
  691. return node;
  692. }
  693. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  694. const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  695. if (node) {
  696. node.kind = "init";
  697. node.type = "Property";
  698. }
  699. return node;
  700. }
  701. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  702. return type === "Property" ? "value" : super.isValidLVal(type, isUnparenthesizedInAssign, binding);
  703. }
  704. isAssignable(node, isBinding) {
  705. if (node != null && this.isObjectProperty(node)) {
  706. return this.isAssignable(node.value, isBinding);
  707. }
  708. return super.isAssignable(node, isBinding);
  709. }
  710. toAssignable(node, isLHS = false) {
  711. if (node != null && this.isObjectProperty(node)) {
  712. const {
  713. key,
  714. value
  715. } = node;
  716. if (this.isPrivateName(key)) {
  717. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  718. }
  719. this.toAssignable(value, isLHS);
  720. } else {
  721. super.toAssignable(node, isLHS);
  722. }
  723. }
  724. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  725. if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) {
  726. this.raise(Errors.PatternHasAccessor, prop.key);
  727. } else if (prop.type === "Property" && prop.method) {
  728. this.raise(Errors.PatternHasMethod, prop.key);
  729. } else {
  730. super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  731. }
  732. }
  733. finishCallExpression(unfinished, optional) {
  734. const node = super.finishCallExpression(unfinished, optional);
  735. if (node.callee.type === "Import") {
  736. var _ref, _ref2;
  737. node.type = "ImportExpression";
  738. node.source = node.arguments[0];
  739. node.options = (_ref = node.arguments[1]) != null ? _ref : null;
  740. node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null;
  741. delete node.arguments;
  742. delete node.callee;
  743. }
  744. return node;
  745. }
  746. toReferencedArguments(node) {
  747. if (node.type === "ImportExpression") {
  748. return;
  749. }
  750. super.toReferencedArguments(node);
  751. }
  752. parseExport(unfinished, decorators) {
  753. const exportStartLoc = this.state.lastTokStartLoc;
  754. const node = super.parseExport(unfinished, decorators);
  755. switch (node.type) {
  756. case "ExportAllDeclaration":
  757. node.exported = null;
  758. break;
  759. case "ExportNamedDeclaration":
  760. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  761. node.type = "ExportAllDeclaration";
  762. node.exported = node.specifiers[0].exported;
  763. delete node.specifiers;
  764. }
  765. case "ExportDefaultDeclaration":
  766. {
  767. var _declaration$decorato;
  768. const {
  769. declaration
  770. } = node;
  771. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) {
  772. this.resetStartLocation(node, exportStartLoc);
  773. }
  774. }
  775. break;
  776. }
  777. return node;
  778. }
  779. parseSubscript(base, startLoc, noCalls, state) {
  780. const node = super.parseSubscript(base, startLoc, noCalls, state);
  781. if (state.optionalChainMember) {
  782. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  783. node.type = node.type.substring(8);
  784. }
  785. if (state.stop) {
  786. const chain = this.startNodeAtNode(node);
  787. chain.expression = node;
  788. return this.finishNode(chain, "ChainExpression");
  789. }
  790. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  791. node.optional = false;
  792. }
  793. return node;
  794. }
  795. isOptionalMemberExpression(node) {
  796. if (node.type === "ChainExpression") {
  797. return node.expression.type === "MemberExpression";
  798. }
  799. return super.isOptionalMemberExpression(node);
  800. }
  801. hasPropertyAsPrivateName(node) {
  802. if (node.type === "ChainExpression") {
  803. node = node.expression;
  804. }
  805. return super.hasPropertyAsPrivateName(node);
  806. }
  807. isObjectProperty(node) {
  808. return node.type === "Property" && node.kind === "init" && !node.method;
  809. }
  810. isObjectMethod(node) {
  811. return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set");
  812. }
  813. finishNodeAt(node, type, endLoc) {
  814. return toESTreeLocation(super.finishNodeAt(node, type, endLoc));
  815. }
  816. resetStartLocation(node, startLoc) {
  817. super.resetStartLocation(node, startLoc);
  818. toESTreeLocation(node);
  819. }
  820. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  821. super.resetEndLocation(node, endLoc);
  822. toESTreeLocation(node);
  823. }
  824. };
  825. class TokContext {
  826. constructor(token, preserveSpace) {
  827. this.token = void 0;
  828. this.preserveSpace = void 0;
  829. this.token = token;
  830. this.preserveSpace = !!preserveSpace;
  831. }
  832. }
  833. const types = {
  834. brace: new TokContext("{"),
  835. j_oTag: new TokContext("<tag"),
  836. j_cTag: new TokContext("</tag"),
  837. j_expr: new TokContext("<tag>...</tag>", true)
  838. };
  839. {
  840. types.template = new TokContext("`", true);
  841. }
  842. const beforeExpr = true;
  843. const startsExpr = true;
  844. const isLoop = true;
  845. const isAssign = true;
  846. const prefix = true;
  847. const postfix = true;
  848. class ExportedTokenType {
  849. constructor(label, conf = {}) {
  850. this.label = void 0;
  851. this.keyword = void 0;
  852. this.beforeExpr = void 0;
  853. this.startsExpr = void 0;
  854. this.rightAssociative = void 0;
  855. this.isLoop = void 0;
  856. this.isAssign = void 0;
  857. this.prefix = void 0;
  858. this.postfix = void 0;
  859. this.binop = void 0;
  860. this.label = label;
  861. this.keyword = conf.keyword;
  862. this.beforeExpr = !!conf.beforeExpr;
  863. this.startsExpr = !!conf.startsExpr;
  864. this.rightAssociative = !!conf.rightAssociative;
  865. this.isLoop = !!conf.isLoop;
  866. this.isAssign = !!conf.isAssign;
  867. this.prefix = !!conf.prefix;
  868. this.postfix = !!conf.postfix;
  869. this.binop = conf.binop != null ? conf.binop : null;
  870. {
  871. this.updateContext = null;
  872. }
  873. }
  874. }
  875. const keywords$1 = new Map();
  876. function createKeyword(name, options = {}) {
  877. options.keyword = name;
  878. const token = createToken(name, options);
  879. keywords$1.set(name, token);
  880. return token;
  881. }
  882. function createBinop(name, binop) {
  883. return createToken(name, {
  884. beforeExpr,
  885. binop
  886. });
  887. }
  888. let tokenTypeCounter = -1;
  889. const tokenTypes = [];
  890. const tokenLabels = [];
  891. const tokenBinops = [];
  892. const tokenBeforeExprs = [];
  893. const tokenStartsExprs = [];
  894. const tokenPrefixes = [];
  895. function createToken(name, options = {}) {
  896. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  897. ++tokenTypeCounter;
  898. tokenLabels.push(name);
  899. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  900. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  901. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  902. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  903. tokenTypes.push(new ExportedTokenType(name, options));
  904. return tokenTypeCounter;
  905. }
  906. function createKeywordLike(name, options = {}) {
  907. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  908. ++tokenTypeCounter;
  909. keywords$1.set(name, tokenTypeCounter);
  910. tokenLabels.push(name);
  911. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  912. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  913. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  914. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  915. tokenTypes.push(new ExportedTokenType("name", options));
  916. return tokenTypeCounter;
  917. }
  918. const tt = {
  919. bracketL: createToken("[", {
  920. beforeExpr,
  921. startsExpr
  922. }),
  923. bracketHashL: createToken("#[", {
  924. beforeExpr,
  925. startsExpr
  926. }),
  927. bracketBarL: createToken("[|", {
  928. beforeExpr,
  929. startsExpr
  930. }),
  931. bracketR: createToken("]"),
  932. bracketBarR: createToken("|]"),
  933. braceL: createToken("{", {
  934. beforeExpr,
  935. startsExpr
  936. }),
  937. braceBarL: createToken("{|", {
  938. beforeExpr,
  939. startsExpr
  940. }),
  941. braceHashL: createToken("#{", {
  942. beforeExpr,
  943. startsExpr
  944. }),
  945. braceR: createToken("}"),
  946. braceBarR: createToken("|}"),
  947. parenL: createToken("(", {
  948. beforeExpr,
  949. startsExpr
  950. }),
  951. parenR: createToken(")"),
  952. comma: createToken(",", {
  953. beforeExpr
  954. }),
  955. semi: createToken(";", {
  956. beforeExpr
  957. }),
  958. colon: createToken(":", {
  959. beforeExpr
  960. }),
  961. doubleColon: createToken("::", {
  962. beforeExpr
  963. }),
  964. dot: createToken("."),
  965. question: createToken("?", {
  966. beforeExpr
  967. }),
  968. questionDot: createToken("?."),
  969. arrow: createToken("=>", {
  970. beforeExpr
  971. }),
  972. template: createToken("template"),
  973. ellipsis: createToken("...", {
  974. beforeExpr
  975. }),
  976. backQuote: createToken("`", {
  977. startsExpr
  978. }),
  979. dollarBraceL: createToken("${", {
  980. beforeExpr,
  981. startsExpr
  982. }),
  983. templateTail: createToken("...`", {
  984. startsExpr
  985. }),
  986. templateNonTail: createToken("...${", {
  987. beforeExpr,
  988. startsExpr
  989. }),
  990. at: createToken("@"),
  991. hash: createToken("#", {
  992. startsExpr
  993. }),
  994. interpreterDirective: createToken("#!..."),
  995. eq: createToken("=", {
  996. beforeExpr,
  997. isAssign
  998. }),
  999. assign: createToken("_=", {
  1000. beforeExpr,
  1001. isAssign
  1002. }),
  1003. slashAssign: createToken("_=", {
  1004. beforeExpr,
  1005. isAssign
  1006. }),
  1007. xorAssign: createToken("_=", {
  1008. beforeExpr,
  1009. isAssign
  1010. }),
  1011. moduloAssign: createToken("_=", {
  1012. beforeExpr,
  1013. isAssign
  1014. }),
  1015. incDec: createToken("++/--", {
  1016. prefix,
  1017. postfix,
  1018. startsExpr
  1019. }),
  1020. bang: createToken("!", {
  1021. beforeExpr,
  1022. prefix,
  1023. startsExpr
  1024. }),
  1025. tilde: createToken("~", {
  1026. beforeExpr,
  1027. prefix,
  1028. startsExpr
  1029. }),
  1030. doubleCaret: createToken("^^", {
  1031. startsExpr
  1032. }),
  1033. doubleAt: createToken("@@", {
  1034. startsExpr
  1035. }),
  1036. pipeline: createBinop("|>", 0),
  1037. nullishCoalescing: createBinop("??", 1),
  1038. logicalOR: createBinop("||", 1),
  1039. logicalAND: createBinop("&&", 2),
  1040. bitwiseOR: createBinop("|", 3),
  1041. bitwiseXOR: createBinop("^", 4),
  1042. bitwiseAND: createBinop("&", 5),
  1043. equality: createBinop("==/!=/===/!==", 6),
  1044. lt: createBinop("</>/<=/>=", 7),
  1045. gt: createBinop("</>/<=/>=", 7),
  1046. relational: createBinop("</>/<=/>=", 7),
  1047. bitShift: createBinop("<</>>/>>>", 8),
  1048. bitShiftL: createBinop("<</>>/>>>", 8),
  1049. bitShiftR: createBinop("<</>>/>>>", 8),
  1050. plusMin: createToken("+/-", {
  1051. beforeExpr,
  1052. binop: 9,
  1053. prefix,
  1054. startsExpr
  1055. }),
  1056. modulo: createToken("%", {
  1057. binop: 10,
  1058. startsExpr
  1059. }),
  1060. star: createToken("*", {
  1061. binop: 10
  1062. }),
  1063. slash: createBinop("/", 10),
  1064. exponent: createToken("**", {
  1065. beforeExpr,
  1066. binop: 11,
  1067. rightAssociative: true
  1068. }),
  1069. _in: createKeyword("in", {
  1070. beforeExpr,
  1071. binop: 7
  1072. }),
  1073. _instanceof: createKeyword("instanceof", {
  1074. beforeExpr,
  1075. binop: 7
  1076. }),
  1077. _break: createKeyword("break"),
  1078. _case: createKeyword("case", {
  1079. beforeExpr
  1080. }),
  1081. _catch: createKeyword("catch"),
  1082. _continue: createKeyword("continue"),
  1083. _debugger: createKeyword("debugger"),
  1084. _default: createKeyword("default", {
  1085. beforeExpr
  1086. }),
  1087. _else: createKeyword("else", {
  1088. beforeExpr
  1089. }),
  1090. _finally: createKeyword("finally"),
  1091. _function: createKeyword("function", {
  1092. startsExpr
  1093. }),
  1094. _if: createKeyword("if"),
  1095. _return: createKeyword("return", {
  1096. beforeExpr
  1097. }),
  1098. _switch: createKeyword("switch"),
  1099. _throw: createKeyword("throw", {
  1100. beforeExpr,
  1101. prefix,
  1102. startsExpr
  1103. }),
  1104. _try: createKeyword("try"),
  1105. _var: createKeyword("var"),
  1106. _const: createKeyword("const"),
  1107. _with: createKeyword("with"),
  1108. _new: createKeyword("new", {
  1109. beforeExpr,
  1110. startsExpr
  1111. }),
  1112. _this: createKeyword("this", {
  1113. startsExpr
  1114. }),
  1115. _super: createKeyword("super", {
  1116. startsExpr
  1117. }),
  1118. _class: createKeyword("class", {
  1119. startsExpr
  1120. }),
  1121. _extends: createKeyword("extends", {
  1122. beforeExpr
  1123. }),
  1124. _export: createKeyword("export"),
  1125. _import: createKeyword("import", {
  1126. startsExpr
  1127. }),
  1128. _null: createKeyword("null", {
  1129. startsExpr
  1130. }),
  1131. _true: createKeyword("true", {
  1132. startsExpr
  1133. }),
  1134. _false: createKeyword("false", {
  1135. startsExpr
  1136. }),
  1137. _typeof: createKeyword("typeof", {
  1138. beforeExpr,
  1139. prefix,
  1140. startsExpr
  1141. }),
  1142. _void: createKeyword("void", {
  1143. beforeExpr,
  1144. prefix,
  1145. startsExpr
  1146. }),
  1147. _delete: createKeyword("delete", {
  1148. beforeExpr,
  1149. prefix,
  1150. startsExpr
  1151. }),
  1152. _do: createKeyword("do", {
  1153. isLoop,
  1154. beforeExpr
  1155. }),
  1156. _for: createKeyword("for", {
  1157. isLoop
  1158. }),
  1159. _while: createKeyword("while", {
  1160. isLoop
  1161. }),
  1162. _as: createKeywordLike("as", {
  1163. startsExpr
  1164. }),
  1165. _assert: createKeywordLike("assert", {
  1166. startsExpr
  1167. }),
  1168. _async: createKeywordLike("async", {
  1169. startsExpr
  1170. }),
  1171. _await: createKeywordLike("await", {
  1172. startsExpr
  1173. }),
  1174. _defer: createKeywordLike("defer", {
  1175. startsExpr
  1176. }),
  1177. _from: createKeywordLike("from", {
  1178. startsExpr
  1179. }),
  1180. _get: createKeywordLike("get", {
  1181. startsExpr
  1182. }),
  1183. _let: createKeywordLike("let", {
  1184. startsExpr
  1185. }),
  1186. _meta: createKeywordLike("meta", {
  1187. startsExpr
  1188. }),
  1189. _of: createKeywordLike("of", {
  1190. startsExpr
  1191. }),
  1192. _sent: createKeywordLike("sent", {
  1193. startsExpr
  1194. }),
  1195. _set: createKeywordLike("set", {
  1196. startsExpr
  1197. }),
  1198. _source: createKeywordLike("source", {
  1199. startsExpr
  1200. }),
  1201. _static: createKeywordLike("static", {
  1202. startsExpr
  1203. }),
  1204. _using: createKeywordLike("using", {
  1205. startsExpr
  1206. }),
  1207. _yield: createKeywordLike("yield", {
  1208. startsExpr
  1209. }),
  1210. _asserts: createKeywordLike("asserts", {
  1211. startsExpr
  1212. }),
  1213. _checks: createKeywordLike("checks", {
  1214. startsExpr
  1215. }),
  1216. _exports: createKeywordLike("exports", {
  1217. startsExpr
  1218. }),
  1219. _global: createKeywordLike("global", {
  1220. startsExpr
  1221. }),
  1222. _implements: createKeywordLike("implements", {
  1223. startsExpr
  1224. }),
  1225. _intrinsic: createKeywordLike("intrinsic", {
  1226. startsExpr
  1227. }),
  1228. _infer: createKeywordLike("infer", {
  1229. startsExpr
  1230. }),
  1231. _is: createKeywordLike("is", {
  1232. startsExpr
  1233. }),
  1234. _mixins: createKeywordLike("mixins", {
  1235. startsExpr
  1236. }),
  1237. _proto: createKeywordLike("proto", {
  1238. startsExpr
  1239. }),
  1240. _require: createKeywordLike("require", {
  1241. startsExpr
  1242. }),
  1243. _satisfies: createKeywordLike("satisfies", {
  1244. startsExpr
  1245. }),
  1246. _keyof: createKeywordLike("keyof", {
  1247. startsExpr
  1248. }),
  1249. _readonly: createKeywordLike("readonly", {
  1250. startsExpr
  1251. }),
  1252. _unique: createKeywordLike("unique", {
  1253. startsExpr
  1254. }),
  1255. _abstract: createKeywordLike("abstract", {
  1256. startsExpr
  1257. }),
  1258. _declare: createKeywordLike("declare", {
  1259. startsExpr
  1260. }),
  1261. _enum: createKeywordLike("enum", {
  1262. startsExpr
  1263. }),
  1264. _module: createKeywordLike("module", {
  1265. startsExpr
  1266. }),
  1267. _namespace: createKeywordLike("namespace", {
  1268. startsExpr
  1269. }),
  1270. _interface: createKeywordLike("interface", {
  1271. startsExpr
  1272. }),
  1273. _type: createKeywordLike("type", {
  1274. startsExpr
  1275. }),
  1276. _opaque: createKeywordLike("opaque", {
  1277. startsExpr
  1278. }),
  1279. name: createToken("name", {
  1280. startsExpr
  1281. }),
  1282. placeholder: createToken("%%", {
  1283. startsExpr: true
  1284. }),
  1285. string: createToken("string", {
  1286. startsExpr
  1287. }),
  1288. num: createToken("num", {
  1289. startsExpr
  1290. }),
  1291. bigint: createToken("bigint", {
  1292. startsExpr
  1293. }),
  1294. decimal: createToken("decimal", {
  1295. startsExpr
  1296. }),
  1297. regexp: createToken("regexp", {
  1298. startsExpr
  1299. }),
  1300. privateName: createToken("#name", {
  1301. startsExpr
  1302. }),
  1303. eof: createToken("eof"),
  1304. jsxName: createToken("jsxName"),
  1305. jsxText: createToken("jsxText", {
  1306. beforeExpr: true
  1307. }),
  1308. jsxTagStart: createToken("jsxTagStart", {
  1309. startsExpr: true
  1310. }),
  1311. jsxTagEnd: createToken("jsxTagEnd")
  1312. };
  1313. function tokenIsIdentifier(token) {
  1314. return token >= 93 && token <= 133;
  1315. }
  1316. function tokenKeywordOrIdentifierIsKeyword(token) {
  1317. return token <= 92;
  1318. }
  1319. function tokenIsKeywordOrIdentifier(token) {
  1320. return token >= 58 && token <= 133;
  1321. }
  1322. function tokenIsLiteralPropertyName(token) {
  1323. return token >= 58 && token <= 137;
  1324. }
  1325. function tokenComesBeforeExpression(token) {
  1326. return tokenBeforeExprs[token];
  1327. }
  1328. function tokenCanStartExpression(token) {
  1329. return tokenStartsExprs[token];
  1330. }
  1331. function tokenIsAssignment(token) {
  1332. return token >= 29 && token <= 33;
  1333. }
  1334. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  1335. return token >= 129 && token <= 131;
  1336. }
  1337. function tokenIsLoop(token) {
  1338. return token >= 90 && token <= 92;
  1339. }
  1340. function tokenIsKeyword(token) {
  1341. return token >= 58 && token <= 92;
  1342. }
  1343. function tokenIsOperator(token) {
  1344. return token >= 39 && token <= 59;
  1345. }
  1346. function tokenIsPostfix(token) {
  1347. return token === 34;
  1348. }
  1349. function tokenIsPrefix(token) {
  1350. return tokenPrefixes[token];
  1351. }
  1352. function tokenIsTSTypeOperator(token) {
  1353. return token >= 121 && token <= 123;
  1354. }
  1355. function tokenIsTSDeclarationStart(token) {
  1356. return token >= 124 && token <= 130;
  1357. }
  1358. function tokenLabelName(token) {
  1359. return tokenLabels[token];
  1360. }
  1361. function tokenOperatorPrecedence(token) {
  1362. return tokenBinops[token];
  1363. }
  1364. function tokenIsRightAssociative(token) {
  1365. return token === 57;
  1366. }
  1367. function tokenIsTemplate(token) {
  1368. return token >= 24 && token <= 25;
  1369. }
  1370. function getExportedToken(token) {
  1371. return tokenTypes[token];
  1372. }
  1373. {
  1374. tokenTypes[8].updateContext = context => {
  1375. context.pop();
  1376. };
  1377. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  1378. context.push(types.brace);
  1379. };
  1380. tokenTypes[22].updateContext = context => {
  1381. if (context[context.length - 1] === types.template) {
  1382. context.pop();
  1383. } else {
  1384. context.push(types.template);
  1385. }
  1386. };
  1387. tokenTypes[143].updateContext = context => {
  1388. context.push(types.j_expr, types.j_oTag);
  1389. };
  1390. }
  1391. 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
  1392. 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";
  1393. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1394. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1395. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1396. 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];
  1397. 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];
  1398. function isInAstralSet(code, set) {
  1399. let pos = 0x10000;
  1400. for (let i = 0, length = set.length; i < length; i += 2) {
  1401. pos += set[i];
  1402. if (pos > code) return false;
  1403. pos += set[i + 1];
  1404. if (pos >= code) return true;
  1405. }
  1406. return false;
  1407. }
  1408. function isIdentifierStart(code) {
  1409. if (code < 65) return code === 36;
  1410. if (code <= 90) return true;
  1411. if (code < 97) return code === 95;
  1412. if (code <= 122) return true;
  1413. if (code <= 0xffff) {
  1414. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1415. }
  1416. return isInAstralSet(code, astralIdentifierStartCodes);
  1417. }
  1418. function isIdentifierChar(code) {
  1419. if (code < 48) return code === 36;
  1420. if (code < 58) return true;
  1421. if (code < 65) return false;
  1422. if (code <= 90) return true;
  1423. if (code < 97) return code === 95;
  1424. if (code <= 122) return true;
  1425. if (code <= 0xffff) {
  1426. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1427. }
  1428. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1429. }
  1430. const reservedWords = {
  1431. 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"],
  1432. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1433. strictBind: ["eval", "arguments"]
  1434. };
  1435. const keywords = new Set(reservedWords.keyword);
  1436. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1437. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1438. function isReservedWord(word, inModule) {
  1439. return inModule && word === "await" || word === "enum";
  1440. }
  1441. function isStrictReservedWord(word, inModule) {
  1442. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1443. }
  1444. function isStrictBindOnlyReservedWord(word) {
  1445. return reservedWordsStrictBindSet.has(word);
  1446. }
  1447. function isStrictBindReservedWord(word, inModule) {
  1448. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1449. }
  1450. function isKeyword(word) {
  1451. return keywords.has(word);
  1452. }
  1453. function isIteratorStart(current, next, next2) {
  1454. return current === 64 && next === 64 && isIdentifierStart(next2);
  1455. }
  1456. 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"]);
  1457. function canBeReservedWord(word) {
  1458. return reservedWordLikeSet.has(word);
  1459. }
  1460. class Scope {
  1461. constructor(flags) {
  1462. this.flags = 0;
  1463. this.names = new Map();
  1464. this.firstLexicalName = "";
  1465. this.flags = flags;
  1466. }
  1467. }
  1468. class ScopeHandler {
  1469. constructor(parser, inModule) {
  1470. this.parser = void 0;
  1471. this.scopeStack = [];
  1472. this.inModule = void 0;
  1473. this.undefinedExports = new Map();
  1474. this.parser = parser;
  1475. this.inModule = inModule;
  1476. }
  1477. get inTopLevel() {
  1478. return (this.currentScope().flags & 1) > 0;
  1479. }
  1480. get inFunction() {
  1481. return (this.currentVarScopeFlags() & 2) > 0;
  1482. }
  1483. get allowSuper() {
  1484. return (this.currentThisScopeFlags() & 16) > 0;
  1485. }
  1486. get allowDirectSuper() {
  1487. return (this.currentThisScopeFlags() & 32) > 0;
  1488. }
  1489. get inClass() {
  1490. return (this.currentThisScopeFlags() & 64) > 0;
  1491. }
  1492. get inClassAndNotInNonArrowFunction() {
  1493. const flags = this.currentThisScopeFlags();
  1494. return (flags & 64) > 0 && (flags & 2) === 0;
  1495. }
  1496. get inStaticBlock() {
  1497. for (let i = this.scopeStack.length - 1;; i--) {
  1498. const {
  1499. flags
  1500. } = this.scopeStack[i];
  1501. if (flags & 128) {
  1502. return true;
  1503. }
  1504. if (flags & (387 | 64)) {
  1505. return false;
  1506. }
  1507. }
  1508. }
  1509. get inNonArrowFunction() {
  1510. return (this.currentThisScopeFlags() & 2) > 0;
  1511. }
  1512. get treatFunctionsAsVar() {
  1513. return this.treatFunctionsAsVarInScope(this.currentScope());
  1514. }
  1515. createScope(flags) {
  1516. return new Scope(flags);
  1517. }
  1518. enter(flags) {
  1519. this.scopeStack.push(this.createScope(flags));
  1520. }
  1521. exit() {
  1522. const scope = this.scopeStack.pop();
  1523. return scope.flags;
  1524. }
  1525. treatFunctionsAsVarInScope(scope) {
  1526. return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1);
  1527. }
  1528. declareName(name, bindingType, loc) {
  1529. let scope = this.currentScope();
  1530. if (bindingType & 8 || bindingType & 16) {
  1531. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1532. let type = scope.names.get(name) || 0;
  1533. if (bindingType & 16) {
  1534. type = type | 4;
  1535. } else {
  1536. if (!scope.firstLexicalName) {
  1537. scope.firstLexicalName = name;
  1538. }
  1539. type = type | 2;
  1540. }
  1541. scope.names.set(name, type);
  1542. if (bindingType & 8) {
  1543. this.maybeExportDefined(scope, name);
  1544. }
  1545. } else if (bindingType & 4) {
  1546. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  1547. scope = this.scopeStack[i];
  1548. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1549. scope.names.set(name, (scope.names.get(name) || 0) | 1);
  1550. this.maybeExportDefined(scope, name);
  1551. if (scope.flags & 387) break;
  1552. }
  1553. }
  1554. if (this.parser.inModule && scope.flags & 1) {
  1555. this.undefinedExports.delete(name);
  1556. }
  1557. }
  1558. maybeExportDefined(scope, name) {
  1559. if (this.parser.inModule && scope.flags & 1) {
  1560. this.undefinedExports.delete(name);
  1561. }
  1562. }
  1563. checkRedeclarationInScope(scope, name, bindingType, loc) {
  1564. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  1565. this.parser.raise(Errors.VarRedeclaration, loc, {
  1566. identifierName: name
  1567. });
  1568. }
  1569. }
  1570. isRedeclaredInScope(scope, name, bindingType) {
  1571. if (!(bindingType & 1)) return false;
  1572. if (bindingType & 8) {
  1573. return scope.names.has(name);
  1574. }
  1575. const type = scope.names.get(name);
  1576. if (bindingType & 16) {
  1577. return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0;
  1578. }
  1579. return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0;
  1580. }
  1581. checkLocalExport(id) {
  1582. const {
  1583. name
  1584. } = id;
  1585. const topLevelScope = this.scopeStack[0];
  1586. if (!topLevelScope.names.has(name)) {
  1587. this.undefinedExports.set(name, id.loc.start);
  1588. }
  1589. }
  1590. currentScope() {
  1591. return this.scopeStack[this.scopeStack.length - 1];
  1592. }
  1593. currentVarScopeFlags() {
  1594. for (let i = this.scopeStack.length - 1;; i--) {
  1595. const {
  1596. flags
  1597. } = this.scopeStack[i];
  1598. if (flags & 387) {
  1599. return flags;
  1600. }
  1601. }
  1602. }
  1603. currentThisScopeFlags() {
  1604. for (let i = this.scopeStack.length - 1;; i--) {
  1605. const {
  1606. flags
  1607. } = this.scopeStack[i];
  1608. if (flags & (387 | 64) && !(flags & 4)) {
  1609. return flags;
  1610. }
  1611. }
  1612. }
  1613. }
  1614. class FlowScope extends Scope {
  1615. constructor(...args) {
  1616. super(...args);
  1617. this.declareFunctions = new Set();
  1618. }
  1619. }
  1620. class FlowScopeHandler extends ScopeHandler {
  1621. createScope(flags) {
  1622. return new FlowScope(flags);
  1623. }
  1624. declareName(name, bindingType, loc) {
  1625. const scope = this.currentScope();
  1626. if (bindingType & 2048) {
  1627. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1628. this.maybeExportDefined(scope, name);
  1629. scope.declareFunctions.add(name);
  1630. return;
  1631. }
  1632. super.declareName(name, bindingType, loc);
  1633. }
  1634. isRedeclaredInScope(scope, name, bindingType) {
  1635. if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
  1636. if (bindingType & 2048 && !scope.declareFunctions.has(name)) {
  1637. const type = scope.names.get(name);
  1638. return (type & 4) > 0 || (type & 2) > 0;
  1639. }
  1640. return false;
  1641. }
  1642. checkLocalExport(id) {
  1643. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  1644. super.checkLocalExport(id);
  1645. }
  1646. }
  1647. }
  1648. class BaseParser {
  1649. constructor() {
  1650. this.sawUnambiguousESM = false;
  1651. this.ambiguousScriptDifferentAst = false;
  1652. }
  1653. sourceToOffsetPos(sourcePos) {
  1654. return sourcePos + this.startIndex;
  1655. }
  1656. offsetToSourcePos(offsetPos) {
  1657. return offsetPos - this.startIndex;
  1658. }
  1659. hasPlugin(pluginConfig) {
  1660. if (typeof pluginConfig === "string") {
  1661. return this.plugins.has(pluginConfig);
  1662. } else {
  1663. const [pluginName, pluginOptions] = pluginConfig;
  1664. if (!this.hasPlugin(pluginName)) {
  1665. return false;
  1666. }
  1667. const actualOptions = this.plugins.get(pluginName);
  1668. for (const key of Object.keys(pluginOptions)) {
  1669. if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) {
  1670. return false;
  1671. }
  1672. }
  1673. return true;
  1674. }
  1675. }
  1676. getPluginOption(plugin, name) {
  1677. var _this$plugins$get;
  1678. return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name];
  1679. }
  1680. }
  1681. function setTrailingComments(node, comments) {
  1682. if (node.trailingComments === undefined) {
  1683. node.trailingComments = comments;
  1684. } else {
  1685. node.trailingComments.unshift(...comments);
  1686. }
  1687. }
  1688. function setLeadingComments(node, comments) {
  1689. if (node.leadingComments === undefined) {
  1690. node.leadingComments = comments;
  1691. } else {
  1692. node.leadingComments.unshift(...comments);
  1693. }
  1694. }
  1695. function setInnerComments(node, comments) {
  1696. if (node.innerComments === undefined) {
  1697. node.innerComments = comments;
  1698. } else {
  1699. node.innerComments.unshift(...comments);
  1700. }
  1701. }
  1702. function adjustInnerComments(node, elements, commentWS) {
  1703. let lastElement = null;
  1704. let i = elements.length;
  1705. while (lastElement === null && i > 0) {
  1706. lastElement = elements[--i];
  1707. }
  1708. if (lastElement === null || lastElement.start > commentWS.start) {
  1709. setInnerComments(node, commentWS.comments);
  1710. } else {
  1711. setTrailingComments(lastElement, commentWS.comments);
  1712. }
  1713. }
  1714. class CommentsParser extends BaseParser {
  1715. addComment(comment) {
  1716. if (this.filename) comment.loc.filename = this.filename;
  1717. const {
  1718. commentsLen
  1719. } = this.state;
  1720. if (this.comments.length !== commentsLen) {
  1721. this.comments.length = commentsLen;
  1722. }
  1723. this.comments.push(comment);
  1724. this.state.commentsLen++;
  1725. }
  1726. processComment(node) {
  1727. const {
  1728. commentStack
  1729. } = this.state;
  1730. const commentStackLength = commentStack.length;
  1731. if (commentStackLength === 0) return;
  1732. let i = commentStackLength - 1;
  1733. const lastCommentWS = commentStack[i];
  1734. if (lastCommentWS.start === node.end) {
  1735. lastCommentWS.leadingNode = node;
  1736. i--;
  1737. }
  1738. const {
  1739. start: nodeStart
  1740. } = node;
  1741. for (; i >= 0; i--) {
  1742. const commentWS = commentStack[i];
  1743. const commentEnd = commentWS.end;
  1744. if (commentEnd > nodeStart) {
  1745. commentWS.containingNode = node;
  1746. this.finalizeComment(commentWS);
  1747. commentStack.splice(i, 1);
  1748. } else {
  1749. if (commentEnd === nodeStart) {
  1750. commentWS.trailingNode = node;
  1751. }
  1752. break;
  1753. }
  1754. }
  1755. }
  1756. finalizeComment(commentWS) {
  1757. const {
  1758. comments
  1759. } = commentWS;
  1760. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  1761. if (commentWS.leadingNode !== null) {
  1762. setTrailingComments(commentWS.leadingNode, comments);
  1763. }
  1764. if (commentWS.trailingNode !== null) {
  1765. setLeadingComments(commentWS.trailingNode, comments);
  1766. }
  1767. } else {
  1768. const {
  1769. containingNode: node,
  1770. start: commentStart
  1771. } = commentWS;
  1772. if (this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) === 44) {
  1773. switch (node.type) {
  1774. case "ObjectExpression":
  1775. case "ObjectPattern":
  1776. case "RecordExpression":
  1777. adjustInnerComments(node, node.properties, commentWS);
  1778. break;
  1779. case "CallExpression":
  1780. case "OptionalCallExpression":
  1781. adjustInnerComments(node, node.arguments, commentWS);
  1782. break;
  1783. case "FunctionDeclaration":
  1784. case "FunctionExpression":
  1785. case "ArrowFunctionExpression":
  1786. case "ObjectMethod":
  1787. case "ClassMethod":
  1788. case "ClassPrivateMethod":
  1789. adjustInnerComments(node, node.params, commentWS);
  1790. break;
  1791. case "ArrayExpression":
  1792. case "ArrayPattern":
  1793. case "TupleExpression":
  1794. adjustInnerComments(node, node.elements, commentWS);
  1795. break;
  1796. case "ExportNamedDeclaration":
  1797. case "ImportDeclaration":
  1798. adjustInnerComments(node, node.specifiers, commentWS);
  1799. break;
  1800. case "TSEnumDeclaration":
  1801. {
  1802. adjustInnerComments(node, node.members, commentWS);
  1803. }
  1804. break;
  1805. case "TSEnumBody":
  1806. adjustInnerComments(node, node.members, commentWS);
  1807. break;
  1808. default:
  1809. {
  1810. setInnerComments(node, comments);
  1811. }
  1812. }
  1813. } else {
  1814. setInnerComments(node, comments);
  1815. }
  1816. }
  1817. }
  1818. finalizeRemainingComments() {
  1819. const {
  1820. commentStack
  1821. } = this.state;
  1822. for (let i = commentStack.length - 1; i >= 0; i--) {
  1823. this.finalizeComment(commentStack[i]);
  1824. }
  1825. this.state.commentStack = [];
  1826. }
  1827. resetPreviousNodeTrailingComments(node) {
  1828. const {
  1829. commentStack
  1830. } = this.state;
  1831. const {
  1832. length
  1833. } = commentStack;
  1834. if (length === 0) return;
  1835. const commentWS = commentStack[length - 1];
  1836. if (commentWS.leadingNode === node) {
  1837. commentWS.leadingNode = null;
  1838. }
  1839. }
  1840. resetPreviousIdentifierLeadingComments(node) {
  1841. const {
  1842. commentStack
  1843. } = this.state;
  1844. const {
  1845. length
  1846. } = commentStack;
  1847. if (length === 0) return;
  1848. if (commentStack[length - 1].trailingNode === node) {
  1849. commentStack[length - 1].trailingNode = null;
  1850. } else if (length >= 2 && commentStack[length - 2].trailingNode === node) {
  1851. commentStack[length - 2].trailingNode = null;
  1852. }
  1853. }
  1854. takeSurroundingComments(node, start, end) {
  1855. const {
  1856. commentStack
  1857. } = this.state;
  1858. const commentStackLength = commentStack.length;
  1859. if (commentStackLength === 0) return;
  1860. let i = commentStackLength - 1;
  1861. for (; i >= 0; i--) {
  1862. const commentWS = commentStack[i];
  1863. const commentEnd = commentWS.end;
  1864. const commentStart = commentWS.start;
  1865. if (commentStart === end) {
  1866. commentWS.leadingNode = node;
  1867. } else if (commentEnd === start) {
  1868. commentWS.trailingNode = node;
  1869. } else if (commentEnd < start) {
  1870. break;
  1871. }
  1872. }
  1873. }
  1874. }
  1875. const lineBreak = /\r\n|[\r\n\u2028\u2029]/;
  1876. const lineBreakG = new RegExp(lineBreak.source, "g");
  1877. function isNewLine(code) {
  1878. switch (code) {
  1879. case 10:
  1880. case 13:
  1881. case 8232:
  1882. case 8233:
  1883. return true;
  1884. default:
  1885. return false;
  1886. }
  1887. }
  1888. function hasNewLine(input, start, end) {
  1889. for (let i = start; i < end; i++) {
  1890. if (isNewLine(input.charCodeAt(i))) {
  1891. return true;
  1892. }
  1893. }
  1894. return false;
  1895. }
  1896. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  1897. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;
  1898. function isWhitespace(code) {
  1899. switch (code) {
  1900. case 0x0009:
  1901. case 0x000b:
  1902. case 0x000c:
  1903. case 32:
  1904. case 160:
  1905. case 5760:
  1906. case 0x2000:
  1907. case 0x2001:
  1908. case 0x2002:
  1909. case 0x2003:
  1910. case 0x2004:
  1911. case 0x2005:
  1912. case 0x2006:
  1913. case 0x2007:
  1914. case 0x2008:
  1915. case 0x2009:
  1916. case 0x200a:
  1917. case 0x202f:
  1918. case 0x205f:
  1919. case 0x3000:
  1920. case 0xfeff:
  1921. return true;
  1922. default:
  1923. return false;
  1924. }
  1925. }
  1926. class State {
  1927. constructor() {
  1928. this.flags = 1024;
  1929. this.startIndex = void 0;
  1930. this.curLine = void 0;
  1931. this.lineStart = void 0;
  1932. this.startLoc = void 0;
  1933. this.endLoc = void 0;
  1934. this.errors = [];
  1935. this.potentialArrowAt = -1;
  1936. this.noArrowAt = [];
  1937. this.noArrowParamsConversionAt = [];
  1938. this.topicContext = {
  1939. maxNumOfResolvableTopics: 0,
  1940. maxTopicIndex: null
  1941. };
  1942. this.labels = [];
  1943. this.commentsLen = 0;
  1944. this.commentStack = [];
  1945. this.pos = 0;
  1946. this.type = 140;
  1947. this.value = null;
  1948. this.start = 0;
  1949. this.end = 0;
  1950. this.lastTokEndLoc = null;
  1951. this.lastTokStartLoc = null;
  1952. this.context = [types.brace];
  1953. this.firstInvalidTemplateEscapePos = null;
  1954. this.strictErrors = new Map();
  1955. this.tokensLength = 0;
  1956. }
  1957. get strict() {
  1958. return (this.flags & 1) > 0;
  1959. }
  1960. set strict(v) {
  1961. if (v) this.flags |= 1;else this.flags &= -2;
  1962. }
  1963. init({
  1964. strictMode,
  1965. sourceType,
  1966. startIndex,
  1967. startLine,
  1968. startColumn
  1969. }) {
  1970. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  1971. this.startIndex = startIndex;
  1972. this.curLine = startLine;
  1973. this.lineStart = -startColumn;
  1974. this.startLoc = this.endLoc = new Position(startLine, startColumn, startIndex);
  1975. }
  1976. get maybeInArrowParameters() {
  1977. return (this.flags & 2) > 0;
  1978. }
  1979. set maybeInArrowParameters(v) {
  1980. if (v) this.flags |= 2;else this.flags &= -3;
  1981. }
  1982. get inType() {
  1983. return (this.flags & 4) > 0;
  1984. }
  1985. set inType(v) {
  1986. if (v) this.flags |= 4;else this.flags &= -5;
  1987. }
  1988. get noAnonFunctionType() {
  1989. return (this.flags & 8) > 0;
  1990. }
  1991. set noAnonFunctionType(v) {
  1992. if (v) this.flags |= 8;else this.flags &= -9;
  1993. }
  1994. get hasFlowComment() {
  1995. return (this.flags & 16) > 0;
  1996. }
  1997. set hasFlowComment(v) {
  1998. if (v) this.flags |= 16;else this.flags &= -17;
  1999. }
  2000. get isAmbientContext() {
  2001. return (this.flags & 32) > 0;
  2002. }
  2003. set isAmbientContext(v) {
  2004. if (v) this.flags |= 32;else this.flags &= -33;
  2005. }
  2006. get inAbstractClass() {
  2007. return (this.flags & 64) > 0;
  2008. }
  2009. set inAbstractClass(v) {
  2010. if (v) this.flags |= 64;else this.flags &= -65;
  2011. }
  2012. get inDisallowConditionalTypesContext() {
  2013. return (this.flags & 128) > 0;
  2014. }
  2015. set inDisallowConditionalTypesContext(v) {
  2016. if (v) this.flags |= 128;else this.flags &= -129;
  2017. }
  2018. get soloAwait() {
  2019. return (this.flags & 256) > 0;
  2020. }
  2021. set soloAwait(v) {
  2022. if (v) this.flags |= 256;else this.flags &= -257;
  2023. }
  2024. get inFSharpPipelineDirectBody() {
  2025. return (this.flags & 512) > 0;
  2026. }
  2027. set inFSharpPipelineDirectBody(v) {
  2028. if (v) this.flags |= 512;else this.flags &= -513;
  2029. }
  2030. get canStartJSXElement() {
  2031. return (this.flags & 1024) > 0;
  2032. }
  2033. set canStartJSXElement(v) {
  2034. if (v) this.flags |= 1024;else this.flags &= -1025;
  2035. }
  2036. get containsEsc() {
  2037. return (this.flags & 2048) > 0;
  2038. }
  2039. set containsEsc(v) {
  2040. if (v) this.flags |= 2048;else this.flags &= -2049;
  2041. }
  2042. get hasTopLevelAwait() {
  2043. return (this.flags & 4096) > 0;
  2044. }
  2045. set hasTopLevelAwait(v) {
  2046. if (v) this.flags |= 4096;else this.flags &= -4097;
  2047. }
  2048. curPosition() {
  2049. return new Position(this.curLine, this.pos - this.lineStart, this.pos + this.startIndex);
  2050. }
  2051. clone() {
  2052. const state = new State();
  2053. state.flags = this.flags;
  2054. state.startIndex = this.startIndex;
  2055. state.curLine = this.curLine;
  2056. state.lineStart = this.lineStart;
  2057. state.startLoc = this.startLoc;
  2058. state.endLoc = this.endLoc;
  2059. state.errors = this.errors.slice();
  2060. state.potentialArrowAt = this.potentialArrowAt;
  2061. state.noArrowAt = this.noArrowAt.slice();
  2062. state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();
  2063. state.topicContext = this.topicContext;
  2064. state.labels = this.labels.slice();
  2065. state.commentsLen = this.commentsLen;
  2066. state.commentStack = this.commentStack.slice();
  2067. state.pos = this.pos;
  2068. state.type = this.type;
  2069. state.value = this.value;
  2070. state.start = this.start;
  2071. state.end = this.end;
  2072. state.lastTokEndLoc = this.lastTokEndLoc;
  2073. state.lastTokStartLoc = this.lastTokStartLoc;
  2074. state.context = this.context.slice();
  2075. state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;
  2076. state.strictErrors = this.strictErrors;
  2077. state.tokensLength = this.tokensLength;
  2078. return state;
  2079. }
  2080. }
  2081. var _isDigit = function isDigit(code) {
  2082. return code >= 48 && code <= 57;
  2083. };
  2084. const forbiddenNumericSeparatorSiblings = {
  2085. decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]),
  2086. hex: new Set([46, 88, 95, 120])
  2087. };
  2088. const isAllowedNumericSeparatorSibling = {
  2089. bin: ch => ch === 48 || ch === 49,
  2090. oct: ch => ch >= 48 && ch <= 55,
  2091. dec: ch => ch >= 48 && ch <= 57,
  2092. hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102
  2093. };
  2094. function readStringContents(type, input, pos, lineStart, curLine, errors) {
  2095. const initialPos = pos;
  2096. const initialLineStart = lineStart;
  2097. const initialCurLine = curLine;
  2098. let out = "";
  2099. let firstInvalidLoc = null;
  2100. let chunkStart = pos;
  2101. const {
  2102. length
  2103. } = input;
  2104. for (;;) {
  2105. if (pos >= length) {
  2106. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  2107. out += input.slice(chunkStart, pos);
  2108. break;
  2109. }
  2110. const ch = input.charCodeAt(pos);
  2111. if (isStringEnd(type, ch, input, pos)) {
  2112. out += input.slice(chunkStart, pos);
  2113. break;
  2114. }
  2115. if (ch === 92) {
  2116. out += input.slice(chunkStart, pos);
  2117. const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors);
  2118. if (res.ch === null && !firstInvalidLoc) {
  2119. firstInvalidLoc = {
  2120. pos,
  2121. lineStart,
  2122. curLine
  2123. };
  2124. } else {
  2125. out += res.ch;
  2126. }
  2127. ({
  2128. pos,
  2129. lineStart,
  2130. curLine
  2131. } = res);
  2132. chunkStart = pos;
  2133. } else if (ch === 8232 || ch === 8233) {
  2134. ++pos;
  2135. ++curLine;
  2136. lineStart = pos;
  2137. } else if (ch === 10 || ch === 13) {
  2138. if (type === "template") {
  2139. out += input.slice(chunkStart, pos) + "\n";
  2140. ++pos;
  2141. if (ch === 13 && input.charCodeAt(pos) === 10) {
  2142. ++pos;
  2143. }
  2144. ++curLine;
  2145. chunkStart = lineStart = pos;
  2146. } else {
  2147. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  2148. }
  2149. } else {
  2150. ++pos;
  2151. }
  2152. }
  2153. return {
  2154. pos,
  2155. str: out,
  2156. firstInvalidLoc,
  2157. lineStart,
  2158. curLine,
  2159. containsInvalid: !!firstInvalidLoc
  2160. };
  2161. }
  2162. function isStringEnd(type, ch, input, pos) {
  2163. if (type === "template") {
  2164. return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123;
  2165. }
  2166. return ch === (type === "double" ? 34 : 39);
  2167. }
  2168. function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
  2169. const throwOnInvalid = !inTemplate;
  2170. pos++;
  2171. const res = ch => ({
  2172. pos,
  2173. ch,
  2174. lineStart,
  2175. curLine
  2176. });
  2177. const ch = input.charCodeAt(pos++);
  2178. switch (ch) {
  2179. case 110:
  2180. return res("\n");
  2181. case 114:
  2182. return res("\r");
  2183. case 120:
  2184. {
  2185. let code;
  2186. ({
  2187. code,
  2188. pos
  2189. } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors));
  2190. return res(code === null ? null : String.fromCharCode(code));
  2191. }
  2192. case 117:
  2193. {
  2194. let code;
  2195. ({
  2196. code,
  2197. pos
  2198. } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors));
  2199. return res(code === null ? null : String.fromCodePoint(code));
  2200. }
  2201. case 116:
  2202. return res("\t");
  2203. case 98:
  2204. return res("\b");
  2205. case 118:
  2206. return res("\u000b");
  2207. case 102:
  2208. return res("\f");
  2209. case 13:
  2210. if (input.charCodeAt(pos) === 10) {
  2211. ++pos;
  2212. }
  2213. case 10:
  2214. lineStart = pos;
  2215. ++curLine;
  2216. case 8232:
  2217. case 8233:
  2218. return res("");
  2219. case 56:
  2220. case 57:
  2221. if (inTemplate) {
  2222. return res(null);
  2223. } else {
  2224. errors.strictNumericEscape(pos - 1, lineStart, curLine);
  2225. }
  2226. default:
  2227. if (ch >= 48 && ch <= 55) {
  2228. const startPos = pos - 1;
  2229. const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));
  2230. let octalStr = match[0];
  2231. let octal = parseInt(octalStr, 8);
  2232. if (octal > 255) {
  2233. octalStr = octalStr.slice(0, -1);
  2234. octal = parseInt(octalStr, 8);
  2235. }
  2236. pos += octalStr.length - 1;
  2237. const next = input.charCodeAt(pos);
  2238. if (octalStr !== "0" || next === 56 || next === 57) {
  2239. if (inTemplate) {
  2240. return res(null);
  2241. } else {
  2242. errors.strictNumericEscape(startPos, lineStart, curLine);
  2243. }
  2244. }
  2245. return res(String.fromCharCode(octal));
  2246. }
  2247. return res(String.fromCharCode(ch));
  2248. }
  2249. }
  2250. function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) {
  2251. const initialPos = pos;
  2252. let n;
  2253. ({
  2254. n,
  2255. pos
  2256. } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid));
  2257. if (n === null) {
  2258. if (throwOnInvalid) {
  2259. errors.invalidEscapeSequence(initialPos, lineStart, curLine);
  2260. } else {
  2261. pos = initialPos - 1;
  2262. }
  2263. }
  2264. return {
  2265. code: n,
  2266. pos
  2267. };
  2268. }
  2269. function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) {
  2270. const start = pos;
  2271. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  2272. const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin;
  2273. let invalid = false;
  2274. let total = 0;
  2275. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  2276. const code = input.charCodeAt(pos);
  2277. let val;
  2278. if (code === 95 && allowNumSeparator !== "bail") {
  2279. const prev = input.charCodeAt(pos - 1);
  2280. const next = input.charCodeAt(pos + 1);
  2281. if (!allowNumSeparator) {
  2282. if (bailOnError) return {
  2283. n: null,
  2284. pos
  2285. };
  2286. errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
  2287. } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
  2288. if (bailOnError) return {
  2289. n: null,
  2290. pos
  2291. };
  2292. errors.unexpectedNumericSeparator(pos, lineStart, curLine);
  2293. }
  2294. ++pos;
  2295. continue;
  2296. }
  2297. if (code >= 97) {
  2298. val = code - 97 + 10;
  2299. } else if (code >= 65) {
  2300. val = code - 65 + 10;
  2301. } else if (_isDigit(code)) {
  2302. val = code - 48;
  2303. } else {
  2304. val = Infinity;
  2305. }
  2306. if (val >= radix) {
  2307. if (val <= 9 && bailOnError) {
  2308. return {
  2309. n: null,
  2310. pos
  2311. };
  2312. } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) {
  2313. val = 0;
  2314. } else if (forceLen) {
  2315. val = 0;
  2316. invalid = true;
  2317. } else {
  2318. break;
  2319. }
  2320. }
  2321. ++pos;
  2322. total = total * radix + val;
  2323. }
  2324. if (pos === start || len != null && pos - start !== len || invalid) {
  2325. return {
  2326. n: null,
  2327. pos
  2328. };
  2329. }
  2330. return {
  2331. n: total,
  2332. pos
  2333. };
  2334. }
  2335. function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) {
  2336. const ch = input.charCodeAt(pos);
  2337. let code;
  2338. if (ch === 123) {
  2339. ++pos;
  2340. ({
  2341. code,
  2342. pos
  2343. } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors));
  2344. ++pos;
  2345. if (code !== null && code > 0x10ffff) {
  2346. if (throwOnInvalid) {
  2347. errors.invalidCodePoint(pos, lineStart, curLine);
  2348. } else {
  2349. return {
  2350. code: null,
  2351. pos
  2352. };
  2353. }
  2354. }
  2355. } else {
  2356. ({
  2357. code,
  2358. pos
  2359. } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors));
  2360. }
  2361. return {
  2362. code,
  2363. pos
  2364. };
  2365. }
  2366. function buildPosition(pos, lineStart, curLine) {
  2367. return new Position(curLine, pos - lineStart, pos);
  2368. }
  2369. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]);
  2370. class Token {
  2371. constructor(state) {
  2372. const startIndex = state.startIndex || 0;
  2373. this.type = state.type;
  2374. this.value = state.value;
  2375. this.start = startIndex + state.start;
  2376. this.end = startIndex + state.end;
  2377. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  2378. }
  2379. }
  2380. class Tokenizer extends CommentsParser {
  2381. constructor(options, input) {
  2382. super();
  2383. this.isLookahead = void 0;
  2384. this.tokens = [];
  2385. this.errorHandlers_readInt = {
  2386. invalidDigit: (pos, lineStart, curLine, radix) => {
  2387. if (!(this.optionFlags & 2048)) return false;
  2388. this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), {
  2389. radix
  2390. });
  2391. return true;
  2392. },
  2393. numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),
  2394. unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator)
  2395. };
  2396. this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, {
  2397. invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),
  2398. invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint)
  2399. });
  2400. this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, {
  2401. strictNumericEscape: (pos, lineStart, curLine) => {
  2402. this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine));
  2403. },
  2404. unterminated: (pos, lineStart, curLine) => {
  2405. throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine));
  2406. }
  2407. });
  2408. this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, {
  2409. strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),
  2410. unterminated: (pos, lineStart, curLine) => {
  2411. throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine));
  2412. }
  2413. });
  2414. this.state = new State();
  2415. this.state.init(options);
  2416. this.input = input;
  2417. this.length = input.length;
  2418. this.comments = [];
  2419. this.isLookahead = false;
  2420. }
  2421. pushToken(token) {
  2422. this.tokens.length = this.state.tokensLength;
  2423. this.tokens.push(token);
  2424. ++this.state.tokensLength;
  2425. }
  2426. next() {
  2427. this.checkKeywordEscapes();
  2428. if (this.optionFlags & 256) {
  2429. this.pushToken(new Token(this.state));
  2430. }
  2431. this.state.lastTokEndLoc = this.state.endLoc;
  2432. this.state.lastTokStartLoc = this.state.startLoc;
  2433. this.nextToken();
  2434. }
  2435. eat(type) {
  2436. if (this.match(type)) {
  2437. this.next();
  2438. return true;
  2439. } else {
  2440. return false;
  2441. }
  2442. }
  2443. match(type) {
  2444. return this.state.type === type;
  2445. }
  2446. createLookaheadState(state) {
  2447. return {
  2448. pos: state.pos,
  2449. value: null,
  2450. type: state.type,
  2451. start: state.start,
  2452. end: state.end,
  2453. context: [this.curContext()],
  2454. inType: state.inType,
  2455. startLoc: state.startLoc,
  2456. lastTokEndLoc: state.lastTokEndLoc,
  2457. curLine: state.curLine,
  2458. lineStart: state.lineStart,
  2459. curPosition: state.curPosition
  2460. };
  2461. }
  2462. lookahead() {
  2463. const old = this.state;
  2464. this.state = this.createLookaheadState(old);
  2465. this.isLookahead = true;
  2466. this.nextToken();
  2467. this.isLookahead = false;
  2468. const curr = this.state;
  2469. this.state = old;
  2470. return curr;
  2471. }
  2472. nextTokenStart() {
  2473. return this.nextTokenStartSince(this.state.pos);
  2474. }
  2475. nextTokenStartSince(pos) {
  2476. skipWhiteSpace.lastIndex = pos;
  2477. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  2478. }
  2479. lookaheadCharCode() {
  2480. return this.input.charCodeAt(this.nextTokenStart());
  2481. }
  2482. nextTokenInLineStart() {
  2483. return this.nextTokenInLineStartSince(this.state.pos);
  2484. }
  2485. nextTokenInLineStartSince(pos) {
  2486. skipWhiteSpaceInLine.lastIndex = pos;
  2487. return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos;
  2488. }
  2489. lookaheadInLineCharCode() {
  2490. return this.input.charCodeAt(this.nextTokenInLineStart());
  2491. }
  2492. codePointAtPos(pos) {
  2493. let cp = this.input.charCodeAt(pos);
  2494. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  2495. const trail = this.input.charCodeAt(pos);
  2496. if ((trail & 0xfc00) === 0xdc00) {
  2497. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  2498. }
  2499. }
  2500. return cp;
  2501. }
  2502. setStrict(strict) {
  2503. this.state.strict = strict;
  2504. if (strict) {
  2505. this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at));
  2506. this.state.strictErrors.clear();
  2507. }
  2508. }
  2509. curContext() {
  2510. return this.state.context[this.state.context.length - 1];
  2511. }
  2512. nextToken() {
  2513. this.skipSpace();
  2514. this.state.start = this.state.pos;
  2515. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  2516. if (this.state.pos >= this.length) {
  2517. this.finishToken(140);
  2518. return;
  2519. }
  2520. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  2521. }
  2522. skipBlockComment(commentEnd) {
  2523. let startLoc;
  2524. if (!this.isLookahead) startLoc = this.state.curPosition();
  2525. const start = this.state.pos;
  2526. const end = this.input.indexOf(commentEnd, start + 2);
  2527. if (end === -1) {
  2528. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  2529. }
  2530. this.state.pos = end + commentEnd.length;
  2531. lineBreakG.lastIndex = start + 2;
  2532. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  2533. ++this.state.curLine;
  2534. this.state.lineStart = lineBreakG.lastIndex;
  2535. }
  2536. if (this.isLookahead) return;
  2537. const comment = {
  2538. type: "CommentBlock",
  2539. value: this.input.slice(start + 2, end),
  2540. start: this.sourceToOffsetPos(start),
  2541. end: this.sourceToOffsetPos(end + commentEnd.length),
  2542. loc: new SourceLocation(startLoc, this.state.curPosition())
  2543. };
  2544. if (this.optionFlags & 256) this.pushToken(comment);
  2545. return comment;
  2546. }
  2547. skipLineComment(startSkip) {
  2548. const start = this.state.pos;
  2549. let startLoc;
  2550. if (!this.isLookahead) startLoc = this.state.curPosition();
  2551. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  2552. if (this.state.pos < this.length) {
  2553. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2554. ch = this.input.charCodeAt(this.state.pos);
  2555. }
  2556. }
  2557. if (this.isLookahead) return;
  2558. const end = this.state.pos;
  2559. const value = this.input.slice(start + startSkip, end);
  2560. const comment = {
  2561. type: "CommentLine",
  2562. value,
  2563. start: this.sourceToOffsetPos(start),
  2564. end: this.sourceToOffsetPos(end),
  2565. loc: new SourceLocation(startLoc, this.state.curPosition())
  2566. };
  2567. if (this.optionFlags & 256) this.pushToken(comment);
  2568. return comment;
  2569. }
  2570. skipSpace() {
  2571. const spaceStart = this.state.pos;
  2572. const comments = this.optionFlags & 4096 ? [] : null;
  2573. loop: while (this.state.pos < this.length) {
  2574. const ch = this.input.charCodeAt(this.state.pos);
  2575. switch (ch) {
  2576. case 32:
  2577. case 160:
  2578. case 9:
  2579. ++this.state.pos;
  2580. break;
  2581. case 13:
  2582. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  2583. ++this.state.pos;
  2584. }
  2585. case 10:
  2586. case 8232:
  2587. case 8233:
  2588. ++this.state.pos;
  2589. ++this.state.curLine;
  2590. this.state.lineStart = this.state.pos;
  2591. break;
  2592. case 47:
  2593. switch (this.input.charCodeAt(this.state.pos + 1)) {
  2594. case 42:
  2595. {
  2596. const comment = this.skipBlockComment("*/");
  2597. if (comment !== undefined) {
  2598. this.addComment(comment);
  2599. comments == null || comments.push(comment);
  2600. }
  2601. break;
  2602. }
  2603. case 47:
  2604. {
  2605. const comment = this.skipLineComment(2);
  2606. if (comment !== undefined) {
  2607. this.addComment(comment);
  2608. comments == null || comments.push(comment);
  2609. }
  2610. break;
  2611. }
  2612. default:
  2613. break loop;
  2614. }
  2615. break;
  2616. default:
  2617. if (isWhitespace(ch)) {
  2618. ++this.state.pos;
  2619. } else if (ch === 45 && !this.inModule && this.optionFlags & 8192) {
  2620. const pos = this.state.pos;
  2621. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  2622. const comment = this.skipLineComment(3);
  2623. if (comment !== undefined) {
  2624. this.addComment(comment);
  2625. comments == null || comments.push(comment);
  2626. }
  2627. } else {
  2628. break loop;
  2629. }
  2630. } else if (ch === 60 && !this.inModule && this.optionFlags & 8192) {
  2631. const pos = this.state.pos;
  2632. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  2633. const comment = this.skipLineComment(4);
  2634. if (comment !== undefined) {
  2635. this.addComment(comment);
  2636. comments == null || comments.push(comment);
  2637. }
  2638. } else {
  2639. break loop;
  2640. }
  2641. } else {
  2642. break loop;
  2643. }
  2644. }
  2645. }
  2646. if ((comments == null ? void 0 : comments.length) > 0) {
  2647. const end = this.state.pos;
  2648. const commentWhitespace = {
  2649. start: this.sourceToOffsetPos(spaceStart),
  2650. end: this.sourceToOffsetPos(end),
  2651. comments,
  2652. leadingNode: null,
  2653. trailingNode: null,
  2654. containingNode: null
  2655. };
  2656. this.state.commentStack.push(commentWhitespace);
  2657. }
  2658. }
  2659. finishToken(type, val) {
  2660. this.state.end = this.state.pos;
  2661. this.state.endLoc = this.state.curPosition();
  2662. const prevType = this.state.type;
  2663. this.state.type = type;
  2664. this.state.value = val;
  2665. if (!this.isLookahead) {
  2666. this.updateContext(prevType);
  2667. }
  2668. }
  2669. replaceToken(type) {
  2670. this.state.type = type;
  2671. this.updateContext();
  2672. }
  2673. readToken_numberSign() {
  2674. if (this.state.pos === 0 && this.readToken_interpreter()) {
  2675. return;
  2676. }
  2677. const nextPos = this.state.pos + 1;
  2678. const next = this.codePointAtPos(nextPos);
  2679. if (next >= 48 && next <= 57) {
  2680. throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition());
  2681. }
  2682. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  2683. this.expectPlugin("recordAndTuple");
  2684. if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") {
  2685. throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition());
  2686. }
  2687. this.state.pos += 2;
  2688. if (next === 123) {
  2689. this.finishToken(7);
  2690. } else {
  2691. this.finishToken(1);
  2692. }
  2693. } else if (isIdentifierStart(next)) {
  2694. ++this.state.pos;
  2695. this.finishToken(139, this.readWord1(next));
  2696. } else if (next === 92) {
  2697. ++this.state.pos;
  2698. this.finishToken(139, this.readWord1());
  2699. } else {
  2700. this.finishOp(27, 1);
  2701. }
  2702. }
  2703. readToken_dot() {
  2704. const next = this.input.charCodeAt(this.state.pos + 1);
  2705. if (next >= 48 && next <= 57) {
  2706. this.readNumber(true);
  2707. return;
  2708. }
  2709. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  2710. this.state.pos += 3;
  2711. this.finishToken(21);
  2712. } else {
  2713. ++this.state.pos;
  2714. this.finishToken(16);
  2715. }
  2716. }
  2717. readToken_slash() {
  2718. const next = this.input.charCodeAt(this.state.pos + 1);
  2719. if (next === 61) {
  2720. this.finishOp(31, 2);
  2721. } else {
  2722. this.finishOp(56, 1);
  2723. }
  2724. }
  2725. readToken_interpreter() {
  2726. if (this.state.pos !== 0 || this.length < 2) return false;
  2727. let ch = this.input.charCodeAt(this.state.pos + 1);
  2728. if (ch !== 33) return false;
  2729. const start = this.state.pos;
  2730. this.state.pos += 1;
  2731. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2732. ch = this.input.charCodeAt(this.state.pos);
  2733. }
  2734. const value = this.input.slice(start + 2, this.state.pos);
  2735. this.finishToken(28, value);
  2736. return true;
  2737. }
  2738. readToken_mult_modulo(code) {
  2739. let type = code === 42 ? 55 : 54;
  2740. let width = 1;
  2741. let next = this.input.charCodeAt(this.state.pos + 1);
  2742. if (code === 42 && next === 42) {
  2743. width++;
  2744. next = this.input.charCodeAt(this.state.pos + 2);
  2745. type = 57;
  2746. }
  2747. if (next === 61 && !this.state.inType) {
  2748. width++;
  2749. type = code === 37 ? 33 : 30;
  2750. }
  2751. this.finishOp(type, width);
  2752. }
  2753. readToken_pipe_amp(code) {
  2754. const next = this.input.charCodeAt(this.state.pos + 1);
  2755. if (next === code) {
  2756. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  2757. this.finishOp(30, 3);
  2758. } else {
  2759. this.finishOp(code === 124 ? 41 : 42, 2);
  2760. }
  2761. return;
  2762. }
  2763. if (code === 124) {
  2764. if (next === 62) {
  2765. this.finishOp(39, 2);
  2766. return;
  2767. }
  2768. if (this.hasPlugin("recordAndTuple") && next === 125) {
  2769. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2770. throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  2771. }
  2772. this.state.pos += 2;
  2773. this.finishToken(9);
  2774. return;
  2775. }
  2776. if (this.hasPlugin("recordAndTuple") && next === 93) {
  2777. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2778. throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  2779. }
  2780. this.state.pos += 2;
  2781. this.finishToken(4);
  2782. return;
  2783. }
  2784. }
  2785. if (next === 61) {
  2786. this.finishOp(30, 2);
  2787. return;
  2788. }
  2789. this.finishOp(code === 124 ? 43 : 45, 1);
  2790. }
  2791. readToken_caret() {
  2792. const next = this.input.charCodeAt(this.state.pos + 1);
  2793. if (next === 61 && !this.state.inType) {
  2794. this.finishOp(32, 2);
  2795. } else if (next === 94 && this.hasPlugin(["pipelineOperator", {
  2796. proposal: "hack",
  2797. topicToken: "^^"
  2798. }])) {
  2799. this.finishOp(37, 2);
  2800. const lookaheadCh = this.input.codePointAt(this.state.pos);
  2801. if (lookaheadCh === 94) {
  2802. this.unexpected();
  2803. }
  2804. } else {
  2805. this.finishOp(44, 1);
  2806. }
  2807. }
  2808. readToken_atSign() {
  2809. const next = this.input.charCodeAt(this.state.pos + 1);
  2810. if (next === 64 && this.hasPlugin(["pipelineOperator", {
  2811. proposal: "hack",
  2812. topicToken: "@@"
  2813. }])) {
  2814. this.finishOp(38, 2);
  2815. } else {
  2816. this.finishOp(26, 1);
  2817. }
  2818. }
  2819. readToken_plus_min(code) {
  2820. const next = this.input.charCodeAt(this.state.pos + 1);
  2821. if (next === code) {
  2822. this.finishOp(34, 2);
  2823. return;
  2824. }
  2825. if (next === 61) {
  2826. this.finishOp(30, 2);
  2827. } else {
  2828. this.finishOp(53, 1);
  2829. }
  2830. }
  2831. readToken_lt() {
  2832. const {
  2833. pos
  2834. } = this.state;
  2835. const next = this.input.charCodeAt(pos + 1);
  2836. if (next === 60) {
  2837. if (this.input.charCodeAt(pos + 2) === 61) {
  2838. this.finishOp(30, 3);
  2839. return;
  2840. }
  2841. this.finishOp(51, 2);
  2842. return;
  2843. }
  2844. if (next === 61) {
  2845. this.finishOp(49, 2);
  2846. return;
  2847. }
  2848. this.finishOp(47, 1);
  2849. }
  2850. readToken_gt() {
  2851. const {
  2852. pos
  2853. } = this.state;
  2854. const next = this.input.charCodeAt(pos + 1);
  2855. if (next === 62) {
  2856. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  2857. if (this.input.charCodeAt(pos + size) === 61) {
  2858. this.finishOp(30, size + 1);
  2859. return;
  2860. }
  2861. this.finishOp(52, size);
  2862. return;
  2863. }
  2864. if (next === 61) {
  2865. this.finishOp(49, 2);
  2866. return;
  2867. }
  2868. this.finishOp(48, 1);
  2869. }
  2870. readToken_eq_excl(code) {
  2871. const next = this.input.charCodeAt(this.state.pos + 1);
  2872. if (next === 61) {
  2873. this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  2874. return;
  2875. }
  2876. if (code === 61 && next === 62) {
  2877. this.state.pos += 2;
  2878. this.finishToken(19);
  2879. return;
  2880. }
  2881. this.finishOp(code === 61 ? 29 : 35, 1);
  2882. }
  2883. readToken_question() {
  2884. const next = this.input.charCodeAt(this.state.pos + 1);
  2885. const next2 = this.input.charCodeAt(this.state.pos + 2);
  2886. if (next === 63) {
  2887. if (next2 === 61) {
  2888. this.finishOp(30, 3);
  2889. } else {
  2890. this.finishOp(40, 2);
  2891. }
  2892. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  2893. this.state.pos += 2;
  2894. this.finishToken(18);
  2895. } else {
  2896. ++this.state.pos;
  2897. this.finishToken(17);
  2898. }
  2899. }
  2900. getTokenFromCode(code) {
  2901. switch (code) {
  2902. case 46:
  2903. this.readToken_dot();
  2904. return;
  2905. case 40:
  2906. ++this.state.pos;
  2907. this.finishToken(10);
  2908. return;
  2909. case 41:
  2910. ++this.state.pos;
  2911. this.finishToken(11);
  2912. return;
  2913. case 59:
  2914. ++this.state.pos;
  2915. this.finishToken(13);
  2916. return;
  2917. case 44:
  2918. ++this.state.pos;
  2919. this.finishToken(12);
  2920. return;
  2921. case 91:
  2922. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2923. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2924. throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  2925. }
  2926. this.state.pos += 2;
  2927. this.finishToken(2);
  2928. } else {
  2929. ++this.state.pos;
  2930. this.finishToken(0);
  2931. }
  2932. return;
  2933. case 93:
  2934. ++this.state.pos;
  2935. this.finishToken(3);
  2936. return;
  2937. case 123:
  2938. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2939. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2940. throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  2941. }
  2942. this.state.pos += 2;
  2943. this.finishToken(6);
  2944. } else {
  2945. ++this.state.pos;
  2946. this.finishToken(5);
  2947. }
  2948. return;
  2949. case 125:
  2950. ++this.state.pos;
  2951. this.finishToken(8);
  2952. return;
  2953. case 58:
  2954. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  2955. this.finishOp(15, 2);
  2956. } else {
  2957. ++this.state.pos;
  2958. this.finishToken(14);
  2959. }
  2960. return;
  2961. case 63:
  2962. this.readToken_question();
  2963. return;
  2964. case 96:
  2965. this.readTemplateToken();
  2966. return;
  2967. case 48:
  2968. {
  2969. const next = this.input.charCodeAt(this.state.pos + 1);
  2970. if (next === 120 || next === 88) {
  2971. this.readRadixNumber(16);
  2972. return;
  2973. }
  2974. if (next === 111 || next === 79) {
  2975. this.readRadixNumber(8);
  2976. return;
  2977. }
  2978. if (next === 98 || next === 66) {
  2979. this.readRadixNumber(2);
  2980. return;
  2981. }
  2982. }
  2983. case 49:
  2984. case 50:
  2985. case 51:
  2986. case 52:
  2987. case 53:
  2988. case 54:
  2989. case 55:
  2990. case 56:
  2991. case 57:
  2992. this.readNumber(false);
  2993. return;
  2994. case 34:
  2995. case 39:
  2996. this.readString(code);
  2997. return;
  2998. case 47:
  2999. this.readToken_slash();
  3000. return;
  3001. case 37:
  3002. case 42:
  3003. this.readToken_mult_modulo(code);
  3004. return;
  3005. case 124:
  3006. case 38:
  3007. this.readToken_pipe_amp(code);
  3008. return;
  3009. case 94:
  3010. this.readToken_caret();
  3011. return;
  3012. case 43:
  3013. case 45:
  3014. this.readToken_plus_min(code);
  3015. return;
  3016. case 60:
  3017. this.readToken_lt();
  3018. return;
  3019. case 62:
  3020. this.readToken_gt();
  3021. return;
  3022. case 61:
  3023. case 33:
  3024. this.readToken_eq_excl(code);
  3025. return;
  3026. case 126:
  3027. this.finishOp(36, 1);
  3028. return;
  3029. case 64:
  3030. this.readToken_atSign();
  3031. return;
  3032. case 35:
  3033. this.readToken_numberSign();
  3034. return;
  3035. case 92:
  3036. this.readWord();
  3037. return;
  3038. default:
  3039. if (isIdentifierStart(code)) {
  3040. this.readWord(code);
  3041. return;
  3042. }
  3043. }
  3044. throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), {
  3045. unexpected: String.fromCodePoint(code)
  3046. });
  3047. }
  3048. finishOp(type, size) {
  3049. const str = this.input.slice(this.state.pos, this.state.pos + size);
  3050. this.state.pos += size;
  3051. this.finishToken(type, str);
  3052. }
  3053. readRegexp() {
  3054. const startLoc = this.state.startLoc;
  3055. const start = this.state.start + 1;
  3056. let escaped, inClass;
  3057. let {
  3058. pos
  3059. } = this.state;
  3060. for (;; ++pos) {
  3061. if (pos >= this.length) {
  3062. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  3063. }
  3064. const ch = this.input.charCodeAt(pos);
  3065. if (isNewLine(ch)) {
  3066. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  3067. }
  3068. if (escaped) {
  3069. escaped = false;
  3070. } else {
  3071. if (ch === 91) {
  3072. inClass = true;
  3073. } else if (ch === 93 && inClass) {
  3074. inClass = false;
  3075. } else if (ch === 47 && !inClass) {
  3076. break;
  3077. }
  3078. escaped = ch === 92;
  3079. }
  3080. }
  3081. const content = this.input.slice(start, pos);
  3082. ++pos;
  3083. let mods = "";
  3084. const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start);
  3085. while (pos < this.length) {
  3086. const cp = this.codePointAtPos(pos);
  3087. const char = String.fromCharCode(cp);
  3088. if (VALID_REGEX_FLAGS.has(cp)) {
  3089. if (cp === 118) {
  3090. if (mods.includes("u")) {
  3091. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  3092. }
  3093. } else if (cp === 117) {
  3094. if (mods.includes("v")) {
  3095. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  3096. }
  3097. }
  3098. if (mods.includes(char)) {
  3099. this.raise(Errors.DuplicateRegExpFlags, nextPos());
  3100. }
  3101. } else if (isIdentifierChar(cp) || cp === 92) {
  3102. this.raise(Errors.MalformedRegExpFlags, nextPos());
  3103. } else {
  3104. break;
  3105. }
  3106. ++pos;
  3107. mods += char;
  3108. }
  3109. this.state.pos = pos;
  3110. this.finishToken(138, {
  3111. pattern: content,
  3112. flags: mods
  3113. });
  3114. }
  3115. readInt(radix, len, forceLen = false, allowNumSeparator = true) {
  3116. const {
  3117. n,
  3118. pos
  3119. } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false);
  3120. this.state.pos = pos;
  3121. return n;
  3122. }
  3123. readRadixNumber(radix) {
  3124. const start = this.state.pos;
  3125. const startLoc = this.state.curPosition();
  3126. let isBigInt = false;
  3127. this.state.pos += 2;
  3128. const val = this.readInt(radix);
  3129. if (val == null) {
  3130. this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), {
  3131. radix
  3132. });
  3133. }
  3134. const next = this.input.charCodeAt(this.state.pos);
  3135. if (next === 110) {
  3136. ++this.state.pos;
  3137. isBigInt = true;
  3138. } else if (next === 109) {
  3139. throw this.raise(Errors.InvalidDecimal, startLoc);
  3140. }
  3141. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3142. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  3143. }
  3144. if (isBigInt) {
  3145. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  3146. this.finishToken(136, str);
  3147. return;
  3148. }
  3149. this.finishToken(135, val);
  3150. }
  3151. readNumber(startsWithDot) {
  3152. const start = this.state.pos;
  3153. const startLoc = this.state.curPosition();
  3154. let isFloat = false;
  3155. let isBigInt = false;
  3156. let hasExponent = false;
  3157. let isOctal = false;
  3158. if (!startsWithDot && this.readInt(10) === null) {
  3159. this.raise(Errors.InvalidNumber, this.state.curPosition());
  3160. }
  3161. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  3162. if (hasLeadingZero) {
  3163. const integer = this.input.slice(start, this.state.pos);
  3164. this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc);
  3165. if (!this.state.strict) {
  3166. const underscorePos = integer.indexOf("_");
  3167. if (underscorePos > 0) {
  3168. this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos));
  3169. }
  3170. }
  3171. isOctal = hasLeadingZero && !/[89]/.test(integer);
  3172. }
  3173. let next = this.input.charCodeAt(this.state.pos);
  3174. if (next === 46 && !isOctal) {
  3175. ++this.state.pos;
  3176. this.readInt(10);
  3177. isFloat = true;
  3178. next = this.input.charCodeAt(this.state.pos);
  3179. }
  3180. if ((next === 69 || next === 101) && !isOctal) {
  3181. next = this.input.charCodeAt(++this.state.pos);
  3182. if (next === 43 || next === 45) {
  3183. ++this.state.pos;
  3184. }
  3185. if (this.readInt(10) === null) {
  3186. this.raise(Errors.InvalidOrMissingExponent, startLoc);
  3187. }
  3188. isFloat = true;
  3189. hasExponent = true;
  3190. next = this.input.charCodeAt(this.state.pos);
  3191. }
  3192. if (next === 110) {
  3193. if (isFloat || hasLeadingZero) {
  3194. this.raise(Errors.InvalidBigIntLiteral, startLoc);
  3195. }
  3196. ++this.state.pos;
  3197. isBigInt = true;
  3198. }
  3199. if (next === 109) {
  3200. this.expectPlugin("decimal", this.state.curPosition());
  3201. if (hasExponent || hasLeadingZero) {
  3202. this.raise(Errors.InvalidDecimal, startLoc);
  3203. }
  3204. ++this.state.pos;
  3205. var isDecimal = true;
  3206. }
  3207. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3208. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  3209. }
  3210. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  3211. if (isBigInt) {
  3212. this.finishToken(136, str);
  3213. return;
  3214. }
  3215. if (isDecimal) {
  3216. this.finishToken(137, str);
  3217. return;
  3218. }
  3219. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  3220. this.finishToken(135, val);
  3221. }
  3222. readCodePoint(throwOnInvalid) {
  3223. const {
  3224. code,
  3225. pos
  3226. } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint);
  3227. this.state.pos = pos;
  3228. return code;
  3229. }
  3230. readString(quote) {
  3231. const {
  3232. str,
  3233. pos,
  3234. curLine,
  3235. lineStart
  3236. } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string);
  3237. this.state.pos = pos + 1;
  3238. this.state.lineStart = lineStart;
  3239. this.state.curLine = curLine;
  3240. this.finishToken(134, str);
  3241. }
  3242. readTemplateContinuation() {
  3243. if (!this.match(8)) {
  3244. this.unexpected(null, 8);
  3245. }
  3246. this.state.pos--;
  3247. this.readTemplateToken();
  3248. }
  3249. readTemplateToken() {
  3250. const opening = this.input[this.state.pos];
  3251. const {
  3252. str,
  3253. firstInvalidLoc,
  3254. pos,
  3255. curLine,
  3256. lineStart
  3257. } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template);
  3258. this.state.pos = pos + 1;
  3259. this.state.lineStart = lineStart;
  3260. this.state.curLine = curLine;
  3261. if (firstInvalidLoc) {
  3262. this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, this.sourceToOffsetPos(firstInvalidLoc.pos));
  3263. }
  3264. if (this.input.codePointAt(pos) === 96) {
  3265. this.finishToken(24, firstInvalidLoc ? null : opening + str + "`");
  3266. } else {
  3267. this.state.pos++;
  3268. this.finishToken(25, firstInvalidLoc ? null : opening + str + "${");
  3269. }
  3270. }
  3271. recordStrictModeErrors(toParseError, at) {
  3272. const index = at.index;
  3273. if (this.state.strict && !this.state.strictErrors.has(index)) {
  3274. this.raise(toParseError, at);
  3275. } else {
  3276. this.state.strictErrors.set(index, [toParseError, at]);
  3277. }
  3278. }
  3279. readWord1(firstCode) {
  3280. this.state.containsEsc = false;
  3281. let word = "";
  3282. const start = this.state.pos;
  3283. let chunkStart = this.state.pos;
  3284. if (firstCode !== undefined) {
  3285. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  3286. }
  3287. while (this.state.pos < this.length) {
  3288. const ch = this.codePointAtPos(this.state.pos);
  3289. if (isIdentifierChar(ch)) {
  3290. this.state.pos += ch <= 0xffff ? 1 : 2;
  3291. } else if (ch === 92) {
  3292. this.state.containsEsc = true;
  3293. word += this.input.slice(chunkStart, this.state.pos);
  3294. const escStart = this.state.curPosition();
  3295. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  3296. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  3297. this.raise(Errors.MissingUnicodeEscape, this.state.curPosition());
  3298. chunkStart = this.state.pos - 1;
  3299. continue;
  3300. }
  3301. ++this.state.pos;
  3302. const esc = this.readCodePoint(true);
  3303. if (esc !== null) {
  3304. if (!identifierCheck(esc)) {
  3305. this.raise(Errors.EscapedCharNotAnIdentifier, escStart);
  3306. }
  3307. word += String.fromCodePoint(esc);
  3308. }
  3309. chunkStart = this.state.pos;
  3310. } else {
  3311. break;
  3312. }
  3313. }
  3314. return word + this.input.slice(chunkStart, this.state.pos);
  3315. }
  3316. readWord(firstCode) {
  3317. const word = this.readWord1(firstCode);
  3318. const type = keywords$1.get(word);
  3319. if (type !== undefined) {
  3320. this.finishToken(type, tokenLabelName(type));
  3321. } else {
  3322. this.finishToken(132, word);
  3323. }
  3324. }
  3325. checkKeywordEscapes() {
  3326. const {
  3327. type
  3328. } = this.state;
  3329. if (tokenIsKeyword(type) && this.state.containsEsc) {
  3330. this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, {
  3331. reservedWord: tokenLabelName(type)
  3332. });
  3333. }
  3334. }
  3335. raise(toParseError, at, details = {}) {
  3336. const loc = at instanceof Position ? at : at.loc.start;
  3337. const error = toParseError(loc, details);
  3338. if (!(this.optionFlags & 2048)) throw error;
  3339. if (!this.isLookahead) this.state.errors.push(error);
  3340. return error;
  3341. }
  3342. raiseOverwrite(toParseError, at, details = {}) {
  3343. const loc = at instanceof Position ? at : at.loc.start;
  3344. const pos = loc.index;
  3345. const errors = this.state.errors;
  3346. for (let i = errors.length - 1; i >= 0; i--) {
  3347. const error = errors[i];
  3348. if (error.loc.index === pos) {
  3349. return errors[i] = toParseError(loc, details);
  3350. }
  3351. if (error.loc.index < pos) break;
  3352. }
  3353. return this.raise(toParseError, at, details);
  3354. }
  3355. updateContext(prevType) {}
  3356. unexpected(loc, type) {
  3357. throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, {
  3358. expected: type ? tokenLabelName(type) : null
  3359. });
  3360. }
  3361. expectPlugin(pluginName, loc) {
  3362. if (this.hasPlugin(pluginName)) {
  3363. return true;
  3364. }
  3365. throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, {
  3366. missingPlugin: [pluginName]
  3367. });
  3368. }
  3369. expectOnePlugin(pluginNames) {
  3370. if (!pluginNames.some(name => this.hasPlugin(name))) {
  3371. throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, {
  3372. missingPlugin: pluginNames
  3373. });
  3374. }
  3375. }
  3376. errorBuilder(error) {
  3377. return (pos, lineStart, curLine) => {
  3378. this.raise(error, buildPosition(pos, lineStart, curLine));
  3379. };
  3380. }
  3381. }
  3382. class ClassScope {
  3383. constructor() {
  3384. this.privateNames = new Set();
  3385. this.loneAccessors = new Map();
  3386. this.undefinedPrivateNames = new Map();
  3387. }
  3388. }
  3389. class ClassScopeHandler {
  3390. constructor(parser) {
  3391. this.parser = void 0;
  3392. this.stack = [];
  3393. this.undefinedPrivateNames = new Map();
  3394. this.parser = parser;
  3395. }
  3396. current() {
  3397. return this.stack[this.stack.length - 1];
  3398. }
  3399. enter() {
  3400. this.stack.push(new ClassScope());
  3401. }
  3402. exit() {
  3403. const oldClassScope = this.stack.pop();
  3404. const current = this.current();
  3405. for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {
  3406. if (current) {
  3407. if (!current.undefinedPrivateNames.has(name)) {
  3408. current.undefinedPrivateNames.set(name, loc);
  3409. }
  3410. } else {
  3411. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  3412. identifierName: name
  3413. });
  3414. }
  3415. }
  3416. }
  3417. declarePrivateName(name, elementType, loc) {
  3418. const {
  3419. privateNames,
  3420. loneAccessors,
  3421. undefinedPrivateNames
  3422. } = this.current();
  3423. let redefined = privateNames.has(name);
  3424. if (elementType & 3) {
  3425. const accessor = redefined && loneAccessors.get(name);
  3426. if (accessor) {
  3427. const oldStatic = accessor & 4;
  3428. const newStatic = elementType & 4;
  3429. const oldKind = accessor & 3;
  3430. const newKind = elementType & 3;
  3431. redefined = oldKind === newKind || oldStatic !== newStatic;
  3432. if (!redefined) loneAccessors.delete(name);
  3433. } else if (!redefined) {
  3434. loneAccessors.set(name, elementType);
  3435. }
  3436. }
  3437. if (redefined) {
  3438. this.parser.raise(Errors.PrivateNameRedeclaration, loc, {
  3439. identifierName: name
  3440. });
  3441. }
  3442. privateNames.add(name);
  3443. undefinedPrivateNames.delete(name);
  3444. }
  3445. usePrivateName(name, loc) {
  3446. let classScope;
  3447. for (classScope of this.stack) {
  3448. if (classScope.privateNames.has(name)) return;
  3449. }
  3450. if (classScope) {
  3451. classScope.undefinedPrivateNames.set(name, loc);
  3452. } else {
  3453. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  3454. identifierName: name
  3455. });
  3456. }
  3457. }
  3458. }
  3459. class ExpressionScope {
  3460. constructor(type = 0) {
  3461. this.type = type;
  3462. }
  3463. canBeArrowParameterDeclaration() {
  3464. return this.type === 2 || this.type === 1;
  3465. }
  3466. isCertainlyParameterDeclaration() {
  3467. return this.type === 3;
  3468. }
  3469. }
  3470. class ArrowHeadParsingScope extends ExpressionScope {
  3471. constructor(type) {
  3472. super(type);
  3473. this.declarationErrors = new Map();
  3474. }
  3475. recordDeclarationError(ParsingErrorClass, at) {
  3476. const index = at.index;
  3477. this.declarationErrors.set(index, [ParsingErrorClass, at]);
  3478. }
  3479. clearDeclarationError(index) {
  3480. this.declarationErrors.delete(index);
  3481. }
  3482. iterateErrors(iterator) {
  3483. this.declarationErrors.forEach(iterator);
  3484. }
  3485. }
  3486. class ExpressionScopeHandler {
  3487. constructor(parser) {
  3488. this.parser = void 0;
  3489. this.stack = [new ExpressionScope()];
  3490. this.parser = parser;
  3491. }
  3492. enter(scope) {
  3493. this.stack.push(scope);
  3494. }
  3495. exit() {
  3496. this.stack.pop();
  3497. }
  3498. recordParameterInitializerError(toParseError, node) {
  3499. const origin = node.loc.start;
  3500. const {
  3501. stack
  3502. } = this;
  3503. let i = stack.length - 1;
  3504. let scope = stack[i];
  3505. while (!scope.isCertainlyParameterDeclaration()) {
  3506. if (scope.canBeArrowParameterDeclaration()) {
  3507. scope.recordDeclarationError(toParseError, origin);
  3508. } else {
  3509. return;
  3510. }
  3511. scope = stack[--i];
  3512. }
  3513. this.parser.raise(toParseError, origin);
  3514. }
  3515. recordArrowParameterBindingError(error, node) {
  3516. const {
  3517. stack
  3518. } = this;
  3519. const scope = stack[stack.length - 1];
  3520. const origin = node.loc.start;
  3521. if (scope.isCertainlyParameterDeclaration()) {
  3522. this.parser.raise(error, origin);
  3523. } else if (scope.canBeArrowParameterDeclaration()) {
  3524. scope.recordDeclarationError(error, origin);
  3525. } else {
  3526. return;
  3527. }
  3528. }
  3529. recordAsyncArrowParametersError(at) {
  3530. const {
  3531. stack
  3532. } = this;
  3533. let i = stack.length - 1;
  3534. let scope = stack[i];
  3535. while (scope.canBeArrowParameterDeclaration()) {
  3536. if (scope.type === 2) {
  3537. scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at);
  3538. }
  3539. scope = stack[--i];
  3540. }
  3541. }
  3542. validateAsPattern() {
  3543. const {
  3544. stack
  3545. } = this;
  3546. const currentScope = stack[stack.length - 1];
  3547. if (!currentScope.canBeArrowParameterDeclaration()) return;
  3548. currentScope.iterateErrors(([toParseError, loc]) => {
  3549. this.parser.raise(toParseError, loc);
  3550. let i = stack.length - 2;
  3551. let scope = stack[i];
  3552. while (scope.canBeArrowParameterDeclaration()) {
  3553. scope.clearDeclarationError(loc.index);
  3554. scope = stack[--i];
  3555. }
  3556. });
  3557. }
  3558. }
  3559. function newParameterDeclarationScope() {
  3560. return new ExpressionScope(3);
  3561. }
  3562. function newArrowHeadScope() {
  3563. return new ArrowHeadParsingScope(1);
  3564. }
  3565. function newAsyncArrowScope() {
  3566. return new ArrowHeadParsingScope(2);
  3567. }
  3568. function newExpressionScope() {
  3569. return new ExpressionScope();
  3570. }
  3571. class ProductionParameterHandler {
  3572. constructor() {
  3573. this.stacks = [];
  3574. }
  3575. enter(flags) {
  3576. this.stacks.push(flags);
  3577. }
  3578. exit() {
  3579. this.stacks.pop();
  3580. }
  3581. currentFlags() {
  3582. return this.stacks[this.stacks.length - 1];
  3583. }
  3584. get hasAwait() {
  3585. return (this.currentFlags() & 2) > 0;
  3586. }
  3587. get hasYield() {
  3588. return (this.currentFlags() & 1) > 0;
  3589. }
  3590. get hasReturn() {
  3591. return (this.currentFlags() & 4) > 0;
  3592. }
  3593. get hasIn() {
  3594. return (this.currentFlags() & 8) > 0;
  3595. }
  3596. }
  3597. function functionFlags(isAsync, isGenerator) {
  3598. return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0);
  3599. }
  3600. class UtilParser extends Tokenizer {
  3601. addExtra(node, key, value, enumerable = true) {
  3602. if (!node) return;
  3603. let {
  3604. extra
  3605. } = node;
  3606. if (extra == null) {
  3607. extra = {};
  3608. node.extra = extra;
  3609. }
  3610. if (enumerable) {
  3611. extra[key] = value;
  3612. } else {
  3613. Object.defineProperty(extra, key, {
  3614. enumerable,
  3615. value
  3616. });
  3617. }
  3618. }
  3619. isContextual(token) {
  3620. return this.state.type === token && !this.state.containsEsc;
  3621. }
  3622. isUnparsedContextual(nameStart, name) {
  3623. const nameEnd = nameStart + name.length;
  3624. if (this.input.slice(nameStart, nameEnd) === name) {
  3625. const nextCh = this.input.charCodeAt(nameEnd);
  3626. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  3627. }
  3628. return false;
  3629. }
  3630. isLookaheadContextual(name) {
  3631. const next = this.nextTokenStart();
  3632. return this.isUnparsedContextual(next, name);
  3633. }
  3634. eatContextual(token) {
  3635. if (this.isContextual(token)) {
  3636. this.next();
  3637. return true;
  3638. }
  3639. return false;
  3640. }
  3641. expectContextual(token, toParseError) {
  3642. if (!this.eatContextual(token)) {
  3643. if (toParseError != null) {
  3644. throw this.raise(toParseError, this.state.startLoc);
  3645. }
  3646. this.unexpected(null, token);
  3647. }
  3648. }
  3649. canInsertSemicolon() {
  3650. return this.match(140) || this.match(8) || this.hasPrecedingLineBreak();
  3651. }
  3652. hasPrecedingLineBreak() {
  3653. return hasNewLine(this.input, this.offsetToSourcePos(this.state.lastTokEndLoc.index), this.state.start);
  3654. }
  3655. hasFollowingLineBreak() {
  3656. return hasNewLine(this.input, this.state.end, this.nextTokenStart());
  3657. }
  3658. isLineTerminator() {
  3659. return this.eat(13) || this.canInsertSemicolon();
  3660. }
  3661. semicolon(allowAsi = true) {
  3662. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  3663. this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc);
  3664. }
  3665. expect(type, loc) {
  3666. if (!this.eat(type)) {
  3667. this.unexpected(loc, type);
  3668. }
  3669. }
  3670. tryParse(fn, oldState = this.state.clone()) {
  3671. const abortSignal = {
  3672. node: null
  3673. };
  3674. try {
  3675. const node = fn((node = null) => {
  3676. abortSignal.node = node;
  3677. throw abortSignal;
  3678. });
  3679. if (this.state.errors.length > oldState.errors.length) {
  3680. const failState = this.state;
  3681. this.state = oldState;
  3682. this.state.tokensLength = failState.tokensLength;
  3683. return {
  3684. node,
  3685. error: failState.errors[oldState.errors.length],
  3686. thrown: false,
  3687. aborted: false,
  3688. failState
  3689. };
  3690. }
  3691. return {
  3692. node,
  3693. error: null,
  3694. thrown: false,
  3695. aborted: false,
  3696. failState: null
  3697. };
  3698. } catch (error) {
  3699. const failState = this.state;
  3700. this.state = oldState;
  3701. if (error instanceof SyntaxError) {
  3702. return {
  3703. node: null,
  3704. error,
  3705. thrown: true,
  3706. aborted: false,
  3707. failState
  3708. };
  3709. }
  3710. if (error === abortSignal) {
  3711. return {
  3712. node: abortSignal.node,
  3713. error: null,
  3714. thrown: false,
  3715. aborted: true,
  3716. failState
  3717. };
  3718. }
  3719. throw error;
  3720. }
  3721. }
  3722. checkExpressionErrors(refExpressionErrors, andThrow) {
  3723. if (!refExpressionErrors) return false;
  3724. const {
  3725. shorthandAssignLoc,
  3726. doubleProtoLoc,
  3727. privateKeyLoc,
  3728. optionalParametersLoc
  3729. } = refExpressionErrors;
  3730. const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc;
  3731. if (!andThrow) {
  3732. return hasErrors;
  3733. }
  3734. if (shorthandAssignLoc != null) {
  3735. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  3736. }
  3737. if (doubleProtoLoc != null) {
  3738. this.raise(Errors.DuplicateProto, doubleProtoLoc);
  3739. }
  3740. if (privateKeyLoc != null) {
  3741. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  3742. }
  3743. if (optionalParametersLoc != null) {
  3744. this.unexpected(optionalParametersLoc);
  3745. }
  3746. }
  3747. isLiteralPropertyName() {
  3748. return tokenIsLiteralPropertyName(this.state.type);
  3749. }
  3750. isPrivateName(node) {
  3751. return node.type === "PrivateName";
  3752. }
  3753. getPrivateNameSV(node) {
  3754. return node.id.name;
  3755. }
  3756. hasPropertyAsPrivateName(node) {
  3757. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  3758. }
  3759. isObjectProperty(node) {
  3760. return node.type === "ObjectProperty";
  3761. }
  3762. isObjectMethod(node) {
  3763. return node.type === "ObjectMethod";
  3764. }
  3765. initializeScopes(inModule = this.options.sourceType === "module") {
  3766. const oldLabels = this.state.labels;
  3767. this.state.labels = [];
  3768. const oldExportedIdentifiers = this.exportedIdentifiers;
  3769. this.exportedIdentifiers = new Set();
  3770. const oldInModule = this.inModule;
  3771. this.inModule = inModule;
  3772. const oldScope = this.scope;
  3773. const ScopeHandler = this.getScopeHandler();
  3774. this.scope = new ScopeHandler(this, inModule);
  3775. const oldProdParam = this.prodParam;
  3776. this.prodParam = new ProductionParameterHandler();
  3777. const oldClassScope = this.classScope;
  3778. this.classScope = new ClassScopeHandler(this);
  3779. const oldExpressionScope = this.expressionScope;
  3780. this.expressionScope = new ExpressionScopeHandler(this);
  3781. return () => {
  3782. this.state.labels = oldLabels;
  3783. this.exportedIdentifiers = oldExportedIdentifiers;
  3784. this.inModule = oldInModule;
  3785. this.scope = oldScope;
  3786. this.prodParam = oldProdParam;
  3787. this.classScope = oldClassScope;
  3788. this.expressionScope = oldExpressionScope;
  3789. };
  3790. }
  3791. enterInitialScopes() {
  3792. let paramFlags = 0;
  3793. if (this.inModule) {
  3794. paramFlags |= 2;
  3795. }
  3796. if (this.optionFlags & 32) {
  3797. paramFlags |= 1;
  3798. }
  3799. this.scope.enter(1);
  3800. this.prodParam.enter(paramFlags);
  3801. }
  3802. checkDestructuringPrivate(refExpressionErrors) {
  3803. const {
  3804. privateKeyLoc
  3805. } = refExpressionErrors;
  3806. if (privateKeyLoc !== null) {
  3807. this.expectPlugin("destructuringPrivate", privateKeyLoc);
  3808. }
  3809. }
  3810. }
  3811. class ExpressionErrors {
  3812. constructor() {
  3813. this.shorthandAssignLoc = null;
  3814. this.doubleProtoLoc = null;
  3815. this.privateKeyLoc = null;
  3816. this.optionalParametersLoc = null;
  3817. }
  3818. }
  3819. class Node {
  3820. constructor(parser, pos, loc) {
  3821. this.type = "";
  3822. this.start = pos;
  3823. this.end = 0;
  3824. this.loc = new SourceLocation(loc);
  3825. if ((parser == null ? void 0 : parser.optionFlags) & 128) this.range = [pos, 0];
  3826. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  3827. }
  3828. }
  3829. const NodePrototype = Node.prototype;
  3830. {
  3831. NodePrototype.__clone = function () {
  3832. const newNode = new Node(undefined, this.start, this.loc.start);
  3833. const keys = Object.keys(this);
  3834. for (let i = 0, length = keys.length; i < length; i++) {
  3835. const key = keys[i];
  3836. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  3837. newNode[key] = this[key];
  3838. }
  3839. }
  3840. return newNode;
  3841. };
  3842. }
  3843. function clonePlaceholder(node) {
  3844. return cloneIdentifier(node);
  3845. }
  3846. function cloneIdentifier(node) {
  3847. const {
  3848. type,
  3849. start,
  3850. end,
  3851. loc,
  3852. range,
  3853. extra,
  3854. name
  3855. } = node;
  3856. const cloned = Object.create(NodePrototype);
  3857. cloned.type = type;
  3858. cloned.start = start;
  3859. cloned.end = end;
  3860. cloned.loc = loc;
  3861. cloned.range = range;
  3862. cloned.extra = extra;
  3863. cloned.name = name;
  3864. if (type === "Placeholder") {
  3865. cloned.expectedNode = node.expectedNode;
  3866. }
  3867. return cloned;
  3868. }
  3869. function cloneStringLiteral(node) {
  3870. const {
  3871. type,
  3872. start,
  3873. end,
  3874. loc,
  3875. range,
  3876. extra
  3877. } = node;
  3878. if (type === "Placeholder") {
  3879. return clonePlaceholder(node);
  3880. }
  3881. const cloned = Object.create(NodePrototype);
  3882. cloned.type = type;
  3883. cloned.start = start;
  3884. cloned.end = end;
  3885. cloned.loc = loc;
  3886. cloned.range = range;
  3887. if (node.raw !== undefined) {
  3888. cloned.raw = node.raw;
  3889. } else {
  3890. cloned.extra = extra;
  3891. }
  3892. cloned.value = node.value;
  3893. return cloned;
  3894. }
  3895. class NodeUtils extends UtilParser {
  3896. startNode() {
  3897. const loc = this.state.startLoc;
  3898. return new Node(this, loc.index, loc);
  3899. }
  3900. startNodeAt(loc) {
  3901. return new Node(this, loc.index, loc);
  3902. }
  3903. startNodeAtNode(type) {
  3904. return this.startNodeAt(type.loc.start);
  3905. }
  3906. finishNode(node, type) {
  3907. return this.finishNodeAt(node, type, this.state.lastTokEndLoc);
  3908. }
  3909. finishNodeAt(node, type, endLoc) {
  3910. node.type = type;
  3911. node.end = endLoc.index;
  3912. node.loc.end = endLoc;
  3913. if (this.optionFlags & 128) node.range[1] = endLoc.index;
  3914. if (this.optionFlags & 4096) {
  3915. this.processComment(node);
  3916. }
  3917. return node;
  3918. }
  3919. resetStartLocation(node, startLoc) {
  3920. node.start = startLoc.index;
  3921. node.loc.start = startLoc;
  3922. if (this.optionFlags & 128) node.range[0] = startLoc.index;
  3923. }
  3924. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  3925. node.end = endLoc.index;
  3926. node.loc.end = endLoc;
  3927. if (this.optionFlags & 128) node.range[1] = endLoc.index;
  3928. }
  3929. resetStartLocationFromNode(node, locationNode) {
  3930. this.resetStartLocation(node, locationNode.loc.start);
  3931. }
  3932. }
  3933. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  3934. const FlowErrors = ParseErrorEnum`flow`({
  3935. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  3936. 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.",
  3937. AssignReservedType: ({
  3938. reservedType
  3939. }) => `Cannot overwrite reserved type ${reservedType}.`,
  3940. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  3941. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  3942. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  3943. EnumBooleanMemberNotInitialized: ({
  3944. memberName,
  3945. enumName
  3946. }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,
  3947. EnumDuplicateMemberName: ({
  3948. memberName,
  3949. enumName
  3950. }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,
  3951. EnumInconsistentMemberValues: ({
  3952. enumName
  3953. }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,
  3954. EnumInvalidExplicitType: ({
  3955. invalidEnumType,
  3956. enumName
  3957. }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  3958. EnumInvalidExplicitTypeUnknownSupplied: ({
  3959. enumName
  3960. }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  3961. EnumInvalidMemberInitializerPrimaryType: ({
  3962. enumName,
  3963. memberName,
  3964. explicitType
  3965. }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,
  3966. EnumInvalidMemberInitializerSymbolType: ({
  3967. enumName,
  3968. memberName
  3969. }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,
  3970. EnumInvalidMemberInitializerUnknownType: ({
  3971. enumName,
  3972. memberName
  3973. }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,
  3974. EnumInvalidMemberName: ({
  3975. enumName,
  3976. memberName,
  3977. suggestion
  3978. }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,
  3979. EnumNumberMemberNotInitialized: ({
  3980. enumName,
  3981. memberName
  3982. }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,
  3983. EnumStringMemberInconsistentlyInitialized: ({
  3984. enumName
  3985. }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,
  3986. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  3987. ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.",
  3988. 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.",
  3989. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  3990. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  3991. InexactVariance: "Explicit inexact syntax cannot have variance.",
  3992. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  3993. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  3994. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  3995. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  3996. PatternIsOptional: Object.assign({
  3997. message: "A binding pattern parameter cannot be optional in an implementation signature."
  3998. }, {
  3999. reasonCode: "OptionalBindingPattern"
  4000. }),
  4001. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  4002. SpreadVariance: "Spread properties cannot have variance.",
  4003. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  4004. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  4005. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  4006. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  4007. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  4008. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  4009. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  4010. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  4011. UnexpectedReservedType: ({
  4012. reservedType
  4013. }) => `Unexpected reserved type ${reservedType}.`,
  4014. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  4015. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  4016. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  4017. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  4018. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  4019. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  4020. UnsupportedDeclareExportKind: ({
  4021. unsupportedExportKind,
  4022. suggestion
  4023. }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,
  4024. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  4025. UnterminatedFlowComment: "Unterminated flow-comment."
  4026. });
  4027. function isEsModuleType(bodyElement) {
  4028. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  4029. }
  4030. function hasTypeImportKind(node) {
  4031. return node.importKind === "type" || node.importKind === "typeof";
  4032. }
  4033. const exportSuggestions = {
  4034. const: "declare export var",
  4035. let: "declare export var",
  4036. type: "export type",
  4037. interface: "export interface"
  4038. };
  4039. function partition(list, test) {
  4040. const list1 = [];
  4041. const list2 = [];
  4042. for (let i = 0; i < list.length; i++) {
  4043. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  4044. }
  4045. return [list1, list2];
  4046. }
  4047. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  4048. var flow = superClass => class FlowParserMixin extends superClass {
  4049. constructor(...args) {
  4050. super(...args);
  4051. this.flowPragma = undefined;
  4052. }
  4053. getScopeHandler() {
  4054. return FlowScopeHandler;
  4055. }
  4056. shouldParseTypes() {
  4057. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  4058. }
  4059. finishToken(type, val) {
  4060. if (type !== 134 && type !== 13 && type !== 28) {
  4061. if (this.flowPragma === undefined) {
  4062. this.flowPragma = null;
  4063. }
  4064. }
  4065. super.finishToken(type, val);
  4066. }
  4067. addComment(comment) {
  4068. if (this.flowPragma === undefined) {
  4069. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  4070. if (!matches) ;else if (matches[1] === "flow") {
  4071. this.flowPragma = "flow";
  4072. } else if (matches[1] === "noflow") {
  4073. this.flowPragma = "noflow";
  4074. } else {
  4075. throw new Error("Unexpected flow pragma");
  4076. }
  4077. }
  4078. super.addComment(comment);
  4079. }
  4080. flowParseTypeInitialiser(tok) {
  4081. const oldInType = this.state.inType;
  4082. this.state.inType = true;
  4083. this.expect(tok || 14);
  4084. const type = this.flowParseType();
  4085. this.state.inType = oldInType;
  4086. return type;
  4087. }
  4088. flowParsePredicate() {
  4089. const node = this.startNode();
  4090. const moduloLoc = this.state.startLoc;
  4091. this.next();
  4092. this.expectContextual(110);
  4093. if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) {
  4094. this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);
  4095. }
  4096. if (this.eat(10)) {
  4097. node.value = super.parseExpression();
  4098. this.expect(11);
  4099. return this.finishNode(node, "DeclaredPredicate");
  4100. } else {
  4101. return this.finishNode(node, "InferredPredicate");
  4102. }
  4103. }
  4104. flowParseTypeAndPredicateInitialiser() {
  4105. const oldInType = this.state.inType;
  4106. this.state.inType = true;
  4107. this.expect(14);
  4108. let type = null;
  4109. let predicate = null;
  4110. if (this.match(54)) {
  4111. this.state.inType = oldInType;
  4112. predicate = this.flowParsePredicate();
  4113. } else {
  4114. type = this.flowParseType();
  4115. this.state.inType = oldInType;
  4116. if (this.match(54)) {
  4117. predicate = this.flowParsePredicate();
  4118. }
  4119. }
  4120. return [type, predicate];
  4121. }
  4122. flowParseDeclareClass(node) {
  4123. this.next();
  4124. this.flowParseInterfaceish(node, true);
  4125. return this.finishNode(node, "DeclareClass");
  4126. }
  4127. flowParseDeclareFunction(node) {
  4128. this.next();
  4129. const id = node.id = this.parseIdentifier();
  4130. const typeNode = this.startNode();
  4131. const typeContainer = this.startNode();
  4132. if (this.match(47)) {
  4133. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4134. } else {
  4135. typeNode.typeParameters = null;
  4136. }
  4137. this.expect(10);
  4138. const tmp = this.flowParseFunctionTypeParams();
  4139. typeNode.params = tmp.params;
  4140. typeNode.rest = tmp.rest;
  4141. typeNode.this = tmp._this;
  4142. this.expect(11);
  4143. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  4144. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4145. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4146. this.resetEndLocation(id);
  4147. this.semicolon();
  4148. this.scope.declareName(node.id.name, 2048, node.id.loc.start);
  4149. return this.finishNode(node, "DeclareFunction");
  4150. }
  4151. flowParseDeclare(node, insideModule) {
  4152. if (this.match(80)) {
  4153. return this.flowParseDeclareClass(node);
  4154. } else if (this.match(68)) {
  4155. return this.flowParseDeclareFunction(node);
  4156. } else if (this.match(74)) {
  4157. return this.flowParseDeclareVariable(node);
  4158. } else if (this.eatContextual(127)) {
  4159. if (this.match(16)) {
  4160. return this.flowParseDeclareModuleExports(node);
  4161. } else {
  4162. if (insideModule) {
  4163. this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc);
  4164. }
  4165. return this.flowParseDeclareModule(node);
  4166. }
  4167. } else if (this.isContextual(130)) {
  4168. return this.flowParseDeclareTypeAlias(node);
  4169. } else if (this.isContextual(131)) {
  4170. return this.flowParseDeclareOpaqueType(node);
  4171. } else if (this.isContextual(129)) {
  4172. return this.flowParseDeclareInterface(node);
  4173. } else if (this.match(82)) {
  4174. return this.flowParseDeclareExportDeclaration(node, insideModule);
  4175. } else {
  4176. this.unexpected();
  4177. }
  4178. }
  4179. flowParseDeclareVariable(node) {
  4180. this.next();
  4181. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  4182. this.scope.declareName(node.id.name, 5, node.id.loc.start);
  4183. this.semicolon();
  4184. return this.finishNode(node, "DeclareVariable");
  4185. }
  4186. flowParseDeclareModule(node) {
  4187. this.scope.enter(0);
  4188. if (this.match(134)) {
  4189. node.id = super.parseExprAtom();
  4190. } else {
  4191. node.id = this.parseIdentifier();
  4192. }
  4193. const bodyNode = node.body = this.startNode();
  4194. const body = bodyNode.body = [];
  4195. this.expect(5);
  4196. while (!this.match(8)) {
  4197. let bodyNode = this.startNode();
  4198. if (this.match(83)) {
  4199. this.next();
  4200. if (!this.isContextual(130) && !this.match(87)) {
  4201. this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc);
  4202. }
  4203. super.parseImport(bodyNode);
  4204. } else {
  4205. this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule);
  4206. bodyNode = this.flowParseDeclare(bodyNode, true);
  4207. }
  4208. body.push(bodyNode);
  4209. }
  4210. this.scope.exit();
  4211. this.expect(8);
  4212. this.finishNode(bodyNode, "BlockStatement");
  4213. let kind = null;
  4214. let hasModuleExport = false;
  4215. body.forEach(bodyElement => {
  4216. if (isEsModuleType(bodyElement)) {
  4217. if (kind === "CommonJS") {
  4218. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  4219. }
  4220. kind = "ES";
  4221. } else if (bodyElement.type === "DeclareModuleExports") {
  4222. if (hasModuleExport) {
  4223. this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);
  4224. }
  4225. if (kind === "ES") {
  4226. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  4227. }
  4228. kind = "CommonJS";
  4229. hasModuleExport = true;
  4230. }
  4231. });
  4232. node.kind = kind || "CommonJS";
  4233. return this.finishNode(node, "DeclareModule");
  4234. }
  4235. flowParseDeclareExportDeclaration(node, insideModule) {
  4236. this.expect(82);
  4237. if (this.eat(65)) {
  4238. if (this.match(68) || this.match(80)) {
  4239. node.declaration = this.flowParseDeclare(this.startNode());
  4240. } else {
  4241. node.declaration = this.flowParseType();
  4242. this.semicolon();
  4243. }
  4244. node.default = true;
  4245. return this.finishNode(node, "DeclareExportDeclaration");
  4246. } else {
  4247. if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) {
  4248. const label = this.state.value;
  4249. throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, {
  4250. unsupportedExportKind: label,
  4251. suggestion: exportSuggestions[label]
  4252. });
  4253. }
  4254. if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) {
  4255. node.declaration = this.flowParseDeclare(this.startNode());
  4256. node.default = false;
  4257. return this.finishNode(node, "DeclareExportDeclaration");
  4258. } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) {
  4259. node = this.parseExport(node, null);
  4260. if (node.type === "ExportNamedDeclaration") {
  4261. node.type = "ExportDeclaration";
  4262. node.default = false;
  4263. delete node.exportKind;
  4264. }
  4265. node.type = "Declare" + node.type;
  4266. return node;
  4267. }
  4268. }
  4269. this.unexpected();
  4270. }
  4271. flowParseDeclareModuleExports(node) {
  4272. this.next();
  4273. this.expectContextual(111);
  4274. node.typeAnnotation = this.flowParseTypeAnnotation();
  4275. this.semicolon();
  4276. return this.finishNode(node, "DeclareModuleExports");
  4277. }
  4278. flowParseDeclareTypeAlias(node) {
  4279. this.next();
  4280. const finished = this.flowParseTypeAlias(node);
  4281. finished.type = "DeclareTypeAlias";
  4282. return finished;
  4283. }
  4284. flowParseDeclareOpaqueType(node) {
  4285. this.next();
  4286. const finished = this.flowParseOpaqueType(node, true);
  4287. finished.type = "DeclareOpaqueType";
  4288. return finished;
  4289. }
  4290. flowParseDeclareInterface(node) {
  4291. this.next();
  4292. this.flowParseInterfaceish(node, false);
  4293. return this.finishNode(node, "DeclareInterface");
  4294. }
  4295. flowParseInterfaceish(node, isClass) {
  4296. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  4297. this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start);
  4298. if (this.match(47)) {
  4299. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4300. } else {
  4301. node.typeParameters = null;
  4302. }
  4303. node.extends = [];
  4304. if (this.eat(81)) {
  4305. do {
  4306. node.extends.push(this.flowParseInterfaceExtends());
  4307. } while (!isClass && this.eat(12));
  4308. }
  4309. if (isClass) {
  4310. node.implements = [];
  4311. node.mixins = [];
  4312. if (this.eatContextual(117)) {
  4313. do {
  4314. node.mixins.push(this.flowParseInterfaceExtends());
  4315. } while (this.eat(12));
  4316. }
  4317. if (this.eatContextual(113)) {
  4318. do {
  4319. node.implements.push(this.flowParseInterfaceExtends());
  4320. } while (this.eat(12));
  4321. }
  4322. }
  4323. node.body = this.flowParseObjectType({
  4324. allowStatic: isClass,
  4325. allowExact: false,
  4326. allowSpread: false,
  4327. allowProto: isClass,
  4328. allowInexact: false
  4329. });
  4330. }
  4331. flowParseInterfaceExtends() {
  4332. const node = this.startNode();
  4333. node.id = this.flowParseQualifiedTypeIdentifier();
  4334. if (this.match(47)) {
  4335. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4336. } else {
  4337. node.typeParameters = null;
  4338. }
  4339. return this.finishNode(node, "InterfaceExtends");
  4340. }
  4341. flowParseInterface(node) {
  4342. this.flowParseInterfaceish(node, false);
  4343. return this.finishNode(node, "InterfaceDeclaration");
  4344. }
  4345. checkNotUnderscore(word) {
  4346. if (word === "_") {
  4347. this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc);
  4348. }
  4349. }
  4350. checkReservedType(word, startLoc, declaration) {
  4351. if (!reservedTypes.has(word)) return;
  4352. this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, {
  4353. reservedType: word
  4354. });
  4355. }
  4356. flowParseRestrictedIdentifier(liberal, declaration) {
  4357. this.checkReservedType(this.state.value, this.state.startLoc, declaration);
  4358. return this.parseIdentifier(liberal);
  4359. }
  4360. flowParseTypeAlias(node) {
  4361. node.id = this.flowParseRestrictedIdentifier(false, true);
  4362. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  4363. if (this.match(47)) {
  4364. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4365. } else {
  4366. node.typeParameters = null;
  4367. }
  4368. node.right = this.flowParseTypeInitialiser(29);
  4369. this.semicolon();
  4370. return this.finishNode(node, "TypeAlias");
  4371. }
  4372. flowParseOpaqueType(node, declare) {
  4373. this.expectContextual(130);
  4374. node.id = this.flowParseRestrictedIdentifier(true, true);
  4375. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  4376. if (this.match(47)) {
  4377. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4378. } else {
  4379. node.typeParameters = null;
  4380. }
  4381. node.supertype = null;
  4382. if (this.match(14)) {
  4383. node.supertype = this.flowParseTypeInitialiser(14);
  4384. }
  4385. node.impltype = null;
  4386. if (!declare) {
  4387. node.impltype = this.flowParseTypeInitialiser(29);
  4388. }
  4389. this.semicolon();
  4390. return this.finishNode(node, "OpaqueType");
  4391. }
  4392. flowParseTypeParameter(requireDefault = false) {
  4393. const nodeStartLoc = this.state.startLoc;
  4394. const node = this.startNode();
  4395. const variance = this.flowParseVariance();
  4396. const ident = this.flowParseTypeAnnotatableIdentifier();
  4397. node.name = ident.name;
  4398. node.variance = variance;
  4399. node.bound = ident.typeAnnotation;
  4400. if (this.match(29)) {
  4401. this.eat(29);
  4402. node.default = this.flowParseType();
  4403. } else {
  4404. if (requireDefault) {
  4405. this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);
  4406. }
  4407. }
  4408. return this.finishNode(node, "TypeParameter");
  4409. }
  4410. flowParseTypeParameterDeclaration() {
  4411. const oldInType = this.state.inType;
  4412. const node = this.startNode();
  4413. node.params = [];
  4414. this.state.inType = true;
  4415. if (this.match(47) || this.match(143)) {
  4416. this.next();
  4417. } else {
  4418. this.unexpected();
  4419. }
  4420. let defaultRequired = false;
  4421. do {
  4422. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  4423. node.params.push(typeParameter);
  4424. if (typeParameter.default) {
  4425. defaultRequired = true;
  4426. }
  4427. if (!this.match(48)) {
  4428. this.expect(12);
  4429. }
  4430. } while (!this.match(48));
  4431. this.expect(48);
  4432. this.state.inType = oldInType;
  4433. return this.finishNode(node, "TypeParameterDeclaration");
  4434. }
  4435. flowInTopLevelContext(cb) {
  4436. if (this.curContext() !== types.brace) {
  4437. const oldContext = this.state.context;
  4438. this.state.context = [oldContext[0]];
  4439. try {
  4440. return cb();
  4441. } finally {
  4442. this.state.context = oldContext;
  4443. }
  4444. } else {
  4445. return cb();
  4446. }
  4447. }
  4448. flowParseTypeParameterInstantiationInExpression() {
  4449. if (this.reScan_lt() !== 47) return;
  4450. return this.flowParseTypeParameterInstantiation();
  4451. }
  4452. flowParseTypeParameterInstantiation() {
  4453. const node = this.startNode();
  4454. const oldInType = this.state.inType;
  4455. this.state.inType = true;
  4456. node.params = [];
  4457. this.flowInTopLevelContext(() => {
  4458. this.expect(47);
  4459. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4460. this.state.noAnonFunctionType = false;
  4461. while (!this.match(48)) {
  4462. node.params.push(this.flowParseType());
  4463. if (!this.match(48)) {
  4464. this.expect(12);
  4465. }
  4466. }
  4467. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4468. });
  4469. this.state.inType = oldInType;
  4470. if (!this.state.inType && this.curContext() === types.brace) {
  4471. this.reScan_lt_gt();
  4472. }
  4473. this.expect(48);
  4474. return this.finishNode(node, "TypeParameterInstantiation");
  4475. }
  4476. flowParseTypeParameterInstantiationCallOrNew() {
  4477. if (this.reScan_lt() !== 47) return;
  4478. const node = this.startNode();
  4479. const oldInType = this.state.inType;
  4480. node.params = [];
  4481. this.state.inType = true;
  4482. this.expect(47);
  4483. while (!this.match(48)) {
  4484. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  4485. if (!this.match(48)) {
  4486. this.expect(12);
  4487. }
  4488. }
  4489. this.expect(48);
  4490. this.state.inType = oldInType;
  4491. return this.finishNode(node, "TypeParameterInstantiation");
  4492. }
  4493. flowParseInterfaceType() {
  4494. const node = this.startNode();
  4495. this.expectContextual(129);
  4496. node.extends = [];
  4497. if (this.eat(81)) {
  4498. do {
  4499. node.extends.push(this.flowParseInterfaceExtends());
  4500. } while (this.eat(12));
  4501. }
  4502. node.body = this.flowParseObjectType({
  4503. allowStatic: false,
  4504. allowExact: false,
  4505. allowSpread: false,
  4506. allowProto: false,
  4507. allowInexact: false
  4508. });
  4509. return this.finishNode(node, "InterfaceTypeAnnotation");
  4510. }
  4511. flowParseObjectPropertyKey() {
  4512. return this.match(135) || this.match(134) ? super.parseExprAtom() : this.parseIdentifier(true);
  4513. }
  4514. flowParseObjectTypeIndexer(node, isStatic, variance) {
  4515. node.static = isStatic;
  4516. if (this.lookahead().type === 14) {
  4517. node.id = this.flowParseObjectPropertyKey();
  4518. node.key = this.flowParseTypeInitialiser();
  4519. } else {
  4520. node.id = null;
  4521. node.key = this.flowParseType();
  4522. }
  4523. this.expect(3);
  4524. node.value = this.flowParseTypeInitialiser();
  4525. node.variance = variance;
  4526. return this.finishNode(node, "ObjectTypeIndexer");
  4527. }
  4528. flowParseObjectTypeInternalSlot(node, isStatic) {
  4529. node.static = isStatic;
  4530. node.id = this.flowParseObjectPropertyKey();
  4531. this.expect(3);
  4532. this.expect(3);
  4533. if (this.match(47) || this.match(10)) {
  4534. node.method = true;
  4535. node.optional = false;
  4536. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  4537. } else {
  4538. node.method = false;
  4539. if (this.eat(17)) {
  4540. node.optional = true;
  4541. }
  4542. node.value = this.flowParseTypeInitialiser();
  4543. }
  4544. return this.finishNode(node, "ObjectTypeInternalSlot");
  4545. }
  4546. flowParseObjectTypeMethodish(node) {
  4547. node.params = [];
  4548. node.rest = null;
  4549. node.typeParameters = null;
  4550. node.this = null;
  4551. if (this.match(47)) {
  4552. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4553. }
  4554. this.expect(10);
  4555. if (this.match(78)) {
  4556. node.this = this.flowParseFunctionTypeParam(true);
  4557. node.this.name = null;
  4558. if (!this.match(11)) {
  4559. this.expect(12);
  4560. }
  4561. }
  4562. while (!this.match(11) && !this.match(21)) {
  4563. node.params.push(this.flowParseFunctionTypeParam(false));
  4564. if (!this.match(11)) {
  4565. this.expect(12);
  4566. }
  4567. }
  4568. if (this.eat(21)) {
  4569. node.rest = this.flowParseFunctionTypeParam(false);
  4570. }
  4571. this.expect(11);
  4572. node.returnType = this.flowParseTypeInitialiser();
  4573. return this.finishNode(node, "FunctionTypeAnnotation");
  4574. }
  4575. flowParseObjectTypeCallProperty(node, isStatic) {
  4576. const valueNode = this.startNode();
  4577. node.static = isStatic;
  4578. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4579. return this.finishNode(node, "ObjectTypeCallProperty");
  4580. }
  4581. flowParseObjectType({
  4582. allowStatic,
  4583. allowExact,
  4584. allowSpread,
  4585. allowProto,
  4586. allowInexact
  4587. }) {
  4588. const oldInType = this.state.inType;
  4589. this.state.inType = true;
  4590. const nodeStart = this.startNode();
  4591. nodeStart.callProperties = [];
  4592. nodeStart.properties = [];
  4593. nodeStart.indexers = [];
  4594. nodeStart.internalSlots = [];
  4595. let endDelim;
  4596. let exact;
  4597. let inexact = false;
  4598. if (allowExact && this.match(6)) {
  4599. this.expect(6);
  4600. endDelim = 9;
  4601. exact = true;
  4602. } else {
  4603. this.expect(5);
  4604. endDelim = 8;
  4605. exact = false;
  4606. }
  4607. nodeStart.exact = exact;
  4608. while (!this.match(endDelim)) {
  4609. let isStatic = false;
  4610. let protoStartLoc = null;
  4611. let inexactStartLoc = null;
  4612. const node = this.startNode();
  4613. if (allowProto && this.isContextual(118)) {
  4614. const lookahead = this.lookahead();
  4615. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4616. this.next();
  4617. protoStartLoc = this.state.startLoc;
  4618. allowStatic = false;
  4619. }
  4620. }
  4621. if (allowStatic && this.isContextual(106)) {
  4622. const lookahead = this.lookahead();
  4623. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4624. this.next();
  4625. isStatic = true;
  4626. }
  4627. }
  4628. const variance = this.flowParseVariance();
  4629. if (this.eat(0)) {
  4630. if (protoStartLoc != null) {
  4631. this.unexpected(protoStartLoc);
  4632. }
  4633. if (this.eat(0)) {
  4634. if (variance) {
  4635. this.unexpected(variance.loc.start);
  4636. }
  4637. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  4638. } else {
  4639. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4640. }
  4641. } else if (this.match(10) || this.match(47)) {
  4642. if (protoStartLoc != null) {
  4643. this.unexpected(protoStartLoc);
  4644. }
  4645. if (variance) {
  4646. this.unexpected(variance.loc.start);
  4647. }
  4648. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4649. } else {
  4650. let kind = "init";
  4651. if (this.isContextual(99) || this.isContextual(104)) {
  4652. const lookahead = this.lookahead();
  4653. if (tokenIsLiteralPropertyName(lookahead.type)) {
  4654. kind = this.state.value;
  4655. this.next();
  4656. }
  4657. }
  4658. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  4659. if (propOrInexact === null) {
  4660. inexact = true;
  4661. inexactStartLoc = this.state.lastTokStartLoc;
  4662. } else {
  4663. nodeStart.properties.push(propOrInexact);
  4664. }
  4665. }
  4666. this.flowObjectTypeSemicolon();
  4667. if (inexactStartLoc && !this.match(8) && !this.match(9)) {
  4668. this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc);
  4669. }
  4670. }
  4671. this.expect(endDelim);
  4672. if (allowSpread) {
  4673. nodeStart.inexact = inexact;
  4674. }
  4675. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4676. this.state.inType = oldInType;
  4677. return out;
  4678. }
  4679. flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) {
  4680. if (this.eat(21)) {
  4681. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  4682. if (isInexactToken) {
  4683. if (!allowSpread) {
  4684. this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc);
  4685. } else if (!allowInexact) {
  4686. this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc);
  4687. }
  4688. if (variance) {
  4689. this.raise(FlowErrors.InexactVariance, variance);
  4690. }
  4691. return null;
  4692. }
  4693. if (!allowSpread) {
  4694. this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc);
  4695. }
  4696. if (protoStartLoc != null) {
  4697. this.unexpected(protoStartLoc);
  4698. }
  4699. if (variance) {
  4700. this.raise(FlowErrors.SpreadVariance, variance);
  4701. }
  4702. node.argument = this.flowParseType();
  4703. return this.finishNode(node, "ObjectTypeSpreadProperty");
  4704. } else {
  4705. node.key = this.flowParseObjectPropertyKey();
  4706. node.static = isStatic;
  4707. node.proto = protoStartLoc != null;
  4708. node.kind = kind;
  4709. let optional = false;
  4710. if (this.match(47) || this.match(10)) {
  4711. node.method = true;
  4712. if (protoStartLoc != null) {
  4713. this.unexpected(protoStartLoc);
  4714. }
  4715. if (variance) {
  4716. this.unexpected(variance.loc.start);
  4717. }
  4718. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  4719. if (kind === "get" || kind === "set") {
  4720. this.flowCheckGetterSetterParams(node);
  4721. }
  4722. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  4723. this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this);
  4724. }
  4725. } else {
  4726. if (kind !== "init") this.unexpected();
  4727. node.method = false;
  4728. if (this.eat(17)) {
  4729. optional = true;
  4730. }
  4731. node.value = this.flowParseTypeInitialiser();
  4732. node.variance = variance;
  4733. }
  4734. node.optional = optional;
  4735. return this.finishNode(node, "ObjectTypeProperty");
  4736. }
  4737. }
  4738. flowCheckGetterSetterParams(property) {
  4739. const paramCount = property.kind === "get" ? 0 : 1;
  4740. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  4741. if (property.value.this) {
  4742. this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this);
  4743. }
  4744. if (length !== paramCount) {
  4745. this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property);
  4746. }
  4747. if (property.kind === "set" && property.value.rest) {
  4748. this.raise(Errors.BadSetterRestParameter, property);
  4749. }
  4750. }
  4751. flowObjectTypeSemicolon() {
  4752. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  4753. this.unexpected();
  4754. }
  4755. }
  4756. flowParseQualifiedTypeIdentifier(startLoc, id) {
  4757. startLoc != null ? startLoc : startLoc = this.state.startLoc;
  4758. let node = id || this.flowParseRestrictedIdentifier(true);
  4759. while (this.eat(16)) {
  4760. const node2 = this.startNodeAt(startLoc);
  4761. node2.qualification = node;
  4762. node2.id = this.flowParseRestrictedIdentifier(true);
  4763. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4764. }
  4765. return node;
  4766. }
  4767. flowParseGenericType(startLoc, id) {
  4768. const node = this.startNodeAt(startLoc);
  4769. node.typeParameters = null;
  4770. node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);
  4771. if (this.match(47)) {
  4772. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4773. }
  4774. return this.finishNode(node, "GenericTypeAnnotation");
  4775. }
  4776. flowParseTypeofType() {
  4777. const node = this.startNode();
  4778. this.expect(87);
  4779. node.argument = this.flowParsePrimaryType();
  4780. return this.finishNode(node, "TypeofTypeAnnotation");
  4781. }
  4782. flowParseTupleType() {
  4783. const node = this.startNode();
  4784. node.types = [];
  4785. this.expect(0);
  4786. while (this.state.pos < this.length && !this.match(3)) {
  4787. node.types.push(this.flowParseType());
  4788. if (this.match(3)) break;
  4789. this.expect(12);
  4790. }
  4791. this.expect(3);
  4792. return this.finishNode(node, "TupleTypeAnnotation");
  4793. }
  4794. flowParseFunctionTypeParam(first) {
  4795. let name = null;
  4796. let optional = false;
  4797. let typeAnnotation = null;
  4798. const node = this.startNode();
  4799. const lh = this.lookahead();
  4800. const isThis = this.state.type === 78;
  4801. if (lh.type === 14 || lh.type === 17) {
  4802. if (isThis && !first) {
  4803. this.raise(FlowErrors.ThisParamMustBeFirst, node);
  4804. }
  4805. name = this.parseIdentifier(isThis);
  4806. if (this.eat(17)) {
  4807. optional = true;
  4808. if (isThis) {
  4809. this.raise(FlowErrors.ThisParamMayNotBeOptional, node);
  4810. }
  4811. }
  4812. typeAnnotation = this.flowParseTypeInitialiser();
  4813. } else {
  4814. typeAnnotation = this.flowParseType();
  4815. }
  4816. node.name = name;
  4817. node.optional = optional;
  4818. node.typeAnnotation = typeAnnotation;
  4819. return this.finishNode(node, "FunctionTypeParam");
  4820. }
  4821. reinterpretTypeAsFunctionTypeParam(type) {
  4822. const node = this.startNodeAt(type.loc.start);
  4823. node.name = null;
  4824. node.optional = false;
  4825. node.typeAnnotation = type;
  4826. return this.finishNode(node, "FunctionTypeParam");
  4827. }
  4828. flowParseFunctionTypeParams(params = []) {
  4829. let rest = null;
  4830. let _this = null;
  4831. if (this.match(78)) {
  4832. _this = this.flowParseFunctionTypeParam(true);
  4833. _this.name = null;
  4834. if (!this.match(11)) {
  4835. this.expect(12);
  4836. }
  4837. }
  4838. while (!this.match(11) && !this.match(21)) {
  4839. params.push(this.flowParseFunctionTypeParam(false));
  4840. if (!this.match(11)) {
  4841. this.expect(12);
  4842. }
  4843. }
  4844. if (this.eat(21)) {
  4845. rest = this.flowParseFunctionTypeParam(false);
  4846. }
  4847. return {
  4848. params,
  4849. rest,
  4850. _this
  4851. };
  4852. }
  4853. flowIdentToTypeAnnotation(startLoc, node, id) {
  4854. switch (id.name) {
  4855. case "any":
  4856. return this.finishNode(node, "AnyTypeAnnotation");
  4857. case "bool":
  4858. case "boolean":
  4859. return this.finishNode(node, "BooleanTypeAnnotation");
  4860. case "mixed":
  4861. return this.finishNode(node, "MixedTypeAnnotation");
  4862. case "empty":
  4863. return this.finishNode(node, "EmptyTypeAnnotation");
  4864. case "number":
  4865. return this.finishNode(node, "NumberTypeAnnotation");
  4866. case "string":
  4867. return this.finishNode(node, "StringTypeAnnotation");
  4868. case "symbol":
  4869. return this.finishNode(node, "SymbolTypeAnnotation");
  4870. default:
  4871. this.checkNotUnderscore(id.name);
  4872. return this.flowParseGenericType(startLoc, id);
  4873. }
  4874. }
  4875. flowParsePrimaryType() {
  4876. const startLoc = this.state.startLoc;
  4877. const node = this.startNode();
  4878. let tmp;
  4879. let type;
  4880. let isGroupedType = false;
  4881. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4882. switch (this.state.type) {
  4883. case 5:
  4884. return this.flowParseObjectType({
  4885. allowStatic: false,
  4886. allowExact: false,
  4887. allowSpread: true,
  4888. allowProto: false,
  4889. allowInexact: true
  4890. });
  4891. case 6:
  4892. return this.flowParseObjectType({
  4893. allowStatic: false,
  4894. allowExact: true,
  4895. allowSpread: true,
  4896. allowProto: false,
  4897. allowInexact: false
  4898. });
  4899. case 0:
  4900. this.state.noAnonFunctionType = false;
  4901. type = this.flowParseTupleType();
  4902. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4903. return type;
  4904. case 47:
  4905. {
  4906. const node = this.startNode();
  4907. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4908. this.expect(10);
  4909. tmp = this.flowParseFunctionTypeParams();
  4910. node.params = tmp.params;
  4911. node.rest = tmp.rest;
  4912. node.this = tmp._this;
  4913. this.expect(11);
  4914. this.expect(19);
  4915. node.returnType = this.flowParseType();
  4916. return this.finishNode(node, "FunctionTypeAnnotation");
  4917. }
  4918. case 10:
  4919. {
  4920. const node = this.startNode();
  4921. this.next();
  4922. if (!this.match(11) && !this.match(21)) {
  4923. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  4924. const token = this.lookahead().type;
  4925. isGroupedType = token !== 17 && token !== 14;
  4926. } else {
  4927. isGroupedType = true;
  4928. }
  4929. }
  4930. if (isGroupedType) {
  4931. this.state.noAnonFunctionType = false;
  4932. type = this.flowParseType();
  4933. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4934. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  4935. this.expect(11);
  4936. return type;
  4937. } else {
  4938. this.eat(12);
  4939. }
  4940. }
  4941. if (type) {
  4942. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  4943. } else {
  4944. tmp = this.flowParseFunctionTypeParams();
  4945. }
  4946. node.params = tmp.params;
  4947. node.rest = tmp.rest;
  4948. node.this = tmp._this;
  4949. this.expect(11);
  4950. this.expect(19);
  4951. node.returnType = this.flowParseType();
  4952. node.typeParameters = null;
  4953. return this.finishNode(node, "FunctionTypeAnnotation");
  4954. }
  4955. case 134:
  4956. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  4957. case 85:
  4958. case 86:
  4959. node.value = this.match(85);
  4960. this.next();
  4961. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  4962. case 53:
  4963. if (this.state.value === "-") {
  4964. this.next();
  4965. if (this.match(135)) {
  4966. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  4967. }
  4968. if (this.match(136)) {
  4969. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  4970. }
  4971. throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc);
  4972. }
  4973. this.unexpected();
  4974. return;
  4975. case 135:
  4976. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  4977. case 136:
  4978. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  4979. case 88:
  4980. this.next();
  4981. return this.finishNode(node, "VoidTypeAnnotation");
  4982. case 84:
  4983. this.next();
  4984. return this.finishNode(node, "NullLiteralTypeAnnotation");
  4985. case 78:
  4986. this.next();
  4987. return this.finishNode(node, "ThisTypeAnnotation");
  4988. case 55:
  4989. this.next();
  4990. return this.finishNode(node, "ExistsTypeAnnotation");
  4991. case 87:
  4992. return this.flowParseTypeofType();
  4993. default:
  4994. if (tokenIsKeyword(this.state.type)) {
  4995. const label = tokenLabelName(this.state.type);
  4996. this.next();
  4997. return super.createIdentifier(node, label);
  4998. } else if (tokenIsIdentifier(this.state.type)) {
  4999. if (this.isContextual(129)) {
  5000. return this.flowParseInterfaceType();
  5001. }
  5002. return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier());
  5003. }
  5004. }
  5005. this.unexpected();
  5006. }
  5007. flowParsePostfixType() {
  5008. const startLoc = this.state.startLoc;
  5009. let type = this.flowParsePrimaryType();
  5010. let seenOptionalIndexedAccess = false;
  5011. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  5012. const node = this.startNodeAt(startLoc);
  5013. const optional = this.eat(18);
  5014. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  5015. this.expect(0);
  5016. if (!optional && this.match(3)) {
  5017. node.elementType = type;
  5018. this.next();
  5019. type = this.finishNode(node, "ArrayTypeAnnotation");
  5020. } else {
  5021. node.objectType = type;
  5022. node.indexType = this.flowParseType();
  5023. this.expect(3);
  5024. if (seenOptionalIndexedAccess) {
  5025. node.optional = optional;
  5026. type = this.finishNode(node, "OptionalIndexedAccessType");
  5027. } else {
  5028. type = this.finishNode(node, "IndexedAccessType");
  5029. }
  5030. }
  5031. }
  5032. return type;
  5033. }
  5034. flowParsePrefixType() {
  5035. const node = this.startNode();
  5036. if (this.eat(17)) {
  5037. node.typeAnnotation = this.flowParsePrefixType();
  5038. return this.finishNode(node, "NullableTypeAnnotation");
  5039. } else {
  5040. return this.flowParsePostfixType();
  5041. }
  5042. }
  5043. flowParseAnonFunctionWithoutParens() {
  5044. const param = this.flowParsePrefixType();
  5045. if (!this.state.noAnonFunctionType && this.eat(19)) {
  5046. const node = this.startNodeAt(param.loc.start);
  5047. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  5048. node.rest = null;
  5049. node.this = null;
  5050. node.returnType = this.flowParseType();
  5051. node.typeParameters = null;
  5052. return this.finishNode(node, "FunctionTypeAnnotation");
  5053. }
  5054. return param;
  5055. }
  5056. flowParseIntersectionType() {
  5057. const node = this.startNode();
  5058. this.eat(45);
  5059. const type = this.flowParseAnonFunctionWithoutParens();
  5060. node.types = [type];
  5061. while (this.eat(45)) {
  5062. node.types.push(this.flowParseAnonFunctionWithoutParens());
  5063. }
  5064. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  5065. }
  5066. flowParseUnionType() {
  5067. const node = this.startNode();
  5068. this.eat(43);
  5069. const type = this.flowParseIntersectionType();
  5070. node.types = [type];
  5071. while (this.eat(43)) {
  5072. node.types.push(this.flowParseIntersectionType());
  5073. }
  5074. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  5075. }
  5076. flowParseType() {
  5077. const oldInType = this.state.inType;
  5078. this.state.inType = true;
  5079. const type = this.flowParseUnionType();
  5080. this.state.inType = oldInType;
  5081. return type;
  5082. }
  5083. flowParseTypeOrImplicitInstantiation() {
  5084. if (this.state.type === 132 && this.state.value === "_") {
  5085. const startLoc = this.state.startLoc;
  5086. const node = this.parseIdentifier();
  5087. return this.flowParseGenericType(startLoc, node);
  5088. } else {
  5089. return this.flowParseType();
  5090. }
  5091. }
  5092. flowParseTypeAnnotation() {
  5093. const node = this.startNode();
  5094. node.typeAnnotation = this.flowParseTypeInitialiser();
  5095. return this.finishNode(node, "TypeAnnotation");
  5096. }
  5097. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  5098. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  5099. if (this.match(14)) {
  5100. ident.typeAnnotation = this.flowParseTypeAnnotation();
  5101. this.resetEndLocation(ident);
  5102. }
  5103. return ident;
  5104. }
  5105. typeCastToParameter(node) {
  5106. node.expression.typeAnnotation = node.typeAnnotation;
  5107. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  5108. return node.expression;
  5109. }
  5110. flowParseVariance() {
  5111. let variance = null;
  5112. if (this.match(53)) {
  5113. variance = this.startNode();
  5114. if (this.state.value === "+") {
  5115. variance.kind = "plus";
  5116. } else {
  5117. variance.kind = "minus";
  5118. }
  5119. this.next();
  5120. return this.finishNode(variance, "Variance");
  5121. }
  5122. return variance;
  5123. }
  5124. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  5125. if (allowExpressionBody) {
  5126. this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  5127. return;
  5128. }
  5129. super.parseFunctionBody(node, false, isMethod);
  5130. }
  5131. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5132. if (this.match(14)) {
  5133. const typeNode = this.startNode();
  5134. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5135. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  5136. }
  5137. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  5138. }
  5139. parseStatementLike(flags) {
  5140. if (this.state.strict && this.isContextual(129)) {
  5141. const lookahead = this.lookahead();
  5142. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  5143. const node = this.startNode();
  5144. this.next();
  5145. return this.flowParseInterface(node);
  5146. }
  5147. } else if (this.isContextual(126)) {
  5148. const node = this.startNode();
  5149. this.next();
  5150. return this.flowParseEnumDeclaration(node);
  5151. }
  5152. const stmt = super.parseStatementLike(flags);
  5153. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  5154. this.flowPragma = null;
  5155. }
  5156. return stmt;
  5157. }
  5158. parseExpressionStatement(node, expr, decorators) {
  5159. if (expr.type === "Identifier") {
  5160. if (expr.name === "declare") {
  5161. if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) {
  5162. return this.flowParseDeclare(node);
  5163. }
  5164. } else if (tokenIsIdentifier(this.state.type)) {
  5165. if (expr.name === "interface") {
  5166. return this.flowParseInterface(node);
  5167. } else if (expr.name === "type") {
  5168. return this.flowParseTypeAlias(node);
  5169. } else if (expr.name === "opaque") {
  5170. return this.flowParseOpaqueType(node, false);
  5171. }
  5172. }
  5173. }
  5174. return super.parseExpressionStatement(node, expr, decorators);
  5175. }
  5176. shouldParseExportDeclaration() {
  5177. const {
  5178. type
  5179. } = this.state;
  5180. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  5181. return !this.state.containsEsc;
  5182. }
  5183. return super.shouldParseExportDeclaration();
  5184. }
  5185. isExportDefaultSpecifier() {
  5186. const {
  5187. type
  5188. } = this.state;
  5189. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  5190. return this.state.containsEsc;
  5191. }
  5192. return super.isExportDefaultSpecifier();
  5193. }
  5194. parseExportDefaultExpression() {
  5195. if (this.isContextual(126)) {
  5196. const node = this.startNode();
  5197. this.next();
  5198. return this.flowParseEnumDeclaration(node);
  5199. }
  5200. return super.parseExportDefaultExpression();
  5201. }
  5202. parseConditional(expr, startLoc, refExpressionErrors) {
  5203. if (!this.match(17)) return expr;
  5204. if (this.state.maybeInArrowParameters) {
  5205. const nextCh = this.lookaheadCharCode();
  5206. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  5207. this.setOptionalParametersError(refExpressionErrors);
  5208. return expr;
  5209. }
  5210. }
  5211. this.expect(17);
  5212. const state = this.state.clone();
  5213. const originalNoArrowAt = this.state.noArrowAt;
  5214. const node = this.startNodeAt(startLoc);
  5215. let {
  5216. consequent,
  5217. failed
  5218. } = this.tryParseConditionalConsequent();
  5219. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5220. if (failed || invalid.length > 0) {
  5221. const noArrowAt = [...originalNoArrowAt];
  5222. if (invalid.length > 0) {
  5223. this.state = state;
  5224. this.state.noArrowAt = noArrowAt;
  5225. for (let i = 0; i < invalid.length; i++) {
  5226. noArrowAt.push(invalid[i].start);
  5227. }
  5228. ({
  5229. consequent,
  5230. failed
  5231. } = this.tryParseConditionalConsequent());
  5232. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5233. }
  5234. if (failed && valid.length > 1) {
  5235. this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);
  5236. }
  5237. if (failed && valid.length === 1) {
  5238. this.state = state;
  5239. noArrowAt.push(valid[0].start);
  5240. this.state.noArrowAt = noArrowAt;
  5241. ({
  5242. consequent,
  5243. failed
  5244. } = this.tryParseConditionalConsequent());
  5245. }
  5246. }
  5247. this.getArrowLikeExpressions(consequent, true);
  5248. this.state.noArrowAt = originalNoArrowAt;
  5249. this.expect(14);
  5250. node.test = expr;
  5251. node.consequent = consequent;
  5252. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  5253. return this.finishNode(node, "ConditionalExpression");
  5254. }
  5255. tryParseConditionalConsequent() {
  5256. this.state.noArrowParamsConversionAt.push(this.state.start);
  5257. const consequent = this.parseMaybeAssignAllowIn();
  5258. const failed = !this.match(14);
  5259. this.state.noArrowParamsConversionAt.pop();
  5260. return {
  5261. consequent,
  5262. failed
  5263. };
  5264. }
  5265. getArrowLikeExpressions(node, disallowInvalid) {
  5266. const stack = [node];
  5267. const arrows = [];
  5268. while (stack.length !== 0) {
  5269. const node = stack.pop();
  5270. if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
  5271. if (node.typeParameters || !node.returnType) {
  5272. this.finishArrowValidation(node);
  5273. } else {
  5274. arrows.push(node);
  5275. }
  5276. stack.push(node.body);
  5277. } else if (node.type === "ConditionalExpression") {
  5278. stack.push(node.consequent);
  5279. stack.push(node.alternate);
  5280. }
  5281. }
  5282. if (disallowInvalid) {
  5283. arrows.forEach(node => this.finishArrowValidation(node));
  5284. return [arrows, []];
  5285. }
  5286. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  5287. }
  5288. finishArrowValidation(node) {
  5289. var _node$extra;
  5290. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
  5291. this.scope.enter(2 | 4);
  5292. super.checkParams(node, false, true);
  5293. this.scope.exit();
  5294. }
  5295. forwardNoArrowParamsConversionAt(node, parse) {
  5296. let result;
  5297. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  5298. this.state.noArrowParamsConversionAt.push(this.state.start);
  5299. result = parse();
  5300. this.state.noArrowParamsConversionAt.pop();
  5301. } else {
  5302. result = parse();
  5303. }
  5304. return result;
  5305. }
  5306. parseParenItem(node, startLoc) {
  5307. const newNode = super.parseParenItem(node, startLoc);
  5308. if (this.eat(17)) {
  5309. newNode.optional = true;
  5310. this.resetEndLocation(node);
  5311. }
  5312. if (this.match(14)) {
  5313. const typeCastNode = this.startNodeAt(startLoc);
  5314. typeCastNode.expression = newNode;
  5315. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  5316. return this.finishNode(typeCastNode, "TypeCastExpression");
  5317. }
  5318. return newNode;
  5319. }
  5320. assertModuleNodeAllowed(node) {
  5321. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  5322. return;
  5323. }
  5324. super.assertModuleNodeAllowed(node);
  5325. }
  5326. parseExportDeclaration(node) {
  5327. if (this.isContextual(130)) {
  5328. node.exportKind = "type";
  5329. const declarationNode = this.startNode();
  5330. this.next();
  5331. if (this.match(5)) {
  5332. node.specifiers = this.parseExportSpecifiers(true);
  5333. super.parseExportFrom(node);
  5334. return null;
  5335. } else {
  5336. return this.flowParseTypeAlias(declarationNode);
  5337. }
  5338. } else if (this.isContextual(131)) {
  5339. node.exportKind = "type";
  5340. const declarationNode = this.startNode();
  5341. this.next();
  5342. return this.flowParseOpaqueType(declarationNode, false);
  5343. } else if (this.isContextual(129)) {
  5344. node.exportKind = "type";
  5345. const declarationNode = this.startNode();
  5346. this.next();
  5347. return this.flowParseInterface(declarationNode);
  5348. } else if (this.isContextual(126)) {
  5349. node.exportKind = "value";
  5350. const declarationNode = this.startNode();
  5351. this.next();
  5352. return this.flowParseEnumDeclaration(declarationNode);
  5353. } else {
  5354. return super.parseExportDeclaration(node);
  5355. }
  5356. }
  5357. eatExportStar(node) {
  5358. if (super.eatExportStar(node)) return true;
  5359. if (this.isContextual(130) && this.lookahead().type === 55) {
  5360. node.exportKind = "type";
  5361. this.next();
  5362. this.next();
  5363. return true;
  5364. }
  5365. return false;
  5366. }
  5367. maybeParseExportNamespaceSpecifier(node) {
  5368. const {
  5369. startLoc
  5370. } = this.state;
  5371. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  5372. if (hasNamespace && node.exportKind === "type") {
  5373. this.unexpected(startLoc);
  5374. }
  5375. return hasNamespace;
  5376. }
  5377. parseClassId(node, isStatement, optionalId) {
  5378. super.parseClassId(node, isStatement, optionalId);
  5379. if (this.match(47)) {
  5380. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5381. }
  5382. }
  5383. parseClassMember(classBody, member, state) {
  5384. const {
  5385. startLoc
  5386. } = this.state;
  5387. if (this.isContextual(125)) {
  5388. if (super.parseClassMemberFromModifier(classBody, member)) {
  5389. return;
  5390. }
  5391. member.declare = true;
  5392. }
  5393. super.parseClassMember(classBody, member, state);
  5394. if (member.declare) {
  5395. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  5396. this.raise(FlowErrors.DeclareClassElement, startLoc);
  5397. } else if (member.value) {
  5398. this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);
  5399. }
  5400. }
  5401. }
  5402. isIterator(word) {
  5403. return word === "iterator" || word === "asyncIterator";
  5404. }
  5405. readIterator() {
  5406. const word = super.readWord1();
  5407. const fullWord = "@@" + word;
  5408. if (!this.isIterator(word) || !this.state.inType) {
  5409. this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {
  5410. identifierName: fullWord
  5411. });
  5412. }
  5413. this.finishToken(132, fullWord);
  5414. }
  5415. getTokenFromCode(code) {
  5416. const next = this.input.charCodeAt(this.state.pos + 1);
  5417. if (code === 123 && next === 124) {
  5418. this.finishOp(6, 2);
  5419. } else if (this.state.inType && (code === 62 || code === 60)) {
  5420. this.finishOp(code === 62 ? 48 : 47, 1);
  5421. } else if (this.state.inType && code === 63) {
  5422. if (next === 46) {
  5423. this.finishOp(18, 2);
  5424. } else {
  5425. this.finishOp(17, 1);
  5426. }
  5427. } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) {
  5428. this.state.pos += 2;
  5429. this.readIterator();
  5430. } else {
  5431. super.getTokenFromCode(code);
  5432. }
  5433. }
  5434. isAssignable(node, isBinding) {
  5435. if (node.type === "TypeCastExpression") {
  5436. return this.isAssignable(node.expression, isBinding);
  5437. } else {
  5438. return super.isAssignable(node, isBinding);
  5439. }
  5440. }
  5441. toAssignable(node, isLHS = false) {
  5442. if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") {
  5443. node.left = this.typeCastToParameter(node.left);
  5444. }
  5445. super.toAssignable(node, isLHS);
  5446. }
  5447. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  5448. for (let i = 0; i < exprList.length; i++) {
  5449. const expr = exprList[i];
  5450. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  5451. exprList[i] = this.typeCastToParameter(expr);
  5452. }
  5453. }
  5454. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  5455. }
  5456. toReferencedList(exprList, isParenthesizedExpr) {
  5457. for (let i = 0; i < exprList.length; i++) {
  5458. var _expr$extra;
  5459. const expr = exprList[i];
  5460. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  5461. this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);
  5462. }
  5463. }
  5464. return exprList;
  5465. }
  5466. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  5467. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  5468. if (canBePattern && !this.state.maybeInArrowParameters) {
  5469. this.toReferencedList(node.elements);
  5470. }
  5471. return node;
  5472. }
  5473. isValidLVal(type, isParenthesized, binding) {
  5474. return type === "TypeCastExpression" || super.isValidLVal(type, isParenthesized, binding);
  5475. }
  5476. parseClassProperty(node) {
  5477. if (this.match(14)) {
  5478. node.typeAnnotation = this.flowParseTypeAnnotation();
  5479. }
  5480. return super.parseClassProperty(node);
  5481. }
  5482. parseClassPrivateProperty(node) {
  5483. if (this.match(14)) {
  5484. node.typeAnnotation = this.flowParseTypeAnnotation();
  5485. }
  5486. return super.parseClassPrivateProperty(node);
  5487. }
  5488. isClassMethod() {
  5489. return this.match(47) || super.isClassMethod();
  5490. }
  5491. isClassProperty() {
  5492. return this.match(14) || super.isClassProperty();
  5493. }
  5494. isNonstaticConstructor(method) {
  5495. return !this.match(14) && super.isNonstaticConstructor(method);
  5496. }
  5497. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5498. if (method.variance) {
  5499. this.unexpected(method.variance.loc.start);
  5500. }
  5501. delete method.variance;
  5502. if (this.match(47)) {
  5503. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5504. }
  5505. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5506. if (method.params && isConstructor) {
  5507. const params = method.params;
  5508. if (params.length > 0 && this.isThisParam(params[0])) {
  5509. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  5510. }
  5511. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  5512. const params = method.value.params;
  5513. if (params.length > 0 && this.isThisParam(params[0])) {
  5514. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  5515. }
  5516. }
  5517. }
  5518. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5519. if (method.variance) {
  5520. this.unexpected(method.variance.loc.start);
  5521. }
  5522. delete method.variance;
  5523. if (this.match(47)) {
  5524. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5525. }
  5526. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5527. }
  5528. parseClassSuper(node) {
  5529. super.parseClassSuper(node);
  5530. if (node.superClass && (this.match(47) || this.match(51))) {
  5531. {
  5532. node.superTypeParameters = this.flowParseTypeParameterInstantiationInExpression();
  5533. }
  5534. }
  5535. if (this.isContextual(113)) {
  5536. this.next();
  5537. const implemented = node.implements = [];
  5538. do {
  5539. const node = this.startNode();
  5540. node.id = this.flowParseRestrictedIdentifier(true);
  5541. if (this.match(47)) {
  5542. node.typeParameters = this.flowParseTypeParameterInstantiation();
  5543. } else {
  5544. node.typeParameters = null;
  5545. }
  5546. implemented.push(this.finishNode(node, "ClassImplements"));
  5547. } while (this.eat(12));
  5548. }
  5549. }
  5550. checkGetterSetterParams(method) {
  5551. super.checkGetterSetterParams(method);
  5552. const params = this.getObjectOrClassMethodParams(method);
  5553. if (params.length > 0) {
  5554. const param = params[0];
  5555. if (this.isThisParam(param) && method.kind === "get") {
  5556. this.raise(FlowErrors.GetterMayNotHaveThisParam, param);
  5557. } else if (this.isThisParam(param)) {
  5558. this.raise(FlowErrors.SetterMayNotHaveThisParam, param);
  5559. }
  5560. }
  5561. }
  5562. parsePropertyNamePrefixOperator(node) {
  5563. node.variance = this.flowParseVariance();
  5564. }
  5565. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  5566. if (prop.variance) {
  5567. this.unexpected(prop.variance.loc.start);
  5568. }
  5569. delete prop.variance;
  5570. let typeParameters;
  5571. if (this.match(47) && !isAccessor) {
  5572. typeParameters = this.flowParseTypeParameterDeclaration();
  5573. if (!this.match(10)) this.unexpected();
  5574. }
  5575. const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  5576. if (typeParameters) {
  5577. (result.value || result).typeParameters = typeParameters;
  5578. }
  5579. return result;
  5580. }
  5581. parseFunctionParamType(param) {
  5582. if (this.eat(17)) {
  5583. if (param.type !== "Identifier") {
  5584. this.raise(FlowErrors.PatternIsOptional, param);
  5585. }
  5586. if (this.isThisParam(param)) {
  5587. this.raise(FlowErrors.ThisParamMayNotBeOptional, param);
  5588. }
  5589. param.optional = true;
  5590. }
  5591. if (this.match(14)) {
  5592. param.typeAnnotation = this.flowParseTypeAnnotation();
  5593. } else if (this.isThisParam(param)) {
  5594. this.raise(FlowErrors.ThisParamAnnotationRequired, param);
  5595. }
  5596. if (this.match(29) && this.isThisParam(param)) {
  5597. this.raise(FlowErrors.ThisParamNoDefault, param);
  5598. }
  5599. this.resetEndLocation(param);
  5600. return param;
  5601. }
  5602. parseMaybeDefault(startLoc, left) {
  5603. const node = super.parseMaybeDefault(startLoc, left);
  5604. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5605. this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);
  5606. }
  5607. return node;
  5608. }
  5609. checkImportReflection(node) {
  5610. super.checkImportReflection(node);
  5611. if (node.module && node.importKind !== "value") {
  5612. this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  5613. }
  5614. }
  5615. parseImportSpecifierLocal(node, specifier, type) {
  5616. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  5617. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  5618. }
  5619. isPotentialImportPhase(isExport) {
  5620. if (super.isPotentialImportPhase(isExport)) return true;
  5621. if (this.isContextual(130)) {
  5622. if (!isExport) return true;
  5623. const ch = this.lookaheadCharCode();
  5624. return ch === 123 || ch === 42;
  5625. }
  5626. return !isExport && this.isContextual(87);
  5627. }
  5628. applyImportPhase(node, isExport, phase, loc) {
  5629. super.applyImportPhase(node, isExport, phase, loc);
  5630. if (isExport) {
  5631. if (!phase && this.match(65)) {
  5632. return;
  5633. }
  5634. node.exportKind = phase === "type" ? phase : "value";
  5635. } else {
  5636. if (phase === "type" && this.match(55)) this.unexpected();
  5637. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  5638. }
  5639. }
  5640. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  5641. const firstIdent = specifier.imported;
  5642. let specifierTypeKind = null;
  5643. if (firstIdent.type === "Identifier") {
  5644. if (firstIdent.name === "type") {
  5645. specifierTypeKind = "type";
  5646. } else if (firstIdent.name === "typeof") {
  5647. specifierTypeKind = "typeof";
  5648. }
  5649. }
  5650. let isBinding = false;
  5651. if (this.isContextual(93) && !this.isLookaheadContextual("as")) {
  5652. const as_ident = this.parseIdentifier(true);
  5653. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  5654. specifier.imported = as_ident;
  5655. specifier.importKind = specifierTypeKind;
  5656. specifier.local = cloneIdentifier(as_ident);
  5657. } else {
  5658. specifier.imported = firstIdent;
  5659. specifier.importKind = null;
  5660. specifier.local = this.parseIdentifier();
  5661. }
  5662. } else {
  5663. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  5664. specifier.imported = this.parseIdentifier(true);
  5665. specifier.importKind = specifierTypeKind;
  5666. } else {
  5667. if (importedIsString) {
  5668. throw this.raise(Errors.ImportBindingIsString, specifier, {
  5669. importName: firstIdent.value
  5670. });
  5671. }
  5672. specifier.imported = firstIdent;
  5673. specifier.importKind = null;
  5674. }
  5675. if (this.eatContextual(93)) {
  5676. specifier.local = this.parseIdentifier();
  5677. } else {
  5678. isBinding = true;
  5679. specifier.local = cloneIdentifier(specifier.imported);
  5680. }
  5681. }
  5682. const specifierIsTypeImport = hasTypeImportKind(specifier);
  5683. if (isInTypeOnlyImport && specifierIsTypeImport) {
  5684. this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);
  5685. }
  5686. if (isInTypeOnlyImport || specifierIsTypeImport) {
  5687. this.checkReservedType(specifier.local.name, specifier.local.loc.start, true);
  5688. }
  5689. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  5690. this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true);
  5691. }
  5692. return this.finishImportSpecifier(specifier, "ImportSpecifier");
  5693. }
  5694. parseBindingAtom() {
  5695. switch (this.state.type) {
  5696. case 78:
  5697. return this.parseIdentifier(true);
  5698. default:
  5699. return super.parseBindingAtom();
  5700. }
  5701. }
  5702. parseFunctionParams(node, isConstructor) {
  5703. const kind = node.kind;
  5704. if (kind !== "get" && kind !== "set" && this.match(47)) {
  5705. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5706. }
  5707. super.parseFunctionParams(node, isConstructor);
  5708. }
  5709. parseVarId(decl, kind) {
  5710. super.parseVarId(decl, kind);
  5711. if (this.match(14)) {
  5712. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5713. this.resetEndLocation(decl.id);
  5714. }
  5715. }
  5716. parseAsyncArrowFromCallExpression(node, call) {
  5717. if (this.match(14)) {
  5718. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5719. this.state.noAnonFunctionType = true;
  5720. node.returnType = this.flowParseTypeAnnotation();
  5721. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5722. }
  5723. return super.parseAsyncArrowFromCallExpression(node, call);
  5724. }
  5725. shouldParseAsyncArrow() {
  5726. return this.match(14) || super.shouldParseAsyncArrow();
  5727. }
  5728. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  5729. var _jsx;
  5730. let state = null;
  5731. let jsx;
  5732. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  5733. state = this.state.clone();
  5734. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  5735. if (!jsx.error) return jsx.node;
  5736. const {
  5737. context
  5738. } = this.state;
  5739. const currentContext = context[context.length - 1];
  5740. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  5741. context.pop();
  5742. }
  5743. }
  5744. if ((_jsx = jsx) != null && _jsx.error || this.match(47)) {
  5745. var _jsx2, _jsx3;
  5746. state = state || this.state.clone();
  5747. let typeParameters;
  5748. const arrow = this.tryParse(abort => {
  5749. var _arrowExpression$extr;
  5750. typeParameters = this.flowParseTypeParameterDeclaration();
  5751. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  5752. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5753. this.resetStartLocationFromNode(result, typeParameters);
  5754. return result;
  5755. });
  5756. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  5757. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  5758. if (expr.type !== "ArrowFunctionExpression") abort();
  5759. expr.typeParameters = typeParameters;
  5760. this.resetStartLocationFromNode(expr, typeParameters);
  5761. return arrowExpression;
  5762. }, state);
  5763. let arrowExpression = null;
  5764. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  5765. if (!arrow.error && !arrow.aborted) {
  5766. if (arrow.node.async) {
  5767. this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters);
  5768. }
  5769. return arrow.node;
  5770. }
  5771. arrowExpression = arrow.node;
  5772. }
  5773. if ((_jsx2 = jsx) != null && _jsx2.node) {
  5774. this.state = jsx.failState;
  5775. return jsx.node;
  5776. }
  5777. if (arrowExpression) {
  5778. this.state = arrow.failState;
  5779. return arrowExpression;
  5780. }
  5781. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  5782. if (arrow.thrown) throw arrow.error;
  5783. throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters);
  5784. }
  5785. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5786. }
  5787. parseArrow(node) {
  5788. if (this.match(14)) {
  5789. const result = this.tryParse(() => {
  5790. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5791. this.state.noAnonFunctionType = true;
  5792. const typeNode = this.startNode();
  5793. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5794. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5795. if (this.canInsertSemicolon()) this.unexpected();
  5796. if (!this.match(19)) this.unexpected();
  5797. return typeNode;
  5798. });
  5799. if (result.thrown) return null;
  5800. if (result.error) this.state = result.failState;
  5801. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  5802. }
  5803. return super.parseArrow(node);
  5804. }
  5805. shouldParseArrow(params) {
  5806. return this.match(14) || super.shouldParseArrow(params);
  5807. }
  5808. setArrowFunctionParameters(node, params) {
  5809. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  5810. node.params = params;
  5811. } else {
  5812. super.setArrowFunctionParameters(node, params);
  5813. }
  5814. }
  5815. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  5816. if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  5817. return;
  5818. }
  5819. for (let i = 0; i < node.params.length; i++) {
  5820. if (this.isThisParam(node.params[i]) && i > 0) {
  5821. this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);
  5822. }
  5823. }
  5824. super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged);
  5825. }
  5826. parseParenAndDistinguishExpression(canBeArrow) {
  5827. return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)));
  5828. }
  5829. parseSubscripts(base, startLoc, noCalls) {
  5830. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) {
  5831. this.next();
  5832. const node = this.startNodeAt(startLoc);
  5833. node.callee = base;
  5834. node.arguments = super.parseCallExpressionArguments(11);
  5835. base = this.finishNode(node, "CallExpression");
  5836. } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) {
  5837. const state = this.state.clone();
  5838. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state);
  5839. if (!arrow.error && !arrow.aborted) return arrow.node;
  5840. const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state);
  5841. if (result.node && !result.error) return result.node;
  5842. if (arrow.node) {
  5843. this.state = arrow.failState;
  5844. return arrow.node;
  5845. }
  5846. if (result.node) {
  5847. this.state = result.failState;
  5848. return result.node;
  5849. }
  5850. throw arrow.error || result.error;
  5851. }
  5852. return super.parseSubscripts(base, startLoc, noCalls);
  5853. }
  5854. parseSubscript(base, startLoc, noCalls, subscriptState) {
  5855. if (this.match(18) && this.isLookaheadToken_lt()) {
  5856. subscriptState.optionalChainMember = true;
  5857. if (noCalls) {
  5858. subscriptState.stop = true;
  5859. return base;
  5860. }
  5861. this.next();
  5862. const node = this.startNodeAt(startLoc);
  5863. node.callee = base;
  5864. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  5865. this.expect(10);
  5866. node.arguments = this.parseCallExpressionArguments(11);
  5867. node.optional = true;
  5868. return this.finishCallExpression(node, true);
  5869. } else if (!noCalls && this.shouldParseTypes() && (this.match(47) || this.match(51))) {
  5870. const node = this.startNodeAt(startLoc);
  5871. node.callee = base;
  5872. const result = this.tryParse(() => {
  5873. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  5874. this.expect(10);
  5875. node.arguments = super.parseCallExpressionArguments(11);
  5876. if (subscriptState.optionalChainMember) {
  5877. node.optional = false;
  5878. }
  5879. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  5880. });
  5881. if (result.node) {
  5882. if (result.error) this.state = result.failState;
  5883. return result.node;
  5884. }
  5885. }
  5886. return super.parseSubscript(base, startLoc, noCalls, subscriptState);
  5887. }
  5888. parseNewCallee(node) {
  5889. super.parseNewCallee(node);
  5890. let targs = null;
  5891. if (this.shouldParseTypes() && this.match(47)) {
  5892. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  5893. }
  5894. node.typeArguments = targs;
  5895. }
  5896. parseAsyncArrowWithTypeParameters(startLoc) {
  5897. const node = this.startNodeAt(startLoc);
  5898. this.parseFunctionParams(node, false);
  5899. if (!this.parseArrow(node)) return;
  5900. return super.parseArrowExpression(node, undefined, true);
  5901. }
  5902. readToken_mult_modulo(code) {
  5903. const next = this.input.charCodeAt(this.state.pos + 1);
  5904. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  5905. this.state.hasFlowComment = false;
  5906. this.state.pos += 2;
  5907. this.nextToken();
  5908. return;
  5909. }
  5910. super.readToken_mult_modulo(code);
  5911. }
  5912. readToken_pipe_amp(code) {
  5913. const next = this.input.charCodeAt(this.state.pos + 1);
  5914. if (code === 124 && next === 125) {
  5915. this.finishOp(9, 2);
  5916. return;
  5917. }
  5918. super.readToken_pipe_amp(code);
  5919. }
  5920. parseTopLevel(file, program) {
  5921. const fileNode = super.parseTopLevel(file, program);
  5922. if (this.state.hasFlowComment) {
  5923. this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition());
  5924. }
  5925. return fileNode;
  5926. }
  5927. skipBlockComment() {
  5928. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  5929. if (this.state.hasFlowComment) {
  5930. throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);
  5931. }
  5932. this.hasFlowCommentCompletion();
  5933. const commentSkip = this.skipFlowComment();
  5934. if (commentSkip) {
  5935. this.state.pos += commentSkip;
  5936. this.state.hasFlowComment = true;
  5937. }
  5938. return;
  5939. }
  5940. return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/");
  5941. }
  5942. skipFlowComment() {
  5943. const {
  5944. pos
  5945. } = this.state;
  5946. let shiftToFirstNonWhiteSpace = 2;
  5947. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  5948. shiftToFirstNonWhiteSpace++;
  5949. }
  5950. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  5951. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  5952. if (ch2 === 58 && ch3 === 58) {
  5953. return shiftToFirstNonWhiteSpace + 2;
  5954. }
  5955. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  5956. return shiftToFirstNonWhiteSpace + 12;
  5957. }
  5958. if (ch2 === 58 && ch3 !== 58) {
  5959. return shiftToFirstNonWhiteSpace;
  5960. }
  5961. return false;
  5962. }
  5963. hasFlowCommentCompletion() {
  5964. const end = this.input.indexOf("*/", this.state.pos);
  5965. if (end === -1) {
  5966. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  5967. }
  5968. }
  5969. flowEnumErrorBooleanMemberNotInitialized(loc, {
  5970. enumName,
  5971. memberName
  5972. }) {
  5973. this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {
  5974. memberName,
  5975. enumName
  5976. });
  5977. }
  5978. flowEnumErrorInvalidMemberInitializer(loc, enumContext) {
  5979. return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext);
  5980. }
  5981. flowEnumErrorNumberMemberNotInitialized(loc, details) {
  5982. this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);
  5983. }
  5984. flowEnumErrorStringMemberInconsistentlyInitialized(node, details) {
  5985. this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details);
  5986. }
  5987. flowEnumMemberInit() {
  5988. const startLoc = this.state.startLoc;
  5989. const endOfInit = () => this.match(12) || this.match(8);
  5990. switch (this.state.type) {
  5991. case 135:
  5992. {
  5993. const literal = this.parseNumericLiteral(this.state.value);
  5994. if (endOfInit()) {
  5995. return {
  5996. type: "number",
  5997. loc: literal.loc.start,
  5998. value: literal
  5999. };
  6000. }
  6001. return {
  6002. type: "invalid",
  6003. loc: startLoc
  6004. };
  6005. }
  6006. case 134:
  6007. {
  6008. const literal = this.parseStringLiteral(this.state.value);
  6009. if (endOfInit()) {
  6010. return {
  6011. type: "string",
  6012. loc: literal.loc.start,
  6013. value: literal
  6014. };
  6015. }
  6016. return {
  6017. type: "invalid",
  6018. loc: startLoc
  6019. };
  6020. }
  6021. case 85:
  6022. case 86:
  6023. {
  6024. const literal = this.parseBooleanLiteral(this.match(85));
  6025. if (endOfInit()) {
  6026. return {
  6027. type: "boolean",
  6028. loc: literal.loc.start,
  6029. value: literal
  6030. };
  6031. }
  6032. return {
  6033. type: "invalid",
  6034. loc: startLoc
  6035. };
  6036. }
  6037. default:
  6038. return {
  6039. type: "invalid",
  6040. loc: startLoc
  6041. };
  6042. }
  6043. }
  6044. flowEnumMemberRaw() {
  6045. const loc = this.state.startLoc;
  6046. const id = this.parseIdentifier(true);
  6047. const init = this.eat(29) ? this.flowEnumMemberInit() : {
  6048. type: "none",
  6049. loc
  6050. };
  6051. return {
  6052. id,
  6053. init
  6054. };
  6055. }
  6056. flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) {
  6057. const {
  6058. explicitType
  6059. } = context;
  6060. if (explicitType === null) {
  6061. return;
  6062. }
  6063. if (explicitType !== expectedType) {
  6064. this.flowEnumErrorInvalidMemberInitializer(loc, context);
  6065. }
  6066. }
  6067. flowEnumMembers({
  6068. enumName,
  6069. explicitType
  6070. }) {
  6071. const seenNames = new Set();
  6072. const members = {
  6073. booleanMembers: [],
  6074. numberMembers: [],
  6075. stringMembers: [],
  6076. defaultedMembers: []
  6077. };
  6078. let hasUnknownMembers = false;
  6079. while (!this.match(8)) {
  6080. if (this.eat(21)) {
  6081. hasUnknownMembers = true;
  6082. break;
  6083. }
  6084. const memberNode = this.startNode();
  6085. const {
  6086. id,
  6087. init
  6088. } = this.flowEnumMemberRaw();
  6089. const memberName = id.name;
  6090. if (memberName === "") {
  6091. continue;
  6092. }
  6093. if (/^[a-z]/.test(memberName)) {
  6094. this.raise(FlowErrors.EnumInvalidMemberName, id, {
  6095. memberName,
  6096. suggestion: memberName[0].toUpperCase() + memberName.slice(1),
  6097. enumName
  6098. });
  6099. }
  6100. if (seenNames.has(memberName)) {
  6101. this.raise(FlowErrors.EnumDuplicateMemberName, id, {
  6102. memberName,
  6103. enumName
  6104. });
  6105. }
  6106. seenNames.add(memberName);
  6107. const context = {
  6108. enumName,
  6109. explicitType,
  6110. memberName
  6111. };
  6112. memberNode.id = id;
  6113. switch (init.type) {
  6114. case "boolean":
  6115. {
  6116. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean");
  6117. memberNode.init = init.value;
  6118. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  6119. break;
  6120. }
  6121. case "number":
  6122. {
  6123. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number");
  6124. memberNode.init = init.value;
  6125. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  6126. break;
  6127. }
  6128. case "string":
  6129. {
  6130. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string");
  6131. memberNode.init = init.value;
  6132. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  6133. break;
  6134. }
  6135. case "invalid":
  6136. {
  6137. throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);
  6138. }
  6139. case "none":
  6140. {
  6141. switch (explicitType) {
  6142. case "boolean":
  6143. this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context);
  6144. break;
  6145. case "number":
  6146. this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);
  6147. break;
  6148. default:
  6149. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  6150. }
  6151. }
  6152. }
  6153. if (!this.match(8)) {
  6154. this.expect(12);
  6155. }
  6156. }
  6157. return {
  6158. members,
  6159. hasUnknownMembers
  6160. };
  6161. }
  6162. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  6163. enumName
  6164. }) {
  6165. if (initializedMembers.length === 0) {
  6166. return defaultedMembers;
  6167. } else if (defaultedMembers.length === 0) {
  6168. return initializedMembers;
  6169. } else if (defaultedMembers.length > initializedMembers.length) {
  6170. for (const member of initializedMembers) {
  6171. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  6172. enumName
  6173. });
  6174. }
  6175. return defaultedMembers;
  6176. } else {
  6177. for (const member of defaultedMembers) {
  6178. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  6179. enumName
  6180. });
  6181. }
  6182. return initializedMembers;
  6183. }
  6184. }
  6185. flowEnumParseExplicitType({
  6186. enumName
  6187. }) {
  6188. if (!this.eatContextual(102)) return null;
  6189. if (!tokenIsIdentifier(this.state.type)) {
  6190. throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, {
  6191. enumName
  6192. });
  6193. }
  6194. const {
  6195. value
  6196. } = this.state;
  6197. this.next();
  6198. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  6199. this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {
  6200. enumName,
  6201. invalidEnumType: value
  6202. });
  6203. }
  6204. return value;
  6205. }
  6206. flowEnumBody(node, id) {
  6207. const enumName = id.name;
  6208. const nameLoc = id.loc.start;
  6209. const explicitType = this.flowEnumParseExplicitType({
  6210. enumName
  6211. });
  6212. this.expect(5);
  6213. const {
  6214. members,
  6215. hasUnknownMembers
  6216. } = this.flowEnumMembers({
  6217. enumName,
  6218. explicitType
  6219. });
  6220. node.hasUnknownMembers = hasUnknownMembers;
  6221. switch (explicitType) {
  6222. case "boolean":
  6223. node.explicitType = true;
  6224. node.members = members.booleanMembers;
  6225. this.expect(8);
  6226. return this.finishNode(node, "EnumBooleanBody");
  6227. case "number":
  6228. node.explicitType = true;
  6229. node.members = members.numberMembers;
  6230. this.expect(8);
  6231. return this.finishNode(node, "EnumNumberBody");
  6232. case "string":
  6233. node.explicitType = true;
  6234. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6235. enumName
  6236. });
  6237. this.expect(8);
  6238. return this.finishNode(node, "EnumStringBody");
  6239. case "symbol":
  6240. node.members = members.defaultedMembers;
  6241. this.expect(8);
  6242. return this.finishNode(node, "EnumSymbolBody");
  6243. default:
  6244. {
  6245. const empty = () => {
  6246. node.members = [];
  6247. this.expect(8);
  6248. return this.finishNode(node, "EnumStringBody");
  6249. };
  6250. node.explicitType = false;
  6251. const boolsLen = members.booleanMembers.length;
  6252. const numsLen = members.numberMembers.length;
  6253. const strsLen = members.stringMembers.length;
  6254. const defaultedLen = members.defaultedMembers.length;
  6255. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  6256. return empty();
  6257. } else if (!boolsLen && !numsLen) {
  6258. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6259. enumName
  6260. });
  6261. this.expect(8);
  6262. return this.finishNode(node, "EnumStringBody");
  6263. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  6264. for (const member of members.defaultedMembers) {
  6265. this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {
  6266. enumName,
  6267. memberName: member.id.name
  6268. });
  6269. }
  6270. node.members = members.booleanMembers;
  6271. this.expect(8);
  6272. return this.finishNode(node, "EnumBooleanBody");
  6273. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  6274. for (const member of members.defaultedMembers) {
  6275. this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {
  6276. enumName,
  6277. memberName: member.id.name
  6278. });
  6279. }
  6280. node.members = members.numberMembers;
  6281. this.expect(8);
  6282. return this.finishNode(node, "EnumNumberBody");
  6283. } else {
  6284. this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {
  6285. enumName
  6286. });
  6287. return empty();
  6288. }
  6289. }
  6290. }
  6291. }
  6292. flowParseEnumDeclaration(node) {
  6293. const id = this.parseIdentifier();
  6294. node.id = id;
  6295. node.body = this.flowEnumBody(this.startNode(), id);
  6296. return this.finishNode(node, "EnumDeclaration");
  6297. }
  6298. jsxParseOpeningElementAfterName(node) {
  6299. if (this.shouldParseTypes()) {
  6300. if (this.match(47) || this.match(51)) {
  6301. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  6302. }
  6303. }
  6304. return super.jsxParseOpeningElementAfterName(node);
  6305. }
  6306. isLookaheadToken_lt() {
  6307. const next = this.nextTokenStart();
  6308. if (this.input.charCodeAt(next) === 60) {
  6309. const afterNext = this.input.charCodeAt(next + 1);
  6310. return afterNext !== 60 && afterNext !== 61;
  6311. }
  6312. return false;
  6313. }
  6314. reScan_lt_gt() {
  6315. const {
  6316. type
  6317. } = this.state;
  6318. if (type === 47) {
  6319. this.state.pos -= 1;
  6320. this.readToken_lt();
  6321. } else if (type === 48) {
  6322. this.state.pos -= 1;
  6323. this.readToken_gt();
  6324. }
  6325. }
  6326. reScan_lt() {
  6327. const {
  6328. type
  6329. } = this.state;
  6330. if (type === 51) {
  6331. this.state.pos -= 2;
  6332. this.finishOp(47, 1);
  6333. return 47;
  6334. }
  6335. return type;
  6336. }
  6337. maybeUnwrapTypeCastExpression(node) {
  6338. return node.type === "TypeCastExpression" ? node.expression : node;
  6339. }
  6340. };
  6341. const entities = {
  6342. __proto__: null,
  6343. quot: "\u0022",
  6344. amp: "&",
  6345. apos: "\u0027",
  6346. lt: "<",
  6347. gt: ">",
  6348. nbsp: "\u00A0",
  6349. iexcl: "\u00A1",
  6350. cent: "\u00A2",
  6351. pound: "\u00A3",
  6352. curren: "\u00A4",
  6353. yen: "\u00A5",
  6354. brvbar: "\u00A6",
  6355. sect: "\u00A7",
  6356. uml: "\u00A8",
  6357. copy: "\u00A9",
  6358. ordf: "\u00AA",
  6359. laquo: "\u00AB",
  6360. not: "\u00AC",
  6361. shy: "\u00AD",
  6362. reg: "\u00AE",
  6363. macr: "\u00AF",
  6364. deg: "\u00B0",
  6365. plusmn: "\u00B1",
  6366. sup2: "\u00B2",
  6367. sup3: "\u00B3",
  6368. acute: "\u00B4",
  6369. micro: "\u00B5",
  6370. para: "\u00B6",
  6371. middot: "\u00B7",
  6372. cedil: "\u00B8",
  6373. sup1: "\u00B9",
  6374. ordm: "\u00BA",
  6375. raquo: "\u00BB",
  6376. frac14: "\u00BC",
  6377. frac12: "\u00BD",
  6378. frac34: "\u00BE",
  6379. iquest: "\u00BF",
  6380. Agrave: "\u00C0",
  6381. Aacute: "\u00C1",
  6382. Acirc: "\u00C2",
  6383. Atilde: "\u00C3",
  6384. Auml: "\u00C4",
  6385. Aring: "\u00C5",
  6386. AElig: "\u00C6",
  6387. Ccedil: "\u00C7",
  6388. Egrave: "\u00C8",
  6389. Eacute: "\u00C9",
  6390. Ecirc: "\u00CA",
  6391. Euml: "\u00CB",
  6392. Igrave: "\u00CC",
  6393. Iacute: "\u00CD",
  6394. Icirc: "\u00CE",
  6395. Iuml: "\u00CF",
  6396. ETH: "\u00D0",
  6397. Ntilde: "\u00D1",
  6398. Ograve: "\u00D2",
  6399. Oacute: "\u00D3",
  6400. Ocirc: "\u00D4",
  6401. Otilde: "\u00D5",
  6402. Ouml: "\u00D6",
  6403. times: "\u00D7",
  6404. Oslash: "\u00D8",
  6405. Ugrave: "\u00D9",
  6406. Uacute: "\u00DA",
  6407. Ucirc: "\u00DB",
  6408. Uuml: "\u00DC",
  6409. Yacute: "\u00DD",
  6410. THORN: "\u00DE",
  6411. szlig: "\u00DF",
  6412. agrave: "\u00E0",
  6413. aacute: "\u00E1",
  6414. acirc: "\u00E2",
  6415. atilde: "\u00E3",
  6416. auml: "\u00E4",
  6417. aring: "\u00E5",
  6418. aelig: "\u00E6",
  6419. ccedil: "\u00E7",
  6420. egrave: "\u00E8",
  6421. eacute: "\u00E9",
  6422. ecirc: "\u00EA",
  6423. euml: "\u00EB",
  6424. igrave: "\u00EC",
  6425. iacute: "\u00ED",
  6426. icirc: "\u00EE",
  6427. iuml: "\u00EF",
  6428. eth: "\u00F0",
  6429. ntilde: "\u00F1",
  6430. ograve: "\u00F2",
  6431. oacute: "\u00F3",
  6432. ocirc: "\u00F4",
  6433. otilde: "\u00F5",
  6434. ouml: "\u00F6",
  6435. divide: "\u00F7",
  6436. oslash: "\u00F8",
  6437. ugrave: "\u00F9",
  6438. uacute: "\u00FA",
  6439. ucirc: "\u00FB",
  6440. uuml: "\u00FC",
  6441. yacute: "\u00FD",
  6442. thorn: "\u00FE",
  6443. yuml: "\u00FF",
  6444. OElig: "\u0152",
  6445. oelig: "\u0153",
  6446. Scaron: "\u0160",
  6447. scaron: "\u0161",
  6448. Yuml: "\u0178",
  6449. fnof: "\u0192",
  6450. circ: "\u02C6",
  6451. tilde: "\u02DC",
  6452. Alpha: "\u0391",
  6453. Beta: "\u0392",
  6454. Gamma: "\u0393",
  6455. Delta: "\u0394",
  6456. Epsilon: "\u0395",
  6457. Zeta: "\u0396",
  6458. Eta: "\u0397",
  6459. Theta: "\u0398",
  6460. Iota: "\u0399",
  6461. Kappa: "\u039A",
  6462. Lambda: "\u039B",
  6463. Mu: "\u039C",
  6464. Nu: "\u039D",
  6465. Xi: "\u039E",
  6466. Omicron: "\u039F",
  6467. Pi: "\u03A0",
  6468. Rho: "\u03A1",
  6469. Sigma: "\u03A3",
  6470. Tau: "\u03A4",
  6471. Upsilon: "\u03A5",
  6472. Phi: "\u03A6",
  6473. Chi: "\u03A7",
  6474. Psi: "\u03A8",
  6475. Omega: "\u03A9",
  6476. alpha: "\u03B1",
  6477. beta: "\u03B2",
  6478. gamma: "\u03B3",
  6479. delta: "\u03B4",
  6480. epsilon: "\u03B5",
  6481. zeta: "\u03B6",
  6482. eta: "\u03B7",
  6483. theta: "\u03B8",
  6484. iota: "\u03B9",
  6485. kappa: "\u03BA",
  6486. lambda: "\u03BB",
  6487. mu: "\u03BC",
  6488. nu: "\u03BD",
  6489. xi: "\u03BE",
  6490. omicron: "\u03BF",
  6491. pi: "\u03C0",
  6492. rho: "\u03C1",
  6493. sigmaf: "\u03C2",
  6494. sigma: "\u03C3",
  6495. tau: "\u03C4",
  6496. upsilon: "\u03C5",
  6497. phi: "\u03C6",
  6498. chi: "\u03C7",
  6499. psi: "\u03C8",
  6500. omega: "\u03C9",
  6501. thetasym: "\u03D1",
  6502. upsih: "\u03D2",
  6503. piv: "\u03D6",
  6504. ensp: "\u2002",
  6505. emsp: "\u2003",
  6506. thinsp: "\u2009",
  6507. zwnj: "\u200C",
  6508. zwj: "\u200D",
  6509. lrm: "\u200E",
  6510. rlm: "\u200F",
  6511. ndash: "\u2013",
  6512. mdash: "\u2014",
  6513. lsquo: "\u2018",
  6514. rsquo: "\u2019",
  6515. sbquo: "\u201A",
  6516. ldquo: "\u201C",
  6517. rdquo: "\u201D",
  6518. bdquo: "\u201E",
  6519. dagger: "\u2020",
  6520. Dagger: "\u2021",
  6521. bull: "\u2022",
  6522. hellip: "\u2026",
  6523. permil: "\u2030",
  6524. prime: "\u2032",
  6525. Prime: "\u2033",
  6526. lsaquo: "\u2039",
  6527. rsaquo: "\u203A",
  6528. oline: "\u203E",
  6529. frasl: "\u2044",
  6530. euro: "\u20AC",
  6531. image: "\u2111",
  6532. weierp: "\u2118",
  6533. real: "\u211C",
  6534. trade: "\u2122",
  6535. alefsym: "\u2135",
  6536. larr: "\u2190",
  6537. uarr: "\u2191",
  6538. rarr: "\u2192",
  6539. darr: "\u2193",
  6540. harr: "\u2194",
  6541. crarr: "\u21B5",
  6542. lArr: "\u21D0",
  6543. uArr: "\u21D1",
  6544. rArr: "\u21D2",
  6545. dArr: "\u21D3",
  6546. hArr: "\u21D4",
  6547. forall: "\u2200",
  6548. part: "\u2202",
  6549. exist: "\u2203",
  6550. empty: "\u2205",
  6551. nabla: "\u2207",
  6552. isin: "\u2208",
  6553. notin: "\u2209",
  6554. ni: "\u220B",
  6555. prod: "\u220F",
  6556. sum: "\u2211",
  6557. minus: "\u2212",
  6558. lowast: "\u2217",
  6559. radic: "\u221A",
  6560. prop: "\u221D",
  6561. infin: "\u221E",
  6562. ang: "\u2220",
  6563. and: "\u2227",
  6564. or: "\u2228",
  6565. cap: "\u2229",
  6566. cup: "\u222A",
  6567. int: "\u222B",
  6568. there4: "\u2234",
  6569. sim: "\u223C",
  6570. cong: "\u2245",
  6571. asymp: "\u2248",
  6572. ne: "\u2260",
  6573. equiv: "\u2261",
  6574. le: "\u2264",
  6575. ge: "\u2265",
  6576. sub: "\u2282",
  6577. sup: "\u2283",
  6578. nsub: "\u2284",
  6579. sube: "\u2286",
  6580. supe: "\u2287",
  6581. oplus: "\u2295",
  6582. otimes: "\u2297",
  6583. perp: "\u22A5",
  6584. sdot: "\u22C5",
  6585. lceil: "\u2308",
  6586. rceil: "\u2309",
  6587. lfloor: "\u230A",
  6588. rfloor: "\u230B",
  6589. lang: "\u2329",
  6590. rang: "\u232A",
  6591. loz: "\u25CA",
  6592. spades: "\u2660",
  6593. clubs: "\u2663",
  6594. hearts: "\u2665",
  6595. diams: "\u2666"
  6596. };
  6597. const JsxErrors = ParseErrorEnum`jsx`({
  6598. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  6599. MissingClosingTagElement: ({
  6600. openingTagName
  6601. }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`,
  6602. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  6603. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  6604. UnexpectedToken: ({
  6605. unexpected,
  6606. HTMLEntity
  6607. }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,
  6608. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  6609. UnterminatedJsxContent: "Unterminated JSX contents.",
  6610. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  6611. });
  6612. function isFragment(object) {
  6613. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  6614. }
  6615. function getQualifiedJSXName(object) {
  6616. if (object.type === "JSXIdentifier") {
  6617. return object.name;
  6618. }
  6619. if (object.type === "JSXNamespacedName") {
  6620. return object.namespace.name + ":" + object.name.name;
  6621. }
  6622. if (object.type === "JSXMemberExpression") {
  6623. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  6624. }
  6625. throw new Error("Node had unexpected type: " + object.type);
  6626. }
  6627. var jsx = superClass => class JSXParserMixin extends superClass {
  6628. jsxReadToken() {
  6629. let out = "";
  6630. let chunkStart = this.state.pos;
  6631. for (;;) {
  6632. if (this.state.pos >= this.length) {
  6633. throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc);
  6634. }
  6635. const ch = this.input.charCodeAt(this.state.pos);
  6636. switch (ch) {
  6637. case 60:
  6638. case 123:
  6639. if (this.state.pos === this.state.start) {
  6640. if (ch === 60 && this.state.canStartJSXElement) {
  6641. ++this.state.pos;
  6642. this.finishToken(143);
  6643. } else {
  6644. super.getTokenFromCode(ch);
  6645. }
  6646. return;
  6647. }
  6648. out += this.input.slice(chunkStart, this.state.pos);
  6649. this.finishToken(142, out);
  6650. return;
  6651. case 38:
  6652. out += this.input.slice(chunkStart, this.state.pos);
  6653. out += this.jsxReadEntity();
  6654. chunkStart = this.state.pos;
  6655. break;
  6656. case 62:
  6657. case 125:
  6658. default:
  6659. if (isNewLine(ch)) {
  6660. out += this.input.slice(chunkStart, this.state.pos);
  6661. out += this.jsxReadNewLine(true);
  6662. chunkStart = this.state.pos;
  6663. } else {
  6664. ++this.state.pos;
  6665. }
  6666. }
  6667. }
  6668. }
  6669. jsxReadNewLine(normalizeCRLF) {
  6670. const ch = this.input.charCodeAt(this.state.pos);
  6671. let out;
  6672. ++this.state.pos;
  6673. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  6674. ++this.state.pos;
  6675. out = normalizeCRLF ? "\n" : "\r\n";
  6676. } else {
  6677. out = String.fromCharCode(ch);
  6678. }
  6679. ++this.state.curLine;
  6680. this.state.lineStart = this.state.pos;
  6681. return out;
  6682. }
  6683. jsxReadString(quote) {
  6684. let out = "";
  6685. let chunkStart = ++this.state.pos;
  6686. for (;;) {
  6687. if (this.state.pos >= this.length) {
  6688. throw this.raise(Errors.UnterminatedString, this.state.startLoc);
  6689. }
  6690. const ch = this.input.charCodeAt(this.state.pos);
  6691. if (ch === quote) break;
  6692. if (ch === 38) {
  6693. out += this.input.slice(chunkStart, this.state.pos);
  6694. out += this.jsxReadEntity();
  6695. chunkStart = this.state.pos;
  6696. } else if (isNewLine(ch)) {
  6697. out += this.input.slice(chunkStart, this.state.pos);
  6698. out += this.jsxReadNewLine(false);
  6699. chunkStart = this.state.pos;
  6700. } else {
  6701. ++this.state.pos;
  6702. }
  6703. }
  6704. out += this.input.slice(chunkStart, this.state.pos++);
  6705. this.finishToken(134, out);
  6706. }
  6707. jsxReadEntity() {
  6708. const startPos = ++this.state.pos;
  6709. if (this.codePointAtPos(this.state.pos) === 35) {
  6710. ++this.state.pos;
  6711. let radix = 10;
  6712. if (this.codePointAtPos(this.state.pos) === 120) {
  6713. radix = 16;
  6714. ++this.state.pos;
  6715. }
  6716. const codePoint = this.readInt(radix, undefined, false, "bail");
  6717. if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) {
  6718. ++this.state.pos;
  6719. return String.fromCodePoint(codePoint);
  6720. }
  6721. } else {
  6722. let count = 0;
  6723. let semi = false;
  6724. while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) {
  6725. ++this.state.pos;
  6726. }
  6727. if (semi) {
  6728. const desc = this.input.slice(startPos, this.state.pos);
  6729. const entity = entities[desc];
  6730. ++this.state.pos;
  6731. if (entity) {
  6732. return entity;
  6733. }
  6734. }
  6735. }
  6736. this.state.pos = startPos;
  6737. return "&";
  6738. }
  6739. jsxReadWord() {
  6740. let ch;
  6741. const start = this.state.pos;
  6742. do {
  6743. ch = this.input.charCodeAt(++this.state.pos);
  6744. } while (isIdentifierChar(ch) || ch === 45);
  6745. this.finishToken(141, this.input.slice(start, this.state.pos));
  6746. }
  6747. jsxParseIdentifier() {
  6748. const node = this.startNode();
  6749. if (this.match(141)) {
  6750. node.name = this.state.value;
  6751. } else if (tokenIsKeyword(this.state.type)) {
  6752. node.name = tokenLabelName(this.state.type);
  6753. } else {
  6754. this.unexpected();
  6755. }
  6756. this.next();
  6757. return this.finishNode(node, "JSXIdentifier");
  6758. }
  6759. jsxParseNamespacedName() {
  6760. const startLoc = this.state.startLoc;
  6761. const name = this.jsxParseIdentifier();
  6762. if (!this.eat(14)) return name;
  6763. const node = this.startNodeAt(startLoc);
  6764. node.namespace = name;
  6765. node.name = this.jsxParseIdentifier();
  6766. return this.finishNode(node, "JSXNamespacedName");
  6767. }
  6768. jsxParseElementName() {
  6769. const startLoc = this.state.startLoc;
  6770. let node = this.jsxParseNamespacedName();
  6771. if (node.type === "JSXNamespacedName") {
  6772. return node;
  6773. }
  6774. while (this.eat(16)) {
  6775. const newNode = this.startNodeAt(startLoc);
  6776. newNode.object = node;
  6777. newNode.property = this.jsxParseIdentifier();
  6778. node = this.finishNode(newNode, "JSXMemberExpression");
  6779. }
  6780. return node;
  6781. }
  6782. jsxParseAttributeValue() {
  6783. let node;
  6784. switch (this.state.type) {
  6785. case 5:
  6786. node = this.startNode();
  6787. this.setContext(types.brace);
  6788. this.next();
  6789. node = this.jsxParseExpressionContainer(node, types.j_oTag);
  6790. if (node.expression.type === "JSXEmptyExpression") {
  6791. this.raise(JsxErrors.AttributeIsEmpty, node);
  6792. }
  6793. return node;
  6794. case 143:
  6795. case 134:
  6796. return this.parseExprAtom();
  6797. default:
  6798. throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);
  6799. }
  6800. }
  6801. jsxParseEmptyExpression() {
  6802. const node = this.startNodeAt(this.state.lastTokEndLoc);
  6803. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc);
  6804. }
  6805. jsxParseSpreadChild(node) {
  6806. this.next();
  6807. node.expression = this.parseExpression();
  6808. this.setContext(types.j_expr);
  6809. this.state.canStartJSXElement = true;
  6810. this.expect(8);
  6811. return this.finishNode(node, "JSXSpreadChild");
  6812. }
  6813. jsxParseExpressionContainer(node, previousContext) {
  6814. if (this.match(8)) {
  6815. node.expression = this.jsxParseEmptyExpression();
  6816. } else {
  6817. const expression = this.parseExpression();
  6818. node.expression = expression;
  6819. }
  6820. this.setContext(previousContext);
  6821. this.state.canStartJSXElement = true;
  6822. this.expect(8);
  6823. return this.finishNode(node, "JSXExpressionContainer");
  6824. }
  6825. jsxParseAttribute() {
  6826. const node = this.startNode();
  6827. if (this.match(5)) {
  6828. this.setContext(types.brace);
  6829. this.next();
  6830. this.expect(21);
  6831. node.argument = this.parseMaybeAssignAllowIn();
  6832. this.setContext(types.j_oTag);
  6833. this.state.canStartJSXElement = true;
  6834. this.expect(8);
  6835. return this.finishNode(node, "JSXSpreadAttribute");
  6836. }
  6837. node.name = this.jsxParseNamespacedName();
  6838. node.value = this.eat(29) ? this.jsxParseAttributeValue() : null;
  6839. return this.finishNode(node, "JSXAttribute");
  6840. }
  6841. jsxParseOpeningElementAt(startLoc) {
  6842. const node = this.startNodeAt(startLoc);
  6843. if (this.eat(144)) {
  6844. return this.finishNode(node, "JSXOpeningFragment");
  6845. }
  6846. node.name = this.jsxParseElementName();
  6847. return this.jsxParseOpeningElementAfterName(node);
  6848. }
  6849. jsxParseOpeningElementAfterName(node) {
  6850. const attributes = [];
  6851. while (!this.match(56) && !this.match(144)) {
  6852. attributes.push(this.jsxParseAttribute());
  6853. }
  6854. node.attributes = attributes;
  6855. node.selfClosing = this.eat(56);
  6856. this.expect(144);
  6857. return this.finishNode(node, "JSXOpeningElement");
  6858. }
  6859. jsxParseClosingElementAt(startLoc) {
  6860. const node = this.startNodeAt(startLoc);
  6861. if (this.eat(144)) {
  6862. return this.finishNode(node, "JSXClosingFragment");
  6863. }
  6864. node.name = this.jsxParseElementName();
  6865. this.expect(144);
  6866. return this.finishNode(node, "JSXClosingElement");
  6867. }
  6868. jsxParseElementAt(startLoc) {
  6869. const node = this.startNodeAt(startLoc);
  6870. const children = [];
  6871. const openingElement = this.jsxParseOpeningElementAt(startLoc);
  6872. let closingElement = null;
  6873. if (!openingElement.selfClosing) {
  6874. contents: for (;;) {
  6875. switch (this.state.type) {
  6876. case 143:
  6877. startLoc = this.state.startLoc;
  6878. this.next();
  6879. if (this.eat(56)) {
  6880. closingElement = this.jsxParseClosingElementAt(startLoc);
  6881. break contents;
  6882. }
  6883. children.push(this.jsxParseElementAt(startLoc));
  6884. break;
  6885. case 142:
  6886. children.push(this.parseLiteral(this.state.value, "JSXText"));
  6887. break;
  6888. case 5:
  6889. {
  6890. const node = this.startNode();
  6891. this.setContext(types.brace);
  6892. this.next();
  6893. if (this.match(21)) {
  6894. children.push(this.jsxParseSpreadChild(node));
  6895. } else {
  6896. children.push(this.jsxParseExpressionContainer(node, types.j_expr));
  6897. }
  6898. break;
  6899. }
  6900. default:
  6901. this.unexpected();
  6902. }
  6903. }
  6904. if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) {
  6905. this.raise(JsxErrors.MissingClosingTagFragment, closingElement);
  6906. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  6907. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  6908. openingTagName: getQualifiedJSXName(openingElement.name)
  6909. });
  6910. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  6911. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  6912. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  6913. openingTagName: getQualifiedJSXName(openingElement.name)
  6914. });
  6915. }
  6916. }
  6917. }
  6918. if (isFragment(openingElement)) {
  6919. node.openingFragment = openingElement;
  6920. node.closingFragment = closingElement;
  6921. } else {
  6922. node.openingElement = openingElement;
  6923. node.closingElement = closingElement;
  6924. }
  6925. node.children = children;
  6926. if (this.match(47)) {
  6927. throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc);
  6928. }
  6929. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  6930. }
  6931. jsxParseElement() {
  6932. const startLoc = this.state.startLoc;
  6933. this.next();
  6934. return this.jsxParseElementAt(startLoc);
  6935. }
  6936. setContext(newContext) {
  6937. const {
  6938. context
  6939. } = this.state;
  6940. context[context.length - 1] = newContext;
  6941. }
  6942. parseExprAtom(refExpressionErrors) {
  6943. if (this.match(143)) {
  6944. return this.jsxParseElement();
  6945. } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) {
  6946. this.replaceToken(143);
  6947. return this.jsxParseElement();
  6948. } else {
  6949. return super.parseExprAtom(refExpressionErrors);
  6950. }
  6951. }
  6952. skipSpace() {
  6953. const curContext = this.curContext();
  6954. if (!curContext.preserveSpace) super.skipSpace();
  6955. }
  6956. getTokenFromCode(code) {
  6957. const context = this.curContext();
  6958. if (context === types.j_expr) {
  6959. this.jsxReadToken();
  6960. return;
  6961. }
  6962. if (context === types.j_oTag || context === types.j_cTag) {
  6963. if (isIdentifierStart(code)) {
  6964. this.jsxReadWord();
  6965. return;
  6966. }
  6967. if (code === 62) {
  6968. ++this.state.pos;
  6969. this.finishToken(144);
  6970. return;
  6971. }
  6972. if ((code === 34 || code === 39) && context === types.j_oTag) {
  6973. this.jsxReadString(code);
  6974. return;
  6975. }
  6976. }
  6977. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  6978. ++this.state.pos;
  6979. this.finishToken(143);
  6980. return;
  6981. }
  6982. super.getTokenFromCode(code);
  6983. }
  6984. updateContext(prevType) {
  6985. const {
  6986. context,
  6987. type
  6988. } = this.state;
  6989. if (type === 56 && prevType === 143) {
  6990. context.splice(-2, 2, types.j_cTag);
  6991. this.state.canStartJSXElement = false;
  6992. } else if (type === 143) {
  6993. context.push(types.j_oTag);
  6994. } else if (type === 144) {
  6995. const out = context[context.length - 1];
  6996. if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) {
  6997. context.pop();
  6998. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  6999. } else {
  7000. this.setContext(types.j_expr);
  7001. this.state.canStartJSXElement = true;
  7002. }
  7003. } else {
  7004. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  7005. }
  7006. }
  7007. };
  7008. class TypeScriptScope extends Scope {
  7009. constructor(...args) {
  7010. super(...args);
  7011. this.tsNames = new Map();
  7012. }
  7013. }
  7014. class TypeScriptScopeHandler extends ScopeHandler {
  7015. constructor(...args) {
  7016. super(...args);
  7017. this.importsStack = [];
  7018. }
  7019. createScope(flags) {
  7020. this.importsStack.push(new Set());
  7021. return new TypeScriptScope(flags);
  7022. }
  7023. enter(flags) {
  7024. if (flags === 256) {
  7025. this.importsStack.push(new Set());
  7026. }
  7027. super.enter(flags);
  7028. }
  7029. exit() {
  7030. const flags = super.exit();
  7031. if (flags === 256) {
  7032. this.importsStack.pop();
  7033. }
  7034. return flags;
  7035. }
  7036. hasImport(name, allowShadow) {
  7037. const len = this.importsStack.length;
  7038. if (this.importsStack[len - 1].has(name)) {
  7039. return true;
  7040. }
  7041. if (!allowShadow && len > 1) {
  7042. for (let i = 0; i < len - 1; i++) {
  7043. if (this.importsStack[i].has(name)) return true;
  7044. }
  7045. }
  7046. return false;
  7047. }
  7048. declareName(name, bindingType, loc) {
  7049. if (bindingType & 4096) {
  7050. if (this.hasImport(name, true)) {
  7051. this.parser.raise(Errors.VarRedeclaration, loc, {
  7052. identifierName: name
  7053. });
  7054. }
  7055. this.importsStack[this.importsStack.length - 1].add(name);
  7056. return;
  7057. }
  7058. const scope = this.currentScope();
  7059. let type = scope.tsNames.get(name) || 0;
  7060. if (bindingType & 1024) {
  7061. this.maybeExportDefined(scope, name);
  7062. scope.tsNames.set(name, type | 16);
  7063. return;
  7064. }
  7065. super.declareName(name, bindingType, loc);
  7066. if (bindingType & 2) {
  7067. if (!(bindingType & 1)) {
  7068. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  7069. this.maybeExportDefined(scope, name);
  7070. }
  7071. type = type | 1;
  7072. }
  7073. if (bindingType & 256) {
  7074. type = type | 2;
  7075. }
  7076. if (bindingType & 512) {
  7077. type = type | 4;
  7078. }
  7079. if (bindingType & 128) {
  7080. type = type | 8;
  7081. }
  7082. if (type) scope.tsNames.set(name, type);
  7083. }
  7084. isRedeclaredInScope(scope, name, bindingType) {
  7085. const type = scope.tsNames.get(name);
  7086. if ((type & 2) > 0) {
  7087. if (bindingType & 256) {
  7088. const isConst = !!(bindingType & 512);
  7089. const wasConst = (type & 4) > 0;
  7090. return isConst !== wasConst;
  7091. }
  7092. return true;
  7093. }
  7094. if (bindingType & 128 && (type & 8) > 0) {
  7095. if (scope.names.get(name) & 2) {
  7096. return !!(bindingType & 1);
  7097. } else {
  7098. return false;
  7099. }
  7100. }
  7101. if (bindingType & 2 && (type & 1) > 0) {
  7102. return true;
  7103. }
  7104. return super.isRedeclaredInScope(scope, name, bindingType);
  7105. }
  7106. checkLocalExport(id) {
  7107. const {
  7108. name
  7109. } = id;
  7110. if (this.hasImport(name)) return;
  7111. const len = this.scopeStack.length;
  7112. for (let i = len - 1; i >= 0; i--) {
  7113. const scope = this.scopeStack[i];
  7114. const type = scope.tsNames.get(name);
  7115. if ((type & 1) > 0 || (type & 16) > 0) {
  7116. return;
  7117. }
  7118. }
  7119. super.checkLocalExport(id);
  7120. }
  7121. }
  7122. const unwrapParenthesizedExpression = node => {
  7123. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7124. };
  7125. class LValParser extends NodeUtils {
  7126. toAssignable(node, isLHS = false) {
  7127. var _node$extra, _node$extra3;
  7128. let parenthesized = undefined;
  7129. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  7130. parenthesized = unwrapParenthesizedExpression(node);
  7131. if (isLHS) {
  7132. if (parenthesized.type === "Identifier") {
  7133. this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node);
  7134. } else if (parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) {
  7135. this.raise(Errors.InvalidParenthesizedAssignment, node);
  7136. }
  7137. } else {
  7138. this.raise(Errors.InvalidParenthesizedAssignment, node);
  7139. }
  7140. }
  7141. switch (node.type) {
  7142. case "Identifier":
  7143. case "ObjectPattern":
  7144. case "ArrayPattern":
  7145. case "AssignmentPattern":
  7146. case "RestElement":
  7147. break;
  7148. case "ObjectExpression":
  7149. node.type = "ObjectPattern";
  7150. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7151. var _node$extra2;
  7152. const prop = node.properties[i];
  7153. const isLast = i === last;
  7154. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  7155. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) {
  7156. this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc);
  7157. }
  7158. }
  7159. break;
  7160. case "ObjectProperty":
  7161. {
  7162. const {
  7163. key,
  7164. value
  7165. } = node;
  7166. if (this.isPrivateName(key)) {
  7167. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  7168. }
  7169. this.toAssignable(value, isLHS);
  7170. break;
  7171. }
  7172. case "SpreadElement":
  7173. {
  7174. throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller.");
  7175. }
  7176. case "ArrayExpression":
  7177. node.type = "ArrayPattern";
  7178. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS);
  7179. break;
  7180. case "AssignmentExpression":
  7181. if (node.operator !== "=") {
  7182. this.raise(Errors.MissingEqInAssignment, node.left.loc.end);
  7183. }
  7184. node.type = "AssignmentPattern";
  7185. delete node.operator;
  7186. this.toAssignable(node.left, isLHS);
  7187. break;
  7188. case "ParenthesizedExpression":
  7189. this.toAssignable(parenthesized, isLHS);
  7190. break;
  7191. }
  7192. }
  7193. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  7194. if (prop.type === "ObjectMethod") {
  7195. this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key);
  7196. } else if (prop.type === "SpreadElement") {
  7197. prop.type = "RestElement";
  7198. const arg = prop.argument;
  7199. this.checkToRestConversion(arg, false);
  7200. this.toAssignable(arg, isLHS);
  7201. if (!isLast) {
  7202. this.raise(Errors.RestTrailingComma, prop);
  7203. }
  7204. } else {
  7205. this.toAssignable(prop, isLHS);
  7206. }
  7207. }
  7208. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  7209. const end = exprList.length - 1;
  7210. for (let i = 0; i <= end; i++) {
  7211. const elt = exprList[i];
  7212. if (!elt) continue;
  7213. this.toAssignableListItem(exprList, i, isLHS);
  7214. if (elt.type === "RestElement") {
  7215. if (i < end) {
  7216. this.raise(Errors.RestTrailingComma, elt);
  7217. } else if (trailingCommaLoc) {
  7218. this.raise(Errors.RestTrailingComma, trailingCommaLoc);
  7219. }
  7220. }
  7221. }
  7222. }
  7223. toAssignableListItem(exprList, index, isLHS) {
  7224. const node = exprList[index];
  7225. if (node.type === "SpreadElement") {
  7226. node.type = "RestElement";
  7227. const arg = node.argument;
  7228. this.checkToRestConversion(arg, true);
  7229. this.toAssignable(arg, isLHS);
  7230. } else {
  7231. this.toAssignable(node, isLHS);
  7232. }
  7233. }
  7234. isAssignable(node, isBinding) {
  7235. switch (node.type) {
  7236. case "Identifier":
  7237. case "ObjectPattern":
  7238. case "ArrayPattern":
  7239. case "AssignmentPattern":
  7240. case "RestElement":
  7241. return true;
  7242. case "ObjectExpression":
  7243. {
  7244. const last = node.properties.length - 1;
  7245. return node.properties.every((prop, i) => {
  7246. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  7247. });
  7248. }
  7249. case "ObjectProperty":
  7250. return this.isAssignable(node.value);
  7251. case "SpreadElement":
  7252. return this.isAssignable(node.argument);
  7253. case "ArrayExpression":
  7254. return node.elements.every(element => element === null || this.isAssignable(element));
  7255. case "AssignmentExpression":
  7256. return node.operator === "=";
  7257. case "ParenthesizedExpression":
  7258. return this.isAssignable(node.expression);
  7259. case "MemberExpression":
  7260. case "OptionalMemberExpression":
  7261. return !isBinding;
  7262. default:
  7263. return false;
  7264. }
  7265. }
  7266. toReferencedList(exprList, isParenthesizedExpr) {
  7267. return exprList;
  7268. }
  7269. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7270. this.toReferencedList(exprList, isParenthesizedExpr);
  7271. for (const expr of exprList) {
  7272. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  7273. this.toReferencedListDeep(expr.elements);
  7274. }
  7275. }
  7276. }
  7277. parseSpread(refExpressionErrors) {
  7278. const node = this.startNode();
  7279. this.next();
  7280. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined);
  7281. return this.finishNode(node, "SpreadElement");
  7282. }
  7283. parseRestBinding() {
  7284. const node = this.startNode();
  7285. this.next();
  7286. node.argument = this.parseBindingAtom();
  7287. return this.finishNode(node, "RestElement");
  7288. }
  7289. parseBindingAtom() {
  7290. switch (this.state.type) {
  7291. case 0:
  7292. {
  7293. const node = this.startNode();
  7294. this.next();
  7295. node.elements = this.parseBindingList(3, 93, 1);
  7296. return this.finishNode(node, "ArrayPattern");
  7297. }
  7298. case 5:
  7299. return this.parseObjectLike(8, true);
  7300. }
  7301. return this.parseIdentifier();
  7302. }
  7303. parseBindingList(close, closeCharCode, flags) {
  7304. const allowEmpty = flags & 1;
  7305. const elts = [];
  7306. let first = true;
  7307. while (!this.eat(close)) {
  7308. if (first) {
  7309. first = false;
  7310. } else {
  7311. this.expect(12);
  7312. }
  7313. if (allowEmpty && this.match(12)) {
  7314. elts.push(null);
  7315. } else if (this.eat(close)) {
  7316. break;
  7317. } else if (this.match(21)) {
  7318. let rest = this.parseRestBinding();
  7319. if (this.hasPlugin("flow") || flags & 2) {
  7320. rest = this.parseFunctionParamType(rest);
  7321. }
  7322. elts.push(rest);
  7323. if (!this.checkCommaAfterRest(closeCharCode)) {
  7324. this.expect(close);
  7325. break;
  7326. }
  7327. } else {
  7328. const decorators = [];
  7329. if (flags & 2) {
  7330. if (this.match(26) && this.hasPlugin("decorators")) {
  7331. this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc);
  7332. }
  7333. while (this.match(26)) {
  7334. decorators.push(this.parseDecorator());
  7335. }
  7336. }
  7337. elts.push(this.parseBindingElement(flags, decorators));
  7338. }
  7339. }
  7340. return elts;
  7341. }
  7342. parseBindingRestProperty(prop) {
  7343. this.next();
  7344. prop.argument = this.parseIdentifier();
  7345. this.checkCommaAfterRest(125);
  7346. return this.finishNode(prop, "RestElement");
  7347. }
  7348. parseBindingProperty() {
  7349. const {
  7350. type,
  7351. startLoc
  7352. } = this.state;
  7353. if (type === 21) {
  7354. return this.parseBindingRestProperty(this.startNode());
  7355. }
  7356. const prop = this.startNode();
  7357. if (type === 139) {
  7358. this.expectPlugin("destructuringPrivate", startLoc);
  7359. this.classScope.usePrivateName(this.state.value, startLoc);
  7360. prop.key = this.parsePrivateName();
  7361. } else {
  7362. this.parsePropertyName(prop);
  7363. }
  7364. prop.method = false;
  7365. return this.parseObjPropValue(prop, startLoc, false, false, true, false);
  7366. }
  7367. parseBindingElement(flags, decorators) {
  7368. const left = this.parseMaybeDefault();
  7369. if (this.hasPlugin("flow") || flags & 2) {
  7370. this.parseFunctionParamType(left);
  7371. }
  7372. const elt = this.parseMaybeDefault(left.loc.start, left);
  7373. if (decorators.length) {
  7374. left.decorators = decorators;
  7375. }
  7376. return elt;
  7377. }
  7378. parseFunctionParamType(param) {
  7379. return param;
  7380. }
  7381. parseMaybeDefault(startLoc, left) {
  7382. startLoc != null ? startLoc : startLoc = this.state.startLoc;
  7383. left = left != null ? left : this.parseBindingAtom();
  7384. if (!this.eat(29)) return left;
  7385. const node = this.startNodeAt(startLoc);
  7386. node.left = left;
  7387. node.right = this.parseMaybeAssignAllowIn();
  7388. return this.finishNode(node, "AssignmentPattern");
  7389. }
  7390. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  7391. switch (type) {
  7392. case "AssignmentPattern":
  7393. return "left";
  7394. case "RestElement":
  7395. return "argument";
  7396. case "ObjectProperty":
  7397. return "value";
  7398. case "ParenthesizedExpression":
  7399. return "expression";
  7400. case "ArrayPattern":
  7401. return "elements";
  7402. case "ObjectPattern":
  7403. return "properties";
  7404. }
  7405. return false;
  7406. }
  7407. isOptionalMemberExpression(expression) {
  7408. return expression.type === "OptionalMemberExpression";
  7409. }
  7410. checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false) {
  7411. var _expression$extra;
  7412. const type = expression.type;
  7413. if (this.isObjectMethod(expression)) return;
  7414. const isOptionalMemberExpression = this.isOptionalMemberExpression(expression);
  7415. if (isOptionalMemberExpression || type === "MemberExpression") {
  7416. if (isOptionalMemberExpression) {
  7417. this.expectPlugin("optionalChainingAssign", expression.loc.start);
  7418. if (ancestor.type !== "AssignmentExpression") {
  7419. this.raise(Errors.InvalidLhsOptionalChaining, expression, {
  7420. ancestor
  7421. });
  7422. }
  7423. }
  7424. if (binding !== 64) {
  7425. this.raise(Errors.InvalidPropertyBindingPattern, expression);
  7426. }
  7427. return;
  7428. }
  7429. if (type === "Identifier") {
  7430. this.checkIdentifier(expression, binding, strictModeChanged);
  7431. const {
  7432. name
  7433. } = expression;
  7434. if (checkClashes) {
  7435. if (checkClashes.has(name)) {
  7436. this.raise(Errors.ParamDupe, expression);
  7437. } else {
  7438. checkClashes.add(name);
  7439. }
  7440. }
  7441. return;
  7442. }
  7443. const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
  7444. if (validity === true) return;
  7445. if (validity === false) {
  7446. const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
  7447. this.raise(ParseErrorClass, expression, {
  7448. ancestor
  7449. });
  7450. return;
  7451. }
  7452. let key, isParenthesizedExpression;
  7453. if (typeof validity === "string") {
  7454. key = validity;
  7455. isParenthesizedExpression = type === "ParenthesizedExpression";
  7456. } else {
  7457. [key, isParenthesizedExpression] = validity;
  7458. }
  7459. const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? {
  7460. type
  7461. } : ancestor;
  7462. const val = expression[key];
  7463. if (Array.isArray(val)) {
  7464. for (const child of val) {
  7465. if (child) {
  7466. this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression);
  7467. }
  7468. }
  7469. } else if (val) {
  7470. this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression);
  7471. }
  7472. }
  7473. checkIdentifier(at, bindingType, strictModeChanged = false) {
  7474. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) {
  7475. if (bindingType === 64) {
  7476. this.raise(Errors.StrictEvalArguments, at, {
  7477. referenceName: at.name
  7478. });
  7479. } else {
  7480. this.raise(Errors.StrictEvalArgumentsBinding, at, {
  7481. bindingName: at.name
  7482. });
  7483. }
  7484. }
  7485. if (bindingType & 8192 && at.name === "let") {
  7486. this.raise(Errors.LetInLexicalBinding, at);
  7487. }
  7488. if (!(bindingType & 64)) {
  7489. this.declareNameFromIdentifier(at, bindingType);
  7490. }
  7491. }
  7492. declareNameFromIdentifier(identifier, binding) {
  7493. this.scope.declareName(identifier.name, binding, identifier.loc.start);
  7494. }
  7495. checkToRestConversion(node, allowPattern) {
  7496. switch (node.type) {
  7497. case "ParenthesizedExpression":
  7498. this.checkToRestConversion(node.expression, allowPattern);
  7499. break;
  7500. case "Identifier":
  7501. case "MemberExpression":
  7502. break;
  7503. case "ArrayExpression":
  7504. case "ObjectExpression":
  7505. if (allowPattern) break;
  7506. default:
  7507. this.raise(Errors.InvalidRestAssignmentPattern, node);
  7508. }
  7509. }
  7510. checkCommaAfterRest(close) {
  7511. if (!this.match(12)) {
  7512. return false;
  7513. }
  7514. this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc);
  7515. return true;
  7516. }
  7517. }
  7518. function nonNull(x) {
  7519. if (x == null) {
  7520. throw new Error(`Unexpected ${x} value.`);
  7521. }
  7522. return x;
  7523. }
  7524. function assert(x) {
  7525. if (!x) {
  7526. throw new Error("Assert fail");
  7527. }
  7528. }
  7529. const TSErrors = ParseErrorEnum`typescript`({
  7530. AbstractMethodHasImplementation: ({
  7531. methodName
  7532. }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`,
  7533. AbstractPropertyHasInitializer: ({
  7534. propertyName
  7535. }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
  7536. AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.",
  7537. AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  7538. AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  7539. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  7540. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  7541. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
  7542. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  7543. DeclareAccessor: ({
  7544. kind
  7545. }) => `'declare' is not allowed in ${kind}ters.`,
  7546. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  7547. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  7548. DuplicateAccessibilityModifier: ({
  7549. modifier
  7550. }) => `Accessibility modifier already seen.`,
  7551. DuplicateModifier: ({
  7552. modifier
  7553. }) => `Duplicate modifier: '${modifier}'.`,
  7554. EmptyHeritageClauseType: ({
  7555. token
  7556. }) => `'${token}' list cannot be empty.`,
  7557. EmptyTypeArguments: "Type argument list cannot be empty.",
  7558. EmptyTypeParameters: "Type parameter list cannot be empty.",
  7559. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  7560. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  7561. ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier",
  7562. IncompatibleModifiers: ({
  7563. modifiers
  7564. }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,
  7565. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  7566. IndexSignatureHasAccessibility: ({
  7567. modifier
  7568. }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`,
  7569. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  7570. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  7571. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  7572. InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.",
  7573. InvalidHeritageClauseType: ({
  7574. token
  7575. }) => `'${token}' list can only include identifiers or qualified-names with optional type arguments.`,
  7576. InvalidModifierOnTypeMember: ({
  7577. modifier
  7578. }) => `'${modifier}' modifier cannot appear on a type member.`,
  7579. InvalidModifierOnTypeParameter: ({
  7580. modifier
  7581. }) => `'${modifier}' modifier cannot appear on a type parameter.`,
  7582. InvalidModifierOnTypeParameterPositions: ({
  7583. modifier
  7584. }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,
  7585. InvalidModifiersOrder: ({
  7586. orderedModifiers
  7587. }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,
  7588. InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.",
  7589. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  7590. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  7591. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  7592. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  7593. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  7594. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  7595. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  7596. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  7597. PrivateElementHasAccessibility: ({
  7598. modifier
  7599. }) => `Private elements cannot have an accessibility modifier ('${modifier}').`,
  7600. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  7601. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  7602. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  7603. SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  7604. SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  7605. SetAccessorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  7606. SingleTypeParameterWithoutTrailingComma: ({
  7607. typeParameterName
  7608. }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,
  7609. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  7610. 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?`).",
  7611. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  7612. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  7613. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  7614. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  7615. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  7616. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  7617. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  7618. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  7619. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  7620. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  7621. UnsupportedSignatureParameterKind: ({
  7622. type
  7623. }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`
  7624. });
  7625. function keywordTypeFromName(value) {
  7626. switch (value) {
  7627. case "any":
  7628. return "TSAnyKeyword";
  7629. case "boolean":
  7630. return "TSBooleanKeyword";
  7631. case "bigint":
  7632. return "TSBigIntKeyword";
  7633. case "never":
  7634. return "TSNeverKeyword";
  7635. case "number":
  7636. return "TSNumberKeyword";
  7637. case "object":
  7638. return "TSObjectKeyword";
  7639. case "string":
  7640. return "TSStringKeyword";
  7641. case "symbol":
  7642. return "TSSymbolKeyword";
  7643. case "undefined":
  7644. return "TSUndefinedKeyword";
  7645. case "unknown":
  7646. return "TSUnknownKeyword";
  7647. default:
  7648. return undefined;
  7649. }
  7650. }
  7651. function tsIsAccessModifier(modifier) {
  7652. return modifier === "private" || modifier === "public" || modifier === "protected";
  7653. }
  7654. function tsIsVarianceAnnotations(modifier) {
  7655. return modifier === "in" || modifier === "out";
  7656. }
  7657. var typescript = superClass => class TypeScriptParserMixin extends superClass {
  7658. constructor(...args) {
  7659. super(...args);
  7660. this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, {
  7661. allowedModifiers: ["in", "out"],
  7662. disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"],
  7663. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  7664. });
  7665. this.tsParseConstModifier = this.tsParseModifiers.bind(this, {
  7666. allowedModifiers: ["const"],
  7667. disallowedModifiers: ["in", "out"],
  7668. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  7669. });
  7670. this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, {
  7671. allowedModifiers: ["in", "out", "const"],
  7672. disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"],
  7673. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  7674. });
  7675. }
  7676. getScopeHandler() {
  7677. return TypeScriptScopeHandler;
  7678. }
  7679. tsIsIdentifier() {
  7680. return tokenIsIdentifier(this.state.type);
  7681. }
  7682. tsTokenCanFollowModifier() {
  7683. return this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(139) || this.isLiteralPropertyName();
  7684. }
  7685. tsNextTokenOnSameLineAndCanFollowModifier() {
  7686. this.next();
  7687. if (this.hasPrecedingLineBreak()) {
  7688. return false;
  7689. }
  7690. return this.tsTokenCanFollowModifier();
  7691. }
  7692. tsNextTokenCanFollowModifier() {
  7693. if (this.match(106)) {
  7694. this.next();
  7695. return this.tsTokenCanFollowModifier();
  7696. }
  7697. return this.tsNextTokenOnSameLineAndCanFollowModifier();
  7698. }
  7699. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
  7700. if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) {
  7701. return undefined;
  7702. }
  7703. const modifier = this.state.value;
  7704. if (allowedModifiers.includes(modifier)) {
  7705. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  7706. return undefined;
  7707. }
  7708. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  7709. return modifier;
  7710. }
  7711. }
  7712. return undefined;
  7713. }
  7714. tsParseModifiers({
  7715. allowedModifiers,
  7716. disallowedModifiers,
  7717. stopOnStartOfClassStaticBlock,
  7718. errorTemplate = TSErrors.InvalidModifierOnTypeMember
  7719. }, modified) {
  7720. const enforceOrder = (loc, modifier, before, after) => {
  7721. if (modifier === before && modified[after]) {
  7722. this.raise(TSErrors.InvalidModifiersOrder, loc, {
  7723. orderedModifiers: [before, after]
  7724. });
  7725. }
  7726. };
  7727. const incompatible = (loc, modifier, mod1, mod2) => {
  7728. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  7729. this.raise(TSErrors.IncompatibleModifiers, loc, {
  7730. modifiers: [mod1, mod2]
  7731. });
  7732. }
  7733. };
  7734. for (;;) {
  7735. const {
  7736. startLoc
  7737. } = this.state;
  7738. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
  7739. if (!modifier) break;
  7740. if (tsIsAccessModifier(modifier)) {
  7741. if (modified.accessibility) {
  7742. this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, {
  7743. modifier
  7744. });
  7745. } else {
  7746. enforceOrder(startLoc, modifier, modifier, "override");
  7747. enforceOrder(startLoc, modifier, modifier, "static");
  7748. enforceOrder(startLoc, modifier, modifier, "readonly");
  7749. modified.accessibility = modifier;
  7750. }
  7751. } else if (tsIsVarianceAnnotations(modifier)) {
  7752. if (modified[modifier]) {
  7753. this.raise(TSErrors.DuplicateModifier, startLoc, {
  7754. modifier
  7755. });
  7756. }
  7757. modified[modifier] = true;
  7758. enforceOrder(startLoc, modifier, "in", "out");
  7759. } else {
  7760. if (hasOwnProperty.call(modified, modifier)) {
  7761. this.raise(TSErrors.DuplicateModifier, startLoc, {
  7762. modifier
  7763. });
  7764. } else {
  7765. enforceOrder(startLoc, modifier, "static", "readonly");
  7766. enforceOrder(startLoc, modifier, "static", "override");
  7767. enforceOrder(startLoc, modifier, "override", "readonly");
  7768. enforceOrder(startLoc, modifier, "abstract", "override");
  7769. incompatible(startLoc, modifier, "declare", "override");
  7770. incompatible(startLoc, modifier, "static", "abstract");
  7771. }
  7772. modified[modifier] = true;
  7773. }
  7774. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  7775. this.raise(errorTemplate, startLoc, {
  7776. modifier
  7777. });
  7778. }
  7779. }
  7780. }
  7781. tsIsListTerminator(kind) {
  7782. switch (kind) {
  7783. case "EnumMembers":
  7784. case "TypeMembers":
  7785. return this.match(8);
  7786. case "HeritageClauseElement":
  7787. return this.match(5);
  7788. case "TupleElementTypes":
  7789. return this.match(3);
  7790. case "TypeParametersOrArguments":
  7791. return this.match(48);
  7792. }
  7793. }
  7794. tsParseList(kind, parseElement) {
  7795. const result = [];
  7796. while (!this.tsIsListTerminator(kind)) {
  7797. result.push(parseElement());
  7798. }
  7799. return result;
  7800. }
  7801. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  7802. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  7803. }
  7804. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  7805. const result = [];
  7806. let trailingCommaPos = -1;
  7807. for (;;) {
  7808. if (this.tsIsListTerminator(kind)) {
  7809. break;
  7810. }
  7811. trailingCommaPos = -1;
  7812. const element = parseElement();
  7813. if (element == null) {
  7814. return undefined;
  7815. }
  7816. result.push(element);
  7817. if (this.eat(12)) {
  7818. trailingCommaPos = this.state.lastTokStartLoc.index;
  7819. continue;
  7820. }
  7821. if (this.tsIsListTerminator(kind)) {
  7822. break;
  7823. }
  7824. if (expectSuccess) {
  7825. this.expect(12);
  7826. }
  7827. return undefined;
  7828. }
  7829. if (refTrailingCommaPos) {
  7830. refTrailingCommaPos.value = trailingCommaPos;
  7831. }
  7832. return result;
  7833. }
  7834. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  7835. if (!skipFirstToken) {
  7836. if (bracket) {
  7837. this.expect(0);
  7838. } else {
  7839. this.expect(47);
  7840. }
  7841. }
  7842. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  7843. if (bracket) {
  7844. this.expect(3);
  7845. } else {
  7846. this.expect(48);
  7847. }
  7848. return result;
  7849. }
  7850. tsParseImportType() {
  7851. const node = this.startNode();
  7852. this.expect(83);
  7853. this.expect(10);
  7854. if (!this.match(134)) {
  7855. this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc);
  7856. {
  7857. node.argument = super.parseExprAtom();
  7858. }
  7859. } else {
  7860. {
  7861. node.argument = this.parseStringLiteral(this.state.value);
  7862. }
  7863. }
  7864. if (this.eat(12) && !this.match(11)) {
  7865. node.options = super.parseMaybeAssignAllowIn();
  7866. this.eat(12);
  7867. } else {
  7868. node.options = null;
  7869. }
  7870. this.expect(11);
  7871. if (this.eat(16)) {
  7872. node.qualifier = this.tsParseEntityName(1 | 2);
  7873. }
  7874. if (this.match(47)) {
  7875. {
  7876. node.typeParameters = this.tsParseTypeArguments();
  7877. }
  7878. }
  7879. return this.finishNode(node, "TSImportType");
  7880. }
  7881. tsParseEntityName(flags) {
  7882. let entity;
  7883. if (flags & 1 && this.match(78)) {
  7884. if (flags & 2) {
  7885. entity = this.parseIdentifier(true);
  7886. } else {
  7887. const node = this.startNode();
  7888. this.next();
  7889. entity = this.finishNode(node, "ThisExpression");
  7890. }
  7891. } else {
  7892. entity = this.parseIdentifier(!!(flags & 1));
  7893. }
  7894. while (this.eat(16)) {
  7895. const node = this.startNodeAtNode(entity);
  7896. node.left = entity;
  7897. node.right = this.parseIdentifier(!!(flags & 1));
  7898. entity = this.finishNode(node, "TSQualifiedName");
  7899. }
  7900. return entity;
  7901. }
  7902. tsParseTypeReference() {
  7903. const node = this.startNode();
  7904. node.typeName = this.tsParseEntityName(1);
  7905. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  7906. {
  7907. node.typeParameters = this.tsParseTypeArguments();
  7908. }
  7909. }
  7910. return this.finishNode(node, "TSTypeReference");
  7911. }
  7912. tsParseThisTypePredicate(lhs) {
  7913. this.next();
  7914. const node = this.startNodeAtNode(lhs);
  7915. node.parameterName = lhs;
  7916. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  7917. node.asserts = false;
  7918. return this.finishNode(node, "TSTypePredicate");
  7919. }
  7920. tsParseThisTypeNode() {
  7921. const node = this.startNode();
  7922. this.next();
  7923. return this.finishNode(node, "TSThisType");
  7924. }
  7925. tsParseTypeQuery() {
  7926. const node = this.startNode();
  7927. this.expect(87);
  7928. if (this.match(83)) {
  7929. node.exprName = this.tsParseImportType();
  7930. } else {
  7931. {
  7932. node.exprName = this.tsParseEntityName(1 | 2);
  7933. }
  7934. }
  7935. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  7936. {
  7937. node.typeParameters = this.tsParseTypeArguments();
  7938. }
  7939. }
  7940. return this.finishNode(node, "TSTypeQuery");
  7941. }
  7942. tsParseTypeParameter(parseModifiers) {
  7943. const node = this.startNode();
  7944. parseModifiers(node);
  7945. node.name = this.tsParseTypeParameterName();
  7946. node.constraint = this.tsEatThenParseType(81);
  7947. node.default = this.tsEatThenParseType(29);
  7948. return this.finishNode(node, "TSTypeParameter");
  7949. }
  7950. tsTryParseTypeParameters(parseModifiers) {
  7951. if (this.match(47)) {
  7952. return this.tsParseTypeParameters(parseModifiers);
  7953. }
  7954. }
  7955. tsParseTypeParameters(parseModifiers) {
  7956. const node = this.startNode();
  7957. if (this.match(47) || this.match(143)) {
  7958. this.next();
  7959. } else {
  7960. this.unexpected();
  7961. }
  7962. const refTrailingCommaPos = {
  7963. value: -1
  7964. };
  7965. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos);
  7966. if (node.params.length === 0) {
  7967. this.raise(TSErrors.EmptyTypeParameters, node);
  7968. }
  7969. if (refTrailingCommaPos.value !== -1) {
  7970. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  7971. }
  7972. return this.finishNode(node, "TSTypeParameterDeclaration");
  7973. }
  7974. tsFillSignature(returnToken, signature) {
  7975. const returnTokenRequired = returnToken === 19;
  7976. const paramsKey = "parameters";
  7977. const returnTypeKey = "typeAnnotation";
  7978. signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  7979. this.expect(10);
  7980. signature[paramsKey] = this.tsParseBindingListForSignature();
  7981. if (returnTokenRequired) {
  7982. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7983. } else if (this.match(returnToken)) {
  7984. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7985. }
  7986. }
  7987. tsParseBindingListForSignature() {
  7988. const list = super.parseBindingList(11, 41, 2);
  7989. for (const pattern of list) {
  7990. const {
  7991. type
  7992. } = pattern;
  7993. if (type === "AssignmentPattern" || type === "TSParameterProperty") {
  7994. this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, {
  7995. type
  7996. });
  7997. }
  7998. }
  7999. return list;
  8000. }
  8001. tsParseTypeMemberSemicolon() {
  8002. if (!this.eat(12) && !this.isLineTerminator()) {
  8003. this.expect(13);
  8004. }
  8005. }
  8006. tsParseSignatureMember(kind, node) {
  8007. this.tsFillSignature(14, node);
  8008. this.tsParseTypeMemberSemicolon();
  8009. return this.finishNode(node, kind);
  8010. }
  8011. tsIsUnambiguouslyIndexSignature() {
  8012. this.next();
  8013. if (tokenIsIdentifier(this.state.type)) {
  8014. this.next();
  8015. return this.match(14);
  8016. }
  8017. return false;
  8018. }
  8019. tsTryParseIndexSignature(node) {
  8020. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  8021. return;
  8022. }
  8023. this.expect(0);
  8024. const id = this.parseIdentifier();
  8025. id.typeAnnotation = this.tsParseTypeAnnotation();
  8026. this.resetEndLocation(id);
  8027. this.expect(3);
  8028. node.parameters = [id];
  8029. const type = this.tsTryParseTypeAnnotation();
  8030. if (type) node.typeAnnotation = type;
  8031. this.tsParseTypeMemberSemicolon();
  8032. return this.finishNode(node, "TSIndexSignature");
  8033. }
  8034. tsParsePropertyOrMethodSignature(node, readonly) {
  8035. if (this.eat(17)) node.optional = true;
  8036. const nodeAny = node;
  8037. if (this.match(10) || this.match(47)) {
  8038. if (readonly) {
  8039. this.raise(TSErrors.ReadonlyForMethodSignature, node);
  8040. }
  8041. const method = nodeAny;
  8042. if (method.kind && this.match(47)) {
  8043. this.raise(TSErrors.AccessorCannotHaveTypeParameters, this.state.curPosition());
  8044. }
  8045. this.tsFillSignature(14, method);
  8046. this.tsParseTypeMemberSemicolon();
  8047. const paramsKey = "parameters";
  8048. const returnTypeKey = "typeAnnotation";
  8049. if (method.kind === "get") {
  8050. if (method[paramsKey].length > 0) {
  8051. this.raise(Errors.BadGetterArity, this.state.curPosition());
  8052. if (this.isThisParam(method[paramsKey][0])) {
  8053. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  8054. }
  8055. }
  8056. } else if (method.kind === "set") {
  8057. if (method[paramsKey].length !== 1) {
  8058. this.raise(Errors.BadSetterArity, this.state.curPosition());
  8059. } else {
  8060. const firstParameter = method[paramsKey][0];
  8061. if (this.isThisParam(firstParameter)) {
  8062. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  8063. }
  8064. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  8065. this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition());
  8066. }
  8067. if (firstParameter.type === "RestElement") {
  8068. this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition());
  8069. }
  8070. }
  8071. if (method[returnTypeKey]) {
  8072. this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]);
  8073. }
  8074. } else {
  8075. method.kind = "method";
  8076. }
  8077. return this.finishNode(method, "TSMethodSignature");
  8078. } else {
  8079. const property = nodeAny;
  8080. if (readonly) property.readonly = true;
  8081. const type = this.tsTryParseTypeAnnotation();
  8082. if (type) property.typeAnnotation = type;
  8083. this.tsParseTypeMemberSemicolon();
  8084. return this.finishNode(property, "TSPropertySignature");
  8085. }
  8086. }
  8087. tsParseTypeMember() {
  8088. const node = this.startNode();
  8089. if (this.match(10) || this.match(47)) {
  8090. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  8091. }
  8092. if (this.match(77)) {
  8093. const id = this.startNode();
  8094. this.next();
  8095. if (this.match(10) || this.match(47)) {
  8096. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  8097. } else {
  8098. node.key = this.createIdentifier(id, "new");
  8099. return this.tsParsePropertyOrMethodSignature(node, false);
  8100. }
  8101. }
  8102. this.tsParseModifiers({
  8103. allowedModifiers: ["readonly"],
  8104. disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"]
  8105. }, node);
  8106. const idx = this.tsTryParseIndexSignature(node);
  8107. if (idx) {
  8108. return idx;
  8109. }
  8110. super.parsePropertyName(node);
  8111. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  8112. node.kind = node.key.name;
  8113. super.parsePropertyName(node);
  8114. }
  8115. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  8116. }
  8117. tsParseTypeLiteral() {
  8118. const node = this.startNode();
  8119. node.members = this.tsParseObjectTypeMembers();
  8120. return this.finishNode(node, "TSTypeLiteral");
  8121. }
  8122. tsParseObjectTypeMembers() {
  8123. this.expect(5);
  8124. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  8125. this.expect(8);
  8126. return members;
  8127. }
  8128. tsIsStartOfMappedType() {
  8129. this.next();
  8130. if (this.eat(53)) {
  8131. return this.isContextual(122);
  8132. }
  8133. if (this.isContextual(122)) {
  8134. this.next();
  8135. }
  8136. if (!this.match(0)) {
  8137. return false;
  8138. }
  8139. this.next();
  8140. if (!this.tsIsIdentifier()) {
  8141. return false;
  8142. }
  8143. this.next();
  8144. return this.match(58);
  8145. }
  8146. tsParseMappedType() {
  8147. const node = this.startNode();
  8148. this.expect(5);
  8149. if (this.match(53)) {
  8150. node.readonly = this.state.value;
  8151. this.next();
  8152. this.expectContextual(122);
  8153. } else if (this.eatContextual(122)) {
  8154. node.readonly = true;
  8155. }
  8156. this.expect(0);
  8157. {
  8158. const typeParameter = this.startNode();
  8159. typeParameter.name = this.tsParseTypeParameterName();
  8160. typeParameter.constraint = this.tsExpectThenParseType(58);
  8161. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  8162. }
  8163. node.nameType = this.eatContextual(93) ? this.tsParseType() : null;
  8164. this.expect(3);
  8165. if (this.match(53)) {
  8166. node.optional = this.state.value;
  8167. this.next();
  8168. this.expect(17);
  8169. } else if (this.eat(17)) {
  8170. node.optional = true;
  8171. }
  8172. node.typeAnnotation = this.tsTryParseType();
  8173. this.semicolon();
  8174. this.expect(8);
  8175. return this.finishNode(node, "TSMappedType");
  8176. }
  8177. tsParseTupleType() {
  8178. const node = this.startNode();
  8179. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  8180. let seenOptionalElement = false;
  8181. node.elementTypes.forEach(elementNode => {
  8182. const {
  8183. type
  8184. } = elementNode;
  8185. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  8186. this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode);
  8187. }
  8188. seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType");
  8189. });
  8190. return this.finishNode(node, "TSTupleType");
  8191. }
  8192. tsParseTupleElementType() {
  8193. const restStartLoc = this.state.startLoc;
  8194. const rest = this.eat(21);
  8195. const {
  8196. startLoc
  8197. } = this.state;
  8198. let labeled;
  8199. let label;
  8200. let optional;
  8201. let type;
  8202. const isWord = tokenIsKeywordOrIdentifier(this.state.type);
  8203. const chAfterWord = isWord ? this.lookaheadCharCode() : null;
  8204. if (chAfterWord === 58) {
  8205. labeled = true;
  8206. optional = false;
  8207. label = this.parseIdentifier(true);
  8208. this.expect(14);
  8209. type = this.tsParseType();
  8210. } else if (chAfterWord === 63) {
  8211. optional = true;
  8212. const wordName = this.state.value;
  8213. const typeOrLabel = this.tsParseNonArrayType();
  8214. if (this.lookaheadCharCode() === 58) {
  8215. labeled = true;
  8216. label = this.createIdentifier(this.startNodeAt(startLoc), wordName);
  8217. this.expect(17);
  8218. this.expect(14);
  8219. type = this.tsParseType();
  8220. } else {
  8221. labeled = false;
  8222. type = typeOrLabel;
  8223. this.expect(17);
  8224. }
  8225. } else {
  8226. type = this.tsParseType();
  8227. optional = this.eat(17);
  8228. labeled = this.eat(14);
  8229. }
  8230. if (labeled) {
  8231. let labeledNode;
  8232. if (label) {
  8233. labeledNode = this.startNodeAt(startLoc);
  8234. labeledNode.optional = optional;
  8235. labeledNode.label = label;
  8236. labeledNode.elementType = type;
  8237. if (this.eat(17)) {
  8238. labeledNode.optional = true;
  8239. this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc);
  8240. }
  8241. } else {
  8242. labeledNode = this.startNodeAt(startLoc);
  8243. labeledNode.optional = optional;
  8244. this.raise(TSErrors.InvalidTupleMemberLabel, type);
  8245. labeledNode.label = type;
  8246. labeledNode.elementType = this.tsParseType();
  8247. }
  8248. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  8249. } else if (optional) {
  8250. const optionalTypeNode = this.startNodeAt(startLoc);
  8251. optionalTypeNode.typeAnnotation = type;
  8252. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  8253. }
  8254. if (rest) {
  8255. const restNode = this.startNodeAt(restStartLoc);
  8256. restNode.typeAnnotation = type;
  8257. type = this.finishNode(restNode, "TSRestType");
  8258. }
  8259. return type;
  8260. }
  8261. tsParseParenthesizedType() {
  8262. const node = this.startNode();
  8263. this.expect(10);
  8264. node.typeAnnotation = this.tsParseType();
  8265. this.expect(11);
  8266. return this.finishNode(node, "TSParenthesizedType");
  8267. }
  8268. tsParseFunctionOrConstructorType(type, abstract) {
  8269. const node = this.startNode();
  8270. if (type === "TSConstructorType") {
  8271. node.abstract = !!abstract;
  8272. if (abstract) this.next();
  8273. this.next();
  8274. }
  8275. this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node));
  8276. return this.finishNode(node, type);
  8277. }
  8278. tsParseLiteralTypeNode() {
  8279. const node = this.startNode();
  8280. switch (this.state.type) {
  8281. case 135:
  8282. case 136:
  8283. case 134:
  8284. case 85:
  8285. case 86:
  8286. node.literal = super.parseExprAtom();
  8287. break;
  8288. default:
  8289. this.unexpected();
  8290. }
  8291. return this.finishNode(node, "TSLiteralType");
  8292. }
  8293. tsParseTemplateLiteralType() {
  8294. {
  8295. const node = this.startNode();
  8296. node.literal = super.parseTemplate(false);
  8297. return this.finishNode(node, "TSLiteralType");
  8298. }
  8299. }
  8300. parseTemplateSubstitution() {
  8301. if (this.state.inType) return this.tsParseType();
  8302. return super.parseTemplateSubstitution();
  8303. }
  8304. tsParseThisTypeOrThisTypePredicate() {
  8305. const thisKeyword = this.tsParseThisTypeNode();
  8306. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  8307. return this.tsParseThisTypePredicate(thisKeyword);
  8308. } else {
  8309. return thisKeyword;
  8310. }
  8311. }
  8312. tsParseNonArrayType() {
  8313. switch (this.state.type) {
  8314. case 134:
  8315. case 135:
  8316. case 136:
  8317. case 85:
  8318. case 86:
  8319. return this.tsParseLiteralTypeNode();
  8320. case 53:
  8321. if (this.state.value === "-") {
  8322. const node = this.startNode();
  8323. const nextToken = this.lookahead();
  8324. if (nextToken.type !== 135 && nextToken.type !== 136) {
  8325. this.unexpected();
  8326. }
  8327. node.literal = this.parseMaybeUnary();
  8328. return this.finishNode(node, "TSLiteralType");
  8329. }
  8330. break;
  8331. case 78:
  8332. return this.tsParseThisTypeOrThisTypePredicate();
  8333. case 87:
  8334. return this.tsParseTypeQuery();
  8335. case 83:
  8336. return this.tsParseImportType();
  8337. case 5:
  8338. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  8339. case 0:
  8340. return this.tsParseTupleType();
  8341. case 10:
  8342. return this.tsParseParenthesizedType();
  8343. case 25:
  8344. case 24:
  8345. return this.tsParseTemplateLiteralType();
  8346. default:
  8347. {
  8348. const {
  8349. type
  8350. } = this.state;
  8351. if (tokenIsIdentifier(type) || type === 88 || type === 84) {
  8352. const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  8353. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  8354. const node = this.startNode();
  8355. this.next();
  8356. return this.finishNode(node, nodeType);
  8357. }
  8358. return this.tsParseTypeReference();
  8359. }
  8360. }
  8361. }
  8362. this.unexpected();
  8363. }
  8364. tsParseArrayTypeOrHigher() {
  8365. const {
  8366. startLoc
  8367. } = this.state;
  8368. let type = this.tsParseNonArrayType();
  8369. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  8370. if (this.match(3)) {
  8371. const node = this.startNodeAt(startLoc);
  8372. node.elementType = type;
  8373. this.expect(3);
  8374. type = this.finishNode(node, "TSArrayType");
  8375. } else {
  8376. const node = this.startNodeAt(startLoc);
  8377. node.objectType = type;
  8378. node.indexType = this.tsParseType();
  8379. this.expect(3);
  8380. type = this.finishNode(node, "TSIndexedAccessType");
  8381. }
  8382. }
  8383. return type;
  8384. }
  8385. tsParseTypeOperator() {
  8386. const node = this.startNode();
  8387. const operator = this.state.value;
  8388. this.next();
  8389. node.operator = operator;
  8390. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  8391. if (operator === "readonly") {
  8392. this.tsCheckTypeAnnotationForReadOnly(node);
  8393. }
  8394. return this.finishNode(node, "TSTypeOperator");
  8395. }
  8396. tsCheckTypeAnnotationForReadOnly(node) {
  8397. switch (node.typeAnnotation.type) {
  8398. case "TSTupleType":
  8399. case "TSArrayType":
  8400. return;
  8401. default:
  8402. this.raise(TSErrors.UnexpectedReadonly, node);
  8403. }
  8404. }
  8405. tsParseInferType() {
  8406. const node = this.startNode();
  8407. this.expectContextual(115);
  8408. const typeParameter = this.startNode();
  8409. typeParameter.name = this.tsParseTypeParameterName();
  8410. typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType());
  8411. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  8412. return this.finishNode(node, "TSInferType");
  8413. }
  8414. tsParseConstraintForInferType() {
  8415. if (this.eat(81)) {
  8416. const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType());
  8417. if (this.state.inDisallowConditionalTypesContext || !this.match(17)) {
  8418. return constraint;
  8419. }
  8420. }
  8421. }
  8422. tsParseTypeOperatorOrHigher() {
  8423. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  8424. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher());
  8425. }
  8426. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  8427. const node = this.startNode();
  8428. const hasLeadingOperator = this.eat(operator);
  8429. const types = [];
  8430. do {
  8431. types.push(parseConstituentType());
  8432. } while (this.eat(operator));
  8433. if (types.length === 1 && !hasLeadingOperator) {
  8434. return types[0];
  8435. }
  8436. node.types = types;
  8437. return this.finishNode(node, kind);
  8438. }
  8439. tsParseIntersectionTypeOrHigher() {
  8440. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45);
  8441. }
  8442. tsParseUnionTypeOrHigher() {
  8443. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43);
  8444. }
  8445. tsIsStartOfFunctionType() {
  8446. if (this.match(47)) {
  8447. return true;
  8448. }
  8449. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  8450. }
  8451. tsSkipParameterStart() {
  8452. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  8453. this.next();
  8454. return true;
  8455. }
  8456. if (this.match(5)) {
  8457. const {
  8458. errors
  8459. } = this.state;
  8460. const previousErrorCount = errors.length;
  8461. try {
  8462. this.parseObjectLike(8, true);
  8463. return errors.length === previousErrorCount;
  8464. } catch (_unused) {
  8465. return false;
  8466. }
  8467. }
  8468. if (this.match(0)) {
  8469. this.next();
  8470. const {
  8471. errors
  8472. } = this.state;
  8473. const previousErrorCount = errors.length;
  8474. try {
  8475. super.parseBindingList(3, 93, 1);
  8476. return errors.length === previousErrorCount;
  8477. } catch (_unused2) {
  8478. return false;
  8479. }
  8480. }
  8481. return false;
  8482. }
  8483. tsIsUnambiguouslyStartOfFunctionType() {
  8484. this.next();
  8485. if (this.match(11) || this.match(21)) {
  8486. return true;
  8487. }
  8488. if (this.tsSkipParameterStart()) {
  8489. if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) {
  8490. return true;
  8491. }
  8492. if (this.match(11)) {
  8493. this.next();
  8494. if (this.match(19)) {
  8495. return true;
  8496. }
  8497. }
  8498. }
  8499. return false;
  8500. }
  8501. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  8502. return this.tsInType(() => {
  8503. const t = this.startNode();
  8504. this.expect(returnToken);
  8505. const node = this.startNode();
  8506. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  8507. if (asserts && this.match(78)) {
  8508. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  8509. if (thisTypePredicate.type === "TSThisType") {
  8510. node.parameterName = thisTypePredicate;
  8511. node.asserts = true;
  8512. node.typeAnnotation = null;
  8513. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  8514. } else {
  8515. this.resetStartLocationFromNode(thisTypePredicate, node);
  8516. thisTypePredicate.asserts = true;
  8517. }
  8518. t.typeAnnotation = thisTypePredicate;
  8519. return this.finishNode(t, "TSTypeAnnotation");
  8520. }
  8521. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  8522. if (!typePredicateVariable) {
  8523. if (!asserts) {
  8524. return this.tsParseTypeAnnotation(false, t);
  8525. }
  8526. node.parameterName = this.parseIdentifier();
  8527. node.asserts = asserts;
  8528. node.typeAnnotation = null;
  8529. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8530. return this.finishNode(t, "TSTypeAnnotation");
  8531. }
  8532. const type = this.tsParseTypeAnnotation(false);
  8533. node.parameterName = typePredicateVariable;
  8534. node.typeAnnotation = type;
  8535. node.asserts = asserts;
  8536. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8537. return this.finishNode(t, "TSTypeAnnotation");
  8538. });
  8539. }
  8540. tsTryParseTypeOrTypePredicateAnnotation() {
  8541. if (this.match(14)) {
  8542. return this.tsParseTypeOrTypePredicateAnnotation(14);
  8543. }
  8544. }
  8545. tsTryParseTypeAnnotation() {
  8546. if (this.match(14)) {
  8547. return this.tsParseTypeAnnotation();
  8548. }
  8549. }
  8550. tsTryParseType() {
  8551. return this.tsEatThenParseType(14);
  8552. }
  8553. tsParseTypePredicatePrefix() {
  8554. const id = this.parseIdentifier();
  8555. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  8556. this.next();
  8557. return id;
  8558. }
  8559. }
  8560. tsParseTypePredicateAsserts() {
  8561. if (this.state.type !== 109) {
  8562. return false;
  8563. }
  8564. const containsEsc = this.state.containsEsc;
  8565. this.next();
  8566. if (!tokenIsIdentifier(this.state.type) && !this.match(78)) {
  8567. return false;
  8568. }
  8569. if (containsEsc) {
  8570. this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, {
  8571. reservedWord: "asserts"
  8572. });
  8573. }
  8574. return true;
  8575. }
  8576. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  8577. this.tsInType(() => {
  8578. if (eatColon) this.expect(14);
  8579. t.typeAnnotation = this.tsParseType();
  8580. });
  8581. return this.finishNode(t, "TSTypeAnnotation");
  8582. }
  8583. tsParseType() {
  8584. assert(this.state.inType);
  8585. const type = this.tsParseNonConditionalType();
  8586. if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) {
  8587. return type;
  8588. }
  8589. const node = this.startNodeAtNode(type);
  8590. node.checkType = type;
  8591. node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType());
  8592. this.expect(17);
  8593. node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  8594. this.expect(14);
  8595. node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  8596. return this.finishNode(node, "TSConditionalType");
  8597. }
  8598. isAbstractConstructorSignature() {
  8599. return this.isContextual(124) && this.lookahead().type === 77;
  8600. }
  8601. tsParseNonConditionalType() {
  8602. if (this.tsIsStartOfFunctionType()) {
  8603. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  8604. }
  8605. if (this.match(77)) {
  8606. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  8607. } else if (this.isAbstractConstructorSignature()) {
  8608. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  8609. }
  8610. return this.tsParseUnionTypeOrHigher();
  8611. }
  8612. tsParseTypeAssertion() {
  8613. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8614. this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc);
  8615. }
  8616. const node = this.startNode();
  8617. node.typeAnnotation = this.tsInType(() => {
  8618. this.next();
  8619. return this.match(75) ? this.tsParseTypeReference() : this.tsParseType();
  8620. });
  8621. this.expect(48);
  8622. node.expression = this.parseMaybeUnary();
  8623. return this.finishNode(node, "TSTypeAssertion");
  8624. }
  8625. tsParseHeritageClause(token) {
  8626. const originalStartLoc = this.state.startLoc;
  8627. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => {
  8628. {
  8629. const node = this.startNode();
  8630. node.expression = this.tsParseEntityName(1 | 2);
  8631. if (this.match(47)) {
  8632. node.typeParameters = this.tsParseTypeArguments();
  8633. }
  8634. return this.finishNode(node, "TSExpressionWithTypeArguments");
  8635. }
  8636. });
  8637. if (!delimitedList.length) {
  8638. this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, {
  8639. token
  8640. });
  8641. }
  8642. return delimitedList;
  8643. }
  8644. tsParseInterfaceDeclaration(node, properties = {}) {
  8645. if (this.hasFollowingLineBreak()) return null;
  8646. this.expectContextual(129);
  8647. if (properties.declare) node.declare = true;
  8648. if (tokenIsIdentifier(this.state.type)) {
  8649. node.id = this.parseIdentifier();
  8650. this.checkIdentifier(node.id, 130);
  8651. } else {
  8652. node.id = null;
  8653. this.raise(TSErrors.MissingInterfaceName, this.state.startLoc);
  8654. }
  8655. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  8656. if (this.eat(81)) {
  8657. node.extends = this.tsParseHeritageClause("extends");
  8658. }
  8659. const body = this.startNode();
  8660. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  8661. node.body = this.finishNode(body, "TSInterfaceBody");
  8662. return this.finishNode(node, "TSInterfaceDeclaration");
  8663. }
  8664. tsParseTypeAliasDeclaration(node) {
  8665. node.id = this.parseIdentifier();
  8666. this.checkIdentifier(node.id, 2);
  8667. node.typeAnnotation = this.tsInType(() => {
  8668. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
  8669. this.expect(29);
  8670. if (this.isContextual(114) && this.lookahead().type !== 16) {
  8671. const node = this.startNode();
  8672. this.next();
  8673. return this.finishNode(node, "TSIntrinsicKeyword");
  8674. }
  8675. return this.tsParseType();
  8676. });
  8677. this.semicolon();
  8678. return this.finishNode(node, "TSTypeAliasDeclaration");
  8679. }
  8680. tsInTopLevelContext(cb) {
  8681. if (this.curContext() !== types.brace) {
  8682. const oldContext = this.state.context;
  8683. this.state.context = [oldContext[0]];
  8684. try {
  8685. return cb();
  8686. } finally {
  8687. this.state.context = oldContext;
  8688. }
  8689. } else {
  8690. return cb();
  8691. }
  8692. }
  8693. tsInType(cb) {
  8694. const oldInType = this.state.inType;
  8695. this.state.inType = true;
  8696. try {
  8697. return cb();
  8698. } finally {
  8699. this.state.inType = oldInType;
  8700. }
  8701. }
  8702. tsInDisallowConditionalTypesContext(cb) {
  8703. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  8704. this.state.inDisallowConditionalTypesContext = true;
  8705. try {
  8706. return cb();
  8707. } finally {
  8708. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  8709. }
  8710. }
  8711. tsInAllowConditionalTypesContext(cb) {
  8712. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  8713. this.state.inDisallowConditionalTypesContext = false;
  8714. try {
  8715. return cb();
  8716. } finally {
  8717. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  8718. }
  8719. }
  8720. tsEatThenParseType(token) {
  8721. if (this.match(token)) {
  8722. return this.tsNextThenParseType();
  8723. }
  8724. }
  8725. tsExpectThenParseType(token) {
  8726. return this.tsInType(() => {
  8727. this.expect(token);
  8728. return this.tsParseType();
  8729. });
  8730. }
  8731. tsNextThenParseType() {
  8732. return this.tsInType(() => {
  8733. this.next();
  8734. return this.tsParseType();
  8735. });
  8736. }
  8737. tsParseEnumMember() {
  8738. const node = this.startNode();
  8739. node.id = this.match(134) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true);
  8740. if (this.eat(29)) {
  8741. node.initializer = super.parseMaybeAssignAllowIn();
  8742. }
  8743. return this.finishNode(node, "TSEnumMember");
  8744. }
  8745. tsParseEnumDeclaration(node, properties = {}) {
  8746. if (properties.const) node.const = true;
  8747. if (properties.declare) node.declare = true;
  8748. this.expectContextual(126);
  8749. node.id = this.parseIdentifier();
  8750. this.checkIdentifier(node.id, node.const ? 8971 : 8459);
  8751. {
  8752. this.expect(5);
  8753. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8754. this.expect(8);
  8755. }
  8756. return this.finishNode(node, "TSEnumDeclaration");
  8757. }
  8758. tsParseEnumBody() {
  8759. const node = this.startNode();
  8760. this.expect(5);
  8761. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8762. this.expect(8);
  8763. return this.finishNode(node, "TSEnumBody");
  8764. }
  8765. tsParseModuleBlock() {
  8766. const node = this.startNode();
  8767. this.scope.enter(0);
  8768. this.expect(5);
  8769. super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  8770. this.scope.exit();
  8771. return this.finishNode(node, "TSModuleBlock");
  8772. }
  8773. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  8774. node.id = this.parseIdentifier();
  8775. if (!nested) {
  8776. this.checkIdentifier(node.id, 1024);
  8777. }
  8778. if (this.eat(16)) {
  8779. const inner = this.startNode();
  8780. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  8781. node.body = inner;
  8782. } else {
  8783. this.scope.enter(256);
  8784. this.prodParam.enter(0);
  8785. node.body = this.tsParseModuleBlock();
  8786. this.prodParam.exit();
  8787. this.scope.exit();
  8788. }
  8789. return this.finishNode(node, "TSModuleDeclaration");
  8790. }
  8791. tsParseAmbientExternalModuleDeclaration(node) {
  8792. if (this.isContextual(112)) {
  8793. node.kind = "global";
  8794. {
  8795. node.global = true;
  8796. }
  8797. node.id = this.parseIdentifier();
  8798. } else if (this.match(134)) {
  8799. node.kind = "module";
  8800. node.id = super.parseStringLiteral(this.state.value);
  8801. } else {
  8802. this.unexpected();
  8803. }
  8804. if (this.match(5)) {
  8805. this.scope.enter(256);
  8806. this.prodParam.enter(0);
  8807. node.body = this.tsParseModuleBlock();
  8808. this.prodParam.exit();
  8809. this.scope.exit();
  8810. } else {
  8811. this.semicolon();
  8812. }
  8813. return this.finishNode(node, "TSModuleDeclaration");
  8814. }
  8815. tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) {
  8816. {
  8817. node.isExport = isExport || false;
  8818. }
  8819. node.id = maybeDefaultIdentifier || this.parseIdentifier();
  8820. this.checkIdentifier(node.id, 4096);
  8821. this.expect(29);
  8822. const moduleReference = this.tsParseModuleReference();
  8823. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  8824. this.raise(TSErrors.ImportAliasHasImportType, moduleReference);
  8825. }
  8826. node.moduleReference = moduleReference;
  8827. this.semicolon();
  8828. return this.finishNode(node, "TSImportEqualsDeclaration");
  8829. }
  8830. tsIsExternalModuleReference() {
  8831. return this.isContextual(119) && this.lookaheadCharCode() === 40;
  8832. }
  8833. tsParseModuleReference() {
  8834. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(0);
  8835. }
  8836. tsParseExternalModuleReference() {
  8837. const node = this.startNode();
  8838. this.expectContextual(119);
  8839. this.expect(10);
  8840. if (!this.match(134)) {
  8841. this.unexpected();
  8842. }
  8843. node.expression = super.parseExprAtom();
  8844. this.expect(11);
  8845. this.sawUnambiguousESM = true;
  8846. return this.finishNode(node, "TSExternalModuleReference");
  8847. }
  8848. tsLookAhead(f) {
  8849. const state = this.state.clone();
  8850. const res = f();
  8851. this.state = state;
  8852. return res;
  8853. }
  8854. tsTryParseAndCatch(f) {
  8855. const result = this.tryParse(abort => f() || abort());
  8856. if (result.aborted || !result.node) return;
  8857. if (result.error) this.state = result.failState;
  8858. return result.node;
  8859. }
  8860. tsTryParse(f) {
  8861. const state = this.state.clone();
  8862. const result = f();
  8863. if (result !== undefined && result !== false) {
  8864. return result;
  8865. }
  8866. this.state = state;
  8867. }
  8868. tsTryParseDeclare(nany) {
  8869. if (this.isLineTerminator()) {
  8870. return;
  8871. }
  8872. let startType = this.state.type;
  8873. let kind;
  8874. if (this.isContextual(100)) {
  8875. startType = 74;
  8876. kind = "let";
  8877. }
  8878. return this.tsInAmbientContext(() => {
  8879. switch (startType) {
  8880. case 68:
  8881. nany.declare = true;
  8882. return super.parseFunctionStatement(nany, false, false);
  8883. case 80:
  8884. nany.declare = true;
  8885. return this.parseClass(nany, true, false);
  8886. case 126:
  8887. return this.tsParseEnumDeclaration(nany, {
  8888. declare: true
  8889. });
  8890. case 112:
  8891. return this.tsParseAmbientExternalModuleDeclaration(nany);
  8892. case 75:
  8893. case 74:
  8894. if (!this.match(75) || !this.isLookaheadContextual("enum")) {
  8895. nany.declare = true;
  8896. return this.parseVarStatement(nany, kind || this.state.value, true);
  8897. }
  8898. this.expect(75);
  8899. return this.tsParseEnumDeclaration(nany, {
  8900. const: true,
  8901. declare: true
  8902. });
  8903. case 129:
  8904. {
  8905. const result = this.tsParseInterfaceDeclaration(nany, {
  8906. declare: true
  8907. });
  8908. if (result) return result;
  8909. }
  8910. default:
  8911. if (tokenIsIdentifier(startType)) {
  8912. return this.tsParseDeclaration(nany, this.state.value, true, null);
  8913. }
  8914. }
  8915. });
  8916. }
  8917. tsTryParseExportDeclaration() {
  8918. return this.tsParseDeclaration(this.startNode(), this.state.value, true, null);
  8919. }
  8920. tsParseExpressionStatement(node, expr, decorators) {
  8921. switch (expr.name) {
  8922. case "declare":
  8923. {
  8924. const declaration = this.tsTryParseDeclare(node);
  8925. if (declaration) {
  8926. declaration.declare = true;
  8927. }
  8928. return declaration;
  8929. }
  8930. case "global":
  8931. if (this.match(5)) {
  8932. this.scope.enter(256);
  8933. this.prodParam.enter(0);
  8934. const mod = node;
  8935. mod.kind = "global";
  8936. {
  8937. node.global = true;
  8938. }
  8939. mod.id = expr;
  8940. mod.body = this.tsParseModuleBlock();
  8941. this.scope.exit();
  8942. this.prodParam.exit();
  8943. return this.finishNode(mod, "TSModuleDeclaration");
  8944. }
  8945. break;
  8946. default:
  8947. return this.tsParseDeclaration(node, expr.name, false, decorators);
  8948. }
  8949. }
  8950. tsParseDeclaration(node, value, next, decorators) {
  8951. switch (value) {
  8952. case "abstract":
  8953. if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) {
  8954. return this.tsParseAbstractDeclaration(node, decorators);
  8955. }
  8956. break;
  8957. case "module":
  8958. if (this.tsCheckLineTerminator(next)) {
  8959. if (this.match(134)) {
  8960. return this.tsParseAmbientExternalModuleDeclaration(node);
  8961. } else if (tokenIsIdentifier(this.state.type)) {
  8962. node.kind = "module";
  8963. return this.tsParseModuleOrNamespaceDeclaration(node);
  8964. }
  8965. }
  8966. break;
  8967. case "namespace":
  8968. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8969. node.kind = "namespace";
  8970. return this.tsParseModuleOrNamespaceDeclaration(node);
  8971. }
  8972. break;
  8973. case "type":
  8974. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8975. return this.tsParseTypeAliasDeclaration(node);
  8976. }
  8977. break;
  8978. }
  8979. }
  8980. tsCheckLineTerminator(next) {
  8981. if (next) {
  8982. if (this.hasFollowingLineBreak()) return false;
  8983. this.next();
  8984. return true;
  8985. }
  8986. return !this.isLineTerminator();
  8987. }
  8988. tsTryParseGenericAsyncArrowFunction(startLoc) {
  8989. if (!this.match(47)) return;
  8990. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8991. this.state.maybeInArrowParameters = true;
  8992. const res = this.tsTryParseAndCatch(() => {
  8993. const node = this.startNodeAt(startLoc);
  8994. node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  8995. super.parseFunctionParams(node);
  8996. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  8997. this.expect(19);
  8998. return node;
  8999. });
  9000. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9001. if (!res) return;
  9002. return super.parseArrowExpression(res, null, true);
  9003. }
  9004. tsParseTypeArgumentsInExpression() {
  9005. if (this.reScan_lt() !== 47) return;
  9006. return this.tsParseTypeArguments();
  9007. }
  9008. tsParseTypeArguments() {
  9009. const node = this.startNode();
  9010. node.params = this.tsInType(() => this.tsInTopLevelContext(() => {
  9011. this.expect(47);
  9012. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  9013. }));
  9014. if (node.params.length === 0) {
  9015. this.raise(TSErrors.EmptyTypeArguments, node);
  9016. } else if (!this.state.inType && this.curContext() === types.brace) {
  9017. this.reScan_lt_gt();
  9018. }
  9019. this.expect(48);
  9020. return this.finishNode(node, "TSTypeParameterInstantiation");
  9021. }
  9022. tsIsDeclarationStart() {
  9023. return tokenIsTSDeclarationStart(this.state.type);
  9024. }
  9025. isExportDefaultSpecifier() {
  9026. if (this.tsIsDeclarationStart()) return false;
  9027. return super.isExportDefaultSpecifier();
  9028. }
  9029. parseBindingElement(flags, decorators) {
  9030. const startLoc = this.state.startLoc;
  9031. const modified = {};
  9032. this.tsParseModifiers({
  9033. allowedModifiers: ["public", "private", "protected", "override", "readonly"]
  9034. }, modified);
  9035. const accessibility = modified.accessibility;
  9036. const override = modified.override;
  9037. const readonly = modified.readonly;
  9038. if (!(flags & 4) && (accessibility || readonly || override)) {
  9039. this.raise(TSErrors.UnexpectedParameterModifier, startLoc);
  9040. }
  9041. const left = this.parseMaybeDefault();
  9042. if (flags & 2) {
  9043. this.parseFunctionParamType(left);
  9044. }
  9045. const elt = this.parseMaybeDefault(left.loc.start, left);
  9046. if (accessibility || readonly || override) {
  9047. const pp = this.startNodeAt(startLoc);
  9048. if (decorators.length) {
  9049. pp.decorators = decorators;
  9050. }
  9051. if (accessibility) pp.accessibility = accessibility;
  9052. if (readonly) pp.readonly = readonly;
  9053. if (override) pp.override = override;
  9054. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  9055. this.raise(TSErrors.UnsupportedParameterPropertyKind, pp);
  9056. }
  9057. pp.parameter = elt;
  9058. return this.finishNode(pp, "TSParameterProperty");
  9059. }
  9060. if (decorators.length) {
  9061. left.decorators = decorators;
  9062. }
  9063. return elt;
  9064. }
  9065. isSimpleParameter(node) {
  9066. return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node);
  9067. }
  9068. tsDisallowOptionalPattern(node) {
  9069. for (const param of node.params) {
  9070. if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) {
  9071. this.raise(TSErrors.PatternIsOptional, param);
  9072. }
  9073. }
  9074. }
  9075. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  9076. super.setArrowFunctionParameters(node, params, trailingCommaLoc);
  9077. this.tsDisallowOptionalPattern(node);
  9078. }
  9079. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  9080. if (this.match(14)) {
  9081. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9082. }
  9083. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  9084. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  9085. return this.finishNode(node, bodilessType);
  9086. }
  9087. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  9088. this.raise(TSErrors.DeclareFunctionHasImplementation, node);
  9089. if (node.declare) {
  9090. return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  9091. }
  9092. }
  9093. this.tsDisallowOptionalPattern(node);
  9094. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  9095. }
  9096. registerFunctionStatementId(node) {
  9097. if (!node.body && node.id) {
  9098. this.checkIdentifier(node.id, 1024);
  9099. } else {
  9100. super.registerFunctionStatementId(node);
  9101. }
  9102. }
  9103. tsCheckForInvalidTypeCasts(items) {
  9104. items.forEach(node => {
  9105. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  9106. this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation);
  9107. }
  9108. });
  9109. }
  9110. toReferencedList(exprList, isInParens) {
  9111. this.tsCheckForInvalidTypeCasts(exprList);
  9112. return exprList;
  9113. }
  9114. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  9115. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  9116. if (node.type === "ArrayExpression") {
  9117. this.tsCheckForInvalidTypeCasts(node.elements);
  9118. }
  9119. return node;
  9120. }
  9121. parseSubscript(base, startLoc, noCalls, state) {
  9122. if (!this.hasPrecedingLineBreak() && this.match(35)) {
  9123. this.state.canStartJSXElement = false;
  9124. this.next();
  9125. const nonNullExpression = this.startNodeAt(startLoc);
  9126. nonNullExpression.expression = base;
  9127. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  9128. }
  9129. let isOptionalCall = false;
  9130. if (this.match(18) && this.lookaheadCharCode() === 60) {
  9131. if (noCalls) {
  9132. state.stop = true;
  9133. return base;
  9134. }
  9135. state.optionalChainMember = isOptionalCall = true;
  9136. this.next();
  9137. }
  9138. if (this.match(47) || this.match(51)) {
  9139. let missingParenErrorLoc;
  9140. const result = this.tsTryParseAndCatch(() => {
  9141. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  9142. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc);
  9143. if (asyncArrowFn) {
  9144. return asyncArrowFn;
  9145. }
  9146. }
  9147. const typeArguments = this.tsParseTypeArgumentsInExpression();
  9148. if (!typeArguments) return;
  9149. if (isOptionalCall && !this.match(10)) {
  9150. missingParenErrorLoc = this.state.curPosition();
  9151. return;
  9152. }
  9153. if (tokenIsTemplate(this.state.type)) {
  9154. const result = super.parseTaggedTemplateExpression(base, startLoc, state);
  9155. {
  9156. result.typeParameters = typeArguments;
  9157. }
  9158. return result;
  9159. }
  9160. if (!noCalls && this.eat(10)) {
  9161. const node = this.startNodeAt(startLoc);
  9162. node.callee = base;
  9163. node.arguments = this.parseCallExpressionArguments(11);
  9164. this.tsCheckForInvalidTypeCasts(node.arguments);
  9165. {
  9166. node.typeParameters = typeArguments;
  9167. }
  9168. if (state.optionalChainMember) {
  9169. node.optional = isOptionalCall;
  9170. }
  9171. return this.finishCallExpression(node, state.optionalChainMember);
  9172. }
  9173. const tokenType = this.state.type;
  9174. if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) {
  9175. return;
  9176. }
  9177. const node = this.startNodeAt(startLoc);
  9178. node.expression = base;
  9179. {
  9180. node.typeParameters = typeArguments;
  9181. }
  9182. return this.finishNode(node, "TSInstantiationExpression");
  9183. });
  9184. if (missingParenErrorLoc) {
  9185. this.unexpected(missingParenErrorLoc, 10);
  9186. }
  9187. if (result) {
  9188. if (result.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) {
  9189. this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc);
  9190. }
  9191. return result;
  9192. }
  9193. }
  9194. return super.parseSubscript(base, startLoc, noCalls, state);
  9195. }
  9196. parseNewCallee(node) {
  9197. var _callee$extra;
  9198. super.parseNewCallee(node);
  9199. const {
  9200. callee
  9201. } = node;
  9202. if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) {
  9203. {
  9204. node.typeParameters = callee.typeParameters;
  9205. }
  9206. node.callee = callee.expression;
  9207. }
  9208. }
  9209. parseExprOp(left, leftStartLoc, minPrec) {
  9210. let isSatisfies;
  9211. if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) {
  9212. const node = this.startNodeAt(leftStartLoc);
  9213. node.expression = left;
  9214. node.typeAnnotation = this.tsInType(() => {
  9215. this.next();
  9216. if (this.match(75)) {
  9217. if (isSatisfies) {
  9218. this.raise(Errors.UnexpectedKeyword, this.state.startLoc, {
  9219. keyword: "const"
  9220. });
  9221. }
  9222. return this.tsParseTypeReference();
  9223. }
  9224. return this.tsParseType();
  9225. });
  9226. this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression");
  9227. this.reScan_lt_gt();
  9228. return this.parseExprOp(node, leftStartLoc, minPrec);
  9229. }
  9230. return super.parseExprOp(left, leftStartLoc, minPrec);
  9231. }
  9232. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9233. if (!this.state.isAmbientContext) {
  9234. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  9235. }
  9236. }
  9237. checkImportReflection(node) {
  9238. super.checkImportReflection(node);
  9239. if (node.module && node.importKind !== "value") {
  9240. this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  9241. }
  9242. }
  9243. checkDuplicateExports() {}
  9244. isPotentialImportPhase(isExport) {
  9245. if (super.isPotentialImportPhase(isExport)) return true;
  9246. if (this.isContextual(130)) {
  9247. const ch = this.lookaheadCharCode();
  9248. return isExport ? ch === 123 || ch === 42 : ch !== 61;
  9249. }
  9250. return !isExport && this.isContextual(87);
  9251. }
  9252. applyImportPhase(node, isExport, phase, loc) {
  9253. super.applyImportPhase(node, isExport, phase, loc);
  9254. if (isExport) {
  9255. node.exportKind = phase === "type" ? "type" : "value";
  9256. } else {
  9257. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  9258. }
  9259. }
  9260. parseImport(node) {
  9261. if (this.match(134)) {
  9262. node.importKind = "value";
  9263. return super.parseImport(node);
  9264. }
  9265. let importNode;
  9266. if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) {
  9267. node.importKind = "value";
  9268. return this.tsParseImportEqualsDeclaration(node);
  9269. } else if (this.isContextual(130)) {
  9270. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false);
  9271. if (this.lookaheadCharCode() === 61) {
  9272. return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier);
  9273. } else {
  9274. importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier);
  9275. }
  9276. } else {
  9277. importNode = super.parseImport(node);
  9278. }
  9279. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  9280. this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode);
  9281. }
  9282. return importNode;
  9283. }
  9284. parseExport(node, decorators) {
  9285. if (this.match(83)) {
  9286. const nodeImportEquals = node;
  9287. this.next();
  9288. let maybeDefaultIdentifier = null;
  9289. if (this.isContextual(130) && this.isPotentialImportPhase(false)) {
  9290. maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false);
  9291. } else {
  9292. nodeImportEquals.importKind = "value";
  9293. }
  9294. const declaration = this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true);
  9295. {
  9296. return declaration;
  9297. }
  9298. } else if (this.eat(29)) {
  9299. const assign = node;
  9300. assign.expression = super.parseExpression();
  9301. this.semicolon();
  9302. this.sawUnambiguousESM = true;
  9303. return this.finishNode(assign, "TSExportAssignment");
  9304. } else if (this.eatContextual(93)) {
  9305. const decl = node;
  9306. this.expectContextual(128);
  9307. decl.id = this.parseIdentifier();
  9308. this.semicolon();
  9309. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  9310. } else {
  9311. return super.parseExport(node, decorators);
  9312. }
  9313. }
  9314. isAbstractClass() {
  9315. return this.isContextual(124) && this.lookahead().type === 80;
  9316. }
  9317. parseExportDefaultExpression() {
  9318. if (this.isAbstractClass()) {
  9319. const cls = this.startNode();
  9320. this.next();
  9321. cls.abstract = true;
  9322. return this.parseClass(cls, true, true);
  9323. }
  9324. if (this.match(129)) {
  9325. const result = this.tsParseInterfaceDeclaration(this.startNode());
  9326. if (result) return result;
  9327. }
  9328. return super.parseExportDefaultExpression();
  9329. }
  9330. parseVarStatement(node, kind, allowMissingInitializer = false) {
  9331. const {
  9332. isAmbientContext
  9333. } = this.state;
  9334. const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext);
  9335. if (!isAmbientContext) return declaration;
  9336. for (const {
  9337. id,
  9338. init
  9339. } of declaration.declarations) {
  9340. if (!init) continue;
  9341. if (kind !== "const" || !!id.typeAnnotation) {
  9342. this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init);
  9343. } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) {
  9344. this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init);
  9345. }
  9346. }
  9347. return declaration;
  9348. }
  9349. parseStatementContent(flags, decorators) {
  9350. if (this.match(75) && this.isLookaheadContextual("enum")) {
  9351. const node = this.startNode();
  9352. this.expect(75);
  9353. return this.tsParseEnumDeclaration(node, {
  9354. const: true
  9355. });
  9356. }
  9357. if (this.isContextual(126)) {
  9358. return this.tsParseEnumDeclaration(this.startNode());
  9359. }
  9360. if (this.isContextual(129)) {
  9361. const result = this.tsParseInterfaceDeclaration(this.startNode());
  9362. if (result) return result;
  9363. }
  9364. return super.parseStatementContent(flags, decorators);
  9365. }
  9366. parseAccessModifier() {
  9367. return this.tsParseModifier(["public", "protected", "private"]);
  9368. }
  9369. tsHasSomeModifiers(member, modifiers) {
  9370. return modifiers.some(modifier => {
  9371. if (tsIsAccessModifier(modifier)) {
  9372. return member.accessibility === modifier;
  9373. }
  9374. return !!member[modifier];
  9375. });
  9376. }
  9377. tsIsStartOfStaticBlocks() {
  9378. return this.isContextual(106) && this.lookaheadCharCode() === 123;
  9379. }
  9380. parseClassMember(classBody, member, state) {
  9381. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  9382. this.tsParseModifiers({
  9383. allowedModifiers: modifiers,
  9384. disallowedModifiers: ["in", "out"],
  9385. stopOnStartOfClassStaticBlock: true,
  9386. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  9387. }, member);
  9388. const callParseClassMemberWithIsStatic = () => {
  9389. if (this.tsIsStartOfStaticBlocks()) {
  9390. this.next();
  9391. this.next();
  9392. if (this.tsHasSomeModifiers(member, modifiers)) {
  9393. this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition());
  9394. }
  9395. super.parseClassStaticBlock(classBody, member);
  9396. } else {
  9397. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  9398. }
  9399. };
  9400. if (member.declare) {
  9401. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  9402. } else {
  9403. callParseClassMemberWithIsStatic();
  9404. }
  9405. }
  9406. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  9407. const idx = this.tsTryParseIndexSignature(member);
  9408. if (idx) {
  9409. classBody.body.push(idx);
  9410. if (member.abstract) {
  9411. this.raise(TSErrors.IndexSignatureHasAbstract, member);
  9412. }
  9413. if (member.accessibility) {
  9414. this.raise(TSErrors.IndexSignatureHasAccessibility, member, {
  9415. modifier: member.accessibility
  9416. });
  9417. }
  9418. if (member.declare) {
  9419. this.raise(TSErrors.IndexSignatureHasDeclare, member);
  9420. }
  9421. if (member.override) {
  9422. this.raise(TSErrors.IndexSignatureHasOverride, member);
  9423. }
  9424. return;
  9425. }
  9426. if (!this.state.inAbstractClass && member.abstract) {
  9427. this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member);
  9428. }
  9429. if (member.override) {
  9430. if (!state.hadSuperClass) {
  9431. this.raise(TSErrors.OverrideNotInSubClass, member);
  9432. }
  9433. }
  9434. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  9435. }
  9436. parsePostMemberNameModifiers(methodOrProp) {
  9437. const optional = this.eat(17);
  9438. if (optional) methodOrProp.optional = true;
  9439. if (methodOrProp.readonly && this.match(10)) {
  9440. this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp);
  9441. }
  9442. if (methodOrProp.declare && this.match(10)) {
  9443. this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp);
  9444. }
  9445. }
  9446. parseExpressionStatement(node, expr, decorators) {
  9447. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr, decorators) : undefined;
  9448. return decl || super.parseExpressionStatement(node, expr, decorators);
  9449. }
  9450. shouldParseExportDeclaration() {
  9451. if (this.tsIsDeclarationStart()) return true;
  9452. return super.shouldParseExportDeclaration();
  9453. }
  9454. parseConditional(expr, startLoc, refExpressionErrors) {
  9455. if (!this.match(17)) return expr;
  9456. if (this.state.maybeInArrowParameters) {
  9457. const nextCh = this.lookaheadCharCode();
  9458. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  9459. this.setOptionalParametersError(refExpressionErrors);
  9460. return expr;
  9461. }
  9462. }
  9463. return super.parseConditional(expr, startLoc, refExpressionErrors);
  9464. }
  9465. parseParenItem(node, startLoc) {
  9466. const newNode = super.parseParenItem(node, startLoc);
  9467. if (this.eat(17)) {
  9468. newNode.optional = true;
  9469. this.resetEndLocation(node);
  9470. }
  9471. if (this.match(14)) {
  9472. const typeCastNode = this.startNodeAt(startLoc);
  9473. typeCastNode.expression = node;
  9474. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  9475. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  9476. }
  9477. return node;
  9478. }
  9479. parseExportDeclaration(node) {
  9480. if (!this.state.isAmbientContext && this.isContextual(125)) {
  9481. return this.tsInAmbientContext(() => this.parseExportDeclaration(node));
  9482. }
  9483. const startLoc = this.state.startLoc;
  9484. const isDeclare = this.eatContextual(125);
  9485. if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) {
  9486. throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc);
  9487. }
  9488. const isIdentifier = tokenIsIdentifier(this.state.type);
  9489. const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node);
  9490. if (!declaration) return null;
  9491. if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) {
  9492. node.exportKind = "type";
  9493. }
  9494. if (isDeclare && declaration.type !== "TSImportEqualsDeclaration") {
  9495. this.resetStartLocation(declaration, startLoc);
  9496. declaration.declare = true;
  9497. }
  9498. return declaration;
  9499. }
  9500. parseClassId(node, isStatement, optionalId, bindingType) {
  9501. if ((!isStatement || optionalId) && this.isContextual(113)) {
  9502. return;
  9503. }
  9504. super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331);
  9505. const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  9506. if (typeParameters) node.typeParameters = typeParameters;
  9507. }
  9508. parseClassPropertyAnnotation(node) {
  9509. if (!node.optional) {
  9510. if (this.eat(35)) {
  9511. node.definite = true;
  9512. } else if (this.eat(17)) {
  9513. node.optional = true;
  9514. }
  9515. }
  9516. const type = this.tsTryParseTypeAnnotation();
  9517. if (type) node.typeAnnotation = type;
  9518. }
  9519. parseClassProperty(node) {
  9520. this.parseClassPropertyAnnotation(node);
  9521. if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) {
  9522. this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc);
  9523. }
  9524. if (node.abstract && this.match(29)) {
  9525. const {
  9526. key
  9527. } = node;
  9528. this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, {
  9529. propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  9530. });
  9531. }
  9532. return super.parseClassProperty(node);
  9533. }
  9534. parseClassPrivateProperty(node) {
  9535. if (node.abstract) {
  9536. this.raise(TSErrors.PrivateElementHasAbstract, node);
  9537. }
  9538. if (node.accessibility) {
  9539. this.raise(TSErrors.PrivateElementHasAccessibility, node, {
  9540. modifier: node.accessibility
  9541. });
  9542. }
  9543. this.parseClassPropertyAnnotation(node);
  9544. return super.parseClassPrivateProperty(node);
  9545. }
  9546. parseClassAccessorProperty(node) {
  9547. this.parseClassPropertyAnnotation(node);
  9548. if (node.optional) {
  9549. this.raise(TSErrors.AccessorCannotBeOptional, node);
  9550. }
  9551. return super.parseClassAccessorProperty(node);
  9552. }
  9553. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9554. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9555. if (typeParameters && isConstructor) {
  9556. this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters);
  9557. }
  9558. const {
  9559. declare = false,
  9560. kind
  9561. } = method;
  9562. if (declare && (kind === "get" || kind === "set")) {
  9563. this.raise(TSErrors.DeclareAccessor, method, {
  9564. kind
  9565. });
  9566. }
  9567. if (typeParameters) method.typeParameters = typeParameters;
  9568. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  9569. }
  9570. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9571. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9572. if (typeParameters) method.typeParameters = typeParameters;
  9573. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  9574. }
  9575. declareClassPrivateMethodInScope(node, kind) {
  9576. if (node.type === "TSDeclareMethod") return;
  9577. if (node.type === "MethodDefinition" && !hasOwnProperty.call(node.value, "body")) {
  9578. return;
  9579. }
  9580. super.declareClassPrivateMethodInScope(node, kind);
  9581. }
  9582. parseClassSuper(node) {
  9583. super.parseClassSuper(node);
  9584. if (node.superClass && (this.match(47) || this.match(51))) {
  9585. {
  9586. node.superTypeParameters = this.tsParseTypeArgumentsInExpression();
  9587. }
  9588. }
  9589. if (this.eatContextual(113)) {
  9590. node.implements = this.tsParseHeritageClause("implements");
  9591. }
  9592. }
  9593. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  9594. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9595. if (typeParameters) prop.typeParameters = typeParameters;
  9596. return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  9597. }
  9598. parseFunctionParams(node, isConstructor) {
  9599. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9600. if (typeParameters) node.typeParameters = typeParameters;
  9601. super.parseFunctionParams(node, isConstructor);
  9602. }
  9603. parseVarId(decl, kind) {
  9604. super.parseVarId(decl, kind);
  9605. if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) {
  9606. decl.definite = true;
  9607. }
  9608. const type = this.tsTryParseTypeAnnotation();
  9609. if (type) {
  9610. decl.id.typeAnnotation = type;
  9611. this.resetEndLocation(decl.id);
  9612. }
  9613. }
  9614. parseAsyncArrowFromCallExpression(node, call) {
  9615. if (this.match(14)) {
  9616. node.returnType = this.tsParseTypeAnnotation();
  9617. }
  9618. return super.parseAsyncArrowFromCallExpression(node, call);
  9619. }
  9620. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  9621. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2;
  9622. let state;
  9623. let jsx;
  9624. let typeCast;
  9625. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  9626. state = this.state.clone();
  9627. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  9628. if (!jsx.error) return jsx.node;
  9629. const {
  9630. context
  9631. } = this.state;
  9632. const currentContext = context[context.length - 1];
  9633. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  9634. context.pop();
  9635. }
  9636. }
  9637. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) {
  9638. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  9639. }
  9640. if (!state || state === this.state) state = this.state.clone();
  9641. let typeParameters;
  9642. const arrow = this.tryParse(abort => {
  9643. var _expr$extra, _typeParameters;
  9644. typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  9645. const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  9646. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  9647. abort();
  9648. }
  9649. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  9650. this.resetStartLocationFromNode(expr, typeParameters);
  9651. }
  9652. expr.typeParameters = typeParameters;
  9653. return expr;
  9654. }, state);
  9655. if (!arrow.error && !arrow.aborted) {
  9656. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  9657. return arrow.node;
  9658. }
  9659. if (!jsx) {
  9660. assert(!this.hasPlugin("jsx"));
  9661. typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  9662. if (!typeCast.error) return typeCast.node;
  9663. }
  9664. if ((_jsx2 = jsx) != null && _jsx2.node) {
  9665. this.state = jsx.failState;
  9666. return jsx.node;
  9667. }
  9668. if (arrow.node) {
  9669. this.state = arrow.failState;
  9670. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  9671. return arrow.node;
  9672. }
  9673. if ((_typeCast = typeCast) != null && _typeCast.node) {
  9674. this.state = typeCast.failState;
  9675. return typeCast.node;
  9676. }
  9677. throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error);
  9678. }
  9679. reportReservedArrowTypeParam(node) {
  9680. var _node$extra2;
  9681. if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra2 = node.extra) != null && _node$extra2.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  9682. this.raise(TSErrors.ReservedArrowTypeParam, node);
  9683. }
  9684. }
  9685. parseMaybeUnary(refExpressionErrors, sawUnary) {
  9686. if (!this.hasPlugin("jsx") && this.match(47)) {
  9687. return this.tsParseTypeAssertion();
  9688. }
  9689. return super.parseMaybeUnary(refExpressionErrors, sawUnary);
  9690. }
  9691. parseArrow(node) {
  9692. if (this.match(14)) {
  9693. const result = this.tryParse(abort => {
  9694. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9695. if (this.canInsertSemicolon() || !this.match(19)) abort();
  9696. return returnType;
  9697. });
  9698. if (result.aborted) return;
  9699. if (!result.thrown) {
  9700. if (result.error) this.state = result.failState;
  9701. node.returnType = result.node;
  9702. }
  9703. }
  9704. return super.parseArrow(node);
  9705. }
  9706. parseFunctionParamType(param) {
  9707. if (this.eat(17)) {
  9708. param.optional = true;
  9709. }
  9710. const type = this.tsTryParseTypeAnnotation();
  9711. if (type) param.typeAnnotation = type;
  9712. this.resetEndLocation(param);
  9713. return param;
  9714. }
  9715. isAssignable(node, isBinding) {
  9716. switch (node.type) {
  9717. case "TSTypeCastExpression":
  9718. return this.isAssignable(node.expression, isBinding);
  9719. case "TSParameterProperty":
  9720. return true;
  9721. default:
  9722. return super.isAssignable(node, isBinding);
  9723. }
  9724. }
  9725. toAssignable(node, isLHS = false) {
  9726. switch (node.type) {
  9727. case "ParenthesizedExpression":
  9728. this.toAssignableParenthesizedExpression(node, isLHS);
  9729. break;
  9730. case "TSAsExpression":
  9731. case "TSSatisfiesExpression":
  9732. case "TSNonNullExpression":
  9733. case "TSTypeAssertion":
  9734. if (isLHS) {
  9735. this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node);
  9736. } else {
  9737. this.raise(TSErrors.UnexpectedTypeCastInParameter, node);
  9738. }
  9739. this.toAssignable(node.expression, isLHS);
  9740. break;
  9741. case "AssignmentExpression":
  9742. if (!isLHS && node.left.type === "TSTypeCastExpression") {
  9743. node.left = this.typeCastToParameter(node.left);
  9744. }
  9745. default:
  9746. super.toAssignable(node, isLHS);
  9747. }
  9748. }
  9749. toAssignableParenthesizedExpression(node, isLHS) {
  9750. switch (node.expression.type) {
  9751. case "TSAsExpression":
  9752. case "TSSatisfiesExpression":
  9753. case "TSNonNullExpression":
  9754. case "TSTypeAssertion":
  9755. case "ParenthesizedExpression":
  9756. this.toAssignable(node.expression, isLHS);
  9757. break;
  9758. default:
  9759. super.toAssignable(node, isLHS);
  9760. }
  9761. }
  9762. checkToRestConversion(node, allowPattern) {
  9763. switch (node.type) {
  9764. case "TSAsExpression":
  9765. case "TSSatisfiesExpression":
  9766. case "TSTypeAssertion":
  9767. case "TSNonNullExpression":
  9768. this.checkToRestConversion(node.expression, false);
  9769. break;
  9770. default:
  9771. super.checkToRestConversion(node, allowPattern);
  9772. }
  9773. }
  9774. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  9775. switch (type) {
  9776. case "TSTypeCastExpression":
  9777. return true;
  9778. case "TSParameterProperty":
  9779. return "parameter";
  9780. case "TSNonNullExpression":
  9781. return "expression";
  9782. case "TSAsExpression":
  9783. case "TSSatisfiesExpression":
  9784. case "TSTypeAssertion":
  9785. return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true];
  9786. default:
  9787. return super.isValidLVal(type, isUnparenthesizedInAssign, binding);
  9788. }
  9789. }
  9790. parseBindingAtom() {
  9791. if (this.state.type === 78) {
  9792. return this.parseIdentifier(true);
  9793. }
  9794. return super.parseBindingAtom();
  9795. }
  9796. parseMaybeDecoratorArguments(expr, startLoc) {
  9797. if (this.match(47) || this.match(51)) {
  9798. const typeArguments = this.tsParseTypeArgumentsInExpression();
  9799. if (this.match(10)) {
  9800. const call = super.parseMaybeDecoratorArguments(expr, startLoc);
  9801. {
  9802. call.typeParameters = typeArguments;
  9803. }
  9804. return call;
  9805. }
  9806. this.unexpected(null, 10);
  9807. }
  9808. return super.parseMaybeDecoratorArguments(expr, startLoc);
  9809. }
  9810. checkCommaAfterRest(close) {
  9811. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  9812. this.next();
  9813. return false;
  9814. }
  9815. return super.checkCommaAfterRest(close);
  9816. }
  9817. isClassMethod() {
  9818. return this.match(47) || super.isClassMethod();
  9819. }
  9820. isClassProperty() {
  9821. return this.match(35) || this.match(14) || super.isClassProperty();
  9822. }
  9823. parseMaybeDefault(startLoc, left) {
  9824. const node = super.parseMaybeDefault(startLoc, left);
  9825. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  9826. this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation);
  9827. }
  9828. return node;
  9829. }
  9830. getTokenFromCode(code) {
  9831. if (this.state.inType) {
  9832. if (code === 62) {
  9833. this.finishOp(48, 1);
  9834. return;
  9835. }
  9836. if (code === 60) {
  9837. this.finishOp(47, 1);
  9838. return;
  9839. }
  9840. }
  9841. super.getTokenFromCode(code);
  9842. }
  9843. reScan_lt_gt() {
  9844. const {
  9845. type
  9846. } = this.state;
  9847. if (type === 47) {
  9848. this.state.pos -= 1;
  9849. this.readToken_lt();
  9850. } else if (type === 48) {
  9851. this.state.pos -= 1;
  9852. this.readToken_gt();
  9853. }
  9854. }
  9855. reScan_lt() {
  9856. const {
  9857. type
  9858. } = this.state;
  9859. if (type === 51) {
  9860. this.state.pos -= 2;
  9861. this.finishOp(47, 1);
  9862. return 47;
  9863. }
  9864. return type;
  9865. }
  9866. toAssignableListItem(exprList, index, isLHS) {
  9867. const node = exprList[index];
  9868. if (node.type === "TSTypeCastExpression") {
  9869. exprList[index] = this.typeCastToParameter(node);
  9870. }
  9871. super.toAssignableListItem(exprList, index, isLHS);
  9872. }
  9873. typeCastToParameter(node) {
  9874. node.expression.typeAnnotation = node.typeAnnotation;
  9875. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  9876. return node.expression;
  9877. }
  9878. shouldParseArrow(params) {
  9879. if (this.match(14)) {
  9880. return params.every(expr => this.isAssignable(expr, true));
  9881. }
  9882. return super.shouldParseArrow(params);
  9883. }
  9884. shouldParseAsyncArrow() {
  9885. return this.match(14) || super.shouldParseAsyncArrow();
  9886. }
  9887. canHaveLeadingDecorator() {
  9888. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  9889. }
  9890. jsxParseOpeningElementAfterName(node) {
  9891. if (this.match(47) || this.match(51)) {
  9892. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression());
  9893. if (typeArguments) {
  9894. {
  9895. node.typeParameters = typeArguments;
  9896. }
  9897. }
  9898. }
  9899. return super.jsxParseOpeningElementAfterName(node);
  9900. }
  9901. getGetterSetterExpectedParamCount(method) {
  9902. const baseCount = super.getGetterSetterExpectedParamCount(method);
  9903. const params = this.getObjectOrClassMethodParams(method);
  9904. const firstParam = params[0];
  9905. const hasContextParam = firstParam && this.isThisParam(firstParam);
  9906. return hasContextParam ? baseCount + 1 : baseCount;
  9907. }
  9908. parseCatchClauseParam() {
  9909. const param = super.parseCatchClauseParam();
  9910. const type = this.tsTryParseTypeAnnotation();
  9911. if (type) {
  9912. param.typeAnnotation = type;
  9913. this.resetEndLocation(param);
  9914. }
  9915. return param;
  9916. }
  9917. tsInAmbientContext(cb) {
  9918. const {
  9919. isAmbientContext: oldIsAmbientContext,
  9920. strict: oldStrict
  9921. } = this.state;
  9922. this.state.isAmbientContext = true;
  9923. this.state.strict = false;
  9924. try {
  9925. return cb();
  9926. } finally {
  9927. this.state.isAmbientContext = oldIsAmbientContext;
  9928. this.state.strict = oldStrict;
  9929. }
  9930. }
  9931. parseClass(node, isStatement, optionalId) {
  9932. const oldInAbstractClass = this.state.inAbstractClass;
  9933. this.state.inAbstractClass = !!node.abstract;
  9934. try {
  9935. return super.parseClass(node, isStatement, optionalId);
  9936. } finally {
  9937. this.state.inAbstractClass = oldInAbstractClass;
  9938. }
  9939. }
  9940. tsParseAbstractDeclaration(node, decorators) {
  9941. if (this.match(80)) {
  9942. node.abstract = true;
  9943. return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false));
  9944. } else if (this.isContextual(129)) {
  9945. if (!this.hasFollowingLineBreak()) {
  9946. node.abstract = true;
  9947. this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, node);
  9948. return this.tsParseInterfaceDeclaration(node);
  9949. }
  9950. } else {
  9951. this.unexpected(null, 80);
  9952. }
  9953. }
  9954. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) {
  9955. const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  9956. if (method.abstract) {
  9957. const hasEstreePlugin = this.hasPlugin("estree");
  9958. const methodFn = hasEstreePlugin ? method.value : method;
  9959. if (methodFn.body) {
  9960. const {
  9961. key
  9962. } = method;
  9963. this.raise(TSErrors.AbstractMethodHasImplementation, method, {
  9964. methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  9965. });
  9966. }
  9967. }
  9968. return method;
  9969. }
  9970. tsParseTypeParameterName() {
  9971. const typeName = this.parseIdentifier();
  9972. return typeName.name;
  9973. }
  9974. shouldParseAsAmbientContext() {
  9975. return !!this.getPluginOption("typescript", "dts");
  9976. }
  9977. parse() {
  9978. if (this.shouldParseAsAmbientContext()) {
  9979. this.state.isAmbientContext = true;
  9980. }
  9981. return super.parse();
  9982. }
  9983. getExpression() {
  9984. if (this.shouldParseAsAmbientContext()) {
  9985. this.state.isAmbientContext = true;
  9986. }
  9987. return super.getExpression();
  9988. }
  9989. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  9990. if (!isString && isMaybeTypeOnly) {
  9991. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  9992. return this.finishNode(node, "ExportSpecifier");
  9993. }
  9994. node.exportKind = "value";
  9995. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  9996. }
  9997. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  9998. if (!importedIsString && isMaybeTypeOnly) {
  9999. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  10000. return this.finishNode(specifier, "ImportSpecifier");
  10001. }
  10002. specifier.importKind = "value";
  10003. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096);
  10004. }
  10005. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  10006. const leftOfAsKey = isImport ? "imported" : "local";
  10007. const rightOfAsKey = isImport ? "local" : "exported";
  10008. let leftOfAs = node[leftOfAsKey];
  10009. let rightOfAs;
  10010. let hasTypeSpecifier = false;
  10011. let canParseAsKeyword = true;
  10012. const loc = leftOfAs.loc.start;
  10013. if (this.isContextual(93)) {
  10014. const firstAs = this.parseIdentifier();
  10015. if (this.isContextual(93)) {
  10016. const secondAs = this.parseIdentifier();
  10017. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  10018. hasTypeSpecifier = true;
  10019. leftOfAs = firstAs;
  10020. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  10021. canParseAsKeyword = false;
  10022. } else {
  10023. rightOfAs = secondAs;
  10024. canParseAsKeyword = false;
  10025. }
  10026. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  10027. canParseAsKeyword = false;
  10028. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  10029. } else {
  10030. hasTypeSpecifier = true;
  10031. leftOfAs = firstAs;
  10032. }
  10033. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  10034. hasTypeSpecifier = true;
  10035. if (isImport) {
  10036. leftOfAs = this.parseIdentifier(true);
  10037. if (!this.isContextual(93)) {
  10038. this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true);
  10039. }
  10040. } else {
  10041. leftOfAs = this.parseModuleExportName();
  10042. }
  10043. }
  10044. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  10045. this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc);
  10046. }
  10047. node[leftOfAsKey] = leftOfAs;
  10048. node[rightOfAsKey] = rightOfAs;
  10049. const kindKey = isImport ? "importKind" : "exportKind";
  10050. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  10051. if (canParseAsKeyword && this.eatContextual(93)) {
  10052. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  10053. }
  10054. if (!node[rightOfAsKey]) {
  10055. node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
  10056. }
  10057. if (isImport) {
  10058. this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096);
  10059. }
  10060. }
  10061. };
  10062. function isPossiblyLiteralEnum(expression) {
  10063. if (expression.type !== "MemberExpression") return false;
  10064. const {
  10065. computed,
  10066. property
  10067. } = expression;
  10068. if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) {
  10069. return false;
  10070. }
  10071. return isUncomputedMemberExpressionChain(expression.object);
  10072. }
  10073. function isValidAmbientConstInitializer(expression, estree) {
  10074. var _expression$extra;
  10075. const {
  10076. type
  10077. } = expression;
  10078. if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) {
  10079. return false;
  10080. }
  10081. if (estree) {
  10082. if (type === "Literal") {
  10083. const {
  10084. value
  10085. } = expression;
  10086. if (typeof value === "string" || typeof value === "boolean") {
  10087. return true;
  10088. }
  10089. }
  10090. } else {
  10091. if (type === "StringLiteral" || type === "BooleanLiteral") {
  10092. return true;
  10093. }
  10094. }
  10095. if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) {
  10096. return true;
  10097. }
  10098. if (type === "TemplateLiteral" && expression.expressions.length === 0) {
  10099. return true;
  10100. }
  10101. if (isPossiblyLiteralEnum(expression)) {
  10102. return true;
  10103. }
  10104. return false;
  10105. }
  10106. function isNumber(expression, estree) {
  10107. if (estree) {
  10108. return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression);
  10109. }
  10110. return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral";
  10111. }
  10112. function isNegativeNumber(expression, estree) {
  10113. if (expression.type === "UnaryExpression") {
  10114. const {
  10115. operator,
  10116. argument
  10117. } = expression;
  10118. if (operator === "-" && isNumber(argument, estree)) {
  10119. return true;
  10120. }
  10121. }
  10122. return false;
  10123. }
  10124. function isUncomputedMemberExpressionChain(expression) {
  10125. if (expression.type === "Identifier") return true;
  10126. if (expression.type !== "MemberExpression" || expression.computed) {
  10127. return false;
  10128. }
  10129. return isUncomputedMemberExpressionChain(expression.object);
  10130. }
  10131. const PlaceholderErrors = ParseErrorEnum`placeholders`({
  10132. ClassNameIsRequired: "A class name is required.",
  10133. UnexpectedSpace: "Unexpected space in placeholder."
  10134. });
  10135. var placeholders = superClass => class PlaceholdersParserMixin extends superClass {
  10136. parsePlaceholder(expectedNode) {
  10137. if (this.match(133)) {
  10138. const node = this.startNode();
  10139. this.next();
  10140. this.assertNoSpace();
  10141. node.name = super.parseIdentifier(true);
  10142. this.assertNoSpace();
  10143. this.expect(133);
  10144. return this.finishPlaceholder(node, expectedNode);
  10145. }
  10146. }
  10147. finishPlaceholder(node, expectedNode) {
  10148. let placeholder = node;
  10149. if (!placeholder.expectedNode || !placeholder.type) {
  10150. placeholder = this.finishNode(placeholder, "Placeholder");
  10151. }
  10152. placeholder.expectedNode = expectedNode;
  10153. return placeholder;
  10154. }
  10155. getTokenFromCode(code) {
  10156. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  10157. this.finishOp(133, 2);
  10158. } else {
  10159. super.getTokenFromCode(code);
  10160. }
  10161. }
  10162. parseExprAtom(refExpressionErrors) {
  10163. return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors);
  10164. }
  10165. parseIdentifier(liberal) {
  10166. return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal);
  10167. }
  10168. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  10169. if (word !== undefined) {
  10170. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  10171. }
  10172. }
  10173. parseBindingAtom() {
  10174. return this.parsePlaceholder("Pattern") || super.parseBindingAtom();
  10175. }
  10176. isValidLVal(type, isParenthesized, binding) {
  10177. return type === "Placeholder" || super.isValidLVal(type, isParenthesized, binding);
  10178. }
  10179. toAssignable(node, isLHS) {
  10180. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  10181. node.expectedNode = "Pattern";
  10182. } else {
  10183. super.toAssignable(node, isLHS);
  10184. }
  10185. }
  10186. chStartsBindingIdentifier(ch, pos) {
  10187. if (super.chStartsBindingIdentifier(ch, pos)) {
  10188. return true;
  10189. }
  10190. const nextToken = this.lookahead();
  10191. if (nextToken.type === 133) {
  10192. return true;
  10193. }
  10194. return false;
  10195. }
  10196. verifyBreakContinue(node, isBreak) {
  10197. if (node.label && node.label.type === "Placeholder") return;
  10198. super.verifyBreakContinue(node, isBreak);
  10199. }
  10200. parseExpressionStatement(node, expr) {
  10201. var _expr$extra;
  10202. if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  10203. return super.parseExpressionStatement(node, expr);
  10204. }
  10205. if (this.match(14)) {
  10206. const stmt = node;
  10207. stmt.label = this.finishPlaceholder(expr, "Identifier");
  10208. this.next();
  10209. stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration();
  10210. return this.finishNode(stmt, "LabeledStatement");
  10211. }
  10212. this.semicolon();
  10213. const stmtPlaceholder = node;
  10214. stmtPlaceholder.name = expr.name;
  10215. return this.finishPlaceholder(stmtPlaceholder, "Statement");
  10216. }
  10217. parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) {
  10218. return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse);
  10219. }
  10220. parseFunctionId(requireId) {
  10221. return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId);
  10222. }
  10223. parseClass(node, isStatement, optionalId) {
  10224. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  10225. this.next();
  10226. const oldStrict = this.state.strict;
  10227. const placeholder = this.parsePlaceholder("Identifier");
  10228. if (placeholder) {
  10229. if (this.match(81) || this.match(133) || this.match(5)) {
  10230. node.id = placeholder;
  10231. } else if (optionalId || !isStatement) {
  10232. node.id = null;
  10233. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  10234. return this.finishNode(node, type);
  10235. } else {
  10236. throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc);
  10237. }
  10238. } else {
  10239. this.parseClassId(node, isStatement, optionalId);
  10240. }
  10241. super.parseClassSuper(node);
  10242. node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict);
  10243. return this.finishNode(node, type);
  10244. }
  10245. parseExport(node, decorators) {
  10246. const placeholder = this.parsePlaceholder("Identifier");
  10247. if (!placeholder) return super.parseExport(node, decorators);
  10248. const node2 = node;
  10249. if (!this.isContextual(98) && !this.match(12)) {
  10250. node2.specifiers = [];
  10251. node2.source = null;
  10252. node2.declaration = this.finishPlaceholder(placeholder, "Declaration");
  10253. return this.finishNode(node2, "ExportNamedDeclaration");
  10254. }
  10255. this.expectPlugin("exportDefaultFrom");
  10256. const specifier = this.startNode();
  10257. specifier.exported = placeholder;
  10258. node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  10259. return super.parseExport(node2, decorators);
  10260. }
  10261. isExportDefaultSpecifier() {
  10262. if (this.match(65)) {
  10263. const next = this.nextTokenStart();
  10264. if (this.isUnparsedContextual(next, "from")) {
  10265. if (this.input.startsWith(tokenLabelName(133), this.nextTokenStartSince(next + 4))) {
  10266. return true;
  10267. }
  10268. }
  10269. }
  10270. return super.isExportDefaultSpecifier();
  10271. }
  10272. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  10273. var _specifiers;
  10274. if ((_specifiers = node.specifiers) != null && _specifiers.length) {
  10275. return true;
  10276. }
  10277. return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  10278. }
  10279. checkExport(node) {
  10280. const {
  10281. specifiers
  10282. } = node;
  10283. if (specifiers != null && specifiers.length) {
  10284. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  10285. }
  10286. super.checkExport(node);
  10287. node.specifiers = specifiers;
  10288. }
  10289. parseImport(node) {
  10290. const placeholder = this.parsePlaceholder("Identifier");
  10291. if (!placeholder) return super.parseImport(node);
  10292. node.specifiers = [];
  10293. if (!this.isContextual(98) && !this.match(12)) {
  10294. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  10295. this.semicolon();
  10296. return this.finishNode(node, "ImportDeclaration");
  10297. }
  10298. const specifier = this.startNodeAtNode(placeholder);
  10299. specifier.local = placeholder;
  10300. node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier"));
  10301. if (this.eat(12)) {
  10302. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  10303. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  10304. }
  10305. this.expectContextual(98);
  10306. node.source = this.parseImportSource();
  10307. this.semicolon();
  10308. return this.finishNode(node, "ImportDeclaration");
  10309. }
  10310. parseImportSource() {
  10311. return this.parsePlaceholder("StringLiteral") || super.parseImportSource();
  10312. }
  10313. assertNoSpace() {
  10314. if (this.state.start > this.offsetToSourcePos(this.state.lastTokEndLoc.index)) {
  10315. this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc);
  10316. }
  10317. }
  10318. };
  10319. var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass {
  10320. parseV8Intrinsic() {
  10321. if (this.match(54)) {
  10322. const v8IntrinsicStartLoc = this.state.startLoc;
  10323. const node = this.startNode();
  10324. this.next();
  10325. if (tokenIsIdentifier(this.state.type)) {
  10326. const name = this.parseIdentifierName();
  10327. const identifier = this.createIdentifier(node, name);
  10328. identifier.type = "V8IntrinsicIdentifier";
  10329. if (this.match(10)) {
  10330. return identifier;
  10331. }
  10332. }
  10333. this.unexpected(v8IntrinsicStartLoc);
  10334. }
  10335. }
  10336. parseExprAtom(refExpressionErrors) {
  10337. return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors);
  10338. }
  10339. };
  10340. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  10341. const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"];
  10342. function validatePlugins(pluginsMap) {
  10343. if (pluginsMap.has("decorators")) {
  10344. if (pluginsMap.has("decorators-legacy")) {
  10345. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  10346. }
  10347. const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport;
  10348. if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") {
  10349. throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");
  10350. }
  10351. const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized;
  10352. if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") {
  10353. throw new Error("'allowCallParenthesized' must be a boolean.");
  10354. }
  10355. }
  10356. if (pluginsMap.has("flow") && pluginsMap.has("typescript")) {
  10357. throw new Error("Cannot combine flow and typescript plugins.");
  10358. }
  10359. if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) {
  10360. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  10361. }
  10362. if (pluginsMap.has("pipelineOperator")) {
  10363. var _pluginsMap$get;
  10364. const proposal = pluginsMap.get("pipelineOperator").proposal;
  10365. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  10366. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  10367. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  10368. }
  10369. const tupleSyntaxIsHash = ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash";
  10370. if (proposal === "hack") {
  10371. if (pluginsMap.has("placeholders")) {
  10372. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  10373. }
  10374. if (pluginsMap.has("v8intrinsic")) {
  10375. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  10376. }
  10377. const topicToken = pluginsMap.get("pipelineOperator").topicToken;
  10378. if (!TOPIC_TOKENS.includes(topicToken)) {
  10379. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  10380. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  10381. }
  10382. if (topicToken === "#" && tupleSyntaxIsHash) {
  10383. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  10384. }
  10385. } else if (proposal === "smart" && tupleSyntaxIsHash) {
  10386. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  10387. }
  10388. }
  10389. if (pluginsMap.has("moduleAttributes")) {
  10390. {
  10391. if (pluginsMap.has("deprecatedImportAssert") || pluginsMap.has("importAssertions")) {
  10392. throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");
  10393. }
  10394. const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version;
  10395. if (moduleAttributesVersionPluginOption !== "may-2020") {
  10396. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  10397. }
  10398. }
  10399. }
  10400. if (pluginsMap.has("importAssertions")) {
  10401. if (pluginsMap.has("deprecatedImportAssert")) {
  10402. throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");
  10403. }
  10404. }
  10405. if (!pluginsMap.has("deprecatedImportAssert") && pluginsMap.has("importAttributes") && pluginsMap.get("importAttributes").deprecatedAssertSyntax) {
  10406. {
  10407. pluginsMap.set("deprecatedImportAssert", {});
  10408. }
  10409. }
  10410. if (pluginsMap.has("recordAndTuple")) {
  10411. const syntaxType = pluginsMap.get("recordAndTuple").syntaxType;
  10412. if (syntaxType != null) {
  10413. {
  10414. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  10415. if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) {
  10416. throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  10417. }
  10418. }
  10419. }
  10420. }
  10421. if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) {
  10422. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  10423. error.missingPlugins = "doExpressions";
  10424. throw error;
  10425. }
  10426. if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") {
  10427. throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'.");
  10428. }
  10429. }
  10430. const mixinPlugins = {
  10431. estree,
  10432. jsx,
  10433. flow,
  10434. typescript,
  10435. v8intrinsic,
  10436. placeholders
  10437. };
  10438. const mixinPluginNames = Object.keys(mixinPlugins);
  10439. class ExpressionParser extends LValParser {
  10440. checkProto(prop, isRecord, sawProto, refExpressionErrors) {
  10441. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  10442. return sawProto;
  10443. }
  10444. const key = prop.key;
  10445. const name = key.type === "Identifier" ? key.name : key.value;
  10446. if (name === "__proto__") {
  10447. if (isRecord) {
  10448. this.raise(Errors.RecordNoProto, key);
  10449. return true;
  10450. }
  10451. if (sawProto) {
  10452. if (refExpressionErrors) {
  10453. if (refExpressionErrors.doubleProtoLoc === null) {
  10454. refExpressionErrors.doubleProtoLoc = key.loc.start;
  10455. }
  10456. } else {
  10457. this.raise(Errors.DuplicateProto, key);
  10458. }
  10459. }
  10460. return true;
  10461. }
  10462. return sawProto;
  10463. }
  10464. shouldExitDescending(expr, potentialArrowAt) {
  10465. return expr.type === "ArrowFunctionExpression" && this.offsetToSourcePos(expr.start) === potentialArrowAt;
  10466. }
  10467. getExpression() {
  10468. this.enterInitialScopes();
  10469. this.nextToken();
  10470. const expr = this.parseExpression();
  10471. if (!this.match(140)) {
  10472. this.unexpected();
  10473. }
  10474. this.finalizeRemainingComments();
  10475. expr.comments = this.comments;
  10476. expr.errors = this.state.errors;
  10477. if (this.optionFlags & 256) {
  10478. expr.tokens = this.tokens;
  10479. }
  10480. return expr;
  10481. }
  10482. parseExpression(disallowIn, refExpressionErrors) {
  10483. if (disallowIn) {
  10484. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10485. }
  10486. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10487. }
  10488. parseExpressionBase(refExpressionErrors) {
  10489. const startLoc = this.state.startLoc;
  10490. const expr = this.parseMaybeAssign(refExpressionErrors);
  10491. if (this.match(12)) {
  10492. const node = this.startNodeAt(startLoc);
  10493. node.expressions = [expr];
  10494. while (this.eat(12)) {
  10495. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  10496. }
  10497. this.toReferencedList(node.expressions);
  10498. return this.finishNode(node, "SequenceExpression");
  10499. }
  10500. return expr;
  10501. }
  10502. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  10503. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10504. }
  10505. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  10506. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10507. }
  10508. setOptionalParametersError(refExpressionErrors) {
  10509. refExpressionErrors.optionalParametersLoc = this.state.startLoc;
  10510. }
  10511. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  10512. const startLoc = this.state.startLoc;
  10513. const isYield = this.isContextual(108);
  10514. if (isYield) {
  10515. if (this.prodParam.hasYield) {
  10516. this.next();
  10517. let left = this.parseYield(startLoc);
  10518. if (afterLeftParse) {
  10519. left = afterLeftParse.call(this, left, startLoc);
  10520. }
  10521. return left;
  10522. }
  10523. }
  10524. let ownExpressionErrors;
  10525. if (refExpressionErrors) {
  10526. ownExpressionErrors = false;
  10527. } else {
  10528. refExpressionErrors = new ExpressionErrors();
  10529. ownExpressionErrors = true;
  10530. }
  10531. const {
  10532. type
  10533. } = this.state;
  10534. if (type === 10 || tokenIsIdentifier(type)) {
  10535. this.state.potentialArrowAt = this.state.start;
  10536. }
  10537. let left = this.parseMaybeConditional(refExpressionErrors);
  10538. if (afterLeftParse) {
  10539. left = afterLeftParse.call(this, left, startLoc);
  10540. }
  10541. if (tokenIsAssignment(this.state.type)) {
  10542. const node = this.startNodeAt(startLoc);
  10543. const operator = this.state.value;
  10544. node.operator = operator;
  10545. if (this.match(29)) {
  10546. this.toAssignable(left, true);
  10547. node.left = left;
  10548. const startIndex = startLoc.index;
  10549. if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) {
  10550. refExpressionErrors.doubleProtoLoc = null;
  10551. }
  10552. if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) {
  10553. refExpressionErrors.shorthandAssignLoc = null;
  10554. }
  10555. if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) {
  10556. this.checkDestructuringPrivate(refExpressionErrors);
  10557. refExpressionErrors.privateKeyLoc = null;
  10558. }
  10559. } else {
  10560. node.left = left;
  10561. }
  10562. this.next();
  10563. node.right = this.parseMaybeAssign();
  10564. this.checkLVal(left, this.finishNode(node, "AssignmentExpression"));
  10565. return node;
  10566. } else if (ownExpressionErrors) {
  10567. this.checkExpressionErrors(refExpressionErrors, true);
  10568. }
  10569. if (isYield) {
  10570. const {
  10571. type
  10572. } = this.state;
  10573. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  10574. if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {
  10575. this.raiseOverwrite(Errors.YieldNotInGeneratorFunction, startLoc);
  10576. return this.parseYield(startLoc);
  10577. }
  10578. }
  10579. return left;
  10580. }
  10581. parseMaybeConditional(refExpressionErrors) {
  10582. const startLoc = this.state.startLoc;
  10583. const potentialArrowAt = this.state.potentialArrowAt;
  10584. const expr = this.parseExprOps(refExpressionErrors);
  10585. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10586. return expr;
  10587. }
  10588. return this.parseConditional(expr, startLoc, refExpressionErrors);
  10589. }
  10590. parseConditional(expr, startLoc, refExpressionErrors) {
  10591. if (this.eat(17)) {
  10592. const node = this.startNodeAt(startLoc);
  10593. node.test = expr;
  10594. node.consequent = this.parseMaybeAssignAllowIn();
  10595. this.expect(14);
  10596. node.alternate = this.parseMaybeAssign();
  10597. return this.finishNode(node, "ConditionalExpression");
  10598. }
  10599. return expr;
  10600. }
  10601. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  10602. return this.match(139) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  10603. }
  10604. parseExprOps(refExpressionErrors) {
  10605. const startLoc = this.state.startLoc;
  10606. const potentialArrowAt = this.state.potentialArrowAt;
  10607. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  10608. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10609. return expr;
  10610. }
  10611. return this.parseExprOp(expr, startLoc, -1);
  10612. }
  10613. parseExprOp(left, leftStartLoc, minPrec) {
  10614. if (this.isPrivateName(left)) {
  10615. const value = this.getPrivateNameSV(left);
  10616. if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) {
  10617. this.raise(Errors.PrivateInExpectedIn, left, {
  10618. identifierName: value
  10619. });
  10620. }
  10621. this.classScope.usePrivateName(value, left.loc.start);
  10622. }
  10623. const op = this.state.type;
  10624. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) {
  10625. let prec = tokenOperatorPrecedence(op);
  10626. if (prec > minPrec) {
  10627. if (op === 39) {
  10628. this.expectPlugin("pipelineOperator");
  10629. if (this.state.inFSharpPipelineDirectBody) {
  10630. return left;
  10631. }
  10632. this.checkPipelineAtInfixOperator(left, leftStartLoc);
  10633. }
  10634. const node = this.startNodeAt(leftStartLoc);
  10635. node.left = left;
  10636. node.operator = this.state.value;
  10637. const logical = op === 41 || op === 42;
  10638. const coalesce = op === 40;
  10639. if (coalesce) {
  10640. prec = tokenOperatorPrecedence(42);
  10641. }
  10642. this.next();
  10643. if (op === 39 && this.hasPlugin(["pipelineOperator", {
  10644. proposal: "minimal"
  10645. }])) {
  10646. if (this.state.type === 96 && this.prodParam.hasAwait) {
  10647. throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc);
  10648. }
  10649. }
  10650. node.right = this.parseExprOpRightExpr(op, prec);
  10651. const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  10652. const nextOp = this.state.type;
  10653. if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) {
  10654. throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc);
  10655. }
  10656. return this.parseExprOp(finishedNode, leftStartLoc, minPrec);
  10657. }
  10658. }
  10659. return left;
  10660. }
  10661. parseExprOpRightExpr(op, prec) {
  10662. const startLoc = this.state.startLoc;
  10663. switch (op) {
  10664. case 39:
  10665. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  10666. case "hack":
  10667. return this.withTopicBindingContext(() => {
  10668. return this.parseHackPipeBody();
  10669. });
  10670. case "fsharp":
  10671. return this.withSoloAwaitPermittingContext(() => {
  10672. return this.parseFSharpPipelineBody(prec);
  10673. });
  10674. }
  10675. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  10676. return this.withTopicBindingContext(() => {
  10677. if (this.prodParam.hasYield && this.isContextual(108)) {
  10678. throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc);
  10679. }
  10680. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc);
  10681. });
  10682. }
  10683. default:
  10684. return this.parseExprOpBaseRightExpr(op, prec);
  10685. }
  10686. }
  10687. parseExprOpBaseRightExpr(op, prec) {
  10688. const startLoc = this.state.startLoc;
  10689. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  10690. }
  10691. parseHackPipeBody() {
  10692. var _body$extra;
  10693. const {
  10694. startLoc
  10695. } = this.state;
  10696. const body = this.parseMaybeAssign();
  10697. const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type);
  10698. if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  10699. this.raise(Errors.PipeUnparenthesizedBody, startLoc, {
  10700. type: body.type
  10701. });
  10702. }
  10703. if (!this.topicReferenceWasUsedInCurrentContext()) {
  10704. this.raise(Errors.PipeTopicUnused, startLoc);
  10705. }
  10706. return body;
  10707. }
  10708. checkExponentialAfterUnary(node) {
  10709. if (this.match(57)) {
  10710. this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument);
  10711. }
  10712. }
  10713. parseMaybeUnary(refExpressionErrors, sawUnary) {
  10714. const startLoc = this.state.startLoc;
  10715. const isAwait = this.isContextual(96);
  10716. if (isAwait && this.recordAwaitIfAllowed()) {
  10717. this.next();
  10718. const expr = this.parseAwait(startLoc);
  10719. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  10720. return expr;
  10721. }
  10722. const update = this.match(34);
  10723. const node = this.startNode();
  10724. if (tokenIsPrefix(this.state.type)) {
  10725. node.operator = this.state.value;
  10726. node.prefix = true;
  10727. if (this.match(72)) {
  10728. this.expectPlugin("throwExpressions");
  10729. }
  10730. const isDelete = this.match(89);
  10731. this.next();
  10732. node.argument = this.parseMaybeUnary(null, true);
  10733. this.checkExpressionErrors(refExpressionErrors, true);
  10734. if (this.state.strict && isDelete) {
  10735. const arg = node.argument;
  10736. if (arg.type === "Identifier") {
  10737. this.raise(Errors.StrictDelete, node);
  10738. } else if (this.hasPropertyAsPrivateName(arg)) {
  10739. this.raise(Errors.DeletePrivateField, node);
  10740. }
  10741. }
  10742. if (!update) {
  10743. if (!sawUnary) {
  10744. this.checkExponentialAfterUnary(node);
  10745. }
  10746. return this.finishNode(node, "UnaryExpression");
  10747. }
  10748. }
  10749. const expr = this.parseUpdate(node, update, refExpressionErrors);
  10750. if (isAwait) {
  10751. const {
  10752. type
  10753. } = this.state;
  10754. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  10755. if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {
  10756. this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc);
  10757. return this.parseAwait(startLoc);
  10758. }
  10759. }
  10760. return expr;
  10761. }
  10762. parseUpdate(node, update, refExpressionErrors) {
  10763. if (update) {
  10764. const updateExpressionNode = node;
  10765. this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression"));
  10766. return node;
  10767. }
  10768. const startLoc = this.state.startLoc;
  10769. let expr = this.parseExprSubscripts(refExpressionErrors);
  10770. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  10771. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  10772. const node = this.startNodeAt(startLoc);
  10773. node.operator = this.state.value;
  10774. node.prefix = false;
  10775. node.argument = expr;
  10776. this.next();
  10777. this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression"));
  10778. }
  10779. return expr;
  10780. }
  10781. parseExprSubscripts(refExpressionErrors) {
  10782. const startLoc = this.state.startLoc;
  10783. const potentialArrowAt = this.state.potentialArrowAt;
  10784. const expr = this.parseExprAtom(refExpressionErrors);
  10785. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10786. return expr;
  10787. }
  10788. return this.parseSubscripts(expr, startLoc);
  10789. }
  10790. parseSubscripts(base, startLoc, noCalls) {
  10791. const state = {
  10792. optionalChainMember: false,
  10793. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  10794. stop: false
  10795. };
  10796. do {
  10797. base = this.parseSubscript(base, startLoc, noCalls, state);
  10798. state.maybeAsyncArrow = false;
  10799. } while (!state.stop);
  10800. return base;
  10801. }
  10802. parseSubscript(base, startLoc, noCalls, state) {
  10803. const {
  10804. type
  10805. } = this.state;
  10806. if (!noCalls && type === 15) {
  10807. return this.parseBind(base, startLoc, noCalls, state);
  10808. } else if (tokenIsTemplate(type)) {
  10809. return this.parseTaggedTemplateExpression(base, startLoc, state);
  10810. }
  10811. let optional = false;
  10812. if (type === 18) {
  10813. if (noCalls) {
  10814. this.raise(Errors.OptionalChainingNoNew, this.state.startLoc);
  10815. if (this.lookaheadCharCode() === 40) {
  10816. state.stop = true;
  10817. return base;
  10818. }
  10819. }
  10820. state.optionalChainMember = optional = true;
  10821. this.next();
  10822. }
  10823. if (!noCalls && this.match(10)) {
  10824. return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional);
  10825. } else {
  10826. const computed = this.eat(0);
  10827. if (computed || optional || this.eat(16)) {
  10828. return this.parseMember(base, startLoc, state, computed, optional);
  10829. } else {
  10830. state.stop = true;
  10831. return base;
  10832. }
  10833. }
  10834. }
  10835. parseMember(base, startLoc, state, computed, optional) {
  10836. const node = this.startNodeAt(startLoc);
  10837. node.object = base;
  10838. node.computed = computed;
  10839. if (computed) {
  10840. node.property = this.parseExpression();
  10841. this.expect(3);
  10842. } else if (this.match(139)) {
  10843. if (base.type === "Super") {
  10844. this.raise(Errors.SuperPrivateField, startLoc);
  10845. }
  10846. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  10847. node.property = this.parsePrivateName();
  10848. } else {
  10849. node.property = this.parseIdentifier(true);
  10850. }
  10851. if (state.optionalChainMember) {
  10852. node.optional = optional;
  10853. return this.finishNode(node, "OptionalMemberExpression");
  10854. } else {
  10855. return this.finishNode(node, "MemberExpression");
  10856. }
  10857. }
  10858. parseBind(base, startLoc, noCalls, state) {
  10859. const node = this.startNodeAt(startLoc);
  10860. node.object = base;
  10861. this.next();
  10862. node.callee = this.parseNoCallExpr();
  10863. state.stop = true;
  10864. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls);
  10865. }
  10866. parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) {
  10867. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10868. let refExpressionErrors = null;
  10869. this.state.maybeInArrowParameters = true;
  10870. this.next();
  10871. const node = this.startNodeAt(startLoc);
  10872. node.callee = base;
  10873. const {
  10874. maybeAsyncArrow,
  10875. optionalChainMember
  10876. } = state;
  10877. if (maybeAsyncArrow) {
  10878. this.expressionScope.enter(newAsyncArrowScope());
  10879. refExpressionErrors = new ExpressionErrors();
  10880. }
  10881. if (optionalChainMember) {
  10882. node.optional = optional;
  10883. }
  10884. if (optional) {
  10885. node.arguments = this.parseCallExpressionArguments(11);
  10886. } else {
  10887. node.arguments = this.parseCallExpressionArguments(11, base.type !== "Super", node, refExpressionErrors);
  10888. }
  10889. let finishedNode = this.finishCallExpression(node, optionalChainMember);
  10890. if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  10891. state.stop = true;
  10892. this.checkDestructuringPrivate(refExpressionErrors);
  10893. this.expressionScope.validateAsPattern();
  10894. this.expressionScope.exit();
  10895. finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode);
  10896. } else {
  10897. if (maybeAsyncArrow) {
  10898. this.checkExpressionErrors(refExpressionErrors, true);
  10899. this.expressionScope.exit();
  10900. }
  10901. this.toReferencedArguments(finishedNode);
  10902. }
  10903. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10904. return finishedNode;
  10905. }
  10906. toReferencedArguments(node, isParenthesizedExpr) {
  10907. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  10908. }
  10909. parseTaggedTemplateExpression(base, startLoc, state) {
  10910. const node = this.startNodeAt(startLoc);
  10911. node.tag = base;
  10912. node.quasi = this.parseTemplate(true);
  10913. if (state.optionalChainMember) {
  10914. this.raise(Errors.OptionalChainingNoTemplate, startLoc);
  10915. }
  10916. return this.finishNode(node, "TaggedTemplateExpression");
  10917. }
  10918. atPossibleAsyncArrow(base) {
  10919. 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;
  10920. }
  10921. finishCallExpression(node, optional) {
  10922. if (node.callee.type === "Import") {
  10923. if (node.arguments.length === 0 || node.arguments.length > 2) {
  10924. this.raise(Errors.ImportCallArity, node);
  10925. } else {
  10926. for (const arg of node.arguments) {
  10927. if (arg.type === "SpreadElement") {
  10928. this.raise(Errors.ImportCallSpreadArgument, arg);
  10929. }
  10930. }
  10931. }
  10932. }
  10933. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  10934. }
  10935. parseCallExpressionArguments(close, allowPlaceholder, nodeForExtra, refExpressionErrors) {
  10936. const elts = [];
  10937. let first = true;
  10938. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10939. this.state.inFSharpPipelineDirectBody = false;
  10940. while (!this.eat(close)) {
  10941. if (first) {
  10942. first = false;
  10943. } else {
  10944. this.expect(12);
  10945. if (this.match(close)) {
  10946. if (nodeForExtra) {
  10947. this.addTrailingCommaExtraToNode(nodeForExtra);
  10948. }
  10949. this.next();
  10950. break;
  10951. }
  10952. }
  10953. elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
  10954. }
  10955. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10956. return elts;
  10957. }
  10958. shouldParseAsyncArrow() {
  10959. return this.match(19) && !this.canInsertSemicolon();
  10960. }
  10961. parseAsyncArrowFromCallExpression(node, call) {
  10962. var _call$extra;
  10963. this.resetPreviousNodeTrailingComments(call);
  10964. this.expect(19);
  10965. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc);
  10966. if (call.innerComments) {
  10967. setInnerComments(node, call.innerComments);
  10968. }
  10969. if (call.callee.trailingComments) {
  10970. setInnerComments(node, call.callee.trailingComments);
  10971. }
  10972. return node;
  10973. }
  10974. parseNoCallExpr() {
  10975. const startLoc = this.state.startLoc;
  10976. return this.parseSubscripts(this.parseExprAtom(), startLoc, true);
  10977. }
  10978. parseExprAtom(refExpressionErrors) {
  10979. let node;
  10980. let decorators = null;
  10981. const {
  10982. type
  10983. } = this.state;
  10984. switch (type) {
  10985. case 79:
  10986. return this.parseSuper();
  10987. case 83:
  10988. node = this.startNode();
  10989. this.next();
  10990. if (this.match(16)) {
  10991. return this.parseImportMetaProperty(node);
  10992. }
  10993. if (this.match(10)) {
  10994. if (this.optionFlags & 512) {
  10995. return this.parseImportCall(node);
  10996. } else {
  10997. return this.finishNode(node, "Import");
  10998. }
  10999. } else {
  11000. this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc);
  11001. return this.finishNode(node, "Import");
  11002. }
  11003. case 78:
  11004. node = this.startNode();
  11005. this.next();
  11006. return this.finishNode(node, "ThisExpression");
  11007. case 90:
  11008. {
  11009. return this.parseDo(this.startNode(), false);
  11010. }
  11011. case 56:
  11012. case 31:
  11013. {
  11014. this.readRegexp();
  11015. return this.parseRegExpLiteral(this.state.value);
  11016. }
  11017. case 135:
  11018. return this.parseNumericLiteral(this.state.value);
  11019. case 136:
  11020. return this.parseBigIntLiteral(this.state.value);
  11021. case 134:
  11022. return this.parseStringLiteral(this.state.value);
  11023. case 84:
  11024. return this.parseNullLiteral();
  11025. case 85:
  11026. return this.parseBooleanLiteral(true);
  11027. case 86:
  11028. return this.parseBooleanLiteral(false);
  11029. case 10:
  11030. {
  11031. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  11032. return this.parseParenAndDistinguishExpression(canBeArrow);
  11033. }
  11034. case 2:
  11035. case 1:
  11036. {
  11037. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
  11038. }
  11039. case 0:
  11040. {
  11041. return this.parseArrayLike(3, true, false, refExpressionErrors);
  11042. }
  11043. case 6:
  11044. case 7:
  11045. {
  11046. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  11047. }
  11048. case 5:
  11049. {
  11050. return this.parseObjectLike(8, false, false, refExpressionErrors);
  11051. }
  11052. case 68:
  11053. return this.parseFunctionOrFunctionSent();
  11054. case 26:
  11055. decorators = this.parseDecorators();
  11056. case 80:
  11057. return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false);
  11058. case 77:
  11059. return this.parseNewOrNewTarget();
  11060. case 25:
  11061. case 24:
  11062. return this.parseTemplate(false);
  11063. case 15:
  11064. {
  11065. node = this.startNode();
  11066. this.next();
  11067. node.object = null;
  11068. const callee = node.callee = this.parseNoCallExpr();
  11069. if (callee.type === "MemberExpression") {
  11070. return this.finishNode(node, "BindExpression");
  11071. } else {
  11072. throw this.raise(Errors.UnsupportedBind, callee);
  11073. }
  11074. }
  11075. case 139:
  11076. {
  11077. this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, {
  11078. identifierName: this.state.value
  11079. });
  11080. return this.parsePrivateName();
  11081. }
  11082. case 33:
  11083. {
  11084. return this.parseTopicReferenceThenEqualsSign(54, "%");
  11085. }
  11086. case 32:
  11087. {
  11088. return this.parseTopicReferenceThenEqualsSign(44, "^");
  11089. }
  11090. case 37:
  11091. case 38:
  11092. {
  11093. return this.parseTopicReference("hack");
  11094. }
  11095. case 44:
  11096. case 54:
  11097. case 27:
  11098. {
  11099. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  11100. if (pipeProposal) {
  11101. return this.parseTopicReference(pipeProposal);
  11102. }
  11103. this.unexpected();
  11104. break;
  11105. }
  11106. case 47:
  11107. {
  11108. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  11109. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  11110. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  11111. } else {
  11112. this.unexpected();
  11113. }
  11114. break;
  11115. }
  11116. default:
  11117. if (type === 137) {
  11118. return this.parseDecimalLiteral(this.state.value);
  11119. }
  11120. if (tokenIsIdentifier(type)) {
  11121. if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) {
  11122. return this.parseModuleExpression();
  11123. }
  11124. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  11125. const containsEsc = this.state.containsEsc;
  11126. const id = this.parseIdentifier();
  11127. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  11128. const {
  11129. type
  11130. } = this.state;
  11131. if (type === 68) {
  11132. this.resetPreviousNodeTrailingComments(id);
  11133. this.next();
  11134. return this.parseAsyncFunctionExpression(this.startNodeAtNode(id));
  11135. } else if (tokenIsIdentifier(type)) {
  11136. if (this.lookaheadCharCode() === 61) {
  11137. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  11138. } else {
  11139. return id;
  11140. }
  11141. } else if (type === 90) {
  11142. this.resetPreviousNodeTrailingComments(id);
  11143. return this.parseDo(this.startNodeAtNode(id), true);
  11144. }
  11145. }
  11146. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  11147. this.next();
  11148. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  11149. }
  11150. return id;
  11151. } else {
  11152. this.unexpected();
  11153. }
  11154. }
  11155. }
  11156. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  11157. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  11158. if (pipeProposal) {
  11159. this.state.type = topicTokenType;
  11160. this.state.value = topicTokenValue;
  11161. this.state.pos--;
  11162. this.state.end--;
  11163. this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);
  11164. return this.parseTopicReference(pipeProposal);
  11165. } else {
  11166. this.unexpected();
  11167. }
  11168. }
  11169. parseTopicReference(pipeProposal) {
  11170. const node = this.startNode();
  11171. const startLoc = this.state.startLoc;
  11172. const tokenType = this.state.type;
  11173. this.next();
  11174. return this.finishTopicReference(node, startLoc, pipeProposal, tokenType);
  11175. }
  11176. finishTopicReference(node, startLoc, pipeProposal, tokenType) {
  11177. if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) {
  11178. if (pipeProposal === "hack") {
  11179. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  11180. this.raise(Errors.PipeTopicUnbound, startLoc);
  11181. }
  11182. this.registerTopicReference();
  11183. return this.finishNode(node, "TopicReference");
  11184. } else {
  11185. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  11186. this.raise(Errors.PrimaryTopicNotAllowed, startLoc);
  11187. }
  11188. this.registerTopicReference();
  11189. return this.finishNode(node, "PipelinePrimaryTopicReference");
  11190. }
  11191. } else {
  11192. throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, {
  11193. token: tokenLabelName(tokenType)
  11194. });
  11195. }
  11196. }
  11197. testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) {
  11198. switch (pipeProposal) {
  11199. case "hack":
  11200. {
  11201. return this.hasPlugin(["pipelineOperator", {
  11202. topicToken: tokenLabelName(tokenType)
  11203. }]);
  11204. }
  11205. case "smart":
  11206. return tokenType === 27;
  11207. default:
  11208. throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc);
  11209. }
  11210. }
  11211. parseAsyncArrowUnaryFunction(node) {
  11212. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  11213. const params = [this.parseIdentifier()];
  11214. this.prodParam.exit();
  11215. if (this.hasPrecedingLineBreak()) {
  11216. this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition());
  11217. }
  11218. this.expect(19);
  11219. return this.parseArrowExpression(node, params, true);
  11220. }
  11221. parseDo(node, isAsync) {
  11222. this.expectPlugin("doExpressions");
  11223. if (isAsync) {
  11224. this.expectPlugin("asyncDoExpressions");
  11225. }
  11226. node.async = isAsync;
  11227. this.next();
  11228. const oldLabels = this.state.labels;
  11229. this.state.labels = [];
  11230. if (isAsync) {
  11231. this.prodParam.enter(2);
  11232. node.body = this.parseBlock();
  11233. this.prodParam.exit();
  11234. } else {
  11235. node.body = this.parseBlock();
  11236. }
  11237. this.state.labels = oldLabels;
  11238. return this.finishNode(node, "DoExpression");
  11239. }
  11240. parseSuper() {
  11241. const node = this.startNode();
  11242. this.next();
  11243. if (this.match(10) && !this.scope.allowDirectSuper && !(this.optionFlags & 16)) {
  11244. this.raise(Errors.SuperNotAllowed, node);
  11245. } else if (!this.scope.allowSuper && !(this.optionFlags & 16)) {
  11246. this.raise(Errors.UnexpectedSuper, node);
  11247. }
  11248. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  11249. this.raise(Errors.UnsupportedSuper, node);
  11250. }
  11251. return this.finishNode(node, "Super");
  11252. }
  11253. parsePrivateName() {
  11254. const node = this.startNode();
  11255. const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1));
  11256. const name = this.state.value;
  11257. this.next();
  11258. node.id = this.createIdentifier(id, name);
  11259. return this.finishNode(node, "PrivateName");
  11260. }
  11261. parseFunctionOrFunctionSent() {
  11262. const node = this.startNode();
  11263. this.next();
  11264. if (this.prodParam.hasYield && this.match(16)) {
  11265. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  11266. this.next();
  11267. if (this.match(103)) {
  11268. this.expectPlugin("functionSent");
  11269. } else if (!this.hasPlugin("functionSent")) {
  11270. this.unexpected();
  11271. }
  11272. return this.parseMetaProperty(node, meta, "sent");
  11273. }
  11274. return this.parseFunction(node);
  11275. }
  11276. parseMetaProperty(node, meta, propertyName) {
  11277. node.meta = meta;
  11278. const containsEsc = this.state.containsEsc;
  11279. node.property = this.parseIdentifier(true);
  11280. if (node.property.name !== propertyName || containsEsc) {
  11281. this.raise(Errors.UnsupportedMetaProperty, node.property, {
  11282. target: meta.name,
  11283. onlyValidPropertyName: propertyName
  11284. });
  11285. }
  11286. return this.finishNode(node, "MetaProperty");
  11287. }
  11288. parseImportMetaProperty(node) {
  11289. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  11290. this.next();
  11291. if (this.isContextual(101)) {
  11292. if (!this.inModule) {
  11293. this.raise(Errors.ImportMetaOutsideModule, id);
  11294. }
  11295. this.sawUnambiguousESM = true;
  11296. } else if (this.isContextual(105) || this.isContextual(97)) {
  11297. const isSource = this.isContextual(105);
  11298. this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation");
  11299. if (!(this.optionFlags & 512)) {
  11300. throw this.raise(Errors.DynamicImportPhaseRequiresImportExpressions, this.state.startLoc, {
  11301. phase: this.state.value
  11302. });
  11303. }
  11304. this.next();
  11305. node.phase = isSource ? "source" : "defer";
  11306. return this.parseImportCall(node);
  11307. }
  11308. return this.parseMetaProperty(node, id, "meta");
  11309. }
  11310. parseLiteralAtNode(value, type, node) {
  11311. this.addExtra(node, "rawValue", value);
  11312. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  11313. node.value = value;
  11314. this.next();
  11315. return this.finishNode(node, type);
  11316. }
  11317. parseLiteral(value, type) {
  11318. const node = this.startNode();
  11319. return this.parseLiteralAtNode(value, type, node);
  11320. }
  11321. parseStringLiteral(value) {
  11322. return this.parseLiteral(value, "StringLiteral");
  11323. }
  11324. parseNumericLiteral(value) {
  11325. return this.parseLiteral(value, "NumericLiteral");
  11326. }
  11327. parseBigIntLiteral(value) {
  11328. return this.parseLiteral(value, "BigIntLiteral");
  11329. }
  11330. parseDecimalLiteral(value) {
  11331. return this.parseLiteral(value, "DecimalLiteral");
  11332. }
  11333. parseRegExpLiteral(value) {
  11334. const node = this.startNode();
  11335. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  11336. node.pattern = value.pattern;
  11337. node.flags = value.flags;
  11338. this.next();
  11339. return this.finishNode(node, "RegExpLiteral");
  11340. }
  11341. parseBooleanLiteral(value) {
  11342. const node = this.startNode();
  11343. node.value = value;
  11344. this.next();
  11345. return this.finishNode(node, "BooleanLiteral");
  11346. }
  11347. parseNullLiteral() {
  11348. const node = this.startNode();
  11349. this.next();
  11350. return this.finishNode(node, "NullLiteral");
  11351. }
  11352. parseParenAndDistinguishExpression(canBeArrow) {
  11353. const startLoc = this.state.startLoc;
  11354. let val;
  11355. this.next();
  11356. this.expressionScope.enter(newArrowHeadScope());
  11357. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11358. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11359. this.state.maybeInArrowParameters = true;
  11360. this.state.inFSharpPipelineDirectBody = false;
  11361. const innerStartLoc = this.state.startLoc;
  11362. const exprList = [];
  11363. const refExpressionErrors = new ExpressionErrors();
  11364. let first = true;
  11365. let spreadStartLoc;
  11366. let optionalCommaStartLoc;
  11367. while (!this.match(11)) {
  11368. if (first) {
  11369. first = false;
  11370. } else {
  11371. this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc);
  11372. if (this.match(11)) {
  11373. optionalCommaStartLoc = this.state.startLoc;
  11374. break;
  11375. }
  11376. }
  11377. if (this.match(21)) {
  11378. const spreadNodeStartLoc = this.state.startLoc;
  11379. spreadStartLoc = this.state.startLoc;
  11380. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc));
  11381. if (!this.checkCommaAfterRest(41)) {
  11382. break;
  11383. }
  11384. } else {
  11385. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
  11386. }
  11387. }
  11388. const innerEndLoc = this.state.lastTokEndLoc;
  11389. this.expect(11);
  11390. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11391. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11392. let arrowNode = this.startNodeAt(startLoc);
  11393. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  11394. this.checkDestructuringPrivate(refExpressionErrors);
  11395. this.expressionScope.validateAsPattern();
  11396. this.expressionScope.exit();
  11397. this.parseArrowExpression(arrowNode, exprList, false);
  11398. return arrowNode;
  11399. }
  11400. this.expressionScope.exit();
  11401. if (!exprList.length) {
  11402. this.unexpected(this.state.lastTokStartLoc);
  11403. }
  11404. if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc);
  11405. if (spreadStartLoc) this.unexpected(spreadStartLoc);
  11406. this.checkExpressionErrors(refExpressionErrors, true);
  11407. this.toReferencedListDeep(exprList, true);
  11408. if (exprList.length > 1) {
  11409. val = this.startNodeAt(innerStartLoc);
  11410. val.expressions = exprList;
  11411. this.finishNode(val, "SequenceExpression");
  11412. this.resetEndLocation(val, innerEndLoc);
  11413. } else {
  11414. val = exprList[0];
  11415. }
  11416. return this.wrapParenthesis(startLoc, val);
  11417. }
  11418. wrapParenthesis(startLoc, expression) {
  11419. if (!(this.optionFlags & 1024)) {
  11420. this.addExtra(expression, "parenthesized", true);
  11421. this.addExtra(expression, "parenStart", startLoc.index);
  11422. this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index);
  11423. return expression;
  11424. }
  11425. const parenExpression = this.startNodeAt(startLoc);
  11426. parenExpression.expression = expression;
  11427. return this.finishNode(parenExpression, "ParenthesizedExpression");
  11428. }
  11429. shouldParseArrow(params) {
  11430. return !this.canInsertSemicolon();
  11431. }
  11432. parseArrow(node) {
  11433. if (this.eat(19)) {
  11434. return node;
  11435. }
  11436. }
  11437. parseParenItem(node, startLoc) {
  11438. return node;
  11439. }
  11440. parseNewOrNewTarget() {
  11441. const node = this.startNode();
  11442. this.next();
  11443. if (this.match(16)) {
  11444. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  11445. this.next();
  11446. const metaProp = this.parseMetaProperty(node, meta, "target");
  11447. if (!this.scope.inNonArrowFunction && !this.scope.inClass && !(this.optionFlags & 4)) {
  11448. this.raise(Errors.UnexpectedNewTarget, metaProp);
  11449. }
  11450. return metaProp;
  11451. }
  11452. return this.parseNew(node);
  11453. }
  11454. parseNew(node) {
  11455. this.parseNewCallee(node);
  11456. if (this.eat(10)) {
  11457. const args = this.parseExprList(11);
  11458. this.toReferencedList(args);
  11459. node.arguments = args;
  11460. } else {
  11461. node.arguments = [];
  11462. }
  11463. return this.finishNode(node, "NewExpression");
  11464. }
  11465. parseNewCallee(node) {
  11466. const isImport = this.match(83);
  11467. const callee = this.parseNoCallExpr();
  11468. node.callee = callee;
  11469. if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) {
  11470. this.raise(Errors.ImportCallNotNewExpression, callee);
  11471. }
  11472. }
  11473. parseTemplateElement(isTagged) {
  11474. const {
  11475. start,
  11476. startLoc,
  11477. end,
  11478. value
  11479. } = this.state;
  11480. const elemStart = start + 1;
  11481. const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1));
  11482. if (value === null) {
  11483. if (!isTagged) {
  11484. this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1));
  11485. }
  11486. }
  11487. const isTail = this.match(24);
  11488. const endOffset = isTail ? -1 : -2;
  11489. const elemEnd = end + endOffset;
  11490. elem.value = {
  11491. raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"),
  11492. cooked: value === null ? null : value.slice(1, endOffset)
  11493. };
  11494. elem.tail = isTail;
  11495. this.next();
  11496. const finishedNode = this.finishNode(elem, "TemplateElement");
  11497. this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset));
  11498. return finishedNode;
  11499. }
  11500. parseTemplate(isTagged) {
  11501. const node = this.startNode();
  11502. let curElt = this.parseTemplateElement(isTagged);
  11503. const quasis = [curElt];
  11504. const substitutions = [];
  11505. while (!curElt.tail) {
  11506. substitutions.push(this.parseTemplateSubstitution());
  11507. this.readTemplateContinuation();
  11508. quasis.push(curElt = this.parseTemplateElement(isTagged));
  11509. }
  11510. node.expressions = substitutions;
  11511. node.quasis = quasis;
  11512. return this.finishNode(node, "TemplateLiteral");
  11513. }
  11514. parseTemplateSubstitution() {
  11515. return this.parseExpression();
  11516. }
  11517. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  11518. if (isRecord) {
  11519. this.expectPlugin("recordAndTuple");
  11520. }
  11521. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11522. this.state.inFSharpPipelineDirectBody = false;
  11523. let sawProto = false;
  11524. let first = true;
  11525. const node = this.startNode();
  11526. node.properties = [];
  11527. this.next();
  11528. while (!this.match(close)) {
  11529. if (first) {
  11530. first = false;
  11531. } else {
  11532. this.expect(12);
  11533. if (this.match(close)) {
  11534. this.addTrailingCommaExtraToNode(node);
  11535. break;
  11536. }
  11537. }
  11538. let prop;
  11539. if (isPattern) {
  11540. prop = this.parseBindingProperty();
  11541. } else {
  11542. prop = this.parsePropertyDefinition(refExpressionErrors);
  11543. sawProto = this.checkProto(prop, isRecord, sawProto, refExpressionErrors);
  11544. }
  11545. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  11546. this.raise(Errors.InvalidRecordProperty, prop);
  11547. }
  11548. {
  11549. if (prop.shorthand) {
  11550. this.addExtra(prop, "shorthand", true);
  11551. }
  11552. }
  11553. node.properties.push(prop);
  11554. }
  11555. this.next();
  11556. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11557. let type = "ObjectExpression";
  11558. if (isPattern) {
  11559. type = "ObjectPattern";
  11560. } else if (isRecord) {
  11561. type = "RecordExpression";
  11562. }
  11563. return this.finishNode(node, type);
  11564. }
  11565. addTrailingCommaExtraToNode(node) {
  11566. this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index);
  11567. this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false);
  11568. }
  11569. maybeAsyncOrAccessorProp(prop) {
  11570. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55));
  11571. }
  11572. parsePropertyDefinition(refExpressionErrors) {
  11573. let decorators = [];
  11574. if (this.match(26)) {
  11575. if (this.hasPlugin("decorators")) {
  11576. this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc);
  11577. }
  11578. while (this.match(26)) {
  11579. decorators.push(this.parseDecorator());
  11580. }
  11581. }
  11582. const prop = this.startNode();
  11583. let isAsync = false;
  11584. let isAccessor = false;
  11585. let startLoc;
  11586. if (this.match(21)) {
  11587. if (decorators.length) this.unexpected();
  11588. return this.parseSpread();
  11589. }
  11590. if (decorators.length) {
  11591. prop.decorators = decorators;
  11592. decorators = [];
  11593. }
  11594. prop.method = false;
  11595. if (refExpressionErrors) {
  11596. startLoc = this.state.startLoc;
  11597. }
  11598. let isGenerator = this.eat(55);
  11599. this.parsePropertyNamePrefixOperator(prop);
  11600. const containsEsc = this.state.containsEsc;
  11601. this.parsePropertyName(prop, refExpressionErrors);
  11602. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  11603. const {
  11604. key
  11605. } = prop;
  11606. const keyName = key.name;
  11607. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  11608. isAsync = true;
  11609. this.resetPreviousNodeTrailingComments(key);
  11610. isGenerator = this.eat(55);
  11611. this.parsePropertyName(prop);
  11612. }
  11613. if (keyName === "get" || keyName === "set") {
  11614. isAccessor = true;
  11615. this.resetPreviousNodeTrailingComments(key);
  11616. prop.kind = keyName;
  11617. if (this.match(55)) {
  11618. isGenerator = true;
  11619. this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), {
  11620. kind: keyName
  11621. });
  11622. this.next();
  11623. }
  11624. this.parsePropertyName(prop);
  11625. }
  11626. }
  11627. return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  11628. }
  11629. getGetterSetterExpectedParamCount(method) {
  11630. return method.kind === "get" ? 0 : 1;
  11631. }
  11632. getObjectOrClassMethodParams(method) {
  11633. return method.params;
  11634. }
  11635. checkGetterSetterParams(method) {
  11636. var _params;
  11637. const paramCount = this.getGetterSetterExpectedParamCount(method);
  11638. const params = this.getObjectOrClassMethodParams(method);
  11639. if (params.length !== paramCount) {
  11640. this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method);
  11641. }
  11642. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  11643. this.raise(Errors.BadSetterRestParameter, method);
  11644. }
  11645. }
  11646. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  11647. if (isAccessor) {
  11648. const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  11649. this.checkGetterSetterParams(finishedProp);
  11650. return finishedProp;
  11651. }
  11652. if (isAsync || isGenerator || this.match(10)) {
  11653. if (isPattern) this.unexpected();
  11654. prop.kind = "method";
  11655. prop.method = true;
  11656. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  11657. }
  11658. }
  11659. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  11660. prop.shorthand = false;
  11661. if (this.eat(14)) {
  11662. prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  11663. return this.finishNode(prop, "ObjectProperty");
  11664. }
  11665. if (!prop.computed && prop.key.type === "Identifier") {
  11666. this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);
  11667. if (isPattern) {
  11668. prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
  11669. } else if (this.match(29)) {
  11670. const shorthandAssignLoc = this.state.startLoc;
  11671. if (refExpressionErrors != null) {
  11672. if (refExpressionErrors.shorthandAssignLoc === null) {
  11673. refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;
  11674. }
  11675. } else {
  11676. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  11677. }
  11678. prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
  11679. } else {
  11680. prop.value = cloneIdentifier(prop.key);
  11681. }
  11682. prop.shorthand = true;
  11683. return this.finishNode(prop, "ObjectProperty");
  11684. }
  11685. }
  11686. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  11687. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  11688. if (!node) this.unexpected();
  11689. return node;
  11690. }
  11691. parsePropertyName(prop, refExpressionErrors) {
  11692. if (this.eat(0)) {
  11693. prop.computed = true;
  11694. prop.key = this.parseMaybeAssignAllowIn();
  11695. this.expect(3);
  11696. } else {
  11697. const {
  11698. type,
  11699. value
  11700. } = this.state;
  11701. let key;
  11702. if (tokenIsKeywordOrIdentifier(type)) {
  11703. key = this.parseIdentifier(true);
  11704. } else {
  11705. switch (type) {
  11706. case 135:
  11707. key = this.parseNumericLiteral(value);
  11708. break;
  11709. case 134:
  11710. key = this.parseStringLiteral(value);
  11711. break;
  11712. case 136:
  11713. key = this.parseBigIntLiteral(value);
  11714. break;
  11715. case 139:
  11716. {
  11717. const privateKeyLoc = this.state.startLoc;
  11718. if (refExpressionErrors != null) {
  11719. if (refExpressionErrors.privateKeyLoc === null) {
  11720. refExpressionErrors.privateKeyLoc = privateKeyLoc;
  11721. }
  11722. } else {
  11723. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  11724. }
  11725. key = this.parsePrivateName();
  11726. break;
  11727. }
  11728. default:
  11729. if (type === 137) {
  11730. key = this.parseDecimalLiteral(value);
  11731. break;
  11732. }
  11733. this.unexpected();
  11734. }
  11735. }
  11736. prop.key = key;
  11737. if (type !== 139) {
  11738. prop.computed = false;
  11739. }
  11740. }
  11741. }
  11742. initFunction(node, isAsync) {
  11743. node.id = null;
  11744. node.generator = false;
  11745. node.async = isAsync;
  11746. }
  11747. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  11748. this.initFunction(node, isAsync);
  11749. node.generator = isGenerator;
  11750. this.scope.enter(2 | 16 | (inClassScope ? 64 : 0) | (allowDirectSuper ? 32 : 0));
  11751. this.prodParam.enter(functionFlags(isAsync, node.generator));
  11752. this.parseFunctionParams(node, isConstructor);
  11753. const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
  11754. this.prodParam.exit();
  11755. this.scope.exit();
  11756. return finishedNode;
  11757. }
  11758. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  11759. if (isTuple) {
  11760. this.expectPlugin("recordAndTuple");
  11761. }
  11762. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11763. this.state.inFSharpPipelineDirectBody = false;
  11764. const node = this.startNode();
  11765. this.next();
  11766. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  11767. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11768. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  11769. }
  11770. parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
  11771. this.scope.enter(2 | 4);
  11772. let flags = functionFlags(isAsync, false);
  11773. if (!this.match(5) && this.prodParam.hasIn) {
  11774. flags |= 8;
  11775. }
  11776. this.prodParam.enter(flags);
  11777. this.initFunction(node, isAsync);
  11778. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11779. if (params) {
  11780. this.state.maybeInArrowParameters = true;
  11781. this.setArrowFunctionParameters(node, params, trailingCommaLoc);
  11782. }
  11783. this.state.maybeInArrowParameters = false;
  11784. this.parseFunctionBody(node, true);
  11785. this.prodParam.exit();
  11786. this.scope.exit();
  11787. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11788. return this.finishNode(node, "ArrowFunctionExpression");
  11789. }
  11790. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  11791. this.toAssignableList(params, trailingCommaLoc, false);
  11792. node.params = params;
  11793. }
  11794. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11795. this.parseFunctionBody(node, false, isMethod);
  11796. return this.finishNode(node, type);
  11797. }
  11798. parseFunctionBody(node, allowExpression, isMethod = false) {
  11799. const isExpression = allowExpression && !this.match(5);
  11800. this.expressionScope.enter(newExpressionScope());
  11801. if (isExpression) {
  11802. node.body = this.parseMaybeAssign();
  11803. this.checkParams(node, false, allowExpression, false);
  11804. } else {
  11805. const oldStrict = this.state.strict;
  11806. const oldLabels = this.state.labels;
  11807. this.state.labels = [];
  11808. this.prodParam.enter(this.prodParam.currentFlags() | 4);
  11809. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  11810. const nonSimple = !this.isSimpleParamList(node.params);
  11811. if (hasStrictModeDirective && nonSimple) {
  11812. this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node);
  11813. }
  11814. const strictModeChanged = !oldStrict && this.state.strict;
  11815. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  11816. if (this.state.strict && node.id) {
  11817. this.checkIdentifier(node.id, 65, strictModeChanged);
  11818. }
  11819. });
  11820. this.prodParam.exit();
  11821. this.state.labels = oldLabels;
  11822. }
  11823. this.expressionScope.exit();
  11824. }
  11825. isSimpleParameter(node) {
  11826. return node.type === "Identifier";
  11827. }
  11828. isSimpleParamList(params) {
  11829. for (let i = 0, len = params.length; i < len; i++) {
  11830. if (!this.isSimpleParameter(params[i])) return false;
  11831. }
  11832. return true;
  11833. }
  11834. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  11835. const checkClashes = !allowDuplicates && new Set();
  11836. const formalParameters = {
  11837. type: "FormalParameters"
  11838. };
  11839. for (const param of node.params) {
  11840. this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged);
  11841. }
  11842. }
  11843. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  11844. const elts = [];
  11845. let first = true;
  11846. while (!this.eat(close)) {
  11847. if (first) {
  11848. first = false;
  11849. } else {
  11850. this.expect(12);
  11851. if (this.match(close)) {
  11852. if (nodeForExtra) {
  11853. this.addTrailingCommaExtraToNode(nodeForExtra);
  11854. }
  11855. this.next();
  11856. break;
  11857. }
  11858. }
  11859. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  11860. }
  11861. return elts;
  11862. }
  11863. parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
  11864. let elt;
  11865. if (this.match(12)) {
  11866. if (!allowEmpty) {
  11867. this.raise(Errors.UnexpectedToken, this.state.curPosition(), {
  11868. unexpected: ","
  11869. });
  11870. }
  11871. elt = null;
  11872. } else if (this.match(21)) {
  11873. const spreadNodeStartLoc = this.state.startLoc;
  11874. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc);
  11875. } else if (this.match(17)) {
  11876. this.expectPlugin("partialApplication");
  11877. if (!allowPlaceholder) {
  11878. this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc);
  11879. }
  11880. const node = this.startNode();
  11881. this.next();
  11882. elt = this.finishNode(node, "ArgumentPlaceholder");
  11883. } else {
  11884. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
  11885. }
  11886. return elt;
  11887. }
  11888. parseIdentifier(liberal) {
  11889. const node = this.startNode();
  11890. const name = this.parseIdentifierName(liberal);
  11891. return this.createIdentifier(node, name);
  11892. }
  11893. createIdentifier(node, name) {
  11894. node.name = name;
  11895. node.loc.identifierName = name;
  11896. return this.finishNode(node, "Identifier");
  11897. }
  11898. parseIdentifierName(liberal) {
  11899. let name;
  11900. const {
  11901. startLoc,
  11902. type
  11903. } = this.state;
  11904. if (tokenIsKeywordOrIdentifier(type)) {
  11905. name = this.state.value;
  11906. } else {
  11907. this.unexpected();
  11908. }
  11909. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  11910. if (liberal) {
  11911. if (tokenIsKeyword) {
  11912. this.replaceToken(132);
  11913. }
  11914. } else {
  11915. this.checkReservedWord(name, startLoc, tokenIsKeyword, false);
  11916. }
  11917. this.next();
  11918. return name;
  11919. }
  11920. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  11921. if (word.length > 10) {
  11922. return;
  11923. }
  11924. if (!canBeReservedWord(word)) {
  11925. return;
  11926. }
  11927. if (checkKeywords && isKeyword(word)) {
  11928. this.raise(Errors.UnexpectedKeyword, startLoc, {
  11929. keyword: word
  11930. });
  11931. return;
  11932. }
  11933. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  11934. if (reservedTest(word, this.inModule)) {
  11935. this.raise(Errors.UnexpectedReservedWord, startLoc, {
  11936. reservedWord: word
  11937. });
  11938. return;
  11939. } else if (word === "yield") {
  11940. if (this.prodParam.hasYield) {
  11941. this.raise(Errors.YieldBindingIdentifier, startLoc);
  11942. return;
  11943. }
  11944. } else if (word === "await") {
  11945. if (this.prodParam.hasAwait) {
  11946. this.raise(Errors.AwaitBindingIdentifier, startLoc);
  11947. return;
  11948. }
  11949. if (this.scope.inStaticBlock) {
  11950. this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc);
  11951. return;
  11952. }
  11953. this.expressionScope.recordAsyncArrowParametersError(startLoc);
  11954. } else if (word === "arguments") {
  11955. if (this.scope.inClassAndNotInNonArrowFunction) {
  11956. this.raise(Errors.ArgumentsInClass, startLoc);
  11957. return;
  11958. }
  11959. }
  11960. }
  11961. recordAwaitIfAllowed() {
  11962. const isAwaitAllowed = this.prodParam.hasAwait || this.optionFlags & 1 && !this.scope.inFunction;
  11963. if (isAwaitAllowed && !this.scope.inFunction) {
  11964. this.state.hasTopLevelAwait = true;
  11965. }
  11966. return isAwaitAllowed;
  11967. }
  11968. parseAwait(startLoc) {
  11969. const node = this.startNodeAt(startLoc);
  11970. this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node);
  11971. if (this.eat(55)) {
  11972. this.raise(Errors.ObsoleteAwaitStar, node);
  11973. }
  11974. if (!this.scope.inFunction && !(this.optionFlags & 1)) {
  11975. if (this.isAmbiguousPrefixOrIdentifier()) {
  11976. this.ambiguousScriptDifferentAst = true;
  11977. } else {
  11978. this.sawUnambiguousESM = true;
  11979. }
  11980. }
  11981. if (!this.state.soloAwait) {
  11982. node.argument = this.parseMaybeUnary(null, true);
  11983. }
  11984. return this.finishNode(node, "AwaitExpression");
  11985. }
  11986. isAmbiguousPrefixOrIdentifier() {
  11987. if (this.hasPrecedingLineBreak()) return true;
  11988. const {
  11989. type
  11990. } = this.state;
  11991. return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 138 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54;
  11992. }
  11993. parseYield(startLoc) {
  11994. const node = this.startNodeAt(startLoc);
  11995. this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node);
  11996. let delegating = false;
  11997. let argument = null;
  11998. if (!this.hasPrecedingLineBreak()) {
  11999. delegating = this.eat(55);
  12000. switch (this.state.type) {
  12001. case 13:
  12002. case 140:
  12003. case 8:
  12004. case 11:
  12005. case 3:
  12006. case 9:
  12007. case 14:
  12008. case 12:
  12009. if (!delegating) break;
  12010. default:
  12011. argument = this.parseMaybeAssign();
  12012. }
  12013. }
  12014. node.delegate = delegating;
  12015. node.argument = argument;
  12016. return this.finishNode(node, "YieldExpression");
  12017. }
  12018. parseImportCall(node) {
  12019. this.next();
  12020. node.source = this.parseMaybeAssignAllowIn();
  12021. node.options = null;
  12022. if (this.eat(12)) {
  12023. if (!this.match(11)) {
  12024. node.options = this.parseMaybeAssignAllowIn();
  12025. if (this.eat(12) && !this.match(11)) {
  12026. do {
  12027. this.parseMaybeAssignAllowIn();
  12028. } while (this.eat(12) && !this.match(11));
  12029. this.raise(Errors.ImportCallArity, node);
  12030. }
  12031. }
  12032. }
  12033. this.expect(11);
  12034. return this.finishNode(node, "ImportExpression");
  12035. }
  12036. checkPipelineAtInfixOperator(left, leftStartLoc) {
  12037. if (this.hasPlugin(["pipelineOperator", {
  12038. proposal: "smart"
  12039. }])) {
  12040. if (left.type === "SequenceExpression") {
  12041. this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc);
  12042. }
  12043. }
  12044. }
  12045. parseSmartPipelineBodyInStyle(childExpr, startLoc) {
  12046. if (this.isSimpleReference(childExpr)) {
  12047. const bodyNode = this.startNodeAt(startLoc);
  12048. bodyNode.callee = childExpr;
  12049. return this.finishNode(bodyNode, "PipelineBareFunction");
  12050. } else {
  12051. const bodyNode = this.startNodeAt(startLoc);
  12052. this.checkSmartPipeTopicBodyEarlyErrors(startLoc);
  12053. bodyNode.expression = childExpr;
  12054. return this.finishNode(bodyNode, "PipelineTopicExpression");
  12055. }
  12056. }
  12057. isSimpleReference(expression) {
  12058. switch (expression.type) {
  12059. case "MemberExpression":
  12060. return !expression.computed && this.isSimpleReference(expression.object);
  12061. case "Identifier":
  12062. return true;
  12063. default:
  12064. return false;
  12065. }
  12066. }
  12067. checkSmartPipeTopicBodyEarlyErrors(startLoc) {
  12068. if (this.match(19)) {
  12069. throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc);
  12070. }
  12071. if (!this.topicReferenceWasUsedInCurrentContext()) {
  12072. this.raise(Errors.PipelineTopicUnused, startLoc);
  12073. }
  12074. }
  12075. withTopicBindingContext(callback) {
  12076. const outerContextTopicState = this.state.topicContext;
  12077. this.state.topicContext = {
  12078. maxNumOfResolvableTopics: 1,
  12079. maxTopicIndex: null
  12080. };
  12081. try {
  12082. return callback();
  12083. } finally {
  12084. this.state.topicContext = outerContextTopicState;
  12085. }
  12086. }
  12087. withSmartMixTopicForbiddingContext(callback) {
  12088. if (this.hasPlugin(["pipelineOperator", {
  12089. proposal: "smart"
  12090. }])) {
  12091. const outerContextTopicState = this.state.topicContext;
  12092. this.state.topicContext = {
  12093. maxNumOfResolvableTopics: 0,
  12094. maxTopicIndex: null
  12095. };
  12096. try {
  12097. return callback();
  12098. } finally {
  12099. this.state.topicContext = outerContextTopicState;
  12100. }
  12101. } else {
  12102. return callback();
  12103. }
  12104. }
  12105. withSoloAwaitPermittingContext(callback) {
  12106. const outerContextSoloAwaitState = this.state.soloAwait;
  12107. this.state.soloAwait = true;
  12108. try {
  12109. return callback();
  12110. } finally {
  12111. this.state.soloAwait = outerContextSoloAwaitState;
  12112. }
  12113. }
  12114. allowInAnd(callback) {
  12115. const flags = this.prodParam.currentFlags();
  12116. const prodParamToSet = 8 & ~flags;
  12117. if (prodParamToSet) {
  12118. this.prodParam.enter(flags | 8);
  12119. try {
  12120. return callback();
  12121. } finally {
  12122. this.prodParam.exit();
  12123. }
  12124. }
  12125. return callback();
  12126. }
  12127. disallowInAnd(callback) {
  12128. const flags = this.prodParam.currentFlags();
  12129. const prodParamToClear = 8 & flags;
  12130. if (prodParamToClear) {
  12131. this.prodParam.enter(flags & ~8);
  12132. try {
  12133. return callback();
  12134. } finally {
  12135. this.prodParam.exit();
  12136. }
  12137. }
  12138. return callback();
  12139. }
  12140. registerTopicReference() {
  12141. this.state.topicContext.maxTopicIndex = 0;
  12142. }
  12143. topicReferenceIsAllowedInCurrentContext() {
  12144. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  12145. }
  12146. topicReferenceWasUsedInCurrentContext() {
  12147. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  12148. }
  12149. parseFSharpPipelineBody(prec) {
  12150. const startLoc = this.state.startLoc;
  12151. this.state.potentialArrowAt = this.state.start;
  12152. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  12153. this.state.inFSharpPipelineDirectBody = true;
  12154. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec);
  12155. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  12156. return ret;
  12157. }
  12158. parseModuleExpression() {
  12159. this.expectPlugin("moduleBlocks");
  12160. const node = this.startNode();
  12161. this.next();
  12162. if (!this.match(5)) {
  12163. this.unexpected(null, 5);
  12164. }
  12165. const program = this.startNodeAt(this.state.endLoc);
  12166. this.next();
  12167. const revertScopes = this.initializeScopes(true);
  12168. this.enterInitialScopes();
  12169. try {
  12170. node.body = this.parseProgram(program, 8, "module");
  12171. } finally {
  12172. revertScopes();
  12173. }
  12174. return this.finishNode(node, "ModuleExpression");
  12175. }
  12176. parsePropertyNamePrefixOperator(prop) {}
  12177. }
  12178. const loopLabel = {
  12179. kind: 1
  12180. },
  12181. switchLabel = {
  12182. kind: 2
  12183. };
  12184. const loneSurrogate = /[\uD800-\uDFFF]/u;
  12185. const keywordRelationalOperator = /in(?:stanceof)?/y;
  12186. function babel7CompatTokens(tokens, input, startIndex) {
  12187. for (let i = 0; i < tokens.length; i++) {
  12188. const token = tokens[i];
  12189. const {
  12190. type
  12191. } = token;
  12192. if (typeof type === "number") {
  12193. {
  12194. if (type === 139) {
  12195. const {
  12196. loc,
  12197. start,
  12198. value,
  12199. end
  12200. } = token;
  12201. const hashEndPos = start + 1;
  12202. const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);
  12203. tokens.splice(i, 1, new Token({
  12204. type: getExportedToken(27),
  12205. value: "#",
  12206. start: start,
  12207. end: hashEndPos,
  12208. startLoc: loc.start,
  12209. endLoc: hashEndLoc
  12210. }), new Token({
  12211. type: getExportedToken(132),
  12212. value: value,
  12213. start: hashEndPos,
  12214. end: end,
  12215. startLoc: hashEndLoc,
  12216. endLoc: loc.end
  12217. }));
  12218. i++;
  12219. continue;
  12220. }
  12221. if (tokenIsTemplate(type)) {
  12222. const {
  12223. loc,
  12224. start,
  12225. value,
  12226. end
  12227. } = token;
  12228. const backquoteEnd = start + 1;
  12229. const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);
  12230. let startToken;
  12231. if (input.charCodeAt(start - startIndex) === 96) {
  12232. startToken = new Token({
  12233. type: getExportedToken(22),
  12234. value: "`",
  12235. start: start,
  12236. end: backquoteEnd,
  12237. startLoc: loc.start,
  12238. endLoc: backquoteEndLoc
  12239. });
  12240. } else {
  12241. startToken = new Token({
  12242. type: getExportedToken(8),
  12243. value: "}",
  12244. start: start,
  12245. end: backquoteEnd,
  12246. startLoc: loc.start,
  12247. endLoc: backquoteEndLoc
  12248. });
  12249. }
  12250. let templateValue, templateElementEnd, templateElementEndLoc, endToken;
  12251. if (type === 24) {
  12252. templateElementEnd = end - 1;
  12253. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);
  12254. templateValue = value === null ? null : value.slice(1, -1);
  12255. endToken = new Token({
  12256. type: getExportedToken(22),
  12257. value: "`",
  12258. start: templateElementEnd,
  12259. end: end,
  12260. startLoc: templateElementEndLoc,
  12261. endLoc: loc.end
  12262. });
  12263. } else {
  12264. templateElementEnd = end - 2;
  12265. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);
  12266. templateValue = value === null ? null : value.slice(1, -2);
  12267. endToken = new Token({
  12268. type: getExportedToken(23),
  12269. value: "${",
  12270. start: templateElementEnd,
  12271. end: end,
  12272. startLoc: templateElementEndLoc,
  12273. endLoc: loc.end
  12274. });
  12275. }
  12276. tokens.splice(i, 1, startToken, new Token({
  12277. type: getExportedToken(20),
  12278. value: templateValue,
  12279. start: backquoteEnd,
  12280. end: templateElementEnd,
  12281. startLoc: backquoteEndLoc,
  12282. endLoc: templateElementEndLoc
  12283. }), endToken);
  12284. i += 2;
  12285. continue;
  12286. }
  12287. }
  12288. token.type = getExportedToken(type);
  12289. }
  12290. }
  12291. return tokens;
  12292. }
  12293. class StatementParser extends ExpressionParser {
  12294. parseTopLevel(file, program) {
  12295. file.program = this.parseProgram(program);
  12296. file.comments = this.comments;
  12297. if (this.optionFlags & 256) {
  12298. file.tokens = babel7CompatTokens(this.tokens, this.input, this.startIndex);
  12299. }
  12300. return this.finishNode(file, "File");
  12301. }
  12302. parseProgram(program, end = 140, sourceType = this.options.sourceType) {
  12303. program.sourceType = sourceType;
  12304. program.interpreter = this.parseInterpreterDirective();
  12305. this.parseBlockBody(program, true, true, end);
  12306. if (this.inModule) {
  12307. if (!(this.optionFlags & 64) && this.scope.undefinedExports.size > 0) {
  12308. for (const [localName, at] of Array.from(this.scope.undefinedExports)) {
  12309. this.raise(Errors.ModuleExportUndefined, at, {
  12310. localName
  12311. });
  12312. }
  12313. }
  12314. this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait);
  12315. }
  12316. let finishedProgram;
  12317. if (end === 140) {
  12318. finishedProgram = this.finishNode(program, "Program");
  12319. } else {
  12320. finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1));
  12321. }
  12322. return finishedProgram;
  12323. }
  12324. stmtToDirective(stmt) {
  12325. const directive = stmt;
  12326. directive.type = "Directive";
  12327. directive.value = directive.expression;
  12328. delete directive.expression;
  12329. const directiveLiteral = directive.value;
  12330. const expressionValue = directiveLiteral.value;
  12331. const raw = this.input.slice(this.offsetToSourcePos(directiveLiteral.start), this.offsetToSourcePos(directiveLiteral.end));
  12332. const val = directiveLiteral.value = raw.slice(1, -1);
  12333. this.addExtra(directiveLiteral, "raw", raw);
  12334. this.addExtra(directiveLiteral, "rawValue", val);
  12335. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  12336. directiveLiteral.type = "DirectiveLiteral";
  12337. return directive;
  12338. }
  12339. parseInterpreterDirective() {
  12340. if (!this.match(28)) {
  12341. return null;
  12342. }
  12343. const node = this.startNode();
  12344. node.value = this.state.value;
  12345. this.next();
  12346. return this.finishNode(node, "InterpreterDirective");
  12347. }
  12348. isLet() {
  12349. if (!this.isContextual(100)) {
  12350. return false;
  12351. }
  12352. return this.hasFollowingBindingAtom();
  12353. }
  12354. chStartsBindingIdentifier(ch, pos) {
  12355. if (isIdentifierStart(ch)) {
  12356. keywordRelationalOperator.lastIndex = pos;
  12357. if (keywordRelationalOperator.test(this.input)) {
  12358. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  12359. if (!isIdentifierChar(endCh) && endCh !== 92) {
  12360. return false;
  12361. }
  12362. }
  12363. return true;
  12364. } else if (ch === 92) {
  12365. return true;
  12366. } else {
  12367. return false;
  12368. }
  12369. }
  12370. chStartsBindingPattern(ch) {
  12371. return ch === 91 || ch === 123;
  12372. }
  12373. hasFollowingBindingAtom() {
  12374. const next = this.nextTokenStart();
  12375. const nextCh = this.codePointAtPos(next);
  12376. return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
  12377. }
  12378. hasInLineFollowingBindingIdentifierOrBrace() {
  12379. const next = this.nextTokenInLineStart();
  12380. const nextCh = this.codePointAtPos(next);
  12381. return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next);
  12382. }
  12383. startsUsingForOf() {
  12384. const {
  12385. type,
  12386. containsEsc
  12387. } = this.lookahead();
  12388. if (type === 102 && !containsEsc) {
  12389. return false;
  12390. } else if (tokenIsIdentifier(type) && !this.hasFollowingLineBreak()) {
  12391. this.expectPlugin("explicitResourceManagement");
  12392. return true;
  12393. }
  12394. }
  12395. startsAwaitUsing() {
  12396. let next = this.nextTokenInLineStart();
  12397. if (this.isUnparsedContextual(next, "using")) {
  12398. next = this.nextTokenInLineStartSince(next + 5);
  12399. const nextCh = this.codePointAtPos(next);
  12400. if (this.chStartsBindingIdentifier(nextCh, next)) {
  12401. this.expectPlugin("explicitResourceManagement");
  12402. return true;
  12403. }
  12404. }
  12405. return false;
  12406. }
  12407. parseModuleItem() {
  12408. return this.parseStatementLike(1 | 2 | 4 | 8);
  12409. }
  12410. parseStatementListItem() {
  12411. return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8));
  12412. }
  12413. parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) {
  12414. let flags = 0;
  12415. if (this.options.annexB && !this.state.strict) {
  12416. flags |= 4;
  12417. if (allowLabeledFunction) {
  12418. flags |= 8;
  12419. }
  12420. }
  12421. return this.parseStatementLike(flags);
  12422. }
  12423. parseStatement() {
  12424. return this.parseStatementLike(0);
  12425. }
  12426. parseStatementLike(flags) {
  12427. let decorators = null;
  12428. if (this.match(26)) {
  12429. decorators = this.parseDecorators(true);
  12430. }
  12431. return this.parseStatementContent(flags, decorators);
  12432. }
  12433. parseStatementContent(flags, decorators) {
  12434. const startType = this.state.type;
  12435. const node = this.startNode();
  12436. const allowDeclaration = !!(flags & 2);
  12437. const allowFunctionDeclaration = !!(flags & 4);
  12438. const topLevel = flags & 1;
  12439. switch (startType) {
  12440. case 60:
  12441. return this.parseBreakContinueStatement(node, true);
  12442. case 63:
  12443. return this.parseBreakContinueStatement(node, false);
  12444. case 64:
  12445. return this.parseDebuggerStatement(node);
  12446. case 90:
  12447. return this.parseDoWhileStatement(node);
  12448. case 91:
  12449. return this.parseForStatement(node);
  12450. case 68:
  12451. if (this.lookaheadCharCode() === 46) break;
  12452. if (!allowFunctionDeclaration) {
  12453. this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc);
  12454. }
  12455. return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration);
  12456. case 80:
  12457. if (!allowDeclaration) this.unexpected();
  12458. return this.parseClass(this.maybeTakeDecorators(decorators, node), true);
  12459. case 69:
  12460. return this.parseIfStatement(node);
  12461. case 70:
  12462. return this.parseReturnStatement(node);
  12463. case 71:
  12464. return this.parseSwitchStatement(node);
  12465. case 72:
  12466. return this.parseThrowStatement(node);
  12467. case 73:
  12468. return this.parseTryStatement(node);
  12469. case 96:
  12470. if (!this.state.containsEsc && this.startsAwaitUsing()) {
  12471. if (!this.recordAwaitIfAllowed()) {
  12472. this.raise(Errors.AwaitUsingNotInAsyncContext, node);
  12473. } else if (!allowDeclaration) {
  12474. this.raise(Errors.UnexpectedLexicalDeclaration, node);
  12475. }
  12476. this.next();
  12477. return this.parseVarStatement(node, "await using");
  12478. }
  12479. break;
  12480. case 107:
  12481. if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) {
  12482. break;
  12483. }
  12484. this.expectPlugin("explicitResourceManagement");
  12485. if (!this.scope.inModule && this.scope.inTopLevel) {
  12486. this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc);
  12487. } else if (!allowDeclaration) {
  12488. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  12489. }
  12490. return this.parseVarStatement(node, "using");
  12491. case 100:
  12492. {
  12493. if (this.state.containsEsc) {
  12494. break;
  12495. }
  12496. const next = this.nextTokenStart();
  12497. const nextCh = this.codePointAtPos(next);
  12498. if (nextCh !== 91) {
  12499. if (!allowDeclaration && this.hasFollowingLineBreak()) break;
  12500. if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) {
  12501. break;
  12502. }
  12503. }
  12504. }
  12505. case 75:
  12506. {
  12507. if (!allowDeclaration) {
  12508. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  12509. }
  12510. }
  12511. case 74:
  12512. {
  12513. const kind = this.state.value;
  12514. return this.parseVarStatement(node, kind);
  12515. }
  12516. case 92:
  12517. return this.parseWhileStatement(node);
  12518. case 76:
  12519. return this.parseWithStatement(node);
  12520. case 5:
  12521. return this.parseBlock();
  12522. case 13:
  12523. return this.parseEmptyStatement(node);
  12524. case 83:
  12525. {
  12526. const nextTokenCharCode = this.lookaheadCharCode();
  12527. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  12528. break;
  12529. }
  12530. }
  12531. case 82:
  12532. {
  12533. if (!(this.optionFlags & 8) && !topLevel) {
  12534. this.raise(Errors.UnexpectedImportExport, this.state.startLoc);
  12535. }
  12536. this.next();
  12537. let result;
  12538. if (startType === 83) {
  12539. result = this.parseImport(node);
  12540. } else {
  12541. result = this.parseExport(node, decorators);
  12542. }
  12543. this.assertModuleNodeAllowed(result);
  12544. return result;
  12545. }
  12546. default:
  12547. {
  12548. if (this.isAsyncFunction()) {
  12549. if (!allowDeclaration) {
  12550. this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc);
  12551. }
  12552. this.next();
  12553. return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration);
  12554. }
  12555. }
  12556. }
  12557. const maybeName = this.state.value;
  12558. const expr = this.parseExpression();
  12559. if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) {
  12560. return this.parseLabeledStatement(node, maybeName, expr, flags);
  12561. } else {
  12562. return this.parseExpressionStatement(node, expr, decorators);
  12563. }
  12564. }
  12565. assertModuleNodeAllowed(node) {
  12566. if (!(this.optionFlags & 8) && !this.inModule) {
  12567. this.raise(Errors.ImportOutsideModule, node);
  12568. }
  12569. }
  12570. decoratorsEnabledBeforeExport() {
  12571. if (this.hasPlugin("decorators-legacy")) return true;
  12572. return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false;
  12573. }
  12574. maybeTakeDecorators(maybeDecorators, classNode, exportNode) {
  12575. if (maybeDecorators) {
  12576. var _classNode$decorators;
  12577. if ((_classNode$decorators = classNode.decorators) != null && _classNode$decorators.length) {
  12578. if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") {
  12579. this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]);
  12580. }
  12581. classNode.decorators.unshift(...maybeDecorators);
  12582. } else {
  12583. classNode.decorators = maybeDecorators;
  12584. }
  12585. this.resetStartLocationFromNode(classNode, maybeDecorators[0]);
  12586. if (exportNode) this.resetStartLocationFromNode(exportNode, classNode);
  12587. }
  12588. return classNode;
  12589. }
  12590. canHaveLeadingDecorator() {
  12591. return this.match(80);
  12592. }
  12593. parseDecorators(allowExport) {
  12594. const decorators = [];
  12595. do {
  12596. decorators.push(this.parseDecorator());
  12597. } while (this.match(26));
  12598. if (this.match(82)) {
  12599. if (!allowExport) {
  12600. this.unexpected();
  12601. }
  12602. if (!this.decoratorsEnabledBeforeExport()) {
  12603. this.raise(Errors.DecoratorExportClass, this.state.startLoc);
  12604. }
  12605. } else if (!this.canHaveLeadingDecorator()) {
  12606. throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc);
  12607. }
  12608. return decorators;
  12609. }
  12610. parseDecorator() {
  12611. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  12612. const node = this.startNode();
  12613. this.next();
  12614. if (this.hasPlugin("decorators")) {
  12615. const startLoc = this.state.startLoc;
  12616. let expr;
  12617. if (this.match(10)) {
  12618. const startLoc = this.state.startLoc;
  12619. this.next();
  12620. expr = this.parseExpression();
  12621. this.expect(11);
  12622. expr = this.wrapParenthesis(startLoc, expr);
  12623. const paramsStartLoc = this.state.startLoc;
  12624. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  12625. if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) {
  12626. this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc);
  12627. }
  12628. } else {
  12629. expr = this.parseIdentifier(false);
  12630. while (this.eat(16)) {
  12631. const node = this.startNodeAt(startLoc);
  12632. node.object = expr;
  12633. if (this.match(139)) {
  12634. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  12635. node.property = this.parsePrivateName();
  12636. } else {
  12637. node.property = this.parseIdentifier(true);
  12638. }
  12639. node.computed = false;
  12640. expr = this.finishNode(node, "MemberExpression");
  12641. }
  12642. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  12643. }
  12644. } else {
  12645. node.expression = this.parseExprSubscripts();
  12646. }
  12647. return this.finishNode(node, "Decorator");
  12648. }
  12649. parseMaybeDecoratorArguments(expr, startLoc) {
  12650. if (this.eat(10)) {
  12651. const node = this.startNodeAt(startLoc);
  12652. node.callee = expr;
  12653. node.arguments = this.parseCallExpressionArguments(11);
  12654. this.toReferencedList(node.arguments);
  12655. return this.finishNode(node, "CallExpression");
  12656. }
  12657. return expr;
  12658. }
  12659. parseBreakContinueStatement(node, isBreak) {
  12660. this.next();
  12661. if (this.isLineTerminator()) {
  12662. node.label = null;
  12663. } else {
  12664. node.label = this.parseIdentifier();
  12665. this.semicolon();
  12666. }
  12667. this.verifyBreakContinue(node, isBreak);
  12668. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  12669. }
  12670. verifyBreakContinue(node, isBreak) {
  12671. let i;
  12672. for (i = 0; i < this.state.labels.length; ++i) {
  12673. const lab = this.state.labels[i];
  12674. if (node.label == null || lab.name === node.label.name) {
  12675. if (lab.kind != null && (isBreak || lab.kind === 1)) {
  12676. break;
  12677. }
  12678. if (node.label && isBreak) break;
  12679. }
  12680. }
  12681. if (i === this.state.labels.length) {
  12682. const type = isBreak ? "BreakStatement" : "ContinueStatement";
  12683. this.raise(Errors.IllegalBreakContinue, node, {
  12684. type
  12685. });
  12686. }
  12687. }
  12688. parseDebuggerStatement(node) {
  12689. this.next();
  12690. this.semicolon();
  12691. return this.finishNode(node, "DebuggerStatement");
  12692. }
  12693. parseHeaderExpression() {
  12694. this.expect(10);
  12695. const val = this.parseExpression();
  12696. this.expect(11);
  12697. return val;
  12698. }
  12699. parseDoWhileStatement(node) {
  12700. this.next();
  12701. this.state.labels.push(loopLabel);
  12702. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12703. this.state.labels.pop();
  12704. this.expect(92);
  12705. node.test = this.parseHeaderExpression();
  12706. this.eat(13);
  12707. return this.finishNode(node, "DoWhileStatement");
  12708. }
  12709. parseForStatement(node) {
  12710. this.next();
  12711. this.state.labels.push(loopLabel);
  12712. let awaitAt = null;
  12713. if (this.isContextual(96) && this.recordAwaitIfAllowed()) {
  12714. awaitAt = this.state.startLoc;
  12715. this.next();
  12716. }
  12717. this.scope.enter(0);
  12718. this.expect(10);
  12719. if (this.match(13)) {
  12720. if (awaitAt !== null) {
  12721. this.unexpected(awaitAt);
  12722. }
  12723. return this.parseFor(node, null);
  12724. }
  12725. const startsWithLet = this.isContextual(100);
  12726. {
  12727. const startsWithAwaitUsing = this.isContextual(96) && this.startsAwaitUsing();
  12728. const starsWithUsingDeclaration = startsWithAwaitUsing || this.isContextual(107) && this.startsUsingForOf();
  12729. const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration;
  12730. if (this.match(74) || this.match(75) || isLetOrUsing) {
  12731. const initNode = this.startNode();
  12732. let kind;
  12733. if (startsWithAwaitUsing) {
  12734. kind = "await using";
  12735. if (!this.recordAwaitIfAllowed()) {
  12736. this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc);
  12737. }
  12738. this.next();
  12739. } else {
  12740. kind = this.state.value;
  12741. }
  12742. this.next();
  12743. this.parseVar(initNode, true, kind);
  12744. const init = this.finishNode(initNode, "VariableDeclaration");
  12745. const isForIn = this.match(58);
  12746. if (isForIn && starsWithUsingDeclaration) {
  12747. this.raise(Errors.ForInUsing, init);
  12748. }
  12749. if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) {
  12750. return this.parseForIn(node, init, awaitAt);
  12751. }
  12752. if (awaitAt !== null) {
  12753. this.unexpected(awaitAt);
  12754. }
  12755. return this.parseFor(node, init);
  12756. }
  12757. }
  12758. const startsWithAsync = this.isContextual(95);
  12759. const refExpressionErrors = new ExpressionErrors();
  12760. const init = this.parseExpression(true, refExpressionErrors);
  12761. const isForOf = this.isContextual(102);
  12762. if (isForOf) {
  12763. if (startsWithLet) {
  12764. this.raise(Errors.ForOfLet, init);
  12765. }
  12766. if (awaitAt === null && startsWithAsync && init.type === "Identifier") {
  12767. this.raise(Errors.ForOfAsync, init);
  12768. }
  12769. }
  12770. if (isForOf || this.match(58)) {
  12771. this.checkDestructuringPrivate(refExpressionErrors);
  12772. this.toAssignable(init, true);
  12773. const type = isForOf ? "ForOfStatement" : "ForInStatement";
  12774. this.checkLVal(init, {
  12775. type
  12776. });
  12777. return this.parseForIn(node, init, awaitAt);
  12778. } else {
  12779. this.checkExpressionErrors(refExpressionErrors, true);
  12780. }
  12781. if (awaitAt !== null) {
  12782. this.unexpected(awaitAt);
  12783. }
  12784. return this.parseFor(node, init);
  12785. }
  12786. parseFunctionStatement(node, isAsync, isHangingDeclaration) {
  12787. this.next();
  12788. return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0));
  12789. }
  12790. parseIfStatement(node) {
  12791. this.next();
  12792. node.test = this.parseHeaderExpression();
  12793. node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration();
  12794. node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null;
  12795. return this.finishNode(node, "IfStatement");
  12796. }
  12797. parseReturnStatement(node) {
  12798. if (!this.prodParam.hasReturn && !(this.optionFlags & 2)) {
  12799. this.raise(Errors.IllegalReturn, this.state.startLoc);
  12800. }
  12801. this.next();
  12802. if (this.isLineTerminator()) {
  12803. node.argument = null;
  12804. } else {
  12805. node.argument = this.parseExpression();
  12806. this.semicolon();
  12807. }
  12808. return this.finishNode(node, "ReturnStatement");
  12809. }
  12810. parseSwitchStatement(node) {
  12811. this.next();
  12812. node.discriminant = this.parseHeaderExpression();
  12813. const cases = node.cases = [];
  12814. this.expect(5);
  12815. this.state.labels.push(switchLabel);
  12816. this.scope.enter(0);
  12817. let cur;
  12818. for (let sawDefault; !this.match(8);) {
  12819. if (this.match(61) || this.match(65)) {
  12820. const isCase = this.match(61);
  12821. if (cur) this.finishNode(cur, "SwitchCase");
  12822. cases.push(cur = this.startNode());
  12823. cur.consequent = [];
  12824. this.next();
  12825. if (isCase) {
  12826. cur.test = this.parseExpression();
  12827. } else {
  12828. if (sawDefault) {
  12829. this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc);
  12830. }
  12831. sawDefault = true;
  12832. cur.test = null;
  12833. }
  12834. this.expect(14);
  12835. } else {
  12836. if (cur) {
  12837. cur.consequent.push(this.parseStatementListItem());
  12838. } else {
  12839. this.unexpected();
  12840. }
  12841. }
  12842. }
  12843. this.scope.exit();
  12844. if (cur) this.finishNode(cur, "SwitchCase");
  12845. this.next();
  12846. this.state.labels.pop();
  12847. return this.finishNode(node, "SwitchStatement");
  12848. }
  12849. parseThrowStatement(node) {
  12850. this.next();
  12851. if (this.hasPrecedingLineBreak()) {
  12852. this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc);
  12853. }
  12854. node.argument = this.parseExpression();
  12855. this.semicolon();
  12856. return this.finishNode(node, "ThrowStatement");
  12857. }
  12858. parseCatchClauseParam() {
  12859. const param = this.parseBindingAtom();
  12860. this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0);
  12861. this.checkLVal(param, {
  12862. type: "CatchClause"
  12863. }, 9);
  12864. return param;
  12865. }
  12866. parseTryStatement(node) {
  12867. this.next();
  12868. node.block = this.parseBlock();
  12869. node.handler = null;
  12870. if (this.match(62)) {
  12871. const clause = this.startNode();
  12872. this.next();
  12873. if (this.match(10)) {
  12874. this.expect(10);
  12875. clause.param = this.parseCatchClauseParam();
  12876. this.expect(11);
  12877. } else {
  12878. clause.param = null;
  12879. this.scope.enter(0);
  12880. }
  12881. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  12882. this.scope.exit();
  12883. node.handler = this.finishNode(clause, "CatchClause");
  12884. }
  12885. node.finalizer = this.eat(67) ? this.parseBlock() : null;
  12886. if (!node.handler && !node.finalizer) {
  12887. this.raise(Errors.NoCatchOrFinally, node);
  12888. }
  12889. return this.finishNode(node, "TryStatement");
  12890. }
  12891. parseVarStatement(node, kind, allowMissingInitializer = false) {
  12892. this.next();
  12893. this.parseVar(node, false, kind, allowMissingInitializer);
  12894. this.semicolon();
  12895. return this.finishNode(node, "VariableDeclaration");
  12896. }
  12897. parseWhileStatement(node) {
  12898. this.next();
  12899. node.test = this.parseHeaderExpression();
  12900. this.state.labels.push(loopLabel);
  12901. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12902. this.state.labels.pop();
  12903. return this.finishNode(node, "WhileStatement");
  12904. }
  12905. parseWithStatement(node) {
  12906. if (this.state.strict) {
  12907. this.raise(Errors.StrictWith, this.state.startLoc);
  12908. }
  12909. this.next();
  12910. node.object = this.parseHeaderExpression();
  12911. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12912. return this.finishNode(node, "WithStatement");
  12913. }
  12914. parseEmptyStatement(node) {
  12915. this.next();
  12916. return this.finishNode(node, "EmptyStatement");
  12917. }
  12918. parseLabeledStatement(node, maybeName, expr, flags) {
  12919. for (const label of this.state.labels) {
  12920. if (label.name === maybeName) {
  12921. this.raise(Errors.LabelRedeclaration, expr, {
  12922. labelName: maybeName
  12923. });
  12924. }
  12925. }
  12926. const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null;
  12927. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  12928. const label = this.state.labels[i];
  12929. if (label.statementStart === node.start) {
  12930. label.statementStart = this.sourceToOffsetPos(this.state.start);
  12931. label.kind = kind;
  12932. } else {
  12933. break;
  12934. }
  12935. }
  12936. this.state.labels.push({
  12937. name: maybeName,
  12938. kind: kind,
  12939. statementStart: this.sourceToOffsetPos(this.state.start)
  12940. });
  12941. node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement();
  12942. this.state.labels.pop();
  12943. node.label = expr;
  12944. return this.finishNode(node, "LabeledStatement");
  12945. }
  12946. parseExpressionStatement(node, expr, decorators) {
  12947. node.expression = expr;
  12948. this.semicolon();
  12949. return this.finishNode(node, "ExpressionStatement");
  12950. }
  12951. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  12952. const node = this.startNode();
  12953. if (allowDirectives) {
  12954. this.state.strictErrors.clear();
  12955. }
  12956. this.expect(5);
  12957. if (createNewLexicalScope) {
  12958. this.scope.enter(0);
  12959. }
  12960. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  12961. if (createNewLexicalScope) {
  12962. this.scope.exit();
  12963. }
  12964. return this.finishNode(node, "BlockStatement");
  12965. }
  12966. isValidDirective(stmt) {
  12967. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  12968. }
  12969. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  12970. const body = node.body = [];
  12971. const directives = node.directives = [];
  12972. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  12973. }
  12974. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  12975. const oldStrict = this.state.strict;
  12976. let hasStrictModeDirective = false;
  12977. let parsedNonDirective = false;
  12978. while (!this.match(end)) {
  12979. const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem();
  12980. if (directives && !parsedNonDirective) {
  12981. if (this.isValidDirective(stmt)) {
  12982. const directive = this.stmtToDirective(stmt);
  12983. directives.push(directive);
  12984. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  12985. hasStrictModeDirective = true;
  12986. this.setStrict(true);
  12987. }
  12988. continue;
  12989. }
  12990. parsedNonDirective = true;
  12991. this.state.strictErrors.clear();
  12992. }
  12993. body.push(stmt);
  12994. }
  12995. afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective);
  12996. if (!oldStrict) {
  12997. this.setStrict(false);
  12998. }
  12999. this.next();
  13000. }
  13001. parseFor(node, init) {
  13002. node.init = init;
  13003. this.semicolon(false);
  13004. node.test = this.match(13) ? null : this.parseExpression();
  13005. this.semicolon(false);
  13006. node.update = this.match(11) ? null : this.parseExpression();
  13007. this.expect(11);
  13008. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  13009. this.scope.exit();
  13010. this.state.labels.pop();
  13011. return this.finishNode(node, "ForStatement");
  13012. }
  13013. parseForIn(node, init, awaitAt) {
  13014. const isForIn = this.match(58);
  13015. this.next();
  13016. if (isForIn) {
  13017. if (awaitAt !== null) this.unexpected(awaitAt);
  13018. } else {
  13019. node.await = awaitAt !== null;
  13020. }
  13021. 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")) {
  13022. this.raise(Errors.ForInOfLoopInitializer, init, {
  13023. type: isForIn ? "ForInStatement" : "ForOfStatement"
  13024. });
  13025. }
  13026. if (init.type === "AssignmentPattern") {
  13027. this.raise(Errors.InvalidLhs, init, {
  13028. ancestor: {
  13029. type: "ForStatement"
  13030. }
  13031. });
  13032. }
  13033. node.left = init;
  13034. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  13035. this.expect(11);
  13036. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  13037. this.scope.exit();
  13038. this.state.labels.pop();
  13039. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  13040. }
  13041. parseVar(node, isFor, kind, allowMissingInitializer = false) {
  13042. const declarations = node.declarations = [];
  13043. node.kind = kind;
  13044. for (;;) {
  13045. const decl = this.startNode();
  13046. this.parseVarId(decl, kind);
  13047. decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  13048. if (decl.init === null && !allowMissingInitializer) {
  13049. if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) {
  13050. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  13051. kind: "destructuring"
  13052. });
  13053. } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) {
  13054. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  13055. kind
  13056. });
  13057. }
  13058. }
  13059. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  13060. if (!this.eat(12)) break;
  13061. }
  13062. return node;
  13063. }
  13064. parseVarId(decl, kind) {
  13065. const id = this.parseBindingAtom();
  13066. if (kind === "using" || kind === "await using") {
  13067. if (id.type === "ArrayPattern" || id.type === "ObjectPattern") {
  13068. this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start);
  13069. }
  13070. }
  13071. this.checkLVal(id, {
  13072. type: "VariableDeclarator"
  13073. }, kind === "var" ? 5 : 8201);
  13074. decl.id = id;
  13075. }
  13076. parseAsyncFunctionExpression(node) {
  13077. return this.parseFunction(node, 8);
  13078. }
  13079. parseFunction(node, flags = 0) {
  13080. const hangingDeclaration = flags & 2;
  13081. const isDeclaration = !!(flags & 1);
  13082. const requireId = isDeclaration && !(flags & 4);
  13083. const isAsync = !!(flags & 8);
  13084. this.initFunction(node, isAsync);
  13085. if (this.match(55)) {
  13086. if (hangingDeclaration) {
  13087. this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc);
  13088. }
  13089. this.next();
  13090. node.generator = true;
  13091. }
  13092. if (isDeclaration) {
  13093. node.id = this.parseFunctionId(requireId);
  13094. }
  13095. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  13096. this.state.maybeInArrowParameters = false;
  13097. this.scope.enter(2);
  13098. this.prodParam.enter(functionFlags(isAsync, node.generator));
  13099. if (!isDeclaration) {
  13100. node.id = this.parseFunctionId();
  13101. }
  13102. this.parseFunctionParams(node, false);
  13103. this.withSmartMixTopicForbiddingContext(() => {
  13104. this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression");
  13105. });
  13106. this.prodParam.exit();
  13107. this.scope.exit();
  13108. if (isDeclaration && !hangingDeclaration) {
  13109. this.registerFunctionStatementId(node);
  13110. }
  13111. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  13112. return node;
  13113. }
  13114. parseFunctionId(requireId) {
  13115. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  13116. }
  13117. parseFunctionParams(node, isConstructor) {
  13118. this.expect(10);
  13119. this.expressionScope.enter(newParameterDeclarationScope());
  13120. node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0));
  13121. this.expressionScope.exit();
  13122. }
  13123. registerFunctionStatementId(node) {
  13124. if (!node.id) return;
  13125. 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);
  13126. }
  13127. parseClass(node, isStatement, optionalId) {
  13128. this.next();
  13129. const oldStrict = this.state.strict;
  13130. this.state.strict = true;
  13131. this.parseClassId(node, isStatement, optionalId);
  13132. this.parseClassSuper(node);
  13133. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  13134. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  13135. }
  13136. isClassProperty() {
  13137. return this.match(29) || this.match(13) || this.match(8);
  13138. }
  13139. isClassMethod() {
  13140. return this.match(10);
  13141. }
  13142. nameIsConstructor(key) {
  13143. return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor";
  13144. }
  13145. isNonstaticConstructor(method) {
  13146. return !method.computed && !method.static && this.nameIsConstructor(method.key);
  13147. }
  13148. parseClassBody(hadSuperClass, oldStrict) {
  13149. this.classScope.enter();
  13150. const state = {
  13151. hadConstructor: false,
  13152. hadSuperClass
  13153. };
  13154. let decorators = [];
  13155. const classBody = this.startNode();
  13156. classBody.body = [];
  13157. this.expect(5);
  13158. this.withSmartMixTopicForbiddingContext(() => {
  13159. while (!this.match(8)) {
  13160. if (this.eat(13)) {
  13161. if (decorators.length > 0) {
  13162. throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc);
  13163. }
  13164. continue;
  13165. }
  13166. if (this.match(26)) {
  13167. decorators.push(this.parseDecorator());
  13168. continue;
  13169. }
  13170. const member = this.startNode();
  13171. if (decorators.length) {
  13172. member.decorators = decorators;
  13173. this.resetStartLocationFromNode(member, decorators[0]);
  13174. decorators = [];
  13175. }
  13176. this.parseClassMember(classBody, member, state);
  13177. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  13178. this.raise(Errors.DecoratorConstructor, member);
  13179. }
  13180. }
  13181. });
  13182. this.state.strict = oldStrict;
  13183. this.next();
  13184. if (decorators.length) {
  13185. throw this.raise(Errors.TrailingDecorator, this.state.startLoc);
  13186. }
  13187. this.classScope.exit();
  13188. return this.finishNode(classBody, "ClassBody");
  13189. }
  13190. parseClassMemberFromModifier(classBody, member) {
  13191. const key = this.parseIdentifier(true);
  13192. if (this.isClassMethod()) {
  13193. const method = member;
  13194. method.kind = "method";
  13195. method.computed = false;
  13196. method.key = key;
  13197. method.static = false;
  13198. this.pushClassMethod(classBody, method, false, false, false, false);
  13199. return true;
  13200. } else if (this.isClassProperty()) {
  13201. const prop = member;
  13202. prop.computed = false;
  13203. prop.key = key;
  13204. prop.static = false;
  13205. classBody.body.push(this.parseClassProperty(prop));
  13206. return true;
  13207. }
  13208. this.resetPreviousNodeTrailingComments(key);
  13209. return false;
  13210. }
  13211. parseClassMember(classBody, member, state) {
  13212. const isStatic = this.isContextual(106);
  13213. if (isStatic) {
  13214. if (this.parseClassMemberFromModifier(classBody, member)) {
  13215. return;
  13216. }
  13217. if (this.eat(5)) {
  13218. this.parseClassStaticBlock(classBody, member);
  13219. return;
  13220. }
  13221. }
  13222. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  13223. }
  13224. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  13225. const publicMethod = member;
  13226. const privateMethod = member;
  13227. const publicProp = member;
  13228. const privateProp = member;
  13229. const accessorProp = member;
  13230. const method = publicMethod;
  13231. const publicMember = publicMethod;
  13232. member.static = isStatic;
  13233. this.parsePropertyNamePrefixOperator(member);
  13234. if (this.eat(55)) {
  13235. method.kind = "method";
  13236. const isPrivateName = this.match(139);
  13237. this.parseClassElementName(method);
  13238. if (isPrivateName) {
  13239. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  13240. return;
  13241. }
  13242. if (this.isNonstaticConstructor(publicMethod)) {
  13243. this.raise(Errors.ConstructorIsGenerator, publicMethod.key);
  13244. }
  13245. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  13246. return;
  13247. }
  13248. const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type);
  13249. const key = this.parseClassElementName(member);
  13250. const maybeContextualKw = isContextual ? key.name : null;
  13251. const isPrivate = this.isPrivateName(key);
  13252. const maybeQuestionTokenStartLoc = this.state.startLoc;
  13253. this.parsePostMemberNameModifiers(publicMember);
  13254. if (this.isClassMethod()) {
  13255. method.kind = "method";
  13256. if (isPrivate) {
  13257. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  13258. return;
  13259. }
  13260. const isConstructor = this.isNonstaticConstructor(publicMethod);
  13261. let allowsDirectSuper = false;
  13262. if (isConstructor) {
  13263. publicMethod.kind = "constructor";
  13264. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  13265. this.raise(Errors.DuplicateConstructor, key);
  13266. }
  13267. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  13268. this.raise(Errors.OverrideOnConstructor, key);
  13269. }
  13270. state.hadConstructor = true;
  13271. allowsDirectSuper = state.hadSuperClass;
  13272. }
  13273. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  13274. } else if (this.isClassProperty()) {
  13275. if (isPrivate) {
  13276. this.pushClassPrivateProperty(classBody, privateProp);
  13277. } else {
  13278. this.pushClassProperty(classBody, publicProp);
  13279. }
  13280. } else if (maybeContextualKw === "async" && !this.isLineTerminator()) {
  13281. this.resetPreviousNodeTrailingComments(key);
  13282. const isGenerator = this.eat(55);
  13283. if (publicMember.optional) {
  13284. this.unexpected(maybeQuestionTokenStartLoc);
  13285. }
  13286. method.kind = "method";
  13287. const isPrivate = this.match(139);
  13288. this.parseClassElementName(method);
  13289. this.parsePostMemberNameModifiers(publicMember);
  13290. if (isPrivate) {
  13291. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  13292. } else {
  13293. if (this.isNonstaticConstructor(publicMethod)) {
  13294. this.raise(Errors.ConstructorIsAsync, publicMethod.key);
  13295. }
  13296. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  13297. }
  13298. } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) {
  13299. this.resetPreviousNodeTrailingComments(key);
  13300. method.kind = maybeContextualKw;
  13301. const isPrivate = this.match(139);
  13302. this.parseClassElementName(publicMethod);
  13303. if (isPrivate) {
  13304. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  13305. } else {
  13306. if (this.isNonstaticConstructor(publicMethod)) {
  13307. this.raise(Errors.ConstructorIsAccessor, publicMethod.key);
  13308. }
  13309. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  13310. }
  13311. this.checkGetterSetterParams(publicMethod);
  13312. } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) {
  13313. this.expectPlugin("decoratorAutoAccessors");
  13314. this.resetPreviousNodeTrailingComments(key);
  13315. const isPrivate = this.match(139);
  13316. this.parseClassElementName(publicProp);
  13317. this.pushClassAccessorProperty(classBody, accessorProp, isPrivate);
  13318. } else if (this.isLineTerminator()) {
  13319. if (isPrivate) {
  13320. this.pushClassPrivateProperty(classBody, privateProp);
  13321. } else {
  13322. this.pushClassProperty(classBody, publicProp);
  13323. }
  13324. } else {
  13325. this.unexpected();
  13326. }
  13327. }
  13328. parseClassElementName(member) {
  13329. const {
  13330. type,
  13331. value
  13332. } = this.state;
  13333. if ((type === 132 || type === 134) && member.static && value === "prototype") {
  13334. this.raise(Errors.StaticPrototype, this.state.startLoc);
  13335. }
  13336. if (type === 139) {
  13337. if (value === "constructor") {
  13338. this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc);
  13339. }
  13340. const key = this.parsePrivateName();
  13341. member.key = key;
  13342. return key;
  13343. }
  13344. this.parsePropertyName(member);
  13345. return member.key;
  13346. }
  13347. parseClassStaticBlock(classBody, member) {
  13348. var _member$decorators;
  13349. this.scope.enter(64 | 128 | 16);
  13350. const oldLabels = this.state.labels;
  13351. this.state.labels = [];
  13352. this.prodParam.enter(0);
  13353. const body = member.body = [];
  13354. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  13355. this.prodParam.exit();
  13356. this.scope.exit();
  13357. this.state.labels = oldLabels;
  13358. classBody.body.push(this.finishNode(member, "StaticBlock"));
  13359. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  13360. this.raise(Errors.DecoratorStaticBlock, member);
  13361. }
  13362. }
  13363. pushClassProperty(classBody, prop) {
  13364. if (!prop.computed && this.nameIsConstructor(prop.key)) {
  13365. this.raise(Errors.ConstructorClassField, prop.key);
  13366. }
  13367. classBody.body.push(this.parseClassProperty(prop));
  13368. }
  13369. pushClassPrivateProperty(classBody, prop) {
  13370. const node = this.parseClassPrivateProperty(prop);
  13371. classBody.body.push(node);
  13372. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  13373. }
  13374. pushClassAccessorProperty(classBody, prop, isPrivate) {
  13375. if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) {
  13376. this.raise(Errors.ConstructorClassField, prop.key);
  13377. }
  13378. const node = this.parseClassAccessorProperty(prop);
  13379. classBody.body.push(node);
  13380. if (isPrivate) {
  13381. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  13382. }
  13383. }
  13384. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  13385. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  13386. }
  13387. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  13388. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  13389. classBody.body.push(node);
  13390. const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0;
  13391. this.declareClassPrivateMethodInScope(node, kind);
  13392. }
  13393. declareClassPrivateMethodInScope(node, kind) {
  13394. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start);
  13395. }
  13396. parsePostMemberNameModifiers(methodOrProp) {}
  13397. parseClassPrivateProperty(node) {
  13398. this.parseInitializer(node);
  13399. this.semicolon();
  13400. return this.finishNode(node, "ClassPrivateProperty");
  13401. }
  13402. parseClassProperty(node) {
  13403. this.parseInitializer(node);
  13404. this.semicolon();
  13405. return this.finishNode(node, "ClassProperty");
  13406. }
  13407. parseClassAccessorProperty(node) {
  13408. this.parseInitializer(node);
  13409. this.semicolon();
  13410. return this.finishNode(node, "ClassAccessorProperty");
  13411. }
  13412. parseInitializer(node) {
  13413. this.scope.enter(64 | 16);
  13414. this.expressionScope.enter(newExpressionScope());
  13415. this.prodParam.enter(0);
  13416. node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
  13417. this.expressionScope.exit();
  13418. this.prodParam.exit();
  13419. this.scope.exit();
  13420. }
  13421. parseClassId(node, isStatement, optionalId, bindingType = 8331) {
  13422. if (tokenIsIdentifier(this.state.type)) {
  13423. node.id = this.parseIdentifier();
  13424. if (isStatement) {
  13425. this.declareNameFromIdentifier(node.id, bindingType);
  13426. }
  13427. } else {
  13428. if (optionalId || !isStatement) {
  13429. node.id = null;
  13430. } else {
  13431. throw this.raise(Errors.MissingClassName, this.state.startLoc);
  13432. }
  13433. }
  13434. }
  13435. parseClassSuper(node) {
  13436. node.superClass = this.eat(81) ? this.parseExprSubscripts() : null;
  13437. }
  13438. parseExport(node, decorators) {
  13439. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true);
  13440. const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  13441. const parseAfterDefault = !hasDefault || this.eat(12);
  13442. const hasStar = parseAfterDefault && this.eatExportStar(node);
  13443. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  13444. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  13445. const isFromRequired = hasDefault || hasStar;
  13446. if (hasStar && !hasNamespace) {
  13447. if (hasDefault) this.unexpected();
  13448. if (decorators) {
  13449. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13450. }
  13451. this.parseExportFrom(node, true);
  13452. this.sawUnambiguousESM = true;
  13453. return this.finishNode(node, "ExportAllDeclaration");
  13454. }
  13455. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  13456. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) {
  13457. this.unexpected(null, 5);
  13458. }
  13459. if (hasNamespace && parseAfterNamespace) {
  13460. this.unexpected(null, 98);
  13461. }
  13462. let hasDeclaration;
  13463. if (isFromRequired || hasSpecifiers) {
  13464. hasDeclaration = false;
  13465. if (decorators) {
  13466. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13467. }
  13468. this.parseExportFrom(node, isFromRequired);
  13469. } else {
  13470. hasDeclaration = this.maybeParseExportDeclaration(node);
  13471. }
  13472. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  13473. var _node2$declaration;
  13474. const node2 = node;
  13475. this.checkExport(node2, true, false, !!node2.source);
  13476. if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") {
  13477. this.maybeTakeDecorators(decorators, node2.declaration, node2);
  13478. } else if (decorators) {
  13479. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13480. }
  13481. this.sawUnambiguousESM = true;
  13482. return this.finishNode(node2, "ExportNamedDeclaration");
  13483. }
  13484. if (this.eat(65)) {
  13485. const node2 = node;
  13486. const decl = this.parseExportDefaultExpression();
  13487. node2.declaration = decl;
  13488. if (decl.type === "ClassDeclaration") {
  13489. this.maybeTakeDecorators(decorators, decl, node2);
  13490. } else if (decorators) {
  13491. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13492. }
  13493. this.checkExport(node2, true, true);
  13494. this.sawUnambiguousESM = true;
  13495. return this.finishNode(node2, "ExportDefaultDeclaration");
  13496. }
  13497. this.unexpected(null, 5);
  13498. }
  13499. eatExportStar(node) {
  13500. return this.eat(55);
  13501. }
  13502. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  13503. if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) {
  13504. this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start);
  13505. const id = maybeDefaultIdentifier || this.parseIdentifier(true);
  13506. const specifier = this.startNodeAtNode(id);
  13507. specifier.exported = id;
  13508. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  13509. return true;
  13510. }
  13511. return false;
  13512. }
  13513. maybeParseExportNamespaceSpecifier(node) {
  13514. if (this.isContextual(93)) {
  13515. var _ref, _ref$specifiers;
  13516. (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = [];
  13517. const specifier = this.startNodeAt(this.state.lastTokStartLoc);
  13518. this.next();
  13519. specifier.exported = this.parseModuleExportName();
  13520. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  13521. return true;
  13522. }
  13523. return false;
  13524. }
  13525. maybeParseExportNamedSpecifiers(node) {
  13526. if (this.match(5)) {
  13527. const node2 = node;
  13528. if (!node2.specifiers) node2.specifiers = [];
  13529. const isTypeExport = node2.exportKind === "type";
  13530. node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  13531. node2.source = null;
  13532. if (this.hasPlugin("importAssertions")) {
  13533. node2.assertions = [];
  13534. } else {
  13535. node2.attributes = [];
  13536. }
  13537. node2.declaration = null;
  13538. return true;
  13539. }
  13540. return false;
  13541. }
  13542. maybeParseExportDeclaration(node) {
  13543. if (this.shouldParseExportDeclaration()) {
  13544. node.specifiers = [];
  13545. node.source = null;
  13546. if (this.hasPlugin("importAssertions")) {
  13547. node.assertions = [];
  13548. } else {
  13549. node.attributes = [];
  13550. }
  13551. node.declaration = this.parseExportDeclaration(node);
  13552. return true;
  13553. }
  13554. return false;
  13555. }
  13556. isAsyncFunction() {
  13557. if (!this.isContextual(95)) return false;
  13558. const next = this.nextTokenInLineStart();
  13559. return this.isUnparsedContextual(next, "function");
  13560. }
  13561. parseExportDefaultExpression() {
  13562. const expr = this.startNode();
  13563. if (this.match(68)) {
  13564. this.next();
  13565. return this.parseFunction(expr, 1 | 4);
  13566. } else if (this.isAsyncFunction()) {
  13567. this.next();
  13568. this.next();
  13569. return this.parseFunction(expr, 1 | 4 | 8);
  13570. }
  13571. if (this.match(80)) {
  13572. return this.parseClass(expr, true, true);
  13573. }
  13574. if (this.match(26)) {
  13575. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  13576. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  13577. }
  13578. return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true);
  13579. }
  13580. if (this.match(75) || this.match(74) || this.isLet()) {
  13581. throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc);
  13582. }
  13583. const res = this.parseMaybeAssignAllowIn();
  13584. this.semicolon();
  13585. return res;
  13586. }
  13587. parseExportDeclaration(node) {
  13588. if (this.match(80)) {
  13589. const node = this.parseClass(this.startNode(), true, false);
  13590. return node;
  13591. }
  13592. return this.parseStatementListItem();
  13593. }
  13594. isExportDefaultSpecifier() {
  13595. const {
  13596. type
  13597. } = this.state;
  13598. if (tokenIsIdentifier(type)) {
  13599. if (type === 95 && !this.state.containsEsc || type === 100) {
  13600. return false;
  13601. }
  13602. if ((type === 130 || type === 129) && !this.state.containsEsc) {
  13603. const {
  13604. type: nextType
  13605. } = this.lookahead();
  13606. if (tokenIsIdentifier(nextType) && nextType !== 98 || nextType === 5) {
  13607. this.expectOnePlugin(["flow", "typescript"]);
  13608. return false;
  13609. }
  13610. }
  13611. } else if (!this.match(65)) {
  13612. return false;
  13613. }
  13614. const next = this.nextTokenStart();
  13615. const hasFrom = this.isUnparsedContextual(next, "from");
  13616. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  13617. return true;
  13618. }
  13619. if (this.match(65) && hasFrom) {
  13620. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  13621. return nextAfterFrom === 34 || nextAfterFrom === 39;
  13622. }
  13623. return false;
  13624. }
  13625. parseExportFrom(node, expect) {
  13626. if (this.eatContextual(98)) {
  13627. node.source = this.parseImportSource();
  13628. this.checkExport(node);
  13629. this.maybeParseImportAttributes(node);
  13630. this.checkJSONModuleImport(node);
  13631. } else if (expect) {
  13632. this.unexpected();
  13633. }
  13634. this.semicolon();
  13635. }
  13636. shouldParseExportDeclaration() {
  13637. const {
  13638. type
  13639. } = this.state;
  13640. if (type === 26) {
  13641. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  13642. if (this.hasPlugin("decorators")) {
  13643. if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  13644. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  13645. }
  13646. return true;
  13647. }
  13648. }
  13649. if (this.isContextual(107)) {
  13650. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  13651. return true;
  13652. }
  13653. if (this.isContextual(96) && this.startsAwaitUsing()) {
  13654. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  13655. return true;
  13656. }
  13657. return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction();
  13658. }
  13659. checkExport(node, checkNames, isDefault, isFrom) {
  13660. if (checkNames) {
  13661. var _node$specifiers;
  13662. if (isDefault) {
  13663. this.checkDuplicateExports(node, "default");
  13664. if (this.hasPlugin("exportDefaultFrom")) {
  13665. var _declaration$extra;
  13666. const declaration = node.declaration;
  13667. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  13668. this.raise(Errors.ExportDefaultFromAsIdentifier, declaration);
  13669. }
  13670. }
  13671. } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
  13672. for (const specifier of node.specifiers) {
  13673. const {
  13674. exported
  13675. } = specifier;
  13676. const exportName = exported.type === "Identifier" ? exported.name : exported.value;
  13677. this.checkDuplicateExports(specifier, exportName);
  13678. if (!isFrom && specifier.local) {
  13679. const {
  13680. local
  13681. } = specifier;
  13682. if (local.type !== "Identifier") {
  13683. this.raise(Errors.ExportBindingIsString, specifier, {
  13684. localName: local.value,
  13685. exportName
  13686. });
  13687. } else {
  13688. this.checkReservedWord(local.name, local.loc.start, true, false);
  13689. this.scope.checkLocalExport(local);
  13690. }
  13691. }
  13692. }
  13693. } else if (node.declaration) {
  13694. const decl = node.declaration;
  13695. if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
  13696. const {
  13697. id
  13698. } = decl;
  13699. if (!id) throw new Error("Assertion failure");
  13700. this.checkDuplicateExports(node, id.name);
  13701. } else if (decl.type === "VariableDeclaration") {
  13702. for (const declaration of decl.declarations) {
  13703. this.checkDeclaration(declaration.id);
  13704. }
  13705. }
  13706. }
  13707. }
  13708. }
  13709. checkDeclaration(node) {
  13710. if (node.type === "Identifier") {
  13711. this.checkDuplicateExports(node, node.name);
  13712. } else if (node.type === "ObjectPattern") {
  13713. for (const prop of node.properties) {
  13714. this.checkDeclaration(prop);
  13715. }
  13716. } else if (node.type === "ArrayPattern") {
  13717. for (const elem of node.elements) {
  13718. if (elem) {
  13719. this.checkDeclaration(elem);
  13720. }
  13721. }
  13722. } else if (node.type === "ObjectProperty") {
  13723. this.checkDeclaration(node.value);
  13724. } else if (node.type === "RestElement") {
  13725. this.checkDeclaration(node.argument);
  13726. } else if (node.type === "AssignmentPattern") {
  13727. this.checkDeclaration(node.left);
  13728. }
  13729. }
  13730. checkDuplicateExports(node, exportName) {
  13731. if (this.exportedIdentifiers.has(exportName)) {
  13732. if (exportName === "default") {
  13733. this.raise(Errors.DuplicateDefaultExport, node);
  13734. } else {
  13735. this.raise(Errors.DuplicateExport, node, {
  13736. exportName
  13737. });
  13738. }
  13739. }
  13740. this.exportedIdentifiers.add(exportName);
  13741. }
  13742. parseExportSpecifiers(isInTypeExport) {
  13743. const nodes = [];
  13744. let first = true;
  13745. this.expect(5);
  13746. while (!this.eat(8)) {
  13747. if (first) {
  13748. first = false;
  13749. } else {
  13750. this.expect(12);
  13751. if (this.eat(8)) break;
  13752. }
  13753. const isMaybeTypeOnly = this.isContextual(130);
  13754. const isString = this.match(134);
  13755. const node = this.startNode();
  13756. node.local = this.parseModuleExportName();
  13757. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  13758. }
  13759. return nodes;
  13760. }
  13761. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  13762. if (this.eatContextual(93)) {
  13763. node.exported = this.parseModuleExportName();
  13764. } else if (isString) {
  13765. node.exported = cloneStringLiteral(node.local);
  13766. } else if (!node.exported) {
  13767. node.exported = cloneIdentifier(node.local);
  13768. }
  13769. return this.finishNode(node, "ExportSpecifier");
  13770. }
  13771. parseModuleExportName() {
  13772. if (this.match(134)) {
  13773. const result = this.parseStringLiteral(this.state.value);
  13774. const surrogate = loneSurrogate.exec(result.value);
  13775. if (surrogate) {
  13776. this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, {
  13777. surrogateCharCode: surrogate[0].charCodeAt(0)
  13778. });
  13779. }
  13780. return result;
  13781. }
  13782. return this.parseIdentifier(true);
  13783. }
  13784. isJSONModuleImport(node) {
  13785. if (node.assertions != null) {
  13786. return node.assertions.some(({
  13787. key,
  13788. value
  13789. }) => {
  13790. return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type");
  13791. });
  13792. }
  13793. return false;
  13794. }
  13795. checkImportReflection(node) {
  13796. const {
  13797. specifiers
  13798. } = node;
  13799. const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null;
  13800. if (node.phase === "source") {
  13801. if (singleBindingType !== "ImportDefaultSpecifier") {
  13802. this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start);
  13803. }
  13804. } else if (node.phase === "defer") {
  13805. if (singleBindingType !== "ImportNamespaceSpecifier") {
  13806. this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start);
  13807. }
  13808. } else if (node.module) {
  13809. var _node$assertions;
  13810. if (singleBindingType !== "ImportDefaultSpecifier") {
  13811. this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start);
  13812. }
  13813. if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) {
  13814. this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start);
  13815. }
  13816. }
  13817. }
  13818. checkJSONModuleImport(node) {
  13819. if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") {
  13820. const {
  13821. specifiers
  13822. } = node;
  13823. if (specifiers != null) {
  13824. const nonDefaultNamedSpecifier = specifiers.find(specifier => {
  13825. let imported;
  13826. if (specifier.type === "ExportSpecifier") {
  13827. imported = specifier.local;
  13828. } else if (specifier.type === "ImportSpecifier") {
  13829. imported = specifier.imported;
  13830. }
  13831. if (imported !== undefined) {
  13832. return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default";
  13833. }
  13834. });
  13835. if (nonDefaultNamedSpecifier !== undefined) {
  13836. this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start);
  13837. }
  13838. }
  13839. }
  13840. }
  13841. isPotentialImportPhase(isExport) {
  13842. if (isExport) return false;
  13843. return this.isContextual(105) || this.isContextual(97) || this.isContextual(127);
  13844. }
  13845. applyImportPhase(node, isExport, phase, loc) {
  13846. if (isExport) {
  13847. return;
  13848. }
  13849. if (phase === "module") {
  13850. this.expectPlugin("importReflection", loc);
  13851. node.module = true;
  13852. } else if (this.hasPlugin("importReflection")) {
  13853. node.module = false;
  13854. }
  13855. if (phase === "source") {
  13856. this.expectPlugin("sourcePhaseImports", loc);
  13857. node.phase = "source";
  13858. } else if (phase === "defer") {
  13859. this.expectPlugin("deferredImportEvaluation", loc);
  13860. node.phase = "defer";
  13861. } else if (this.hasPlugin("sourcePhaseImports")) {
  13862. node.phase = null;
  13863. }
  13864. }
  13865. parseMaybeImportPhase(node, isExport) {
  13866. if (!this.isPotentialImportPhase(isExport)) {
  13867. this.applyImportPhase(node, isExport, null);
  13868. return null;
  13869. }
  13870. const phaseIdentifier = this.parseIdentifier(true);
  13871. const {
  13872. type
  13873. } = this.state;
  13874. const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  13875. if (isImportPhase) {
  13876. this.resetPreviousIdentifierLeadingComments(phaseIdentifier);
  13877. this.applyImportPhase(node, isExport, phaseIdentifier.name, phaseIdentifier.loc.start);
  13878. return null;
  13879. } else {
  13880. this.applyImportPhase(node, isExport, null);
  13881. return phaseIdentifier;
  13882. }
  13883. }
  13884. isPrecedingIdImportPhase(phase) {
  13885. const {
  13886. type
  13887. } = this.state;
  13888. return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  13889. }
  13890. parseImport(node) {
  13891. if (this.match(134)) {
  13892. return this.parseImportSourceAndAttributes(node);
  13893. }
  13894. return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false));
  13895. }
  13896. parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) {
  13897. node.specifiers = [];
  13898. const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier);
  13899. const parseNext = !hasDefault || this.eat(12);
  13900. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  13901. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  13902. this.expectContextual(98);
  13903. return this.parseImportSourceAndAttributes(node);
  13904. }
  13905. parseImportSourceAndAttributes(node) {
  13906. var _node$specifiers2;
  13907. (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = [];
  13908. node.source = this.parseImportSource();
  13909. this.maybeParseImportAttributes(node);
  13910. this.checkImportReflection(node);
  13911. this.checkJSONModuleImport(node);
  13912. this.semicolon();
  13913. this.sawUnambiguousESM = true;
  13914. return this.finishNode(node, "ImportDeclaration");
  13915. }
  13916. parseImportSource() {
  13917. if (!this.match(134)) this.unexpected();
  13918. return this.parseExprAtom();
  13919. }
  13920. parseImportSpecifierLocal(node, specifier, type) {
  13921. specifier.local = this.parseIdentifier();
  13922. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  13923. }
  13924. finishImportSpecifier(specifier, type, bindingType = 8201) {
  13925. this.checkLVal(specifier.local, {
  13926. type
  13927. }, bindingType);
  13928. return this.finishNode(specifier, type);
  13929. }
  13930. parseImportAttributes() {
  13931. this.expect(5);
  13932. const attrs = [];
  13933. const attrNames = new Set();
  13934. do {
  13935. if (this.match(8)) {
  13936. break;
  13937. }
  13938. const node = this.startNode();
  13939. const keyName = this.state.value;
  13940. if (attrNames.has(keyName)) {
  13941. this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, {
  13942. key: keyName
  13943. });
  13944. }
  13945. attrNames.add(keyName);
  13946. if (this.match(134)) {
  13947. node.key = this.parseStringLiteral(keyName);
  13948. } else {
  13949. node.key = this.parseIdentifier(true);
  13950. }
  13951. this.expect(14);
  13952. if (!this.match(134)) {
  13953. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  13954. }
  13955. node.value = this.parseStringLiteral(this.state.value);
  13956. attrs.push(this.finishNode(node, "ImportAttribute"));
  13957. } while (this.eat(12));
  13958. this.expect(8);
  13959. return attrs;
  13960. }
  13961. parseModuleAttributes() {
  13962. const attrs = [];
  13963. const attributes = new Set();
  13964. do {
  13965. const node = this.startNode();
  13966. node.key = this.parseIdentifier(true);
  13967. if (node.key.name !== "type") {
  13968. this.raise(Errors.ModuleAttributeDifferentFromType, node.key);
  13969. }
  13970. if (attributes.has(node.key.name)) {
  13971. this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, {
  13972. key: node.key.name
  13973. });
  13974. }
  13975. attributes.add(node.key.name);
  13976. this.expect(14);
  13977. if (!this.match(134)) {
  13978. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  13979. }
  13980. node.value = this.parseStringLiteral(this.state.value);
  13981. attrs.push(this.finishNode(node, "ImportAttribute"));
  13982. } while (this.eat(12));
  13983. return attrs;
  13984. }
  13985. maybeParseImportAttributes(node) {
  13986. let attributes;
  13987. {
  13988. var useWith = false;
  13989. }
  13990. if (this.match(76)) {
  13991. if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) {
  13992. return;
  13993. }
  13994. this.next();
  13995. if (this.hasPlugin("moduleAttributes")) {
  13996. attributes = this.parseModuleAttributes();
  13997. this.addExtra(node, "deprecatedWithLegacySyntax", true);
  13998. } else {
  13999. attributes = this.parseImportAttributes();
  14000. }
  14001. {
  14002. useWith = true;
  14003. }
  14004. } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) {
  14005. if (!this.hasPlugin("deprecatedImportAssert") && !this.hasPlugin("importAssertions")) {
  14006. this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc);
  14007. }
  14008. if (!this.hasPlugin("importAssertions")) {
  14009. this.addExtra(node, "deprecatedAssertSyntax", true);
  14010. }
  14011. this.next();
  14012. attributes = this.parseImportAttributes();
  14013. } else {
  14014. attributes = [];
  14015. }
  14016. if (!useWith && this.hasPlugin("importAssertions")) {
  14017. node.assertions = attributes;
  14018. } else {
  14019. node.attributes = attributes;
  14020. }
  14021. }
  14022. maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) {
  14023. if (maybeDefaultIdentifier) {
  14024. const specifier = this.startNodeAtNode(maybeDefaultIdentifier);
  14025. specifier.local = maybeDefaultIdentifier;
  14026. node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier"));
  14027. return true;
  14028. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14029. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier");
  14030. return true;
  14031. }
  14032. return false;
  14033. }
  14034. maybeParseStarImportSpecifier(node) {
  14035. if (this.match(55)) {
  14036. const specifier = this.startNode();
  14037. this.next();
  14038. this.expectContextual(93);
  14039. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier");
  14040. return true;
  14041. }
  14042. return false;
  14043. }
  14044. parseNamedImportSpecifiers(node) {
  14045. let first = true;
  14046. this.expect(5);
  14047. while (!this.eat(8)) {
  14048. if (first) {
  14049. first = false;
  14050. } else {
  14051. if (this.eat(14)) {
  14052. throw this.raise(Errors.DestructureNamedImport, this.state.startLoc);
  14053. }
  14054. this.expect(12);
  14055. if (this.eat(8)) break;
  14056. }
  14057. const specifier = this.startNode();
  14058. const importedIsString = this.match(134);
  14059. const isMaybeTypeOnly = this.isContextual(130);
  14060. specifier.imported = this.parseModuleExportName();
  14061. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined);
  14062. node.specifiers.push(importSpecifier);
  14063. }
  14064. }
  14065. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  14066. if (this.eatContextual(93)) {
  14067. specifier.local = this.parseIdentifier();
  14068. } else {
  14069. const {
  14070. imported
  14071. } = specifier;
  14072. if (importedIsString) {
  14073. throw this.raise(Errors.ImportBindingIsString, specifier, {
  14074. importName: imported.value
  14075. });
  14076. }
  14077. this.checkReservedWord(imported.name, specifier.loc.start, true, true);
  14078. if (!specifier.local) {
  14079. specifier.local = cloneIdentifier(imported);
  14080. }
  14081. }
  14082. return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType);
  14083. }
  14084. isThisParam(param) {
  14085. return param.type === "Identifier" && param.name === "this";
  14086. }
  14087. }
  14088. class Parser extends StatementParser {
  14089. constructor(options, input, pluginsMap) {
  14090. options = getOptions(options);
  14091. super(options, input);
  14092. this.options = options;
  14093. this.initializeScopes();
  14094. this.plugins = pluginsMap;
  14095. this.filename = options.sourceFilename;
  14096. this.startIndex = options.startIndex;
  14097. let optionFlags = 0;
  14098. if (options.allowAwaitOutsideFunction) {
  14099. optionFlags |= 1;
  14100. }
  14101. if (options.allowReturnOutsideFunction) {
  14102. optionFlags |= 2;
  14103. }
  14104. if (options.allowImportExportEverywhere) {
  14105. optionFlags |= 8;
  14106. }
  14107. if (options.allowSuperOutsideMethod) {
  14108. optionFlags |= 16;
  14109. }
  14110. if (options.allowUndeclaredExports) {
  14111. optionFlags |= 64;
  14112. }
  14113. if (options.allowNewTargetOutsideFunction) {
  14114. optionFlags |= 4;
  14115. }
  14116. if (options.allowYieldOutsideFunction) {
  14117. optionFlags |= 32;
  14118. }
  14119. if (options.ranges) {
  14120. optionFlags |= 128;
  14121. }
  14122. if (options.tokens) {
  14123. optionFlags |= 256;
  14124. }
  14125. if (options.createImportExpressions) {
  14126. optionFlags |= 512;
  14127. }
  14128. if (options.createParenthesizedExpressions) {
  14129. optionFlags |= 1024;
  14130. }
  14131. if (options.errorRecovery) {
  14132. optionFlags |= 2048;
  14133. }
  14134. if (options.attachComment) {
  14135. optionFlags |= 4096;
  14136. }
  14137. if (options.annexB) {
  14138. optionFlags |= 8192;
  14139. }
  14140. this.optionFlags = optionFlags;
  14141. }
  14142. getScopeHandler() {
  14143. return ScopeHandler;
  14144. }
  14145. parse() {
  14146. this.enterInitialScopes();
  14147. const file = this.startNode();
  14148. const program = this.startNode();
  14149. this.nextToken();
  14150. file.errors = null;
  14151. this.parseTopLevel(file, program);
  14152. file.errors = this.state.errors;
  14153. file.comments.length = this.state.commentsLen;
  14154. return file;
  14155. }
  14156. }
  14157. function parse(input, options) {
  14158. var _options;
  14159. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  14160. options = Object.assign({}, options);
  14161. try {
  14162. options.sourceType = "module";
  14163. const parser = getParser(options, input);
  14164. const ast = parser.parse();
  14165. if (parser.sawUnambiguousESM) {
  14166. return ast;
  14167. }
  14168. if (parser.ambiguousScriptDifferentAst) {
  14169. try {
  14170. options.sourceType = "script";
  14171. return getParser(options, input).parse();
  14172. } catch (_unused) {}
  14173. } else {
  14174. ast.program.sourceType = "script";
  14175. }
  14176. return ast;
  14177. } catch (moduleError) {
  14178. try {
  14179. options.sourceType = "script";
  14180. return getParser(options, input).parse();
  14181. } catch (_unused2) {}
  14182. throw moduleError;
  14183. }
  14184. } else {
  14185. return getParser(options, input).parse();
  14186. }
  14187. }
  14188. function parseExpression(input, options) {
  14189. const parser = getParser(options, input);
  14190. if (parser.options.strictMode) {
  14191. parser.state.strict = true;
  14192. }
  14193. return parser.getExpression();
  14194. }
  14195. function generateExportedTokenTypes(internalTokenTypes) {
  14196. const tokenTypes = {};
  14197. for (const typeName of Object.keys(internalTokenTypes)) {
  14198. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  14199. }
  14200. return tokenTypes;
  14201. }
  14202. const tokTypes = generateExportedTokenTypes(tt);
  14203. function getParser(options, input) {
  14204. let cls = Parser;
  14205. const pluginsMap = new Map();
  14206. if (options != null && options.plugins) {
  14207. for (const plugin of options.plugins) {
  14208. let name, opts;
  14209. if (typeof plugin === "string") {
  14210. name = plugin;
  14211. } else {
  14212. [name, opts] = plugin;
  14213. }
  14214. if (!pluginsMap.has(name)) {
  14215. pluginsMap.set(name, opts || {});
  14216. }
  14217. }
  14218. validatePlugins(pluginsMap);
  14219. cls = getParserClass(pluginsMap);
  14220. }
  14221. return new cls(options, input, pluginsMap);
  14222. }
  14223. const parserClassCache = new Map();
  14224. function getParserClass(pluginsMap) {
  14225. const pluginList = [];
  14226. for (const name of mixinPluginNames) {
  14227. if (pluginsMap.has(name)) {
  14228. pluginList.push(name);
  14229. }
  14230. }
  14231. const key = pluginList.join("|");
  14232. let cls = parserClassCache.get(key);
  14233. if (!cls) {
  14234. cls = Parser;
  14235. for (const plugin of pluginList) {
  14236. cls = mixinPlugins[plugin](cls);
  14237. }
  14238. parserClassCache.set(key, cls);
  14239. }
  14240. return cls;
  14241. }
  14242. exports.parse = parse;
  14243. exports.parseExpression = parseExpression;
  14244. exports.tokTypes = tokTypes;
  14245. //# sourceMappingURL=index.js.map