index.js 84 KB

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