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.

12195 lines
355 KiB

4 years ago
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. const beforeExpr = true;
  4. const startsExpr = true;
  5. const isLoop = true;
  6. const isAssign = true;
  7. const prefix = true;
  8. const postfix = true;
  9. class TokenType {
  10. constructor(label, conf = {}) {
  11. this.label = label;
  12. this.keyword = conf.keyword;
  13. this.beforeExpr = !!conf.beforeExpr;
  14. this.startsExpr = !!conf.startsExpr;
  15. this.rightAssociative = !!conf.rightAssociative;
  16. this.isLoop = !!conf.isLoop;
  17. this.isAssign = !!conf.isAssign;
  18. this.prefix = !!conf.prefix;
  19. this.postfix = !!conf.postfix;
  20. this.binop = conf.binop != null ? conf.binop : null;
  21. this.updateContext = null;
  22. }
  23. }
  24. const keywords = new Map();
  25. function createKeyword(name, options = {}) {
  26. options.keyword = name;
  27. const token = new TokenType(name, options);
  28. keywords.set(name, token);
  29. return token;
  30. }
  31. function createBinop(name, binop) {
  32. return new TokenType(name, {
  33. beforeExpr,
  34. binop
  35. });
  36. }
  37. const types = {
  38. num: new TokenType("num", {
  39. startsExpr
  40. }),
  41. bigint: new TokenType("bigint", {
  42. startsExpr
  43. }),
  44. regexp: new TokenType("regexp", {
  45. startsExpr
  46. }),
  47. string: new TokenType("string", {
  48. startsExpr
  49. }),
  50. name: new TokenType("name", {
  51. startsExpr
  52. }),
  53. eof: new TokenType("eof"),
  54. bracketL: new TokenType("[", {
  55. beforeExpr,
  56. startsExpr
  57. }),
  58. bracketR: new TokenType("]"),
  59. braceL: new TokenType("{", {
  60. beforeExpr,
  61. startsExpr
  62. }),
  63. braceBarL: new TokenType("{|", {
  64. beforeExpr,
  65. startsExpr
  66. }),
  67. braceR: new TokenType("}"),
  68. braceBarR: new TokenType("|}"),
  69. parenL: new TokenType("(", {
  70. beforeExpr,
  71. startsExpr
  72. }),
  73. parenR: new TokenType(")"),
  74. comma: new TokenType(",", {
  75. beforeExpr
  76. }),
  77. semi: new TokenType(";", {
  78. beforeExpr
  79. }),
  80. colon: new TokenType(":", {
  81. beforeExpr
  82. }),
  83. doubleColon: new TokenType("::", {
  84. beforeExpr
  85. }),
  86. dot: new TokenType("."),
  87. question: new TokenType("?", {
  88. beforeExpr
  89. }),
  90. questionDot: new TokenType("?."),
  91. arrow: new TokenType("=>", {
  92. beforeExpr
  93. }),
  94. template: new TokenType("template"),
  95. ellipsis: new TokenType("...", {
  96. beforeExpr
  97. }),
  98. backQuote: new TokenType("`", {
  99. startsExpr
  100. }),
  101. dollarBraceL: new TokenType("${", {
  102. beforeExpr,
  103. startsExpr
  104. }),
  105. at: new TokenType("@"),
  106. hash: new TokenType("#", {
  107. startsExpr
  108. }),
  109. interpreterDirective: new TokenType("#!..."),
  110. eq: new TokenType("=", {
  111. beforeExpr,
  112. isAssign
  113. }),
  114. assign: new TokenType("_=", {
  115. beforeExpr,
  116. isAssign
  117. }),
  118. incDec: new TokenType("++/--", {
  119. prefix,
  120. postfix,
  121. startsExpr
  122. }),
  123. bang: new TokenType("!", {
  124. beforeExpr,
  125. prefix,
  126. startsExpr
  127. }),
  128. tilde: new TokenType("~", {
  129. beforeExpr,
  130. prefix,
  131. startsExpr
  132. }),
  133. pipeline: createBinop("|>", 0),
  134. nullishCoalescing: createBinop("??", 1),
  135. logicalOR: createBinop("||", 2),
  136. logicalAND: createBinop("&&", 3),
  137. bitwiseOR: createBinop("|", 4),
  138. bitwiseXOR: createBinop("^", 5),
  139. bitwiseAND: createBinop("&", 6),
  140. equality: createBinop("==/!=/===/!==", 7),
  141. relational: createBinop("</>/<=/>=", 8),
  142. bitShift: createBinop("<</>>/>>>", 9),
  143. plusMin: new TokenType("+/-", {
  144. beforeExpr,
  145. binop: 10,
  146. prefix,
  147. startsExpr
  148. }),
  149. modulo: new TokenType("%", {
  150. beforeExpr,
  151. binop: 11,
  152. startsExpr
  153. }),
  154. star: createBinop("*", 11),
  155. slash: createBinop("/", 11),
  156. exponent: new TokenType("**", {
  157. beforeExpr,
  158. binop: 12,
  159. rightAssociative: true
  160. }),
  161. _break: createKeyword("break"),
  162. _case: createKeyword("case", {
  163. beforeExpr
  164. }),
  165. _catch: createKeyword("catch"),
  166. _continue: createKeyword("continue"),
  167. _debugger: createKeyword("debugger"),
  168. _default: createKeyword("default", {
  169. beforeExpr
  170. }),
  171. _do: createKeyword("do", {
  172. isLoop,
  173. beforeExpr
  174. }),
  175. _else: createKeyword("else", {
  176. beforeExpr
  177. }),
  178. _finally: createKeyword("finally"),
  179. _for: createKeyword("for", {
  180. isLoop
  181. }),
  182. _function: createKeyword("function", {
  183. startsExpr
  184. }),
  185. _if: createKeyword("if"),
  186. _return: createKeyword("return", {
  187. beforeExpr
  188. }),
  189. _switch: createKeyword("switch"),
  190. _throw: createKeyword("throw", {
  191. beforeExpr,
  192. prefix,
  193. startsExpr
  194. }),
  195. _try: createKeyword("try"),
  196. _var: createKeyword("var"),
  197. _const: createKeyword("const"),
  198. _while: createKeyword("while", {
  199. isLoop
  200. }),
  201. _with: createKeyword("with"),
  202. _new: createKeyword("new", {
  203. beforeExpr,
  204. startsExpr
  205. }),
  206. _this: createKeyword("this", {
  207. startsExpr
  208. }),
  209. _super: createKeyword("super", {
  210. startsExpr
  211. }),
  212. _class: createKeyword("class", {
  213. startsExpr
  214. }),
  215. _extends: createKeyword("extends", {
  216. beforeExpr
  217. }),
  218. _export: createKeyword("export"),
  219. _import: createKeyword("import", {
  220. startsExpr
  221. }),
  222. _null: createKeyword("null", {
  223. startsExpr
  224. }),
  225. _true: createKeyword("true", {
  226. startsExpr
  227. }),
  228. _false: createKeyword("false", {
  229. startsExpr
  230. }),
  231. _in: createKeyword("in", {
  232. beforeExpr,
  233. binop: 8
  234. }),
  235. _instanceof: createKeyword("instanceof", {
  236. beforeExpr,
  237. binop: 8
  238. }),
  239. _typeof: createKeyword("typeof", {
  240. beforeExpr,
  241. prefix,
  242. startsExpr
  243. }),
  244. _void: createKeyword("void", {
  245. beforeExpr,
  246. prefix,
  247. startsExpr
  248. }),
  249. _delete: createKeyword("delete", {
  250. beforeExpr,
  251. prefix,
  252. startsExpr
  253. })
  254. };
  255. const SCOPE_OTHER = 0b0000000000,
  256. SCOPE_PROGRAM = 0b0000000001,
  257. SCOPE_FUNCTION = 0b0000000010,
  258. SCOPE_ASYNC = 0b0000000100,
  259. SCOPE_GENERATOR = 0b0000001000,
  260. SCOPE_ARROW = 0b0000010000,
  261. SCOPE_SIMPLE_CATCH = 0b0000100000,
  262. SCOPE_SUPER = 0b0001000000,
  263. SCOPE_DIRECT_SUPER = 0b0010000000,
  264. SCOPE_CLASS = 0b0100000000,
  265. SCOPE_TS_MODULE = 0b1000000000,
  266. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  267. function functionFlags(isAsync, isGenerator) {
  268. return SCOPE_FUNCTION | (isAsync ? SCOPE_ASYNC : 0) | (isGenerator ? SCOPE_GENERATOR : 0);
  269. }
  270. const BIND_KIND_VALUE = 0b00000000001,
  271. BIND_KIND_TYPE = 0b00000000010,
  272. BIND_SCOPE_VAR = 0b00000000100,
  273. BIND_SCOPE_LEXICAL = 0b00000001000,
  274. BIND_SCOPE_FUNCTION = 0b00000010000,
  275. BIND_FLAGS_NONE = 0b00001000000,
  276. BIND_FLAGS_CLASS = 0b00010000000,
  277. BIND_FLAGS_TS_ENUM = 0b00100000000,
  278. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  279. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  280. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  281. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  282. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  283. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  284. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  285. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  286. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  287. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  288. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  289. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  290. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  291. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  292. function isSimpleProperty(node) {
  293. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  294. }
  295. var estree = (superClass => class extends superClass {
  296. estreeParseRegExpLiteral({
  297. pattern,
  298. flags
  299. }) {
  300. let regex = null;
  301. try {
  302. regex = new RegExp(pattern, flags);
  303. } catch (e) {}
  304. const node = this.estreeParseLiteral(regex);
  305. node.regex = {
  306. pattern,
  307. flags
  308. };
  309. return node;
  310. }
  311. estreeParseLiteral(value) {
  312. return this.parseLiteral(value, "Literal");
  313. }
  314. directiveToStmt(directive) {
  315. const directiveLiteral = directive.value;
  316. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  317. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  318. expression.value = directiveLiteral.value;
  319. expression.raw = directiveLiteral.extra.raw;
  320. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  321. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  322. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  323. }
  324. initFunction(node, isAsync) {
  325. super.initFunction(node, isAsync);
  326. node.expression = false;
  327. }
  328. checkDeclaration(node) {
  329. if (isSimpleProperty(node)) {
  330. this.checkDeclaration(node.value);
  331. } else {
  332. super.checkDeclaration(node);
  333. }
  334. }
  335. checkGetterSetterParams(method) {
  336. const prop = method;
  337. const paramCount = prop.kind === "get" ? 0 : 1;
  338. const start = prop.start;
  339. if (prop.value.params.length !== paramCount) {
  340. if (prop.kind === "get") {
  341. this.raise(start, "getter must not have any formal parameters");
  342. } else {
  343. this.raise(start, "setter must have exactly one formal parameter");
  344. }
  345. } else if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
  346. this.raise(start, "setter function argument must not be a rest parameter");
  347. }
  348. }
  349. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding) {
  350. switch (expr.type) {
  351. case "ObjectPattern":
  352. expr.properties.forEach(prop => {
  353. this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  354. });
  355. break;
  356. default:
  357. super.checkLVal(expr, bindingType, checkClashes, contextDescription, disallowLetBinding);
  358. }
  359. }
  360. checkDuplicatedProto(prop, protoRef) {
  361. if (prop.type === "SpreadElement" || prop.computed || prop.method || prop.shorthand) {
  362. return;
  363. }
  364. const key = prop.key;
  365. const name = key.type === "Identifier" ? key.name : String(key.value);
  366. if (name === "__proto__" && prop.kind === "init") {
  367. if (protoRef.used && !protoRef.start) {
  368. protoRef.start = key.start;
  369. }
  370. protoRef.used = true;
  371. }
  372. }
  373. isStrictBody(node) {
  374. const isBlockStatement = node.body.type === "BlockStatement";
  375. if (isBlockStatement && node.body.body.length > 0) {
  376. for (let _i = 0, _node$body$body = node.body.body; _i < _node$body$body.length; _i++) {
  377. const directive = _node$body$body[_i];
  378. if (directive.type === "ExpressionStatement" && directive.expression.type === "Literal") {
  379. if (directive.expression.value === "use strict") return true;
  380. } else {
  381. break;
  382. }
  383. }
  384. }
  385. return false;
  386. }
  387. isValidDirective(stmt) {
  388. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized);
  389. }
  390. stmtToDirective(stmt) {
  391. const directive = super.stmtToDirective(stmt);
  392. const value = stmt.expression.value;
  393. directive.value.value = value;
  394. return directive;
  395. }
  396. parseBlockBody(node, allowDirectives, topLevel, end) {
  397. super.parseBlockBody(node, allowDirectives, topLevel, end);
  398. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  399. node.body = directiveStatements.concat(node.body);
  400. delete node.directives;
  401. }
  402. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  403. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  404. if (method.typeParameters) {
  405. method.value.typeParameters = method.typeParameters;
  406. delete method.typeParameters;
  407. }
  408. classBody.body.push(method);
  409. }
  410. parseExprAtom(refShorthandDefaultPos) {
  411. switch (this.state.type) {
  412. case types.regexp:
  413. return this.estreeParseRegExpLiteral(this.state.value);
  414. case types.num:
  415. case types.string:
  416. return this.estreeParseLiteral(this.state.value);
  417. case types._null:
  418. return this.estreeParseLiteral(null);
  419. case types._true:
  420. return this.estreeParseLiteral(true);
  421. case types._false:
  422. return this.estreeParseLiteral(false);
  423. default:
  424. return super.parseExprAtom(refShorthandDefaultPos);
  425. }
  426. }
  427. parseLiteral(value, type, startPos, startLoc) {
  428. const node = super.parseLiteral(value, type, startPos, startLoc);
  429. node.raw = node.extra.raw;
  430. delete node.extra;
  431. return node;
  432. }
  433. parseFunctionBody(node, allowExpression, isMethod = false) {
  434. super.parseFunctionBody(node, allowExpression, isMethod);
  435. node.expression = node.body.type !== "BlockStatement";
  436. }
  437. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  438. let funcNode = this.startNode();
  439. funcNode.kind = node.kind;
  440. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  441. funcNode.type = "FunctionExpression";
  442. delete funcNode.kind;
  443. node.value = funcNode;
  444. type = type === "ClassMethod" ? "MethodDefinition" : type;
  445. return this.finishNode(node, type);
  446. }
  447. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  448. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc);
  449. if (node) {
  450. node.type = "Property";
  451. if (node.kind === "method") node.kind = "init";
  452. node.shorthand = false;
  453. }
  454. return node;
  455. }
  456. parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos) {
  457. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos);
  458. if (node) {
  459. node.kind = "init";
  460. node.type = "Property";
  461. }
  462. return node;
  463. }
  464. toAssignable(node, isBinding, contextDescription) {
  465. if (isSimpleProperty(node)) {
  466. this.toAssignable(node.value, isBinding, contextDescription);
  467. return node;
  468. }
  469. return super.toAssignable(node, isBinding, contextDescription);
  470. }
  471. toAssignableObjectExpressionProp(prop, isBinding, isLast) {
  472. if (prop.kind === "get" || prop.kind === "set") {
  473. throw this.raise(prop.key.start, "Object pattern can't contain getter or setter");
  474. } else if (prop.method) {
  475. throw this.raise(prop.key.start, "Object pattern can't contain methods");
  476. } else {
  477. super.toAssignableObjectExpressionProp(prop, isBinding, isLast);
  478. }
  479. }
  480. });
  481. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  482. const lineBreakG = new RegExp(lineBreak.source, "g");
  483. function isNewLine(code) {
  484. switch (code) {
  485. case 10:
  486. case 13:
  487. case 8232:
  488. case 8233:
  489. return true;
  490. default:
  491. return false;
  492. }
  493. }
  494. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  495. function isWhitespace(code) {
  496. switch (code) {
  497. case 0x0009:
  498. case 0x000b:
  499. case 0x000c:
  500. case 32:
  501. case 160:
  502. case 5760:
  503. case 0x2000:
  504. case 0x2001:
  505. case 0x2002:
  506. case 0x2003:
  507. case 0x2004:
  508. case 0x2005:
  509. case 0x2006:
  510. case 0x2007:
  511. case 0x2008:
  512. case 0x2009:
  513. case 0x200a:
  514. case 0x202f:
  515. case 0x205f:
  516. case 0x3000:
  517. case 0xfeff:
  518. return true;
  519. default:
  520. return false;
  521. }
  522. }
  523. class TokContext {
  524. constructor(token, isExpr, preserveSpace, override) {
  525. this.token = token;
  526. this.isExpr = !!isExpr;
  527. this.preserveSpace = !!preserveSpace;
  528. this.override = override;
  529. }
  530. }
  531. const types$1 = {
  532. braceStatement: new TokContext("{", false),
  533. braceExpression: new TokContext("{", true),
  534. templateQuasi: new TokContext("${", false),
  535. parenStatement: new TokContext("(", false),
  536. parenExpression: new TokContext("(", true),
  537. template: new TokContext("`", true, true, p => p.readTmplToken()),
  538. functionExpression: new TokContext("function", true),
  539. functionStatement: new TokContext("function", false)
  540. };
  541. types.parenR.updateContext = types.braceR.updateContext = function () {
  542. if (this.state.context.length === 1) {
  543. this.state.exprAllowed = true;
  544. return;
  545. }
  546. let out = this.state.context.pop();
  547. if (out === types$1.braceStatement && this.curContext().token === "function") {
  548. out = this.state.context.pop();
  549. }
  550. this.state.exprAllowed = !out.isExpr;
  551. };
  552. types.name.updateContext = function (prevType) {
  553. let allowed = false;
  554. if (prevType !== types.dot) {
  555. if (this.state.value === "of" && !this.state.exprAllowed || this.state.value === "yield" && this.scope.inGenerator) {
  556. allowed = true;
  557. }
  558. }
  559. this.state.exprAllowed = allowed;
  560. if (this.state.isIterator) {
  561. this.state.isIterator = false;
  562. }
  563. };
  564. types.braceL.updateContext = function (prevType) {
  565. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  566. this.state.exprAllowed = true;
  567. };
  568. types.dollarBraceL.updateContext = function () {
  569. this.state.context.push(types$1.templateQuasi);
  570. this.state.exprAllowed = true;
  571. };
  572. types.parenL.updateContext = function (prevType) {
  573. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  574. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  575. this.state.exprAllowed = true;
  576. };
  577. types.incDec.updateContext = function () {};
  578. types._function.updateContext = types._class.updateContext = function (prevType) {
  579. if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
  580. this.state.context.push(types$1.functionExpression);
  581. } else {
  582. this.state.context.push(types$1.functionStatement);
  583. }
  584. this.state.exprAllowed = false;
  585. };
  586. types.backQuote.updateContext = function () {
  587. if (this.curContext() === types$1.template) {
  588. this.state.context.pop();
  589. } else {
  590. this.state.context.push(types$1.template);
  591. }
  592. this.state.exprAllowed = false;
  593. };
  594. const reservedWords = {
  595. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  596. strictBind: ["eval", "arguments"]
  597. };
  598. const reservedWordsStrictSet = new Set(reservedWords.strict);
  599. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  600. const isReservedWord = (word, inModule) => {
  601. return inModule && word === "await" || word === "enum";
  602. };
  603. function isStrictReservedWord(word, inModule) {
  604. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  605. }
  606. function isStrictBindOnlyReservedWord(word) {
  607. return reservedWordsStrictBindSet.has(word);
  608. }
  609. function isStrictBindReservedWord(word, inModule) {
  610. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  611. }
  612. function isKeyword(word) {
  613. return keywords.has(word);
  614. }
  615. const keywordRelationalOperator = /^in(stanceof)?$/;
  616. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\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-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\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-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7c6\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab67\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-
  617. let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  618. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  619. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  620. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  621. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 477, 28, 11, 0, 9, 21, 155, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 12, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 0, 33, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 0, 161, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 270, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 754, 9486, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 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, 42710, 42, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541];
  622. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 525, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 232, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 792487, 239];
  623. function isInAstralSet(code, set) {
  624. let pos = 0x10000;
  625. for (let i = 0, length = set.length; i < length; i += 2) {
  626. pos += set[i];
  627. if (pos > code) return false;
  628. pos += set[i + 1];
  629. if (pos >= code) return true;
  630. }
  631. return false;
  632. }
  633. function isIdentifierStart(code) {
  634. if (code < 65) return code === 36;
  635. if (code <= 90) return true;
  636. if (code < 97) return code === 95;
  637. if (code <= 122) return true;
  638. if (code <= 0xffff) {
  639. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  640. }
  641. return isInAstralSet(code, astralIdentifierStartCodes);
  642. }
  643. function isIteratorStart(current, next) {
  644. return current === 64 && next === 64;
  645. }
  646. function isIdentifierChar(code) {
  647. if (code < 48) return code === 36;
  648. if (code < 58) return true;
  649. if (code < 65) return false;
  650. if (code <= 90) return true;
  651. if (code < 97) return code === 95;
  652. if (code <= 122) return true;
  653. if (code <= 0xffff) {
  654. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  655. }
  656. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  657. }
  658. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  659. function isEsModuleType(bodyElement) {
  660. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  661. }
  662. function hasTypeImportKind(node) {
  663. return node.importKind === "type" || node.importKind === "typeof";
  664. }
  665. function isMaybeDefaultImport(state) {
  666. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  667. }
  668. const exportSuggestions = {
  669. const: "declare export var",
  670. let: "declare export var",
  671. type: "export type",
  672. interface: "export interface"
  673. };
  674. function partition(list, test) {
  675. const list1 = [];
  676. const list2 = [];
  677. for (let i = 0; i < list.length; i++) {
  678. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  679. }
  680. return [list1, list2];
  681. }
  682. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  683. var flow = (superClass => class extends superClass {
  684. constructor(options, input) {
  685. super(options, input);
  686. this.flowPragma = undefined;
  687. }
  688. shouldParseTypes() {
  689. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  690. }
  691. shouldParseEnums() {
  692. return !!this.getPluginOption("flow", "enums");
  693. }
  694. finishToken(type, val) {
  695. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  696. if (this.flowPragma === undefined) {
  697. this.flowPragma = null;
  698. }
  699. }
  700. return super.finishToken(type, val);
  701. }
  702. addComment(comment) {
  703. if (this.flowPragma === undefined) {
  704. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  705. if (!matches) ; else if (matches[1] === "flow") {
  706. this.flowPragma = "flow";
  707. } else if (matches[1] === "noflow") {
  708. this.flowPragma = "noflow";
  709. } else {
  710. throw new Error("Unexpected flow pragma");
  711. }
  712. }
  713. return super.addComment(comment);
  714. }
  715. flowParseTypeInitialiser(tok) {
  716. const oldInType = this.state.inType;
  717. this.state.inType = true;
  718. this.expect(tok || types.colon);
  719. const type = this.flowParseType();
  720. this.state.inType = oldInType;
  721. return type;
  722. }
  723. flowParsePredicate() {
  724. const node = this.startNode();
  725. const moduloLoc = this.state.startLoc;
  726. const moduloPos = this.state.start;
  727. this.expect(types.modulo);
  728. const checksLoc = this.state.startLoc;
  729. this.expectContextual("checks");
  730. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  731. this.raise(moduloPos, "Spaces between ´%´ and ´checks´ are not allowed here.");
  732. }
  733. if (this.eat(types.parenL)) {
  734. node.value = this.parseExpression();
  735. this.expect(types.parenR);
  736. return this.finishNode(node, "DeclaredPredicate");
  737. } else {
  738. return this.finishNode(node, "InferredPredicate");
  739. }
  740. }
  741. flowParseTypeAndPredicateInitialiser() {
  742. const oldInType = this.state.inType;
  743. this.state.inType = true;
  744. this.expect(types.colon);
  745. let type = null;
  746. let predicate = null;
  747. if (this.match(types.modulo)) {
  748. this.state.inType = oldInType;
  749. predicate = this.flowParsePredicate();
  750. } else {
  751. type = this.flowParseType();
  752. this.state.inType = oldInType;
  753. if (this.match(types.modulo)) {
  754. predicate = this.flowParsePredicate();
  755. }
  756. }
  757. return [type, predicate];
  758. }
  759. flowParseDeclareClass(node) {
  760. this.next();
  761. this.flowParseInterfaceish(node, true);
  762. return this.finishNode(node, "DeclareClass");
  763. }
  764. flowParseDeclareFunction(node) {
  765. this.next();
  766. const id = node.id = this.parseIdentifier();
  767. const typeNode = this.startNode();
  768. const typeContainer = this.startNode();
  769. if (this.isRelational("<")) {
  770. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  771. } else {
  772. typeNode.typeParameters = null;
  773. }
  774. this.expect(types.parenL);
  775. const tmp = this.flowParseFunctionTypeParams();
  776. typeNode.params = tmp.params;
  777. typeNode.rest = tmp.rest;
  778. this.expect(types.parenR);
  779. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  780. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  781. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  782. this.resetEndLocation(id);
  783. this.semicolon();
  784. return this.finishNode(node, "DeclareFunction");
  785. }
  786. flowParseDeclare(node, insideModule) {
  787. if (this.match(types._class)) {
  788. return this.flowParseDeclareClass(node);
  789. } else if (this.match(types._function)) {
  790. return this.flowParseDeclareFunction(node);
  791. } else if (this.match(types._var)) {
  792. return this.flowParseDeclareVariable(node);
  793. } else if (this.eatContextual("module")) {
  794. if (this.match(types.dot)) {
  795. return this.flowParseDeclareModuleExports(node);
  796. } else {
  797. if (insideModule) {
  798. this.raise(this.state.lastTokStart, "`declare module` cannot be used inside another `declare module`");
  799. }
  800. return this.flowParseDeclareModule(node);
  801. }
  802. } else if (this.isContextual("type")) {
  803. return this.flowParseDeclareTypeAlias(node);
  804. } else if (this.isContextual("opaque")) {
  805. return this.flowParseDeclareOpaqueType(node);
  806. } else if (this.isContextual("interface")) {
  807. return this.flowParseDeclareInterface(node);
  808. } else if (this.match(types._export)) {
  809. return this.flowParseDeclareExportDeclaration(node, insideModule);
  810. } else {
  811. throw this.unexpected();
  812. }
  813. }
  814. flowParseDeclareVariable(node) {
  815. this.next();
  816. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  817. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  818. this.semicolon();
  819. return this.finishNode(node, "DeclareVariable");
  820. }
  821. flowParseDeclareModule(node) {
  822. this.scope.enter(SCOPE_OTHER);
  823. if (this.match(types.string)) {
  824. node.id = this.parseExprAtom();
  825. } else {
  826. node.id = this.parseIdentifier();
  827. }
  828. const bodyNode = node.body = this.startNode();
  829. const body = bodyNode.body = [];
  830. this.expect(types.braceL);
  831. while (!this.match(types.braceR)) {
  832. let bodyNode = this.startNode();
  833. if (this.match(types._import)) {
  834. this.next();
  835. if (!this.isContextual("type") && !this.match(types._typeof)) {
  836. this.raise(this.state.lastTokStart, "Imports within a `declare module` body must always be `import type` or `import typeof`");
  837. }
  838. this.parseImport(bodyNode);
  839. } else {
  840. this.expectContextual("declare", "Only declares and type imports are allowed inside declare module");
  841. bodyNode = this.flowParseDeclare(bodyNode, true);
  842. }
  843. body.push(bodyNode);
  844. }
  845. this.scope.exit();
  846. this.expect(types.braceR);
  847. this.finishNode(bodyNode, "BlockStatement");
  848. let kind = null;
  849. let hasModuleExport = false;
  850. const errorMessage = "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";
  851. body.forEach(bodyElement => {
  852. if (isEsModuleType(bodyElement)) {
  853. if (kind === "CommonJS") {
  854. this.raise(bodyElement.start, errorMessage);
  855. }
  856. kind = "ES";
  857. } else if (bodyElement.type === "DeclareModuleExports") {
  858. if (hasModuleExport) {
  859. this.raise(bodyElement.start, "Duplicate `declare module.exports` statement");
  860. }
  861. if (kind === "ES") this.raise(bodyElement.start, errorMessage);
  862. kind = "CommonJS";
  863. hasModuleExport = true;
  864. }
  865. });
  866. node.kind = kind || "CommonJS";
  867. return this.finishNode(node, "DeclareModule");
  868. }
  869. flowParseDeclareExportDeclaration(node, insideModule) {
  870. this.expect(types._export);
  871. if (this.eat(types._default)) {
  872. if (this.match(types._function) || this.match(types._class)) {
  873. node.declaration = this.flowParseDeclare(this.startNode());
  874. } else {
  875. node.declaration = this.flowParseType();
  876. this.semicolon();
  877. }
  878. node.default = true;
  879. return this.finishNode(node, "DeclareExportDeclaration");
  880. } else {
  881. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  882. const label = this.state.value;
  883. const suggestion = exportSuggestions[label];
  884. this.unexpected(this.state.start, `\`declare export ${label}\` is not supported. Use \`${suggestion}\` instead`);
  885. }
  886. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  887. node.declaration = this.flowParseDeclare(this.startNode());
  888. node.default = false;
  889. return this.finishNode(node, "DeclareExportDeclaration");
  890. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  891. node = this.parseExport(node);
  892. if (node.type === "ExportNamedDeclaration") {
  893. node.type = "ExportDeclaration";
  894. node.default = false;
  895. delete node.exportKind;
  896. }
  897. node.type = "Declare" + node.type;
  898. return node;
  899. }
  900. }
  901. throw this.unexpected();
  902. }
  903. flowParseDeclareModuleExports(node) {
  904. this.next();
  905. this.expectContextual("exports");
  906. node.typeAnnotation = this.flowParseTypeAnnotation();
  907. this.semicolon();
  908. return this.finishNode(node, "DeclareModuleExports");
  909. }
  910. flowParseDeclareTypeAlias(node) {
  911. this.next();
  912. this.flowParseTypeAlias(node);
  913. node.type = "DeclareTypeAlias";
  914. return node;
  915. }
  916. flowParseDeclareOpaqueType(node) {
  917. this.next();
  918. this.flowParseOpaqueType(node, true);
  919. node.type = "DeclareOpaqueType";
  920. return node;
  921. }
  922. flowParseDeclareInterface(node) {
  923. this.next();
  924. this.flowParseInterfaceish(node);
  925. return this.finishNode(node, "DeclareInterface");
  926. }
  927. flowParseInterfaceish(node, isClass = false) {
  928. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  929. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  930. if (this.isRelational("<")) {
  931. node.typeParameters = this.flowParseTypeParameterDeclaration();
  932. } else {
  933. node.typeParameters = null;
  934. }
  935. node.extends = [];
  936. node.implements = [];
  937. node.mixins = [];
  938. if (this.eat(types._extends)) {
  939. do {
  940. node.extends.push(this.flowParseInterfaceExtends());
  941. } while (!isClass && this.eat(types.comma));
  942. }
  943. if (this.isContextual("mixins")) {
  944. this.next();
  945. do {
  946. node.mixins.push(this.flowParseInterfaceExtends());
  947. } while (this.eat(types.comma));
  948. }
  949. if (this.isContextual("implements")) {
  950. this.next();
  951. do {
  952. node.implements.push(this.flowParseInterfaceExtends());
  953. } while (this.eat(types.comma));
  954. }
  955. node.body = this.flowParseObjectType({
  956. allowStatic: isClass,
  957. allowExact: false,
  958. allowSpread: false,
  959. allowProto: isClass,
  960. allowInexact: false
  961. });
  962. }
  963. flowParseInterfaceExtends() {
  964. const node = this.startNode();
  965. node.id = this.flowParseQualifiedTypeIdentifier();
  966. if (this.isRelational("<")) {
  967. node.typeParameters = this.flowParseTypeParameterInstantiation();
  968. } else {
  969. node.typeParameters = null;
  970. }
  971. return this.finishNode(node, "InterfaceExtends");
  972. }
  973. flowParseInterface(node) {
  974. this.flowParseInterfaceish(node);
  975. return this.finishNode(node, "InterfaceDeclaration");
  976. }
  977. checkNotUnderscore(word) {
  978. if (word === "_") {
  979. this.raise(this.state.start, "`_` is only allowed as a type argument to call or new");
  980. }
  981. }
  982. checkReservedType(word, startLoc, declaration) {
  983. if (!reservedTypes.has(word)) return;
  984. if (declaration) {
  985. this.raise(startLoc, `Cannot overwrite reserved type ${word}`);
  986. return;
  987. }
  988. this.raise(startLoc, `Unexpected reserved type ${word}`);
  989. }
  990. flowParseRestrictedIdentifier(liberal, declaration) {
  991. this.checkReservedType(this.state.value, this.state.start, declaration);
  992. return this.parseIdentifier(liberal);
  993. }
  994. flowParseTypeAlias(node) {
  995. node.id = this.flowParseRestrictedIdentifier(false, true);
  996. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  997. if (this.isRelational("<")) {
  998. node.typeParameters = this.flowParseTypeParameterDeclaration();
  999. } else {
  1000. node.typeParameters = null;
  1001. }
  1002. node.right = this.flowParseTypeInitialiser(types.eq);
  1003. this.semicolon();
  1004. return this.finishNode(node, "TypeAlias");
  1005. }
  1006. flowParseOpaqueType(node, declare) {
  1007. this.expectContextual("type");
  1008. node.id = this.flowParseRestrictedIdentifier(true, true);
  1009. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1010. if (this.isRelational("<")) {
  1011. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1012. } else {
  1013. node.typeParameters = null;
  1014. }
  1015. node.supertype = null;
  1016. if (this.match(types.colon)) {
  1017. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1018. }
  1019. node.impltype = null;
  1020. if (!declare) {
  1021. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1022. }
  1023. this.semicolon();
  1024. return this.finishNode(node, "OpaqueType");
  1025. }
  1026. flowParseTypeParameter(requireDefault = false) {
  1027. const nodeStart = this.state.start;
  1028. const node = this.startNode();
  1029. const variance = this.flowParseVariance();
  1030. const ident = this.flowParseTypeAnnotatableIdentifier();
  1031. node.name = ident.name;
  1032. node.variance = variance;
  1033. node.bound = ident.typeAnnotation;
  1034. if (this.match(types.eq)) {
  1035. this.eat(types.eq);
  1036. node.default = this.flowParseType();
  1037. } else {
  1038. if (requireDefault) {
  1039. this.raise(nodeStart, "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.");
  1040. }
  1041. }
  1042. return this.finishNode(node, "TypeParameter");
  1043. }
  1044. flowParseTypeParameterDeclaration() {
  1045. const oldInType = this.state.inType;
  1046. const node = this.startNode();
  1047. node.params = [];
  1048. this.state.inType = true;
  1049. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1050. this.next();
  1051. } else {
  1052. this.unexpected();
  1053. }
  1054. let defaultRequired = false;
  1055. do {
  1056. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1057. node.params.push(typeParameter);
  1058. if (typeParameter.default) {
  1059. defaultRequired = true;
  1060. }
  1061. if (!this.isRelational(">")) {
  1062. this.expect(types.comma);
  1063. }
  1064. } while (!this.isRelational(">"));
  1065. this.expectRelational(">");
  1066. this.state.inType = oldInType;
  1067. return this.finishNode(node, "TypeParameterDeclaration");
  1068. }
  1069. flowParseTypeParameterInstantiation() {
  1070. const node = this.startNode();
  1071. const oldInType = this.state.inType;
  1072. node.params = [];
  1073. this.state.inType = true;
  1074. this.expectRelational("<");
  1075. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1076. this.state.noAnonFunctionType = false;
  1077. while (!this.isRelational(">")) {
  1078. node.params.push(this.flowParseType());
  1079. if (!this.isRelational(">")) {
  1080. this.expect(types.comma);
  1081. }
  1082. }
  1083. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1084. this.expectRelational(">");
  1085. this.state.inType = oldInType;
  1086. return this.finishNode(node, "TypeParameterInstantiation");
  1087. }
  1088. flowParseTypeParameterInstantiationCallOrNew() {
  1089. const node = this.startNode();
  1090. const oldInType = this.state.inType;
  1091. node.params = [];
  1092. this.state.inType = true;
  1093. this.expectRelational("<");
  1094. while (!this.isRelational(">")) {
  1095. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1096. if (!this.isRelational(">")) {
  1097. this.expect(types.comma);
  1098. }
  1099. }
  1100. this.expectRelational(">");
  1101. this.state.inType = oldInType;
  1102. return this.finishNode(node, "TypeParameterInstantiation");
  1103. }
  1104. flowParseInterfaceType() {
  1105. const node = this.startNode();
  1106. this.expectContextual("interface");
  1107. node.extends = [];
  1108. if (this.eat(types._extends)) {
  1109. do {
  1110. node.extends.push(this.flowParseInterfaceExtends());
  1111. } while (this.eat(types.comma));
  1112. }
  1113. node.body = this.flowParseObjectType({
  1114. allowStatic: false,
  1115. allowExact: false,
  1116. allowSpread: false,
  1117. allowProto: false,
  1118. allowInexact: false
  1119. });
  1120. return this.finishNode(node, "InterfaceTypeAnnotation");
  1121. }
  1122. flowParseObjectPropertyKey() {
  1123. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1124. }
  1125. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1126. node.static = isStatic;
  1127. if (this.lookahead().type === types.colon) {
  1128. node.id = this.flowParseObjectPropertyKey();
  1129. node.key = this.flowParseTypeInitialiser();
  1130. } else {
  1131. node.id = null;
  1132. node.key = this.flowParseType();
  1133. }
  1134. this.expect(types.bracketR);
  1135. node.value = this.flowParseTypeInitialiser();
  1136. node.variance = variance;
  1137. return this.finishNode(node, "ObjectTypeIndexer");
  1138. }
  1139. flowParseObjectTypeInternalSlot(node, isStatic) {
  1140. node.static = isStatic;
  1141. node.id = this.flowParseObjectPropertyKey();
  1142. this.expect(types.bracketR);
  1143. this.expect(types.bracketR);
  1144. if (this.isRelational("<") || this.match(types.parenL)) {
  1145. node.method = true;
  1146. node.optional = false;
  1147. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1148. } else {
  1149. node.method = false;
  1150. if (this.eat(types.question)) {
  1151. node.optional = true;
  1152. }
  1153. node.value = this.flowParseTypeInitialiser();
  1154. }
  1155. return this.finishNode(node, "ObjectTypeInternalSlot");
  1156. }
  1157. flowParseObjectTypeMethodish(node) {
  1158. node.params = [];
  1159. node.rest = null;
  1160. node.typeParameters = null;
  1161. if (this.isRelational("<")) {
  1162. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1163. }
  1164. this.expect(types.parenL);
  1165. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1166. node.params.push(this.flowParseFunctionTypeParam());
  1167. if (!this.match(types.parenR)) {
  1168. this.expect(types.comma);
  1169. }
  1170. }
  1171. if (this.eat(types.ellipsis)) {
  1172. node.rest = this.flowParseFunctionTypeParam();
  1173. }
  1174. this.expect(types.parenR);
  1175. node.returnType = this.flowParseTypeInitialiser();
  1176. return this.finishNode(node, "FunctionTypeAnnotation");
  1177. }
  1178. flowParseObjectTypeCallProperty(node, isStatic) {
  1179. const valueNode = this.startNode();
  1180. node.static = isStatic;
  1181. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1182. return this.finishNode(node, "ObjectTypeCallProperty");
  1183. }
  1184. flowParseObjectType({
  1185. allowStatic,
  1186. allowExact,
  1187. allowSpread,
  1188. allowProto,
  1189. allowInexact
  1190. }) {
  1191. const oldInType = this.state.inType;
  1192. this.state.inType = true;
  1193. const nodeStart = this.startNode();
  1194. nodeStart.callProperties = [];
  1195. nodeStart.properties = [];
  1196. nodeStart.indexers = [];
  1197. nodeStart.internalSlots = [];
  1198. let endDelim;
  1199. let exact;
  1200. let inexact = false;
  1201. if (allowExact && this.match(types.braceBarL)) {
  1202. this.expect(types.braceBarL);
  1203. endDelim = types.braceBarR;
  1204. exact = true;
  1205. } else {
  1206. this.expect(types.braceL);
  1207. endDelim = types.braceR;
  1208. exact = false;
  1209. }
  1210. nodeStart.exact = exact;
  1211. while (!this.match(endDelim)) {
  1212. let isStatic = false;
  1213. let protoStart = null;
  1214. let inexactStart = null;
  1215. const node = this.startNode();
  1216. if (allowProto && this.isContextual("proto")) {
  1217. const lookahead = this.lookahead();
  1218. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1219. this.next();
  1220. protoStart = this.state.start;
  1221. allowStatic = false;
  1222. }
  1223. }
  1224. if (allowStatic && this.isContextual("static")) {
  1225. const lookahead = this.lookahead();
  1226. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1227. this.next();
  1228. isStatic = true;
  1229. }
  1230. }
  1231. const variance = this.flowParseVariance();
  1232. if (this.eat(types.bracketL)) {
  1233. if (protoStart != null) {
  1234. this.unexpected(protoStart);
  1235. }
  1236. if (this.eat(types.bracketL)) {
  1237. if (variance) {
  1238. this.unexpected(variance.start);
  1239. }
  1240. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1241. } else {
  1242. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1243. }
  1244. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1245. if (protoStart != null) {
  1246. this.unexpected(protoStart);
  1247. }
  1248. if (variance) {
  1249. this.unexpected(variance.start);
  1250. }
  1251. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1252. } else {
  1253. var _allowInexact;
  1254. let kind = "init";
  1255. if (this.isContextual("get") || this.isContextual("set")) {
  1256. const lookahead = this.lookahead();
  1257. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1258. kind = this.state.value;
  1259. this.next();
  1260. }
  1261. }
  1262. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, (_allowInexact = allowInexact) != null ? _allowInexact : !exact);
  1263. if (propOrInexact === null) {
  1264. inexact = true;
  1265. inexactStart = this.state.lastTokStart;
  1266. } else {
  1267. nodeStart.properties.push(propOrInexact);
  1268. }
  1269. }
  1270. this.flowObjectTypeSemicolon();
  1271. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1272. this.raise(inexactStart, "Explicit inexact syntax must appear at the end of an inexact object");
  1273. }
  1274. }
  1275. this.expect(endDelim);
  1276. if (allowSpread) {
  1277. nodeStart.inexact = inexact;
  1278. }
  1279. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1280. this.state.inType = oldInType;
  1281. return out;
  1282. }
  1283. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1284. if (this.eat(types.ellipsis)) {
  1285. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  1286. if (isInexactToken) {
  1287. if (!allowSpread) {
  1288. this.raise(this.state.lastTokStart, "Explicit inexact syntax cannot appear in class or interface definitions");
  1289. } else if (!allowInexact) {
  1290. this.raise(this.state.lastTokStart, "Explicit inexact syntax cannot appear inside an explicit exact object type");
  1291. }
  1292. if (variance) {
  1293. this.raise(variance.start, "Explicit inexact syntax cannot have variance");
  1294. }
  1295. return null;
  1296. }
  1297. if (!allowSpread) {
  1298. this.raise(this.state.lastTokStart, "Spread operator cannot appear in class or interface definitions");
  1299. }
  1300. if (protoStart != null) {
  1301. this.unexpected(protoStart);
  1302. }
  1303. if (variance) {
  1304. this.raise(variance.start, "Spread properties cannot have variance");
  1305. }
  1306. node.argument = this.flowParseType();
  1307. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1308. } else {
  1309. node.key = this.flowParseObjectPropertyKey();
  1310. node.static = isStatic;
  1311. node.proto = protoStart != null;
  1312. node.kind = kind;
  1313. let optional = false;
  1314. if (this.isRelational("<") || this.match(types.parenL)) {
  1315. node.method = true;
  1316. if (protoStart != null) {
  1317. this.unexpected(protoStart);
  1318. }
  1319. if (variance) {
  1320. this.unexpected(variance.start);
  1321. }
  1322. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1323. if (kind === "get" || kind === "set") {
  1324. this.flowCheckGetterSetterParams(node);
  1325. }
  1326. } else {
  1327. if (kind !== "init") this.unexpected();
  1328. node.method = false;
  1329. if (this.eat(types.question)) {
  1330. optional = true;
  1331. }
  1332. node.value = this.flowParseTypeInitialiser();
  1333. node.variance = variance;
  1334. }
  1335. node.optional = optional;
  1336. return this.finishNode(node, "ObjectTypeProperty");
  1337. }
  1338. }
  1339. flowCheckGetterSetterParams(property) {
  1340. const paramCount = property.kind === "get" ? 0 : 1;
  1341. const start = property.start;
  1342. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1343. if (length !== paramCount) {
  1344. if (property.kind === "get") {
  1345. this.raise(start, "getter must not have any formal parameters");
  1346. } else {
  1347. this.raise(start, "setter must have exactly one formal parameter");
  1348. }
  1349. }
  1350. if (property.kind === "set" && property.value.rest) {
  1351. this.raise(start, "setter function argument must not be a rest parameter");
  1352. }
  1353. }
  1354. flowObjectTypeSemicolon() {
  1355. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1356. this.unexpected();
  1357. }
  1358. }
  1359. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1360. startPos = startPos || this.state.start;
  1361. startLoc = startLoc || this.state.startLoc;
  1362. let node = id || this.flowParseRestrictedIdentifier(true);
  1363. while (this.eat(types.dot)) {
  1364. const node2 = this.startNodeAt(startPos, startLoc);
  1365. node2.qualification = node;
  1366. node2.id = this.flowParseRestrictedIdentifier(true);
  1367. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1368. }
  1369. return node;
  1370. }
  1371. flowParseGenericType(startPos, startLoc, id) {
  1372. const node = this.startNodeAt(startPos, startLoc);
  1373. node.typeParameters = null;
  1374. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1375. if (this.isRelational("<")) {
  1376. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1377. }
  1378. return this.finishNode(node, "GenericTypeAnnotation");
  1379. }
  1380. flowParseTypeofType() {
  1381. const node = this.startNode();
  1382. this.expect(types._typeof);
  1383. node.argument = this.flowParsePrimaryType();
  1384. return this.finishNode(node, "TypeofTypeAnnotation");
  1385. }
  1386. flowParseTupleType() {
  1387. const node = this.startNode();
  1388. node.types = [];
  1389. this.expect(types.bracketL);
  1390. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1391. node.types.push(this.flowParseType());
  1392. if (this.match(types.bracketR)) break;
  1393. this.expect(types.comma);
  1394. }
  1395. this.expect(types.bracketR);
  1396. return this.finishNode(node, "TupleTypeAnnotation");
  1397. }
  1398. flowParseFunctionTypeParam() {
  1399. let name = null;
  1400. let optional = false;
  1401. let typeAnnotation = null;
  1402. const node = this.startNode();
  1403. const lh = this.lookahead();
  1404. if (lh.type === types.colon || lh.type === types.question) {
  1405. name = this.parseIdentifier();
  1406. if (this.eat(types.question)) {
  1407. optional = true;
  1408. }
  1409. typeAnnotation = this.flowParseTypeInitialiser();
  1410. } else {
  1411. typeAnnotation = this.flowParseType();
  1412. }
  1413. node.name = name;
  1414. node.optional = optional;
  1415. node.typeAnnotation = typeAnnotation;
  1416. return this.finishNode(node, "FunctionTypeParam");
  1417. }
  1418. reinterpretTypeAsFunctionTypeParam(type) {
  1419. const node = this.startNodeAt(type.start, type.loc.start);
  1420. node.name = null;
  1421. node.optional = false;
  1422. node.typeAnnotation = type;
  1423. return this.finishNode(node, "FunctionTypeParam");
  1424. }
  1425. flowParseFunctionTypeParams(params = []) {
  1426. let rest = null;
  1427. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1428. params.push(this.flowParseFunctionTypeParam());
  1429. if (!this.match(types.parenR)) {
  1430. this.expect(types.comma);
  1431. }
  1432. }
  1433. if (this.eat(types.ellipsis)) {
  1434. rest = this.flowParseFunctionTypeParam();
  1435. }
  1436. return {
  1437. params,
  1438. rest
  1439. };
  1440. }
  1441. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1442. switch (id.name) {
  1443. case "any":
  1444. return this.finishNode(node, "AnyTypeAnnotation");
  1445. case "bool":
  1446. case "boolean":
  1447. return this.finishNode(node, "BooleanTypeAnnotation");
  1448. case "mixed":
  1449. return this.finishNode(node, "MixedTypeAnnotation");
  1450. case "empty":
  1451. return this.finishNode(node, "EmptyTypeAnnotation");
  1452. case "number":
  1453. return this.finishNode(node, "NumberTypeAnnotation");
  1454. case "string":
  1455. return this.finishNode(node, "StringTypeAnnotation");
  1456. default:
  1457. this.checkNotUnderscore(id.name);
  1458. return this.flowParseGenericType(startPos, startLoc, id);
  1459. }
  1460. }
  1461. flowParsePrimaryType() {
  1462. const startPos = this.state.start;
  1463. const startLoc = this.state.startLoc;
  1464. const node = this.startNode();
  1465. let tmp;
  1466. let type;
  1467. let isGroupedType = false;
  1468. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1469. switch (this.state.type) {
  1470. case types.name:
  1471. if (this.isContextual("interface")) {
  1472. return this.flowParseInterfaceType();
  1473. }
  1474. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1475. case types.braceL:
  1476. return this.flowParseObjectType({
  1477. allowStatic: false,
  1478. allowExact: false,
  1479. allowSpread: true,
  1480. allowProto: false,
  1481. allowInexact: true
  1482. });
  1483. case types.braceBarL:
  1484. return this.flowParseObjectType({
  1485. allowStatic: false,
  1486. allowExact: true,
  1487. allowSpread: true,
  1488. allowProto: false,
  1489. allowInexact: false
  1490. });
  1491. case types.bracketL:
  1492. this.state.noAnonFunctionType = false;
  1493. type = this.flowParseTupleType();
  1494. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1495. return type;
  1496. case types.relational:
  1497. if (this.state.value === "<") {
  1498. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1499. this.expect(types.parenL);
  1500. tmp = this.flowParseFunctionTypeParams();
  1501. node.params = tmp.params;
  1502. node.rest = tmp.rest;
  1503. this.expect(types.parenR);
  1504. this.expect(types.arrow);
  1505. node.returnType = this.flowParseType();
  1506. return this.finishNode(node, "FunctionTypeAnnotation");
  1507. }
  1508. break;
  1509. case types.parenL:
  1510. this.next();
  1511. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1512. if (this.match(types.name)) {
  1513. const token = this.lookahead().type;
  1514. isGroupedType = token !== types.question && token !== types.colon;
  1515. } else {
  1516. isGroupedType = true;
  1517. }
  1518. }
  1519. if (isGroupedType) {
  1520. this.state.noAnonFunctionType = false;
  1521. type = this.flowParseType();
  1522. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1523. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  1524. this.expect(types.parenR);
  1525. return type;
  1526. } else {
  1527. this.eat(types.comma);
  1528. }
  1529. }
  1530. if (type) {
  1531. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  1532. } else {
  1533. tmp = this.flowParseFunctionTypeParams();
  1534. }
  1535. node.params = tmp.params;
  1536. node.rest = tmp.rest;
  1537. this.expect(types.parenR);
  1538. this.expect(types.arrow);
  1539. node.returnType = this.flowParseType();
  1540. node.typeParameters = null;
  1541. return this.finishNode(node, "FunctionTypeAnnotation");
  1542. case types.string:
  1543. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  1544. case types._true:
  1545. case types._false:
  1546. node.value = this.match(types._true);
  1547. this.next();
  1548. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  1549. case types.plusMin:
  1550. if (this.state.value === "-") {
  1551. this.next();
  1552. if (this.match(types.num)) {
  1553. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  1554. }
  1555. if (this.match(types.bigint)) {
  1556. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  1557. }
  1558. throw this.raise(this.state.start, `Unexpected token, expected "number" or "bigint"`);
  1559. }
  1560. this.unexpected();
  1561. case types.num:
  1562. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  1563. case types.bigint:
  1564. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  1565. case types._void:
  1566. this.next();
  1567. return this.finishNode(node, "VoidTypeAnnotation");
  1568. case types._null:
  1569. this.next();
  1570. return this.finishNode(node, "NullLiteralTypeAnnotation");
  1571. case types._this:
  1572. this.next();
  1573. return this.finishNode(node, "ThisTypeAnnotation");
  1574. case types.star:
  1575. this.next();
  1576. return this.finishNode(node, "ExistsTypeAnnotation");
  1577. default:
  1578. if (this.state.type.keyword === "typeof") {
  1579. return this.flowParseTypeofType();
  1580. } else if (this.state.type.keyword) {
  1581. const label = this.state.type.label;
  1582. this.next();
  1583. return super.createIdentifier(node, label);
  1584. }
  1585. }
  1586. throw this.unexpected();
  1587. }
  1588. flowParsePostfixType() {
  1589. const startPos = this.state.start,
  1590. startLoc = this.state.startLoc;
  1591. let type = this.flowParsePrimaryType();
  1592. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  1593. const node = this.startNodeAt(startPos, startLoc);
  1594. node.elementType = type;
  1595. this.expect(types.bracketL);
  1596. this.expect(types.bracketR);
  1597. type = this.finishNode(node, "ArrayTypeAnnotation");
  1598. }
  1599. return type;
  1600. }
  1601. flowParsePrefixType() {
  1602. const node = this.startNode();
  1603. if (this.eat(types.question)) {
  1604. node.typeAnnotation = this.flowParsePrefixType();
  1605. return this.finishNode(node, "NullableTypeAnnotation");
  1606. } else {
  1607. return this.flowParsePostfixType();
  1608. }
  1609. }
  1610. flowParseAnonFunctionWithoutParens() {
  1611. const param = this.flowParsePrefixType();
  1612. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  1613. const node = this.startNodeAt(param.start, param.loc.start);
  1614. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  1615. node.rest = null;
  1616. node.returnType = this.flowParseType();
  1617. node.typeParameters = null;
  1618. return this.finishNode(node, "FunctionTypeAnnotation");
  1619. }
  1620. return param;
  1621. }
  1622. flowParseIntersectionType() {
  1623. const node = this.startNode();
  1624. this.eat(types.bitwiseAND);
  1625. const type = this.flowParseAnonFunctionWithoutParens();
  1626. node.types = [type];
  1627. while (this.eat(types.bitwiseAND)) {
  1628. node.types.push(this.flowParseAnonFunctionWithoutParens());
  1629. }
  1630. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  1631. }
  1632. flowParseUnionType() {
  1633. const node = this.startNode();
  1634. this.eat(types.bitwiseOR);
  1635. const type = this.flowParseIntersectionType();
  1636. node.types = [type];
  1637. while (this.eat(types.bitwiseOR)) {
  1638. node.types.push(this.flowParseIntersectionType());
  1639. }
  1640. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  1641. }
  1642. flowParseType() {
  1643. const oldInType = this.state.inType;
  1644. this.state.inType = true;
  1645. const type = this.flowParseUnionType();
  1646. this.state.inType = oldInType;
  1647. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  1648. return type;
  1649. }
  1650. flowParseTypeOrImplicitInstantiation() {
  1651. if (this.state.type === types.name && this.state.value === "_") {
  1652. const startPos = this.state.start;
  1653. const startLoc = this.state.startLoc;
  1654. const node = this.parseIdentifier();
  1655. return this.flowParseGenericType(startPos, startLoc, node);
  1656. } else {
  1657. return this.flowParseType();
  1658. }
  1659. }
  1660. flowParseTypeAnnotation() {
  1661. const node = this.startNode();
  1662. node.typeAnnotation = this.flowParseTypeInitialiser();
  1663. return this.finishNode(node, "TypeAnnotation");
  1664. }
  1665. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  1666. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  1667. if (this.match(types.colon)) {
  1668. ident.typeAnnotation = this.flowParseTypeAnnotation();
  1669. this.resetEndLocation(ident);
  1670. }
  1671. return ident;
  1672. }
  1673. typeCastToParameter(node) {
  1674. node.expression.typeAnnotation = node.typeAnnotation;
  1675. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  1676. return node.expression;
  1677. }
  1678. flowParseVariance() {
  1679. let variance = null;
  1680. if (this.match(types.plusMin)) {
  1681. variance = this.startNode();
  1682. if (this.state.value === "+") {
  1683. variance.kind = "plus";
  1684. } else {
  1685. variance.kind = "minus";
  1686. }
  1687. this.next();
  1688. this.finishNode(variance, "Variance");
  1689. }
  1690. return variance;
  1691. }
  1692. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  1693. if (allowExpressionBody) {
  1694. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  1695. }
  1696. return super.parseFunctionBody(node, false, isMethod);
  1697. }
  1698. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  1699. if (this.match(types.colon)) {
  1700. const typeNode = this.startNode();
  1701. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1702. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  1703. }
  1704. super.parseFunctionBodyAndFinish(node, type, isMethod);
  1705. }
  1706. parseStatement(context, topLevel) {
  1707. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  1708. const node = this.startNode();
  1709. this.next();
  1710. return this.flowParseInterface(node);
  1711. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  1712. const node = this.startNode();
  1713. this.next();
  1714. return this.flowParseEnumDeclaration(node);
  1715. } else {
  1716. const stmt = super.parseStatement(context, topLevel);
  1717. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  1718. this.flowPragma = null;
  1719. }
  1720. return stmt;
  1721. }
  1722. }
  1723. parseExpressionStatement(node, expr) {
  1724. if (expr.type === "Identifier") {
  1725. if (expr.name === "declare") {
  1726. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  1727. return this.flowParseDeclare(node);
  1728. }
  1729. } else if (this.match(types.name)) {
  1730. if (expr.name === "interface") {
  1731. return this.flowParseInterface(node);
  1732. } else if (expr.name === "type") {
  1733. return this.flowParseTypeAlias(node);
  1734. } else if (expr.name === "opaque") {
  1735. return this.flowParseOpaqueType(node, false);
  1736. }
  1737. }
  1738. }
  1739. return super.parseExpressionStatement(node, expr);
  1740. }
  1741. shouldParseExportDeclaration() {
  1742. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  1743. }
  1744. isExportDefaultSpecifier() {
  1745. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  1746. return false;
  1747. }
  1748. return super.isExportDefaultSpecifier();
  1749. }
  1750. parseExportDefaultExpression() {
  1751. if (this.shouldParseEnums() && this.isContextual("enum")) {
  1752. const node = this.startNode();
  1753. this.next();
  1754. return this.flowParseEnumDeclaration(node);
  1755. }
  1756. return super.parseExportDefaultExpression();
  1757. }
  1758. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  1759. if (!this.match(types.question)) return expr;
  1760. if (refNeedsArrowPos) {
  1761. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  1762. if (!result.node) {
  1763. refNeedsArrowPos.start = result.error.pos || this.state.start;
  1764. return expr;
  1765. }
  1766. if (result.error) this.state = result.failState;
  1767. return result.node;
  1768. }
  1769. this.expect(types.question);
  1770. const state = this.state.clone();
  1771. const originalNoArrowAt = this.state.noArrowAt;
  1772. const node = this.startNodeAt(startPos, startLoc);
  1773. let {
  1774. consequent,
  1775. failed
  1776. } = this.tryParseConditionalConsequent();
  1777. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  1778. if (failed || invalid.length > 0) {
  1779. const noArrowAt = [...originalNoArrowAt];
  1780. if (invalid.length > 0) {
  1781. this.state = state;
  1782. this.state.noArrowAt = noArrowAt;
  1783. for (let i = 0; i < invalid.length; i++) {
  1784. noArrowAt.push(invalid[i].start);
  1785. }
  1786. ({
  1787. consequent,
  1788. failed
  1789. } = this.tryParseConditionalConsequent());
  1790. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  1791. }
  1792. if (failed && valid.length > 1) {
  1793. this.raise(state.start, "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.");
  1794. }
  1795. if (failed && valid.length === 1) {
  1796. this.state = state;
  1797. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  1798. ({
  1799. consequent,
  1800. failed
  1801. } = this.tryParseConditionalConsequent());
  1802. }
  1803. }
  1804. this.getArrowLikeExpressions(consequent, true);
  1805. this.state.noArrowAt = originalNoArrowAt;
  1806. this.expect(types.colon);
  1807. node.test = expr;
  1808. node.consequent = consequent;
  1809. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(noIn, undefined, undefined, undefined));
  1810. return this.finishNode(node, "ConditionalExpression");
  1811. }
  1812. tryParseConditionalConsequent() {
  1813. this.state.noArrowParamsConversionAt.push(this.state.start);
  1814. const consequent = this.parseMaybeAssign();
  1815. const failed = !this.match(types.colon);
  1816. this.state.noArrowParamsConversionAt.pop();
  1817. return {
  1818. consequent,
  1819. failed
  1820. };
  1821. }
  1822. getArrowLikeExpressions(node, disallowInvalid) {
  1823. const stack = [node];
  1824. const arrows = [];
  1825. while (stack.length !== 0) {
  1826. const node = stack.pop();
  1827. if (node.type === "ArrowFunctionExpression") {
  1828. if (node.typeParameters || !node.returnType) {
  1829. this.finishArrowValidation(node);
  1830. } else {
  1831. arrows.push(node);
  1832. }
  1833. stack.push(node.body);
  1834. } else if (node.type === "ConditionalExpression") {
  1835. stack.push(node.consequent);
  1836. stack.push(node.alternate);
  1837. }
  1838. }
  1839. if (disallowInvalid) {
  1840. arrows.forEach(node => this.finishArrowValidation(node));
  1841. return [arrows, []];
  1842. }
  1843. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  1844. }
  1845. finishArrowValidation(node) {
  1846. var _node$extra;
  1847. this.toAssignableList(node.params, true, "arrow function parameters", (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma);
  1848. this.scope.enter(functionFlags(false, false) | SCOPE_ARROW);
  1849. super.checkParams(node, false, true);
  1850. this.scope.exit();
  1851. }
  1852. forwardNoArrowParamsConversionAt(node, parse) {
  1853. let result;
  1854. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  1855. this.state.noArrowParamsConversionAt.push(this.state.start);
  1856. result = parse();
  1857. this.state.noArrowParamsConversionAt.pop();
  1858. } else {
  1859. result = parse();
  1860. }
  1861. return result;
  1862. }
  1863. parseParenItem(node, startPos, startLoc) {
  1864. node = super.parseParenItem(node, startPos, startLoc);
  1865. if (this.eat(types.question)) {
  1866. node.optional = true;
  1867. this.resetEndLocation(node);
  1868. }
  1869. if (this.match(types.colon)) {
  1870. const typeCastNode = this.startNodeAt(startPos, startLoc);
  1871. typeCastNode.expression = node;
  1872. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  1873. return this.finishNode(typeCastNode, "TypeCastExpression");
  1874. }
  1875. return node;
  1876. }
  1877. assertModuleNodeAllowed(node) {
  1878. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  1879. return;
  1880. }
  1881. super.assertModuleNodeAllowed(node);
  1882. }
  1883. parseExport(node) {
  1884. const decl = super.parseExport(node);
  1885. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  1886. decl.exportKind = decl.exportKind || "value";
  1887. }
  1888. return decl;
  1889. }
  1890. parseExportDeclaration(node) {
  1891. if (this.isContextual("type")) {
  1892. node.exportKind = "type";
  1893. const declarationNode = this.startNode();
  1894. this.next();
  1895. if (this.match(types.braceL)) {
  1896. node.specifiers = this.parseExportSpecifiers();
  1897. this.parseExportFrom(node);
  1898. return null;
  1899. } else {
  1900. return this.flowParseTypeAlias(declarationNode);
  1901. }
  1902. } else if (this.isContextual("opaque")) {
  1903. node.exportKind = "type";
  1904. const declarationNode = this.startNode();
  1905. this.next();
  1906. return this.flowParseOpaqueType(declarationNode, false);
  1907. } else if (this.isContextual("interface")) {
  1908. node.exportKind = "type";
  1909. const declarationNode = this.startNode();
  1910. this.next();
  1911. return this.flowParseInterface(declarationNode);
  1912. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  1913. node.exportKind = "value";
  1914. const declarationNode = this.startNode();
  1915. this.next();
  1916. return this.flowParseEnumDeclaration(declarationNode);
  1917. } else {
  1918. return super.parseExportDeclaration(node);
  1919. }
  1920. }
  1921. eatExportStar(node) {
  1922. if (super.eatExportStar(...arguments)) return true;
  1923. if (this.isContextual("type") && this.lookahead().type === types.star) {
  1924. node.exportKind = "type";
  1925. this.next();
  1926. this.next();
  1927. return true;
  1928. }
  1929. return false;
  1930. }
  1931. maybeParseExportNamespaceSpecifier(node) {
  1932. const pos = this.state.start;
  1933. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  1934. if (hasNamespace && node.exportKind === "type") {
  1935. this.unexpected(pos);
  1936. }
  1937. return hasNamespace;
  1938. }
  1939. parseClassId(node, isStatement, optionalId) {
  1940. super.parseClassId(node, isStatement, optionalId);
  1941. if (this.isRelational("<")) {
  1942. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1943. }
  1944. }
  1945. getTokenFromCode(code) {
  1946. const next = this.input.charCodeAt(this.state.pos + 1);
  1947. if (code === 123 && next === 124) {
  1948. return this.finishOp(types.braceBarL, 2);
  1949. } else if (this.state.inType && (code === 62 || code === 60)) {
  1950. return this.finishOp(types.relational, 1);
  1951. } else if (isIteratorStart(code, next)) {
  1952. this.state.isIterator = true;
  1953. return super.readWord();
  1954. } else {
  1955. return super.getTokenFromCode(code);
  1956. }
  1957. }
  1958. isAssignable(node, isBinding) {
  1959. switch (node.type) {
  1960. case "Identifier":
  1961. case "ObjectPattern":
  1962. case "ArrayPattern":
  1963. case "AssignmentPattern":
  1964. return true;
  1965. case "ObjectExpression":
  1966. {
  1967. const last = node.properties.length - 1;
  1968. return node.properties.every((prop, i) => {
  1969. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  1970. });
  1971. }
  1972. case "ObjectProperty":
  1973. return this.isAssignable(node.value);
  1974. case "SpreadElement":
  1975. return this.isAssignable(node.argument);
  1976. case "ArrayExpression":
  1977. return node.elements.every(element => this.isAssignable(element));
  1978. case "AssignmentExpression":
  1979. return node.operator === "=";
  1980. case "ParenthesizedExpression":
  1981. case "TypeCastExpression":
  1982. return this.isAssignable(node.expression);
  1983. case "MemberExpression":
  1984. case "OptionalMemberExpression":
  1985. return !isBinding;
  1986. default:
  1987. return false;
  1988. }
  1989. }
  1990. toAssignable(node, isBinding, contextDescription) {
  1991. if (node.type === "TypeCastExpression") {
  1992. return super.toAssignable(this.typeCastToParameter(node), isBinding, contextDescription);
  1993. } else {
  1994. return super.toAssignable(node, isBinding, contextDescription);
  1995. }
  1996. }
  1997. toAssignableList(exprList, isBinding, contextDescription, trailingCommaPos) {
  1998. for (let i = 0; i < exprList.length; i++) {
  1999. const expr = exprList[i];
  2000. if (expr && expr.type === "TypeCastExpression") {
  2001. exprList[i] = this.typeCastToParameter(expr);
  2002. }
  2003. }
  2004. return super.toAssignableList(exprList, isBinding, contextDescription, trailingCommaPos);
  2005. }
  2006. toReferencedList(exprList, isParenthesizedExpr) {
  2007. for (let i = 0; i < exprList.length; i++) {
  2008. const expr = exprList[i];
  2009. if (expr && expr.type === "TypeCastExpression" && (!expr.extra || !expr.extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2010. this.raise(expr.typeAnnotation.start, "The type cast expression is expected to be wrapped with parenthesis");
  2011. }
  2012. }
  2013. return exprList;
  2014. }
  2015. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  2016. if (expr.type !== "TypeCastExpression") {
  2017. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  2018. }
  2019. }
  2020. parseClassProperty(node) {
  2021. if (this.match(types.colon)) {
  2022. node.typeAnnotation = this.flowParseTypeAnnotation();
  2023. }
  2024. return super.parseClassProperty(node);
  2025. }
  2026. parseClassPrivateProperty(node) {
  2027. if (this.match(types.colon)) {
  2028. node.typeAnnotation = this.flowParseTypeAnnotation();
  2029. }
  2030. return super.parseClassPrivateProperty(node);
  2031. }
  2032. isClassMethod() {
  2033. return this.isRelational("<") || super.isClassMethod();
  2034. }
  2035. isClassProperty() {
  2036. return this.match(types.colon) || super.isClassProperty();
  2037. }
  2038. isNonstaticConstructor(method) {
  2039. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2040. }
  2041. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2042. if (method.variance) {
  2043. this.unexpected(method.variance.start);
  2044. }
  2045. delete method.variance;
  2046. if (this.isRelational("<")) {
  2047. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2048. }
  2049. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2050. }
  2051. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2052. if (method.variance) {
  2053. this.unexpected(method.variance.start);
  2054. }
  2055. delete method.variance;
  2056. if (this.isRelational("<")) {
  2057. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2058. }
  2059. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2060. }
  2061. parseClassSuper(node) {
  2062. super.parseClassSuper(node);
  2063. if (node.superClass && this.isRelational("<")) {
  2064. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2065. }
  2066. if (this.isContextual("implements")) {
  2067. this.next();
  2068. const implemented = node.implements = [];
  2069. do {
  2070. const node = this.startNode();
  2071. node.id = this.flowParseRestrictedIdentifier(true);
  2072. if (this.isRelational("<")) {
  2073. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2074. } else {
  2075. node.typeParameters = null;
  2076. }
  2077. implemented.push(this.finishNode(node, "ClassImplements"));
  2078. } while (this.eat(types.comma));
  2079. }
  2080. }
  2081. parsePropertyName(node) {
  2082. const variance = this.flowParseVariance();
  2083. const key = super.parsePropertyName(node);
  2084. node.variance = variance;
  2085. return key;
  2086. }
  2087. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc) {
  2088. if (prop.variance) {
  2089. this.unexpected(prop.variance.start);
  2090. }
  2091. delete prop.variance;
  2092. let typeParameters;
  2093. if (this.isRelational("<")) {
  2094. typeParameters = this.flowParseTypeParameterDeclaration();
  2095. if (!this.match(types.parenL)) this.unexpected();
  2096. }
  2097. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc);
  2098. if (typeParameters) {
  2099. (prop.value || prop).typeParameters = typeParameters;
  2100. }
  2101. }
  2102. parseAssignableListItemTypes(param) {
  2103. if (this.eat(types.question)) {
  2104. if (param.type !== "Identifier") {
  2105. this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature.");
  2106. }
  2107. param.optional = true;
  2108. }
  2109. if (this.match(types.colon)) {
  2110. param.typeAnnotation = this.flowParseTypeAnnotation();
  2111. }
  2112. this.resetEndLocation(param);
  2113. return param;
  2114. }
  2115. parseMaybeDefault(startPos, startLoc, left) {
  2116. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2117. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2118. this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`");
  2119. }
  2120. return node;
  2121. }
  2122. shouldParseDefaultImport(node) {
  2123. if (!hasTypeImportKind(node)) {
  2124. return super.shouldParseDefaultImport(node);
  2125. }
  2126. return isMaybeDefaultImport(this.state);
  2127. }
  2128. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2129. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2130. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  2131. node.specifiers.push(this.finishNode(specifier, type));
  2132. }
  2133. maybeParseDefaultImportSpecifier(node) {
  2134. node.importKind = "value";
  2135. let kind = null;
  2136. if (this.match(types._typeof)) {
  2137. kind = "typeof";
  2138. } else if (this.isContextual("type")) {
  2139. kind = "type";
  2140. }
  2141. if (kind) {
  2142. const lh = this.lookahead();
  2143. if (kind === "type" && lh.type === types.star) {
  2144. this.unexpected(lh.start);
  2145. }
  2146. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2147. this.next();
  2148. node.importKind = kind;
  2149. }
  2150. }
  2151. return super.maybeParseDefaultImportSpecifier(node);
  2152. }
  2153. parseImportSpecifier(node) {
  2154. const specifier = this.startNode();
  2155. const firstIdentLoc = this.state.start;
  2156. const firstIdent = this.parseIdentifier(true);
  2157. let specifierTypeKind = null;
  2158. if (firstIdent.name === "type") {
  2159. specifierTypeKind = "type";
  2160. } else if (firstIdent.name === "typeof") {
  2161. specifierTypeKind = "typeof";
  2162. }
  2163. let isBinding = false;
  2164. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2165. const as_ident = this.parseIdentifier(true);
  2166. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2167. specifier.imported = as_ident;
  2168. specifier.importKind = specifierTypeKind;
  2169. specifier.local = as_ident.__clone();
  2170. } else {
  2171. specifier.imported = firstIdent;
  2172. specifier.importKind = null;
  2173. specifier.local = this.parseIdentifier();
  2174. }
  2175. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2176. specifier.imported = this.parseIdentifier(true);
  2177. specifier.importKind = specifierTypeKind;
  2178. if (this.eatContextual("as")) {
  2179. specifier.local = this.parseIdentifier();
  2180. } else {
  2181. isBinding = true;
  2182. specifier.local = specifier.imported.__clone();
  2183. }
  2184. } else {
  2185. isBinding = true;
  2186. specifier.imported = firstIdent;
  2187. specifier.importKind = null;
  2188. specifier.local = specifier.imported.__clone();
  2189. }
  2190. const nodeIsTypeImport = hasTypeImportKind(node);
  2191. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2192. if (nodeIsTypeImport && specifierIsTypeImport) {
  2193. this.raise(firstIdentLoc, "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");
  2194. }
  2195. if (nodeIsTypeImport || specifierIsTypeImport) {
  2196. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  2197. }
  2198. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2199. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2200. }
  2201. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  2202. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2203. }
  2204. parseFunctionParams(node, allowModifiers) {
  2205. const kind = node.kind;
  2206. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2207. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2208. }
  2209. super.parseFunctionParams(node, allowModifiers);
  2210. }
  2211. parseVarId(decl, kind) {
  2212. super.parseVarId(decl, kind);
  2213. if (this.match(types.colon)) {
  2214. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2215. this.resetEndLocation(decl.id);
  2216. }
  2217. }
  2218. parseAsyncArrowFromCallExpression(node, call) {
  2219. if (this.match(types.colon)) {
  2220. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2221. this.state.noAnonFunctionType = true;
  2222. node.returnType = this.flowParseTypeAnnotation();
  2223. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2224. }
  2225. return super.parseAsyncArrowFromCallExpression(node, call);
  2226. }
  2227. shouldParseAsyncArrow() {
  2228. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2229. }
  2230. parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) {
  2231. let state = null;
  2232. let jsx;
  2233. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2234. state = this.state.clone();
  2235. jsx = this.tryParse(() => super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos), state);
  2236. if (!jsx.error) return jsx.node;
  2237. const {
  2238. context
  2239. } = this.state;
  2240. if (context[context.length - 1] === types$1.j_oTag) {
  2241. context.length -= 2;
  2242. } else if (context[context.length - 1] === types$1.j_expr) {
  2243. context.length -= 1;
  2244. }
  2245. }
  2246. if (jsx && jsx.error || this.isRelational("<")) {
  2247. state = state || this.state.clone();
  2248. let typeParameters;
  2249. const arrow = this.tryParse(() => {
  2250. typeParameters = this.flowParseTypeParameterDeclaration();
  2251. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos));
  2252. arrowExpression.typeParameters = typeParameters;
  2253. this.resetStartLocationFromNode(arrowExpression, typeParameters);
  2254. return arrowExpression;
  2255. }, state);
  2256. const arrowExpression = arrow.node && arrow.node.type === "ArrowFunctionExpression" ? arrow.node : null;
  2257. if (!arrow.error && arrowExpression) return arrowExpression;
  2258. if (jsx && jsx.node) {
  2259. this.state = jsx.failState;
  2260. return jsx.node;
  2261. }
  2262. if (arrowExpression) {
  2263. this.state = arrow.failState;
  2264. return arrowExpression;
  2265. }
  2266. if (jsx && jsx.thrown) throw jsx.error;
  2267. if (arrow.thrown) throw arrow.error;
  2268. throw this.raise(typeParameters.start, "Expected an arrow function after this type parameter declaration");
  2269. }
  2270. return super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos);
  2271. }
  2272. parseArrow(node) {
  2273. if (this.match(types.colon)) {
  2274. const result = this.tryParse(() => {
  2275. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2276. this.state.noAnonFunctionType = true;
  2277. const typeNode = this.startNode();
  2278. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2279. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2280. if (this.canInsertSemicolon()) this.unexpected();
  2281. if (!this.match(types.arrow)) this.unexpected();
  2282. return typeNode;
  2283. });
  2284. if (result.thrown) return null;
  2285. if (result.error) this.state = result.failState;
  2286. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  2287. }
  2288. return super.parseArrow(node);
  2289. }
  2290. shouldParseArrow() {
  2291. return this.match(types.colon) || super.shouldParseArrow();
  2292. }
  2293. setArrowFunctionParameters(node, params) {
  2294. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2295. node.params = params;
  2296. } else {
  2297. super.setArrowFunctionParameters(node, params);
  2298. }
  2299. }
  2300. checkParams(node, allowDuplicates, isArrowFunction) {
  2301. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2302. return;
  2303. }
  2304. return super.checkParams(...arguments);
  2305. }
  2306. parseParenAndDistinguishExpression(canBeArrow) {
  2307. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2308. }
  2309. parseSubscripts(base, startPos, startLoc, noCalls) {
  2310. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2311. this.next();
  2312. const node = this.startNodeAt(startPos, startLoc);
  2313. node.callee = base;
  2314. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2315. base = this.finishNode(node, "CallExpression");
  2316. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2317. const state = this.state.clone();
  2318. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  2319. if (!arrow.error && !arrow.aborted) return arrow.node;
  2320. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  2321. if (result.node && !result.error) return result.node;
  2322. if (arrow.node) {
  2323. this.state = arrow.failState;
  2324. return arrow.node;
  2325. }
  2326. if (result.node) {
  2327. this.state = result.failState;
  2328. return result.node;
  2329. }
  2330. throw arrow.error || result.error;
  2331. }
  2332. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2333. }
  2334. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  2335. if (this.match(types.questionDot) && this.isLookaheadRelational("<")) {
  2336. this.expectPlugin("optionalChaining");
  2337. subscriptState.optionalChainMember = true;
  2338. if (noCalls) {
  2339. subscriptState.stop = true;
  2340. return base;
  2341. }
  2342. this.next();
  2343. const node = this.startNodeAt(startPos, startLoc);
  2344. node.callee = base;
  2345. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2346. this.expect(types.parenL);
  2347. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2348. node.optional = true;
  2349. return this.finishCallExpression(node, true);
  2350. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2351. const node = this.startNodeAt(startPos, startLoc);
  2352. node.callee = base;
  2353. const result = this.tryParse(() => {
  2354. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2355. this.expect(types.parenL);
  2356. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2357. if (subscriptState.optionalChainMember) node.optional = false;
  2358. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  2359. });
  2360. if (result.node) {
  2361. if (result.error) this.state = result.failState;
  2362. return result.node;
  2363. }
  2364. }
  2365. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  2366. }
  2367. parseNewArguments(node) {
  2368. let targs = null;
  2369. if (this.shouldParseTypes() && this.isRelational("<")) {
  2370. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  2371. }
  2372. node.typeArguments = targs;
  2373. super.parseNewArguments(node);
  2374. }
  2375. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2376. const node = this.startNodeAt(startPos, startLoc);
  2377. this.parseFunctionParams(node);
  2378. if (!this.parseArrow(node)) return;
  2379. return this.parseArrowExpression(node, undefined, true);
  2380. }
  2381. readToken_mult_modulo(code) {
  2382. const next = this.input.charCodeAt(this.state.pos + 1);
  2383. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2384. this.state.hasFlowComment = false;
  2385. this.state.pos += 2;
  2386. this.nextToken();
  2387. return;
  2388. }
  2389. super.readToken_mult_modulo(code);
  2390. }
  2391. readToken_pipe_amp(code) {
  2392. const next = this.input.charCodeAt(this.state.pos + 1);
  2393. if (code === 124 && next === 125) {
  2394. this.finishOp(types.braceBarR, 2);
  2395. return;
  2396. }
  2397. super.readToken_pipe_amp(code);
  2398. }
  2399. parseTopLevel(file, program) {
  2400. const fileNode = super.parseTopLevel(file, program);
  2401. if (this.state.hasFlowComment) {
  2402. this.raise(this.state.pos, "Unterminated flow-comment");
  2403. }
  2404. return fileNode;
  2405. }
  2406. skipBlockComment() {
  2407. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2408. if (this.state.hasFlowComment) {
  2409. this.unexpected(null, "Cannot have a flow comment inside another flow comment");
  2410. }
  2411. this.hasFlowCommentCompletion();
  2412. this.state.pos += this.skipFlowComment();
  2413. this.state.hasFlowComment = true;
  2414. return;
  2415. }
  2416. if (this.state.hasFlowComment) {
  2417. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2418. if (end === -1) {
  2419. throw this.raise(this.state.pos - 2, "Unterminated comment");
  2420. }
  2421. this.state.pos = end + 3;
  2422. return;
  2423. }
  2424. super.skipBlockComment();
  2425. }
  2426. skipFlowComment() {
  2427. const {
  2428. pos
  2429. } = this.state;
  2430. let shiftToFirstNonWhiteSpace = 2;
  2431. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2432. shiftToFirstNonWhiteSpace++;
  2433. }
  2434. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2435. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2436. if (ch2 === 58 && ch3 === 58) {
  2437. return shiftToFirstNonWhiteSpace + 2;
  2438. }
  2439. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2440. return shiftToFirstNonWhiteSpace + 12;
  2441. }
  2442. if (ch2 === 58 && ch3 !== 58) {
  2443. return shiftToFirstNonWhiteSpace;
  2444. }
  2445. return false;
  2446. }
  2447. hasFlowCommentCompletion() {
  2448. const end = this.input.indexOf("*/", this.state.pos);
  2449. if (end === -1) {
  2450. throw this.raise(this.state.pos, "Unterminated comment");
  2451. }
  2452. }
  2453. flowEnumErrorBooleanMemberNotInitialized(pos, {
  2454. enumName,
  2455. memberName
  2456. }) {
  2457. this.raise(pos, `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` ` + `or \`${memberName} = false,\` in enum \`${enumName}\`.`);
  2458. }
  2459. flowEnumErrorInvalidMemberName(pos, {
  2460. enumName,
  2461. memberName
  2462. }) {
  2463. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  2464. this.raise(pos, `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using ` + `\`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`);
  2465. }
  2466. flowEnumErrorDuplicateMemberName(pos, {
  2467. enumName,
  2468. memberName
  2469. }) {
  2470. this.raise(pos, `Enum member names need to be unique, but the name \`${memberName}\` has already been used ` + `before in enum \`${enumName}\`.`);
  2471. }
  2472. flowEnumErrorInconsistentMemberValues(pos, {
  2473. enumName
  2474. }) {
  2475. this.raise(pos, `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or ` + `consistently use literals (either booleans, numbers, or strings) for all member initializers.`);
  2476. }
  2477. flowEnumErrorInvalidExplicitType(pos, {
  2478. enumName,
  2479. suppliedType
  2480. }) {
  2481. const suggestion = `Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in ` + `enum \`${enumName}\`.`;
  2482. const message = suppliedType === null ? `Supplied enum type is not valid. ${suggestion}` : `Enum type \`${suppliedType}\` is not valid. ${suggestion}`;
  2483. return this.raise(pos, message);
  2484. }
  2485. flowEnumErrorInvalidMemberInitializer(pos, {
  2486. enumName,
  2487. explicitType,
  2488. memberName
  2489. }) {
  2490. let message = null;
  2491. switch (explicitType) {
  2492. case "boolean":
  2493. case "number":
  2494. case "string":
  2495. message = `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of ` + `\`${memberName}\` needs to be a ${explicitType} literal.`;
  2496. break;
  2497. case "symbol":
  2498. message = `Symbol enum members cannot be initialized. Use \`${memberName},\` in ` + `enum \`${enumName}\`.`;
  2499. break;
  2500. default:
  2501. message = `The enum member initializer for \`${memberName}\` needs to be a literal (either ` + `a boolean, number, or string) in enum \`${enumName}\`.`;
  2502. }
  2503. return this.raise(pos, message);
  2504. }
  2505. flowEnumErrorNumberMemberNotInitialized(pos, {
  2506. enumName,
  2507. memberName
  2508. }) {
  2509. this.raise(pos, `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`);
  2510. }
  2511. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  2512. enumName
  2513. }) {
  2514. this.raise(pos, `String enum members need to consistently either all use initializers, or use no initializers, ` + `in enum \`${enumName}\`.`);
  2515. }
  2516. flowEnumMemberInit() {
  2517. const startPos = this.state.start;
  2518. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  2519. switch (this.state.type) {
  2520. case types.num:
  2521. {
  2522. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  2523. if (endOfInit()) {
  2524. return {
  2525. type: "number",
  2526. pos: literal.start,
  2527. value: literal
  2528. };
  2529. }
  2530. return {
  2531. type: "invalid",
  2532. pos: startPos
  2533. };
  2534. }
  2535. case types.string:
  2536. {
  2537. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  2538. if (endOfInit()) {
  2539. return {
  2540. type: "string",
  2541. pos: literal.start,
  2542. value: literal
  2543. };
  2544. }
  2545. return {
  2546. type: "invalid",
  2547. pos: startPos
  2548. };
  2549. }
  2550. case types._true:
  2551. case types._false:
  2552. {
  2553. const literal = this.parseBooleanLiteral();
  2554. if (endOfInit()) {
  2555. return {
  2556. type: "boolean",
  2557. pos: literal.start,
  2558. value: literal
  2559. };
  2560. }
  2561. return {
  2562. type: "invalid",
  2563. pos: startPos
  2564. };
  2565. }
  2566. default:
  2567. return {
  2568. type: "invalid",
  2569. pos: startPos
  2570. };
  2571. }
  2572. }
  2573. flowEnumMemberRaw() {
  2574. const pos = this.state.start;
  2575. const id = this.parseIdentifier(true);
  2576. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  2577. type: "none",
  2578. pos
  2579. };
  2580. return {
  2581. id,
  2582. init
  2583. };
  2584. }
  2585. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  2586. const {
  2587. explicitType
  2588. } = context;
  2589. if (explicitType === null) {
  2590. return;
  2591. }
  2592. if (explicitType !== expectedType) {
  2593. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  2594. }
  2595. }
  2596. flowEnumMembers({
  2597. enumName,
  2598. explicitType
  2599. }) {
  2600. const seenNames = new Set();
  2601. const members = {
  2602. booleanMembers: [],
  2603. numberMembers: [],
  2604. stringMembers: [],
  2605. defaultedMembers: []
  2606. };
  2607. while (!this.match(types.braceR)) {
  2608. const memberNode = this.startNode();
  2609. const {
  2610. id,
  2611. init
  2612. } = this.flowEnumMemberRaw();
  2613. const memberName = id.name;
  2614. if (memberName === "") {
  2615. continue;
  2616. }
  2617. if (/^[a-z]/.test(memberName)) {
  2618. this.flowEnumErrorInvalidMemberName(id.start, {
  2619. enumName,
  2620. memberName
  2621. });
  2622. }
  2623. if (seenNames.has(memberName)) {
  2624. this.flowEnumErrorDuplicateMemberName(id.start, {
  2625. enumName,
  2626. memberName
  2627. });
  2628. }
  2629. seenNames.add(memberName);
  2630. const context = {
  2631. enumName,
  2632. explicitType,
  2633. memberName
  2634. };
  2635. memberNode.id = id;
  2636. switch (init.type) {
  2637. case "boolean":
  2638. {
  2639. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  2640. memberNode.init = init.value;
  2641. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  2642. break;
  2643. }
  2644. case "number":
  2645. {
  2646. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  2647. memberNode.init = init.value;
  2648. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  2649. break;
  2650. }
  2651. case "string":
  2652. {
  2653. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  2654. memberNode.init = init.value;
  2655. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  2656. break;
  2657. }
  2658. case "invalid":
  2659. {
  2660. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  2661. }
  2662. case "none":
  2663. {
  2664. switch (explicitType) {
  2665. case "boolean":
  2666. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  2667. break;
  2668. case "number":
  2669. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  2670. break;
  2671. default:
  2672. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  2673. }
  2674. }
  2675. }
  2676. if (!this.match(types.braceR)) {
  2677. this.expect(types.comma);
  2678. }
  2679. }
  2680. return members;
  2681. }
  2682. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  2683. enumName
  2684. }) {
  2685. if (initializedMembers.length === 0) {
  2686. return defaultedMembers;
  2687. } else if (defaultedMembers.length === 0) {
  2688. return initializedMembers;
  2689. } else if (defaultedMembers.length > initializedMembers.length) {
  2690. for (let _i = 0; _i < initializedMembers.length; _i++) {
  2691. const member = initializedMembers[_i];
  2692. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  2693. enumName
  2694. });
  2695. }
  2696. return defaultedMembers;
  2697. } else {
  2698. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  2699. const member = defaultedMembers[_i2];
  2700. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  2701. enumName
  2702. });
  2703. }
  2704. return initializedMembers;
  2705. }
  2706. }
  2707. flowEnumParseExplicitType({
  2708. enumName
  2709. }) {
  2710. if (this.eatContextual("of")) {
  2711. if (!this.match(types.name)) {
  2712. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  2713. enumName,
  2714. suppliedType: null
  2715. });
  2716. }
  2717. const {
  2718. value
  2719. } = this.state;
  2720. this.next();
  2721. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  2722. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  2723. enumName,
  2724. suppliedType: value
  2725. });
  2726. }
  2727. return value;
  2728. }
  2729. return null;
  2730. }
  2731. flowEnumBody(node, {
  2732. enumName,
  2733. nameLoc
  2734. }) {
  2735. const explicitType = this.flowEnumParseExplicitType({
  2736. enumName
  2737. });
  2738. this.expect(types.braceL);
  2739. const members = this.flowEnumMembers({
  2740. enumName,
  2741. explicitType
  2742. });
  2743. switch (explicitType) {
  2744. case "boolean":
  2745. node.explicitType = true;
  2746. node.members = members.booleanMembers;
  2747. this.expect(types.braceR);
  2748. return this.finishNode(node, "EnumBooleanBody");
  2749. case "number":
  2750. node.explicitType = true;
  2751. node.members = members.numberMembers;
  2752. this.expect(types.braceR);
  2753. return this.finishNode(node, "EnumNumberBody");
  2754. case "string":
  2755. node.explicitType = true;
  2756. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  2757. enumName
  2758. });
  2759. this.expect(types.braceR);
  2760. return this.finishNode(node, "EnumStringBody");
  2761. case "symbol":
  2762. node.members = members.defaultedMembers;
  2763. this.expect(types.braceR);
  2764. return this.finishNode(node, "EnumSymbolBody");
  2765. default:
  2766. {
  2767. const empty = () => {
  2768. node.members = [];
  2769. this.expect(types.braceR);
  2770. return this.finishNode(node, "EnumStringBody");
  2771. };
  2772. node.explicitType = false;
  2773. const boolsLen = members.booleanMembers.length;
  2774. const numsLen = members.numberMembers.length;
  2775. const strsLen = members.stringMembers.length;
  2776. const defaultedLen = members.defaultedMembers.length;
  2777. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  2778. return empty();
  2779. } else if (!boolsLen && !numsLen) {
  2780. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  2781. enumName
  2782. });
  2783. this.expect(types.braceR);
  2784. return this.finishNode(node, "EnumStringBody");
  2785. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  2786. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  2787. const member = _members$defaultedMem[_i3];
  2788. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  2789. enumName,
  2790. memberName: member.id.name
  2791. });
  2792. }
  2793. node.members = members.booleanMembers;
  2794. this.expect(types.braceR);
  2795. return this.finishNode(node, "EnumBooleanBody");
  2796. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  2797. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  2798. const member = _members$defaultedMem2[_i4];
  2799. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  2800. enumName,
  2801. memberName: member.id.name
  2802. });
  2803. }
  2804. node.members = members.numberMembers;
  2805. this.expect(types.braceR);
  2806. return this.finishNode(node, "EnumNumberBody");
  2807. } else {
  2808. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  2809. enumName
  2810. });
  2811. return empty();
  2812. }
  2813. }
  2814. }
  2815. }
  2816. flowParseEnumDeclaration(node) {
  2817. const id = this.parseIdentifier();
  2818. node.id = id;
  2819. node.body = this.flowEnumBody(this.startNode(), {
  2820. enumName: id.name,
  2821. nameLoc: id.start
  2822. });
  2823. return this.finishNode(node, "EnumDeclaration");
  2824. }
  2825. });
  2826. const entities = {
  2827. quot: "\u0022",
  2828. amp: "&",
  2829. apos: "\u0027",
  2830. lt: "<",
  2831. gt: ">",
  2832. nbsp: "\u00A0",
  2833. iexcl: "\u00A1",
  2834. cent: "\u00A2",
  2835. pound: "\u00A3",
  2836. curren: "\u00A4",
  2837. yen: "\u00A5",
  2838. brvbar: "\u00A6",
  2839. sect: "\u00A7",
  2840. uml: "\u00A8",
  2841. copy: "\u00A9",
  2842. ordf: "\u00AA",
  2843. laquo: "\u00AB",
  2844. not: "\u00AC",
  2845. shy: "\u00AD",
  2846. reg: "\u00AE",
  2847. macr: "\u00AF",
  2848. deg: "\u00B0",
  2849. plusmn: "\u00B1",
  2850. sup2: "\u00B2",
  2851. sup3: "\u00B3",
  2852. acute: "\u00B4",
  2853. micro: "\u00B5",
  2854. para: "\u00B6",
  2855. middot: "\u00B7",
  2856. cedil: "\u00B8",
  2857. sup1: "\u00B9",
  2858. ordm: "\u00BA",
  2859. raquo: "\u00BB",
  2860. frac14: "\u00BC",
  2861. frac12: "\u00BD",
  2862. frac34: "\u00BE",
  2863. iquest: "\u00BF",
  2864. Agrave: "\u00C0",
  2865. Aacute: "\u00C1",
  2866. Acirc: "\u00C2",
  2867. Atilde: "\u00C3",
  2868. Auml: "\u00C4",
  2869. Aring: "\u00C5",
  2870. AElig: "\u00C6",
  2871. Ccedil: "\u00C7",
  2872. Egrave: "\u00C8",
  2873. Eacute: "\u00C9",
  2874. Ecirc: "\u00CA",
  2875. Euml: "\u00CB",
  2876. Igrave: "\u00CC",
  2877. Iacute: "\u00CD",
  2878. Icirc: "\u00CE",
  2879. Iuml: "\u00CF",
  2880. ETH: "\u00D0",
  2881. Ntilde: "\u00D1",
  2882. Ograve: "\u00D2",
  2883. Oacute: "\u00D3",
  2884. Ocirc: "\u00D4",
  2885. Otilde: "\u00D5",
  2886. Ouml: "\u00D6",
  2887. times: "\u00D7",
  2888. Oslash: "\u00D8",
  2889. Ugrave: "\u00D9",
  2890. Uacute: "\u00DA",
  2891. Ucirc: "\u00DB",
  2892. Uuml: "\u00DC",
  2893. Yacute: "\u00DD",
  2894. THORN: "\u00DE",
  2895. szlig: "\u00DF",
  2896. agrave: "\u00E0",
  2897. aacute: "\u00E1",
  2898. acirc: "\u00E2",
  2899. atilde: "\u00E3",
  2900. auml: "\u00E4",
  2901. aring: "\u00E5",
  2902. aelig: "\u00E6",
  2903. ccedil: "\u00E7",
  2904. egrave: "\u00E8",
  2905. eacute: "\u00E9",
  2906. ecirc: "\u00EA",
  2907. euml: "\u00EB",
  2908. igrave: "\u00EC",
  2909. iacute: "\u00ED",
  2910. icirc: "\u00EE",
  2911. iuml: "\u00EF",
  2912. eth: "\u00F0",
  2913. ntilde: "\u00F1",
  2914. ograve: "\u00F2",
  2915. oacute: "\u00F3",
  2916. ocirc: "\u00F4",
  2917. otilde: "\u00F5",
  2918. ouml: "\u00F6",
  2919. divide: "\u00F7",
  2920. oslash: "\u00F8",
  2921. ugrave: "\u00F9",
  2922. uacute: "\u00FA",
  2923. ucirc: "\u00FB",
  2924. uuml: "\u00FC",
  2925. yacute: "\u00FD",
  2926. thorn: "\u00FE",
  2927. yuml: "\u00FF",
  2928. OElig: "\u0152",
  2929. oelig: "\u0153",
  2930. Scaron: "\u0160",
  2931. scaron: "\u0161",
  2932. Yuml: "\u0178",
  2933. fnof: "\u0192",
  2934. circ: "\u02C6",
  2935. tilde: "\u02DC",
  2936. Alpha: "\u0391",
  2937. Beta: "\u0392",
  2938. Gamma: "\u0393",
  2939. Delta: "\u0394",
  2940. Epsilon: "\u0395",
  2941. Zeta: "\u0396",
  2942. Eta: "\u0397",
  2943. Theta: "\u0398",
  2944. Iota: "\u0399",
  2945. Kappa: "\u039A",
  2946. Lambda: "\u039B",
  2947. Mu: "\u039C",
  2948. Nu: "\u039D",
  2949. Xi: "\u039E",
  2950. Omicron: "\u039F",
  2951. Pi: "\u03A0",
  2952. Rho: "\u03A1",
  2953. Sigma: "\u03A3",
  2954. Tau: "\u03A4",
  2955. Upsilon: "\u03A5",
  2956. Phi: "\u03A6",
  2957. Chi: "\u03A7",
  2958. Psi: "\u03A8",
  2959. Omega: "\u03A9",
  2960. alpha: "\u03B1",
  2961. beta: "\u03B2",
  2962. gamma: "\u03B3",
  2963. delta: "\u03B4",
  2964. epsilon: "\u03B5",
  2965. zeta: "\u03B6",
  2966. eta: "\u03B7",
  2967. theta: "\u03B8",
  2968. iota: "\u03B9",
  2969. kappa: "\u03BA",
  2970. lambda: "\u03BB",
  2971. mu: "\u03BC",
  2972. nu: "\u03BD",
  2973. xi: "\u03BE",
  2974. omicron: "\u03BF",
  2975. pi: "\u03C0",
  2976. rho: "\u03C1",
  2977. sigmaf: "\u03C2",
  2978. sigma: "\u03C3",
  2979. tau: "\u03C4",
  2980. upsilon: "\u03C5",
  2981. phi: "\u03C6",
  2982. chi: "\u03C7",
  2983. psi: "\u03C8",
  2984. omega: "\u03C9",
  2985. thetasym: "\u03D1",
  2986. upsih: "\u03D2",
  2987. piv: "\u03D6",
  2988. ensp: "\u2002",
  2989. emsp: "\u2003",
  2990. thinsp: "\u2009",
  2991. zwnj: "\u200C",
  2992. zwj: "\u200D",
  2993. lrm: "\u200E",
  2994. rlm: "\u200F",
  2995. ndash: "\u2013",
  2996. mdash: "\u2014",
  2997. lsquo: "\u2018",
  2998. rsquo: "\u2019",
  2999. sbquo: "\u201A",
  3000. ldquo: "\u201C",
  3001. rdquo: "\u201D",
  3002. bdquo: "\u201E",
  3003. dagger: "\u2020",
  3004. Dagger: "\u2021",
  3005. bull: "\u2022",
  3006. hellip: "\u2026",
  3007. permil: "\u2030",
  3008. prime: "\u2032",
  3009. Prime: "\u2033",
  3010. lsaquo: "\u2039",
  3011. rsaquo: "\u203A",
  3012. oline: "\u203E",
  3013. frasl: "\u2044",
  3014. euro: "\u20AC",
  3015. image: "\u2111",
  3016. weierp: "\u2118",
  3017. real: "\u211C",
  3018. trade: "\u2122",
  3019. alefsym: "\u2135",
  3020. larr: "\u2190",
  3021. uarr: "\u2191",
  3022. rarr: "\u2192",
  3023. darr: "\u2193",
  3024. harr: "\u2194",
  3025. crarr: "\u21B5",
  3026. lArr: "\u21D0",
  3027. uArr: "\u21D1",
  3028. rArr: "\u21D2",
  3029. dArr: "\u21D3",
  3030. hArr: "\u21D4",
  3031. forall: "\u2200",
  3032. part: "\u2202",
  3033. exist: "\u2203",
  3034. empty: "\u2205",
  3035. nabla: "\u2207",
  3036. isin: "\u2208",
  3037. notin: "\u2209",
  3038. ni: "\u220B",
  3039. prod: "\u220F",
  3040. sum: "\u2211",
  3041. minus: "\u2212",
  3042. lowast: "\u2217",
  3043. radic: "\u221A",
  3044. prop: "\u221D",
  3045. infin: "\u221E",
  3046. ang: "\u2220",
  3047. and: "\u2227",
  3048. or: "\u2228",
  3049. cap: "\u2229",
  3050. cup: "\u222A",
  3051. int: "\u222B",
  3052. there4: "\u2234",
  3053. sim: "\u223C",
  3054. cong: "\u2245",
  3055. asymp: "\u2248",
  3056. ne: "\u2260",
  3057. equiv: "\u2261",
  3058. le: "\u2264",
  3059. ge: "\u2265",
  3060. sub: "\u2282",
  3061. sup: "\u2283",
  3062. nsub: "\u2284",
  3063. sube: "\u2286",
  3064. supe: "\u2287",
  3065. oplus: "\u2295",
  3066. otimes: "\u2297",
  3067. perp: "\u22A5",
  3068. sdot: "\u22C5",
  3069. lceil: "\u2308",
  3070. rceil: "\u2309",
  3071. lfloor: "\u230A",
  3072. rfloor: "\u230B",
  3073. lang: "\u2329",
  3074. rang: "\u232A",
  3075. loz: "\u25CA",
  3076. spades: "\u2660",
  3077. clubs: "\u2663",
  3078. hearts: "\u2665",
  3079. diams: "\u2666"
  3080. };
  3081. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3082. const DECIMAL_NUMBER = /^\d+$/;
  3083. types$1.j_oTag = new TokContext("<tag", false);
  3084. types$1.j_cTag = new TokContext("</tag", false);
  3085. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3086. types.jsxName = new TokenType("jsxName");
  3087. types.jsxText = new TokenType("jsxText", {
  3088. beforeExpr: true
  3089. });
  3090. types.jsxTagStart = new TokenType("jsxTagStart", {
  3091. startsExpr: true
  3092. });
  3093. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3094. types.jsxTagStart.updateContext = function () {
  3095. this.state.context.push(types$1.j_expr);
  3096. this.state.context.push(types$1.j_oTag);
  3097. this.state.exprAllowed = false;
  3098. };
  3099. types.jsxTagEnd.updateContext = function (prevType) {
  3100. const out = this.state.context.pop();
  3101. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3102. this.state.context.pop();
  3103. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3104. } else {
  3105. this.state.exprAllowed = true;
  3106. }
  3107. };
  3108. function isFragment(object) {
  3109. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  3110. }
  3111. function getQualifiedJSXName(object) {
  3112. if (object.type === "JSXIdentifier") {
  3113. return object.name;
  3114. }
  3115. if (object.type === "JSXNamespacedName") {
  3116. return object.namespace.name + ":" + object.name.name;
  3117. }
  3118. if (object.type === "JSXMemberExpression") {
  3119. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  3120. }
  3121. throw new Error("Node had unexpected type: " + object.type);
  3122. }
  3123. var jsx = (superClass => class extends superClass {
  3124. jsxReadToken() {
  3125. let out = "";
  3126. let chunkStart = this.state.pos;
  3127. for (;;) {
  3128. if (this.state.pos >= this.length) {
  3129. throw this.raise(this.state.start, "Unterminated JSX contents");
  3130. }
  3131. const ch = this.input.charCodeAt(this.state.pos);
  3132. switch (ch) {
  3133. case 60:
  3134. case 123:
  3135. if (this.state.pos === this.state.start) {
  3136. if (ch === 60 && this.state.exprAllowed) {
  3137. ++this.state.pos;
  3138. return this.finishToken(types.jsxTagStart);
  3139. }
  3140. return super.getTokenFromCode(ch);
  3141. }
  3142. out += this.input.slice(chunkStart, this.state.pos);
  3143. return this.finishToken(types.jsxText, out);
  3144. case 38:
  3145. out += this.input.slice(chunkStart, this.state.pos);
  3146. out += this.jsxReadEntity();
  3147. chunkStart = this.state.pos;
  3148. break;
  3149. default:
  3150. if (isNewLine(ch)) {
  3151. out += this.input.slice(chunkStart, this.state.pos);
  3152. out += this.jsxReadNewLine(true);
  3153. chunkStart = this.state.pos;
  3154. } else {
  3155. ++this.state.pos;
  3156. }
  3157. }
  3158. }
  3159. }
  3160. jsxReadNewLine(normalizeCRLF) {
  3161. const ch = this.input.charCodeAt(this.state.pos);
  3162. let out;
  3163. ++this.state.pos;
  3164. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  3165. ++this.state.pos;
  3166. out = normalizeCRLF ? "\n" : "\r\n";
  3167. } else {
  3168. out = String.fromCharCode(ch);
  3169. }
  3170. ++this.state.curLine;
  3171. this.state.lineStart = this.state.pos;
  3172. return out;
  3173. }
  3174. jsxReadString(quote) {
  3175. let out = "";
  3176. let chunkStart = ++this.state.pos;
  3177. for (;;) {
  3178. if (this.state.pos >= this.length) {
  3179. throw this.raise(this.state.start, "Unterminated string constant");
  3180. }
  3181. const ch = this.input.charCodeAt(this.state.pos);
  3182. if (ch === quote) break;
  3183. if (ch === 38) {
  3184. out += this.input.slice(chunkStart, this.state.pos);
  3185. out += this.jsxReadEntity();
  3186. chunkStart = this.state.pos;
  3187. } else if (isNewLine(ch)) {
  3188. out += this.input.slice(chunkStart, this.state.pos);
  3189. out += this.jsxReadNewLine(false);
  3190. chunkStart = this.state.pos;
  3191. } else {
  3192. ++this.state.pos;
  3193. }
  3194. }
  3195. out += this.input.slice(chunkStart, this.state.pos++);
  3196. return this.finishToken(types.string, out);
  3197. }
  3198. jsxReadEntity() {
  3199. let str = "";
  3200. let count = 0;
  3201. let entity;
  3202. let ch = this.input[this.state.pos];
  3203. const startPos = ++this.state.pos;
  3204. while (this.state.pos < this.length && count++ < 10) {
  3205. ch = this.input[this.state.pos++];
  3206. if (ch === ";") {
  3207. if (str[0] === "#") {
  3208. if (str[1] === "x") {
  3209. str = str.substr(2);
  3210. if (HEX_NUMBER.test(str)) {
  3211. entity = String.fromCodePoint(parseInt(str, 16));
  3212. }
  3213. } else {
  3214. str = str.substr(1);
  3215. if (DECIMAL_NUMBER.test(str)) {
  3216. entity = String.fromCodePoint(parseInt(str, 10));
  3217. }
  3218. }
  3219. } else {
  3220. entity = entities[str];
  3221. }
  3222. break;
  3223. }
  3224. str += ch;
  3225. }
  3226. if (!entity) {
  3227. this.state.pos = startPos;
  3228. return "&";
  3229. }
  3230. return entity;
  3231. }
  3232. jsxReadWord() {
  3233. let ch;
  3234. const start = this.state.pos;
  3235. do {
  3236. ch = this.input.charCodeAt(++this.state.pos);
  3237. } while (isIdentifierChar(ch) || ch === 45);
  3238. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  3239. }
  3240. jsxParseIdentifier() {
  3241. const node = this.startNode();
  3242. if (this.match(types.jsxName)) {
  3243. node.name = this.state.value;
  3244. } else if (this.state.type.keyword) {
  3245. node.name = this.state.type.keyword;
  3246. } else {
  3247. this.unexpected();
  3248. }
  3249. this.next();
  3250. return this.finishNode(node, "JSXIdentifier");
  3251. }
  3252. jsxParseNamespacedName() {
  3253. const startPos = this.state.start;
  3254. const startLoc = this.state.startLoc;
  3255. const name = this.jsxParseIdentifier();
  3256. if (!this.eat(types.colon)) return name;
  3257. const node = this.startNodeAt(startPos, startLoc);
  3258. node.namespace = name;
  3259. node.name = this.jsxParseIdentifier();
  3260. return this.finishNode(node, "JSXNamespacedName");
  3261. }
  3262. jsxParseElementName() {
  3263. const startPos = this.state.start;
  3264. const startLoc = this.state.startLoc;
  3265. let node = this.jsxParseNamespacedName();
  3266. if (node.type === "JSXNamespacedName") {
  3267. return node;
  3268. }
  3269. while (this.eat(types.dot)) {
  3270. const newNode = this.startNodeAt(startPos, startLoc);
  3271. newNode.object = node;
  3272. newNode.property = this.jsxParseIdentifier();
  3273. node = this.finishNode(newNode, "JSXMemberExpression");
  3274. }
  3275. return node;
  3276. }
  3277. jsxParseAttributeValue() {
  3278. let node;
  3279. switch (this.state.type) {
  3280. case types.braceL:
  3281. node = this.startNode();
  3282. this.next();
  3283. node = this.jsxParseExpressionContainer(node);
  3284. if (node.expression.type === "JSXEmptyExpression") {
  3285. this.raise(node.start, "JSX attributes must only be assigned a non-empty expression");
  3286. }
  3287. return node;
  3288. case types.jsxTagStart:
  3289. case types.string:
  3290. return this.parseExprAtom();
  3291. default:
  3292. throw this.raise(this.state.start, "JSX value should be either an expression or a quoted JSX text");
  3293. }
  3294. }
  3295. jsxParseEmptyExpression() {
  3296. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  3297. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  3298. }
  3299. jsxParseSpreadChild(node) {
  3300. this.next();
  3301. node.expression = this.parseExpression();
  3302. this.expect(types.braceR);
  3303. return this.finishNode(node, "JSXSpreadChild");
  3304. }
  3305. jsxParseExpressionContainer(node) {
  3306. if (this.match(types.braceR)) {
  3307. node.expression = this.jsxParseEmptyExpression();
  3308. } else {
  3309. node.expression = this.parseExpression();
  3310. }
  3311. this.expect(types.braceR);
  3312. return this.finishNode(node, "JSXExpressionContainer");
  3313. }
  3314. jsxParseAttribute() {
  3315. const node = this.startNode();
  3316. if (this.eat(types.braceL)) {
  3317. this.expect(types.ellipsis);
  3318. node.argument = this.parseMaybeAssign();
  3319. this.expect(types.braceR);
  3320. return this.finishNode(node, "JSXSpreadAttribute");
  3321. }
  3322. node.name = this.jsxParseNamespacedName();
  3323. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  3324. return this.finishNode(node, "JSXAttribute");
  3325. }
  3326. jsxParseOpeningElementAt(startPos, startLoc) {
  3327. const node = this.startNodeAt(startPos, startLoc);
  3328. if (this.match(types.jsxTagEnd)) {
  3329. this.expect(types.jsxTagEnd);
  3330. return this.finishNode(node, "JSXOpeningFragment");
  3331. }
  3332. node.name = this.jsxParseElementName();
  3333. return this.jsxParseOpeningElementAfterName(node);
  3334. }
  3335. jsxParseOpeningElementAfterName(node) {
  3336. const attributes = [];
  3337. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  3338. attributes.push(this.jsxParseAttribute());
  3339. }
  3340. node.attributes = attributes;
  3341. node.selfClosing = this.eat(types.slash);
  3342. this.expect(types.jsxTagEnd);
  3343. return this.finishNode(node, "JSXOpeningElement");
  3344. }
  3345. jsxParseClosingElementAt(startPos, startLoc) {
  3346. const node = this.startNodeAt(startPos, startLoc);
  3347. if (this.match(types.jsxTagEnd)) {
  3348. this.expect(types.jsxTagEnd);
  3349. return this.finishNode(node, "JSXClosingFragment");
  3350. }
  3351. node.name = this.jsxParseElementName();
  3352. this.expect(types.jsxTagEnd);
  3353. return this.finishNode(node, "JSXClosingElement");
  3354. }
  3355. jsxParseElementAt(startPos, startLoc) {
  3356. const node = this.startNodeAt(startPos, startLoc);
  3357. const children = [];
  3358. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  3359. let closingElement = null;
  3360. if (!openingElement.selfClosing) {
  3361. contents: for (;;) {
  3362. switch (this.state.type) {
  3363. case types.jsxTagStart:
  3364. startPos = this.state.start;
  3365. startLoc = this.state.startLoc;
  3366. this.next();
  3367. if (this.eat(types.slash)) {
  3368. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  3369. break contents;
  3370. }
  3371. children.push(this.jsxParseElementAt(startPos, startLoc));
  3372. break;
  3373. case types.jsxText:
  3374. children.push(this.parseExprAtom());
  3375. break;
  3376. case types.braceL:
  3377. {
  3378. const node = this.startNode();
  3379. this.next();
  3380. if (this.match(types.ellipsis)) {
  3381. children.push(this.jsxParseSpreadChild(node));
  3382. } else {
  3383. children.push(this.jsxParseExpressionContainer(node));
  3384. }
  3385. break;
  3386. }
  3387. default:
  3388. throw this.unexpected();
  3389. }
  3390. }
  3391. if (isFragment(openingElement) && !isFragment(closingElement)) {
  3392. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <>");
  3393. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  3394. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
  3395. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  3396. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  3397. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
  3398. }
  3399. }
  3400. }
  3401. if (isFragment(openingElement)) {
  3402. node.openingFragment = openingElement;
  3403. node.closingFragment = closingElement;
  3404. } else {
  3405. node.openingElement = openingElement;
  3406. node.closingElement = closingElement;
  3407. }
  3408. node.children = children;
  3409. if (this.isRelational("<")) {
  3410. throw this.raise(this.state.start, "Adjacent JSX elements must be wrapped in an enclosing tag. " + "Did you want a JSX fragment <>...</>?");
  3411. }
  3412. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  3413. }
  3414. jsxParseElement() {
  3415. const startPos = this.state.start;
  3416. const startLoc = this.state.startLoc;
  3417. this.next();
  3418. return this.jsxParseElementAt(startPos, startLoc);
  3419. }
  3420. parseExprAtom(refShortHandDefaultPos) {
  3421. if (this.match(types.jsxText)) {
  3422. return this.parseLiteral(this.state.value, "JSXText");
  3423. } else if (this.match(types.jsxTagStart)) {
  3424. return this.jsxParseElement();
  3425. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3426. this.finishToken(types.jsxTagStart);
  3427. return this.jsxParseElement();
  3428. } else {
  3429. return super.parseExprAtom(refShortHandDefaultPos);
  3430. }
  3431. }
  3432. getTokenFromCode(code) {
  3433. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  3434. const context = this.curContext();
  3435. if (context === types$1.j_expr) {
  3436. return this.jsxReadToken();
  3437. }
  3438. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  3439. if (isIdentifierStart(code)) {
  3440. return this.jsxReadWord();
  3441. }
  3442. if (code === 62) {
  3443. ++this.state.pos;
  3444. return this.finishToken(types.jsxTagEnd);
  3445. }
  3446. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  3447. return this.jsxReadString(code);
  3448. }
  3449. }
  3450. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  3451. ++this.state.pos;
  3452. return this.finishToken(types.jsxTagStart);
  3453. }
  3454. return super.getTokenFromCode(code);
  3455. }
  3456. updateContext(prevType) {
  3457. if (this.match(types.braceL)) {
  3458. const curContext = this.curContext();
  3459. if (curContext === types$1.j_oTag) {
  3460. this.state.context.push(types$1.braceExpression);
  3461. } else if (curContext === types$1.j_expr) {
  3462. this.state.context.push(types$1.templateQuasi);
  3463. } else {
  3464. super.updateContext(prevType);
  3465. }
  3466. this.state.exprAllowed = true;
  3467. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  3468. this.state.context.length -= 2;
  3469. this.state.context.push(types$1.j_cTag);
  3470. this.state.exprAllowed = false;
  3471. } else {
  3472. return super.updateContext(prevType);
  3473. }
  3474. }
  3475. });
  3476. class Scope {
  3477. constructor(flags) {
  3478. this.var = [];
  3479. this.lexical = [];
  3480. this.functions = [];
  3481. this.flags = flags;
  3482. }
  3483. }
  3484. class ScopeHandler {
  3485. constructor(raise, inModule) {
  3486. this.scopeStack = [];
  3487. this.undefinedExports = new Map();
  3488. this.raise = raise;
  3489. this.inModule = inModule;
  3490. }
  3491. get inFunction() {
  3492. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  3493. }
  3494. get inGenerator() {
  3495. return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;
  3496. }
  3497. get inAsync() {
  3498. return (this.currentVarScope().flags & SCOPE_ASYNC) > 0;
  3499. }
  3500. get allowSuper() {
  3501. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  3502. }
  3503. get allowDirectSuper() {
  3504. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  3505. }
  3506. get inNonArrowFunction() {
  3507. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  3508. }
  3509. get treatFunctionsAsVar() {
  3510. return this.treatFunctionsAsVarInScope(this.currentScope());
  3511. }
  3512. createScope(flags) {
  3513. return new Scope(flags);
  3514. }
  3515. enter(flags) {
  3516. this.scopeStack.push(this.createScope(flags));
  3517. }
  3518. exit() {
  3519. this.scopeStack.pop();
  3520. }
  3521. treatFunctionsAsVarInScope(scope) {
  3522. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  3523. }
  3524. declareName(name, bindingType, pos) {
  3525. let scope = this.currentScope();
  3526. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  3527. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3528. if (bindingType & BIND_SCOPE_FUNCTION) {
  3529. scope.functions.push(name);
  3530. } else {
  3531. scope.lexical.push(name);
  3532. }
  3533. if (bindingType & BIND_SCOPE_LEXICAL) {
  3534. this.maybeExportDefined(scope, name);
  3535. }
  3536. } else if (bindingType & BIND_SCOPE_VAR) {
  3537. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  3538. scope = this.scopeStack[i];
  3539. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3540. scope.var.push(name);
  3541. this.maybeExportDefined(scope, name);
  3542. if (scope.flags & SCOPE_VAR) break;
  3543. }
  3544. }
  3545. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  3546. this.undefinedExports.delete(name);
  3547. }
  3548. }
  3549. maybeExportDefined(scope, name) {
  3550. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  3551. this.undefinedExports.delete(name);
  3552. }
  3553. }
  3554. checkRedeclarationInScope(scope, name, bindingType, pos) {
  3555. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  3556. this.raise(pos, `Identifier '${name}' has already been declared`);
  3557. }
  3558. }
  3559. isRedeclaredInScope(scope, name, bindingType) {
  3560. if (!(bindingType & BIND_KIND_VALUE)) return false;
  3561. if (bindingType & BIND_SCOPE_LEXICAL) {
  3562. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  3563. }
  3564. if (bindingType & BIND_SCOPE_FUNCTION) {
  3565. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  3566. }
  3567. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  3568. }
  3569. checkLocalExport(id) {
  3570. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1 && this.scopeStack[0].functions.indexOf(id.name) === -1) {
  3571. this.undefinedExports.set(id.name, id.start);
  3572. }
  3573. }
  3574. currentScope() {
  3575. return this.scopeStack[this.scopeStack.length - 1];
  3576. }
  3577. currentVarScope() {
  3578. for (let i = this.scopeStack.length - 1;; i--) {
  3579. const scope = this.scopeStack[i];
  3580. if (scope.flags & SCOPE_VAR) {
  3581. return scope;
  3582. }
  3583. }
  3584. }
  3585. currentThisScope() {
  3586. for (let i = this.scopeStack.length - 1;; i--) {
  3587. const scope = this.scopeStack[i];
  3588. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  3589. return scope;
  3590. }
  3591. }
  3592. }
  3593. }
  3594. class TypeScriptScope extends Scope {
  3595. constructor(...args) {
  3596. super(...args);
  3597. this.types = [];
  3598. this.enums = [];
  3599. this.constEnums = [];
  3600. this.classes = [];
  3601. this.exportOnlyBindings = [];
  3602. }
  3603. }
  3604. class TypeScriptScopeHandler extends ScopeHandler {
  3605. createScope(flags) {
  3606. return new TypeScriptScope(flags);
  3607. }
  3608. declareName(name, bindingType, pos) {
  3609. const scope = this.currentScope();
  3610. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  3611. this.maybeExportDefined(scope, name);
  3612. scope.exportOnlyBindings.push(name);
  3613. return;
  3614. }
  3615. super.declareName(...arguments);
  3616. if (bindingType & BIND_KIND_TYPE) {
  3617. if (!(bindingType & BIND_KIND_VALUE)) {
  3618. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3619. this.maybeExportDefined(scope, name);
  3620. }
  3621. scope.types.push(name);
  3622. }
  3623. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  3624. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  3625. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  3626. }
  3627. isRedeclaredInScope(scope, name, bindingType) {
  3628. if (scope.enums.indexOf(name) > -1) {
  3629. if (bindingType & BIND_FLAGS_TS_ENUM) {
  3630. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  3631. const wasConst = scope.constEnums.indexOf(name) > -1;
  3632. return isConst !== wasConst;
  3633. }
  3634. return true;
  3635. }
  3636. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  3637. if (scope.lexical.indexOf(name) > -1) {
  3638. return !!(bindingType & BIND_KIND_VALUE);
  3639. } else {
  3640. return false;
  3641. }
  3642. }
  3643. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  3644. return true;
  3645. }
  3646. return super.isRedeclaredInScope(...arguments);
  3647. }
  3648. checkLocalExport(id) {
  3649. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  3650. super.checkLocalExport(id);
  3651. }
  3652. }
  3653. }
  3654. function nonNull(x) {
  3655. if (x == null) {
  3656. throw new Error(`Unexpected ${x} value.`);
  3657. }
  3658. return x;
  3659. }
  3660. function assert(x) {
  3661. if (!x) {
  3662. throw new Error("Assert fail");
  3663. }
  3664. }
  3665. function keywordTypeFromName(value) {
  3666. switch (value) {
  3667. case "any":
  3668. return "TSAnyKeyword";
  3669. case "boolean":
  3670. return "TSBooleanKeyword";
  3671. case "bigint":
  3672. return "TSBigIntKeyword";
  3673. case "never":
  3674. return "TSNeverKeyword";
  3675. case "number":
  3676. return "TSNumberKeyword";
  3677. case "object":
  3678. return "TSObjectKeyword";
  3679. case "string":
  3680. return "TSStringKeyword";
  3681. case "symbol":
  3682. return "TSSymbolKeyword";
  3683. case "undefined":
  3684. return "TSUndefinedKeyword";
  3685. case "unknown":
  3686. return "TSUnknownKeyword";
  3687. default:
  3688. return undefined;
  3689. }
  3690. }
  3691. var typescript = (superClass => class extends superClass {
  3692. getScopeHandler() {
  3693. return TypeScriptScopeHandler;
  3694. }
  3695. tsIsIdentifier() {
  3696. return this.match(types.name);
  3697. }
  3698. tsNextTokenCanFollowModifier() {
  3699. this.next();
  3700. return !this.hasPrecedingLineBreak() && !this.match(types.parenL) && !this.match(types.parenR) && !this.match(types.colon) && !this.match(types.eq) && !this.match(types.question) && !this.match(types.bang);
  3701. }
  3702. tsParseModifier(allowedModifiers) {
  3703. if (!this.match(types.name)) {
  3704. return undefined;
  3705. }
  3706. const modifier = this.state.value;
  3707. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  3708. return modifier;
  3709. }
  3710. return undefined;
  3711. }
  3712. tsParseModifiers(allowedModifiers) {
  3713. const modifiers = Object.create(null);
  3714. while (true) {
  3715. const startPos = this.state.start;
  3716. const modifier = this.tsParseModifier(allowedModifiers);
  3717. if (!modifier) break;
  3718. if (Object.hasOwnProperty.call(modifiers, modifier)) {
  3719. this.raise(startPos, `Duplicate modifier: '${modifier}'`);
  3720. }
  3721. modifiers[modifier] = true;
  3722. }
  3723. return modifiers;
  3724. }
  3725. tsIsListTerminator(kind) {
  3726. switch (kind) {
  3727. case "EnumMembers":
  3728. case "TypeMembers":
  3729. return this.match(types.braceR);
  3730. case "HeritageClauseElement":
  3731. return this.match(types.braceL);
  3732. case "TupleElementTypes":
  3733. return this.match(types.bracketR);
  3734. case "TypeParametersOrArguments":
  3735. return this.isRelational(">");
  3736. }
  3737. throw new Error("Unreachable");
  3738. }
  3739. tsParseList(kind, parseElement) {
  3740. const result = [];
  3741. while (!this.tsIsListTerminator(kind)) {
  3742. result.push(parseElement());
  3743. }
  3744. return result;
  3745. }
  3746. tsParseDelimitedList(kind, parseElement) {
  3747. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  3748. }
  3749. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  3750. const result = [];
  3751. while (true) {
  3752. if (this.tsIsListTerminator(kind)) {
  3753. break;
  3754. }
  3755. const element = parseElement();
  3756. if (element == null) {
  3757. return undefined;
  3758. }
  3759. result.push(element);
  3760. if (this.eat(types.comma)) {
  3761. continue;
  3762. }
  3763. if (this.tsIsListTerminator(kind)) {
  3764. break;
  3765. }
  3766. if (expectSuccess) {
  3767. this.expect(types.comma);
  3768. }
  3769. return undefined;
  3770. }
  3771. return result;
  3772. }
  3773. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  3774. if (!skipFirstToken) {
  3775. if (bracket) {
  3776. this.expect(types.bracketL);
  3777. } else {
  3778. this.expectRelational("<");
  3779. }
  3780. }
  3781. const result = this.tsParseDelimitedList(kind, parseElement);
  3782. if (bracket) {
  3783. this.expect(types.bracketR);
  3784. } else {
  3785. this.expectRelational(">");
  3786. }
  3787. return result;
  3788. }
  3789. tsParseImportType() {
  3790. const node = this.startNode();
  3791. this.expect(types._import);
  3792. this.expect(types.parenL);
  3793. if (!this.match(types.string)) {
  3794. this.raise(this.state.start, "Argument in a type import must be a string literal");
  3795. }
  3796. node.argument = this.parseExprAtom();
  3797. this.expect(types.parenR);
  3798. if (this.eat(types.dot)) {
  3799. node.qualifier = this.tsParseEntityName(true);
  3800. }
  3801. if (this.isRelational("<")) {
  3802. node.typeParameters = this.tsParseTypeArguments();
  3803. }
  3804. return this.finishNode(node, "TSImportType");
  3805. }
  3806. tsParseEntityName(allowReservedWords) {
  3807. let entity = this.parseIdentifier();
  3808. while (this.eat(types.dot)) {
  3809. const node = this.startNodeAtNode(entity);
  3810. node.left = entity;
  3811. node.right = this.parseIdentifier(allowReservedWords);
  3812. entity = this.finishNode(node, "TSQualifiedName");
  3813. }
  3814. return entity;
  3815. }
  3816. tsParseTypeReference() {
  3817. const node = this.startNode();
  3818. node.typeName = this.tsParseEntityName(false);
  3819. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  3820. node.typeParameters = this.tsParseTypeArguments();
  3821. }
  3822. return this.finishNode(node, "TSTypeReference");
  3823. }
  3824. tsParseThisTypePredicate(lhs) {
  3825. this.next();
  3826. const node = this.startNodeAtNode(lhs);
  3827. node.parameterName = lhs;
  3828. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  3829. return this.finishNode(node, "TSTypePredicate");
  3830. }
  3831. tsParseThisTypeNode() {
  3832. const node = this.startNode();
  3833. this.next();
  3834. return this.finishNode(node, "TSThisType");
  3835. }
  3836. tsParseTypeQuery() {
  3837. const node = this.startNode();
  3838. this.expect(types._typeof);
  3839. if (this.match(types._import)) {
  3840. node.exprName = this.tsParseImportType();
  3841. } else {
  3842. node.exprName = this.tsParseEntityName(true);
  3843. }
  3844. return this.finishNode(node, "TSTypeQuery");
  3845. }
  3846. tsParseTypeParameter() {
  3847. const node = this.startNode();
  3848. node.name = this.parseIdentifierName(node.start);
  3849. node.constraint = this.tsEatThenParseType(types._extends);
  3850. node.default = this.tsEatThenParseType(types.eq);
  3851. return this.finishNode(node, "TSTypeParameter");
  3852. }
  3853. tsTryParseTypeParameters() {
  3854. if (this.isRelational("<")) {
  3855. return this.tsParseTypeParameters();
  3856. }
  3857. }
  3858. tsParseTypeParameters() {
  3859. const node = this.startNode();
  3860. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  3861. this.next();
  3862. } else {
  3863. this.unexpected();
  3864. }
  3865. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  3866. return this.finishNode(node, "TSTypeParameterDeclaration");
  3867. }
  3868. tsTryNextParseConstantContext() {
  3869. if (this.lookahead().type === types._const) {
  3870. this.next();
  3871. return this.tsParseTypeReference();
  3872. }
  3873. return null;
  3874. }
  3875. tsFillSignature(returnToken, signature) {
  3876. const returnTokenRequired = returnToken === types.arrow;
  3877. signature.typeParameters = this.tsTryParseTypeParameters();
  3878. this.expect(types.parenL);
  3879. signature.parameters = this.tsParseBindingListForSignature();
  3880. if (returnTokenRequired) {
  3881. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  3882. } else if (this.match(returnToken)) {
  3883. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  3884. }
  3885. }
  3886. tsParseBindingListForSignature() {
  3887. return this.parseBindingList(types.parenR, 41).map(pattern => {
  3888. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  3889. this.raise(pattern.start, "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern," + `instead got ${pattern.type}`);
  3890. }
  3891. return pattern;
  3892. });
  3893. }
  3894. tsParseTypeMemberSemicolon() {
  3895. if (!this.eat(types.comma)) {
  3896. this.semicolon();
  3897. }
  3898. }
  3899. tsParseSignatureMember(kind, node) {
  3900. this.tsFillSignature(types.colon, node);
  3901. this.tsParseTypeMemberSemicolon();
  3902. return this.finishNode(node, kind);
  3903. }
  3904. tsIsUnambiguouslyIndexSignature() {
  3905. this.next();
  3906. return this.eat(types.name) && this.match(types.colon);
  3907. }
  3908. tsTryParseIndexSignature(node) {
  3909. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  3910. return undefined;
  3911. }
  3912. this.expect(types.bracketL);
  3913. const id = this.parseIdentifier();
  3914. id.typeAnnotation = this.tsParseTypeAnnotation();
  3915. this.resetEndLocation(id);
  3916. this.expect(types.bracketR);
  3917. node.parameters = [id];
  3918. const type = this.tsTryParseTypeAnnotation();
  3919. if (type) node.typeAnnotation = type;
  3920. this.tsParseTypeMemberSemicolon();
  3921. return this.finishNode(node, "TSIndexSignature");
  3922. }
  3923. tsParsePropertyOrMethodSignature(node, readonly) {
  3924. if (this.eat(types.question)) node.optional = true;
  3925. const nodeAny = node;
  3926. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  3927. const method = nodeAny;
  3928. this.tsFillSignature(types.colon, method);
  3929. this.tsParseTypeMemberSemicolon();
  3930. return this.finishNode(method, "TSMethodSignature");
  3931. } else {
  3932. const property = nodeAny;
  3933. if (readonly) property.readonly = true;
  3934. const type = this.tsTryParseTypeAnnotation();
  3935. if (type) property.typeAnnotation = type;
  3936. this.tsParseTypeMemberSemicolon();
  3937. return this.finishNode(property, "TSPropertySignature");
  3938. }
  3939. }
  3940. tsParseTypeMember() {
  3941. const node = this.startNode();
  3942. if (this.match(types.parenL) || this.isRelational("<")) {
  3943. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  3944. }
  3945. if (this.match(types._new)) {
  3946. const id = this.startNode();
  3947. this.next();
  3948. if (this.match(types.parenL) || this.isRelational("<")) {
  3949. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  3950. } else {
  3951. node.key = this.createIdentifier(id, "new");
  3952. return this.tsParsePropertyOrMethodSignature(node, false);
  3953. }
  3954. }
  3955. const readonly = !!this.tsParseModifier(["readonly"]);
  3956. const idx = this.tsTryParseIndexSignature(node);
  3957. if (idx) {
  3958. if (readonly) node.readonly = true;
  3959. return idx;
  3960. }
  3961. this.parsePropertyName(node);
  3962. return this.tsParsePropertyOrMethodSignature(node, readonly);
  3963. }
  3964. tsParseTypeLiteral() {
  3965. const node = this.startNode();
  3966. node.members = this.tsParseObjectTypeMembers();
  3967. return this.finishNode(node, "TSTypeLiteral");
  3968. }
  3969. tsParseObjectTypeMembers() {
  3970. this.expect(types.braceL);
  3971. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  3972. this.expect(types.braceR);
  3973. return members;
  3974. }
  3975. tsIsStartOfMappedType() {
  3976. this.next();
  3977. if (this.eat(types.plusMin)) {
  3978. return this.isContextual("readonly");
  3979. }
  3980. if (this.isContextual("readonly")) {
  3981. this.next();
  3982. }
  3983. if (!this.match(types.bracketL)) {
  3984. return false;
  3985. }
  3986. this.next();
  3987. if (!this.tsIsIdentifier()) {
  3988. return false;
  3989. }
  3990. this.next();
  3991. return this.match(types._in);
  3992. }
  3993. tsParseMappedTypeParameter() {
  3994. const node = this.startNode();
  3995. node.name = this.parseIdentifierName(node.start);
  3996. node.constraint = this.tsExpectThenParseType(types._in);
  3997. return this.finishNode(node, "TSTypeParameter");
  3998. }
  3999. tsParseMappedType() {
  4000. const node = this.startNode();
  4001. this.expect(types.braceL);
  4002. if (this.match(types.plusMin)) {
  4003. node.readonly = this.state.value;
  4004. this.next();
  4005. this.expectContextual("readonly");
  4006. } else if (this.eatContextual("readonly")) {
  4007. node.readonly = true;
  4008. }
  4009. this.expect(types.bracketL);
  4010. node.typeParameter = this.tsParseMappedTypeParameter();
  4011. this.expect(types.bracketR);
  4012. if (this.match(types.plusMin)) {
  4013. node.optional = this.state.value;
  4014. this.next();
  4015. this.expect(types.question);
  4016. } else if (this.eat(types.question)) {
  4017. node.optional = true;
  4018. }
  4019. node.typeAnnotation = this.tsTryParseType();
  4020. this.semicolon();
  4021. this.expect(types.braceR);
  4022. return this.finishNode(node, "TSMappedType");
  4023. }
  4024. tsParseTupleType() {
  4025. const node = this.startNode();
  4026. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4027. let seenOptionalElement = false;
  4028. node.elementTypes.forEach(elementNode => {
  4029. if (elementNode.type === "TSOptionalType") {
  4030. seenOptionalElement = true;
  4031. } else if (seenOptionalElement && elementNode.type !== "TSRestType") {
  4032. this.raise(elementNode.start, "A required element cannot follow an optional element.");
  4033. }
  4034. });
  4035. return this.finishNode(node, "TSTupleType");
  4036. }
  4037. tsParseTupleElementType() {
  4038. if (this.match(types.ellipsis)) {
  4039. const restNode = this.startNode();
  4040. this.next();
  4041. restNode.typeAnnotation = this.tsParseType();
  4042. this.checkCommaAfterRest(93);
  4043. return this.finishNode(restNode, "TSRestType");
  4044. }
  4045. const type = this.tsParseType();
  4046. if (this.eat(types.question)) {
  4047. const optionalTypeNode = this.startNodeAtNode(type);
  4048. optionalTypeNode.typeAnnotation = type;
  4049. return this.finishNode(optionalTypeNode, "TSOptionalType");
  4050. }
  4051. return type;
  4052. }
  4053. tsParseParenthesizedType() {
  4054. const node = this.startNode();
  4055. this.expect(types.parenL);
  4056. node.typeAnnotation = this.tsParseType();
  4057. this.expect(types.parenR);
  4058. return this.finishNode(node, "TSParenthesizedType");
  4059. }
  4060. tsParseFunctionOrConstructorType(type) {
  4061. const node = this.startNode();
  4062. if (type === "TSConstructorType") {
  4063. this.expect(types._new);
  4064. }
  4065. this.tsFillSignature(types.arrow, node);
  4066. return this.finishNode(node, type);
  4067. }
  4068. tsParseLiteralTypeNode() {
  4069. const node = this.startNode();
  4070. node.literal = (() => {
  4071. switch (this.state.type) {
  4072. case types.num:
  4073. case types.string:
  4074. case types._true:
  4075. case types._false:
  4076. return this.parseExprAtom();
  4077. default:
  4078. throw this.unexpected();
  4079. }
  4080. })();
  4081. return this.finishNode(node, "TSLiteralType");
  4082. }
  4083. tsParseTemplateLiteralType() {
  4084. const node = this.startNode();
  4085. const templateNode = this.parseTemplate(false);
  4086. if (templateNode.expressions.length > 0) {
  4087. this.raise(templateNode.expressions[0].start, "Template literal types cannot have any substitution");
  4088. }
  4089. node.literal = templateNode;
  4090. return this.finishNode(node, "TSLiteralType");
  4091. }
  4092. tsParseThisTypeOrThisTypePredicate() {
  4093. const thisKeyword = this.tsParseThisTypeNode();
  4094. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4095. return this.tsParseThisTypePredicate(thisKeyword);
  4096. } else {
  4097. return thisKeyword;
  4098. }
  4099. }
  4100. tsParseNonArrayType() {
  4101. switch (this.state.type) {
  4102. case types.name:
  4103. case types._void:
  4104. case types._null:
  4105. {
  4106. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  4107. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  4108. const node = this.startNode();
  4109. this.next();
  4110. return this.finishNode(node, type);
  4111. }
  4112. return this.tsParseTypeReference();
  4113. }
  4114. case types.string:
  4115. case types.num:
  4116. case types._true:
  4117. case types._false:
  4118. return this.tsParseLiteralTypeNode();
  4119. case types.plusMin:
  4120. if (this.state.value === "-") {
  4121. const node = this.startNode();
  4122. if (this.lookahead().type !== types.num) {
  4123. throw this.unexpected();
  4124. }
  4125. node.literal = this.parseMaybeUnary();
  4126. return this.finishNode(node, "TSLiteralType");
  4127. }
  4128. break;
  4129. case types._this:
  4130. return this.tsParseThisTypeOrThisTypePredicate();
  4131. case types._typeof:
  4132. return this.tsParseTypeQuery();
  4133. case types._import:
  4134. return this.tsParseImportType();
  4135. case types.braceL:
  4136. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  4137. case types.bracketL:
  4138. return this.tsParseTupleType();
  4139. case types.parenL:
  4140. return this.tsParseParenthesizedType();
  4141. case types.backQuote:
  4142. return this.tsParseTemplateLiteralType();
  4143. }
  4144. throw this.unexpected();
  4145. }
  4146. tsParseArrayTypeOrHigher() {
  4147. let type = this.tsParseNonArrayType();
  4148. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  4149. if (this.match(types.bracketR)) {
  4150. const node = this.startNodeAtNode(type);
  4151. node.elementType = type;
  4152. this.expect(types.bracketR);
  4153. type = this.finishNode(node, "TSArrayType");
  4154. } else {
  4155. const node = this.startNodeAtNode(type);
  4156. node.objectType = type;
  4157. node.indexType = this.tsParseType();
  4158. this.expect(types.bracketR);
  4159. type = this.finishNode(node, "TSIndexedAccessType");
  4160. }
  4161. }
  4162. return type;
  4163. }
  4164. tsParseTypeOperator(operator) {
  4165. const node = this.startNode();
  4166. this.expectContextual(operator);
  4167. node.operator = operator;
  4168. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  4169. if (operator === "readonly") {
  4170. this.tsCheckTypeAnnotationForReadOnly(node);
  4171. }
  4172. return this.finishNode(node, "TSTypeOperator");
  4173. }
  4174. tsCheckTypeAnnotationForReadOnly(node) {
  4175. switch (node.typeAnnotation.type) {
  4176. case "TSTupleType":
  4177. case "TSArrayType":
  4178. return;
  4179. default:
  4180. this.raise(node.start, "'readonly' type modifier is only permitted on array and tuple literal types.");
  4181. }
  4182. }
  4183. tsParseInferType() {
  4184. const node = this.startNode();
  4185. this.expectContextual("infer");
  4186. const typeParameter = this.startNode();
  4187. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  4188. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  4189. return this.finishNode(node, "TSInferType");
  4190. }
  4191. tsParseTypeOperatorOrHigher() {
  4192. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  4193. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  4194. }
  4195. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  4196. this.eat(operator);
  4197. let type = parseConstituentType();
  4198. if (this.match(operator)) {
  4199. const types = [type];
  4200. while (this.eat(operator)) {
  4201. types.push(parseConstituentType());
  4202. }
  4203. const node = this.startNodeAtNode(type);
  4204. node.types = types;
  4205. type = this.finishNode(node, kind);
  4206. }
  4207. return type;
  4208. }
  4209. tsParseIntersectionTypeOrHigher() {
  4210. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  4211. }
  4212. tsParseUnionTypeOrHigher() {
  4213. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  4214. }
  4215. tsIsStartOfFunctionType() {
  4216. if (this.isRelational("<")) {
  4217. return true;
  4218. }
  4219. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  4220. }
  4221. tsSkipParameterStart() {
  4222. if (this.match(types.name) || this.match(types._this)) {
  4223. this.next();
  4224. return true;
  4225. }
  4226. if (this.match(types.braceL)) {
  4227. let braceStackCounter = 1;
  4228. this.next();
  4229. while (braceStackCounter > 0) {
  4230. if (this.match(types.braceL)) {
  4231. ++braceStackCounter;
  4232. } else if (this.match(types.braceR)) {
  4233. --braceStackCounter;
  4234. }
  4235. this.next();
  4236. }
  4237. return true;
  4238. }
  4239. if (this.match(types.bracketL)) {
  4240. let braceStackCounter = 1;
  4241. this.next();
  4242. while (braceStackCounter > 0) {
  4243. if (this.match(types.bracketL)) {
  4244. ++braceStackCounter;
  4245. } else if (this.match(types.bracketR)) {
  4246. --braceStackCounter;
  4247. }
  4248. this.next();
  4249. }
  4250. return true;
  4251. }
  4252. return false;
  4253. }
  4254. tsIsUnambiguouslyStartOfFunctionType() {
  4255. this.next();
  4256. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  4257. return true;
  4258. }
  4259. if (this.tsSkipParameterStart()) {
  4260. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  4261. return true;
  4262. }
  4263. if (this.match(types.parenR)) {
  4264. this.next();
  4265. if (this.match(types.arrow)) {
  4266. return true;
  4267. }
  4268. }
  4269. }
  4270. return false;
  4271. }
  4272. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  4273. return this.tsInType(() => {
  4274. const t = this.startNode();
  4275. this.expect(returnToken);
  4276. const asserts = this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  4277. if (asserts && this.match(types._this)) {
  4278. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  4279. if (thisTypePredicate.type === "TSThisType") {
  4280. const node = this.startNodeAtNode(t);
  4281. node.parameterName = thisTypePredicate;
  4282. node.asserts = true;
  4283. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  4284. } else {
  4285. thisTypePredicate.asserts = true;
  4286. }
  4287. t.typeAnnotation = thisTypePredicate;
  4288. return this.finishNode(t, "TSTypeAnnotation");
  4289. }
  4290. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  4291. if (!typePredicateVariable) {
  4292. if (!asserts) {
  4293. return this.tsParseTypeAnnotation(false, t);
  4294. }
  4295. const node = this.startNodeAtNode(t);
  4296. node.parameterName = this.parseIdentifier();
  4297. node.asserts = asserts;
  4298. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4299. return this.finishNode(t, "TSTypeAnnotation");
  4300. }
  4301. const type = this.tsParseTypeAnnotation(false);
  4302. const node = this.startNodeAtNode(t);
  4303. node.parameterName = typePredicateVariable;
  4304. node.typeAnnotation = type;
  4305. node.asserts = asserts;
  4306. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4307. return this.finishNode(t, "TSTypeAnnotation");
  4308. });
  4309. }
  4310. tsTryParseTypeOrTypePredicateAnnotation() {
  4311. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  4312. }
  4313. tsTryParseTypeAnnotation() {
  4314. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  4315. }
  4316. tsTryParseType() {
  4317. return this.tsEatThenParseType(types.colon);
  4318. }
  4319. tsParseTypePredicatePrefix() {
  4320. const id = this.parseIdentifier();
  4321. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4322. this.next();
  4323. return id;
  4324. }
  4325. }
  4326. tsParseTypePredicateAsserts() {
  4327. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  4328. return false;
  4329. }
  4330. const containsEsc = this.state.containsEsc;
  4331. this.next();
  4332. if (!this.match(types.name) && !this.match(types._this)) {
  4333. return false;
  4334. }
  4335. if (containsEsc) {
  4336. this.raise(this.state.lastTokStart, "Escape sequence in keyword asserts");
  4337. }
  4338. return true;
  4339. }
  4340. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  4341. this.tsInType(() => {
  4342. if (eatColon) this.expect(types.colon);
  4343. t.typeAnnotation = this.tsParseType();
  4344. });
  4345. return this.finishNode(t, "TSTypeAnnotation");
  4346. }
  4347. tsParseType() {
  4348. assert(this.state.inType);
  4349. const type = this.tsParseNonConditionalType();
  4350. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  4351. return type;
  4352. }
  4353. const node = this.startNodeAtNode(type);
  4354. node.checkType = type;
  4355. node.extendsType = this.tsParseNonConditionalType();
  4356. this.expect(types.question);
  4357. node.trueType = this.tsParseType();
  4358. this.expect(types.colon);
  4359. node.falseType = this.tsParseType();
  4360. return this.finishNode(node, "TSConditionalType");
  4361. }
  4362. tsParseNonConditionalType() {
  4363. if (this.tsIsStartOfFunctionType()) {
  4364. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  4365. }
  4366. if (this.match(types._new)) {
  4367. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  4368. }
  4369. return this.tsParseUnionTypeOrHigher();
  4370. }
  4371. tsParseTypeAssertion() {
  4372. const node = this.startNode();
  4373. const _const = this.tsTryNextParseConstantContext();
  4374. node.typeAnnotation = _const || this.tsNextThenParseType();
  4375. this.expectRelational(">");
  4376. node.expression = this.parseMaybeUnary();
  4377. return this.finishNode(node, "TSTypeAssertion");
  4378. }
  4379. tsParseHeritageClause(descriptor) {
  4380. const originalStart = this.state.start;
  4381. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  4382. if (!delimitedList.length) {
  4383. this.raise(originalStart, `'${descriptor}' list cannot be empty.`);
  4384. }
  4385. return delimitedList;
  4386. }
  4387. tsParseExpressionWithTypeArguments() {
  4388. const node = this.startNode();
  4389. node.expression = this.tsParseEntityName(false);
  4390. if (this.isRelational("<")) {
  4391. node.typeParameters = this.tsParseTypeArguments();
  4392. }
  4393. return this.finishNode(node, "TSExpressionWithTypeArguments");
  4394. }
  4395. tsParseInterfaceDeclaration(node) {
  4396. node.id = this.parseIdentifier();
  4397. this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration");
  4398. node.typeParameters = this.tsTryParseTypeParameters();
  4399. if (this.eat(types._extends)) {
  4400. node.extends = this.tsParseHeritageClause("extends");
  4401. }
  4402. const body = this.startNode();
  4403. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  4404. node.body = this.finishNode(body, "TSInterfaceBody");
  4405. return this.finishNode(node, "TSInterfaceDeclaration");
  4406. }
  4407. tsParseTypeAliasDeclaration(node) {
  4408. node.id = this.parseIdentifier();
  4409. this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias");
  4410. node.typeParameters = this.tsTryParseTypeParameters();
  4411. node.typeAnnotation = this.tsExpectThenParseType(types.eq);
  4412. this.semicolon();
  4413. return this.finishNode(node, "TSTypeAliasDeclaration");
  4414. }
  4415. tsInNoContext(cb) {
  4416. const oldContext = this.state.context;
  4417. this.state.context = [oldContext[0]];
  4418. try {
  4419. return cb();
  4420. } finally {
  4421. this.state.context = oldContext;
  4422. }
  4423. }
  4424. tsInType(cb) {
  4425. const oldInType = this.state.inType;
  4426. this.state.inType = true;
  4427. try {
  4428. return cb();
  4429. } finally {
  4430. this.state.inType = oldInType;
  4431. }
  4432. }
  4433. tsEatThenParseType(token) {
  4434. return !this.match(token) ? undefined : this.tsNextThenParseType();
  4435. }
  4436. tsExpectThenParseType(token) {
  4437. return this.tsDoThenParseType(() => this.expect(token));
  4438. }
  4439. tsNextThenParseType() {
  4440. return this.tsDoThenParseType(() => this.next());
  4441. }
  4442. tsDoThenParseType(cb) {
  4443. return this.tsInType(() => {
  4444. cb();
  4445. return this.tsParseType();
  4446. });
  4447. }
  4448. tsParseEnumMember() {
  4449. const node = this.startNode();
  4450. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  4451. if (this.eat(types.eq)) {
  4452. node.initializer = this.parseMaybeAssign();
  4453. }
  4454. return this.finishNode(node, "TSEnumMember");
  4455. }
  4456. tsParseEnumDeclaration(node, isConst) {
  4457. if (isConst) node.const = true;
  4458. node.id = this.parseIdentifier();
  4459. this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration");
  4460. this.expect(types.braceL);
  4461. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  4462. this.expect(types.braceR);
  4463. return this.finishNode(node, "TSEnumDeclaration");
  4464. }
  4465. tsParseModuleBlock() {
  4466. const node = this.startNode();
  4467. this.scope.enter(SCOPE_OTHER);
  4468. this.expect(types.braceL);
  4469. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  4470. this.scope.exit();
  4471. return this.finishNode(node, "TSModuleBlock");
  4472. }
  4473. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  4474. node.id = this.parseIdentifier();
  4475. if (!nested) {
  4476. this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration");
  4477. }
  4478. if (this.eat(types.dot)) {
  4479. const inner = this.startNode();
  4480. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  4481. node.body = inner;
  4482. } else {
  4483. this.scope.enter(SCOPE_TS_MODULE);
  4484. node.body = this.tsParseModuleBlock();
  4485. this.scope.exit();
  4486. }
  4487. return this.finishNode(node, "TSModuleDeclaration");
  4488. }
  4489. tsParseAmbientExternalModuleDeclaration(node) {
  4490. if (this.isContextual("global")) {
  4491. node.global = true;
  4492. node.id = this.parseIdentifier();
  4493. } else if (this.match(types.string)) {
  4494. node.id = this.parseExprAtom();
  4495. } else {
  4496. this.unexpected();
  4497. }
  4498. if (this.match(types.braceL)) {
  4499. this.scope.enter(SCOPE_TS_MODULE);
  4500. node.body = this.tsParseModuleBlock();
  4501. this.scope.exit();
  4502. } else {
  4503. this.semicolon();
  4504. }
  4505. return this.finishNode(node, "TSModuleDeclaration");
  4506. }
  4507. tsParseImportEqualsDeclaration(node, isExport) {
  4508. node.isExport = isExport || false;
  4509. node.id = this.parseIdentifier();
  4510. this.checkLVal(node.id, BIND_LEXICAL, undefined, "import equals declaration");
  4511. this.expect(types.eq);
  4512. node.moduleReference = this.tsParseModuleReference();
  4513. this.semicolon();
  4514. return this.finishNode(node, "TSImportEqualsDeclaration");
  4515. }
  4516. tsIsExternalModuleReference() {
  4517. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  4518. }
  4519. tsParseModuleReference() {
  4520. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  4521. }
  4522. tsParseExternalModuleReference() {
  4523. const node = this.startNode();
  4524. this.expectContextual("require");
  4525. this.expect(types.parenL);
  4526. if (!this.match(types.string)) {
  4527. throw this.unexpected();
  4528. }
  4529. node.expression = this.parseExprAtom();
  4530. this.expect(types.parenR);
  4531. return this.finishNode(node, "TSExternalModuleReference");
  4532. }
  4533. tsLookAhead(f) {
  4534. const state = this.state.clone();
  4535. const res = f();
  4536. this.state = state;
  4537. return res;
  4538. }
  4539. tsTryParseAndCatch(f) {
  4540. const result = this.tryParse(abort => f() || abort());
  4541. if (result.aborted || !result.node) return undefined;
  4542. if (result.error) this.state = result.failState;
  4543. return result.node;
  4544. }
  4545. tsTryParse(f) {
  4546. const state = this.state.clone();
  4547. const result = f();
  4548. if (result !== undefined && result !== false) {
  4549. return result;
  4550. } else {
  4551. this.state = state;
  4552. return undefined;
  4553. }
  4554. }
  4555. tsTryParseDeclare(nany) {
  4556. if (this.isLineTerminator()) {
  4557. return;
  4558. }
  4559. let starttype = this.state.type;
  4560. let kind;
  4561. if (this.isContextual("let")) {
  4562. starttype = types._var;
  4563. kind = "let";
  4564. }
  4565. switch (starttype) {
  4566. case types._function:
  4567. return this.parseFunctionStatement(nany, false, true);
  4568. case types._class:
  4569. nany.declare = true;
  4570. return this.parseClass(nany, true, false);
  4571. case types._const:
  4572. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  4573. this.expect(types._const);
  4574. this.expectContextual("enum");
  4575. return this.tsParseEnumDeclaration(nany, true);
  4576. }
  4577. case types._var:
  4578. kind = kind || this.state.value;
  4579. return this.parseVarStatement(nany, kind);
  4580. case types.name:
  4581. {
  4582. const value = this.state.value;
  4583. if (value === "global") {
  4584. return this.tsParseAmbientExternalModuleDeclaration(nany);
  4585. } else {
  4586. return this.tsParseDeclaration(nany, value, true);
  4587. }
  4588. }
  4589. }
  4590. }
  4591. tsTryParseExportDeclaration() {
  4592. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  4593. }
  4594. tsParseExpressionStatement(node, expr) {
  4595. switch (expr.name) {
  4596. case "declare":
  4597. {
  4598. const declaration = this.tsTryParseDeclare(node);
  4599. if (declaration) {
  4600. declaration.declare = true;
  4601. return declaration;
  4602. }
  4603. break;
  4604. }
  4605. case "global":
  4606. if (this.match(types.braceL)) {
  4607. this.scope.enter(SCOPE_TS_MODULE);
  4608. const mod = node;
  4609. mod.global = true;
  4610. mod.id = expr;
  4611. mod.body = this.tsParseModuleBlock();
  4612. this.scope.exit();
  4613. return this.finishNode(mod, "TSModuleDeclaration");
  4614. }
  4615. break;
  4616. default:
  4617. return this.tsParseDeclaration(node, expr.name, false);
  4618. }
  4619. }
  4620. tsParseDeclaration(node, value, next) {
  4621. switch (value) {
  4622. case "abstract":
  4623. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  4624. const cls = node;
  4625. cls.abstract = true;
  4626. if (next) {
  4627. this.next();
  4628. if (!this.match(types._class)) {
  4629. this.unexpected(null, types._class);
  4630. }
  4631. }
  4632. return this.parseClass(cls, true, false);
  4633. }
  4634. break;
  4635. case "enum":
  4636. if (next || this.match(types.name)) {
  4637. if (next) this.next();
  4638. return this.tsParseEnumDeclaration(node, false);
  4639. }
  4640. break;
  4641. case "interface":
  4642. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4643. if (next) this.next();
  4644. return this.tsParseInterfaceDeclaration(node);
  4645. }
  4646. break;
  4647. case "module":
  4648. if (next) this.next();
  4649. if (this.match(types.string)) {
  4650. return this.tsParseAmbientExternalModuleDeclaration(node);
  4651. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4652. return this.tsParseModuleOrNamespaceDeclaration(node);
  4653. }
  4654. break;
  4655. case "namespace":
  4656. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4657. if (next) this.next();
  4658. return this.tsParseModuleOrNamespaceDeclaration(node);
  4659. }
  4660. break;
  4661. case "type":
  4662. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4663. if (next) this.next();
  4664. return this.tsParseTypeAliasDeclaration(node);
  4665. }
  4666. break;
  4667. }
  4668. }
  4669. tsCheckLineTerminatorAndMatch(tokenType, next) {
  4670. return (next || this.match(tokenType)) && !this.isLineTerminator();
  4671. }
  4672. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  4673. if (!this.isRelational("<")) {
  4674. return undefined;
  4675. }
  4676. const res = this.tsTryParseAndCatch(() => {
  4677. const node = this.startNodeAt(startPos, startLoc);
  4678. node.typeParameters = this.tsParseTypeParameters();
  4679. super.parseFunctionParams(node);
  4680. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  4681. this.expect(types.arrow);
  4682. return node;
  4683. });
  4684. if (!res) {
  4685. return undefined;
  4686. }
  4687. return this.parseArrowExpression(res, null, true);
  4688. }
  4689. tsParseTypeArguments() {
  4690. const node = this.startNode();
  4691. node.params = this.tsInType(() => this.tsInNoContext(() => {
  4692. this.expectRelational("<");
  4693. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  4694. }));
  4695. this.state.exprAllowed = false;
  4696. this.expectRelational(">");
  4697. return this.finishNode(node, "TSTypeParameterInstantiation");
  4698. }
  4699. tsIsDeclarationStart() {
  4700. if (this.match(types.name)) {
  4701. switch (this.state.value) {
  4702. case "abstract":
  4703. case "declare":
  4704. case "enum":
  4705. case "interface":
  4706. case "module":
  4707. case "namespace":
  4708. case "type":
  4709. return true;
  4710. }
  4711. }
  4712. return false;
  4713. }
  4714. isExportDefaultSpecifier() {
  4715. if (this.tsIsDeclarationStart()) return false;
  4716. return super.isExportDefaultSpecifier();
  4717. }
  4718. parseAssignableListItem(allowModifiers, decorators) {
  4719. const startPos = this.state.start;
  4720. const startLoc = this.state.startLoc;
  4721. let accessibility;
  4722. let readonly = false;
  4723. if (allowModifiers) {
  4724. accessibility = this.parseAccessModifier();
  4725. readonly = !!this.tsParseModifier(["readonly"]);
  4726. }
  4727. const left = this.parseMaybeDefault();
  4728. this.parseAssignableListItemTypes(left);
  4729. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  4730. if (accessibility || readonly) {
  4731. const pp = this.startNodeAt(startPos, startLoc);
  4732. if (decorators.length) {
  4733. pp.decorators = decorators;
  4734. }
  4735. if (accessibility) pp.accessibility = accessibility;
  4736. if (readonly) pp.readonly = readonly;
  4737. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  4738. this.raise(pp.start, "A parameter property may not be declared using a binding pattern.");
  4739. }
  4740. pp.parameter = elt;
  4741. return this.finishNode(pp, "TSParameterProperty");
  4742. }
  4743. if (decorators.length) {
  4744. left.decorators = decorators;
  4745. }
  4746. return elt;
  4747. }
  4748. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  4749. if (this.match(types.colon)) {
  4750. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  4751. }
  4752. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  4753. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  4754. this.finishNode(node, bodilessType);
  4755. return;
  4756. }
  4757. super.parseFunctionBodyAndFinish(node, type, isMethod);
  4758. }
  4759. registerFunctionStatementId(node) {
  4760. if (!node.body && node.id) {
  4761. this.checkLVal(node.id, BIND_TS_AMBIENT, null, "function name");
  4762. } else {
  4763. super.registerFunctionStatementId(...arguments);
  4764. }
  4765. }
  4766. parseSubscript(base, startPos, startLoc, noCalls, state) {
  4767. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  4768. this.state.exprAllowed = false;
  4769. this.next();
  4770. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  4771. nonNullExpression.expression = base;
  4772. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  4773. }
  4774. if (this.isRelational("<")) {
  4775. const result = this.tsTryParseAndCatch(() => {
  4776. if (!noCalls && this.atPossibleAsync(base)) {
  4777. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  4778. if (asyncArrowFn) {
  4779. return asyncArrowFn;
  4780. }
  4781. }
  4782. const node = this.startNodeAt(startPos, startLoc);
  4783. node.callee = base;
  4784. const typeArguments = this.tsParseTypeArguments();
  4785. if (typeArguments) {
  4786. if (!noCalls && this.eat(types.parenL)) {
  4787. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  4788. node.typeParameters = typeArguments;
  4789. return this.finishCallExpression(node, state.optionalChainMember);
  4790. } else if (this.match(types.backQuote)) {
  4791. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments);
  4792. }
  4793. }
  4794. this.unexpected();
  4795. });
  4796. if (result) return result;
  4797. }
  4798. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  4799. }
  4800. parseNewArguments(node) {
  4801. if (this.isRelational("<")) {
  4802. const typeParameters = this.tsTryParseAndCatch(() => {
  4803. const args = this.tsParseTypeArguments();
  4804. if (!this.match(types.parenL)) this.unexpected();
  4805. return args;
  4806. });
  4807. if (typeParameters) {
  4808. node.typeParameters = typeParameters;
  4809. }
  4810. }
  4811. super.parseNewArguments(node);
  4812. }
  4813. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  4814. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  4815. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  4816. node.expression = left;
  4817. const _const = this.tsTryNextParseConstantContext();
  4818. if (_const) {
  4819. node.typeAnnotation = _const;
  4820. } else {
  4821. node.typeAnnotation = this.tsNextThenParseType();
  4822. }
  4823. this.finishNode(node, "TSAsExpression");
  4824. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  4825. }
  4826. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn);
  4827. }
  4828. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  4829. checkDuplicateExports() {}
  4830. parseImport(node) {
  4831. if (this.match(types.name) && this.lookahead().type === types.eq) {
  4832. return this.tsParseImportEqualsDeclaration(node);
  4833. }
  4834. return super.parseImport(node);
  4835. }
  4836. parseExport(node) {
  4837. if (this.match(types._import)) {
  4838. this.expect(types._import);
  4839. return this.tsParseImportEqualsDeclaration(node, true);
  4840. } else if (this.eat(types.eq)) {
  4841. const assign = node;
  4842. assign.expression = this.parseExpression();
  4843. this.semicolon();
  4844. return this.finishNode(assign, "TSExportAssignment");
  4845. } else if (this.eatContextual("as")) {
  4846. const decl = node;
  4847. this.expectContextual("namespace");
  4848. decl.id = this.parseIdentifier();
  4849. this.semicolon();
  4850. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  4851. } else {
  4852. return super.parseExport(node);
  4853. }
  4854. }
  4855. isAbstractClass() {
  4856. return this.isContextual("abstract") && this.lookahead().type === types._class;
  4857. }
  4858. parseExportDefaultExpression() {
  4859. if (this.isAbstractClass()) {
  4860. const cls = this.startNode();
  4861. this.next();
  4862. this.parseClass(cls, true, true);
  4863. cls.abstract = true;
  4864. return cls;
  4865. }
  4866. if (this.state.value === "interface") {
  4867. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  4868. if (result) return result;
  4869. }
  4870. return super.parseExportDefaultExpression();
  4871. }
  4872. parseStatementContent(context, topLevel) {
  4873. if (this.state.type === types._const) {
  4874. const ahead = this.lookahead();
  4875. if (ahead.type === types.name && ahead.value === "enum") {
  4876. const node = this.startNode();
  4877. this.expect(types._const);
  4878. this.expectContextual("enum");
  4879. return this.tsParseEnumDeclaration(node, true);
  4880. }
  4881. }
  4882. return super.parseStatementContent(context, topLevel);
  4883. }
  4884. parseAccessModifier() {
  4885. return this.tsParseModifier(["public", "protected", "private"]);
  4886. }
  4887. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  4888. const accessibility = this.parseAccessModifier();
  4889. if (accessibility) member.accessibility = accessibility;
  4890. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  4891. }
  4892. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  4893. const modifiers = this.tsParseModifiers(["abstract", "readonly", "declare"]);
  4894. Object.assign(member, modifiers);
  4895. const idx = this.tsTryParseIndexSignature(member);
  4896. if (idx) {
  4897. classBody.body.push(idx);
  4898. if (modifiers.abstract) {
  4899. this.raise(member.start, "Index signatures cannot have the 'abstract' modifier");
  4900. }
  4901. if (isStatic) {
  4902. this.raise(member.start, "Index signatures cannot have the 'static' modifier");
  4903. }
  4904. if (member.accessibility) {
  4905. this.raise(member.start, `Index signatures cannot have an accessibility modifier ('${member.accessibility}')`);
  4906. }
  4907. return;
  4908. }
  4909. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  4910. }
  4911. parsePostMemberNameModifiers(methodOrProp) {
  4912. const optional = this.eat(types.question);
  4913. if (optional) methodOrProp.optional = true;
  4914. if (methodOrProp.readonly && this.match(types.parenL)) {
  4915. this.raise(methodOrProp.start, "Class methods cannot have the 'readonly' modifier");
  4916. }
  4917. if (methodOrProp.declare && this.match(types.parenL)) {
  4918. this.raise(methodOrProp.start, "Class methods cannot have the 'declare' modifier");
  4919. }
  4920. }
  4921. parseExpressionStatement(node, expr) {
  4922. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  4923. return decl || super.parseExpressionStatement(node, expr);
  4924. }
  4925. shouldParseExportDeclaration() {
  4926. if (this.tsIsDeclarationStart()) return true;
  4927. return super.shouldParseExportDeclaration();
  4928. }
  4929. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  4930. if (!refNeedsArrowPos || !this.match(types.question)) {
  4931. return super.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  4932. }
  4933. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  4934. if (!result.node) {
  4935. refNeedsArrowPos.start = result.error.pos || this.state.start;
  4936. return expr;
  4937. }
  4938. if (result.error) this.state = result.failState;
  4939. return result.node;
  4940. }
  4941. parseParenItem(node, startPos, startLoc) {
  4942. node = super.parseParenItem(node, startPos, startLoc);
  4943. if (this.eat(types.question)) {
  4944. node.optional = true;
  4945. this.resetEndLocation(node);
  4946. }
  4947. if (this.match(types.colon)) {
  4948. const typeCastNode = this.startNodeAt(startPos, startLoc);
  4949. typeCastNode.expression = node;
  4950. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  4951. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  4952. }
  4953. return node;
  4954. }
  4955. parseExportDeclaration(node) {
  4956. const startPos = this.state.start;
  4957. const startLoc = this.state.startLoc;
  4958. const isDeclare = this.eatContextual("declare");
  4959. let declaration;
  4960. if (this.match(types.name)) {
  4961. declaration = this.tsTryParseExportDeclaration();
  4962. }
  4963. if (!declaration) {
  4964. declaration = super.parseExportDeclaration(node);
  4965. }
  4966. if (declaration && isDeclare) {
  4967. this.resetStartLocation(declaration, startPos, startLoc);
  4968. declaration.declare = true;
  4969. }
  4970. return declaration;
  4971. }
  4972. parseClassId(node, isStatement, optionalId) {
  4973. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  4974. return;
  4975. }
  4976. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  4977. const typeParameters = this.tsTryParseTypeParameters();
  4978. if (typeParameters) node.typeParameters = typeParameters;
  4979. }
  4980. parseClassPropertyAnnotation(node) {
  4981. if (!node.optional && this.eat(types.bang)) {
  4982. node.definite = true;
  4983. }
  4984. const type = this.tsTryParseTypeAnnotation();
  4985. if (type) node.typeAnnotation = type;
  4986. }
  4987. parseClassProperty(node) {
  4988. this.parseClassPropertyAnnotation(node);
  4989. if (node.declare && this.match(types.equal)) {
  4990. this.raise(this.state.start, "'declare' class fields cannot have an initializer");
  4991. }
  4992. return super.parseClassProperty(node);
  4993. }
  4994. parseClassPrivateProperty(node) {
  4995. if (node.abstract) {
  4996. this.raise(node.start, "Private elements cannot have the 'abstract' modifier.");
  4997. }
  4998. if (node.accessibility) {
  4999. this.raise(node.start, `Private elements cannot have an accessibility modifier ('${node.accessibility}')`);
  5000. }
  5001. this.parseClassPropertyAnnotation(node);
  5002. return super.parseClassPrivateProperty(node);
  5003. }
  5004. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5005. const typeParameters = this.tsTryParseTypeParameters();
  5006. if (typeParameters) method.typeParameters = typeParameters;
  5007. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5008. }
  5009. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5010. const typeParameters = this.tsTryParseTypeParameters();
  5011. if (typeParameters) method.typeParameters = typeParameters;
  5012. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5013. }
  5014. parseClassSuper(node) {
  5015. super.parseClassSuper(node);
  5016. if (node.superClass && this.isRelational("<")) {
  5017. node.superTypeParameters = this.tsParseTypeArguments();
  5018. }
  5019. if (this.eatContextual("implements")) {
  5020. node.implements = this.tsParseHeritageClause("implements");
  5021. }
  5022. }
  5023. parseObjPropValue(prop, ...args) {
  5024. const typeParameters = this.tsTryParseTypeParameters();
  5025. if (typeParameters) prop.typeParameters = typeParameters;
  5026. super.parseObjPropValue(prop, ...args);
  5027. }
  5028. parseFunctionParams(node, allowModifiers) {
  5029. const typeParameters = this.tsTryParseTypeParameters();
  5030. if (typeParameters) node.typeParameters = typeParameters;
  5031. super.parseFunctionParams(node, allowModifiers);
  5032. }
  5033. parseVarId(decl, kind) {
  5034. super.parseVarId(decl, kind);
  5035. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  5036. decl.definite = true;
  5037. }
  5038. const type = this.tsTryParseTypeAnnotation();
  5039. if (type) {
  5040. decl.id.typeAnnotation = type;
  5041. this.resetEndLocation(decl.id);
  5042. }
  5043. }
  5044. parseAsyncArrowFromCallExpression(node, call) {
  5045. if (this.match(types.colon)) {
  5046. node.returnType = this.tsParseTypeAnnotation();
  5047. }
  5048. return super.parseAsyncArrowFromCallExpression(node, call);
  5049. }
  5050. parseMaybeAssign(...args) {
  5051. let state;
  5052. let jsx;
  5053. let typeCast;
  5054. if (this.match(types.jsxTagStart)) {
  5055. state = this.state.clone();
  5056. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5057. if (!jsx.error) return jsx.node;
  5058. const {
  5059. context
  5060. } = this.state;
  5061. if (context[context.length - 1] === types$1.j_oTag) {
  5062. context.length -= 2;
  5063. } else if (context[context.length - 1] === types$1.j_expr) {
  5064. context.length -= 1;
  5065. }
  5066. }
  5067. if (!(jsx && jsx.error) && !this.isRelational("<")) {
  5068. return super.parseMaybeAssign(...args);
  5069. }
  5070. let typeParameters;
  5071. state = state || this.state.clone();
  5072. const arrow = this.tryParse(abort => {
  5073. typeParameters = this.tsParseTypeParameters();
  5074. const expr = super.parseMaybeAssign(...args);
  5075. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  5076. abort();
  5077. }
  5078. if (typeParameters && typeParameters.params.length !== 0) {
  5079. this.resetStartLocationFromNode(expr, typeParameters);
  5080. }
  5081. expr.typeParameters = typeParameters;
  5082. return expr;
  5083. }, state);
  5084. if (!arrow.error && !arrow.aborted) return arrow.node;
  5085. if (!jsx) {
  5086. assert(!this.hasPlugin("jsx"));
  5087. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5088. if (!typeCast.error) return typeCast.node;
  5089. }
  5090. if (jsx && jsx.node) {
  5091. this.state = jsx.failState;
  5092. return jsx.node;
  5093. }
  5094. if (arrow.node) {
  5095. this.state = arrow.failState;
  5096. return arrow.node;
  5097. }
  5098. if (typeCast && typeCast.node) {
  5099. this.state = typeCast.failState;
  5100. return typeCast.node;
  5101. }
  5102. if (jsx && jsx.thrown) throw jsx.error;
  5103. if (arrow.thrown) throw arrow.error;
  5104. if (typeCast && typeCast.thrown) throw typeCast.error;
  5105. throw jsx && jsx.error || arrow.error || typeCast && typeCast.error;
  5106. }
  5107. parseMaybeUnary(refShorthandDefaultPos) {
  5108. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  5109. return this.tsParseTypeAssertion();
  5110. } else {
  5111. return super.parseMaybeUnary(refShorthandDefaultPos);
  5112. }
  5113. }
  5114. parseArrow(node) {
  5115. if (this.match(types.colon)) {
  5116. const result = this.tryParse(abort => {
  5117. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5118. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  5119. return returnType;
  5120. });
  5121. if (result.aborted) return;
  5122. if (!result.thrown) {
  5123. if (result.error) this.state = result.failState;
  5124. node.returnType = result.node;
  5125. }
  5126. }
  5127. return super.parseArrow(node);
  5128. }
  5129. parseAssignableListItemTypes(param) {
  5130. if (this.eat(types.question)) {
  5131. if (param.type !== "Identifier") {
  5132. this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature.");
  5133. }
  5134. param.optional = true;
  5135. }
  5136. const type = this.tsTryParseTypeAnnotation();
  5137. if (type) param.typeAnnotation = type;
  5138. this.resetEndLocation(param);
  5139. return param;
  5140. }
  5141. toAssignable(node, isBinding, contextDescription) {
  5142. switch (node.type) {
  5143. case "TSTypeCastExpression":
  5144. return super.toAssignable(this.typeCastToParameter(node), isBinding, contextDescription);
  5145. case "TSParameterProperty":
  5146. return super.toAssignable(node, isBinding, contextDescription);
  5147. case "TSAsExpression":
  5148. case "TSNonNullExpression":
  5149. case "TSTypeAssertion":
  5150. node.expression = this.toAssignable(node.expression, isBinding, contextDescription);
  5151. return node;
  5152. default:
  5153. return super.toAssignable(node, isBinding, contextDescription);
  5154. }
  5155. }
  5156. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  5157. switch (expr.type) {
  5158. case "TSTypeCastExpression":
  5159. return;
  5160. case "TSParameterProperty":
  5161. this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property");
  5162. return;
  5163. case "TSAsExpression":
  5164. case "TSNonNullExpression":
  5165. case "TSTypeAssertion":
  5166. this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription);
  5167. return;
  5168. default:
  5169. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  5170. return;
  5171. }
  5172. }
  5173. parseBindingAtom() {
  5174. switch (this.state.type) {
  5175. case types._this:
  5176. return this.parseIdentifier(true);
  5177. default:
  5178. return super.parseBindingAtom();
  5179. }
  5180. }
  5181. parseMaybeDecoratorArguments(expr) {
  5182. if (this.isRelational("<")) {
  5183. const typeArguments = this.tsParseTypeArguments();
  5184. if (this.match(types.parenL)) {
  5185. const call = super.parseMaybeDecoratorArguments(expr);
  5186. call.typeParameters = typeArguments;
  5187. return call;
  5188. }
  5189. this.unexpected(this.state.start, types.parenL);
  5190. }
  5191. return super.parseMaybeDecoratorArguments(expr);
  5192. }
  5193. isClassMethod() {
  5194. return this.isRelational("<") || super.isClassMethod();
  5195. }
  5196. isClassProperty() {
  5197. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  5198. }
  5199. parseMaybeDefault(...args) {
  5200. const node = super.parseMaybeDefault(...args);
  5201. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5202. this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`");
  5203. }
  5204. return node;
  5205. }
  5206. getTokenFromCode(code) {
  5207. if (this.state.inType && (code === 62 || code === 60)) {
  5208. return this.finishOp(types.relational, 1);
  5209. } else {
  5210. return super.getTokenFromCode(code);
  5211. }
  5212. }
  5213. toAssignableList(exprList, isBinding) {
  5214. for (let i = 0; i < exprList.length; i++) {
  5215. const expr = exprList[i];
  5216. if (!expr) continue;
  5217. switch (expr.type) {
  5218. case "TSTypeCastExpression":
  5219. exprList[i] = this.typeCastToParameter(expr);
  5220. break;
  5221. case "TSAsExpression":
  5222. case "TSTypeAssertion":
  5223. if (!isBinding) {
  5224. exprList[i] = this.typeCastToParameter(expr);
  5225. } else {
  5226. this.raise(expr.start, "Unexpected type cast in parameter position.");
  5227. }
  5228. break;
  5229. }
  5230. }
  5231. return super.toAssignableList(...arguments);
  5232. }
  5233. typeCastToParameter(node) {
  5234. node.expression.typeAnnotation = node.typeAnnotation;
  5235. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5236. return node.expression;
  5237. }
  5238. toReferencedList(exprList, isInParens) {
  5239. for (let i = 0; i < exprList.length; i++) {
  5240. const expr = exprList[i];
  5241. if (expr && expr._exprListItem && expr.type === "TsTypeCastExpression") {
  5242. this.raise(expr.start, "Did not expect a type annotation here.");
  5243. }
  5244. }
  5245. return exprList;
  5246. }
  5247. shouldParseArrow() {
  5248. return this.match(types.colon) || super.shouldParseArrow();
  5249. }
  5250. shouldParseAsyncArrow() {
  5251. return this.match(types.colon) || super.shouldParseAsyncArrow();
  5252. }
  5253. canHaveLeadingDecorator() {
  5254. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  5255. }
  5256. jsxParseOpeningElementAfterName(node) {
  5257. if (this.isRelational("<")) {
  5258. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  5259. if (typeArguments) node.typeParameters = typeArguments;
  5260. }
  5261. return super.jsxParseOpeningElementAfterName(node);
  5262. }
  5263. getGetterSetterExpectedParamCount(method) {
  5264. const baseCount = super.getGetterSetterExpectedParamCount(method);
  5265. const firstParam = method.params[0];
  5266. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  5267. return hasContextParam ? baseCount + 1 : baseCount;
  5268. }
  5269. });
  5270. types.placeholder = new TokenType("%%", {
  5271. startsExpr: true
  5272. });
  5273. var placeholders = (superClass => class extends superClass {
  5274. parsePlaceholder(expectedNode) {
  5275. if (this.match(types.placeholder)) {
  5276. const node = this.startNode();
  5277. this.next();
  5278. this.assertNoSpace("Unexpected space in placeholder.");
  5279. node.name = super.parseIdentifier(true);
  5280. this.assertNoSpace("Unexpected space in placeholder.");
  5281. this.expect(types.placeholder);
  5282. return this.finishPlaceholder(node, expectedNode);
  5283. }
  5284. }
  5285. finishPlaceholder(node, expectedNode) {
  5286. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  5287. node.expectedNode = expectedNode;
  5288. return isFinished ? node : this.finishNode(node, "Placeholder");
  5289. }
  5290. getTokenFromCode(code) {
  5291. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  5292. return this.finishOp(types.placeholder, 2);
  5293. }
  5294. return super.getTokenFromCode(...arguments);
  5295. }
  5296. parseExprAtom() {
  5297. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  5298. }
  5299. parseIdentifier() {
  5300. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  5301. }
  5302. checkReservedWord(word) {
  5303. if (word !== undefined) super.checkReservedWord(...arguments);
  5304. }
  5305. parseBindingAtom() {
  5306. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  5307. }
  5308. checkLVal(expr) {
  5309. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  5310. }
  5311. toAssignable(node) {
  5312. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  5313. node.expectedNode = "Pattern";
  5314. return node;
  5315. }
  5316. return super.toAssignable(...arguments);
  5317. }
  5318. verifyBreakContinue(node) {
  5319. if (node.label && node.label.type === "Placeholder") return;
  5320. super.verifyBreakContinue(...arguments);
  5321. }
  5322. parseExpressionStatement(node, expr) {
  5323. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  5324. return super.parseExpressionStatement(...arguments);
  5325. }
  5326. if (this.match(types.colon)) {
  5327. const stmt = node;
  5328. stmt.label = this.finishPlaceholder(expr, "Identifier");
  5329. this.next();
  5330. stmt.body = this.parseStatement("label");
  5331. return this.finishNode(stmt, "LabeledStatement");
  5332. }
  5333. this.semicolon();
  5334. node.name = expr.name;
  5335. return this.finishPlaceholder(node, "Statement");
  5336. }
  5337. parseBlock() {
  5338. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  5339. }
  5340. parseFunctionId() {
  5341. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  5342. }
  5343. parseClass(node, isStatement, optionalId) {
  5344. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  5345. this.next();
  5346. this.takeDecorators(node);
  5347. const placeholder = this.parsePlaceholder("Identifier");
  5348. if (placeholder) {
  5349. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  5350. node.id = placeholder;
  5351. } else if (optionalId || !isStatement) {
  5352. node.id = null;
  5353. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  5354. return this.finishNode(node, type);
  5355. } else {
  5356. this.unexpected(null, "A class name is required");
  5357. }
  5358. } else {
  5359. this.parseClassId(node, isStatement, optionalId);
  5360. }
  5361. this.parseClassSuper(node);
  5362. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass);
  5363. return this.finishNode(node, type);
  5364. }
  5365. parseExport(node) {
  5366. const placeholder = this.parsePlaceholder("Identifier");
  5367. if (!placeholder) return super.parseExport(...arguments);
  5368. if (!this.isContextual("from") && !this.match(types.comma)) {
  5369. node.specifiers = [];
  5370. node.source = null;
  5371. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  5372. return this.finishNode(node, "ExportNamedDeclaration");
  5373. }
  5374. this.expectPlugin("exportDefaultFrom");
  5375. const specifier = this.startNode();
  5376. specifier.exported = placeholder;
  5377. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  5378. return super.parseExport(node);
  5379. }
  5380. maybeParseExportDefaultSpecifier(node) {
  5381. if (node.specifiers && node.specifiers.length > 0) {
  5382. return true;
  5383. }
  5384. return super.maybeParseExportDefaultSpecifier(...arguments);
  5385. }
  5386. checkExport(node) {
  5387. const {
  5388. specifiers
  5389. } = node;
  5390. if (specifiers && specifiers.length) {
  5391. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  5392. }
  5393. super.checkExport(node);
  5394. node.specifiers = specifiers;
  5395. }
  5396. parseImport(node) {
  5397. const placeholder = this.parsePlaceholder("Identifier");
  5398. if (!placeholder) return super.parseImport(...arguments);
  5399. node.specifiers = [];
  5400. if (!this.isContextual("from") && !this.match(types.comma)) {
  5401. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  5402. this.semicolon();
  5403. return this.finishNode(node, "ImportDeclaration");
  5404. }
  5405. const specifier = this.startNodeAtNode(placeholder);
  5406. specifier.local = placeholder;
  5407. this.finishNode(specifier, "ImportDefaultSpecifier");
  5408. node.specifiers.push(specifier);
  5409. if (this.eat(types.comma)) {
  5410. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  5411. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  5412. }
  5413. this.expectContextual("from");
  5414. node.source = this.parseImportSource();
  5415. this.semicolon();
  5416. return this.finishNode(node, "ImportDeclaration");
  5417. }
  5418. parseImportSource() {
  5419. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  5420. }
  5421. });
  5422. var v8intrinsic = (superClass => class extends superClass {
  5423. parseV8Intrinsic() {
  5424. if (this.match(types.modulo)) {
  5425. const v8IntrinsicStart = this.state.start;
  5426. const node = this.startNode();
  5427. this.eat(types.modulo);
  5428. if (this.match(types.name)) {
  5429. const name = this.parseIdentifierName(this.state.start);
  5430. const identifier = this.createIdentifier(node, name);
  5431. identifier.type = "V8IntrinsicIdentifier";
  5432. if (this.match(types.parenL)) {
  5433. return identifier;
  5434. }
  5435. }
  5436. this.unexpected(v8IntrinsicStart);
  5437. }
  5438. }
  5439. parseExprAtom() {
  5440. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  5441. }
  5442. });
  5443. function hasPlugin(plugins, name) {
  5444. return plugins.some(plugin => {
  5445. if (Array.isArray(plugin)) {
  5446. return plugin[0] === name;
  5447. } else {
  5448. return plugin === name;
  5449. }
  5450. });
  5451. }
  5452. function getPluginOption(plugins, name, option) {
  5453. const plugin = plugins.find(plugin => {
  5454. if (Array.isArray(plugin)) {
  5455. return plugin[0] === name;
  5456. } else {
  5457. return plugin === name;
  5458. }
  5459. });
  5460. if (plugin && Array.isArray(plugin)) {
  5461. return plugin[1][option];
  5462. }
  5463. return null;
  5464. }
  5465. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  5466. function validatePlugins(plugins) {
  5467. if (hasPlugin(plugins, "decorators")) {
  5468. if (hasPlugin(plugins, "decorators-legacy")) {
  5469. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  5470. }
  5471. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  5472. if (decoratorsBeforeExport == null) {
  5473. throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'.");
  5474. } else if (typeof decoratorsBeforeExport !== "boolean") {
  5475. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  5476. }
  5477. }
  5478. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  5479. throw new Error("Cannot combine flow and typescript plugins.");
  5480. }
  5481. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  5482. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  5483. }
  5484. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  5485. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  5486. }
  5487. }
  5488. const mixinPlugins = {
  5489. estree,
  5490. jsx,
  5491. flow,
  5492. typescript,
  5493. v8intrinsic,
  5494. placeholders
  5495. };
  5496. const mixinPluginNames = Object.keys(mixinPlugins);
  5497. const defaultOptions = {
  5498. sourceType: "script",
  5499. sourceFilename: undefined,
  5500. startLine: 1,
  5501. allowAwaitOutsideFunction: false,
  5502. allowReturnOutsideFunction: false,
  5503. allowImportExportEverywhere: false,
  5504. allowSuperOutsideMethod: false,
  5505. allowUndeclaredExports: false,
  5506. plugins: [],
  5507. strictMode: null,
  5508. ranges: false,
  5509. tokens: false,
  5510. createParenthesizedExpressions: false,
  5511. errorRecovery: false
  5512. };
  5513. function getOptions(opts) {
  5514. const options = {};
  5515. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  5516. const key = _Object$keys[_i];
  5517. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  5518. }
  5519. return options;
  5520. }
  5521. class Position {
  5522. constructor(line, col) {
  5523. this.line = line;
  5524. this.column = col;
  5525. }
  5526. }
  5527. class SourceLocation {
  5528. constructor(start, end) {
  5529. this.start = start;
  5530. this.end = end;
  5531. }
  5532. }
  5533. function getLineInfo(input, offset) {
  5534. let line = 1;
  5535. let lineStart = 0;
  5536. let match;
  5537. lineBreakG.lastIndex = 0;
  5538. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  5539. line++;
  5540. lineStart = lineBreakG.lastIndex;
  5541. }
  5542. return new Position(line, offset - lineStart);
  5543. }
  5544. class BaseParser {
  5545. constructor() {
  5546. this.sawUnambiguousESM = false;
  5547. this.ambiguousScriptDifferentAst = false;
  5548. }
  5549. hasPlugin(name) {
  5550. return this.plugins.has(name);
  5551. }
  5552. getPluginOption(plugin, name) {
  5553. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  5554. }
  5555. }
  5556. function last(stack) {
  5557. return stack[stack.length - 1];
  5558. }
  5559. class CommentsParser extends BaseParser {
  5560. addComment(comment) {
  5561. if (this.filename) comment.loc.filename = this.filename;
  5562. this.state.trailingComments.push(comment);
  5563. this.state.leadingComments.push(comment);
  5564. }
  5565. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  5566. if (this.state.leadingComments.length === 0) {
  5567. return;
  5568. }
  5569. let lastElement = null;
  5570. let i = elements.length;
  5571. while (lastElement === null && i > 0) {
  5572. lastElement = elements[--i];
  5573. }
  5574. if (lastElement === null) {
  5575. return;
  5576. }
  5577. for (let j = 0; j < this.state.leadingComments.length; j++) {
  5578. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  5579. this.state.leadingComments.splice(j, 1);
  5580. j--;
  5581. }
  5582. }
  5583. const newTrailingComments = [];
  5584. for (let i = 0; i < this.state.leadingComments.length; i++) {
  5585. const leadingComment = this.state.leadingComments[i];
  5586. if (leadingComment.end < node.end) {
  5587. newTrailingComments.push(leadingComment);
  5588. if (!takeAllComments) {
  5589. this.state.leadingComments.splice(i, 1);
  5590. i--;
  5591. }
  5592. } else {
  5593. if (node.trailingComments === undefined) {
  5594. node.trailingComments = [];
  5595. }
  5596. node.trailingComments.push(leadingComment);
  5597. }
  5598. }
  5599. if (takeAllComments) this.state.leadingComments = [];
  5600. if (newTrailingComments.length > 0) {
  5601. lastElement.trailingComments = newTrailingComments;
  5602. } else if (lastElement.trailingComments !== undefined) {
  5603. lastElement.trailingComments = [];
  5604. }
  5605. }
  5606. processComment(node) {
  5607. if (node.type === "Program" && node.body.length > 0) return;
  5608. const stack = this.state.commentStack;
  5609. let firstChild, lastChild, trailingComments, i, j;
  5610. if (this.state.trailingComments.length > 0) {
  5611. if (this.state.trailingComments[0].start >= node.end) {
  5612. trailingComments = this.state.trailingComments;
  5613. this.state.trailingComments = [];
  5614. } else {
  5615. this.state.trailingComments.length = 0;
  5616. }
  5617. } else if (stack.length > 0) {
  5618. const lastInStack = last(stack);
  5619. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  5620. trailingComments = lastInStack.trailingComments;
  5621. delete lastInStack.trailingComments;
  5622. }
  5623. }
  5624. if (stack.length > 0 && last(stack).start >= node.start) {
  5625. firstChild = stack.pop();
  5626. }
  5627. while (stack.length > 0 && last(stack).start >= node.start) {
  5628. lastChild = stack.pop();
  5629. }
  5630. if (!lastChild && firstChild) lastChild = firstChild;
  5631. if (firstChild) {
  5632. switch (node.type) {
  5633. case "ObjectExpression":
  5634. this.adjustCommentsAfterTrailingComma(node, node.properties);
  5635. break;
  5636. case "ObjectPattern":
  5637. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  5638. break;
  5639. case "CallExpression":
  5640. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  5641. break;
  5642. case "ArrayExpression":
  5643. this.adjustCommentsAfterTrailingComma(node, node.elements);
  5644. break;
  5645. case "ArrayPattern":
  5646. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  5647. break;
  5648. }
  5649. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  5650. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode], true);
  5651. }
  5652. if (lastChild) {
  5653. if (lastChild.leadingComments) {
  5654. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  5655. node.leadingComments = lastChild.leadingComments;
  5656. delete lastChild.leadingComments;
  5657. } else {
  5658. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  5659. if (lastChild.leadingComments[i].end <= node.start) {
  5660. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  5661. break;
  5662. }
  5663. }
  5664. }
  5665. }
  5666. } else if (this.state.leadingComments.length > 0) {
  5667. if (last(this.state.leadingComments).end <= node.start) {
  5668. if (this.state.commentPreviousNode) {
  5669. for (j = 0; j < this.state.leadingComments.length; j++) {
  5670. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  5671. this.state.leadingComments.splice(j, 1);
  5672. j--;
  5673. }
  5674. }
  5675. }
  5676. if (this.state.leadingComments.length > 0) {
  5677. node.leadingComments = this.state.leadingComments;
  5678. this.state.leadingComments = [];
  5679. }
  5680. } else {
  5681. for (i = 0; i < this.state.leadingComments.length; i++) {
  5682. if (this.state.leadingComments[i].end > node.start) {
  5683. break;
  5684. }
  5685. }
  5686. const leadingComments = this.state.leadingComments.slice(0, i);
  5687. if (leadingComments.length) {
  5688. node.leadingComments = leadingComments;
  5689. }
  5690. trailingComments = this.state.leadingComments.slice(i);
  5691. if (trailingComments.length === 0) {
  5692. trailingComments = null;
  5693. }
  5694. }
  5695. }
  5696. this.state.commentPreviousNode = node;
  5697. if (trailingComments) {
  5698. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  5699. node.innerComments = trailingComments;
  5700. } else {
  5701. node.trailingComments = trailingComments;
  5702. }
  5703. }
  5704. stack.push(node);
  5705. }
  5706. }
  5707. class LocationParser extends CommentsParser {
  5708. getLocationForPosition(pos) {
  5709. let loc;
  5710. if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos);
  5711. return loc;
  5712. }
  5713. raise(pos, message, {
  5714. missingPluginNames,
  5715. code
  5716. } = {}) {
  5717. const loc = this.getLocationForPosition(pos);
  5718. message += ` (${loc.line}:${loc.column})`;
  5719. const err = new SyntaxError(message);
  5720. err.pos = pos;
  5721. err.loc = loc;
  5722. if (missingPluginNames) {
  5723. err.missingPlugin = missingPluginNames;
  5724. }
  5725. if (code !== undefined) {
  5726. err.code = code;
  5727. }
  5728. if (this.options.errorRecovery) {
  5729. if (!this.isLookahead) this.state.errors.push(err);
  5730. return err;
  5731. } else {
  5732. throw err;
  5733. }
  5734. }
  5735. }
  5736. class State {
  5737. constructor() {
  5738. this.errors = [];
  5739. this.potentialArrowAt = -1;
  5740. this.noArrowAt = [];
  5741. this.noArrowParamsConversionAt = [];
  5742. this.inParameters = false;
  5743. this.maybeInArrowParameters = false;
  5744. this.inPipeline = false;
  5745. this.inType = false;
  5746. this.noAnonFunctionType = false;
  5747. this.inPropertyName = false;
  5748. this.inClassProperty = false;
  5749. this.hasFlowComment = false;
  5750. this.isIterator = false;
  5751. this.topicContext = {
  5752. maxNumOfResolvableTopics: 0,
  5753. maxTopicIndex: null
  5754. };
  5755. this.soloAwait = false;
  5756. this.inFSharpPipelineDirectBody = false;
  5757. this.classLevel = 0;
  5758. this.labels = [];
  5759. this.decoratorStack = [[]];
  5760. this.yieldPos = -1;
  5761. this.awaitPos = -1;
  5762. this.tokens = [];
  5763. this.comments = [];
  5764. this.trailingComments = [];
  5765. this.leadingComments = [];
  5766. this.commentStack = [];
  5767. this.commentPreviousNode = null;
  5768. this.pos = 0;
  5769. this.lineStart = 0;
  5770. this.type = types.eof;
  5771. this.value = null;
  5772. this.start = 0;
  5773. this.end = 0;
  5774. this.lastTokEndLoc = null;
  5775. this.lastTokStartLoc = null;
  5776. this.lastTokStart = 0;
  5777. this.lastTokEnd = 0;
  5778. this.context = [types$1.braceStatement];
  5779. this.exprAllowed = true;
  5780. this.containsEsc = false;
  5781. this.containsOctal = false;
  5782. this.octalPosition = null;
  5783. this.exportedIdentifiers = [];
  5784. this.invalidTemplateEscapePosition = null;
  5785. }
  5786. init(options) {
  5787. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  5788. this.curLine = options.startLine;
  5789. this.startLoc = this.endLoc = this.curPosition();
  5790. }
  5791. curPosition() {
  5792. return new Position(this.curLine, this.pos - this.lineStart);
  5793. }
  5794. clone(skipArrays) {
  5795. const state = new State();
  5796. const keys = Object.keys(this);
  5797. for (let i = 0, length = keys.length; i < length; i++) {
  5798. const key = keys[i];
  5799. let val = this[key];
  5800. if (!skipArrays && Array.isArray(val)) {
  5801. val = val.slice();
  5802. }
  5803. state[key] = val;
  5804. }
  5805. return state;
  5806. }
  5807. }
  5808. var _isDigit = function isDigit(code) {
  5809. return code >= 48 && code <= 57;
  5810. };
  5811. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  5812. const forbiddenNumericSeparatorSiblings = {
  5813. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  5814. hex: [46, 88, 95, 120]
  5815. };
  5816. const allowedNumericSeparatorSiblings = {};
  5817. allowedNumericSeparatorSiblings.bin = [48, 49];
  5818. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  5819. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  5820. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  5821. class Token {
  5822. constructor(state) {
  5823. this.type = state.type;
  5824. this.value = state.value;
  5825. this.start = state.start;
  5826. this.end = state.end;
  5827. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  5828. }
  5829. }
  5830. class Tokenizer extends LocationParser {
  5831. constructor(options, input) {
  5832. super();
  5833. this.state = new State();
  5834. this.state.init(options);
  5835. this.input = input;
  5836. this.length = input.length;
  5837. this.isLookahead = false;
  5838. }
  5839. next() {
  5840. if (!this.isLookahead) {
  5841. this.checkKeywordEscapes();
  5842. if (this.options.tokens) {
  5843. this.state.tokens.push(new Token(this.state));
  5844. }
  5845. }
  5846. this.state.lastTokEnd = this.state.end;
  5847. this.state.lastTokStart = this.state.start;
  5848. this.state.lastTokEndLoc = this.state.endLoc;
  5849. this.state.lastTokStartLoc = this.state.startLoc;
  5850. this.nextToken();
  5851. }
  5852. eat(type) {
  5853. if (this.match(type)) {
  5854. this.next();
  5855. return true;
  5856. } else {
  5857. return false;
  5858. }
  5859. }
  5860. match(type) {
  5861. return this.state.type === type;
  5862. }
  5863. lookahead() {
  5864. const old = this.state;
  5865. this.state = old.clone(true);
  5866. this.isLookahead = true;
  5867. this.next();
  5868. this.isLookahead = false;
  5869. const curr = this.state;
  5870. this.state = old;
  5871. return curr;
  5872. }
  5873. nextTokenStart() {
  5874. const thisTokEnd = this.state.pos;
  5875. skipWhiteSpace.lastIndex = thisTokEnd;
  5876. const skip = skipWhiteSpace.exec(this.input);
  5877. return thisTokEnd + skip[0].length;
  5878. }
  5879. lookaheadCharCode() {
  5880. return this.input.charCodeAt(this.nextTokenStart());
  5881. }
  5882. setStrict(strict) {
  5883. this.state.strict = strict;
  5884. if (!this.match(types.num) && !this.match(types.string)) return;
  5885. this.state.pos = this.state.start;
  5886. while (this.state.pos < this.state.lineStart) {
  5887. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  5888. --this.state.curLine;
  5889. }
  5890. this.nextToken();
  5891. }
  5892. curContext() {
  5893. return this.state.context[this.state.context.length - 1];
  5894. }
  5895. nextToken() {
  5896. const curContext = this.curContext();
  5897. if (!curContext || !curContext.preserveSpace) this.skipSpace();
  5898. this.state.containsOctal = false;
  5899. this.state.octalPosition = null;
  5900. this.state.start = this.state.pos;
  5901. this.state.startLoc = this.state.curPosition();
  5902. if (this.state.pos >= this.length) {
  5903. this.finishToken(types.eof);
  5904. return;
  5905. }
  5906. if (curContext.override) {
  5907. curContext.override(this);
  5908. } else {
  5909. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  5910. }
  5911. }
  5912. pushComment(block, text, start, end, startLoc, endLoc) {
  5913. const comment = {
  5914. type: block ? "CommentBlock" : "CommentLine",
  5915. value: text,
  5916. start: start,
  5917. end: end,
  5918. loc: new SourceLocation(startLoc, endLoc)
  5919. };
  5920. if (this.options.tokens) this.state.tokens.push(comment);
  5921. this.state.comments.push(comment);
  5922. this.addComment(comment);
  5923. }
  5924. skipBlockComment() {
  5925. const startLoc = this.state.curPosition();
  5926. const start = this.state.pos;
  5927. const end = this.input.indexOf("*/", this.state.pos + 2);
  5928. if (end === -1) throw this.raise(start, "Unterminated comment");
  5929. this.state.pos = end + 2;
  5930. lineBreakG.lastIndex = start;
  5931. let match;
  5932. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  5933. ++this.state.curLine;
  5934. this.state.lineStart = match.index + match[0].length;
  5935. }
  5936. if (this.isLookahead) return;
  5937. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  5938. }
  5939. skipLineComment(startSkip) {
  5940. const start = this.state.pos;
  5941. const startLoc = this.state.curPosition();
  5942. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  5943. if (this.state.pos < this.length) {
  5944. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  5945. ch = this.input.charCodeAt(this.state.pos);
  5946. }
  5947. }
  5948. if (this.isLookahead) return;
  5949. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  5950. }
  5951. skipSpace() {
  5952. loop: while (this.state.pos < this.length) {
  5953. const ch = this.input.charCodeAt(this.state.pos);
  5954. switch (ch) {
  5955. case 32:
  5956. case 160:
  5957. case 9:
  5958. ++this.state.pos;
  5959. break;
  5960. case 13:
  5961. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  5962. ++this.state.pos;
  5963. }
  5964. case 10:
  5965. case 8232:
  5966. case 8233:
  5967. ++this.state.pos;
  5968. ++this.state.curLine;
  5969. this.state.lineStart = this.state.pos;
  5970. break;
  5971. case 47:
  5972. switch (this.input.charCodeAt(this.state.pos + 1)) {
  5973. case 42:
  5974. this.skipBlockComment();
  5975. break;
  5976. case 47:
  5977. this.skipLineComment(2);
  5978. break;
  5979. default:
  5980. break loop;
  5981. }
  5982. break;
  5983. default:
  5984. if (isWhitespace(ch)) {
  5985. ++this.state.pos;
  5986. } else {
  5987. break loop;
  5988. }
  5989. }
  5990. }
  5991. }
  5992. finishToken(type, val) {
  5993. this.state.end = this.state.pos;
  5994. this.state.endLoc = this.state.curPosition();
  5995. const prevType = this.state.type;
  5996. this.state.type = type;
  5997. this.state.value = val;
  5998. if (!this.isLookahead) this.updateContext(prevType);
  5999. }
  6000. readToken_numberSign() {
  6001. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6002. return;
  6003. }
  6004. const nextPos = this.state.pos + 1;
  6005. const next = this.input.charCodeAt(nextPos);
  6006. if (next >= 48 && next <= 57) {
  6007. throw this.raise(this.state.pos, "Unexpected digit after hash token");
  6008. }
  6009. if ((this.hasPlugin("classPrivateProperties") || this.hasPlugin("classPrivateMethods")) && this.state.classLevel > 0) {
  6010. ++this.state.pos;
  6011. this.finishToken(types.hash);
  6012. return;
  6013. } else if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  6014. this.finishOp(types.hash, 1);
  6015. } else {
  6016. throw this.raise(this.state.pos, "Unexpected character '#'");
  6017. }
  6018. }
  6019. readToken_dot() {
  6020. const next = this.input.charCodeAt(this.state.pos + 1);
  6021. if (next >= 48 && next <= 57) {
  6022. this.readNumber(true);
  6023. return;
  6024. }
  6025. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6026. this.state.pos += 3;
  6027. this.finishToken(types.ellipsis);
  6028. } else {
  6029. ++this.state.pos;
  6030. this.finishToken(types.dot);
  6031. }
  6032. }
  6033. readToken_slash() {
  6034. if (this.state.exprAllowed && !this.state.inType) {
  6035. ++this.state.pos;
  6036. this.readRegexp();
  6037. return;
  6038. }
  6039. const next = this.input.charCodeAt(this.state.pos + 1);
  6040. if (next === 61) {
  6041. this.finishOp(types.assign, 2);
  6042. } else {
  6043. this.finishOp(types.slash, 1);
  6044. }
  6045. }
  6046. readToken_interpreter() {
  6047. if (this.state.pos !== 0 || this.length < 2) return false;
  6048. const start = this.state.pos;
  6049. this.state.pos += 1;
  6050. let ch = this.input.charCodeAt(this.state.pos);
  6051. if (ch !== 33) return false;
  6052. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6053. ch = this.input.charCodeAt(this.state.pos);
  6054. }
  6055. const value = this.input.slice(start + 2, this.state.pos);
  6056. this.finishToken(types.interpreterDirective, value);
  6057. return true;
  6058. }
  6059. readToken_mult_modulo(code) {
  6060. let type = code === 42 ? types.star : types.modulo;
  6061. let width = 1;
  6062. let next = this.input.charCodeAt(this.state.pos + 1);
  6063. const exprAllowed = this.state.exprAllowed;
  6064. if (code === 42 && next === 42) {
  6065. width++;
  6066. next = this.input.charCodeAt(this.state.pos + 2);
  6067. type = types.exponent;
  6068. }
  6069. if (next === 61 && !exprAllowed) {
  6070. width++;
  6071. type = types.assign;
  6072. }
  6073. this.finishOp(type, width);
  6074. }
  6075. readToken_pipe_amp(code) {
  6076. const next = this.input.charCodeAt(this.state.pos + 1);
  6077. if (next === code) {
  6078. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6079. this.finishOp(types.assign, 3);
  6080. } else {
  6081. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6082. }
  6083. return;
  6084. }
  6085. if (code === 124) {
  6086. if (next === 62) {
  6087. this.finishOp(types.pipeline, 2);
  6088. return;
  6089. }
  6090. }
  6091. if (next === 61) {
  6092. this.finishOp(types.assign, 2);
  6093. return;
  6094. }
  6095. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  6096. }
  6097. readToken_caret() {
  6098. const next = this.input.charCodeAt(this.state.pos + 1);
  6099. if (next === 61) {
  6100. this.finishOp(types.assign, 2);
  6101. } else {
  6102. this.finishOp(types.bitwiseXOR, 1);
  6103. }
  6104. }
  6105. readToken_plus_min(code) {
  6106. const next = this.input.charCodeAt(this.state.pos + 1);
  6107. if (next === code) {
  6108. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos)))) {
  6109. this.skipLineComment(3);
  6110. this.skipSpace();
  6111. this.nextToken();
  6112. return;
  6113. }
  6114. this.finishOp(types.incDec, 2);
  6115. return;
  6116. }
  6117. if (next === 61) {
  6118. this.finishOp(types.assign, 2);
  6119. } else {
  6120. this.finishOp(types.plusMin, 1);
  6121. }
  6122. }
  6123. readToken_lt_gt(code) {
  6124. const next = this.input.charCodeAt(this.state.pos + 1);
  6125. let size = 1;
  6126. if (next === code) {
  6127. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  6128. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  6129. this.finishOp(types.assign, size + 1);
  6130. return;
  6131. }
  6132. this.finishOp(types.bitShift, size);
  6133. return;
  6134. }
  6135. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  6136. this.skipLineComment(4);
  6137. this.skipSpace();
  6138. this.nextToken();
  6139. return;
  6140. }
  6141. if (next === 61) {
  6142. size = 2;
  6143. }
  6144. this.finishOp(types.relational, size);
  6145. }
  6146. readToken_eq_excl(code) {
  6147. const next = this.input.charCodeAt(this.state.pos + 1);
  6148. if (next === 61) {
  6149. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  6150. return;
  6151. }
  6152. if (code === 61 && next === 62) {
  6153. this.state.pos += 2;
  6154. this.finishToken(types.arrow);
  6155. return;
  6156. }
  6157. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  6158. }
  6159. readToken_question() {
  6160. const next = this.input.charCodeAt(this.state.pos + 1);
  6161. const next2 = this.input.charCodeAt(this.state.pos + 2);
  6162. if (next === 63 && !this.state.inType) {
  6163. if (next2 === 61) {
  6164. this.finishOp(types.assign, 3);
  6165. } else {
  6166. this.finishOp(types.nullishCoalescing, 2);
  6167. }
  6168. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  6169. this.state.pos += 2;
  6170. this.finishToken(types.questionDot);
  6171. } else {
  6172. ++this.state.pos;
  6173. this.finishToken(types.question);
  6174. }
  6175. }
  6176. getTokenFromCode(code) {
  6177. switch (code) {
  6178. case 46:
  6179. this.readToken_dot();
  6180. return;
  6181. case 40:
  6182. ++this.state.pos;
  6183. this.finishToken(types.parenL);
  6184. return;
  6185. case 41:
  6186. ++this.state.pos;
  6187. this.finishToken(types.parenR);
  6188. return;
  6189. case 59:
  6190. ++this.state.pos;
  6191. this.finishToken(types.semi);
  6192. return;
  6193. case 44:
  6194. ++this.state.pos;
  6195. this.finishToken(types.comma);
  6196. return;
  6197. case 91:
  6198. ++this.state.pos;
  6199. this.finishToken(types.bracketL);
  6200. return;
  6201. case 93:
  6202. ++this.state.pos;
  6203. this.finishToken(types.bracketR);
  6204. return;
  6205. case 123:
  6206. ++this.state.pos;
  6207. this.finishToken(types.braceL);
  6208. return;
  6209. case 125:
  6210. ++this.state.pos;
  6211. this.finishToken(types.braceR);
  6212. return;
  6213. case 58:
  6214. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  6215. this.finishOp(types.doubleColon, 2);
  6216. } else {
  6217. ++this.state.pos;
  6218. this.finishToken(types.colon);
  6219. }
  6220. return;
  6221. case 63:
  6222. this.readToken_question();
  6223. return;
  6224. case 96:
  6225. ++this.state.pos;
  6226. this.finishToken(types.backQuote);
  6227. return;
  6228. case 48:
  6229. {
  6230. const next = this.input.charCodeAt(this.state.pos + 1);
  6231. if (next === 120 || next === 88) {
  6232. this.readRadixNumber(16);
  6233. return;
  6234. }
  6235. if (next === 111 || next === 79) {
  6236. this.readRadixNumber(8);
  6237. return;
  6238. }
  6239. if (next === 98 || next === 66) {
  6240. this.readRadixNumber(2);
  6241. return;
  6242. }
  6243. }
  6244. case 49:
  6245. case 50:
  6246. case 51:
  6247. case 52:
  6248. case 53:
  6249. case 54:
  6250. case 55:
  6251. case 56:
  6252. case 57:
  6253. this.readNumber(false);
  6254. return;
  6255. case 34:
  6256. case 39:
  6257. this.readString(code);
  6258. return;
  6259. case 47:
  6260. this.readToken_slash();
  6261. return;
  6262. case 37:
  6263. case 42:
  6264. this.readToken_mult_modulo(code);
  6265. return;
  6266. case 124:
  6267. case 38:
  6268. this.readToken_pipe_amp(code);
  6269. return;
  6270. case 94:
  6271. this.readToken_caret();
  6272. return;
  6273. case 43:
  6274. case 45:
  6275. this.readToken_plus_min(code);
  6276. return;
  6277. case 60:
  6278. case 62:
  6279. this.readToken_lt_gt(code);
  6280. return;
  6281. case 61:
  6282. case 33:
  6283. this.readToken_eq_excl(code);
  6284. return;
  6285. case 126:
  6286. this.finishOp(types.tilde, 1);
  6287. return;
  6288. case 64:
  6289. ++this.state.pos;
  6290. this.finishToken(types.at);
  6291. return;
  6292. case 35:
  6293. this.readToken_numberSign();
  6294. return;
  6295. case 92:
  6296. this.readWord();
  6297. return;
  6298. default:
  6299. if (isIdentifierStart(code)) {
  6300. this.readWord();
  6301. return;
  6302. }
  6303. }
  6304. throw this.raise(this.state.pos, `Unexpected character '${String.fromCodePoint(code)}'`);
  6305. }
  6306. finishOp(type, size) {
  6307. const str = this.input.slice(this.state.pos, this.state.pos + size);
  6308. this.state.pos += size;
  6309. this.finishToken(type, str);
  6310. }
  6311. readRegexp() {
  6312. const start = this.state.pos;
  6313. let escaped, inClass;
  6314. for (;;) {
  6315. if (this.state.pos >= this.length) {
  6316. throw this.raise(start, "Unterminated regular expression");
  6317. }
  6318. const ch = this.input.charAt(this.state.pos);
  6319. if (lineBreak.test(ch)) {
  6320. throw this.raise(start, "Unterminated regular expression");
  6321. }
  6322. if (escaped) {
  6323. escaped = false;
  6324. } else {
  6325. if (ch === "[") {
  6326. inClass = true;
  6327. } else if (ch === "]" && inClass) {
  6328. inClass = false;
  6329. } else if (ch === "/" && !inClass) {
  6330. break;
  6331. }
  6332. escaped = ch === "\\";
  6333. }
  6334. ++this.state.pos;
  6335. }
  6336. const content = this.input.slice(start, this.state.pos);
  6337. ++this.state.pos;
  6338. let mods = "";
  6339. while (this.state.pos < this.length) {
  6340. const char = this.input[this.state.pos];
  6341. const charCode = this.input.codePointAt(this.state.pos);
  6342. if (VALID_REGEX_FLAGS.has(char)) {
  6343. if (mods.indexOf(char) > -1) {
  6344. this.raise(this.state.pos + 1, "Duplicate regular expression flag");
  6345. }
  6346. } else if (isIdentifierChar(charCode) || charCode === 92) {
  6347. this.raise(this.state.pos + 1, "Invalid regular expression flag");
  6348. } else {
  6349. break;
  6350. }
  6351. ++this.state.pos;
  6352. mods += char;
  6353. }
  6354. this.finishToken(types.regexp, {
  6355. pattern: content,
  6356. flags: mods
  6357. });
  6358. }
  6359. readInt(radix, len, forceLen, allowNumSeparator = true) {
  6360. const start = this.state.pos;
  6361. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  6362. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  6363. let invalid = false;
  6364. let total = 0;
  6365. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  6366. const code = this.input.charCodeAt(this.state.pos);
  6367. let val;
  6368. if (this.hasPlugin("numericSeparator")) {
  6369. if (code === 95) {
  6370. const prev = this.input.charCodeAt(this.state.pos - 1);
  6371. const next = this.input.charCodeAt(this.state.pos + 1);
  6372. if (allowedSiblings.indexOf(next) === -1) {
  6373. this.raise(this.state.pos, "A numeric separator is only allowed between two digits");
  6374. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  6375. this.raise(this.state.pos, "A numeric separator is only allowed between two digits");
  6376. }
  6377. if (!allowNumSeparator) {
  6378. this.raise(this.state.pos, "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences");
  6379. }
  6380. ++this.state.pos;
  6381. continue;
  6382. }
  6383. }
  6384. if (code >= 97) {
  6385. val = code - 97 + 10;
  6386. } else if (code >= 65) {
  6387. val = code - 65 + 10;
  6388. } else if (_isDigit(code)) {
  6389. val = code - 48;
  6390. } else {
  6391. val = Infinity;
  6392. }
  6393. if (val >= radix) {
  6394. if (this.options.errorRecovery && val <= 9) {
  6395. val = 0;
  6396. this.raise(this.state.start + i + 2, "Expected number in radix " + radix);
  6397. } else if (forceLen) {
  6398. val = 0;
  6399. invalid = true;
  6400. } else {
  6401. break;
  6402. }
  6403. }
  6404. ++this.state.pos;
  6405. total = total * radix + val;
  6406. }
  6407. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  6408. return null;
  6409. }
  6410. return total;
  6411. }
  6412. readRadixNumber(radix) {
  6413. const start = this.state.pos;
  6414. let isBigInt = false;
  6415. this.state.pos += 2;
  6416. const val = this.readInt(radix);
  6417. if (val == null) {
  6418. this.raise(this.state.start + 2, "Expected number in radix " + radix);
  6419. }
  6420. if (this.hasPlugin("bigInt")) {
  6421. if (this.input.charCodeAt(this.state.pos) === 110) {
  6422. ++this.state.pos;
  6423. isBigInt = true;
  6424. }
  6425. }
  6426. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6427. throw this.raise(this.state.pos, "Identifier directly after number");
  6428. }
  6429. if (isBigInt) {
  6430. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6431. this.finishToken(types.bigint, str);
  6432. return;
  6433. }
  6434. this.finishToken(types.num, val);
  6435. }
  6436. readNumber(startsWithDot) {
  6437. const start = this.state.pos;
  6438. let isFloat = false;
  6439. let isBigInt = false;
  6440. let isNonOctalDecimalInt = false;
  6441. if (!startsWithDot && this.readInt(10) === null) {
  6442. this.raise(start, "Invalid number");
  6443. }
  6444. let octal = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  6445. if (octal) {
  6446. if (this.state.strict) {
  6447. this.raise(start, "Legacy octal literals are not allowed in strict mode");
  6448. }
  6449. if (/[89]/.test(this.input.slice(start, this.state.pos))) {
  6450. octal = false;
  6451. isNonOctalDecimalInt = true;
  6452. }
  6453. }
  6454. let next = this.input.charCodeAt(this.state.pos);
  6455. if (next === 46 && !octal) {
  6456. ++this.state.pos;
  6457. this.readInt(10);
  6458. isFloat = true;
  6459. next = this.input.charCodeAt(this.state.pos);
  6460. }
  6461. if ((next === 69 || next === 101) && !octal) {
  6462. next = this.input.charCodeAt(++this.state.pos);
  6463. if (next === 43 || next === 45) {
  6464. ++this.state.pos;
  6465. }
  6466. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  6467. isFloat = true;
  6468. next = this.input.charCodeAt(this.state.pos);
  6469. }
  6470. if (this.hasPlugin("numericSeparator") && (octal || isNonOctalDecimalInt)) {
  6471. const underscorePos = this.input.slice(start, this.state.pos).indexOf("_");
  6472. if (underscorePos > 0) {
  6473. this.raise(underscorePos + start, "Numeric separator can not be used after leading 0");
  6474. }
  6475. }
  6476. if (this.hasPlugin("bigInt")) {
  6477. if (next === 110) {
  6478. if (isFloat || octal || isNonOctalDecimalInt) {
  6479. this.raise(start, "Invalid BigIntLiteral");
  6480. }
  6481. ++this.state.pos;
  6482. isBigInt = true;
  6483. }
  6484. }
  6485. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6486. throw this.raise(this.state.pos, "Identifier directly after number");
  6487. }
  6488. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6489. if (isBigInt) {
  6490. this.finishToken(types.bigint, str);
  6491. return;
  6492. }
  6493. const val = octal ? parseInt(str, 8) : parseFloat(str);
  6494. this.finishToken(types.num, val);
  6495. }
  6496. readCodePoint(throwOnInvalid) {
  6497. const ch = this.input.charCodeAt(this.state.pos);
  6498. let code;
  6499. if (ch === 123) {
  6500. const codePos = ++this.state.pos;
  6501. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  6502. ++this.state.pos;
  6503. if (code === null) {
  6504. --this.state.invalidTemplateEscapePosition;
  6505. } else if (code > 0x10ffff) {
  6506. if (throwOnInvalid) {
  6507. this.raise(codePos, "Code point out of bounds");
  6508. } else {
  6509. this.state.invalidTemplateEscapePosition = codePos - 2;
  6510. return null;
  6511. }
  6512. }
  6513. } else {
  6514. code = this.readHexChar(4, false, throwOnInvalid);
  6515. }
  6516. return code;
  6517. }
  6518. readString(quote) {
  6519. let out = "",
  6520. chunkStart = ++this.state.pos;
  6521. for (;;) {
  6522. if (this.state.pos >= this.length) {
  6523. throw this.raise(this.state.start, "Unterminated string constant");
  6524. }
  6525. const ch = this.input.charCodeAt(this.state.pos);
  6526. if (ch === quote) break;
  6527. if (ch === 92) {
  6528. out += this.input.slice(chunkStart, this.state.pos);
  6529. out += this.readEscapedChar(false);
  6530. chunkStart = this.state.pos;
  6531. } else if (ch === 8232 || ch === 8233) {
  6532. ++this.state.pos;
  6533. ++this.state.curLine;
  6534. } else if (isNewLine(ch)) {
  6535. throw this.raise(this.state.start, "Unterminated string constant");
  6536. } else {
  6537. ++this.state.pos;
  6538. }
  6539. }
  6540. out += this.input.slice(chunkStart, this.state.pos++);
  6541. this.finishToken(types.string, out);
  6542. }
  6543. readTmplToken() {
  6544. let out = "",
  6545. chunkStart = this.state.pos,
  6546. containsInvalid = false;
  6547. for (;;) {
  6548. if (this.state.pos >= this.length) {
  6549. throw this.raise(this.state.start, "Unterminated template");
  6550. }
  6551. const ch = this.input.charCodeAt(this.state.pos);
  6552. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  6553. if (this.state.pos === this.state.start && this.match(types.template)) {
  6554. if (ch === 36) {
  6555. this.state.pos += 2;
  6556. this.finishToken(types.dollarBraceL);
  6557. return;
  6558. } else {
  6559. ++this.state.pos;
  6560. this.finishToken(types.backQuote);
  6561. return;
  6562. }
  6563. }
  6564. out += this.input.slice(chunkStart, this.state.pos);
  6565. this.finishToken(types.template, containsInvalid ? null : out);
  6566. return;
  6567. }
  6568. if (ch === 92) {
  6569. out += this.input.slice(chunkStart, this.state.pos);
  6570. const escaped = this.readEscapedChar(true);
  6571. if (escaped === null) {
  6572. containsInvalid = true;
  6573. } else {
  6574. out += escaped;
  6575. }
  6576. chunkStart = this.state.pos;
  6577. } else if (isNewLine(ch)) {
  6578. out += this.input.slice(chunkStart, this.state.pos);
  6579. ++this.state.pos;
  6580. switch (ch) {
  6581. case 13:
  6582. if (this.input.charCodeAt(this.state.pos) === 10) {
  6583. ++this.state.pos;
  6584. }
  6585. case 10:
  6586. out += "\n";
  6587. break;
  6588. default:
  6589. out += String.fromCharCode(ch);
  6590. break;
  6591. }
  6592. ++this.state.curLine;
  6593. this.state.lineStart = this.state.pos;
  6594. chunkStart = this.state.pos;
  6595. } else {
  6596. ++this.state.pos;
  6597. }
  6598. }
  6599. }
  6600. readEscapedChar(inTemplate) {
  6601. const throwOnInvalid = !inTemplate;
  6602. const ch = this.input.charCodeAt(++this.state.pos);
  6603. ++this.state.pos;
  6604. switch (ch) {
  6605. case 110:
  6606. return "\n";
  6607. case 114:
  6608. return "\r";
  6609. case 120:
  6610. {
  6611. const code = this.readHexChar(2, false, throwOnInvalid);
  6612. return code === null ? null : String.fromCharCode(code);
  6613. }
  6614. case 117:
  6615. {
  6616. const code = this.readCodePoint(throwOnInvalid);
  6617. return code === null ? null : String.fromCodePoint(code);
  6618. }
  6619. case 116:
  6620. return "\t";
  6621. case 98:
  6622. return "\b";
  6623. case 118:
  6624. return "\u000b";
  6625. case 102:
  6626. return "\f";
  6627. case 13:
  6628. if (this.input.charCodeAt(this.state.pos) === 10) {
  6629. ++this.state.pos;
  6630. }
  6631. case 10:
  6632. this.state.lineStart = this.state.pos;
  6633. ++this.state.curLine;
  6634. case 8232:
  6635. case 8233:
  6636. return "";
  6637. case 56:
  6638. case 57:
  6639. if (inTemplate) {
  6640. const codePos = this.state.pos - 1;
  6641. this.state.invalidTemplateEscapePosition = codePos;
  6642. return null;
  6643. }
  6644. default:
  6645. if (ch >= 48 && ch <= 55) {
  6646. const codePos = this.state.pos - 1;
  6647. let octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0];
  6648. let octal = parseInt(octalStr, 8);
  6649. if (octal > 255) {
  6650. octalStr = octalStr.slice(0, -1);
  6651. octal = parseInt(octalStr, 8);
  6652. }
  6653. this.state.pos += octalStr.length - 1;
  6654. const next = this.input.charCodeAt(this.state.pos);
  6655. if (octalStr !== "0" || next === 56 || next === 57) {
  6656. if (inTemplate) {
  6657. this.state.invalidTemplateEscapePosition = codePos;
  6658. return null;
  6659. } else if (this.state.strict) {
  6660. this.raise(codePos, "Octal literal in strict mode");
  6661. } else if (!this.state.containsOctal) {
  6662. this.state.containsOctal = true;
  6663. this.state.octalPosition = codePos;
  6664. }
  6665. }
  6666. return String.fromCharCode(octal);
  6667. }
  6668. return String.fromCharCode(ch);
  6669. }
  6670. }
  6671. readHexChar(len, forceLen, throwOnInvalid) {
  6672. const codePos = this.state.pos;
  6673. const n = this.readInt(16, len, forceLen, false);
  6674. if (n === null) {
  6675. if (throwOnInvalid) {
  6676. this.raise(codePos, "Bad character escape sequence");
  6677. } else {
  6678. this.state.pos = codePos - 1;
  6679. this.state.invalidTemplateEscapePosition = codePos - 1;
  6680. }
  6681. }
  6682. return n;
  6683. }
  6684. readWord1() {
  6685. let word = "";
  6686. this.state.containsEsc = false;
  6687. const start = this.state.pos;
  6688. let chunkStart = this.state.pos;
  6689. while (this.state.pos < this.length) {
  6690. const ch = this.input.codePointAt(this.state.pos);
  6691. if (isIdentifierChar(ch)) {
  6692. this.state.pos += ch <= 0xffff ? 1 : 2;
  6693. } else if (this.state.isIterator && ch === 64) {
  6694. ++this.state.pos;
  6695. } else if (ch === 92) {
  6696. this.state.containsEsc = true;
  6697. word += this.input.slice(chunkStart, this.state.pos);
  6698. const escStart = this.state.pos;
  6699. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  6700. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  6701. this.raise(this.state.pos, "Expecting Unicode escape sequence \\uXXXX");
  6702. continue;
  6703. }
  6704. ++this.state.pos;
  6705. const esc = this.readCodePoint(true);
  6706. if (esc !== null) {
  6707. if (!identifierCheck(esc)) {
  6708. this.raise(escStart, "Invalid Unicode escape");
  6709. }
  6710. word += String.fromCodePoint(esc);
  6711. }
  6712. chunkStart = this.state.pos;
  6713. } else {
  6714. break;
  6715. }
  6716. }
  6717. return word + this.input.slice(chunkStart, this.state.pos);
  6718. }
  6719. isIterator(word) {
  6720. return word === "@@iterator" || word === "@@asyncIterator";
  6721. }
  6722. readWord() {
  6723. const word = this.readWord1();
  6724. const type = keywords.get(word) || types.name;
  6725. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  6726. this.raise(this.state.pos, `Invalid identifier ${word}`);
  6727. }
  6728. this.finishToken(type, word);
  6729. }
  6730. checkKeywordEscapes() {
  6731. const kw = this.state.type.keyword;
  6732. if (kw && this.state.containsEsc) {
  6733. this.raise(this.state.start, `Escape sequence in keyword ${kw}`);
  6734. }
  6735. }
  6736. braceIsBlock(prevType) {
  6737. const parent = this.curContext();
  6738. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  6739. return true;
  6740. }
  6741. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  6742. return !parent.isExpr;
  6743. }
  6744. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  6745. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  6746. }
  6747. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  6748. return true;
  6749. }
  6750. if (prevType === types.braceL) {
  6751. return parent === types$1.braceStatement;
  6752. }
  6753. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  6754. return false;
  6755. }
  6756. if (prevType === types.relational) {
  6757. return true;
  6758. }
  6759. return !this.state.exprAllowed;
  6760. }
  6761. updateContext(prevType) {
  6762. const type = this.state.type;
  6763. let update;
  6764. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  6765. this.state.exprAllowed = false;
  6766. } else if (update = type.updateContext) {
  6767. update.call(this, prevType);
  6768. } else {
  6769. this.state.exprAllowed = type.beforeExpr;
  6770. }
  6771. }
  6772. }
  6773. const literal = /^('|")((?:\\?.)*?)\1/;
  6774. class UtilParser extends Tokenizer {
  6775. addExtra(node, key, val) {
  6776. if (!node) return;
  6777. const extra = node.extra = node.extra || {};
  6778. extra[key] = val;
  6779. }
  6780. isRelational(op) {
  6781. return this.match(types.relational) && this.state.value === op;
  6782. }
  6783. isLookaheadRelational(op) {
  6784. const next = this.nextTokenStart();
  6785. if (this.input.charAt(next) === op) {
  6786. if (next + 1 === this.input.length) {
  6787. return true;
  6788. }
  6789. const afterNext = this.input.charCodeAt(next + 1);
  6790. return afterNext !== op.charCodeAt(0) && afterNext !== 61;
  6791. }
  6792. return false;
  6793. }
  6794. expectRelational(op) {
  6795. if (this.isRelational(op)) {
  6796. this.next();
  6797. } else {
  6798. this.unexpected(null, types.relational);
  6799. }
  6800. }
  6801. eatRelational(op) {
  6802. if (this.isRelational(op)) {
  6803. this.next();
  6804. return true;
  6805. }
  6806. return false;
  6807. }
  6808. isContextual(name) {
  6809. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  6810. }
  6811. isUnparsedContextual(nameStart, name) {
  6812. const nameEnd = nameStart + name.length;
  6813. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  6814. }
  6815. isLookaheadContextual(name) {
  6816. const next = this.nextTokenStart();
  6817. return this.isUnparsedContextual(next, name);
  6818. }
  6819. eatContextual(name) {
  6820. return this.isContextual(name) && this.eat(types.name);
  6821. }
  6822. expectContextual(name, message) {
  6823. if (!this.eatContextual(name)) this.unexpected(null, message);
  6824. }
  6825. canInsertSemicolon() {
  6826. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  6827. }
  6828. hasPrecedingLineBreak() {
  6829. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  6830. }
  6831. isLineTerminator() {
  6832. return this.eat(types.semi) || this.canInsertSemicolon();
  6833. }
  6834. semicolon() {
  6835. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  6836. }
  6837. expect(type, pos) {
  6838. this.eat(type) || this.unexpected(pos, type);
  6839. }
  6840. assertNoSpace(message = "Unexpected space.") {
  6841. if (this.state.start > this.state.lastTokEnd) {
  6842. this.raise(this.state.lastTokEnd, message);
  6843. }
  6844. }
  6845. unexpected(pos, messageOrType = "Unexpected token") {
  6846. if (typeof messageOrType !== "string") {
  6847. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  6848. }
  6849. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  6850. }
  6851. expectPlugin(name, pos) {
  6852. if (!this.hasPlugin(name)) {
  6853. throw this.raise(pos != null ? pos : this.state.start, `This experimental syntax requires enabling the parser plugin: '${name}'`, {
  6854. missingPluginNames: [name]
  6855. });
  6856. }
  6857. return true;
  6858. }
  6859. expectOnePlugin(names, pos) {
  6860. if (!names.some(n => this.hasPlugin(n))) {
  6861. throw this.raise(pos != null ? pos : this.state.start, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`, {
  6862. missingPluginNames: names
  6863. });
  6864. }
  6865. }
  6866. checkYieldAwaitInDefaultParams() {
  6867. if (this.state.yieldPos !== -1 && (this.state.awaitPos === -1 || this.state.yieldPos < this.state.awaitPos)) {
  6868. this.raise(this.state.yieldPos, "Yield cannot be used as name inside a generator function");
  6869. }
  6870. if (this.state.awaitPos !== -1) {
  6871. this.raise(this.state.awaitPos, "Await cannot be used as name inside an async function");
  6872. }
  6873. }
  6874. strictDirective(start) {
  6875. for (;;) {
  6876. skipWhiteSpace.lastIndex = start;
  6877. start += skipWhiteSpace.exec(this.input)[0].length;
  6878. const match = literal.exec(this.input.slice(start));
  6879. if (!match) break;
  6880. if (match[2] === "use strict") return true;
  6881. start += match[0].length;
  6882. skipWhiteSpace.lastIndex = start;
  6883. start += skipWhiteSpace.exec(this.input)[0].length;
  6884. if (this.input[start] === ";") {
  6885. start++;
  6886. }
  6887. }
  6888. return false;
  6889. }
  6890. tryParse(fn, oldState = this.state.clone()) {
  6891. const abortSignal = {
  6892. node: null
  6893. };
  6894. try {
  6895. const node = fn((node = null) => {
  6896. abortSignal.node = node;
  6897. throw abortSignal;
  6898. });
  6899. if (this.state.errors.length > oldState.errors.length) {
  6900. const failState = this.state;
  6901. this.state = oldState;
  6902. return {
  6903. node,
  6904. error: failState.errors[oldState.errors.length],
  6905. thrown: false,
  6906. aborted: false,
  6907. failState
  6908. };
  6909. }
  6910. return {
  6911. node,
  6912. error: null,
  6913. thrown: false,
  6914. aborted: false,
  6915. failState: null
  6916. };
  6917. } catch (error) {
  6918. const failState = this.state;
  6919. this.state = oldState;
  6920. if (error instanceof SyntaxError) {
  6921. return {
  6922. node: null,
  6923. error,
  6924. thrown: true,
  6925. aborted: false,
  6926. failState
  6927. };
  6928. }
  6929. if (error === abortSignal) {
  6930. return {
  6931. node: abortSignal.node,
  6932. error: null,
  6933. thrown: false,
  6934. aborted: true,
  6935. failState
  6936. };
  6937. }
  6938. throw error;
  6939. }
  6940. }
  6941. }
  6942. class Node {
  6943. constructor(parser, pos, loc) {
  6944. this.type = "";
  6945. this.start = pos;
  6946. this.end = 0;
  6947. this.loc = new SourceLocation(loc);
  6948. if (parser && parser.options.ranges) this.range = [pos, 0];
  6949. if (parser && parser.filename) this.loc.filename = parser.filename;
  6950. }
  6951. __clone() {
  6952. const newNode = new Node();
  6953. const keys = Object.keys(this);
  6954. for (let i = 0, length = keys.length; i < length; i++) {
  6955. const key = keys[i];
  6956. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  6957. newNode[key] = this[key];
  6958. }
  6959. }
  6960. return newNode;
  6961. }
  6962. }
  6963. class NodeUtils extends UtilParser {
  6964. startNode() {
  6965. return new Node(this, this.state.start, this.state.startLoc);
  6966. }
  6967. startNodeAt(pos, loc) {
  6968. return new Node(this, pos, loc);
  6969. }
  6970. startNodeAtNode(type) {
  6971. return this.startNodeAt(type.start, type.loc.start);
  6972. }
  6973. finishNode(node, type) {
  6974. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  6975. }
  6976. finishNodeAt(node, type, pos, loc) {
  6977. node.type = type;
  6978. node.end = pos;
  6979. node.loc.end = loc;
  6980. if (this.options.ranges) node.range[1] = pos;
  6981. this.processComment(node);
  6982. return node;
  6983. }
  6984. resetStartLocation(node, start, startLoc) {
  6985. node.start = start;
  6986. node.loc.start = startLoc;
  6987. if (this.options.ranges) node.range[0] = start;
  6988. }
  6989. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  6990. node.end = end;
  6991. node.loc.end = endLoc;
  6992. if (this.options.ranges) node.range[1] = end;
  6993. }
  6994. resetStartLocationFromNode(node, locationNode) {
  6995. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  6996. }
  6997. }
  6998. class LValParser extends NodeUtils {
  6999. toAssignable(node, isBinding, contextDescription) {
  7000. var _node$extra2;
  7001. if (node) {
  7002. switch (node.type) {
  7003. case "Identifier":
  7004. case "ObjectPattern":
  7005. case "ArrayPattern":
  7006. case "AssignmentPattern":
  7007. break;
  7008. case "ObjectExpression":
  7009. node.type = "ObjectPattern";
  7010. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7011. var _node$extra;
  7012. const prop = node.properties[i];
  7013. const isLast = i === last;
  7014. this.toAssignableObjectExpressionProp(prop, isBinding, isLast);
  7015. if (isLast && prop.type === "RestElement" && ((_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma)) {
  7016. this.raiseRestNotLast(node.extra.trailingComma);
  7017. }
  7018. }
  7019. break;
  7020. case "ObjectProperty":
  7021. this.toAssignable(node.value, isBinding, contextDescription);
  7022. break;
  7023. case "SpreadElement":
  7024. {
  7025. this.checkToRestConversion(node);
  7026. node.type = "RestElement";
  7027. const arg = node.argument;
  7028. this.toAssignable(arg, isBinding, contextDescription);
  7029. break;
  7030. }
  7031. case "ArrayExpression":
  7032. node.type = "ArrayPattern";
  7033. this.toAssignableList(node.elements, isBinding, contextDescription, (_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma);
  7034. break;
  7035. case "AssignmentExpression":
  7036. if (node.operator !== "=") {
  7037. this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
  7038. }
  7039. node.type = "AssignmentPattern";
  7040. delete node.operator;
  7041. this.toAssignable(node.left, isBinding, contextDescription);
  7042. break;
  7043. case "ParenthesizedExpression":
  7044. node.expression = this.toAssignable(node.expression, isBinding, contextDescription);
  7045. break;
  7046. case "MemberExpression":
  7047. if (!isBinding) break;
  7048. default:
  7049. }
  7050. }
  7051. return node;
  7052. }
  7053. toAssignableObjectExpressionProp(prop, isBinding, isLast) {
  7054. if (prop.type === "ObjectMethod") {
  7055. const error = prop.kind === "get" || prop.kind === "set" ? "Object pattern can't contain getter or setter" : "Object pattern can't contain methods";
  7056. this.raise(prop.key.start, error);
  7057. } else if (prop.type === "SpreadElement" && !isLast) {
  7058. this.raiseRestNotLast(prop.start);
  7059. } else {
  7060. this.toAssignable(prop, isBinding, "object destructuring pattern");
  7061. }
  7062. }
  7063. toAssignableList(exprList, isBinding, contextDescription, trailingCommaPos) {
  7064. let end = exprList.length;
  7065. if (end) {
  7066. const last = exprList[end - 1];
  7067. if (last && last.type === "RestElement") {
  7068. --end;
  7069. } else if (last && last.type === "SpreadElement") {
  7070. last.type = "RestElement";
  7071. const arg = last.argument;
  7072. this.toAssignable(arg, isBinding, contextDescription);
  7073. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  7074. this.unexpected(arg.start);
  7075. }
  7076. if (trailingCommaPos) {
  7077. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  7078. }
  7079. --end;
  7080. }
  7081. }
  7082. for (let i = 0; i < end; i++) {
  7083. const elt = exprList[i];
  7084. if (elt) {
  7085. this.toAssignable(elt, isBinding, contextDescription);
  7086. if (elt.type === "RestElement") {
  7087. this.raiseRestNotLast(elt.start);
  7088. }
  7089. }
  7090. }
  7091. return exprList;
  7092. }
  7093. toReferencedList(exprList, isParenthesizedExpr) {
  7094. return exprList;
  7095. }
  7096. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7097. this.toReferencedList(exprList, isParenthesizedExpr);
  7098. for (let _i = 0; _i < exprList.length; _i++) {
  7099. const expr = exprList[_i];
  7100. if (expr && expr.type === "ArrayExpression") {
  7101. this.toReferencedListDeep(expr.elements);
  7102. }
  7103. }
  7104. return exprList;
  7105. }
  7106. parseSpread(refShorthandDefaultPos, refNeedsArrowPos) {
  7107. const node = this.startNode();
  7108. this.next();
  7109. node.argument = this.parseMaybeAssign(false, refShorthandDefaultPos, undefined, refNeedsArrowPos);
  7110. return this.finishNode(node, "SpreadElement");
  7111. }
  7112. parseRestBinding() {
  7113. const node = this.startNode();
  7114. this.next();
  7115. node.argument = this.parseBindingAtom();
  7116. return this.finishNode(node, "RestElement");
  7117. }
  7118. parseBindingAtom() {
  7119. switch (this.state.type) {
  7120. case types.bracketL:
  7121. {
  7122. const node = this.startNode();
  7123. this.next();
  7124. node.elements = this.parseBindingList(types.bracketR, 93, true);
  7125. return this.finishNode(node, "ArrayPattern");
  7126. }
  7127. case types.braceL:
  7128. return this.parseObj(true);
  7129. }
  7130. return this.parseIdentifier();
  7131. }
  7132. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  7133. const elts = [];
  7134. let first = true;
  7135. while (!this.eat(close)) {
  7136. if (first) {
  7137. first = false;
  7138. } else {
  7139. this.expect(types.comma);
  7140. }
  7141. if (allowEmpty && this.match(types.comma)) {
  7142. elts.push(null);
  7143. } else if (this.eat(close)) {
  7144. break;
  7145. } else if (this.match(types.ellipsis)) {
  7146. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  7147. this.checkCommaAfterRest(closeCharCode);
  7148. this.expect(close);
  7149. break;
  7150. } else {
  7151. const decorators = [];
  7152. if (this.match(types.at) && this.hasPlugin("decorators")) {
  7153. this.raise(this.state.start, "Stage 2 decorators cannot be used to decorate parameters");
  7154. }
  7155. while (this.match(types.at)) {
  7156. decorators.push(this.parseDecorator());
  7157. }
  7158. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  7159. }
  7160. }
  7161. return elts;
  7162. }
  7163. parseAssignableListItem(allowModifiers, decorators) {
  7164. const left = this.parseMaybeDefault();
  7165. this.parseAssignableListItemTypes(left);
  7166. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  7167. if (decorators.length) {
  7168. left.decorators = decorators;
  7169. }
  7170. return elt;
  7171. }
  7172. parseAssignableListItemTypes(param) {
  7173. return param;
  7174. }
  7175. parseMaybeDefault(startPos, startLoc, left) {
  7176. startLoc = startLoc || this.state.startLoc;
  7177. startPos = startPos || this.state.start;
  7178. left = left || this.parseBindingAtom();
  7179. if (!this.eat(types.eq)) return left;
  7180. const node = this.startNodeAt(startPos, startLoc);
  7181. node.left = left;
  7182. node.right = this.parseMaybeAssign();
  7183. return this.finishNode(node, "AssignmentPattern");
  7184. }
  7185. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding, strictModeChanged = false) {
  7186. switch (expr.type) {
  7187. case "Identifier":
  7188. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(expr.name, this.inModule) : isStrictBindOnlyReservedWord(expr.name))) {
  7189. this.raise(expr.start, `${bindingType === BIND_NONE ? "Assigning to" : "Binding"} '${expr.name}' in strict mode`);
  7190. }
  7191. if (checkClashes) {
  7192. const key = `_${expr.name}`;
  7193. if (checkClashes[key]) {
  7194. this.raise(expr.start, "Argument name clash");
  7195. } else {
  7196. checkClashes[key] = true;
  7197. }
  7198. }
  7199. if (disallowLetBinding && expr.name === "let") {
  7200. this.raise(expr.start, "'let' is not allowed to be used as a name in 'let' or 'const' declarations.");
  7201. }
  7202. if (!(bindingType & BIND_NONE)) {
  7203. this.scope.declareName(expr.name, bindingType, expr.start);
  7204. }
  7205. break;
  7206. case "MemberExpression":
  7207. if (bindingType !== BIND_NONE) {
  7208. this.raise(expr.start, "Binding member expression");
  7209. }
  7210. break;
  7211. case "ObjectPattern":
  7212. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  7213. let prop = _expr$properties[_i2];
  7214. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  7215. this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  7216. }
  7217. break;
  7218. case "ArrayPattern":
  7219. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  7220. const elem = _expr$elements[_i3];
  7221. if (elem) {
  7222. this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern", disallowLetBinding);
  7223. }
  7224. }
  7225. break;
  7226. case "AssignmentPattern":
  7227. this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern");
  7228. break;
  7229. case "RestElement":
  7230. this.checkLVal(expr.argument, bindingType, checkClashes, "rest element");
  7231. break;
  7232. case "ParenthesizedExpression":
  7233. this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression");
  7234. break;
  7235. default:
  7236. {
  7237. const message = (bindingType === BIND_NONE ? "Invalid" : "Binding invalid") + " left-hand side" + (contextDescription ? " in " + contextDescription : "expression");
  7238. this.raise(expr.start, message);
  7239. }
  7240. }
  7241. }
  7242. checkToRestConversion(node) {
  7243. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  7244. this.raise(node.argument.start, "Invalid rest operator's argument");
  7245. }
  7246. }
  7247. checkCommaAfterRest(close) {
  7248. if (this.match(types.comma)) {
  7249. if (this.lookaheadCharCode() === close) {
  7250. this.raiseTrailingCommaAfterRest(this.state.start);
  7251. } else {
  7252. this.raiseRestNotLast(this.state.start);
  7253. }
  7254. }
  7255. }
  7256. raiseRestNotLast(pos) {
  7257. throw this.raise(pos, `Rest element must be last element`);
  7258. }
  7259. raiseTrailingCommaAfterRest(pos) {
  7260. this.raise(pos, `Unexpected trailing comma after rest element`);
  7261. }
  7262. }
  7263. const unwrapParenthesizedExpression = node => {
  7264. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7265. };
  7266. class ExpressionParser extends LValParser {
  7267. checkDuplicatedProto(prop, protoRef) {
  7268. if (prop.type === "SpreadElement" || prop.computed || prop.kind || prop.shorthand) {
  7269. return;
  7270. }
  7271. const key = prop.key;
  7272. const name = key.type === "Identifier" ? key.name : String(key.value);
  7273. if (name === "__proto__") {
  7274. if (protoRef.used && !protoRef.start) {
  7275. protoRef.start = key.start;
  7276. }
  7277. protoRef.used = true;
  7278. }
  7279. }
  7280. getExpression() {
  7281. this.scope.enter(SCOPE_PROGRAM);
  7282. this.nextToken();
  7283. const expr = this.parseExpression();
  7284. if (!this.match(types.eof)) {
  7285. this.unexpected();
  7286. }
  7287. expr.comments = this.state.comments;
  7288. expr.errors = this.state.errors;
  7289. return expr;
  7290. }
  7291. parseExpression(noIn, refShorthandDefaultPos) {
  7292. const startPos = this.state.start;
  7293. const startLoc = this.state.startLoc;
  7294. const expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
  7295. if (this.match(types.comma)) {
  7296. const node = this.startNodeAt(startPos, startLoc);
  7297. node.expressions = [expr];
  7298. while (this.eat(types.comma)) {
  7299. node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
  7300. }
  7301. this.toReferencedList(node.expressions);
  7302. return this.finishNode(node, "SequenceExpression");
  7303. }
  7304. return expr;
  7305. }
  7306. parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) {
  7307. const startPos = this.state.start;
  7308. const startLoc = this.state.startLoc;
  7309. if (this.isContextual("yield")) {
  7310. if (this.scope.inGenerator) {
  7311. let left = this.parseYield(noIn);
  7312. if (afterLeftParse) {
  7313. left = afterLeftParse.call(this, left, startPos, startLoc);
  7314. }
  7315. return left;
  7316. } else {
  7317. this.state.exprAllowed = false;
  7318. }
  7319. }
  7320. let failOnShorthandAssign;
  7321. if (refShorthandDefaultPos) {
  7322. failOnShorthandAssign = false;
  7323. } else {
  7324. refShorthandDefaultPos = {
  7325. start: 0
  7326. };
  7327. failOnShorthandAssign = true;
  7328. }
  7329. if (this.match(types.parenL) || this.match(types.name)) {
  7330. this.state.potentialArrowAt = this.state.start;
  7331. }
  7332. let left = this.parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos);
  7333. if (afterLeftParse) {
  7334. left = afterLeftParse.call(this, left, startPos, startLoc);
  7335. }
  7336. if (this.state.type.isAssign) {
  7337. const node = this.startNodeAt(startPos, startLoc);
  7338. const operator = this.state.value;
  7339. node.operator = operator;
  7340. if (operator === "??=") {
  7341. this.expectPlugin("nullishCoalescingOperator");
  7342. this.expectPlugin("logicalAssignment");
  7343. }
  7344. if (operator === "||=" || operator === "&&=") {
  7345. this.expectPlugin("logicalAssignment");
  7346. }
  7347. node.left = this.match(types.eq) ? this.toAssignable(left, undefined, "assignment expression") : left;
  7348. if (refShorthandDefaultPos.start >= node.left.start) {
  7349. refShorthandDefaultPos.start = 0;
  7350. }
  7351. this.checkLVal(left, undefined, undefined, "assignment expression");
  7352. const maybePattern = unwrapParenthesizedExpression(left);
  7353. let patternErrorMsg;
  7354. if (maybePattern.type === "ObjectPattern") {
  7355. patternErrorMsg = "`({a}) = 0` use `({a} = 0)`";
  7356. } else if (maybePattern.type === "ArrayPattern") {
  7357. patternErrorMsg = "`([a]) = 0` use `([a] = 0)`";
  7358. }
  7359. if (patternErrorMsg && (left.extra && left.extra.parenthesized || left.type === "ParenthesizedExpression")) {
  7360. this.raise(maybePattern.start, `You're trying to assign to a parenthesized expression, eg. instead of ${patternErrorMsg}`);
  7361. }
  7362. this.next();
  7363. node.right = this.parseMaybeAssign(noIn);
  7364. return this.finishNode(node, "AssignmentExpression");
  7365. } else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
  7366. this.unexpected(refShorthandDefaultPos.start);
  7367. }
  7368. return left;
  7369. }
  7370. parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos) {
  7371. const startPos = this.state.start;
  7372. const startLoc = this.state.startLoc;
  7373. const potentialArrowAt = this.state.potentialArrowAt;
  7374. const expr = this.parseExprOps(noIn, refShorthandDefaultPos);
  7375. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7376. return expr;
  7377. }
  7378. if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
  7379. return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  7380. }
  7381. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  7382. if (this.eat(types.question)) {
  7383. const node = this.startNodeAt(startPos, startLoc);
  7384. node.test = expr;
  7385. node.consequent = this.parseMaybeAssign();
  7386. this.expect(types.colon);
  7387. node.alternate = this.parseMaybeAssign(noIn);
  7388. return this.finishNode(node, "ConditionalExpression");
  7389. }
  7390. return expr;
  7391. }
  7392. parseExprOps(noIn, refShorthandDefaultPos) {
  7393. const startPos = this.state.start;
  7394. const startLoc = this.state.startLoc;
  7395. const potentialArrowAt = this.state.potentialArrowAt;
  7396. const expr = this.parseMaybeUnary(refShorthandDefaultPos);
  7397. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7398. return expr;
  7399. }
  7400. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  7401. return expr;
  7402. }
  7403. return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
  7404. }
  7405. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  7406. const prec = this.state.type.binop;
  7407. if (prec != null && (!noIn || !this.match(types._in))) {
  7408. if (prec > minPrec) {
  7409. const operator = this.state.value;
  7410. if (operator === "|>" && this.state.inFSharpPipelineDirectBody) {
  7411. return left;
  7412. }
  7413. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  7414. node.left = left;
  7415. node.operator = operator;
  7416. if (operator === "**" && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  7417. this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");
  7418. }
  7419. const op = this.state.type;
  7420. if (op === types.pipeline) {
  7421. this.expectPlugin("pipelineOperator");
  7422. this.state.inPipeline = true;
  7423. this.checkPipelineAtInfixOperator(left, leftStartPos);
  7424. } else if (op === types.nullishCoalescing) {
  7425. this.expectPlugin("nullishCoalescingOperator");
  7426. }
  7427. this.next();
  7428. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  7429. if (this.match(types.name) && this.state.value === "await" && this.scope.inAsync) {
  7430. throw this.raise(this.state.start, `Unexpected "await" after pipeline body; await must have parentheses in minimal proposal`);
  7431. }
  7432. }
  7433. node.right = this.parseExprOpRightExpr(op, prec, noIn);
  7434. if (op === types.nullishCoalescing) {
  7435. if (left.type === "LogicalExpression" && left.operator !== "??" && !(left.extra && left.extra.parenthesized)) {
  7436. throw this.raise(left.start, `Nullish coalescing operator(??) requires parens when mixing with logical operators`);
  7437. } else if (node.right.type === "LogicalExpression" && node.right.operator !== "??" && !(node.right.extra && node.right.extra.parenthesized)) {
  7438. throw this.raise(node.right.start, `Nullish coalescing operator(??) requires parens when mixing with logical operators`);
  7439. }
  7440. }
  7441. this.finishNode(node, op === types.logicalOR || op === types.logicalAND || op === types.nullishCoalescing ? "LogicalExpression" : "BinaryExpression");
  7442. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  7443. }
  7444. }
  7445. return left;
  7446. }
  7447. parseExprOpRightExpr(op, prec, noIn) {
  7448. const startPos = this.state.start;
  7449. const startLoc = this.state.startLoc;
  7450. switch (op) {
  7451. case types.pipeline:
  7452. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  7453. case "smart":
  7454. return this.withTopicPermittingContext(() => {
  7455. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec, noIn), startPos, startLoc);
  7456. });
  7457. case "fsharp":
  7458. return this.withSoloAwaitPermittingContext(() => {
  7459. return this.parseFSharpPipelineBody(prec, noIn);
  7460. });
  7461. }
  7462. default:
  7463. return this.parseExprOpBaseRightExpr(op, prec, noIn);
  7464. }
  7465. }
  7466. parseExprOpBaseRightExpr(op, prec, noIn) {
  7467. const startPos = this.state.start;
  7468. const startLoc = this.state.startLoc;
  7469. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);
  7470. }
  7471. parseMaybeUnary(refShorthandDefaultPos) {
  7472. if (this.isContextual("await") && this.isAwaitAllowed()) {
  7473. return this.parseAwait();
  7474. } else if (this.state.type.prefix) {
  7475. const node = this.startNode();
  7476. const update = this.match(types.incDec);
  7477. node.operator = this.state.value;
  7478. node.prefix = true;
  7479. if (node.operator === "throw") {
  7480. this.expectPlugin("throwExpressions");
  7481. }
  7482. this.next();
  7483. node.argument = this.parseMaybeUnary();
  7484. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  7485. this.unexpected(refShorthandDefaultPos.start);
  7486. }
  7487. if (update) {
  7488. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  7489. } else if (this.state.strict && node.operator === "delete") {
  7490. const arg = node.argument;
  7491. if (arg.type === "Identifier") {
  7492. this.raise(node.start, "Deleting local variable in strict mode");
  7493. } else if (arg.type === "MemberExpression" && arg.property.type === "PrivateName") {
  7494. this.raise(node.start, "Deleting a private field is not allowed");
  7495. }
  7496. }
  7497. return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  7498. }
  7499. const startPos = this.state.start;
  7500. const startLoc = this.state.startLoc;
  7501. let expr = this.parseExprSubscripts(refShorthandDefaultPos);
  7502. if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
  7503. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  7504. const node = this.startNodeAt(startPos, startLoc);
  7505. node.operator = this.state.value;
  7506. node.prefix = false;
  7507. node.argument = expr;
  7508. this.checkLVal(expr, undefined, undefined, "postfix operation");
  7509. this.next();
  7510. expr = this.finishNode(node, "UpdateExpression");
  7511. }
  7512. return expr;
  7513. }
  7514. parseExprSubscripts(refShorthandDefaultPos) {
  7515. const startPos = this.state.start;
  7516. const startLoc = this.state.startLoc;
  7517. const potentialArrowAt = this.state.potentialArrowAt;
  7518. const expr = this.parseExprAtom(refShorthandDefaultPos);
  7519. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7520. return expr;
  7521. }
  7522. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  7523. return expr;
  7524. }
  7525. return this.parseSubscripts(expr, startPos, startLoc);
  7526. }
  7527. parseSubscripts(base, startPos, startLoc, noCalls) {
  7528. const state = {
  7529. optionalChainMember: false,
  7530. maybeAsyncArrow: this.atPossibleAsync(base),
  7531. stop: false
  7532. };
  7533. do {
  7534. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  7535. state.maybeAsyncArrow = false;
  7536. } while (!state.stop);
  7537. return base;
  7538. }
  7539. parseSubscript(base, startPos, startLoc, noCalls, state) {
  7540. if (!noCalls && this.eat(types.doubleColon)) {
  7541. const node = this.startNodeAt(startPos, startLoc);
  7542. node.object = base;
  7543. node.callee = this.parseNoCallExpr();
  7544. state.stop = true;
  7545. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  7546. } else if (this.match(types.questionDot)) {
  7547. this.expectPlugin("optionalChaining");
  7548. state.optionalChainMember = true;
  7549. if (noCalls && this.lookaheadCharCode() === 40) {
  7550. state.stop = true;
  7551. return base;
  7552. }
  7553. this.next();
  7554. const node = this.startNodeAt(startPos, startLoc);
  7555. if (this.eat(types.bracketL)) {
  7556. node.object = base;
  7557. node.property = this.parseExpression();
  7558. node.computed = true;
  7559. node.optional = true;
  7560. this.expect(types.bracketR);
  7561. return this.finishNode(node, "OptionalMemberExpression");
  7562. } else if (this.eat(types.parenL)) {
  7563. node.callee = base;
  7564. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  7565. node.optional = true;
  7566. return this.finishCallExpression(node, true);
  7567. } else {
  7568. node.object = base;
  7569. node.property = this.parseIdentifier(true);
  7570. node.computed = false;
  7571. node.optional = true;
  7572. return this.finishNode(node, "OptionalMemberExpression");
  7573. }
  7574. } else if (this.eat(types.dot)) {
  7575. const node = this.startNodeAt(startPos, startLoc);
  7576. node.object = base;
  7577. node.property = this.parseMaybePrivateName();
  7578. node.computed = false;
  7579. if (node.property.type === "PrivateName" && node.object.type === "Super") {
  7580. this.raise(startPos, "Private fields can't be accessed on super");
  7581. }
  7582. if (state.optionalChainMember) {
  7583. node.optional = false;
  7584. return this.finishNode(node, "OptionalMemberExpression");
  7585. }
  7586. return this.finishNode(node, "MemberExpression");
  7587. } else if (this.eat(types.bracketL)) {
  7588. const node = this.startNodeAt(startPos, startLoc);
  7589. node.object = base;
  7590. node.property = this.parseExpression();
  7591. node.computed = true;
  7592. this.expect(types.bracketR);
  7593. if (state.optionalChainMember) {
  7594. node.optional = false;
  7595. return this.finishNode(node, "OptionalMemberExpression");
  7596. }
  7597. return this.finishNode(node, "MemberExpression");
  7598. } else if (!noCalls && this.match(types.parenL)) {
  7599. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7600. const oldYieldPos = this.state.yieldPos;
  7601. const oldAwaitPos = this.state.awaitPos;
  7602. this.state.maybeInArrowParameters = true;
  7603. this.state.yieldPos = -1;
  7604. this.state.awaitPos = -1;
  7605. this.next();
  7606. let node = this.startNodeAt(startPos, startLoc);
  7607. node.callee = base;
  7608. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  7609. this.finishCallExpression(node, state.optionalChainMember);
  7610. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow()) {
  7611. state.stop = true;
  7612. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  7613. this.checkYieldAwaitInDefaultParams();
  7614. this.state.yieldPos = oldYieldPos;
  7615. this.state.awaitPos = oldAwaitPos;
  7616. } else {
  7617. this.toReferencedListDeep(node.arguments);
  7618. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  7619. if (!this.isAwaitAllowed() && !oldMaybeInArrowParameters || oldAwaitPos !== -1) {
  7620. this.state.awaitPos = oldAwaitPos;
  7621. }
  7622. }
  7623. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7624. return node;
  7625. } else if (this.match(types.backQuote)) {
  7626. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state);
  7627. } else {
  7628. state.stop = true;
  7629. return base;
  7630. }
  7631. }
  7632. parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments) {
  7633. const node = this.startNodeAt(startPos, startLoc);
  7634. node.tag = base;
  7635. node.quasi = this.parseTemplate(true);
  7636. if (typeArguments) node.typeParameters = typeArguments;
  7637. if (state.optionalChainMember) {
  7638. this.raise(startPos, "Tagged Template Literals are not allowed in optionalChain");
  7639. }
  7640. return this.finishNode(node, "TaggedTemplateExpression");
  7641. }
  7642. atPossibleAsync(base) {
  7643. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async";
  7644. }
  7645. finishCallExpression(node, optional) {
  7646. if (node.callee.type === "Import") {
  7647. if (node.arguments.length !== 1) {
  7648. this.raise(node.start, "import() requires exactly one argument");
  7649. } else {
  7650. const importArg = node.arguments[0];
  7651. if (importArg && importArg.type === "SpreadElement") {
  7652. this.raise(importArg.start, "... is not allowed in import()");
  7653. }
  7654. }
  7655. }
  7656. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  7657. }
  7658. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  7659. const elts = [];
  7660. let innerParenStart;
  7661. let first = true;
  7662. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  7663. this.state.inFSharpPipelineDirectBody = false;
  7664. while (!this.eat(close)) {
  7665. if (first) {
  7666. first = false;
  7667. } else {
  7668. this.expect(types.comma);
  7669. if (this.match(close)) {
  7670. if (dynamicImport) {
  7671. this.raise(this.state.lastTokStart, "Trailing comma is disallowed inside import(...) arguments");
  7672. }
  7673. if (nodeForExtra) {
  7674. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  7675. }
  7676. this.next();
  7677. break;
  7678. }
  7679. }
  7680. if (this.match(types.parenL) && !innerParenStart) {
  7681. innerParenStart = this.state.start;
  7682. }
  7683. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? {
  7684. start: 0
  7685. } : undefined, possibleAsyncArrow ? {
  7686. start: 0
  7687. } : undefined, allowPlaceholder));
  7688. }
  7689. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  7690. this.unexpected();
  7691. }
  7692. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  7693. return elts;
  7694. }
  7695. shouldParseAsyncArrow() {
  7696. return this.match(types.arrow) && !this.canInsertSemicolon();
  7697. }
  7698. parseAsyncArrowFromCallExpression(node, call) {
  7699. var _call$extra;
  7700. this.expect(types.arrow);
  7701. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  7702. return node;
  7703. }
  7704. parseNoCallExpr() {
  7705. const startPos = this.state.start;
  7706. const startLoc = this.state.startLoc;
  7707. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  7708. }
  7709. parseExprAtom(refShorthandDefaultPos) {
  7710. if (this.state.type === types.slash) this.readRegexp();
  7711. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  7712. let node;
  7713. switch (this.state.type) {
  7714. case types._super:
  7715. node = this.startNode();
  7716. this.next();
  7717. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  7718. this.raise(node.start, "super() is only valid inside a class constructor of a subclass. " + "Maybe a typo in the method name ('constructor') or not extending another class?");
  7719. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  7720. this.raise(node.start, "super is only allowed in object methods and classes");
  7721. }
  7722. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  7723. this.raise(node.start, "super can only be used with function calls (i.e. super()) or " + "in property accesses (i.e. super.prop or super[prop])");
  7724. }
  7725. return this.finishNode(node, "Super");
  7726. case types._import:
  7727. node = this.startNode();
  7728. this.next();
  7729. if (this.match(types.dot)) {
  7730. return this.parseImportMetaProperty(node);
  7731. }
  7732. this.expectPlugin("dynamicImport", node.start);
  7733. if (!this.match(types.parenL)) {
  7734. this.unexpected(null, types.parenL);
  7735. }
  7736. return this.finishNode(node, "Import");
  7737. case types._this:
  7738. node = this.startNode();
  7739. this.next();
  7740. return this.finishNode(node, "ThisExpression");
  7741. case types.name:
  7742. {
  7743. node = this.startNode();
  7744. const containsEsc = this.state.containsEsc;
  7745. const id = this.parseIdentifier();
  7746. if (!containsEsc && id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) {
  7747. this.next();
  7748. return this.parseFunction(node, undefined, true);
  7749. } else if (canBeArrow && !containsEsc && id.name === "async" && this.match(types.name) && !this.canInsertSemicolon()) {
  7750. const params = [this.parseIdentifier()];
  7751. this.expect(types.arrow);
  7752. this.parseArrowExpression(node, params, true);
  7753. return node;
  7754. }
  7755. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  7756. this.next();
  7757. this.parseArrowExpression(node, [id], false);
  7758. return node;
  7759. }
  7760. return id;
  7761. }
  7762. case types._do:
  7763. {
  7764. this.expectPlugin("doExpressions");
  7765. const node = this.startNode();
  7766. this.next();
  7767. const oldLabels = this.state.labels;
  7768. this.state.labels = [];
  7769. node.body = this.parseBlock();
  7770. this.state.labels = oldLabels;
  7771. return this.finishNode(node, "DoExpression");
  7772. }
  7773. case types.regexp:
  7774. {
  7775. const value = this.state.value;
  7776. node = this.parseLiteral(value.value, "RegExpLiteral");
  7777. node.pattern = value.pattern;
  7778. node.flags = value.flags;
  7779. return node;
  7780. }
  7781. case types.num:
  7782. return this.parseLiteral(this.state.value, "NumericLiteral");
  7783. case types.bigint:
  7784. return this.parseLiteral(this.state.value, "BigIntLiteral");
  7785. case types.string:
  7786. return this.parseLiteral(this.state.value, "StringLiteral");
  7787. case types._null:
  7788. node = this.startNode();
  7789. this.next();
  7790. return this.finishNode(node, "NullLiteral");
  7791. case types._true:
  7792. case types._false:
  7793. return this.parseBooleanLiteral();
  7794. case types.parenL:
  7795. return this.parseParenAndDistinguishExpression(canBeArrow);
  7796. case types.bracketL:
  7797. {
  7798. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  7799. this.state.inFSharpPipelineDirectBody = false;
  7800. node = this.startNode();
  7801. this.next();
  7802. node.elements = this.parseExprList(types.bracketR, true, refShorthandDefaultPos, node);
  7803. if (!this.state.maybeInArrowParameters) {
  7804. this.toReferencedList(node.elements);
  7805. }
  7806. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  7807. return this.finishNode(node, "ArrayExpression");
  7808. }
  7809. case types.braceL:
  7810. {
  7811. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  7812. this.state.inFSharpPipelineDirectBody = false;
  7813. const ret = this.parseObj(false, refShorthandDefaultPos);
  7814. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  7815. return ret;
  7816. }
  7817. case types._function:
  7818. return this.parseFunctionExpression();
  7819. case types.at:
  7820. this.parseDecorators();
  7821. case types._class:
  7822. node = this.startNode();
  7823. this.takeDecorators(node);
  7824. return this.parseClass(node, false);
  7825. case types._new:
  7826. return this.parseNew();
  7827. case types.backQuote:
  7828. return this.parseTemplate(false);
  7829. case types.doubleColon:
  7830. {
  7831. node = this.startNode();
  7832. this.next();
  7833. node.object = null;
  7834. const callee = node.callee = this.parseNoCallExpr();
  7835. if (callee.type === "MemberExpression") {
  7836. return this.finishNode(node, "BindExpression");
  7837. } else {
  7838. throw this.raise(callee.start, "Binding should be performed on object property.");
  7839. }
  7840. }
  7841. case types.hash:
  7842. {
  7843. if (this.state.inPipeline) {
  7844. node = this.startNode();
  7845. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  7846. this.raise(node.start, "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.");
  7847. }
  7848. this.next();
  7849. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  7850. this.raise(node.start, `Topic reference was used in a lexical context without topic binding`);
  7851. }
  7852. this.registerTopicReference();
  7853. return this.finishNode(node, "PipelinePrimaryTopicReference");
  7854. }
  7855. }
  7856. default:
  7857. throw this.unexpected();
  7858. }
  7859. }
  7860. parseBooleanLiteral() {
  7861. const node = this.startNode();
  7862. node.value = this.match(types._true);
  7863. this.next();
  7864. return this.finishNode(node, "BooleanLiteral");
  7865. }
  7866. parseMaybePrivateName() {
  7867. const isPrivate = this.match(types.hash);
  7868. if (isPrivate) {
  7869. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  7870. const node = this.startNode();
  7871. this.next();
  7872. this.assertNoSpace("Unexpected space between # and identifier");
  7873. node.id = this.parseIdentifier(true);
  7874. return this.finishNode(node, "PrivateName");
  7875. } else {
  7876. return this.parseIdentifier(true);
  7877. }
  7878. }
  7879. parseFunctionExpression() {
  7880. const node = this.startNode();
  7881. let meta = this.startNode();
  7882. this.next();
  7883. meta = this.createIdentifier(meta, "function");
  7884. if (this.scope.inGenerator && this.eat(types.dot)) {
  7885. return this.parseMetaProperty(node, meta, "sent");
  7886. }
  7887. return this.parseFunction(node);
  7888. }
  7889. parseMetaProperty(node, meta, propertyName) {
  7890. node.meta = meta;
  7891. if (meta.name === "function" && propertyName === "sent") {
  7892. if (this.isContextual(propertyName)) {
  7893. this.expectPlugin("functionSent");
  7894. } else if (!this.hasPlugin("functionSent")) {
  7895. this.unexpected();
  7896. }
  7897. }
  7898. const containsEsc = this.state.containsEsc;
  7899. node.property = this.parseIdentifier(true);
  7900. if (node.property.name !== propertyName || containsEsc) {
  7901. this.raise(node.property.start, `The only valid meta property for ${meta.name} is ${meta.name}.${propertyName}`);
  7902. }
  7903. return this.finishNode(node, "MetaProperty");
  7904. }
  7905. parseImportMetaProperty(node) {
  7906. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  7907. this.expect(types.dot);
  7908. if (this.isContextual("meta")) {
  7909. this.expectPlugin("importMeta");
  7910. if (!this.inModule) {
  7911. this.raise(id.start, `import.meta may appear only with 'sourceType: "module"'`, {
  7912. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  7913. });
  7914. }
  7915. this.sawUnambiguousESM = true;
  7916. } else if (!this.hasPlugin("importMeta")) {
  7917. this.raise(id.start, `Dynamic imports require a parameter: import('a.js')`);
  7918. }
  7919. return this.parseMetaProperty(node, id, "meta");
  7920. }
  7921. parseLiteral(value, type, startPos, startLoc) {
  7922. startPos = startPos || this.state.start;
  7923. startLoc = startLoc || this.state.startLoc;
  7924. const node = this.startNodeAt(startPos, startLoc);
  7925. this.addExtra(node, "rawValue", value);
  7926. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  7927. node.value = value;
  7928. this.next();
  7929. return this.finishNode(node, type);
  7930. }
  7931. parseParenAndDistinguishExpression(canBeArrow) {
  7932. const startPos = this.state.start;
  7933. const startLoc = this.state.startLoc;
  7934. let val;
  7935. this.expect(types.parenL);
  7936. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7937. const oldYieldPos = this.state.yieldPos;
  7938. const oldAwaitPos = this.state.awaitPos;
  7939. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  7940. this.state.maybeInArrowParameters = true;
  7941. this.state.yieldPos = -1;
  7942. this.state.awaitPos = -1;
  7943. this.state.inFSharpPipelineDirectBody = false;
  7944. const innerStartPos = this.state.start;
  7945. const innerStartLoc = this.state.startLoc;
  7946. const exprList = [];
  7947. const refShorthandDefaultPos = {
  7948. start: 0
  7949. };
  7950. const refNeedsArrowPos = {
  7951. start: 0
  7952. };
  7953. let first = true;
  7954. let spreadStart;
  7955. let optionalCommaStart;
  7956. while (!this.match(types.parenR)) {
  7957. if (first) {
  7958. first = false;
  7959. } else {
  7960. this.expect(types.comma, refNeedsArrowPos.start || null);
  7961. if (this.match(types.parenR)) {
  7962. optionalCommaStart = this.state.start;
  7963. break;
  7964. }
  7965. }
  7966. if (this.match(types.ellipsis)) {
  7967. const spreadNodeStartPos = this.state.start;
  7968. const spreadNodeStartLoc = this.state.startLoc;
  7969. spreadStart = this.state.start;
  7970. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  7971. this.checkCommaAfterRest(41);
  7972. break;
  7973. } else {
  7974. exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos));
  7975. }
  7976. }
  7977. const innerEndPos = this.state.start;
  7978. const innerEndLoc = this.state.startLoc;
  7979. this.expect(types.parenR);
  7980. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7981. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  7982. let arrowNode = this.startNodeAt(startPos, startLoc);
  7983. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  7984. this.checkYieldAwaitInDefaultParams();
  7985. this.state.yieldPos = oldYieldPos;
  7986. this.state.awaitPos = oldAwaitPos;
  7987. for (let _i = 0; _i < exprList.length; _i++) {
  7988. const param = exprList[_i];
  7989. if (param.extra && param.extra.parenthesized) {
  7990. this.unexpected(param.extra.parenStart);
  7991. }
  7992. }
  7993. this.parseArrowExpression(arrowNode, exprList, false);
  7994. return arrowNode;
  7995. }
  7996. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  7997. if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos;
  7998. if (!exprList.length) {
  7999. this.unexpected(this.state.lastTokStart);
  8000. }
  8001. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  8002. if (spreadStart) this.unexpected(spreadStart);
  8003. if (refShorthandDefaultPos.start) {
  8004. this.unexpected(refShorthandDefaultPos.start);
  8005. }
  8006. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  8007. this.toReferencedListDeep(exprList, true);
  8008. if (exprList.length > 1) {
  8009. val = this.startNodeAt(innerStartPos, innerStartLoc);
  8010. val.expressions = exprList;
  8011. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  8012. } else {
  8013. val = exprList[0];
  8014. }
  8015. if (!this.options.createParenthesizedExpressions) {
  8016. this.addExtra(val, "parenthesized", true);
  8017. this.addExtra(val, "parenStart", startPos);
  8018. return val;
  8019. }
  8020. const parenExpression = this.startNodeAt(startPos, startLoc);
  8021. parenExpression.expression = val;
  8022. this.finishNode(parenExpression, "ParenthesizedExpression");
  8023. return parenExpression;
  8024. }
  8025. shouldParseArrow() {
  8026. return !this.canInsertSemicolon();
  8027. }
  8028. parseArrow(node) {
  8029. if (this.eat(types.arrow)) {
  8030. return node;
  8031. }
  8032. }
  8033. parseParenItem(node, startPos, startLoc) {
  8034. return node;
  8035. }
  8036. parseNew() {
  8037. const node = this.startNode();
  8038. let meta = this.startNode();
  8039. this.next();
  8040. meta = this.createIdentifier(meta, "new");
  8041. if (this.eat(types.dot)) {
  8042. const metaProp = this.parseMetaProperty(node, meta, "target");
  8043. if (!this.scope.inNonArrowFunction && !this.state.inClassProperty) {
  8044. let error = "new.target can only be used in functions";
  8045. if (this.hasPlugin("classProperties")) {
  8046. error += " or class properties";
  8047. }
  8048. this.raise(metaProp.start, error);
  8049. }
  8050. return metaProp;
  8051. }
  8052. node.callee = this.parseNoCallExpr();
  8053. if (node.callee.type === "Import") {
  8054. this.raise(node.callee.start, "Cannot use new with import(...)");
  8055. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  8056. this.raise(this.state.lastTokEnd, "constructors in/after an Optional Chain are not allowed");
  8057. } else if (this.eat(types.questionDot)) {
  8058. this.raise(this.state.start, "constructors in/after an Optional Chain are not allowed");
  8059. }
  8060. this.parseNewArguments(node);
  8061. return this.finishNode(node, "NewExpression");
  8062. }
  8063. parseNewArguments(node) {
  8064. if (this.eat(types.parenL)) {
  8065. const args = this.parseExprList(types.parenR);
  8066. this.toReferencedList(args);
  8067. node.arguments = args;
  8068. } else {
  8069. node.arguments = [];
  8070. }
  8071. }
  8072. parseTemplateElement(isTagged) {
  8073. const elem = this.startNode();
  8074. if (this.state.value === null) {
  8075. if (!isTagged) {
  8076. this.raise(this.state.invalidTemplateEscapePosition || 0, "Invalid escape sequence in template");
  8077. } else {
  8078. this.state.invalidTemplateEscapePosition = null;
  8079. }
  8080. }
  8081. elem.value = {
  8082. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  8083. cooked: this.state.value
  8084. };
  8085. this.next();
  8086. elem.tail = this.match(types.backQuote);
  8087. return this.finishNode(elem, "TemplateElement");
  8088. }
  8089. parseTemplate(isTagged) {
  8090. const node = this.startNode();
  8091. this.next();
  8092. node.expressions = [];
  8093. let curElt = this.parseTemplateElement(isTagged);
  8094. node.quasis = [curElt];
  8095. while (!curElt.tail) {
  8096. this.expect(types.dollarBraceL);
  8097. node.expressions.push(this.parseExpression());
  8098. this.expect(types.braceR);
  8099. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  8100. }
  8101. this.next();
  8102. return this.finishNode(node, "TemplateLiteral");
  8103. }
  8104. parseObj(isPattern, refShorthandDefaultPos) {
  8105. const propHash = Object.create(null);
  8106. let first = true;
  8107. const node = this.startNode();
  8108. node.properties = [];
  8109. this.next();
  8110. while (!this.eat(types.braceR)) {
  8111. if (first) {
  8112. first = false;
  8113. } else {
  8114. this.expect(types.comma);
  8115. if (this.match(types.braceR)) {
  8116. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  8117. this.next();
  8118. break;
  8119. }
  8120. }
  8121. const prop = this.parseObjectMember(isPattern, refShorthandDefaultPos);
  8122. if (!isPattern) this.checkDuplicatedProto(prop, propHash);
  8123. if (prop.shorthand) {
  8124. this.addExtra(prop, "shorthand", true);
  8125. }
  8126. node.properties.push(prop);
  8127. }
  8128. if (!this.match(types.eq) && propHash.start !== undefined) {
  8129. this.raise(propHash.start, "Redefinition of __proto__ property");
  8130. }
  8131. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
  8132. }
  8133. isAsyncProp(prop) {
  8134. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.match(types.name) || this.match(types.num) || this.match(types.string) || this.match(types.bracketL) || this.state.type.keyword || this.match(types.star)) && !this.hasPrecedingLineBreak();
  8135. }
  8136. parseObjectMember(isPattern, refShorthandDefaultPos) {
  8137. let decorators = [];
  8138. if (this.match(types.at)) {
  8139. if (this.hasPlugin("decorators")) {
  8140. this.raise(this.state.start, "Stage 2 decorators disallow object literal property decorators");
  8141. }
  8142. while (this.match(types.at)) {
  8143. decorators.push(this.parseDecorator());
  8144. }
  8145. }
  8146. const prop = this.startNode();
  8147. let isGenerator = false;
  8148. let isAsync = false;
  8149. let startPos;
  8150. let startLoc;
  8151. if (this.match(types.ellipsis)) {
  8152. if (decorators.length) this.unexpected();
  8153. if (isPattern) {
  8154. this.next();
  8155. prop.argument = this.parseIdentifier();
  8156. this.checkCommaAfterRest(125);
  8157. return this.finishNode(prop, "RestElement");
  8158. }
  8159. return this.parseSpread();
  8160. }
  8161. if (decorators.length) {
  8162. prop.decorators = decorators;
  8163. decorators = [];
  8164. }
  8165. prop.method = false;
  8166. if (isPattern || refShorthandDefaultPos) {
  8167. startPos = this.state.start;
  8168. startLoc = this.state.startLoc;
  8169. }
  8170. if (!isPattern) {
  8171. isGenerator = this.eat(types.star);
  8172. }
  8173. const containsEsc = this.state.containsEsc;
  8174. this.parsePropertyName(prop);
  8175. if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) {
  8176. isAsync = true;
  8177. isGenerator = this.eat(types.star);
  8178. this.parsePropertyName(prop);
  8179. } else {
  8180. isAsync = false;
  8181. }
  8182. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc);
  8183. return prop;
  8184. }
  8185. isGetterOrSetterMethod(prop, isPattern) {
  8186. return !isPattern && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.match(types.string) || this.match(types.num) || this.match(types.bracketL) || this.match(types.name) || !!this.state.type.keyword);
  8187. }
  8188. getGetterSetterExpectedParamCount(method) {
  8189. return method.kind === "get" ? 0 : 1;
  8190. }
  8191. checkGetterSetterParams(method) {
  8192. const paramCount = this.getGetterSetterExpectedParamCount(method);
  8193. const start = method.start;
  8194. if (method.params.length !== paramCount) {
  8195. if (method.kind === "get") {
  8196. this.raise(start, "getter must not have any formal parameters");
  8197. } else {
  8198. this.raise(start, "setter must have exactly one formal parameter");
  8199. }
  8200. }
  8201. if (method.kind === "set" && method.params[method.params.length - 1].type === "RestElement") {
  8202. this.raise(start, "setter function argument must not be a rest parameter");
  8203. }
  8204. }
  8205. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  8206. if (isAsync || isGenerator || this.match(types.parenL)) {
  8207. if (isPattern) this.unexpected();
  8208. prop.kind = "method";
  8209. prop.method = true;
  8210. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  8211. }
  8212. if (!containsEsc && this.isGetterOrSetterMethod(prop, isPattern)) {
  8213. if (isGenerator || isAsync) this.unexpected();
  8214. prop.kind = prop.key.name;
  8215. this.parsePropertyName(prop);
  8216. this.parseMethod(prop, false, false, false, false, "ObjectMethod");
  8217. this.checkGetterSetterParams(prop);
  8218. return prop;
  8219. }
  8220. }
  8221. parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos) {
  8222. prop.shorthand = false;
  8223. if (this.eat(types.colon)) {
  8224. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos);
  8225. return this.finishNode(prop, "ObjectProperty");
  8226. }
  8227. if (!prop.computed && prop.key.type === "Identifier") {
  8228. this.checkReservedWord(prop.key.name, prop.key.start, true, true);
  8229. if (isPattern) {
  8230. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8231. } else if (this.match(types.eq) && refShorthandDefaultPos) {
  8232. if (!refShorthandDefaultPos.start) {
  8233. refShorthandDefaultPos.start = this.state.start;
  8234. }
  8235. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8236. } else {
  8237. prop.value = prop.key.__clone();
  8238. }
  8239. prop.shorthand = true;
  8240. return this.finishNode(prop, "ObjectProperty");
  8241. }
  8242. }
  8243. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc) {
  8244. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos);
  8245. if (!node) this.unexpected();
  8246. return node;
  8247. }
  8248. parsePropertyName(prop) {
  8249. if (this.eat(types.bracketL)) {
  8250. prop.computed = true;
  8251. prop.key = this.parseMaybeAssign();
  8252. this.expect(types.bracketR);
  8253. } else {
  8254. const oldInPropertyName = this.state.inPropertyName;
  8255. this.state.inPropertyName = true;
  8256. prop.key = this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseMaybePrivateName();
  8257. if (prop.key.type !== "PrivateName") {
  8258. prop.computed = false;
  8259. }
  8260. this.state.inPropertyName = oldInPropertyName;
  8261. }
  8262. return prop.key;
  8263. }
  8264. initFunction(node, isAsync) {
  8265. node.id = null;
  8266. node.generator = false;
  8267. node.async = !!isAsync;
  8268. }
  8269. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  8270. const oldYieldPos = this.state.yieldPos;
  8271. const oldAwaitPos = this.state.awaitPos;
  8272. this.state.yieldPos = -1;
  8273. this.state.awaitPos = -1;
  8274. this.initFunction(node, isAsync);
  8275. node.generator = !!isGenerator;
  8276. const allowModifiers = isConstructor;
  8277. this.scope.enter(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  8278. this.parseFunctionParams(node, allowModifiers);
  8279. this.checkYieldAwaitInDefaultParams();
  8280. this.parseFunctionBodyAndFinish(node, type, true);
  8281. this.scope.exit();
  8282. this.state.yieldPos = oldYieldPos;
  8283. this.state.awaitPos = oldAwaitPos;
  8284. return node;
  8285. }
  8286. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  8287. this.scope.enter(functionFlags(isAsync, false) | SCOPE_ARROW);
  8288. this.initFunction(node, isAsync);
  8289. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8290. const oldYieldPos = this.state.yieldPos;
  8291. const oldAwaitPos = this.state.awaitPos;
  8292. this.state.maybeInArrowParameters = false;
  8293. this.state.yieldPos = -1;
  8294. this.state.awaitPos = -1;
  8295. if (params) this.setArrowFunctionParameters(node, params, trailingCommaPos);
  8296. this.parseFunctionBody(node, true);
  8297. this.scope.exit();
  8298. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8299. this.state.yieldPos = oldYieldPos;
  8300. this.state.awaitPos = oldAwaitPos;
  8301. return this.finishNode(node, "ArrowFunctionExpression");
  8302. }
  8303. setArrowFunctionParameters(node, params, trailingCommaPos) {
  8304. node.params = this.toAssignableList(params, true, "arrow function parameters", trailingCommaPos);
  8305. }
  8306. isStrictBody(node) {
  8307. const isBlockStatement = node.body.type === "BlockStatement";
  8308. if (isBlockStatement && node.body.directives.length) {
  8309. for (let _i2 = 0, _node$body$directives = node.body.directives; _i2 < _node$body$directives.length; _i2++) {
  8310. const directive = _node$body$directives[_i2];
  8311. if (directive.value.value === "use strict") {
  8312. return true;
  8313. }
  8314. }
  8315. }
  8316. return false;
  8317. }
  8318. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8319. this.parseFunctionBody(node, false, isMethod);
  8320. this.finishNode(node, type);
  8321. }
  8322. parseFunctionBody(node, allowExpression, isMethod = false) {
  8323. const isExpression = allowExpression && !this.match(types.braceL);
  8324. const oldStrict = this.state.strict;
  8325. let useStrict = false;
  8326. const oldInParameters = this.state.inParameters;
  8327. this.state.inParameters = false;
  8328. if (isExpression) {
  8329. node.body = this.parseMaybeAssign();
  8330. this.checkParams(node, false, allowExpression, false);
  8331. } else {
  8332. const nonSimple = !this.isSimpleParamList(node.params);
  8333. if (!oldStrict || nonSimple) {
  8334. useStrict = this.strictDirective(this.state.end);
  8335. if (useStrict && nonSimple) {
  8336. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  8337. this.raise(errorPos, "Illegal 'use strict' directive in function with non-simple parameter list");
  8338. }
  8339. }
  8340. const oldLabels = this.state.labels;
  8341. this.state.labels = [];
  8342. if (useStrict) this.state.strict = true;
  8343. this.checkParams(node, !oldStrict && !useStrict && !allowExpression && !isMethod && !nonSimple, allowExpression, !oldStrict && useStrict);
  8344. node.body = this.parseBlock(true, false);
  8345. this.state.labels = oldLabels;
  8346. }
  8347. this.state.inParameters = oldInParameters;
  8348. if (this.state.strict && node.id) {
  8349. this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name", undefined, !oldStrict && useStrict);
  8350. }
  8351. this.state.strict = oldStrict;
  8352. }
  8353. isSimpleParamList(params) {
  8354. for (let i = 0, len = params.length; i < len; i++) {
  8355. if (params[i].type !== "Identifier") return false;
  8356. }
  8357. return true;
  8358. }
  8359. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  8360. const nameHash = Object.create(null);
  8361. for (let i = 0; i < node.params.length; i++) {
  8362. this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function parameter list", undefined, strictModeChanged);
  8363. }
  8364. }
  8365. parseExprList(close, allowEmpty, refShorthandDefaultPos, nodeForExtra) {
  8366. const elts = [];
  8367. let first = true;
  8368. while (!this.eat(close)) {
  8369. if (first) {
  8370. first = false;
  8371. } else {
  8372. this.expect(types.comma);
  8373. if (this.match(close)) {
  8374. if (nodeForExtra) {
  8375. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8376. }
  8377. this.next();
  8378. break;
  8379. }
  8380. }
  8381. elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos));
  8382. }
  8383. return elts;
  8384. }
  8385. parseExprListItem(allowEmpty, refShorthandDefaultPos, refNeedsArrowPos, allowPlaceholder) {
  8386. let elt;
  8387. if (allowEmpty && this.match(types.comma)) {
  8388. elt = null;
  8389. } else if (this.match(types.ellipsis)) {
  8390. const spreadNodeStartPos = this.state.start;
  8391. const spreadNodeStartLoc = this.state.startLoc;
  8392. elt = this.parseParenItem(this.parseSpread(refShorthandDefaultPos, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  8393. } else if (this.match(types.question)) {
  8394. this.expectPlugin("partialApplication");
  8395. if (!allowPlaceholder) {
  8396. this.raise(this.state.start, "Unexpected argument placeholder");
  8397. }
  8398. const node = this.startNode();
  8399. this.next();
  8400. elt = this.finishNode(node, "ArgumentPlaceholder");
  8401. } else {
  8402. elt = this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos);
  8403. }
  8404. return elt;
  8405. }
  8406. parseIdentifier(liberal) {
  8407. const node = this.startNode();
  8408. const name = this.parseIdentifierName(node.start, liberal);
  8409. return this.createIdentifier(node, name);
  8410. }
  8411. createIdentifier(node, name) {
  8412. node.name = name;
  8413. node.loc.identifierName = name;
  8414. return this.finishNode(node, "Identifier");
  8415. }
  8416. parseIdentifierName(pos, liberal) {
  8417. let name;
  8418. if (this.match(types.name)) {
  8419. name = this.state.value;
  8420. } else if (this.state.type.keyword) {
  8421. name = this.state.type.keyword;
  8422. if ((name === "class" || name === "function") && (this.state.lastTokEnd !== this.state.lastTokStart + 1 || this.input.charCodeAt(this.state.lastTokStart) !== 46)) {
  8423. this.state.context.pop();
  8424. }
  8425. } else {
  8426. throw this.unexpected();
  8427. }
  8428. if (liberal) {
  8429. this.state.type = types.name;
  8430. } else {
  8431. this.checkReservedWord(name, this.state.start, !!this.state.type.keyword, false);
  8432. }
  8433. this.next();
  8434. return name;
  8435. }
  8436. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  8437. if (this.scope.inGenerator && word === "yield") {
  8438. this.raise(startLoc, "Can not use 'yield' as identifier inside a generator");
  8439. return;
  8440. }
  8441. if (word === "await") {
  8442. if (this.scope.inAsync) {
  8443. this.raise(startLoc, "Can not use 'await' as identifier inside an async function");
  8444. return;
  8445. }
  8446. if (this.state.awaitPos === -1 && (this.state.maybeInArrowParameters || this.isAwaitAllowed())) {
  8447. this.state.awaitPos = this.state.start;
  8448. }
  8449. }
  8450. if (this.state.inClassProperty && word === "arguments") {
  8451. this.raise(startLoc, "'arguments' is not allowed in class field initializer");
  8452. return;
  8453. }
  8454. if (checkKeywords && isKeyword(word)) {
  8455. this.raise(startLoc, `Unexpected keyword '${word}'`);
  8456. return;
  8457. }
  8458. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  8459. if (reservedTest(word, this.inModule)) {
  8460. if (!this.scope.inAsync && word === "await") {
  8461. this.raise(startLoc, "Can not use keyword 'await' outside an async function");
  8462. } else {
  8463. this.raise(startLoc, `Unexpected reserved word '${word}'`);
  8464. }
  8465. }
  8466. }
  8467. isAwaitAllowed() {
  8468. if (this.scope.inFunction) return this.scope.inAsync;
  8469. if (this.options.allowAwaitOutsideFunction) return true;
  8470. if (this.hasPlugin("topLevelAwait")) return this.inModule;
  8471. return false;
  8472. }
  8473. parseAwait() {
  8474. const node = this.startNode();
  8475. this.next();
  8476. if (this.state.inParameters) {
  8477. this.raise(node.start, "await is not allowed in async function parameters");
  8478. } else if (this.state.awaitPos === -1) {
  8479. this.state.awaitPos = node.start;
  8480. }
  8481. if (this.eat(types.star)) {
  8482. this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead.");
  8483. }
  8484. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  8485. if (this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo)) {
  8486. this.ambiguousScriptDifferentAst = true;
  8487. } else {
  8488. this.sawUnambiguousESM = true;
  8489. }
  8490. }
  8491. if (!this.state.soloAwait) {
  8492. node.argument = this.parseMaybeUnary();
  8493. }
  8494. return this.finishNode(node, "AwaitExpression");
  8495. }
  8496. parseYield(noIn) {
  8497. const node = this.startNode();
  8498. if (this.state.inParameters) {
  8499. this.raise(node.start, "yield is not allowed in generator parameters");
  8500. } else if (this.state.yieldPos === -1) {
  8501. this.state.yieldPos = node.start;
  8502. }
  8503. this.next();
  8504. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  8505. node.delegate = false;
  8506. node.argument = null;
  8507. } else {
  8508. node.delegate = this.eat(types.star);
  8509. node.argument = this.parseMaybeAssign(noIn);
  8510. }
  8511. return this.finishNode(node, "YieldExpression");
  8512. }
  8513. checkPipelineAtInfixOperator(left, leftStartPos) {
  8514. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  8515. if (left.type === "SequenceExpression") {
  8516. this.raise(leftStartPos, `Pipeline head should not be a comma-separated sequence expression`);
  8517. }
  8518. }
  8519. }
  8520. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  8521. const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression);
  8522. this.checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos);
  8523. return this.parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc);
  8524. }
  8525. checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos) {
  8526. if (this.match(types.arrow)) {
  8527. throw this.raise(this.state.start, `Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized`);
  8528. } else if (pipelineStyle === "PipelineTopicExpression" && childExpression.type === "SequenceExpression") {
  8529. this.raise(startPos, `Pipeline body may not be a comma-separated sequence expression`);
  8530. }
  8531. }
  8532. parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc) {
  8533. const bodyNode = this.startNodeAt(startPos, startLoc);
  8534. switch (pipelineStyle) {
  8535. case "PipelineBareFunction":
  8536. bodyNode.callee = childExpression;
  8537. break;
  8538. case "PipelineBareConstructor":
  8539. bodyNode.callee = childExpression.callee;
  8540. break;
  8541. case "PipelineBareAwaitedFunction":
  8542. bodyNode.callee = childExpression.argument;
  8543. break;
  8544. case "PipelineTopicExpression":
  8545. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  8546. this.raise(startPos, `Pipeline is in topic style but does not use topic reference`);
  8547. }
  8548. bodyNode.expression = childExpression;
  8549. break;
  8550. default:
  8551. throw new Error(`Internal @babel/parser error: Unknown pipeline style (${pipelineStyle})`);
  8552. }
  8553. return this.finishNode(bodyNode, pipelineStyle);
  8554. }
  8555. checkSmartPipelineBodyStyle(expression) {
  8556. switch (expression.type) {
  8557. default:
  8558. return this.isSimpleReference(expression) ? "PipelineBareFunction" : "PipelineTopicExpression";
  8559. }
  8560. }
  8561. isSimpleReference(expression) {
  8562. switch (expression.type) {
  8563. case "MemberExpression":
  8564. return !expression.computed && this.isSimpleReference(expression.object);
  8565. case "Identifier":
  8566. return true;
  8567. default:
  8568. return false;
  8569. }
  8570. }
  8571. withTopicPermittingContext(callback) {
  8572. const outerContextTopicState = this.state.topicContext;
  8573. this.state.topicContext = {
  8574. maxNumOfResolvableTopics: 1,
  8575. maxTopicIndex: null
  8576. };
  8577. try {
  8578. return callback();
  8579. } finally {
  8580. this.state.topicContext = outerContextTopicState;
  8581. }
  8582. }
  8583. withTopicForbiddingContext(callback) {
  8584. const outerContextTopicState = this.state.topicContext;
  8585. this.state.topicContext = {
  8586. maxNumOfResolvableTopics: 0,
  8587. maxTopicIndex: null
  8588. };
  8589. try {
  8590. return callback();
  8591. } finally {
  8592. this.state.topicContext = outerContextTopicState;
  8593. }
  8594. }
  8595. withSoloAwaitPermittingContext(callback) {
  8596. const outerContextSoloAwaitState = this.state.soloAwait;
  8597. this.state.soloAwait = true;
  8598. try {
  8599. return callback();
  8600. } finally {
  8601. this.state.soloAwait = outerContextSoloAwaitState;
  8602. }
  8603. }
  8604. registerTopicReference() {
  8605. this.state.topicContext.maxTopicIndex = 0;
  8606. }
  8607. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  8608. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  8609. }
  8610. topicReferenceWasUsedInCurrentTopicContext() {
  8611. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  8612. }
  8613. parseFSharpPipelineBody(prec, noIn) {
  8614. const startPos = this.state.start;
  8615. const startLoc = this.state.startLoc;
  8616. this.state.potentialArrowAt = this.state.start;
  8617. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8618. this.state.inFSharpPipelineDirectBody = true;
  8619. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
  8620. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8621. return ret;
  8622. }
  8623. }
  8624. const loopLabel = {
  8625. kind: "loop"
  8626. },
  8627. switchLabel = {
  8628. kind: "switch"
  8629. };
  8630. const FUNC_NO_FLAGS = 0b000,
  8631. FUNC_STATEMENT = 0b001,
  8632. FUNC_HANGING_STATEMENT = 0b010,
  8633. FUNC_NULLABLE_ID = 0b100;
  8634. class StatementParser extends ExpressionParser {
  8635. parseTopLevel(file, program) {
  8636. program.sourceType = this.options.sourceType;
  8637. program.interpreter = this.parseInterpreterDirective();
  8638. this.parseBlockBody(program, true, true, types.eof);
  8639. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  8640. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  8641. const [name] = _Array$from[_i];
  8642. const pos = this.scope.undefinedExports.get(name);
  8643. this.raise(pos, `Export '${name}' is not defined`);
  8644. }
  8645. }
  8646. file.program = this.finishNode(program, "Program");
  8647. file.comments = this.state.comments;
  8648. if (this.options.tokens) file.tokens = this.state.tokens;
  8649. return this.finishNode(file, "File");
  8650. }
  8651. stmtToDirective(stmt) {
  8652. const expr = stmt.expression;
  8653. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  8654. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  8655. const raw = this.input.slice(expr.start, expr.end);
  8656. const val = directiveLiteral.value = raw.slice(1, -1);
  8657. this.addExtra(directiveLiteral, "raw", raw);
  8658. this.addExtra(directiveLiteral, "rawValue", val);
  8659. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  8660. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  8661. }
  8662. parseInterpreterDirective() {
  8663. if (!this.match(types.interpreterDirective)) {
  8664. return null;
  8665. }
  8666. const node = this.startNode();
  8667. node.value = this.state.value;
  8668. this.next();
  8669. return this.finishNode(node, "InterpreterDirective");
  8670. }
  8671. isLet(context) {
  8672. if (!this.isContextual("let")) {
  8673. return false;
  8674. }
  8675. const next = this.nextTokenStart();
  8676. const nextCh = this.input.charCodeAt(next);
  8677. if (nextCh === 91) return true;
  8678. if (context) return false;
  8679. if (nextCh === 123) return true;
  8680. if (isIdentifierStart(nextCh)) {
  8681. let pos = next + 1;
  8682. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  8683. ++pos;
  8684. }
  8685. const ident = this.input.slice(next, pos);
  8686. if (!keywordRelationalOperator.test(ident)) return true;
  8687. }
  8688. return false;
  8689. }
  8690. parseStatement(context, topLevel) {
  8691. if (this.match(types.at)) {
  8692. this.parseDecorators(true);
  8693. }
  8694. return this.parseStatementContent(context, topLevel);
  8695. }
  8696. parseStatementContent(context, topLevel) {
  8697. let starttype = this.state.type;
  8698. const node = this.startNode();
  8699. let kind;
  8700. if (this.isLet(context)) {
  8701. starttype = types._var;
  8702. kind = "let";
  8703. }
  8704. switch (starttype) {
  8705. case types._break:
  8706. case types._continue:
  8707. return this.parseBreakContinueStatement(node, starttype.keyword);
  8708. case types._debugger:
  8709. return this.parseDebuggerStatement(node);
  8710. case types._do:
  8711. return this.parseDoStatement(node);
  8712. case types._for:
  8713. return this.parseForStatement(node);
  8714. case types._function:
  8715. if (this.lookaheadCharCode() === 46) break;
  8716. if (context) {
  8717. if (this.state.strict) {
  8718. this.raise(this.state.start, "In strict mode code, functions can only be declared at top level or inside a block");
  8719. } else if (context !== "if" && context !== "label") {
  8720. this.raise(this.state.start, "In non-strict mode code, functions can only be declared at top level, " + "inside a block, or as the body of an if statement");
  8721. }
  8722. }
  8723. return this.parseFunctionStatement(node, false, !context);
  8724. case types._class:
  8725. if (context) this.unexpected();
  8726. return this.parseClass(node, true);
  8727. case types._if:
  8728. return this.parseIfStatement(node);
  8729. case types._return:
  8730. return this.parseReturnStatement(node);
  8731. case types._switch:
  8732. return this.parseSwitchStatement(node);
  8733. case types._throw:
  8734. return this.parseThrowStatement(node);
  8735. case types._try:
  8736. return this.parseTryStatement(node);
  8737. case types._const:
  8738. case types._var:
  8739. kind = kind || this.state.value;
  8740. if (context && kind !== "var") {
  8741. this.raise(this.state.start, "Lexical declaration cannot appear in a single-statement context");
  8742. }
  8743. return this.parseVarStatement(node, kind);
  8744. case types._while:
  8745. return this.parseWhileStatement(node);
  8746. case types._with:
  8747. return this.parseWithStatement(node);
  8748. case types.braceL:
  8749. return this.parseBlock();
  8750. case types.semi:
  8751. return this.parseEmptyStatement(node);
  8752. case types._export:
  8753. case types._import:
  8754. {
  8755. const nextTokenCharCode = this.lookaheadCharCode();
  8756. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  8757. break;
  8758. }
  8759. if (!this.options.allowImportExportEverywhere && !topLevel) {
  8760. this.raise(this.state.start, "'import' and 'export' may only appear at the top level");
  8761. }
  8762. this.next();
  8763. let result;
  8764. if (starttype === types._import) {
  8765. result = this.parseImport(node);
  8766. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  8767. this.sawUnambiguousESM = true;
  8768. }
  8769. } else {
  8770. result = this.parseExport(node);
  8771. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  8772. this.sawUnambiguousESM = true;
  8773. }
  8774. }
  8775. this.assertModuleNodeAllowed(node);
  8776. return result;
  8777. }
  8778. default:
  8779. {
  8780. if (this.isAsyncFunction()) {
  8781. if (context) {
  8782. this.raise(this.state.start, "Async functions can only be declared at the top level or inside a block");
  8783. }
  8784. this.next();
  8785. return this.parseFunctionStatement(node, true, !context);
  8786. }
  8787. }
  8788. }
  8789. const maybeName = this.state.value;
  8790. const expr = this.parseExpression();
  8791. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  8792. return this.parseLabeledStatement(node, maybeName, expr, context);
  8793. } else {
  8794. return this.parseExpressionStatement(node, expr);
  8795. }
  8796. }
  8797. assertModuleNodeAllowed(node) {
  8798. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  8799. this.raise(node.start, `'import' and 'export' may appear only with 'sourceType: "module"'`, {
  8800. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8801. });
  8802. }
  8803. }
  8804. takeDecorators(node) {
  8805. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  8806. if (decorators.length) {
  8807. node.decorators = decorators;
  8808. this.resetStartLocationFromNode(node, decorators[0]);
  8809. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  8810. }
  8811. }
  8812. canHaveLeadingDecorator() {
  8813. return this.match(types._class);
  8814. }
  8815. parseDecorators(allowExport) {
  8816. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  8817. while (this.match(types.at)) {
  8818. const decorator = this.parseDecorator();
  8819. currentContextDecorators.push(decorator);
  8820. }
  8821. if (this.match(types._export)) {
  8822. if (!allowExport) {
  8823. this.unexpected();
  8824. }
  8825. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  8826. this.raise(this.state.start, "Using the export keyword between a decorator and a class is not allowed. " + "Please use `export @dec class` instead.");
  8827. }
  8828. } else if (!this.canHaveLeadingDecorator()) {
  8829. throw this.raise(this.state.start, "Leading decorators must be attached to a class declaration");
  8830. }
  8831. }
  8832. parseDecorator() {
  8833. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  8834. const node = this.startNode();
  8835. this.next();
  8836. if (this.hasPlugin("decorators")) {
  8837. this.state.decoratorStack.push([]);
  8838. const startPos = this.state.start;
  8839. const startLoc = this.state.startLoc;
  8840. let expr;
  8841. if (this.eat(types.parenL)) {
  8842. expr = this.parseExpression();
  8843. this.expect(types.parenR);
  8844. } else {
  8845. expr = this.parseIdentifier(false);
  8846. while (this.eat(types.dot)) {
  8847. const node = this.startNodeAt(startPos, startLoc);
  8848. node.object = expr;
  8849. node.property = this.parseIdentifier(true);
  8850. node.computed = false;
  8851. expr = this.finishNode(node, "MemberExpression");
  8852. }
  8853. }
  8854. node.expression = this.parseMaybeDecoratorArguments(expr);
  8855. this.state.decoratorStack.pop();
  8856. } else {
  8857. node.expression = this.parseExprSubscripts();
  8858. }
  8859. return this.finishNode(node, "Decorator");
  8860. }
  8861. parseMaybeDecoratorArguments(expr) {
  8862. if (this.eat(types.parenL)) {
  8863. const node = this.startNodeAtNode(expr);
  8864. node.callee = expr;
  8865. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8866. this.toReferencedList(node.arguments);
  8867. return this.finishNode(node, "CallExpression");
  8868. }
  8869. return expr;
  8870. }
  8871. parseBreakContinueStatement(node, keyword) {
  8872. const isBreak = keyword === "break";
  8873. this.next();
  8874. if (this.isLineTerminator()) {
  8875. node.label = null;
  8876. } else {
  8877. node.label = this.parseIdentifier();
  8878. this.semicolon();
  8879. }
  8880. this.verifyBreakContinue(node, keyword);
  8881. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  8882. }
  8883. verifyBreakContinue(node, keyword) {
  8884. const isBreak = keyword === "break";
  8885. let i;
  8886. for (i = 0; i < this.state.labels.length; ++i) {
  8887. const lab = this.state.labels[i];
  8888. if (node.label == null || lab.name === node.label.name) {
  8889. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  8890. if (node.label && isBreak) break;
  8891. }
  8892. }
  8893. if (i === this.state.labels.length) {
  8894. this.raise(node.start, "Unsyntactic " + keyword);
  8895. }
  8896. }
  8897. parseDebuggerStatement(node) {
  8898. this.next();
  8899. this.semicolon();
  8900. return this.finishNode(node, "DebuggerStatement");
  8901. }
  8902. parseHeaderExpression() {
  8903. this.expect(types.parenL);
  8904. const val = this.parseExpression();
  8905. this.expect(types.parenR);
  8906. return val;
  8907. }
  8908. parseDoStatement(node) {
  8909. this.next();
  8910. this.state.labels.push(loopLabel);
  8911. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  8912. this.state.labels.pop();
  8913. this.expect(types._while);
  8914. node.test = this.parseHeaderExpression();
  8915. this.eat(types.semi);
  8916. return this.finishNode(node, "DoWhileStatement");
  8917. }
  8918. parseForStatement(node) {
  8919. this.next();
  8920. this.state.labels.push(loopLabel);
  8921. let awaitAt = -1;
  8922. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  8923. awaitAt = this.state.lastTokStart;
  8924. }
  8925. this.scope.enter(SCOPE_OTHER);
  8926. this.expect(types.parenL);
  8927. if (this.match(types.semi)) {
  8928. if (awaitAt > -1) {
  8929. this.unexpected(awaitAt);
  8930. }
  8931. return this.parseFor(node, null);
  8932. }
  8933. const isLet = this.isLet();
  8934. if (this.match(types._var) || this.match(types._const) || isLet) {
  8935. const init = this.startNode();
  8936. const kind = isLet ? "let" : this.state.value;
  8937. this.next();
  8938. this.parseVar(init, true, kind);
  8939. this.finishNode(init, "VariableDeclaration");
  8940. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  8941. return this.parseForIn(node, init, awaitAt);
  8942. }
  8943. if (awaitAt > -1) {
  8944. this.unexpected(awaitAt);
  8945. }
  8946. return this.parseFor(node, init);
  8947. }
  8948. const refShorthandDefaultPos = {
  8949. start: 0
  8950. };
  8951. const init = this.parseExpression(true, refShorthandDefaultPos);
  8952. if (this.match(types._in) || this.isContextual("of")) {
  8953. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  8954. this.toAssignable(init, undefined, description);
  8955. this.checkLVal(init, undefined, undefined, description);
  8956. return this.parseForIn(node, init, awaitAt);
  8957. } else if (refShorthandDefaultPos.start) {
  8958. this.unexpected(refShorthandDefaultPos.start);
  8959. }
  8960. if (awaitAt > -1) {
  8961. this.unexpected(awaitAt);
  8962. }
  8963. return this.parseFor(node, init);
  8964. }
  8965. parseFunctionStatement(node, isAsync, declarationPosition) {
  8966. this.next();
  8967. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  8968. }
  8969. parseIfStatement(node) {
  8970. this.next();
  8971. node.test = this.parseHeaderExpression();
  8972. node.consequent = this.parseStatement("if");
  8973. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  8974. return this.finishNode(node, "IfStatement");
  8975. }
  8976. parseReturnStatement(node) {
  8977. if (!this.scope.inFunction && !this.options.allowReturnOutsideFunction) {
  8978. this.raise(this.state.start, "'return' outside of function");
  8979. }
  8980. this.next();
  8981. if (this.isLineTerminator()) {
  8982. node.argument = null;
  8983. } else {
  8984. node.argument = this.parseExpression();
  8985. this.semicolon();
  8986. }
  8987. return this.finishNode(node, "ReturnStatement");
  8988. }
  8989. parseSwitchStatement(node) {
  8990. this.next();
  8991. node.discriminant = this.parseHeaderExpression();
  8992. const cases = node.cases = [];
  8993. this.expect(types.braceL);
  8994. this.state.labels.push(switchLabel);
  8995. this.scope.enter(SCOPE_OTHER);
  8996. let cur;
  8997. for (let sawDefault; !this.match(types.braceR);) {
  8998. if (this.match(types._case) || this.match(types._default)) {
  8999. const isCase = this.match(types._case);
  9000. if (cur) this.finishNode(cur, "SwitchCase");
  9001. cases.push(cur = this.startNode());
  9002. cur.consequent = [];
  9003. this.next();
  9004. if (isCase) {
  9005. cur.test = this.parseExpression();
  9006. } else {
  9007. if (sawDefault) {
  9008. this.raise(this.state.lastTokStart, "Multiple default clauses");
  9009. }
  9010. sawDefault = true;
  9011. cur.test = null;
  9012. }
  9013. this.expect(types.colon);
  9014. } else {
  9015. if (cur) {
  9016. cur.consequent.push(this.parseStatement(null));
  9017. } else {
  9018. this.unexpected();
  9019. }
  9020. }
  9021. }
  9022. this.scope.exit();
  9023. if (cur) this.finishNode(cur, "SwitchCase");
  9024. this.next();
  9025. this.state.labels.pop();
  9026. return this.finishNode(node, "SwitchStatement");
  9027. }
  9028. parseThrowStatement(node) {
  9029. this.next();
  9030. if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) {
  9031. this.raise(this.state.lastTokEnd, "Illegal newline after throw");
  9032. }
  9033. node.argument = this.parseExpression();
  9034. this.semicolon();
  9035. return this.finishNode(node, "ThrowStatement");
  9036. }
  9037. parseTryStatement(node) {
  9038. this.next();
  9039. node.block = this.parseBlock();
  9040. node.handler = null;
  9041. if (this.match(types._catch)) {
  9042. const clause = this.startNode();
  9043. this.next();
  9044. if (this.match(types.parenL)) {
  9045. this.expect(types.parenL);
  9046. clause.param = this.parseBindingAtom();
  9047. const simple = clause.param.type === "Identifier";
  9048. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  9049. this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause");
  9050. this.expect(types.parenR);
  9051. } else {
  9052. clause.param = null;
  9053. this.scope.enter(SCOPE_OTHER);
  9054. }
  9055. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  9056. this.scope.exit();
  9057. node.handler = this.finishNode(clause, "CatchClause");
  9058. }
  9059. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  9060. if (!node.handler && !node.finalizer) {
  9061. this.raise(node.start, "Missing catch or finally clause");
  9062. }
  9063. return this.finishNode(node, "TryStatement");
  9064. }
  9065. parseVarStatement(node, kind) {
  9066. this.next();
  9067. this.parseVar(node, false, kind);
  9068. this.semicolon();
  9069. return this.finishNode(node, "VariableDeclaration");
  9070. }
  9071. parseWhileStatement(node) {
  9072. this.next();
  9073. node.test = this.parseHeaderExpression();
  9074. this.state.labels.push(loopLabel);
  9075. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  9076. this.state.labels.pop();
  9077. return this.finishNode(node, "WhileStatement");
  9078. }
  9079. parseWithStatement(node) {
  9080. if (this.state.strict) {
  9081. this.raise(this.state.start, "'with' in strict mode");
  9082. }
  9083. this.next();
  9084. node.object = this.parseHeaderExpression();
  9085. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  9086. return this.finishNode(node, "WithStatement");
  9087. }
  9088. parseEmptyStatement(node) {
  9089. this.next();
  9090. return this.finishNode(node, "EmptyStatement");
  9091. }
  9092. parseLabeledStatement(node, maybeName, expr, context) {
  9093. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  9094. const label = _this$state$labels[_i2];
  9095. if (label.name === maybeName) {
  9096. this.raise(expr.start, `Label '${maybeName}' is already declared`);
  9097. }
  9098. }
  9099. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  9100. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  9101. const label = this.state.labels[i];
  9102. if (label.statementStart === node.start) {
  9103. label.statementStart = this.state.start;
  9104. label.kind = kind;
  9105. } else {
  9106. break;
  9107. }
  9108. }
  9109. this.state.labels.push({
  9110. name: maybeName,
  9111. kind: kind,
  9112. statementStart: this.state.start
  9113. });
  9114. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  9115. this.state.labels.pop();
  9116. node.label = expr;
  9117. return this.finishNode(node, "LabeledStatement");
  9118. }
  9119. parseExpressionStatement(node, expr) {
  9120. node.expression = expr;
  9121. this.semicolon();
  9122. return this.finishNode(node, "ExpressionStatement");
  9123. }
  9124. parseBlock(allowDirectives = false, createNewLexicalScope = true) {
  9125. const node = this.startNode();
  9126. this.expect(types.braceL);
  9127. if (createNewLexicalScope) {
  9128. this.scope.enter(SCOPE_OTHER);
  9129. }
  9130. this.parseBlockBody(node, allowDirectives, false, types.braceR);
  9131. if (createNewLexicalScope) {
  9132. this.scope.exit();
  9133. }
  9134. return this.finishNode(node, "BlockStatement");
  9135. }
  9136. isValidDirective(stmt) {
  9137. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  9138. }
  9139. parseBlockBody(node, allowDirectives, topLevel, end) {
  9140. const body = node.body = [];
  9141. const directives = node.directives = [];
  9142. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end);
  9143. }
  9144. parseBlockOrModuleBlockBody(body, directives, topLevel, end) {
  9145. let parsedNonDirective = false;
  9146. let oldStrict;
  9147. let octalPosition;
  9148. while (!this.eat(end)) {
  9149. if (!parsedNonDirective && this.state.containsOctal && !octalPosition) {
  9150. octalPosition = this.state.octalPosition;
  9151. }
  9152. const stmt = this.parseStatement(null, topLevel);
  9153. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  9154. const directive = this.stmtToDirective(stmt);
  9155. directives.push(directive);
  9156. if (oldStrict === undefined && directive.value.value === "use strict") {
  9157. oldStrict = this.state.strict;
  9158. this.setStrict(true);
  9159. if (octalPosition) {
  9160. this.raise(octalPosition, "Octal literal in strict mode");
  9161. }
  9162. }
  9163. continue;
  9164. }
  9165. parsedNonDirective = true;
  9166. body.push(stmt);
  9167. }
  9168. if (oldStrict === false) {
  9169. this.setStrict(false);
  9170. }
  9171. }
  9172. parseFor(node, init) {
  9173. node.init = init;
  9174. this.expect(types.semi);
  9175. node.test = this.match(types.semi) ? null : this.parseExpression();
  9176. this.expect(types.semi);
  9177. node.update = this.match(types.parenR) ? null : this.parseExpression();
  9178. this.expect(types.parenR);
  9179. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9180. this.scope.exit();
  9181. this.state.labels.pop();
  9182. return this.finishNode(node, "ForStatement");
  9183. }
  9184. parseForIn(node, init, awaitAt) {
  9185. const isForIn = this.match(types._in);
  9186. this.next();
  9187. if (isForIn) {
  9188. if (awaitAt > -1) this.unexpected(awaitAt);
  9189. } else {
  9190. node.await = awaitAt > -1;
  9191. }
  9192. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  9193. this.raise(init.start, `${isForIn ? "for-in" : "for-of"} loop variable declaration may not have an initializer`);
  9194. } else if (init.type === "AssignmentPattern") {
  9195. this.raise(init.start, "Invalid left-hand side in for-loop");
  9196. }
  9197. node.left = init;
  9198. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  9199. this.expect(types.parenR);
  9200. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9201. this.scope.exit();
  9202. this.state.labels.pop();
  9203. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  9204. }
  9205. parseVar(node, isFor, kind) {
  9206. const declarations = node.declarations = [];
  9207. const isTypescript = this.hasPlugin("typescript");
  9208. node.kind = kind;
  9209. for (;;) {
  9210. const decl = this.startNode();
  9211. this.parseVarId(decl, kind);
  9212. if (this.eat(types.eq)) {
  9213. decl.init = this.parseMaybeAssign(isFor);
  9214. } else {
  9215. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  9216. if (!isTypescript) {
  9217. this.unexpected();
  9218. }
  9219. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  9220. this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value");
  9221. }
  9222. decl.init = null;
  9223. }
  9224. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  9225. if (!this.eat(types.comma)) break;
  9226. }
  9227. return node;
  9228. }
  9229. parseVarId(decl, kind) {
  9230. decl.id = this.parseBindingAtom();
  9231. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration", kind !== "var");
  9232. }
  9233. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  9234. const isStatement = statement & FUNC_STATEMENT;
  9235. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  9236. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  9237. this.initFunction(node, isAsync);
  9238. if (this.match(types.star) && isHangingStatement) {
  9239. this.raise(this.state.start, "Generators can only be declared at the top level or inside a block");
  9240. }
  9241. node.generator = this.eat(types.star);
  9242. if (isStatement) {
  9243. node.id = this.parseFunctionId(requireId);
  9244. }
  9245. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9246. const oldInClassProperty = this.state.inClassProperty;
  9247. const oldYieldPos = this.state.yieldPos;
  9248. const oldAwaitPos = this.state.awaitPos;
  9249. this.state.maybeInArrowParameters = false;
  9250. this.state.inClassProperty = false;
  9251. this.state.yieldPos = -1;
  9252. this.state.awaitPos = -1;
  9253. this.scope.enter(functionFlags(node.async, node.generator));
  9254. if (!isStatement) {
  9255. node.id = this.parseFunctionId();
  9256. }
  9257. this.parseFunctionParams(node);
  9258. this.withTopicForbiddingContext(() => {
  9259. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  9260. });
  9261. this.scope.exit();
  9262. if (isStatement && !isHangingStatement) {
  9263. this.registerFunctionStatementId(node);
  9264. }
  9265. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9266. this.state.inClassProperty = oldInClassProperty;
  9267. this.state.yieldPos = oldYieldPos;
  9268. this.state.awaitPos = oldAwaitPos;
  9269. return node;
  9270. }
  9271. parseFunctionId(requireId) {
  9272. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  9273. }
  9274. parseFunctionParams(node, allowModifiers) {
  9275. const oldInParameters = this.state.inParameters;
  9276. this.state.inParameters = true;
  9277. this.expect(types.parenL);
  9278. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  9279. this.state.inParameters = oldInParameters;
  9280. this.checkYieldAwaitInDefaultParams();
  9281. }
  9282. registerFunctionStatementId(node) {
  9283. if (!node.id) return;
  9284. this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start);
  9285. }
  9286. parseClass(node, isStatement, optionalId) {
  9287. this.next();
  9288. this.takeDecorators(node);
  9289. const oldStrict = this.state.strict;
  9290. this.state.strict = true;
  9291. this.parseClassId(node, isStatement, optionalId);
  9292. this.parseClassSuper(node);
  9293. node.body = this.parseClassBody(!!node.superClass);
  9294. this.state.strict = oldStrict;
  9295. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  9296. }
  9297. isClassProperty() {
  9298. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  9299. }
  9300. isClassMethod() {
  9301. return this.match(types.parenL);
  9302. }
  9303. isNonstaticConstructor(method) {
  9304. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  9305. }
  9306. parseClassBody(constructorAllowsSuper) {
  9307. this.state.classLevel++;
  9308. const state = {
  9309. hadConstructor: false
  9310. };
  9311. let decorators = [];
  9312. const classBody = this.startNode();
  9313. classBody.body = [];
  9314. this.expect(types.braceL);
  9315. this.withTopicForbiddingContext(() => {
  9316. while (!this.eat(types.braceR)) {
  9317. if (this.eat(types.semi)) {
  9318. if (decorators.length > 0) {
  9319. throw this.raise(this.state.lastTokEnd, "Decorators must not be followed by a semicolon");
  9320. }
  9321. continue;
  9322. }
  9323. if (this.match(types.at)) {
  9324. decorators.push(this.parseDecorator());
  9325. continue;
  9326. }
  9327. const member = this.startNode();
  9328. if (decorators.length) {
  9329. member.decorators = decorators;
  9330. this.resetStartLocationFromNode(member, decorators[0]);
  9331. decorators = [];
  9332. }
  9333. this.parseClassMember(classBody, member, state, constructorAllowsSuper);
  9334. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  9335. this.raise(member.start, "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?");
  9336. }
  9337. }
  9338. });
  9339. if (decorators.length) {
  9340. throw this.raise(this.state.start, "You have trailing decorators with no method");
  9341. }
  9342. this.state.classLevel--;
  9343. return this.finishNode(classBody, "ClassBody");
  9344. }
  9345. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  9346. let isStatic = false;
  9347. const containsEsc = this.state.containsEsc;
  9348. if (this.match(types.name) && this.state.value === "static") {
  9349. const key = this.parseIdentifier(true);
  9350. if (this.isClassMethod()) {
  9351. const method = member;
  9352. method.kind = "method";
  9353. method.computed = false;
  9354. method.key = key;
  9355. method.static = false;
  9356. this.pushClassMethod(classBody, method, false, false, false, false);
  9357. return;
  9358. } else if (this.isClassProperty()) {
  9359. const prop = member;
  9360. prop.computed = false;
  9361. prop.key = key;
  9362. prop.static = false;
  9363. classBody.body.push(this.parseClassProperty(prop));
  9364. return;
  9365. } else if (containsEsc) {
  9366. throw this.unexpected();
  9367. }
  9368. isStatic = true;
  9369. }
  9370. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  9371. }
  9372. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  9373. const publicMethod = member;
  9374. const privateMethod = member;
  9375. const publicProp = member;
  9376. const privateProp = member;
  9377. const method = publicMethod;
  9378. const publicMember = publicMethod;
  9379. member.static = isStatic;
  9380. if (this.eat(types.star)) {
  9381. method.kind = "method";
  9382. this.parseClassPropertyName(method);
  9383. if (method.key.type === "PrivateName") {
  9384. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  9385. return;
  9386. }
  9387. if (this.isNonstaticConstructor(publicMethod)) {
  9388. this.raise(publicMethod.key.start, "Constructor can't be a generator");
  9389. }
  9390. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  9391. return;
  9392. }
  9393. const containsEsc = this.state.containsEsc;
  9394. const key = this.parseClassPropertyName(member);
  9395. const isPrivate = key.type === "PrivateName";
  9396. const isSimple = key.type === "Identifier";
  9397. const maybeQuestionTokenStart = this.state.start;
  9398. this.parsePostMemberNameModifiers(publicMember);
  9399. if (this.isClassMethod()) {
  9400. method.kind = "method";
  9401. if (isPrivate) {
  9402. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9403. return;
  9404. }
  9405. const isConstructor = this.isNonstaticConstructor(publicMethod);
  9406. let allowsDirectSuper = false;
  9407. if (isConstructor) {
  9408. publicMethod.kind = "constructor";
  9409. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  9410. this.raise(key.start, "Duplicate constructor in the same class");
  9411. }
  9412. state.hadConstructor = true;
  9413. allowsDirectSuper = constructorAllowsSuper;
  9414. }
  9415. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  9416. } else if (this.isClassProperty()) {
  9417. if (isPrivate) {
  9418. this.pushClassPrivateProperty(classBody, privateProp);
  9419. } else {
  9420. this.pushClassProperty(classBody, publicProp);
  9421. }
  9422. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  9423. const isGenerator = this.eat(types.star);
  9424. if (publicMember.optional) {
  9425. this.unexpected(maybeQuestionTokenStart);
  9426. }
  9427. method.kind = "method";
  9428. this.parseClassPropertyName(method);
  9429. this.parsePostMemberNameModifiers(publicMember);
  9430. if (method.key.type === "PrivateName") {
  9431. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  9432. } else {
  9433. if (this.isNonstaticConstructor(publicMethod)) {
  9434. this.raise(publicMethod.key.start, "Constructor can't be an async function");
  9435. }
  9436. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  9437. }
  9438. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  9439. method.kind = key.name;
  9440. this.parseClassPropertyName(publicMethod);
  9441. if (method.key.type === "PrivateName") {
  9442. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9443. } else {
  9444. if (this.isNonstaticConstructor(publicMethod)) {
  9445. this.raise(publicMethod.key.start, "Constructor can't have get/set modifier");
  9446. }
  9447. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  9448. }
  9449. this.checkGetterSetterParams(publicMethod);
  9450. } else if (this.isLineTerminator()) {
  9451. if (isPrivate) {
  9452. this.pushClassPrivateProperty(classBody, privateProp);
  9453. } else {
  9454. this.pushClassProperty(classBody, publicProp);
  9455. }
  9456. } else {
  9457. this.unexpected();
  9458. }
  9459. }
  9460. parseClassPropertyName(member) {
  9461. const key = this.parsePropertyName(member);
  9462. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  9463. this.raise(key.start, "Classes may not have static property named prototype");
  9464. }
  9465. if (key.type === "PrivateName" && key.id.name === "constructor") {
  9466. this.raise(key.start, "Classes may not have a private field named '#constructor'");
  9467. }
  9468. return key;
  9469. }
  9470. pushClassProperty(classBody, prop) {
  9471. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  9472. this.raise(prop.key.start, "Classes may not have a field named 'constructor'");
  9473. }
  9474. classBody.body.push(this.parseClassProperty(prop));
  9475. }
  9476. pushClassPrivateProperty(classBody, prop) {
  9477. this.expectPlugin("classPrivateProperties", prop.key.start);
  9478. classBody.body.push(this.parseClassPrivateProperty(prop));
  9479. }
  9480. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9481. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  9482. }
  9483. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9484. this.expectPlugin("classPrivateMethods", method.key.start);
  9485. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true));
  9486. }
  9487. parsePostMemberNameModifiers(methodOrProp) {}
  9488. parseAccessModifier() {
  9489. return undefined;
  9490. }
  9491. parseClassPrivateProperty(node) {
  9492. this.state.inClassProperty = true;
  9493. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9494. node.value = this.eat(types.eq) ? this.parseMaybeAssign() : null;
  9495. this.semicolon();
  9496. this.state.inClassProperty = false;
  9497. this.scope.exit();
  9498. return this.finishNode(node, "ClassPrivateProperty");
  9499. }
  9500. parseClassProperty(node) {
  9501. if (!node.typeAnnotation) {
  9502. this.expectPlugin("classProperties");
  9503. }
  9504. this.state.inClassProperty = true;
  9505. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9506. if (this.match(types.eq)) {
  9507. this.expectPlugin("classProperties");
  9508. this.next();
  9509. node.value = this.parseMaybeAssign();
  9510. } else {
  9511. node.value = null;
  9512. }
  9513. this.semicolon();
  9514. this.state.inClassProperty = false;
  9515. this.scope.exit();
  9516. return this.finishNode(node, "ClassProperty");
  9517. }
  9518. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  9519. if (this.match(types.name)) {
  9520. node.id = this.parseIdentifier();
  9521. if (isStatement) {
  9522. this.checkLVal(node.id, bindingType, undefined, "class name");
  9523. }
  9524. } else {
  9525. if (optionalId || !isStatement) {
  9526. node.id = null;
  9527. } else {
  9528. this.unexpected(null, "A class name is required");
  9529. }
  9530. }
  9531. }
  9532. parseClassSuper(node) {
  9533. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  9534. }
  9535. parseExport(node) {
  9536. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  9537. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  9538. const hasStar = parseAfterDefault && this.eatExportStar(node);
  9539. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  9540. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  9541. const isFromRequired = hasDefault || hasStar;
  9542. if (hasStar && !hasNamespace) {
  9543. if (hasDefault) this.unexpected();
  9544. this.parseExportFrom(node, true);
  9545. return this.finishNode(node, "ExportAllDeclaration");
  9546. }
  9547. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  9548. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  9549. throw this.unexpected(null, types.braceL);
  9550. }
  9551. let hasDeclaration;
  9552. if (isFromRequired || hasSpecifiers) {
  9553. hasDeclaration = false;
  9554. this.parseExportFrom(node, isFromRequired);
  9555. } else {
  9556. hasDeclaration = this.maybeParseExportDeclaration(node);
  9557. }
  9558. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  9559. this.checkExport(node, true, false, !!node.source);
  9560. return this.finishNode(node, "ExportNamedDeclaration");
  9561. }
  9562. if (this.eat(types._default)) {
  9563. node.declaration = this.parseExportDefaultExpression();
  9564. this.checkExport(node, true, true);
  9565. return this.finishNode(node, "ExportDefaultDeclaration");
  9566. }
  9567. throw this.unexpected(null, types.braceL);
  9568. }
  9569. eatExportStar(node) {
  9570. return this.eat(types.star);
  9571. }
  9572. maybeParseExportDefaultSpecifier(node) {
  9573. if (this.isExportDefaultSpecifier()) {
  9574. this.expectPlugin("exportDefaultFrom");
  9575. const specifier = this.startNode();
  9576. specifier.exported = this.parseIdentifier(true);
  9577. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9578. return true;
  9579. }
  9580. return false;
  9581. }
  9582. maybeParseExportNamespaceSpecifier(node) {
  9583. if (this.isContextual("as")) {
  9584. if (!node.specifiers) node.specifiers = [];
  9585. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  9586. this.next();
  9587. specifier.exported = this.parseIdentifier(true);
  9588. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  9589. return true;
  9590. }
  9591. return false;
  9592. }
  9593. maybeParseExportNamedSpecifiers(node) {
  9594. if (this.match(types.braceL)) {
  9595. if (!node.specifiers) node.specifiers = [];
  9596. node.specifiers.push(...this.parseExportSpecifiers());
  9597. node.source = null;
  9598. node.declaration = null;
  9599. return true;
  9600. }
  9601. return false;
  9602. }
  9603. maybeParseExportDeclaration(node) {
  9604. if (this.shouldParseExportDeclaration()) {
  9605. if (this.isContextual("async")) {
  9606. const next = this.nextTokenStart();
  9607. if (!this.isUnparsedContextual(next, "function")) {
  9608. this.unexpected(next, `Unexpected token, expected "function"`);
  9609. }
  9610. }
  9611. node.specifiers = [];
  9612. node.source = null;
  9613. node.declaration = this.parseExportDeclaration(node);
  9614. return true;
  9615. }
  9616. return false;
  9617. }
  9618. isAsyncFunction() {
  9619. if (!this.isContextual("async")) return false;
  9620. const next = this.nextTokenStart();
  9621. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  9622. }
  9623. parseExportDefaultExpression() {
  9624. const expr = this.startNode();
  9625. const isAsync = this.isAsyncFunction();
  9626. if (this.match(types._function) || isAsync) {
  9627. this.next();
  9628. if (isAsync) {
  9629. this.next();
  9630. }
  9631. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  9632. } else if (this.match(types._class)) {
  9633. return this.parseClass(expr, true, true);
  9634. } else if (this.match(types.at)) {
  9635. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9636. this.raise(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax");
  9637. }
  9638. this.parseDecorators(false);
  9639. return this.parseClass(expr, true, true);
  9640. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  9641. throw this.raise(this.state.start, "Only expressions, functions or classes are allowed as the `default` export.");
  9642. } else {
  9643. const res = this.parseMaybeAssign();
  9644. this.semicolon();
  9645. return res;
  9646. }
  9647. }
  9648. parseExportDeclaration(node) {
  9649. return this.parseStatement(null);
  9650. }
  9651. isExportDefaultSpecifier() {
  9652. if (this.match(types.name)) {
  9653. return this.state.value !== "async" && this.state.value !== "let";
  9654. }
  9655. if (!this.match(types._default)) {
  9656. return false;
  9657. }
  9658. const next = this.nextTokenStart();
  9659. return this.input.charCodeAt(next) === 44 || this.isUnparsedContextual(next, "from");
  9660. }
  9661. parseExportFrom(node, expect) {
  9662. if (this.eatContextual("from")) {
  9663. node.source = this.parseImportSource();
  9664. this.checkExport(node);
  9665. } else {
  9666. if (expect) {
  9667. this.unexpected();
  9668. } else {
  9669. node.source = null;
  9670. }
  9671. }
  9672. this.semicolon();
  9673. }
  9674. shouldParseExportDeclaration() {
  9675. if (this.match(types.at)) {
  9676. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  9677. if (this.hasPlugin("decorators")) {
  9678. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9679. this.unexpected(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax");
  9680. } else {
  9681. return true;
  9682. }
  9683. }
  9684. }
  9685. return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction();
  9686. }
  9687. checkExport(node, checkNames, isDefault, isFrom) {
  9688. if (checkNames) {
  9689. if (isDefault) {
  9690. this.checkDuplicateExports(node, "default");
  9691. } else if (node.specifiers && node.specifiers.length) {
  9692. for (let _i3 = 0, _node$specifiers = node.specifiers; _i3 < _node$specifiers.length; _i3++) {
  9693. const specifier = _node$specifiers[_i3];
  9694. this.checkDuplicateExports(specifier, specifier.exported.name);
  9695. if (!isFrom && specifier.local) {
  9696. this.checkReservedWord(specifier.local.name, specifier.local.start, true, false);
  9697. this.scope.checkLocalExport(specifier.local);
  9698. }
  9699. }
  9700. } else if (node.declaration) {
  9701. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  9702. const id = node.declaration.id;
  9703. if (!id) throw new Error("Assertion failure");
  9704. this.checkDuplicateExports(node, id.name);
  9705. } else if (node.declaration.type === "VariableDeclaration") {
  9706. for (let _i4 = 0, _node$declaration$dec = node.declaration.declarations; _i4 < _node$declaration$dec.length; _i4++) {
  9707. const declaration = _node$declaration$dec[_i4];
  9708. this.checkDeclaration(declaration.id);
  9709. }
  9710. }
  9711. }
  9712. }
  9713. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9714. if (currentContextDecorators.length) {
  9715. const isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
  9716. if (!node.declaration || !isClass) {
  9717. throw this.raise(node.start, "You can only use decorators on an export when exporting a class");
  9718. }
  9719. this.takeDecorators(node.declaration);
  9720. }
  9721. }
  9722. checkDeclaration(node) {
  9723. if (node.type === "Identifier") {
  9724. this.checkDuplicateExports(node, node.name);
  9725. } else if (node.type === "ObjectPattern") {
  9726. for (let _i5 = 0, _node$properties = node.properties; _i5 < _node$properties.length; _i5++) {
  9727. const prop = _node$properties[_i5];
  9728. this.checkDeclaration(prop);
  9729. }
  9730. } else if (node.type === "ArrayPattern") {
  9731. for (let _i6 = 0, _node$elements = node.elements; _i6 < _node$elements.length; _i6++) {
  9732. const elem = _node$elements[_i6];
  9733. if (elem) {
  9734. this.checkDeclaration(elem);
  9735. }
  9736. }
  9737. } else if (node.type === "ObjectProperty") {
  9738. this.checkDeclaration(node.value);
  9739. } else if (node.type === "RestElement") {
  9740. this.checkDeclaration(node.argument);
  9741. } else if (node.type === "AssignmentPattern") {
  9742. this.checkDeclaration(node.left);
  9743. }
  9744. }
  9745. checkDuplicateExports(node, name) {
  9746. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  9747. this.raise(node.start, name === "default" ? "Only one default export allowed per module." : `\`${name}\` has already been exported. Exported identifiers must be unique.`);
  9748. }
  9749. this.state.exportedIdentifiers.push(name);
  9750. }
  9751. parseExportSpecifiers() {
  9752. const nodes = [];
  9753. let first = true;
  9754. this.expect(types.braceL);
  9755. while (!this.eat(types.braceR)) {
  9756. if (first) {
  9757. first = false;
  9758. } else {
  9759. this.expect(types.comma);
  9760. if (this.eat(types.braceR)) break;
  9761. }
  9762. const node = this.startNode();
  9763. node.local = this.parseIdentifier(true);
  9764. node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
  9765. nodes.push(this.finishNode(node, "ExportSpecifier"));
  9766. }
  9767. return nodes;
  9768. }
  9769. parseImport(node) {
  9770. node.specifiers = [];
  9771. if (!this.match(types.string)) {
  9772. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  9773. const parseNext = !hasDefault || this.eat(types.comma);
  9774. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  9775. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  9776. this.expectContextual("from");
  9777. }
  9778. node.source = this.parseImportSource();
  9779. this.semicolon();
  9780. return this.finishNode(node, "ImportDeclaration");
  9781. }
  9782. parseImportSource() {
  9783. if (!this.match(types.string)) this.unexpected();
  9784. return this.parseExprAtom();
  9785. }
  9786. shouldParseDefaultImport(node) {
  9787. return this.match(types.name);
  9788. }
  9789. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  9790. specifier.local = this.parseIdentifier();
  9791. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  9792. node.specifiers.push(this.finishNode(specifier, type));
  9793. }
  9794. maybeParseDefaultImportSpecifier(node) {
  9795. if (this.shouldParseDefaultImport(node)) {
  9796. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  9797. return true;
  9798. }
  9799. return false;
  9800. }
  9801. maybeParseStarImportSpecifier(node) {
  9802. if (this.match(types.star)) {
  9803. const specifier = this.startNode();
  9804. this.next();
  9805. this.expectContextual("as");
  9806. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  9807. return true;
  9808. }
  9809. return false;
  9810. }
  9811. parseNamedImportSpecifiers(node) {
  9812. let first = true;
  9813. this.expect(types.braceL);
  9814. while (!this.eat(types.braceR)) {
  9815. if (first) {
  9816. first = false;
  9817. } else {
  9818. if (this.eat(types.colon)) {
  9819. throw this.raise(this.state.start, "ES2015 named imports do not destructure. " + "Use another statement for destructuring after the import.");
  9820. }
  9821. this.expect(types.comma);
  9822. if (this.eat(types.braceR)) break;
  9823. }
  9824. this.parseImportSpecifier(node);
  9825. }
  9826. }
  9827. parseImportSpecifier(node) {
  9828. const specifier = this.startNode();
  9829. specifier.imported = this.parseIdentifier(true);
  9830. if (this.eatContextual("as")) {
  9831. specifier.local = this.parseIdentifier();
  9832. } else {
  9833. this.checkReservedWord(specifier.imported.name, specifier.start, true, true);
  9834. specifier.local = specifier.imported.__clone();
  9835. }
  9836. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  9837. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  9838. }
  9839. }
  9840. class Parser extends StatementParser {
  9841. constructor(options, input) {
  9842. options = getOptions(options);
  9843. super(options, input);
  9844. const ScopeHandler = this.getScopeHandler();
  9845. this.options = options;
  9846. this.inModule = this.options.sourceType === "module";
  9847. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  9848. this.plugins = pluginsMap(this.options.plugins);
  9849. this.filename = options.sourceFilename;
  9850. }
  9851. getScopeHandler() {
  9852. return ScopeHandler;
  9853. }
  9854. parse() {
  9855. this.scope.enter(SCOPE_PROGRAM);
  9856. const file = this.startNode();
  9857. const program = this.startNode();
  9858. this.nextToken();
  9859. file.errors = null;
  9860. this.parseTopLevel(file, program);
  9861. file.errors = this.state.errors;
  9862. return file;
  9863. }
  9864. }
  9865. function pluginsMap(plugins) {
  9866. const pluginMap = new Map();
  9867. for (let _i = 0; _i < plugins.length; _i++) {
  9868. const plugin = plugins[_i];
  9869. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  9870. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  9871. }
  9872. return pluginMap;
  9873. }
  9874. function parse(input, options) {
  9875. if (options && options.sourceType === "unambiguous") {
  9876. options = Object.assign({}, options);
  9877. try {
  9878. options.sourceType = "module";
  9879. const parser = getParser(options, input);
  9880. const ast = parser.parse();
  9881. if (parser.sawUnambiguousESM) {
  9882. return ast;
  9883. }
  9884. if (parser.ambiguousScriptDifferentAst) {
  9885. try {
  9886. options.sourceType = "script";
  9887. return getParser(options, input).parse();
  9888. } catch (_unused) {}
  9889. } else {
  9890. ast.program.sourceType = "script";
  9891. }
  9892. return ast;
  9893. } catch (moduleError) {
  9894. try {
  9895. options.sourceType = "script";
  9896. return getParser(options, input).parse();
  9897. } catch (_unused2) {}
  9898. throw moduleError;
  9899. }
  9900. } else {
  9901. return getParser(options, input).parse();
  9902. }
  9903. }
  9904. function parseExpression(input, options) {
  9905. const parser = getParser(options, input);
  9906. if (parser.options.strictMode) {
  9907. parser.state.strict = true;
  9908. }
  9909. return parser.getExpression();
  9910. }
  9911. function getParser(options, input) {
  9912. let cls = Parser;
  9913. if (options && options.plugins) {
  9914. validatePlugins(options.plugins);
  9915. cls = getParserClass(options.plugins);
  9916. }
  9917. return new cls(options, input);
  9918. }
  9919. const parserClassCache = {};
  9920. function getParserClass(pluginsFromOptions) {
  9921. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  9922. const key = pluginList.join("/");
  9923. let cls = parserClassCache[key];
  9924. if (!cls) {
  9925. cls = Parser;
  9926. for (let _i = 0; _i < pluginList.length; _i++) {
  9927. const plugin = pluginList[_i];
  9928. cls = mixinPlugins[plugin](cls);
  9929. }
  9930. parserClassCache[key] = cls;
  9931. }
  9932. return cls;
  9933. }
  9934. exports.parse = parse;
  9935. exports.parseExpression = parseExpression;
  9936. exports.tokTypes = types;