flow.js 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _types = require("../tokenizer/types");
  7. var N = _interopRequireWildcard(require("../types"));
  8. var _context = require("../tokenizer/context");
  9. var _identifier = require("../util/identifier");
  10. var _scopeflags = require("../util/scopeflags");
  11. var _error = require("../parser/error");
  12. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  13. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  14. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  15. const FlowErrors = Object.freeze({
  16. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  17. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",
  18. AssignReservedType: "Cannot overwrite reserved type %0",
  19. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  20. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  21. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  22. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  23. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  24. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  25. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  26. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  27. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  28. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  29. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  30. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  31. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  32. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  33. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",
  34. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  35. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  36. InexactVariance: "Explicit inexact syntax cannot have variance",
  37. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  38. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  39. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  40. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  41. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  42. SpreadVariance: "Spread properties cannot have variance",
  43. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  44. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  45. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  46. UnexpectedReservedType: "Unexpected reserved type %0",
  47. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  48. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  49. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  50. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  51. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  52. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
  53. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  54. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  55. UnterminatedFlowComment: "Unterminated flow-comment"
  56. });
  57. function isEsModuleType(bodyElement) {
  58. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  59. }
  60. function hasTypeImportKind(node) {
  61. return node.importKind === "type" || node.importKind === "typeof";
  62. }
  63. function isMaybeDefaultImport(state) {
  64. return (state.type === _types.types.name || !!state.type.keyword) && state.value !== "from";
  65. }
  66. const exportSuggestions = {
  67. const: "declare export var",
  68. let: "declare export var",
  69. type: "export type",
  70. interface: "export interface"
  71. };
  72. function partition(list, test) {
  73. const list1 = [];
  74. const list2 = [];
  75. for (let i = 0; i < list.length; i++) {
  76. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  77. }
  78. return [list1, list2];
  79. }
  80. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  81. var _default = superClass => {
  82. var _temp;
  83. return _temp = class extends superClass {
  84. constructor(options, input) {
  85. super(options, input);
  86. this.flowPragma = void 0;
  87. this.flowPragma = undefined;
  88. }
  89. shouldParseTypes() {
  90. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  91. }
  92. shouldParseEnums() {
  93. return !!this.getPluginOption("flow", "enums");
  94. }
  95. finishToken(type, val) {
  96. if (type !== _types.types.string && type !== _types.types.semi && type !== _types.types.interpreterDirective) {
  97. if (this.flowPragma === undefined) {
  98. this.flowPragma = null;
  99. }
  100. }
  101. return super.finishToken(type, val);
  102. }
  103. addComment(comment) {
  104. if (this.flowPragma === undefined) {
  105. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  106. if (!matches) {} else if (matches[1] === "flow") {
  107. this.flowPragma = "flow";
  108. } else if (matches[1] === "noflow") {
  109. this.flowPragma = "noflow";
  110. } else {
  111. throw new Error("Unexpected flow pragma");
  112. }
  113. }
  114. return super.addComment(comment);
  115. }
  116. flowParseTypeInitialiser(tok) {
  117. const oldInType = this.state.inType;
  118. this.state.inType = true;
  119. this.expect(tok || _types.types.colon);
  120. const type = this.flowParseType();
  121. this.state.inType = oldInType;
  122. return type;
  123. }
  124. flowParsePredicate() {
  125. const node = this.startNode();
  126. const moduloLoc = this.state.startLoc;
  127. const moduloPos = this.state.start;
  128. this.expect(_types.types.modulo);
  129. const checksLoc = this.state.startLoc;
  130. this.expectContextual("checks");
  131. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  132. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  133. }
  134. if (this.eat(_types.types.parenL)) {
  135. node.value = this.parseExpression();
  136. this.expect(_types.types.parenR);
  137. return this.finishNode(node, "DeclaredPredicate");
  138. } else {
  139. return this.finishNode(node, "InferredPredicate");
  140. }
  141. }
  142. flowParseTypeAndPredicateInitialiser() {
  143. const oldInType = this.state.inType;
  144. this.state.inType = true;
  145. this.expect(_types.types.colon);
  146. let type = null;
  147. let predicate = null;
  148. if (this.match(_types.types.modulo)) {
  149. this.state.inType = oldInType;
  150. predicate = this.flowParsePredicate();
  151. } else {
  152. type = this.flowParseType();
  153. this.state.inType = oldInType;
  154. if (this.match(_types.types.modulo)) {
  155. predicate = this.flowParsePredicate();
  156. }
  157. }
  158. return [type, predicate];
  159. }
  160. flowParseDeclareClass(node) {
  161. this.next();
  162. this.flowParseInterfaceish(node, true);
  163. return this.finishNode(node, "DeclareClass");
  164. }
  165. flowParseDeclareFunction(node) {
  166. this.next();
  167. const id = node.id = this.parseIdentifier();
  168. const typeNode = this.startNode();
  169. const typeContainer = this.startNode();
  170. if (this.isRelational("<")) {
  171. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  172. } else {
  173. typeNode.typeParameters = null;
  174. }
  175. this.expect(_types.types.parenL);
  176. const tmp = this.flowParseFunctionTypeParams();
  177. typeNode.params = tmp.params;
  178. typeNode.rest = tmp.rest;
  179. this.expect(_types.types.parenR);
  180. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  181. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  182. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  183. this.resetEndLocation(id);
  184. this.semicolon();
  185. return this.finishNode(node, "DeclareFunction");
  186. }
  187. flowParseDeclare(node, insideModule) {
  188. if (this.match(_types.types._class)) {
  189. return this.flowParseDeclareClass(node);
  190. } else if (this.match(_types.types._function)) {
  191. return this.flowParseDeclareFunction(node);
  192. } else if (this.match(_types.types._var)) {
  193. return this.flowParseDeclareVariable(node);
  194. } else if (this.eatContextual("module")) {
  195. if (this.match(_types.types.dot)) {
  196. return this.flowParseDeclareModuleExports(node);
  197. } else {
  198. if (insideModule) {
  199. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  200. }
  201. return this.flowParseDeclareModule(node);
  202. }
  203. } else if (this.isContextual("type")) {
  204. return this.flowParseDeclareTypeAlias(node);
  205. } else if (this.isContextual("opaque")) {
  206. return this.flowParseDeclareOpaqueType(node);
  207. } else if (this.isContextual("interface")) {
  208. return this.flowParseDeclareInterface(node);
  209. } else if (this.match(_types.types._export)) {
  210. return this.flowParseDeclareExportDeclaration(node, insideModule);
  211. } else {
  212. throw this.unexpected();
  213. }
  214. }
  215. flowParseDeclareVariable(node) {
  216. this.next();
  217. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  218. this.scope.declareName(node.id.name, _scopeflags.BIND_VAR, node.id.start);
  219. this.semicolon();
  220. return this.finishNode(node, "DeclareVariable");
  221. }
  222. flowParseDeclareModule(node) {
  223. this.scope.enter(_scopeflags.SCOPE_OTHER);
  224. if (this.match(_types.types.string)) {
  225. node.id = this.parseExprAtom();
  226. } else {
  227. node.id = this.parseIdentifier();
  228. }
  229. const bodyNode = node.body = this.startNode();
  230. const body = bodyNode.body = [];
  231. this.expect(_types.types.braceL);
  232. while (!this.match(_types.types.braceR)) {
  233. let bodyNode = this.startNode();
  234. if (this.match(_types.types._import)) {
  235. this.next();
  236. if (!this.isContextual("type") && !this.match(_types.types._typeof)) {
  237. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  238. }
  239. this.parseImport(bodyNode);
  240. } else {
  241. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  242. bodyNode = this.flowParseDeclare(bodyNode, true);
  243. }
  244. body.push(bodyNode);
  245. }
  246. this.scope.exit();
  247. this.expect(_types.types.braceR);
  248. this.finishNode(bodyNode, "BlockStatement");
  249. let kind = null;
  250. let hasModuleExport = false;
  251. body.forEach(bodyElement => {
  252. if (isEsModuleType(bodyElement)) {
  253. if (kind === "CommonJS") {
  254. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  255. }
  256. kind = "ES";
  257. } else if (bodyElement.type === "DeclareModuleExports") {
  258. if (hasModuleExport) {
  259. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  260. }
  261. if (kind === "ES") {
  262. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  263. }
  264. kind = "CommonJS";
  265. hasModuleExport = true;
  266. }
  267. });
  268. node.kind = kind || "CommonJS";
  269. return this.finishNode(node, "DeclareModule");
  270. }
  271. flowParseDeclareExportDeclaration(node, insideModule) {
  272. this.expect(_types.types._export);
  273. if (this.eat(_types.types._default)) {
  274. if (this.match(_types.types._function) || this.match(_types.types._class)) {
  275. node.declaration = this.flowParseDeclare(this.startNode());
  276. } else {
  277. node.declaration = this.flowParseType();
  278. this.semicolon();
  279. }
  280. node.default = true;
  281. return this.finishNode(node, "DeclareExportDeclaration");
  282. } else {
  283. if (this.match(_types.types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  284. const label = this.state.value;
  285. const suggestion = exportSuggestions[label];
  286. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  287. }
  288. if (this.match(_types.types._var) || this.match(_types.types._function) || this.match(_types.types._class) || this.isContextual("opaque")) {
  289. node.declaration = this.flowParseDeclare(this.startNode());
  290. node.default = false;
  291. return this.finishNode(node, "DeclareExportDeclaration");
  292. } else if (this.match(_types.types.star) || this.match(_types.types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  293. node = this.parseExport(node);
  294. if (node.type === "ExportNamedDeclaration") {
  295. node.type = "ExportDeclaration";
  296. node.default = false;
  297. delete node.exportKind;
  298. }
  299. node.type = "Declare" + node.type;
  300. return node;
  301. }
  302. }
  303. throw this.unexpected();
  304. }
  305. flowParseDeclareModuleExports(node) {
  306. this.next();
  307. this.expectContextual("exports");
  308. node.typeAnnotation = this.flowParseTypeAnnotation();
  309. this.semicolon();
  310. return this.finishNode(node, "DeclareModuleExports");
  311. }
  312. flowParseDeclareTypeAlias(node) {
  313. this.next();
  314. this.flowParseTypeAlias(node);
  315. node.type = "DeclareTypeAlias";
  316. return node;
  317. }
  318. flowParseDeclareOpaqueType(node) {
  319. this.next();
  320. this.flowParseOpaqueType(node, true);
  321. node.type = "DeclareOpaqueType";
  322. return node;
  323. }
  324. flowParseDeclareInterface(node) {
  325. this.next();
  326. this.flowParseInterfaceish(node);
  327. return this.finishNode(node, "DeclareInterface");
  328. }
  329. flowParseInterfaceish(node, isClass = false) {
  330. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  331. this.scope.declareName(node.id.name, isClass ? _scopeflags.BIND_FUNCTION : _scopeflags.BIND_LEXICAL, node.id.start);
  332. if (this.isRelational("<")) {
  333. node.typeParameters = this.flowParseTypeParameterDeclaration();
  334. } else {
  335. node.typeParameters = null;
  336. }
  337. node.extends = [];
  338. node.implements = [];
  339. node.mixins = [];
  340. if (this.eat(_types.types._extends)) {
  341. do {
  342. node.extends.push(this.flowParseInterfaceExtends());
  343. } while (!isClass && this.eat(_types.types.comma));
  344. }
  345. if (this.isContextual("mixins")) {
  346. this.next();
  347. do {
  348. node.mixins.push(this.flowParseInterfaceExtends());
  349. } while (this.eat(_types.types.comma));
  350. }
  351. if (this.isContextual("implements")) {
  352. this.next();
  353. do {
  354. node.implements.push(this.flowParseInterfaceExtends());
  355. } while (this.eat(_types.types.comma));
  356. }
  357. node.body = this.flowParseObjectType({
  358. allowStatic: isClass,
  359. allowExact: false,
  360. allowSpread: false,
  361. allowProto: isClass,
  362. allowInexact: false
  363. });
  364. }
  365. flowParseInterfaceExtends() {
  366. const node = this.startNode();
  367. node.id = this.flowParseQualifiedTypeIdentifier();
  368. if (this.isRelational("<")) {
  369. node.typeParameters = this.flowParseTypeParameterInstantiation();
  370. } else {
  371. node.typeParameters = null;
  372. }
  373. return this.finishNode(node, "InterfaceExtends");
  374. }
  375. flowParseInterface(node) {
  376. this.flowParseInterfaceish(node);
  377. return this.finishNode(node, "InterfaceDeclaration");
  378. }
  379. checkNotUnderscore(word) {
  380. if (word === "_") {
  381. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  382. }
  383. }
  384. checkReservedType(word, startLoc, declaration) {
  385. if (!reservedTypes.has(word)) return;
  386. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  387. }
  388. flowParseRestrictedIdentifier(liberal, declaration) {
  389. this.checkReservedType(this.state.value, this.state.start, declaration);
  390. return this.parseIdentifier(liberal);
  391. }
  392. flowParseTypeAlias(node) {
  393. node.id = this.flowParseRestrictedIdentifier(false, true);
  394. this.scope.declareName(node.id.name, _scopeflags.BIND_LEXICAL, node.id.start);
  395. if (this.isRelational("<")) {
  396. node.typeParameters = this.flowParseTypeParameterDeclaration();
  397. } else {
  398. node.typeParameters = null;
  399. }
  400. node.right = this.flowParseTypeInitialiser(_types.types.eq);
  401. this.semicolon();
  402. return this.finishNode(node, "TypeAlias");
  403. }
  404. flowParseOpaqueType(node, declare) {
  405. this.expectContextual("type");
  406. node.id = this.flowParseRestrictedIdentifier(true, true);
  407. this.scope.declareName(node.id.name, _scopeflags.BIND_LEXICAL, node.id.start);
  408. if (this.isRelational("<")) {
  409. node.typeParameters = this.flowParseTypeParameterDeclaration();
  410. } else {
  411. node.typeParameters = null;
  412. }
  413. node.supertype = null;
  414. if (this.match(_types.types.colon)) {
  415. node.supertype = this.flowParseTypeInitialiser(_types.types.colon);
  416. }
  417. node.impltype = null;
  418. if (!declare) {
  419. node.impltype = this.flowParseTypeInitialiser(_types.types.eq);
  420. }
  421. this.semicolon();
  422. return this.finishNode(node, "OpaqueType");
  423. }
  424. flowParseTypeParameter(requireDefault = false) {
  425. const nodeStart = this.state.start;
  426. const node = this.startNode();
  427. const variance = this.flowParseVariance();
  428. const ident = this.flowParseTypeAnnotatableIdentifier();
  429. node.name = ident.name;
  430. node.variance = variance;
  431. node.bound = ident.typeAnnotation;
  432. if (this.match(_types.types.eq)) {
  433. this.eat(_types.types.eq);
  434. node.default = this.flowParseType();
  435. } else {
  436. if (requireDefault) {
  437. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  438. }
  439. }
  440. return this.finishNode(node, "TypeParameter");
  441. }
  442. flowParseTypeParameterDeclaration() {
  443. const oldInType = this.state.inType;
  444. const node = this.startNode();
  445. node.params = [];
  446. this.state.inType = true;
  447. if (this.isRelational("<") || this.match(_types.types.jsxTagStart)) {
  448. this.next();
  449. } else {
  450. this.unexpected();
  451. }
  452. let defaultRequired = false;
  453. do {
  454. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  455. node.params.push(typeParameter);
  456. if (typeParameter.default) {
  457. defaultRequired = true;
  458. }
  459. if (!this.isRelational(">")) {
  460. this.expect(_types.types.comma);
  461. }
  462. } while (!this.isRelational(">"));
  463. this.expectRelational(">");
  464. this.state.inType = oldInType;
  465. return this.finishNode(node, "TypeParameterDeclaration");
  466. }
  467. flowParseTypeParameterInstantiation() {
  468. const node = this.startNode();
  469. const oldInType = this.state.inType;
  470. node.params = [];
  471. this.state.inType = true;
  472. this.expectRelational("<");
  473. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  474. this.state.noAnonFunctionType = false;
  475. while (!this.isRelational(">")) {
  476. node.params.push(this.flowParseType());
  477. if (!this.isRelational(">")) {
  478. this.expect(_types.types.comma);
  479. }
  480. }
  481. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  482. this.expectRelational(">");
  483. this.state.inType = oldInType;
  484. return this.finishNode(node, "TypeParameterInstantiation");
  485. }
  486. flowParseTypeParameterInstantiationCallOrNew() {
  487. const node = this.startNode();
  488. const oldInType = this.state.inType;
  489. node.params = [];
  490. this.state.inType = true;
  491. this.expectRelational("<");
  492. while (!this.isRelational(">")) {
  493. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  494. if (!this.isRelational(">")) {
  495. this.expect(_types.types.comma);
  496. }
  497. }
  498. this.expectRelational(">");
  499. this.state.inType = oldInType;
  500. return this.finishNode(node, "TypeParameterInstantiation");
  501. }
  502. flowParseInterfaceType() {
  503. const node = this.startNode();
  504. this.expectContextual("interface");
  505. node.extends = [];
  506. if (this.eat(_types.types._extends)) {
  507. do {
  508. node.extends.push(this.flowParseInterfaceExtends());
  509. } while (this.eat(_types.types.comma));
  510. }
  511. node.body = this.flowParseObjectType({
  512. allowStatic: false,
  513. allowExact: false,
  514. allowSpread: false,
  515. allowProto: false,
  516. allowInexact: false
  517. });
  518. return this.finishNode(node, "InterfaceTypeAnnotation");
  519. }
  520. flowParseObjectPropertyKey() {
  521. return this.match(_types.types.num) || this.match(_types.types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  522. }
  523. flowParseObjectTypeIndexer(node, isStatic, variance) {
  524. node.static = isStatic;
  525. if (this.lookahead().type === _types.types.colon) {
  526. node.id = this.flowParseObjectPropertyKey();
  527. node.key = this.flowParseTypeInitialiser();
  528. } else {
  529. node.id = null;
  530. node.key = this.flowParseType();
  531. }
  532. this.expect(_types.types.bracketR);
  533. node.value = this.flowParseTypeInitialiser();
  534. node.variance = variance;
  535. return this.finishNode(node, "ObjectTypeIndexer");
  536. }
  537. flowParseObjectTypeInternalSlot(node, isStatic) {
  538. node.static = isStatic;
  539. node.id = this.flowParseObjectPropertyKey();
  540. this.expect(_types.types.bracketR);
  541. this.expect(_types.types.bracketR);
  542. if (this.isRelational("<") || this.match(_types.types.parenL)) {
  543. node.method = true;
  544. node.optional = false;
  545. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  546. } else {
  547. node.method = false;
  548. if (this.eat(_types.types.question)) {
  549. node.optional = true;
  550. }
  551. node.value = this.flowParseTypeInitialiser();
  552. }
  553. return this.finishNode(node, "ObjectTypeInternalSlot");
  554. }
  555. flowParseObjectTypeMethodish(node) {
  556. node.params = [];
  557. node.rest = null;
  558. node.typeParameters = null;
  559. if (this.isRelational("<")) {
  560. node.typeParameters = this.flowParseTypeParameterDeclaration();
  561. }
  562. this.expect(_types.types.parenL);
  563. while (!this.match(_types.types.parenR) && !this.match(_types.types.ellipsis)) {
  564. node.params.push(this.flowParseFunctionTypeParam());
  565. if (!this.match(_types.types.parenR)) {
  566. this.expect(_types.types.comma);
  567. }
  568. }
  569. if (this.eat(_types.types.ellipsis)) {
  570. node.rest = this.flowParseFunctionTypeParam();
  571. }
  572. this.expect(_types.types.parenR);
  573. node.returnType = this.flowParseTypeInitialiser();
  574. return this.finishNode(node, "FunctionTypeAnnotation");
  575. }
  576. flowParseObjectTypeCallProperty(node, isStatic) {
  577. const valueNode = this.startNode();
  578. node.static = isStatic;
  579. node.value = this.flowParseObjectTypeMethodish(valueNode);
  580. return this.finishNode(node, "ObjectTypeCallProperty");
  581. }
  582. flowParseObjectType({
  583. allowStatic,
  584. allowExact,
  585. allowSpread,
  586. allowProto,
  587. allowInexact
  588. }) {
  589. const oldInType = this.state.inType;
  590. this.state.inType = true;
  591. const nodeStart = this.startNode();
  592. nodeStart.callProperties = [];
  593. nodeStart.properties = [];
  594. nodeStart.indexers = [];
  595. nodeStart.internalSlots = [];
  596. let endDelim;
  597. let exact;
  598. let inexact = false;
  599. if (allowExact && this.match(_types.types.braceBarL)) {
  600. this.expect(_types.types.braceBarL);
  601. endDelim = _types.types.braceBarR;
  602. exact = true;
  603. } else {
  604. this.expect(_types.types.braceL);
  605. endDelim = _types.types.braceR;
  606. exact = false;
  607. }
  608. nodeStart.exact = exact;
  609. while (!this.match(endDelim)) {
  610. let isStatic = false;
  611. let protoStart = null;
  612. let inexactStart = null;
  613. const node = this.startNode();
  614. if (allowProto && this.isContextual("proto")) {
  615. const lookahead = this.lookahead();
  616. if (lookahead.type !== _types.types.colon && lookahead.type !== _types.types.question) {
  617. this.next();
  618. protoStart = this.state.start;
  619. allowStatic = false;
  620. }
  621. }
  622. if (allowStatic && this.isContextual("static")) {
  623. const lookahead = this.lookahead();
  624. if (lookahead.type !== _types.types.colon && lookahead.type !== _types.types.question) {
  625. this.next();
  626. isStatic = true;
  627. }
  628. }
  629. const variance = this.flowParseVariance();
  630. if (this.eat(_types.types.bracketL)) {
  631. if (protoStart != null) {
  632. this.unexpected(protoStart);
  633. }
  634. if (this.eat(_types.types.bracketL)) {
  635. if (variance) {
  636. this.unexpected(variance.start);
  637. }
  638. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  639. } else {
  640. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  641. }
  642. } else if (this.match(_types.types.parenL) || this.isRelational("<")) {
  643. if (protoStart != null) {
  644. this.unexpected(protoStart);
  645. }
  646. if (variance) {
  647. this.unexpected(variance.start);
  648. }
  649. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  650. } else {
  651. let kind = "init";
  652. if (this.isContextual("get") || this.isContextual("set")) {
  653. const lookahead = this.lookahead();
  654. if (lookahead.type === _types.types.name || lookahead.type === _types.types.string || lookahead.type === _types.types.num) {
  655. kind = this.state.value;
  656. this.next();
  657. }
  658. }
  659. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact ?? !exact);
  660. if (propOrInexact === null) {
  661. inexact = true;
  662. inexactStart = this.state.lastTokStart;
  663. } else {
  664. nodeStart.properties.push(propOrInexact);
  665. }
  666. }
  667. this.flowObjectTypeSemicolon();
  668. if (inexactStart && !this.match(_types.types.braceR) && !this.match(_types.types.braceBarR)) {
  669. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  670. }
  671. }
  672. this.expect(endDelim);
  673. if (allowSpread) {
  674. nodeStart.inexact = inexact;
  675. }
  676. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  677. this.state.inType = oldInType;
  678. return out;
  679. }
  680. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  681. if (this.eat(_types.types.ellipsis)) {
  682. const isInexactToken = this.match(_types.types.comma) || this.match(_types.types.semi) || this.match(_types.types.braceR) || this.match(_types.types.braceBarR);
  683. if (isInexactToken) {
  684. if (!allowSpread) {
  685. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  686. } else if (!allowInexact) {
  687. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  688. }
  689. if (variance) {
  690. this.raise(variance.start, FlowErrors.InexactVariance);
  691. }
  692. return null;
  693. }
  694. if (!allowSpread) {
  695. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  696. }
  697. if (protoStart != null) {
  698. this.unexpected(protoStart);
  699. }
  700. if (variance) {
  701. this.raise(variance.start, FlowErrors.SpreadVariance);
  702. }
  703. node.argument = this.flowParseType();
  704. return this.finishNode(node, "ObjectTypeSpreadProperty");
  705. } else {
  706. node.key = this.flowParseObjectPropertyKey();
  707. node.static = isStatic;
  708. node.proto = protoStart != null;
  709. node.kind = kind;
  710. let optional = false;
  711. if (this.isRelational("<") || this.match(_types.types.parenL)) {
  712. node.method = true;
  713. if (protoStart != null) {
  714. this.unexpected(protoStart);
  715. }
  716. if (variance) {
  717. this.unexpected(variance.start);
  718. }
  719. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  720. if (kind === "get" || kind === "set") {
  721. this.flowCheckGetterSetterParams(node);
  722. }
  723. } else {
  724. if (kind !== "init") this.unexpected();
  725. node.method = false;
  726. if (this.eat(_types.types.question)) {
  727. optional = true;
  728. }
  729. node.value = this.flowParseTypeInitialiser();
  730. node.variance = variance;
  731. }
  732. node.optional = optional;
  733. return this.finishNode(node, "ObjectTypeProperty");
  734. }
  735. }
  736. flowCheckGetterSetterParams(property) {
  737. const paramCount = property.kind === "get" ? 0 : 1;
  738. const start = property.start;
  739. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  740. if (length !== paramCount) {
  741. if (property.kind === "get") {
  742. this.raise(start, _error.Errors.BadGetterArity);
  743. } else {
  744. this.raise(start, _error.Errors.BadSetterArity);
  745. }
  746. }
  747. if (property.kind === "set" && property.value.rest) {
  748. this.raise(start, _error.Errors.BadSetterRestParameter);
  749. }
  750. }
  751. flowObjectTypeSemicolon() {
  752. if (!this.eat(_types.types.semi) && !this.eat(_types.types.comma) && !this.match(_types.types.braceR) && !this.match(_types.types.braceBarR)) {
  753. this.unexpected();
  754. }
  755. }
  756. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  757. startPos = startPos || this.state.start;
  758. startLoc = startLoc || this.state.startLoc;
  759. let node = id || this.flowParseRestrictedIdentifier(true);
  760. while (this.eat(_types.types.dot)) {
  761. const node2 = this.startNodeAt(startPos, startLoc);
  762. node2.qualification = node;
  763. node2.id = this.flowParseRestrictedIdentifier(true);
  764. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  765. }
  766. return node;
  767. }
  768. flowParseGenericType(startPos, startLoc, id) {
  769. const node = this.startNodeAt(startPos, startLoc);
  770. node.typeParameters = null;
  771. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  772. if (this.isRelational("<")) {
  773. node.typeParameters = this.flowParseTypeParameterInstantiation();
  774. }
  775. return this.finishNode(node, "GenericTypeAnnotation");
  776. }
  777. flowParseTypeofType() {
  778. const node = this.startNode();
  779. this.expect(_types.types._typeof);
  780. node.argument = this.flowParsePrimaryType();
  781. return this.finishNode(node, "TypeofTypeAnnotation");
  782. }
  783. flowParseTupleType() {
  784. const node = this.startNode();
  785. node.types = [];
  786. this.expect(_types.types.bracketL);
  787. while (this.state.pos < this.length && !this.match(_types.types.bracketR)) {
  788. node.types.push(this.flowParseType());
  789. if (this.match(_types.types.bracketR)) break;
  790. this.expect(_types.types.comma);
  791. }
  792. this.expect(_types.types.bracketR);
  793. return this.finishNode(node, "TupleTypeAnnotation");
  794. }
  795. flowParseFunctionTypeParam() {
  796. let name = null;
  797. let optional = false;
  798. let typeAnnotation = null;
  799. const node = this.startNode();
  800. const lh = this.lookahead();
  801. if (lh.type === _types.types.colon || lh.type === _types.types.question) {
  802. name = this.parseIdentifier();
  803. if (this.eat(_types.types.question)) {
  804. optional = true;
  805. }
  806. typeAnnotation = this.flowParseTypeInitialiser();
  807. } else {
  808. typeAnnotation = this.flowParseType();
  809. }
  810. node.name = name;
  811. node.optional = optional;
  812. node.typeAnnotation = typeAnnotation;
  813. return this.finishNode(node, "FunctionTypeParam");
  814. }
  815. reinterpretTypeAsFunctionTypeParam(type) {
  816. const node = this.startNodeAt(type.start, type.loc.start);
  817. node.name = null;
  818. node.optional = false;
  819. node.typeAnnotation = type;
  820. return this.finishNode(node, "FunctionTypeParam");
  821. }
  822. flowParseFunctionTypeParams(params = []) {
  823. let rest = null;
  824. while (!this.match(_types.types.parenR) && !this.match(_types.types.ellipsis)) {
  825. params.push(this.flowParseFunctionTypeParam());
  826. if (!this.match(_types.types.parenR)) {
  827. this.expect(_types.types.comma);
  828. }
  829. }
  830. if (this.eat(_types.types.ellipsis)) {
  831. rest = this.flowParseFunctionTypeParam();
  832. }
  833. return {
  834. params,
  835. rest
  836. };
  837. }
  838. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  839. switch (id.name) {
  840. case "any":
  841. return this.finishNode(node, "AnyTypeAnnotation");
  842. case "bool":
  843. case "boolean":
  844. return this.finishNode(node, "BooleanTypeAnnotation");
  845. case "mixed":
  846. return this.finishNode(node, "MixedTypeAnnotation");
  847. case "empty":
  848. return this.finishNode(node, "EmptyTypeAnnotation");
  849. case "number":
  850. return this.finishNode(node, "NumberTypeAnnotation");
  851. case "string":
  852. return this.finishNode(node, "StringTypeAnnotation");
  853. case "symbol":
  854. return this.finishNode(node, "SymbolTypeAnnotation");
  855. default:
  856. this.checkNotUnderscore(id.name);
  857. return this.flowParseGenericType(startPos, startLoc, id);
  858. }
  859. }
  860. flowParsePrimaryType() {
  861. const startPos = this.state.start;
  862. const startLoc = this.state.startLoc;
  863. const node = this.startNode();
  864. let tmp;
  865. let type;
  866. let isGroupedType = false;
  867. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  868. switch (this.state.type) {
  869. case _types.types.name:
  870. if (this.isContextual("interface")) {
  871. return this.flowParseInterfaceType();
  872. }
  873. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  874. case _types.types.braceL:
  875. return this.flowParseObjectType({
  876. allowStatic: false,
  877. allowExact: false,
  878. allowSpread: true,
  879. allowProto: false,
  880. allowInexact: true
  881. });
  882. case _types.types.braceBarL:
  883. return this.flowParseObjectType({
  884. allowStatic: false,
  885. allowExact: true,
  886. allowSpread: true,
  887. allowProto: false,
  888. allowInexact: false
  889. });
  890. case _types.types.bracketL:
  891. this.state.noAnonFunctionType = false;
  892. type = this.flowParseTupleType();
  893. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  894. return type;
  895. case _types.types.relational:
  896. if (this.state.value === "<") {
  897. node.typeParameters = this.flowParseTypeParameterDeclaration();
  898. this.expect(_types.types.parenL);
  899. tmp = this.flowParseFunctionTypeParams();
  900. node.params = tmp.params;
  901. node.rest = tmp.rest;
  902. this.expect(_types.types.parenR);
  903. this.expect(_types.types.arrow);
  904. node.returnType = this.flowParseType();
  905. return this.finishNode(node, "FunctionTypeAnnotation");
  906. }
  907. break;
  908. case _types.types.parenL:
  909. this.next();
  910. if (!this.match(_types.types.parenR) && !this.match(_types.types.ellipsis)) {
  911. if (this.match(_types.types.name)) {
  912. const token = this.lookahead().type;
  913. isGroupedType = token !== _types.types.question && token !== _types.types.colon;
  914. } else {
  915. isGroupedType = true;
  916. }
  917. }
  918. if (isGroupedType) {
  919. this.state.noAnonFunctionType = false;
  920. type = this.flowParseType();
  921. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  922. if (this.state.noAnonFunctionType || !(this.match(_types.types.comma) || this.match(_types.types.parenR) && this.lookahead().type === _types.types.arrow)) {
  923. this.expect(_types.types.parenR);
  924. return type;
  925. } else {
  926. this.eat(_types.types.comma);
  927. }
  928. }
  929. if (type) {
  930. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  931. } else {
  932. tmp = this.flowParseFunctionTypeParams();
  933. }
  934. node.params = tmp.params;
  935. node.rest = tmp.rest;
  936. this.expect(_types.types.parenR);
  937. this.expect(_types.types.arrow);
  938. node.returnType = this.flowParseType();
  939. node.typeParameters = null;
  940. return this.finishNode(node, "FunctionTypeAnnotation");
  941. case _types.types.string:
  942. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  943. case _types.types._true:
  944. case _types.types._false:
  945. node.value = this.match(_types.types._true);
  946. this.next();
  947. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  948. case _types.types.plusMin:
  949. if (this.state.value === "-") {
  950. this.next();
  951. if (this.match(_types.types.num)) {
  952. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  953. }
  954. if (this.match(_types.types.bigint)) {
  955. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  956. }
  957. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  958. }
  959. throw this.unexpected();
  960. case _types.types.num:
  961. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  962. case _types.types.bigint:
  963. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  964. case _types.types._void:
  965. this.next();
  966. return this.finishNode(node, "VoidTypeAnnotation");
  967. case _types.types._null:
  968. this.next();
  969. return this.finishNode(node, "NullLiteralTypeAnnotation");
  970. case _types.types._this:
  971. this.next();
  972. return this.finishNode(node, "ThisTypeAnnotation");
  973. case _types.types.star:
  974. this.next();
  975. return this.finishNode(node, "ExistsTypeAnnotation");
  976. default:
  977. if (this.state.type.keyword === "typeof") {
  978. return this.flowParseTypeofType();
  979. } else if (this.state.type.keyword) {
  980. const label = this.state.type.label;
  981. this.next();
  982. return super.createIdentifier(node, label);
  983. }
  984. }
  985. throw this.unexpected();
  986. }
  987. flowParsePostfixType() {
  988. const startPos = this.state.start,
  989. startLoc = this.state.startLoc;
  990. let type = this.flowParsePrimaryType();
  991. while (this.match(_types.types.bracketL) && !this.canInsertSemicolon()) {
  992. const node = this.startNodeAt(startPos, startLoc);
  993. node.elementType = type;
  994. this.expect(_types.types.bracketL);
  995. this.expect(_types.types.bracketR);
  996. type = this.finishNode(node, "ArrayTypeAnnotation");
  997. }
  998. return type;
  999. }
  1000. flowParsePrefixType() {
  1001. const node = this.startNode();
  1002. if (this.eat(_types.types.question)) {
  1003. node.typeAnnotation = this.flowParsePrefixType();
  1004. return this.finishNode(node, "NullableTypeAnnotation");
  1005. } else {
  1006. return this.flowParsePostfixType();
  1007. }
  1008. }
  1009. flowParseAnonFunctionWithoutParens() {
  1010. const param = this.flowParsePrefixType();
  1011. if (!this.state.noAnonFunctionType && this.eat(_types.types.arrow)) {
  1012. const node = this.startNodeAt(param.start, param.loc.start);
  1013. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  1014. node.rest = null;
  1015. node.returnType = this.flowParseType();
  1016. node.typeParameters = null;
  1017. return this.finishNode(node, "FunctionTypeAnnotation");
  1018. }
  1019. return param;
  1020. }
  1021. flowParseIntersectionType() {
  1022. const node = this.startNode();
  1023. this.eat(_types.types.bitwiseAND);
  1024. const type = this.flowParseAnonFunctionWithoutParens();
  1025. node.types = [type];
  1026. while (this.eat(_types.types.bitwiseAND)) {
  1027. node.types.push(this.flowParseAnonFunctionWithoutParens());
  1028. }
  1029. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  1030. }
  1031. flowParseUnionType() {
  1032. const node = this.startNode();
  1033. this.eat(_types.types.bitwiseOR);
  1034. const type = this.flowParseIntersectionType();
  1035. node.types = [type];
  1036. while (this.eat(_types.types.bitwiseOR)) {
  1037. node.types.push(this.flowParseIntersectionType());
  1038. }
  1039. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  1040. }
  1041. flowParseType() {
  1042. const oldInType = this.state.inType;
  1043. this.state.inType = true;
  1044. const type = this.flowParseUnionType();
  1045. this.state.inType = oldInType;
  1046. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  1047. return type;
  1048. }
  1049. flowParseTypeOrImplicitInstantiation() {
  1050. if (this.state.type === _types.types.name && this.state.value === "_") {
  1051. const startPos = this.state.start;
  1052. const startLoc = this.state.startLoc;
  1053. const node = this.parseIdentifier();
  1054. return this.flowParseGenericType(startPos, startLoc, node);
  1055. } else {
  1056. return this.flowParseType();
  1057. }
  1058. }
  1059. flowParseTypeAnnotation() {
  1060. const node = this.startNode();
  1061. node.typeAnnotation = this.flowParseTypeInitialiser();
  1062. return this.finishNode(node, "TypeAnnotation");
  1063. }
  1064. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  1065. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  1066. if (this.match(_types.types.colon)) {
  1067. ident.typeAnnotation = this.flowParseTypeAnnotation();
  1068. this.resetEndLocation(ident);
  1069. }
  1070. return ident;
  1071. }
  1072. typeCastToParameter(node) {
  1073. node.expression.typeAnnotation = node.typeAnnotation;
  1074. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  1075. return node.expression;
  1076. }
  1077. flowParseVariance() {
  1078. let variance = null;
  1079. if (this.match(_types.types.plusMin)) {
  1080. variance = this.startNode();
  1081. if (this.state.value === "+") {
  1082. variance.kind = "plus";
  1083. } else {
  1084. variance.kind = "minus";
  1085. }
  1086. this.next();
  1087. this.finishNode(variance, "Variance");
  1088. }
  1089. return variance;
  1090. }
  1091. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  1092. if (allowExpressionBody) {
  1093. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  1094. }
  1095. return super.parseFunctionBody(node, false, isMethod);
  1096. }
  1097. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  1098. if (this.match(_types.types.colon)) {
  1099. const typeNode = this.startNode();
  1100. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1101. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  1102. }
  1103. super.parseFunctionBodyAndFinish(node, type, isMethod);
  1104. }
  1105. parseStatement(context, topLevel) {
  1106. if (this.state.strict && this.match(_types.types.name) && this.state.value === "interface") {
  1107. const lookahead = this.lookahead();
  1108. if (lookahead.type === _types.types.name || (0, _identifier.isKeyword)(lookahead.value)) {
  1109. const node = this.startNode();
  1110. this.next();
  1111. return this.flowParseInterface(node);
  1112. }
  1113. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  1114. const node = this.startNode();
  1115. this.next();
  1116. return this.flowParseEnumDeclaration(node);
  1117. }
  1118. const stmt = super.parseStatement(context, topLevel);
  1119. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  1120. this.flowPragma = null;
  1121. }
  1122. return stmt;
  1123. }
  1124. parseExpressionStatement(node, expr) {
  1125. if (expr.type === "Identifier") {
  1126. if (expr.name === "declare") {
  1127. if (this.match(_types.types._class) || this.match(_types.types.name) || this.match(_types.types._function) || this.match(_types.types._var) || this.match(_types.types._export)) {
  1128. return this.flowParseDeclare(node);
  1129. }
  1130. } else if (this.match(_types.types.name)) {
  1131. if (expr.name === "interface") {
  1132. return this.flowParseInterface(node);
  1133. } else if (expr.name === "type") {
  1134. return this.flowParseTypeAlias(node);
  1135. } else if (expr.name === "opaque") {
  1136. return this.flowParseOpaqueType(node, false);
  1137. }
  1138. }
  1139. }
  1140. return super.parseExpressionStatement(node, expr);
  1141. }
  1142. shouldParseExportDeclaration() {
  1143. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  1144. }
  1145. isExportDefaultSpecifier() {
  1146. if (this.match(_types.types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  1147. return false;
  1148. }
  1149. return super.isExportDefaultSpecifier();
  1150. }
  1151. parseExportDefaultExpression() {
  1152. if (this.shouldParseEnums() && this.isContextual("enum")) {
  1153. const node = this.startNode();
  1154. this.next();
  1155. return this.flowParseEnumDeclaration(node);
  1156. }
  1157. return super.parseExportDefaultExpression();
  1158. }
  1159. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  1160. if (!this.match(_types.types.question)) return expr;
  1161. if (refNeedsArrowPos) {
  1162. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  1163. if (!result.node) {
  1164. refNeedsArrowPos.start = result.error.pos || this.state.start;
  1165. return expr;
  1166. }
  1167. if (result.error) this.state = result.failState;
  1168. return result.node;
  1169. }
  1170. this.expect(_types.types.question);
  1171. const state = this.state.clone();
  1172. const originalNoArrowAt = this.state.noArrowAt;
  1173. const node = this.startNodeAt(startPos, startLoc);
  1174. let {
  1175. consequent,
  1176. failed
  1177. } = this.tryParseConditionalConsequent();
  1178. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  1179. if (failed || invalid.length > 0) {
  1180. const noArrowAt = [...originalNoArrowAt];
  1181. if (invalid.length > 0) {
  1182. this.state = state;
  1183. this.state.noArrowAt = noArrowAt;
  1184. for (let i = 0; i < invalid.length; i++) {
  1185. noArrowAt.push(invalid[i].start);
  1186. }
  1187. ({
  1188. consequent,
  1189. failed
  1190. } = this.tryParseConditionalConsequent());
  1191. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  1192. }
  1193. if (failed && valid.length > 1) {
  1194. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  1195. }
  1196. if (failed && valid.length === 1) {
  1197. this.state = state;
  1198. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  1199. ({
  1200. consequent,
  1201. failed
  1202. } = this.tryParseConditionalConsequent());
  1203. }
  1204. }
  1205. this.getArrowLikeExpressions(consequent, true);
  1206. this.state.noArrowAt = originalNoArrowAt;
  1207. this.expect(_types.types.colon);
  1208. node.test = expr;
  1209. node.consequent = consequent;
  1210. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
  1211. return this.finishNode(node, "ConditionalExpression");
  1212. }
  1213. tryParseConditionalConsequent() {
  1214. this.state.noArrowParamsConversionAt.push(this.state.start);
  1215. const consequent = this.parseMaybeAssignAllowIn();
  1216. const failed = !this.match(_types.types.colon);
  1217. this.state.noArrowParamsConversionAt.pop();
  1218. return {
  1219. consequent,
  1220. failed
  1221. };
  1222. }
  1223. getArrowLikeExpressions(node, disallowInvalid) {
  1224. const stack = [node];
  1225. const arrows = [];
  1226. while (stack.length !== 0) {
  1227. const node = stack.pop();
  1228. if (node.type === "ArrowFunctionExpression") {
  1229. if (node.typeParameters || !node.returnType) {
  1230. this.finishArrowValidation(node);
  1231. } else {
  1232. arrows.push(node);
  1233. }
  1234. stack.push(node.body);
  1235. } else if (node.type === "ConditionalExpression") {
  1236. stack.push(node.consequent);
  1237. stack.push(node.alternate);
  1238. }
  1239. }
  1240. if (disallowInvalid) {
  1241. arrows.forEach(node => this.finishArrowValidation(node));
  1242. return [arrows, []];
  1243. }
  1244. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  1245. }
  1246. finishArrowValidation(node) {
  1247. this.toAssignableList(node.params, node.extra?.trailingComma);
  1248. this.scope.enter(_scopeflags.SCOPE_FUNCTION | _scopeflags.SCOPE_ARROW);
  1249. super.checkParams(node, false, true);
  1250. this.scope.exit();
  1251. }
  1252. forwardNoArrowParamsConversionAt(node, parse) {
  1253. let result;
  1254. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  1255. this.state.noArrowParamsConversionAt.push(this.state.start);
  1256. result = parse();
  1257. this.state.noArrowParamsConversionAt.pop();
  1258. } else {
  1259. result = parse();
  1260. }
  1261. return result;
  1262. }
  1263. parseParenItem(node, startPos, startLoc) {
  1264. node = super.parseParenItem(node, startPos, startLoc);
  1265. if (this.eat(_types.types.question)) {
  1266. node.optional = true;
  1267. this.resetEndLocation(node);
  1268. }
  1269. if (this.match(_types.types.colon)) {
  1270. const typeCastNode = this.startNodeAt(startPos, startLoc);
  1271. typeCastNode.expression = node;
  1272. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  1273. return this.finishNode(typeCastNode, "TypeCastExpression");
  1274. }
  1275. return node;
  1276. }
  1277. assertModuleNodeAllowed(node) {
  1278. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  1279. return;
  1280. }
  1281. super.assertModuleNodeAllowed(node);
  1282. }
  1283. parseExport(node) {
  1284. const decl = super.parseExport(node);
  1285. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  1286. decl.exportKind = decl.exportKind || "value";
  1287. }
  1288. return decl;
  1289. }
  1290. parseExportDeclaration(node) {
  1291. if (this.isContextual("type")) {
  1292. node.exportKind = "type";
  1293. const declarationNode = this.startNode();
  1294. this.next();
  1295. if (this.match(_types.types.braceL)) {
  1296. node.specifiers = this.parseExportSpecifiers();
  1297. this.parseExportFrom(node);
  1298. return null;
  1299. } else {
  1300. return this.flowParseTypeAlias(declarationNode);
  1301. }
  1302. } else if (this.isContextual("opaque")) {
  1303. node.exportKind = "type";
  1304. const declarationNode = this.startNode();
  1305. this.next();
  1306. return this.flowParseOpaqueType(declarationNode, false);
  1307. } else if (this.isContextual("interface")) {
  1308. node.exportKind = "type";
  1309. const declarationNode = this.startNode();
  1310. this.next();
  1311. return this.flowParseInterface(declarationNode);
  1312. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  1313. node.exportKind = "value";
  1314. const declarationNode = this.startNode();
  1315. this.next();
  1316. return this.flowParseEnumDeclaration(declarationNode);
  1317. } else {
  1318. return super.parseExportDeclaration(node);
  1319. }
  1320. }
  1321. eatExportStar(node) {
  1322. if (super.eatExportStar(...arguments)) return true;
  1323. if (this.isContextual("type") && this.lookahead().type === _types.types.star) {
  1324. node.exportKind = "type";
  1325. this.next();
  1326. this.next();
  1327. return true;
  1328. }
  1329. return false;
  1330. }
  1331. maybeParseExportNamespaceSpecifier(node) {
  1332. const pos = this.state.start;
  1333. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  1334. if (hasNamespace && node.exportKind === "type") {
  1335. this.unexpected(pos);
  1336. }
  1337. return hasNamespace;
  1338. }
  1339. parseClassId(node, isStatement, optionalId) {
  1340. super.parseClassId(node, isStatement, optionalId);
  1341. if (this.isRelational("<")) {
  1342. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1343. }
  1344. }
  1345. parseClassMember(classBody, member, state) {
  1346. const pos = this.state.start;
  1347. if (this.isContextual("declare")) {
  1348. if (this.parseClassMemberFromModifier(classBody, member)) {
  1349. return;
  1350. }
  1351. member.declare = true;
  1352. }
  1353. super.parseClassMember(classBody, member, state);
  1354. if (member.declare) {
  1355. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  1356. this.raise(pos, FlowErrors.DeclareClassElement);
  1357. } else if (member.value) {
  1358. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  1359. }
  1360. }
  1361. }
  1362. getTokenFromCode(code) {
  1363. const next = this.input.charCodeAt(this.state.pos + 1);
  1364. if (code === 123 && next === 124) {
  1365. return this.finishOp(_types.types.braceBarL, 2);
  1366. } else if (this.state.inType && (code === 62 || code === 60)) {
  1367. return this.finishOp(_types.types.relational, 1);
  1368. } else if (this.state.inType && code === 63) {
  1369. return this.finishOp(_types.types.question, 1);
  1370. } else if ((0, _identifier.isIteratorStart)(code, next)) {
  1371. this.state.isIterator = true;
  1372. return super.readWord();
  1373. } else {
  1374. return super.getTokenFromCode(code);
  1375. }
  1376. }
  1377. isAssignable(node, isBinding) {
  1378. switch (node.type) {
  1379. case "Identifier":
  1380. case "ObjectPattern":
  1381. case "ArrayPattern":
  1382. case "AssignmentPattern":
  1383. return true;
  1384. case "ObjectExpression":
  1385. {
  1386. const last = node.properties.length - 1;
  1387. return node.properties.every((prop, i) => {
  1388. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  1389. });
  1390. }
  1391. case "ObjectProperty":
  1392. return this.isAssignable(node.value);
  1393. case "SpreadElement":
  1394. return this.isAssignable(node.argument);
  1395. case "ArrayExpression":
  1396. return node.elements.every(element => this.isAssignable(element));
  1397. case "AssignmentExpression":
  1398. return node.operator === "=";
  1399. case "ParenthesizedExpression":
  1400. case "TypeCastExpression":
  1401. return this.isAssignable(node.expression);
  1402. case "MemberExpression":
  1403. case "OptionalMemberExpression":
  1404. return !isBinding;
  1405. default:
  1406. return false;
  1407. }
  1408. }
  1409. toAssignable(node) {
  1410. if (node.type === "TypeCastExpression") {
  1411. return super.toAssignable(this.typeCastToParameter(node));
  1412. } else {
  1413. return super.toAssignable(node);
  1414. }
  1415. }
  1416. toAssignableList(exprList, trailingCommaPos) {
  1417. for (let i = 0; i < exprList.length; i++) {
  1418. const expr = exprList[i];
  1419. if (expr?.type === "TypeCastExpression") {
  1420. exprList[i] = this.typeCastToParameter(expr);
  1421. }
  1422. }
  1423. return super.toAssignableList(exprList, trailingCommaPos);
  1424. }
  1425. toReferencedList(exprList, isParenthesizedExpr) {
  1426. for (let i = 0; i < exprList.length; i++) {
  1427. const expr = exprList[i];
  1428. if (expr && expr.type === "TypeCastExpression" && !expr.extra?.parenthesized && (exprList.length > 1 || !isParenthesizedExpr)) {
  1429. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  1430. }
  1431. }
  1432. return exprList;
  1433. }
  1434. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  1435. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  1436. if (canBePattern && !this.state.maybeInArrowParameters) {
  1437. this.toReferencedList(node.elements);
  1438. }
  1439. return node;
  1440. }
  1441. checkLVal(expr, bindingType = _scopeflags.BIND_NONE, checkClashes, contextDescription) {
  1442. if (expr.type !== "TypeCastExpression") {
  1443. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  1444. }
  1445. }
  1446. parseClassProperty(node) {
  1447. if (this.match(_types.types.colon)) {
  1448. node.typeAnnotation = this.flowParseTypeAnnotation();
  1449. }
  1450. return super.parseClassProperty(node);
  1451. }
  1452. parseClassPrivateProperty(node) {
  1453. if (this.match(_types.types.colon)) {
  1454. node.typeAnnotation = this.flowParseTypeAnnotation();
  1455. }
  1456. return super.parseClassPrivateProperty(node);
  1457. }
  1458. isClassMethod() {
  1459. return this.isRelational("<") || super.isClassMethod();
  1460. }
  1461. isClassProperty() {
  1462. return this.match(_types.types.colon) || super.isClassProperty();
  1463. }
  1464. isNonstaticConstructor(method) {
  1465. return !this.match(_types.types.colon) && super.isNonstaticConstructor(method);
  1466. }
  1467. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  1468. if (method.variance) {
  1469. this.unexpected(method.variance.start);
  1470. }
  1471. delete method.variance;
  1472. if (this.isRelational("<")) {
  1473. method.typeParameters = this.flowParseTypeParameterDeclaration();
  1474. }
  1475. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  1476. }
  1477. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  1478. if (method.variance) {
  1479. this.unexpected(method.variance.start);
  1480. }
  1481. delete method.variance;
  1482. if (this.isRelational("<")) {
  1483. method.typeParameters = this.flowParseTypeParameterDeclaration();
  1484. }
  1485. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  1486. }
  1487. parseClassSuper(node) {
  1488. super.parseClassSuper(node);
  1489. if (node.superClass && this.isRelational("<")) {
  1490. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  1491. }
  1492. if (this.isContextual("implements")) {
  1493. this.next();
  1494. const implemented = node.implements = [];
  1495. do {
  1496. const node = this.startNode();
  1497. node.id = this.flowParseRestrictedIdentifier(true);
  1498. if (this.isRelational("<")) {
  1499. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1500. } else {
  1501. node.typeParameters = null;
  1502. }
  1503. implemented.push(this.finishNode(node, "ClassImplements"));
  1504. } while (this.eat(_types.types.comma));
  1505. }
  1506. }
  1507. parsePropertyName(node, isPrivateNameAllowed) {
  1508. const variance = this.flowParseVariance();
  1509. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  1510. node.variance = variance;
  1511. return key;
  1512. }
  1513. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  1514. if (prop.variance) {
  1515. this.unexpected(prop.variance.start);
  1516. }
  1517. delete prop.variance;
  1518. let typeParameters;
  1519. if (this.isRelational("<") && !isAccessor) {
  1520. typeParameters = this.flowParseTypeParameterDeclaration();
  1521. if (!this.match(_types.types.parenL)) this.unexpected();
  1522. }
  1523. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  1524. if (typeParameters) {
  1525. (prop.value || prop).typeParameters = typeParameters;
  1526. }
  1527. }
  1528. parseAssignableListItemTypes(param) {
  1529. if (this.eat(_types.types.question)) {
  1530. if (param.type !== "Identifier") {
  1531. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  1532. }
  1533. param.optional = true;
  1534. }
  1535. if (this.match(_types.types.colon)) {
  1536. param.typeAnnotation = this.flowParseTypeAnnotation();
  1537. }
  1538. this.resetEndLocation(param);
  1539. return param;
  1540. }
  1541. parseMaybeDefault(startPos, startLoc, left) {
  1542. const node = super.parseMaybeDefault(startPos, startLoc, left);
  1543. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  1544. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  1545. }
  1546. return node;
  1547. }
  1548. shouldParseDefaultImport(node) {
  1549. if (!hasTypeImportKind(node)) {
  1550. return super.shouldParseDefaultImport(node);
  1551. }
  1552. return isMaybeDefaultImport(this.state);
  1553. }
  1554. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  1555. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  1556. this.checkLVal(specifier.local, _scopeflags.BIND_LEXICAL, undefined, contextDescription);
  1557. node.specifiers.push(this.finishNode(specifier, type));
  1558. }
  1559. maybeParseDefaultImportSpecifier(node) {
  1560. node.importKind = "value";
  1561. let kind = null;
  1562. if (this.match(_types.types._typeof)) {
  1563. kind = "typeof";
  1564. } else if (this.isContextual("type")) {
  1565. kind = "type";
  1566. }
  1567. if (kind) {
  1568. const lh = this.lookahead();
  1569. if (kind === "type" && lh.type === _types.types.star) {
  1570. this.unexpected(lh.start);
  1571. }
  1572. if (isMaybeDefaultImport(lh) || lh.type === _types.types.braceL || lh.type === _types.types.star) {
  1573. this.next();
  1574. node.importKind = kind;
  1575. }
  1576. }
  1577. return super.maybeParseDefaultImportSpecifier(node);
  1578. }
  1579. parseImportSpecifier(node) {
  1580. const specifier = this.startNode();
  1581. const firstIdentLoc = this.state.start;
  1582. const firstIdent = this.parseModuleExportName();
  1583. let specifierTypeKind = null;
  1584. if (firstIdent.type === "Identifier") {
  1585. if (firstIdent.name === "type") {
  1586. specifierTypeKind = "type";
  1587. } else if (firstIdent.name === "typeof") {
  1588. specifierTypeKind = "typeof";
  1589. }
  1590. }
  1591. let isBinding = false;
  1592. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  1593. const as_ident = this.parseIdentifier(true);
  1594. if (specifierTypeKind !== null && !this.match(_types.types.name) && !this.state.type.keyword) {
  1595. specifier.imported = as_ident;
  1596. specifier.importKind = specifierTypeKind;
  1597. specifier.local = as_ident.__clone();
  1598. } else {
  1599. specifier.imported = firstIdent;
  1600. specifier.importKind = null;
  1601. specifier.local = this.parseIdentifier();
  1602. }
  1603. } else if (specifierTypeKind !== null && (this.match(_types.types.name) || this.state.type.keyword)) {
  1604. specifier.imported = this.parseIdentifier(true);
  1605. specifier.importKind = specifierTypeKind;
  1606. if (this.eatContextual("as")) {
  1607. specifier.local = this.parseIdentifier();
  1608. } else {
  1609. isBinding = true;
  1610. specifier.local = specifier.imported.__clone();
  1611. }
  1612. } else {
  1613. if (firstIdent.type === "StringLiteral") {
  1614. throw this.raise(specifier.start, _error.Errors.ImportBindingIsString, firstIdent.value);
  1615. }
  1616. isBinding = true;
  1617. specifier.imported = firstIdent;
  1618. specifier.importKind = null;
  1619. specifier.local = specifier.imported.__clone();
  1620. }
  1621. const nodeIsTypeImport = hasTypeImportKind(node);
  1622. const specifierIsTypeImport = hasTypeImportKind(specifier);
  1623. if (nodeIsTypeImport && specifierIsTypeImport) {
  1624. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  1625. }
  1626. if (nodeIsTypeImport || specifierIsTypeImport) {
  1627. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  1628. }
  1629. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  1630. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  1631. }
  1632. this.checkLVal(specifier.local, _scopeflags.BIND_LEXICAL, undefined, "import specifier");
  1633. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  1634. }
  1635. parseFunctionParams(node, allowModifiers) {
  1636. const kind = node.kind;
  1637. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  1638. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1639. }
  1640. super.parseFunctionParams(node, allowModifiers);
  1641. }
  1642. parseVarId(decl, kind) {
  1643. super.parseVarId(decl, kind);
  1644. if (this.match(_types.types.colon)) {
  1645. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  1646. this.resetEndLocation(decl.id);
  1647. }
  1648. }
  1649. parseAsyncArrowFromCallExpression(node, call) {
  1650. if (this.match(_types.types.colon)) {
  1651. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1652. this.state.noAnonFunctionType = true;
  1653. node.returnType = this.flowParseTypeAnnotation();
  1654. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1655. }
  1656. return super.parseAsyncArrowFromCallExpression(node, call);
  1657. }
  1658. shouldParseAsyncArrow() {
  1659. return this.match(_types.types.colon) || super.shouldParseAsyncArrow();
  1660. }
  1661. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  1662. let state = null;
  1663. let jsx;
  1664. if (this.hasPlugin("jsx") && (this.match(_types.types.jsxTagStart) || this.isRelational("<"))) {
  1665. state = this.state.clone();
  1666. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  1667. if (!jsx.error) return jsx.node;
  1668. const {
  1669. context
  1670. } = this.state;
  1671. if (context[context.length - 1] === _context.types.j_oTag) {
  1672. context.length -= 2;
  1673. } else if (context[context.length - 1] === _context.types.j_expr) {
  1674. context.length -= 1;
  1675. }
  1676. }
  1677. if (jsx?.error || this.isRelational("<")) {
  1678. state = state || this.state.clone();
  1679. let typeParameters;
  1680. const arrow = this.tryParse(abort => {
  1681. typeParameters = this.flowParseTypeParameterDeclaration();
  1682. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  1683. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  1684. this.resetStartLocationFromNode(result, typeParameters);
  1685. return result;
  1686. });
  1687. if (arrowExpression.type !== "ArrowFunctionExpression" && arrowExpression.extra?.parenthesized) {
  1688. abort();
  1689. }
  1690. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  1691. expr.typeParameters = typeParameters;
  1692. this.resetStartLocationFromNode(expr, typeParameters);
  1693. return arrowExpression;
  1694. }, state);
  1695. let arrowExpression = null;
  1696. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  1697. if (!arrow.error && !arrow.aborted) {
  1698. if (arrow.node.async) {
  1699. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  1700. }
  1701. return arrow.node;
  1702. }
  1703. arrowExpression = arrow.node;
  1704. }
  1705. if (jsx?.node) {
  1706. this.state = jsx.failState;
  1707. return jsx.node;
  1708. }
  1709. if (arrowExpression) {
  1710. this.state = arrow.failState;
  1711. return arrowExpression;
  1712. }
  1713. if (jsx?.thrown) throw jsx.error;
  1714. if (arrow.thrown) throw arrow.error;
  1715. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  1716. }
  1717. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  1718. }
  1719. parseArrow(node) {
  1720. if (this.match(_types.types.colon)) {
  1721. const result = this.tryParse(() => {
  1722. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1723. this.state.noAnonFunctionType = true;
  1724. const typeNode = this.startNode();
  1725. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1726. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1727. if (this.canInsertSemicolon()) this.unexpected();
  1728. if (!this.match(_types.types.arrow)) this.unexpected();
  1729. return typeNode;
  1730. });
  1731. if (result.thrown) return null;
  1732. if (result.error) this.state = result.failState;
  1733. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  1734. }
  1735. return super.parseArrow(node);
  1736. }
  1737. shouldParseArrow() {
  1738. return this.match(_types.types.colon) || super.shouldParseArrow();
  1739. }
  1740. setArrowFunctionParameters(node, params) {
  1741. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  1742. node.params = params;
  1743. } else {
  1744. super.setArrowFunctionParameters(node, params);
  1745. }
  1746. }
  1747. checkParams(node, allowDuplicates, isArrowFunction) {
  1748. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  1749. return;
  1750. }
  1751. return super.checkParams(...arguments);
  1752. }
  1753. parseParenAndDistinguishExpression(canBeArrow) {
  1754. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  1755. }
  1756. parseSubscripts(base, startPos, startLoc, noCalls) {
  1757. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  1758. this.next();
  1759. const node = this.startNodeAt(startPos, startLoc);
  1760. node.callee = base;
  1761. node.arguments = this.parseCallExpressionArguments(_types.types.parenR, false);
  1762. base = this.finishNode(node, "CallExpression");
  1763. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  1764. const state = this.state.clone();
  1765. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  1766. if (!arrow.error && !arrow.aborted) return arrow.node;
  1767. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  1768. if (result.node && !result.error) return result.node;
  1769. if (arrow.node) {
  1770. this.state = arrow.failState;
  1771. return arrow.node;
  1772. }
  1773. if (result.node) {
  1774. this.state = result.failState;
  1775. return result.node;
  1776. }
  1777. throw arrow.error || result.error;
  1778. }
  1779. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  1780. }
  1781. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  1782. if (this.match(_types.types.questionDot) && this.isLookaheadToken_lt()) {
  1783. subscriptState.optionalChainMember = true;
  1784. if (noCalls) {
  1785. subscriptState.stop = true;
  1786. return base;
  1787. }
  1788. this.next();
  1789. const node = this.startNodeAt(startPos, startLoc);
  1790. node.callee = base;
  1791. node.typeArguments = this.flowParseTypeParameterInstantiation();
  1792. this.expect(_types.types.parenL);
  1793. node.arguments = this.parseCallExpressionArguments(_types.types.parenR, false);
  1794. node.optional = true;
  1795. return this.finishCallExpression(node, true);
  1796. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  1797. const node = this.startNodeAt(startPos, startLoc);
  1798. node.callee = base;
  1799. const result = this.tryParse(() => {
  1800. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  1801. this.expect(_types.types.parenL);
  1802. node.arguments = this.parseCallExpressionArguments(_types.types.parenR, false);
  1803. if (subscriptState.optionalChainMember) node.optional = false;
  1804. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  1805. });
  1806. if (result.node) {
  1807. if (result.error) this.state = result.failState;
  1808. return result.node;
  1809. }
  1810. }
  1811. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  1812. }
  1813. parseNewArguments(node) {
  1814. let targs = null;
  1815. if (this.shouldParseTypes() && this.isRelational("<")) {
  1816. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  1817. }
  1818. node.typeArguments = targs;
  1819. super.parseNewArguments(node);
  1820. }
  1821. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  1822. const node = this.startNodeAt(startPos, startLoc);
  1823. this.parseFunctionParams(node);
  1824. if (!this.parseArrow(node)) return;
  1825. return this.parseArrowExpression(node, undefined, true);
  1826. }
  1827. readToken_mult_modulo(code) {
  1828. const next = this.input.charCodeAt(this.state.pos + 1);
  1829. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  1830. this.state.hasFlowComment = false;
  1831. this.state.pos += 2;
  1832. this.nextToken();
  1833. return;
  1834. }
  1835. super.readToken_mult_modulo(code);
  1836. }
  1837. readToken_pipe_amp(code) {
  1838. const next = this.input.charCodeAt(this.state.pos + 1);
  1839. if (code === 124 && next === 125) {
  1840. this.finishOp(_types.types.braceBarR, 2);
  1841. return;
  1842. }
  1843. super.readToken_pipe_amp(code);
  1844. }
  1845. parseTopLevel(file, program) {
  1846. const fileNode = super.parseTopLevel(file, program);
  1847. if (this.state.hasFlowComment) {
  1848. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  1849. }
  1850. return fileNode;
  1851. }
  1852. skipBlockComment() {
  1853. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  1854. if (this.state.hasFlowComment) {
  1855. this.unexpected(null, FlowErrors.NestedFlowComment);
  1856. }
  1857. this.hasFlowCommentCompletion();
  1858. this.state.pos += this.skipFlowComment();
  1859. this.state.hasFlowComment = true;
  1860. return;
  1861. }
  1862. if (this.state.hasFlowComment) {
  1863. const end = this.input.indexOf("*-/", this.state.pos += 2);
  1864. if (end === -1) {
  1865. throw this.raise(this.state.pos - 2, _error.Errors.UnterminatedComment);
  1866. }
  1867. this.state.pos = end + 3;
  1868. return;
  1869. }
  1870. super.skipBlockComment();
  1871. }
  1872. skipFlowComment() {
  1873. const {
  1874. pos
  1875. } = this.state;
  1876. let shiftToFirstNonWhiteSpace = 2;
  1877. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  1878. shiftToFirstNonWhiteSpace++;
  1879. }
  1880. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  1881. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  1882. if (ch2 === 58 && ch3 === 58) {
  1883. return shiftToFirstNonWhiteSpace + 2;
  1884. }
  1885. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  1886. return shiftToFirstNonWhiteSpace + 12;
  1887. }
  1888. if (ch2 === 58 && ch3 !== 58) {
  1889. return shiftToFirstNonWhiteSpace;
  1890. }
  1891. return false;
  1892. }
  1893. hasFlowCommentCompletion() {
  1894. const end = this.input.indexOf("*/", this.state.pos);
  1895. if (end === -1) {
  1896. throw this.raise(this.state.pos, _error.Errors.UnterminatedComment);
  1897. }
  1898. }
  1899. flowEnumErrorBooleanMemberNotInitialized(pos, {
  1900. enumName,
  1901. memberName
  1902. }) {
  1903. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  1904. }
  1905. flowEnumErrorInvalidMemberName(pos, {
  1906. enumName,
  1907. memberName
  1908. }) {
  1909. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  1910. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  1911. }
  1912. flowEnumErrorDuplicateMemberName(pos, {
  1913. enumName,
  1914. memberName
  1915. }) {
  1916. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  1917. }
  1918. flowEnumErrorInconsistentMemberValues(pos, {
  1919. enumName
  1920. }) {
  1921. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  1922. }
  1923. flowEnumErrorInvalidExplicitType(pos, {
  1924. enumName,
  1925. suppliedType
  1926. }) {
  1927. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  1928. }
  1929. flowEnumErrorInvalidMemberInitializer(pos, {
  1930. enumName,
  1931. explicitType,
  1932. memberName
  1933. }) {
  1934. let message = null;
  1935. switch (explicitType) {
  1936. case "boolean":
  1937. case "number":
  1938. case "string":
  1939. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  1940. break;
  1941. case "symbol":
  1942. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  1943. break;
  1944. default:
  1945. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  1946. }
  1947. return this.raise(pos, message, enumName, memberName, explicitType);
  1948. }
  1949. flowEnumErrorNumberMemberNotInitialized(pos, {
  1950. enumName,
  1951. memberName
  1952. }) {
  1953. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  1954. }
  1955. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  1956. enumName
  1957. }) {
  1958. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  1959. }
  1960. flowEnumMemberInit() {
  1961. const startPos = this.state.start;
  1962. const endOfInit = () => this.match(_types.types.comma) || this.match(_types.types.braceR);
  1963. switch (this.state.type) {
  1964. case _types.types.num:
  1965. {
  1966. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  1967. if (endOfInit()) {
  1968. return {
  1969. type: "number",
  1970. pos: literal.start,
  1971. value: literal
  1972. };
  1973. }
  1974. return {
  1975. type: "invalid",
  1976. pos: startPos
  1977. };
  1978. }
  1979. case _types.types.string:
  1980. {
  1981. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  1982. if (endOfInit()) {
  1983. return {
  1984. type: "string",
  1985. pos: literal.start,
  1986. value: literal
  1987. };
  1988. }
  1989. return {
  1990. type: "invalid",
  1991. pos: startPos
  1992. };
  1993. }
  1994. case _types.types._true:
  1995. case _types.types._false:
  1996. {
  1997. const literal = this.parseBooleanLiteral();
  1998. if (endOfInit()) {
  1999. return {
  2000. type: "boolean",
  2001. pos: literal.start,
  2002. value: literal
  2003. };
  2004. }
  2005. return {
  2006. type: "invalid",
  2007. pos: startPos
  2008. };
  2009. }
  2010. default:
  2011. return {
  2012. type: "invalid",
  2013. pos: startPos
  2014. };
  2015. }
  2016. }
  2017. flowEnumMemberRaw() {
  2018. const pos = this.state.start;
  2019. const id = this.parseIdentifier(true);
  2020. const init = this.eat(_types.types.eq) ? this.flowEnumMemberInit() : {
  2021. type: "none",
  2022. pos
  2023. };
  2024. return {
  2025. id,
  2026. init
  2027. };
  2028. }
  2029. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  2030. const {
  2031. explicitType
  2032. } = context;
  2033. if (explicitType === null) {
  2034. return;
  2035. }
  2036. if (explicitType !== expectedType) {
  2037. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  2038. }
  2039. }
  2040. flowEnumMembers({
  2041. enumName,
  2042. explicitType
  2043. }) {
  2044. const seenNames = new Set();
  2045. const members = {
  2046. booleanMembers: [],
  2047. numberMembers: [],
  2048. stringMembers: [],
  2049. defaultedMembers: []
  2050. };
  2051. while (!this.match(_types.types.braceR)) {
  2052. const memberNode = this.startNode();
  2053. const {
  2054. id,
  2055. init
  2056. } = this.flowEnumMemberRaw();
  2057. const memberName = id.name;
  2058. if (memberName === "") {
  2059. continue;
  2060. }
  2061. if (/^[a-z]/.test(memberName)) {
  2062. this.flowEnumErrorInvalidMemberName(id.start, {
  2063. enumName,
  2064. memberName
  2065. });
  2066. }
  2067. if (seenNames.has(memberName)) {
  2068. this.flowEnumErrorDuplicateMemberName(id.start, {
  2069. enumName,
  2070. memberName
  2071. });
  2072. }
  2073. seenNames.add(memberName);
  2074. const context = {
  2075. enumName,
  2076. explicitType,
  2077. memberName
  2078. };
  2079. memberNode.id = id;
  2080. switch (init.type) {
  2081. case "boolean":
  2082. {
  2083. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  2084. memberNode.init = init.value;
  2085. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  2086. break;
  2087. }
  2088. case "number":
  2089. {
  2090. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  2091. memberNode.init = init.value;
  2092. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  2093. break;
  2094. }
  2095. case "string":
  2096. {
  2097. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  2098. memberNode.init = init.value;
  2099. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  2100. break;
  2101. }
  2102. case "invalid":
  2103. {
  2104. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  2105. }
  2106. case "none":
  2107. {
  2108. switch (explicitType) {
  2109. case "boolean":
  2110. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  2111. break;
  2112. case "number":
  2113. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  2114. break;
  2115. default:
  2116. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  2117. }
  2118. }
  2119. }
  2120. if (!this.match(_types.types.braceR)) {
  2121. this.expect(_types.types.comma);
  2122. }
  2123. }
  2124. return members;
  2125. }
  2126. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  2127. enumName
  2128. }) {
  2129. if (initializedMembers.length === 0) {
  2130. return defaultedMembers;
  2131. } else if (defaultedMembers.length === 0) {
  2132. return initializedMembers;
  2133. } else if (defaultedMembers.length > initializedMembers.length) {
  2134. for (let _i = 0; _i < initializedMembers.length; _i++) {
  2135. const member = initializedMembers[_i];
  2136. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  2137. enumName
  2138. });
  2139. }
  2140. return defaultedMembers;
  2141. } else {
  2142. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  2143. const member = defaultedMembers[_i2];
  2144. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  2145. enumName
  2146. });
  2147. }
  2148. return initializedMembers;
  2149. }
  2150. }
  2151. flowEnumParseExplicitType({
  2152. enumName
  2153. }) {
  2154. if (this.eatContextual("of")) {
  2155. if (!this.match(_types.types.name)) {
  2156. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  2157. enumName,
  2158. suppliedType: null
  2159. });
  2160. }
  2161. const {
  2162. value
  2163. } = this.state;
  2164. this.next();
  2165. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  2166. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  2167. enumName,
  2168. suppliedType: value
  2169. });
  2170. }
  2171. return value;
  2172. }
  2173. return null;
  2174. }
  2175. flowEnumBody(node, {
  2176. enumName,
  2177. nameLoc
  2178. }) {
  2179. const explicitType = this.flowEnumParseExplicitType({
  2180. enumName
  2181. });
  2182. this.expect(_types.types.braceL);
  2183. const members = this.flowEnumMembers({
  2184. enumName,
  2185. explicitType
  2186. });
  2187. switch (explicitType) {
  2188. case "boolean":
  2189. node.explicitType = true;
  2190. node.members = members.booleanMembers;
  2191. this.expect(_types.types.braceR);
  2192. return this.finishNode(node, "EnumBooleanBody");
  2193. case "number":
  2194. node.explicitType = true;
  2195. node.members = members.numberMembers;
  2196. this.expect(_types.types.braceR);
  2197. return this.finishNode(node, "EnumNumberBody");
  2198. case "string":
  2199. node.explicitType = true;
  2200. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  2201. enumName
  2202. });
  2203. this.expect(_types.types.braceR);
  2204. return this.finishNode(node, "EnumStringBody");
  2205. case "symbol":
  2206. node.members = members.defaultedMembers;
  2207. this.expect(_types.types.braceR);
  2208. return this.finishNode(node, "EnumSymbolBody");
  2209. default:
  2210. {
  2211. const empty = () => {
  2212. node.members = [];
  2213. this.expect(_types.types.braceR);
  2214. return this.finishNode(node, "EnumStringBody");
  2215. };
  2216. node.explicitType = false;
  2217. const boolsLen = members.booleanMembers.length;
  2218. const numsLen = members.numberMembers.length;
  2219. const strsLen = members.stringMembers.length;
  2220. const defaultedLen = members.defaultedMembers.length;
  2221. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  2222. return empty();
  2223. } else if (!boolsLen && !numsLen) {
  2224. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  2225. enumName
  2226. });
  2227. this.expect(_types.types.braceR);
  2228. return this.finishNode(node, "EnumStringBody");
  2229. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  2230. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  2231. const member = _members$defaultedMem[_i3];
  2232. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  2233. enumName,
  2234. memberName: member.id.name
  2235. });
  2236. }
  2237. node.members = members.booleanMembers;
  2238. this.expect(_types.types.braceR);
  2239. return this.finishNode(node, "EnumBooleanBody");
  2240. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  2241. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  2242. const member = _members$defaultedMem2[_i4];
  2243. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  2244. enumName,
  2245. memberName: member.id.name
  2246. });
  2247. }
  2248. node.members = members.numberMembers;
  2249. this.expect(_types.types.braceR);
  2250. return this.finishNode(node, "EnumNumberBody");
  2251. } else {
  2252. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  2253. enumName
  2254. });
  2255. return empty();
  2256. }
  2257. }
  2258. }
  2259. }
  2260. flowParseEnumDeclaration(node) {
  2261. const id = this.parseIdentifier();
  2262. node.id = id;
  2263. node.body = this.flowEnumBody(this.startNode(), {
  2264. enumName: id.name,
  2265. nameLoc: id.start
  2266. });
  2267. return this.finishNode(node, "EnumDeclaration");
  2268. }
  2269. updateContext(prevType) {
  2270. if (this.match(_types.types.name) && this.state.value === "of" && prevType === _types.types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  2271. this.state.exprAllowed = false;
  2272. } else {
  2273. super.updateContext(prevType);
  2274. }
  2275. }
  2276. isLookaheadToken_lt() {
  2277. const next = this.nextTokenStart();
  2278. if (this.input.charCodeAt(next) === 60) {
  2279. const afterNext = this.input.charCodeAt(next + 1);
  2280. return afterNext !== 60 && afterNext !== 61;
  2281. }
  2282. return false;
  2283. }
  2284. maybeUnwrapTypeCastExpression(node) {
  2285. return node.type === "TypeCastExpression" ? node.expression : node;
  2286. }
  2287. }, _temp;
  2288. };
  2289. exports.default = _default;