parser.js.flow 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
  1. // @flow strict
  2. import inspect from '../jsutils/inspect';
  3. import devAssert from '../jsutils/devAssert';
  4. import type { GraphQLError } from '../error/GraphQLError';
  5. import { syntaxError } from '../error/syntaxError';
  6. import type { TokenKindEnum } from './tokenKind';
  7. import type {
  8. Token,
  9. NameNode,
  10. VariableNode,
  11. DocumentNode,
  12. DefinitionNode,
  13. OperationDefinitionNode,
  14. OperationTypeNode,
  15. VariableDefinitionNode,
  16. SelectionSetNode,
  17. SelectionNode,
  18. FieldNode,
  19. ArgumentNode,
  20. FragmentSpreadNode,
  21. InlineFragmentNode,
  22. FragmentDefinitionNode,
  23. ValueNode,
  24. StringValueNode,
  25. ListValueNode,
  26. ObjectValueNode,
  27. ObjectFieldNode,
  28. DirectiveNode,
  29. TypeNode,
  30. NamedTypeNode,
  31. TypeSystemDefinitionNode,
  32. SchemaDefinitionNode,
  33. OperationTypeDefinitionNode,
  34. ScalarTypeDefinitionNode,
  35. ObjectTypeDefinitionNode,
  36. FieldDefinitionNode,
  37. InputValueDefinitionNode,
  38. InterfaceTypeDefinitionNode,
  39. UnionTypeDefinitionNode,
  40. EnumTypeDefinitionNode,
  41. EnumValueDefinitionNode,
  42. InputObjectTypeDefinitionNode,
  43. DirectiveDefinitionNode,
  44. TypeSystemExtensionNode,
  45. SchemaExtensionNode,
  46. ScalarTypeExtensionNode,
  47. ObjectTypeExtensionNode,
  48. InterfaceTypeExtensionNode,
  49. UnionTypeExtensionNode,
  50. EnumTypeExtensionNode,
  51. InputObjectTypeExtensionNode,
  52. } from './ast';
  53. import { Kind } from './kinds';
  54. import { Location } from './ast';
  55. import { Source } from './source';
  56. import { TokenKind } from './tokenKind';
  57. import { DirectiveLocation } from './directiveLocation';
  58. import { Lexer, isPunctuatorTokenKind } from './lexer';
  59. /**
  60. * Configuration options to control parser behavior
  61. */
  62. export type ParseOptions = {|
  63. /**
  64. * By default, the parser creates AST nodes that know the location
  65. * in the source that they correspond to. This configuration flag
  66. * disables that behavior for performance or testing.
  67. */
  68. noLocation?: boolean,
  69. /**
  70. * If enabled, the parser will parse empty fields sets in the Schema
  71. * Definition Language. Otherwise, the parser will follow the current
  72. * specification.
  73. *
  74. * This option is provided to ease adoption of the final SDL specification
  75. * and will be removed in v16.
  76. */
  77. allowLegacySDLEmptyFields?: boolean,
  78. /**
  79. * If enabled, the parser will parse implemented interfaces with no `&`
  80. * character between each interface. Otherwise, the parser will follow the
  81. * current specification.
  82. *
  83. * This option is provided to ease adoption of the final SDL specification
  84. * and will be removed in v16.
  85. */
  86. allowLegacySDLImplementsInterfaces?: boolean,
  87. /**
  88. * EXPERIMENTAL:
  89. *
  90. * If enabled, the parser will understand and parse variable definitions
  91. * contained in a fragment definition. They'll be represented in the
  92. * `variableDefinitions` field of the FragmentDefinitionNode.
  93. *
  94. * The syntax is identical to normal, query-defined variables. For example:
  95. *
  96. * fragment A($var: Boolean = false) on T {
  97. * ...
  98. * }
  99. *
  100. * Note: this feature is experimental and may change or be removed in the
  101. * future.
  102. */
  103. experimentalFragmentVariables?: boolean,
  104. |};
  105. /**
  106. * Given a GraphQL source, parses it into a Document.
  107. * Throws GraphQLError if a syntax error is encountered.
  108. */
  109. export function parse(
  110. source: string | Source,
  111. options?: ParseOptions,
  112. ): DocumentNode {
  113. const parser = new Parser(source, options);
  114. return parser.parseDocument();
  115. }
  116. /**
  117. * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for
  118. * that value.
  119. * Throws GraphQLError if a syntax error is encountered.
  120. *
  121. * This is useful within tools that operate upon GraphQL Values directly and
  122. * in isolation of complete GraphQL documents.
  123. *
  124. * Consider providing the results to the utility function: valueFromAST().
  125. */
  126. export function parseValue(
  127. source: string | Source,
  128. options?: ParseOptions,
  129. ): ValueNode {
  130. const parser = new Parser(source, options);
  131. parser.expectToken(TokenKind.SOF);
  132. const value = parser.parseValueLiteral(false);
  133. parser.expectToken(TokenKind.EOF);
  134. return value;
  135. }
  136. /**
  137. * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for
  138. * that type.
  139. * Throws GraphQLError if a syntax error is encountered.
  140. *
  141. * This is useful within tools that operate upon GraphQL Types directly and
  142. * in isolation of complete GraphQL documents.
  143. *
  144. * Consider providing the results to the utility function: typeFromAST().
  145. */
  146. export function parseType(
  147. source: string | Source,
  148. options?: ParseOptions,
  149. ): TypeNode {
  150. const parser = new Parser(source, options);
  151. parser.expectToken(TokenKind.SOF);
  152. const type = parser.parseTypeReference();
  153. parser.expectToken(TokenKind.EOF);
  154. return type;
  155. }
  156. class Parser {
  157. _options: ?ParseOptions;
  158. _lexer: Lexer;
  159. constructor(source: string | Source, options?: ParseOptions) {
  160. const sourceObj = typeof source === 'string' ? new Source(source) : source;
  161. devAssert(
  162. sourceObj instanceof Source,
  163. `Must provide Source. Received: ${inspect(sourceObj)}.`,
  164. );
  165. this._lexer = new Lexer(sourceObj);
  166. this._options = options;
  167. }
  168. /**
  169. * Converts a name lex token into a name parse node.
  170. */
  171. parseName(): NameNode {
  172. const token = this.expectToken(TokenKind.NAME);
  173. return {
  174. kind: Kind.NAME,
  175. value: ((token.value: any): string),
  176. loc: this.loc(token),
  177. };
  178. }
  179. // Implements the parsing rules in the Document section.
  180. /**
  181. * Document : Definition+
  182. */
  183. parseDocument(): DocumentNode {
  184. const start = this._lexer.token;
  185. return {
  186. kind: Kind.DOCUMENT,
  187. definitions: this.many(
  188. TokenKind.SOF,
  189. this.parseDefinition,
  190. TokenKind.EOF,
  191. ),
  192. loc: this.loc(start),
  193. };
  194. }
  195. /**
  196. * Definition :
  197. * - ExecutableDefinition
  198. * - TypeSystemDefinition
  199. * - TypeSystemExtension
  200. *
  201. * ExecutableDefinition :
  202. * - OperationDefinition
  203. * - FragmentDefinition
  204. */
  205. parseDefinition(): DefinitionNode {
  206. if (this.peek(TokenKind.NAME)) {
  207. switch (this._lexer.token.value) {
  208. case 'query':
  209. case 'mutation':
  210. case 'subscription':
  211. return this.parseOperationDefinition();
  212. case 'fragment':
  213. return this.parseFragmentDefinition();
  214. case 'schema':
  215. case 'scalar':
  216. case 'type':
  217. case 'interface':
  218. case 'union':
  219. case 'enum':
  220. case 'input':
  221. case 'directive':
  222. return this.parseTypeSystemDefinition();
  223. case 'extend':
  224. return this.parseTypeSystemExtension();
  225. }
  226. } else if (this.peek(TokenKind.BRACE_L)) {
  227. return this.parseOperationDefinition();
  228. } else if (this.peekDescription()) {
  229. return this.parseTypeSystemDefinition();
  230. }
  231. throw this.unexpected();
  232. }
  233. // Implements the parsing rules in the Operations section.
  234. /**
  235. * OperationDefinition :
  236. * - SelectionSet
  237. * - OperationType Name? VariableDefinitions? Directives? SelectionSet
  238. */
  239. parseOperationDefinition(): OperationDefinitionNode {
  240. const start = this._lexer.token;
  241. if (this.peek(TokenKind.BRACE_L)) {
  242. return {
  243. kind: Kind.OPERATION_DEFINITION,
  244. operation: 'query',
  245. name: undefined,
  246. variableDefinitions: [],
  247. directives: [],
  248. selectionSet: this.parseSelectionSet(),
  249. loc: this.loc(start),
  250. };
  251. }
  252. const operation = this.parseOperationType();
  253. let name;
  254. if (this.peek(TokenKind.NAME)) {
  255. name = this.parseName();
  256. }
  257. return {
  258. kind: Kind.OPERATION_DEFINITION,
  259. operation,
  260. name,
  261. variableDefinitions: this.parseVariableDefinitions(),
  262. directives: this.parseDirectives(false),
  263. selectionSet: this.parseSelectionSet(),
  264. loc: this.loc(start),
  265. };
  266. }
  267. /**
  268. * OperationType : one of query mutation subscription
  269. */
  270. parseOperationType(): OperationTypeNode {
  271. const operationToken = this.expectToken(TokenKind.NAME);
  272. switch (operationToken.value) {
  273. case 'query':
  274. return 'query';
  275. case 'mutation':
  276. return 'mutation';
  277. case 'subscription':
  278. return 'subscription';
  279. }
  280. throw this.unexpected(operationToken);
  281. }
  282. /**
  283. * VariableDefinitions : ( VariableDefinition+ )
  284. */
  285. parseVariableDefinitions(): Array<VariableDefinitionNode> {
  286. return this.optionalMany(
  287. TokenKind.PAREN_L,
  288. this.parseVariableDefinition,
  289. TokenKind.PAREN_R,
  290. );
  291. }
  292. /**
  293. * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
  294. */
  295. parseVariableDefinition(): VariableDefinitionNode {
  296. const start = this._lexer.token;
  297. return {
  298. kind: Kind.VARIABLE_DEFINITION,
  299. variable: this.parseVariable(),
  300. type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),
  301. defaultValue: this.expectOptionalToken(TokenKind.EQUALS)
  302. ? this.parseValueLiteral(true)
  303. : undefined,
  304. directives: this.parseDirectives(true),
  305. loc: this.loc(start),
  306. };
  307. }
  308. /**
  309. * Variable : $ Name
  310. */
  311. parseVariable(): VariableNode {
  312. const start = this._lexer.token;
  313. this.expectToken(TokenKind.DOLLAR);
  314. return {
  315. kind: Kind.VARIABLE,
  316. name: this.parseName(),
  317. loc: this.loc(start),
  318. };
  319. }
  320. /**
  321. * SelectionSet : { Selection+ }
  322. */
  323. parseSelectionSet(): SelectionSetNode {
  324. const start = this._lexer.token;
  325. return {
  326. kind: Kind.SELECTION_SET,
  327. selections: this.many(
  328. TokenKind.BRACE_L,
  329. this.parseSelection,
  330. TokenKind.BRACE_R,
  331. ),
  332. loc: this.loc(start),
  333. };
  334. }
  335. /**
  336. * Selection :
  337. * - Field
  338. * - FragmentSpread
  339. * - InlineFragment
  340. */
  341. parseSelection(): SelectionNode {
  342. return this.peek(TokenKind.SPREAD)
  343. ? this.parseFragment()
  344. : this.parseField();
  345. }
  346. /**
  347. * Field : Alias? Name Arguments? Directives? SelectionSet?
  348. *
  349. * Alias : Name :
  350. */
  351. parseField(): FieldNode {
  352. const start = this._lexer.token;
  353. const nameOrAlias = this.parseName();
  354. let alias;
  355. let name;
  356. if (this.expectOptionalToken(TokenKind.COLON)) {
  357. alias = nameOrAlias;
  358. name = this.parseName();
  359. } else {
  360. name = nameOrAlias;
  361. }
  362. return {
  363. kind: Kind.FIELD,
  364. alias,
  365. name,
  366. arguments: this.parseArguments(false),
  367. directives: this.parseDirectives(false),
  368. selectionSet: this.peek(TokenKind.BRACE_L)
  369. ? this.parseSelectionSet()
  370. : undefined,
  371. loc: this.loc(start),
  372. };
  373. }
  374. /**
  375. * Arguments[Const] : ( Argument[?Const]+ )
  376. */
  377. parseArguments(isConst: boolean): Array<ArgumentNode> {
  378. const item = isConst ? this.parseConstArgument : this.parseArgument;
  379. return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
  380. }
  381. /**
  382. * Argument[Const] : Name : Value[?Const]
  383. */
  384. parseArgument(): ArgumentNode {
  385. const start = this._lexer.token;
  386. const name = this.parseName();
  387. this.expectToken(TokenKind.COLON);
  388. return {
  389. kind: Kind.ARGUMENT,
  390. name,
  391. value: this.parseValueLiteral(false),
  392. loc: this.loc(start),
  393. };
  394. }
  395. parseConstArgument(): ArgumentNode {
  396. const start = this._lexer.token;
  397. return {
  398. kind: Kind.ARGUMENT,
  399. name: this.parseName(),
  400. value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)),
  401. loc: this.loc(start),
  402. };
  403. }
  404. // Implements the parsing rules in the Fragments section.
  405. /**
  406. * Corresponds to both FragmentSpread and InlineFragment in the spec.
  407. *
  408. * FragmentSpread : ... FragmentName Directives?
  409. *
  410. * InlineFragment : ... TypeCondition? Directives? SelectionSet
  411. */
  412. parseFragment(): FragmentSpreadNode | InlineFragmentNode {
  413. const start = this._lexer.token;
  414. this.expectToken(TokenKind.SPREAD);
  415. const hasTypeCondition = this.expectOptionalKeyword('on');
  416. if (!hasTypeCondition && this.peek(TokenKind.NAME)) {
  417. return {
  418. kind: Kind.FRAGMENT_SPREAD,
  419. name: this.parseFragmentName(),
  420. directives: this.parseDirectives(false),
  421. loc: this.loc(start),
  422. };
  423. }
  424. return {
  425. kind: Kind.INLINE_FRAGMENT,
  426. typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,
  427. directives: this.parseDirectives(false),
  428. selectionSet: this.parseSelectionSet(),
  429. loc: this.loc(start),
  430. };
  431. }
  432. /**
  433. * FragmentDefinition :
  434. * - fragment FragmentName on TypeCondition Directives? SelectionSet
  435. *
  436. * TypeCondition : NamedType
  437. */
  438. parseFragmentDefinition(): FragmentDefinitionNode {
  439. const start = this._lexer.token;
  440. this.expectKeyword('fragment');
  441. // Experimental support for defining variables within fragments changes
  442. // the grammar of FragmentDefinition:
  443. // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet
  444. if (this._options?.experimentalFragmentVariables === true) {
  445. return {
  446. kind: Kind.FRAGMENT_DEFINITION,
  447. name: this.parseFragmentName(),
  448. variableDefinitions: this.parseVariableDefinitions(),
  449. typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
  450. directives: this.parseDirectives(false),
  451. selectionSet: this.parseSelectionSet(),
  452. loc: this.loc(start),
  453. };
  454. }
  455. return {
  456. kind: Kind.FRAGMENT_DEFINITION,
  457. name: this.parseFragmentName(),
  458. typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
  459. directives: this.parseDirectives(false),
  460. selectionSet: this.parseSelectionSet(),
  461. loc: this.loc(start),
  462. };
  463. }
  464. /**
  465. * FragmentName : Name but not `on`
  466. */
  467. parseFragmentName(): NameNode {
  468. if (this._lexer.token.value === 'on') {
  469. throw this.unexpected();
  470. }
  471. return this.parseName();
  472. }
  473. // Implements the parsing rules in the Values section.
  474. /**
  475. * Value[Const] :
  476. * - [~Const] Variable
  477. * - IntValue
  478. * - FloatValue
  479. * - StringValue
  480. * - BooleanValue
  481. * - NullValue
  482. * - EnumValue
  483. * - ListValue[?Const]
  484. * - ObjectValue[?Const]
  485. *
  486. * BooleanValue : one of `true` `false`
  487. *
  488. * NullValue : `null`
  489. *
  490. * EnumValue : Name but not `true`, `false` or `null`
  491. */
  492. parseValueLiteral(isConst: boolean): ValueNode {
  493. const token = this._lexer.token;
  494. switch (token.kind) {
  495. case TokenKind.BRACKET_L:
  496. return this.parseList(isConst);
  497. case TokenKind.BRACE_L:
  498. return this.parseObject(isConst);
  499. case TokenKind.INT:
  500. this._lexer.advance();
  501. return {
  502. kind: Kind.INT,
  503. value: ((token.value: any): string),
  504. loc: this.loc(token),
  505. };
  506. case TokenKind.FLOAT:
  507. this._lexer.advance();
  508. return {
  509. kind: Kind.FLOAT,
  510. value: ((token.value: any): string),
  511. loc: this.loc(token),
  512. };
  513. case TokenKind.STRING:
  514. case TokenKind.BLOCK_STRING:
  515. return this.parseStringLiteral();
  516. case TokenKind.NAME:
  517. this._lexer.advance();
  518. switch (token.value) {
  519. case 'true':
  520. return { kind: Kind.BOOLEAN, value: true, loc: this.loc(token) };
  521. case 'false':
  522. return { kind: Kind.BOOLEAN, value: false, loc: this.loc(token) };
  523. case 'null':
  524. return { kind: Kind.NULL, loc: this.loc(token) };
  525. default:
  526. return {
  527. kind: Kind.ENUM,
  528. value: ((token.value: any): string),
  529. loc: this.loc(token),
  530. };
  531. }
  532. case TokenKind.DOLLAR:
  533. if (!isConst) {
  534. return this.parseVariable();
  535. }
  536. break;
  537. }
  538. throw this.unexpected();
  539. }
  540. parseStringLiteral(): StringValueNode {
  541. const token = this._lexer.token;
  542. this._lexer.advance();
  543. return {
  544. kind: Kind.STRING,
  545. value: ((token.value: any): string),
  546. block: token.kind === TokenKind.BLOCK_STRING,
  547. loc: this.loc(token),
  548. };
  549. }
  550. /**
  551. * ListValue[Const] :
  552. * - [ ]
  553. * - [ Value[?Const]+ ]
  554. */
  555. parseList(isConst: boolean): ListValueNode {
  556. const start = this._lexer.token;
  557. const item = () => this.parseValueLiteral(isConst);
  558. return {
  559. kind: Kind.LIST,
  560. values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),
  561. loc: this.loc(start),
  562. };
  563. }
  564. /**
  565. * ObjectValue[Const] :
  566. * - { }
  567. * - { ObjectField[?Const]+ }
  568. */
  569. parseObject(isConst: boolean): ObjectValueNode {
  570. const start = this._lexer.token;
  571. const item = () => this.parseObjectField(isConst);
  572. return {
  573. kind: Kind.OBJECT,
  574. fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),
  575. loc: this.loc(start),
  576. };
  577. }
  578. /**
  579. * ObjectField[Const] : Name : Value[?Const]
  580. */
  581. parseObjectField(isConst: boolean): ObjectFieldNode {
  582. const start = this._lexer.token;
  583. const name = this.parseName();
  584. this.expectToken(TokenKind.COLON);
  585. return {
  586. kind: Kind.OBJECT_FIELD,
  587. name,
  588. value: this.parseValueLiteral(isConst),
  589. loc: this.loc(start),
  590. };
  591. }
  592. // Implements the parsing rules in the Directives section.
  593. /**
  594. * Directives[Const] : Directive[?Const]+
  595. */
  596. parseDirectives(isConst: boolean): Array<DirectiveNode> {
  597. const directives = [];
  598. while (this.peek(TokenKind.AT)) {
  599. directives.push(this.parseDirective(isConst));
  600. }
  601. return directives;
  602. }
  603. /**
  604. * Directive[Const] : @ Name Arguments[?Const]?
  605. */
  606. parseDirective(isConst: boolean): DirectiveNode {
  607. const start = this._lexer.token;
  608. this.expectToken(TokenKind.AT);
  609. return {
  610. kind: Kind.DIRECTIVE,
  611. name: this.parseName(),
  612. arguments: this.parseArguments(isConst),
  613. loc: this.loc(start),
  614. };
  615. }
  616. // Implements the parsing rules in the Types section.
  617. /**
  618. * Type :
  619. * - NamedType
  620. * - ListType
  621. * - NonNullType
  622. */
  623. parseTypeReference(): TypeNode {
  624. const start = this._lexer.token;
  625. let type;
  626. if (this.expectOptionalToken(TokenKind.BRACKET_L)) {
  627. type = this.parseTypeReference();
  628. this.expectToken(TokenKind.BRACKET_R);
  629. type = {
  630. kind: Kind.LIST_TYPE,
  631. type,
  632. loc: this.loc(start),
  633. };
  634. } else {
  635. type = this.parseNamedType();
  636. }
  637. if (this.expectOptionalToken(TokenKind.BANG)) {
  638. return {
  639. kind: Kind.NON_NULL_TYPE,
  640. type,
  641. loc: this.loc(start),
  642. };
  643. }
  644. return type;
  645. }
  646. /**
  647. * NamedType : Name
  648. */
  649. parseNamedType(): NamedTypeNode {
  650. const start = this._lexer.token;
  651. return {
  652. kind: Kind.NAMED_TYPE,
  653. name: this.parseName(),
  654. loc: this.loc(start),
  655. };
  656. }
  657. // Implements the parsing rules in the Type Definition section.
  658. /**
  659. * TypeSystemDefinition :
  660. * - SchemaDefinition
  661. * - TypeDefinition
  662. * - DirectiveDefinition
  663. *
  664. * TypeDefinition :
  665. * - ScalarTypeDefinition
  666. * - ObjectTypeDefinition
  667. * - InterfaceTypeDefinition
  668. * - UnionTypeDefinition
  669. * - EnumTypeDefinition
  670. * - InputObjectTypeDefinition
  671. */
  672. parseTypeSystemDefinition(): TypeSystemDefinitionNode {
  673. // Many definitions begin with a description and require a lookahead.
  674. const keywordToken = this.peekDescription()
  675. ? this._lexer.lookahead()
  676. : this._lexer.token;
  677. if (keywordToken.kind === TokenKind.NAME) {
  678. switch (keywordToken.value) {
  679. case 'schema':
  680. return this.parseSchemaDefinition();
  681. case 'scalar':
  682. return this.parseScalarTypeDefinition();
  683. case 'type':
  684. return this.parseObjectTypeDefinition();
  685. case 'interface':
  686. return this.parseInterfaceTypeDefinition();
  687. case 'union':
  688. return this.parseUnionTypeDefinition();
  689. case 'enum':
  690. return this.parseEnumTypeDefinition();
  691. case 'input':
  692. return this.parseInputObjectTypeDefinition();
  693. case 'directive':
  694. return this.parseDirectiveDefinition();
  695. }
  696. }
  697. throw this.unexpected(keywordToken);
  698. }
  699. peekDescription(): boolean {
  700. return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);
  701. }
  702. /**
  703. * Description : StringValue
  704. */
  705. parseDescription(): void | StringValueNode {
  706. if (this.peekDescription()) {
  707. return this.parseStringLiteral();
  708. }
  709. }
  710. /**
  711. * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
  712. */
  713. parseSchemaDefinition(): SchemaDefinitionNode {
  714. const start = this._lexer.token;
  715. const description = this.parseDescription();
  716. this.expectKeyword('schema');
  717. const directives = this.parseDirectives(true);
  718. const operationTypes = this.many(
  719. TokenKind.BRACE_L,
  720. this.parseOperationTypeDefinition,
  721. TokenKind.BRACE_R,
  722. );
  723. return {
  724. kind: Kind.SCHEMA_DEFINITION,
  725. description,
  726. directives,
  727. operationTypes,
  728. loc: this.loc(start),
  729. };
  730. }
  731. /**
  732. * OperationTypeDefinition : OperationType : NamedType
  733. */
  734. parseOperationTypeDefinition(): OperationTypeDefinitionNode {
  735. const start = this._lexer.token;
  736. const operation = this.parseOperationType();
  737. this.expectToken(TokenKind.COLON);
  738. const type = this.parseNamedType();
  739. return {
  740. kind: Kind.OPERATION_TYPE_DEFINITION,
  741. operation,
  742. type,
  743. loc: this.loc(start),
  744. };
  745. }
  746. /**
  747. * ScalarTypeDefinition : Description? scalar Name Directives[Const]?
  748. */
  749. parseScalarTypeDefinition(): ScalarTypeDefinitionNode {
  750. const start = this._lexer.token;
  751. const description = this.parseDescription();
  752. this.expectKeyword('scalar');
  753. const name = this.parseName();
  754. const directives = this.parseDirectives(true);
  755. return {
  756. kind: Kind.SCALAR_TYPE_DEFINITION,
  757. description,
  758. name,
  759. directives,
  760. loc: this.loc(start),
  761. };
  762. }
  763. /**
  764. * ObjectTypeDefinition :
  765. * Description?
  766. * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
  767. */
  768. parseObjectTypeDefinition(): ObjectTypeDefinitionNode {
  769. const start = this._lexer.token;
  770. const description = this.parseDescription();
  771. this.expectKeyword('type');
  772. const name = this.parseName();
  773. const interfaces = this.parseImplementsInterfaces();
  774. const directives = this.parseDirectives(true);
  775. const fields = this.parseFieldsDefinition();
  776. return {
  777. kind: Kind.OBJECT_TYPE_DEFINITION,
  778. description,
  779. name,
  780. interfaces,
  781. directives,
  782. fields,
  783. loc: this.loc(start),
  784. };
  785. }
  786. /**
  787. * ImplementsInterfaces :
  788. * - implements `&`? NamedType
  789. * - ImplementsInterfaces & NamedType
  790. */
  791. parseImplementsInterfaces(): Array<NamedTypeNode> {
  792. const types = [];
  793. if (this.expectOptionalKeyword('implements')) {
  794. // Optional leading ampersand
  795. this.expectOptionalToken(TokenKind.AMP);
  796. do {
  797. types.push(this.parseNamedType());
  798. } while (
  799. this.expectOptionalToken(TokenKind.AMP) ||
  800. // Legacy support for the SDL?
  801. (this._options?.allowLegacySDLImplementsInterfaces === true &&
  802. this.peek(TokenKind.NAME))
  803. );
  804. }
  805. return types;
  806. }
  807. /**
  808. * FieldsDefinition : { FieldDefinition+ }
  809. */
  810. parseFieldsDefinition(): Array<FieldDefinitionNode> {
  811. // Legacy support for the SDL?
  812. if (
  813. this._options?.allowLegacySDLEmptyFields === true &&
  814. this.peek(TokenKind.BRACE_L) &&
  815. this._lexer.lookahead().kind === TokenKind.BRACE_R
  816. ) {
  817. this._lexer.advance();
  818. this._lexer.advance();
  819. return [];
  820. }
  821. return this.optionalMany(
  822. TokenKind.BRACE_L,
  823. this.parseFieldDefinition,
  824. TokenKind.BRACE_R,
  825. );
  826. }
  827. /**
  828. * FieldDefinition :
  829. * - Description? Name ArgumentsDefinition? : Type Directives[Const]?
  830. */
  831. parseFieldDefinition(): FieldDefinitionNode {
  832. const start = this._lexer.token;
  833. const description = this.parseDescription();
  834. const name = this.parseName();
  835. const args = this.parseArgumentDefs();
  836. this.expectToken(TokenKind.COLON);
  837. const type = this.parseTypeReference();
  838. const directives = this.parseDirectives(true);
  839. return {
  840. kind: Kind.FIELD_DEFINITION,
  841. description,
  842. name,
  843. arguments: args,
  844. type,
  845. directives,
  846. loc: this.loc(start),
  847. };
  848. }
  849. /**
  850. * ArgumentsDefinition : ( InputValueDefinition+ )
  851. */
  852. parseArgumentDefs(): Array<InputValueDefinitionNode> {
  853. return this.optionalMany(
  854. TokenKind.PAREN_L,
  855. this.parseInputValueDef,
  856. TokenKind.PAREN_R,
  857. );
  858. }
  859. /**
  860. * InputValueDefinition :
  861. * - Description? Name : Type DefaultValue? Directives[Const]?
  862. */
  863. parseInputValueDef(): InputValueDefinitionNode {
  864. const start = this._lexer.token;
  865. const description = this.parseDescription();
  866. const name = this.parseName();
  867. this.expectToken(TokenKind.COLON);
  868. const type = this.parseTypeReference();
  869. let defaultValue;
  870. if (this.expectOptionalToken(TokenKind.EQUALS)) {
  871. defaultValue = this.parseValueLiteral(true);
  872. }
  873. const directives = this.parseDirectives(true);
  874. return {
  875. kind: Kind.INPUT_VALUE_DEFINITION,
  876. description,
  877. name,
  878. type,
  879. defaultValue,
  880. directives,
  881. loc: this.loc(start),
  882. };
  883. }
  884. /**
  885. * InterfaceTypeDefinition :
  886. * - Description? interface Name Directives[Const]? FieldsDefinition?
  887. */
  888. parseInterfaceTypeDefinition(): InterfaceTypeDefinitionNode {
  889. const start = this._lexer.token;
  890. const description = this.parseDescription();
  891. this.expectKeyword('interface');
  892. const name = this.parseName();
  893. const interfaces = this.parseImplementsInterfaces();
  894. const directives = this.parseDirectives(true);
  895. const fields = this.parseFieldsDefinition();
  896. return {
  897. kind: Kind.INTERFACE_TYPE_DEFINITION,
  898. description,
  899. name,
  900. interfaces,
  901. directives,
  902. fields,
  903. loc: this.loc(start),
  904. };
  905. }
  906. /**
  907. * UnionTypeDefinition :
  908. * - Description? union Name Directives[Const]? UnionMemberTypes?
  909. */
  910. parseUnionTypeDefinition(): UnionTypeDefinitionNode {
  911. const start = this._lexer.token;
  912. const description = this.parseDescription();
  913. this.expectKeyword('union');
  914. const name = this.parseName();
  915. const directives = this.parseDirectives(true);
  916. const types = this.parseUnionMemberTypes();
  917. return {
  918. kind: Kind.UNION_TYPE_DEFINITION,
  919. description,
  920. name,
  921. directives,
  922. types,
  923. loc: this.loc(start),
  924. };
  925. }
  926. /**
  927. * UnionMemberTypes :
  928. * - = `|`? NamedType
  929. * - UnionMemberTypes | NamedType
  930. */
  931. parseUnionMemberTypes(): Array<NamedTypeNode> {
  932. const types = [];
  933. if (this.expectOptionalToken(TokenKind.EQUALS)) {
  934. // Optional leading pipe
  935. this.expectOptionalToken(TokenKind.PIPE);
  936. do {
  937. types.push(this.parseNamedType());
  938. } while (this.expectOptionalToken(TokenKind.PIPE));
  939. }
  940. return types;
  941. }
  942. /**
  943. * EnumTypeDefinition :
  944. * - Description? enum Name Directives[Const]? EnumValuesDefinition?
  945. */
  946. parseEnumTypeDefinition(): EnumTypeDefinitionNode {
  947. const start = this._lexer.token;
  948. const description = this.parseDescription();
  949. this.expectKeyword('enum');
  950. const name = this.parseName();
  951. const directives = this.parseDirectives(true);
  952. const values = this.parseEnumValuesDefinition();
  953. return {
  954. kind: Kind.ENUM_TYPE_DEFINITION,
  955. description,
  956. name,
  957. directives,
  958. values,
  959. loc: this.loc(start),
  960. };
  961. }
  962. /**
  963. * EnumValuesDefinition : { EnumValueDefinition+ }
  964. */
  965. parseEnumValuesDefinition(): Array<EnumValueDefinitionNode> {
  966. return this.optionalMany(
  967. TokenKind.BRACE_L,
  968. this.parseEnumValueDefinition,
  969. TokenKind.BRACE_R,
  970. );
  971. }
  972. /**
  973. * EnumValueDefinition : Description? EnumValue Directives[Const]?
  974. *
  975. * EnumValue : Name
  976. */
  977. parseEnumValueDefinition(): EnumValueDefinitionNode {
  978. const start = this._lexer.token;
  979. const description = this.parseDescription();
  980. const name = this.parseName();
  981. const directives = this.parseDirectives(true);
  982. return {
  983. kind: Kind.ENUM_VALUE_DEFINITION,
  984. description,
  985. name,
  986. directives,
  987. loc: this.loc(start),
  988. };
  989. }
  990. /**
  991. * InputObjectTypeDefinition :
  992. * - Description? input Name Directives[Const]? InputFieldsDefinition?
  993. */
  994. parseInputObjectTypeDefinition(): InputObjectTypeDefinitionNode {
  995. const start = this._lexer.token;
  996. const description = this.parseDescription();
  997. this.expectKeyword('input');
  998. const name = this.parseName();
  999. const directives = this.parseDirectives(true);
  1000. const fields = this.parseInputFieldsDefinition();
  1001. return {
  1002. kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
  1003. description,
  1004. name,
  1005. directives,
  1006. fields,
  1007. loc: this.loc(start),
  1008. };
  1009. }
  1010. /**
  1011. * InputFieldsDefinition : { InputValueDefinition+ }
  1012. */
  1013. parseInputFieldsDefinition(): Array<InputValueDefinitionNode> {
  1014. return this.optionalMany(
  1015. TokenKind.BRACE_L,
  1016. this.parseInputValueDef,
  1017. TokenKind.BRACE_R,
  1018. );
  1019. }
  1020. /**
  1021. * TypeSystemExtension :
  1022. * - SchemaExtension
  1023. * - TypeExtension
  1024. *
  1025. * TypeExtension :
  1026. * - ScalarTypeExtension
  1027. * - ObjectTypeExtension
  1028. * - InterfaceTypeExtension
  1029. * - UnionTypeExtension
  1030. * - EnumTypeExtension
  1031. * - InputObjectTypeDefinition
  1032. */
  1033. parseTypeSystemExtension(): TypeSystemExtensionNode {
  1034. const keywordToken = this._lexer.lookahead();
  1035. if (keywordToken.kind === TokenKind.NAME) {
  1036. switch (keywordToken.value) {
  1037. case 'schema':
  1038. return this.parseSchemaExtension();
  1039. case 'scalar':
  1040. return this.parseScalarTypeExtension();
  1041. case 'type':
  1042. return this.parseObjectTypeExtension();
  1043. case 'interface':
  1044. return this.parseInterfaceTypeExtension();
  1045. case 'union':
  1046. return this.parseUnionTypeExtension();
  1047. case 'enum':
  1048. return this.parseEnumTypeExtension();
  1049. case 'input':
  1050. return this.parseInputObjectTypeExtension();
  1051. }
  1052. }
  1053. throw this.unexpected(keywordToken);
  1054. }
  1055. /**
  1056. * SchemaExtension :
  1057. * - extend schema Directives[Const]? { OperationTypeDefinition+ }
  1058. * - extend schema Directives[Const]
  1059. */
  1060. parseSchemaExtension(): SchemaExtensionNode {
  1061. const start = this._lexer.token;
  1062. this.expectKeyword('extend');
  1063. this.expectKeyword('schema');
  1064. const directives = this.parseDirectives(true);
  1065. const operationTypes = this.optionalMany(
  1066. TokenKind.BRACE_L,
  1067. this.parseOperationTypeDefinition,
  1068. TokenKind.BRACE_R,
  1069. );
  1070. if (directives.length === 0 && operationTypes.length === 0) {
  1071. throw this.unexpected();
  1072. }
  1073. return {
  1074. kind: Kind.SCHEMA_EXTENSION,
  1075. directives,
  1076. operationTypes,
  1077. loc: this.loc(start),
  1078. };
  1079. }
  1080. /**
  1081. * ScalarTypeExtension :
  1082. * - extend scalar Name Directives[Const]
  1083. */
  1084. parseScalarTypeExtension(): ScalarTypeExtensionNode {
  1085. const start = this._lexer.token;
  1086. this.expectKeyword('extend');
  1087. this.expectKeyword('scalar');
  1088. const name = this.parseName();
  1089. const directives = this.parseDirectives(true);
  1090. if (directives.length === 0) {
  1091. throw this.unexpected();
  1092. }
  1093. return {
  1094. kind: Kind.SCALAR_TYPE_EXTENSION,
  1095. name,
  1096. directives,
  1097. loc: this.loc(start),
  1098. };
  1099. }
  1100. /**
  1101. * ObjectTypeExtension :
  1102. * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
  1103. * - extend type Name ImplementsInterfaces? Directives[Const]
  1104. * - extend type Name ImplementsInterfaces
  1105. */
  1106. parseObjectTypeExtension(): ObjectTypeExtensionNode {
  1107. const start = this._lexer.token;
  1108. this.expectKeyword('extend');
  1109. this.expectKeyword('type');
  1110. const name = this.parseName();
  1111. const interfaces = this.parseImplementsInterfaces();
  1112. const directives = this.parseDirectives(true);
  1113. const fields = this.parseFieldsDefinition();
  1114. if (
  1115. interfaces.length === 0 &&
  1116. directives.length === 0 &&
  1117. fields.length === 0
  1118. ) {
  1119. throw this.unexpected();
  1120. }
  1121. return {
  1122. kind: Kind.OBJECT_TYPE_EXTENSION,
  1123. name,
  1124. interfaces,
  1125. directives,
  1126. fields,
  1127. loc: this.loc(start),
  1128. };
  1129. }
  1130. /**
  1131. * InterfaceTypeExtension :
  1132. * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
  1133. * - extend interface Name ImplementsInterfaces? Directives[Const]
  1134. * - extend interface Name ImplementsInterfaces
  1135. */
  1136. parseInterfaceTypeExtension(): InterfaceTypeExtensionNode {
  1137. const start = this._lexer.token;
  1138. this.expectKeyword('extend');
  1139. this.expectKeyword('interface');
  1140. const name = this.parseName();
  1141. const interfaces = this.parseImplementsInterfaces();
  1142. const directives = this.parseDirectives(true);
  1143. const fields = this.parseFieldsDefinition();
  1144. if (
  1145. interfaces.length === 0 &&
  1146. directives.length === 0 &&
  1147. fields.length === 0
  1148. ) {
  1149. throw this.unexpected();
  1150. }
  1151. return {
  1152. kind: Kind.INTERFACE_TYPE_EXTENSION,
  1153. name,
  1154. interfaces,
  1155. directives,
  1156. fields,
  1157. loc: this.loc(start),
  1158. };
  1159. }
  1160. /**
  1161. * UnionTypeExtension :
  1162. * - extend union Name Directives[Const]? UnionMemberTypes
  1163. * - extend union Name Directives[Const]
  1164. */
  1165. parseUnionTypeExtension(): UnionTypeExtensionNode {
  1166. const start = this._lexer.token;
  1167. this.expectKeyword('extend');
  1168. this.expectKeyword('union');
  1169. const name = this.parseName();
  1170. const directives = this.parseDirectives(true);
  1171. const types = this.parseUnionMemberTypes();
  1172. if (directives.length === 0 && types.length === 0) {
  1173. throw this.unexpected();
  1174. }
  1175. return {
  1176. kind: Kind.UNION_TYPE_EXTENSION,
  1177. name,
  1178. directives,
  1179. types,
  1180. loc: this.loc(start),
  1181. };
  1182. }
  1183. /**
  1184. * EnumTypeExtension :
  1185. * - extend enum Name Directives[Const]? EnumValuesDefinition
  1186. * - extend enum Name Directives[Const]
  1187. */
  1188. parseEnumTypeExtension(): EnumTypeExtensionNode {
  1189. const start = this._lexer.token;
  1190. this.expectKeyword('extend');
  1191. this.expectKeyword('enum');
  1192. const name = this.parseName();
  1193. const directives = this.parseDirectives(true);
  1194. const values = this.parseEnumValuesDefinition();
  1195. if (directives.length === 0 && values.length === 0) {
  1196. throw this.unexpected();
  1197. }
  1198. return {
  1199. kind: Kind.ENUM_TYPE_EXTENSION,
  1200. name,
  1201. directives,
  1202. values,
  1203. loc: this.loc(start),
  1204. };
  1205. }
  1206. /**
  1207. * InputObjectTypeExtension :
  1208. * - extend input Name Directives[Const]? InputFieldsDefinition
  1209. * - extend input Name Directives[Const]
  1210. */
  1211. parseInputObjectTypeExtension(): InputObjectTypeExtensionNode {
  1212. const start = this._lexer.token;
  1213. this.expectKeyword('extend');
  1214. this.expectKeyword('input');
  1215. const name = this.parseName();
  1216. const directives = this.parseDirectives(true);
  1217. const fields = this.parseInputFieldsDefinition();
  1218. if (directives.length === 0 && fields.length === 0) {
  1219. throw this.unexpected();
  1220. }
  1221. return {
  1222. kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,
  1223. name,
  1224. directives,
  1225. fields,
  1226. loc: this.loc(start),
  1227. };
  1228. }
  1229. /**
  1230. * DirectiveDefinition :
  1231. * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
  1232. */
  1233. parseDirectiveDefinition(): DirectiveDefinitionNode {
  1234. const start = this._lexer.token;
  1235. const description = this.parseDescription();
  1236. this.expectKeyword('directive');
  1237. this.expectToken(TokenKind.AT);
  1238. const name = this.parseName();
  1239. const args = this.parseArgumentDefs();
  1240. const repeatable = this.expectOptionalKeyword('repeatable');
  1241. this.expectKeyword('on');
  1242. const locations = this.parseDirectiveLocations();
  1243. return {
  1244. kind: Kind.DIRECTIVE_DEFINITION,
  1245. description,
  1246. name,
  1247. arguments: args,
  1248. repeatable,
  1249. locations,
  1250. loc: this.loc(start),
  1251. };
  1252. }
  1253. /**
  1254. * DirectiveLocations :
  1255. * - `|`? DirectiveLocation
  1256. * - DirectiveLocations | DirectiveLocation
  1257. */
  1258. parseDirectiveLocations(): Array<NameNode> {
  1259. // Optional leading pipe
  1260. this.expectOptionalToken(TokenKind.PIPE);
  1261. const locations = [];
  1262. do {
  1263. locations.push(this.parseDirectiveLocation());
  1264. } while (this.expectOptionalToken(TokenKind.PIPE));
  1265. return locations;
  1266. }
  1267. /*
  1268. * DirectiveLocation :
  1269. * - ExecutableDirectiveLocation
  1270. * - TypeSystemDirectiveLocation
  1271. *
  1272. * ExecutableDirectiveLocation : one of
  1273. * `QUERY`
  1274. * `MUTATION`
  1275. * `SUBSCRIPTION`
  1276. * `FIELD`
  1277. * `FRAGMENT_DEFINITION`
  1278. * `FRAGMENT_SPREAD`
  1279. * `INLINE_FRAGMENT`
  1280. *
  1281. * TypeSystemDirectiveLocation : one of
  1282. * `SCHEMA`
  1283. * `SCALAR`
  1284. * `OBJECT`
  1285. * `FIELD_DEFINITION`
  1286. * `ARGUMENT_DEFINITION`
  1287. * `INTERFACE`
  1288. * `UNION`
  1289. * `ENUM`
  1290. * `ENUM_VALUE`
  1291. * `INPUT_OBJECT`
  1292. * `INPUT_FIELD_DEFINITION`
  1293. */
  1294. parseDirectiveLocation(): NameNode {
  1295. const start = this._lexer.token;
  1296. const name = this.parseName();
  1297. if (DirectiveLocation[name.value] !== undefined) {
  1298. return name;
  1299. }
  1300. throw this.unexpected(start);
  1301. }
  1302. // Core parsing utility functions
  1303. /**
  1304. * Returns a location object, used to identify the place in
  1305. * the source that created a given parsed object.
  1306. */
  1307. loc(startToken: Token): Location | void {
  1308. if (this._options?.noLocation !== true) {
  1309. return new Location(
  1310. startToken,
  1311. this._lexer.lastToken,
  1312. this._lexer.source,
  1313. );
  1314. }
  1315. }
  1316. /**
  1317. * Determines if the next token is of a given kind
  1318. */
  1319. peek(kind: TokenKindEnum): boolean {
  1320. return this._lexer.token.kind === kind;
  1321. }
  1322. /**
  1323. * If the next token is of the given kind, return that token after advancing
  1324. * the lexer. Otherwise, do not change the parser state and throw an error.
  1325. */
  1326. expectToken(kind: TokenKindEnum): Token {
  1327. const token = this._lexer.token;
  1328. if (token.kind === kind) {
  1329. this._lexer.advance();
  1330. return token;
  1331. }
  1332. throw syntaxError(
  1333. this._lexer.source,
  1334. token.start,
  1335. `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`,
  1336. );
  1337. }
  1338. /**
  1339. * If the next token is of the given kind, return that token after advancing
  1340. * the lexer. Otherwise, do not change the parser state and return undefined.
  1341. */
  1342. expectOptionalToken(kind: TokenKindEnum): ?Token {
  1343. const token = this._lexer.token;
  1344. if (token.kind === kind) {
  1345. this._lexer.advance();
  1346. return token;
  1347. }
  1348. return undefined;
  1349. }
  1350. /**
  1351. * If the next token is a given keyword, advance the lexer.
  1352. * Otherwise, do not change the parser state and throw an error.
  1353. */
  1354. expectKeyword(value: string) {
  1355. const token = this._lexer.token;
  1356. if (token.kind === TokenKind.NAME && token.value === value) {
  1357. this._lexer.advance();
  1358. } else {
  1359. throw syntaxError(
  1360. this._lexer.source,
  1361. token.start,
  1362. `Expected "${value}", found ${getTokenDesc(token)}.`,
  1363. );
  1364. }
  1365. }
  1366. /**
  1367. * If the next token is a given keyword, return "true" after advancing
  1368. * the lexer. Otherwise, do not change the parser state and return "false".
  1369. */
  1370. expectOptionalKeyword(value: string): boolean {
  1371. const token = this._lexer.token;
  1372. if (token.kind === TokenKind.NAME && token.value === value) {
  1373. this._lexer.advance();
  1374. return true;
  1375. }
  1376. return false;
  1377. }
  1378. /**
  1379. * Helper function for creating an error when an unexpected lexed token
  1380. * is encountered.
  1381. */
  1382. unexpected(atToken?: ?Token): GraphQLError {
  1383. const token = atToken ?? this._lexer.token;
  1384. return syntaxError(
  1385. this._lexer.source,
  1386. token.start,
  1387. `Unexpected ${getTokenDesc(token)}.`,
  1388. );
  1389. }
  1390. /**
  1391. * Returns a possibly empty list of parse nodes, determined by
  1392. * the parseFn. This list begins with a lex token of openKind
  1393. * and ends with a lex token of closeKind. Advances the parser
  1394. * to the next lex token after the closing token.
  1395. */
  1396. any<T>(
  1397. openKind: TokenKindEnum,
  1398. parseFn: () => T,
  1399. closeKind: TokenKindEnum,
  1400. ): Array<T> {
  1401. this.expectToken(openKind);
  1402. const nodes = [];
  1403. while (!this.expectOptionalToken(closeKind)) {
  1404. nodes.push(parseFn.call(this));
  1405. }
  1406. return nodes;
  1407. }
  1408. /**
  1409. * Returns a list of parse nodes, determined by the parseFn.
  1410. * It can be empty only if open token is missing otherwise it will always
  1411. * return non-empty list that begins with a lex token of openKind and ends
  1412. * with a lex token of closeKind. Advances the parser to the next lex token
  1413. * after the closing token.
  1414. */
  1415. optionalMany<T>(
  1416. openKind: TokenKindEnum,
  1417. parseFn: () => T,
  1418. closeKind: TokenKindEnum,
  1419. ): Array<T> {
  1420. if (this.expectOptionalToken(openKind)) {
  1421. const nodes = [];
  1422. do {
  1423. nodes.push(parseFn.call(this));
  1424. } while (!this.expectOptionalToken(closeKind));
  1425. return nodes;
  1426. }
  1427. return [];
  1428. }
  1429. /**
  1430. * Returns a non-empty list of parse nodes, determined by
  1431. * the parseFn. This list begins with a lex token of openKind
  1432. * and ends with a lex token of closeKind. Advances the parser
  1433. * to the next lex token after the closing token.
  1434. */
  1435. many<T>(
  1436. openKind: TokenKindEnum,
  1437. parseFn: () => T,
  1438. closeKind: TokenKindEnum,
  1439. ): Array<T> {
  1440. this.expectToken(openKind);
  1441. const nodes = [];
  1442. do {
  1443. nodes.push(parseFn.call(this));
  1444. } while (!this.expectOptionalToken(closeKind));
  1445. return nodes;
  1446. }
  1447. }
  1448. /**
  1449. * A helper function to describe a token as a string for debugging
  1450. */
  1451. function getTokenDesc(token: Token): string {
  1452. const value = token.value;
  1453. return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : '');
  1454. }
  1455. /**
  1456. * A helper function to describe a token kind as a string for debugging
  1457. */
  1458. function getTokenKindDesc(kind: TokenKindEnum): string {
  1459. return isPunctuatorTokenKind(kind) ? `"${kind}"` : kind;
  1460. }