-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathparser.ts
1639 lines (1525 loc) · 45.3 KB
/
parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Maybe } from '../jsutils/Maybe.js';
import type { GraphQLError } from '../error/GraphQLError.js';
import { syntaxError } from '../error/syntaxError.js';
import type {
ArgumentNode,
BooleanValueNode,
ConstArgumentNode,
ConstDirectiveNode,
ConstListValueNode,
ConstObjectFieldNode,
ConstObjectValueNode,
ConstValueNode,
DefinitionNode,
DirectiveDefinitionNode,
DirectiveNode,
DocumentNode,
EnumTypeDefinitionNode,
EnumTypeExtensionNode,
EnumValueDefinitionNode,
EnumValueNode,
FieldDefinitionNode,
FieldNode,
FloatValueNode,
FragmentArgumentNode,
FragmentDefinitionNode,
FragmentSpreadNode,
InlineFragmentNode,
InputObjectTypeDefinitionNode,
InputObjectTypeExtensionNode,
InputValueDefinitionNode,
InterfaceTypeDefinitionNode,
InterfaceTypeExtensionNode,
IntValueNode,
ListTypeNode,
ListValueNode,
NamedTypeNode,
NameNode,
NonNullTypeNode,
NullValueNode,
ObjectFieldNode,
ObjectTypeDefinitionNode,
ObjectTypeExtensionNode,
ObjectValueNode,
OperationDefinitionNode,
OperationTypeDefinitionNode,
ScalarTypeDefinitionNode,
ScalarTypeExtensionNode,
SchemaDefinitionNode,
SchemaExtensionNode,
SelectionNode,
SelectionSetNode,
StringValueNode,
Token,
TypeNode,
TypeSystemExtensionNode,
UnionTypeDefinitionNode,
UnionTypeExtensionNode,
ValueNode,
VariableDefinitionNode,
VariableNode,
} from './ast.js';
import { Location, OperationTypeNode } from './ast.js';
import { DirectiveLocation } from './directiveLocation.js';
import { Kind } from './kinds.js';
import { isPunctuatorTokenKind, Lexer } from './lexer.js';
import { isSource, Source } from './source.js';
import { TokenKind } from './tokenKind.js';
/**
* Configuration options to control parser behavior
*/
export interface ParseOptions {
/**
* By default, the parser creates AST nodes that know the location
* in the source that they correspond to. This configuration flag
* disables that behavior for performance or testing.
*/
noLocation?: boolean | undefined;
/**
* Parser CPU and memory usage is linear to the number of tokens in a document
* however in extreme cases it becomes quadratic due to memory exhaustion.
* Parsing happens before validation so even invalid queries can burn lots of
* CPU time and memory.
* To prevent this you can set a maximum number of tokens allowed within a document.
*/
maxTokens?: number | undefined;
/**
* EXPERIMENTAL:
*
* If enabled, the parser will understand and parse fragment variable definitions
* and arguments on fragment spreads. Fragment variable definitions will be represented
* in the `variableDefinitions` field of the FragmentDefinitionNode.
* Fragment spread arguments will be represented in the `arguments` field of FragmentSpreadNode.
*
* For example:
*
* ```graphql
* {
* t { ...A(var: true) }
* }
* fragment A($var: Boolean = false) on T {
* ...B(x: $var)
* }
* ```
*/
experimentalFragmentArguments?: boolean | undefined;
}
/**
* Given a GraphQL source, parses it into a Document.
* Throws GraphQLError if a syntax error is encountered.
*/
export function parse(
source: string | Source,
options?: ParseOptions,
): DocumentNode {
const parser = new Parser(source, options);
const document = parser.parseDocument();
Object.defineProperty(document, 'tokenCount', {
enumerable: false,
value: parser.tokenCount,
});
return document;
}
/**
* Given a string containing a GraphQL value (ex. `[42]`), parse the AST for
* that value.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Values directly and
* in isolation of complete GraphQL documents.
*/
export function parseValue(
source: string | Source,
options?: ParseOptions,
): ValueNode {
const parser = new Parser(source, options);
parser.expectToken(TokenKind.SOF);
const value = parser.parseValueLiteral(false);
parser.expectToken(TokenKind.EOF);
return value;
}
/**
* Similar to parseValue(), but raises a parse error if it encounters a
* variable. The return type will be a constant value.
*/
export function parseConstValue(
source: string | Source,
options?: ParseOptions,
): ConstValueNode {
const parser = new Parser(source, options);
parser.expectToken(TokenKind.SOF);
const value = parser.parseConstValueLiteral();
parser.expectToken(TokenKind.EOF);
return value;
}
/**
* Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for
* that type.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Types directly and
* in isolation of complete GraphQL documents.
*
* Consider providing the results to the utility function: typeFromAST().
*/
export function parseType(
source: string | Source,
options?: ParseOptions,
): TypeNode {
const parser = new Parser(source, options);
parser.expectToken(TokenKind.SOF);
const type = parser.parseTypeReference();
parser.expectToken(TokenKind.EOF);
return type;
}
/**
* This class is exported only to assist people in implementing their own parsers
* without duplicating too much code and should be used only as last resort for cases
* such as experimental syntax or if certain features could not be contributed upstream.
*
* It is still part of the internal API and is versioned, so any changes to it are never
* considered breaking changes. If you still need to support multiple versions of the
* library, please use the `versionInfo` variable for version detection.
*
* @internal
*/
export class Parser {
protected _options: ParseOptions;
protected _lexer: Lexer;
protected _tokenCounter: number;
constructor(source: string | Source, options: ParseOptions = {}) {
const sourceObj = isSource(source) ? source : new Source(source);
this._lexer = new Lexer(sourceObj);
this._options = options;
this._tokenCounter = 0;
}
get tokenCount(): number {
return this._tokenCounter;
}
/**
* Converts a name lex token into a name parse node.
*/
parseName(): NameNode {
const token = this.expectToken(TokenKind.NAME);
return this.node<NameNode>(token, {
kind: Kind.NAME,
value: token.value,
});
}
// Implements the parsing rules in the Document section.
/**
* Document : Definition+
*/
parseDocument(): DocumentNode {
return this.node<DocumentNode>(this._lexer.token, {
kind: Kind.DOCUMENT,
definitions: this.many(
TokenKind.SOF,
this.parseDefinition,
TokenKind.EOF,
),
});
}
/**
* Definition :
* - ExecutableDefinition
* - TypeSystemDefinition
* - TypeSystemExtension
*
* ExecutableDefinition :
* - OperationDefinition
* - FragmentDefinition
*
* TypeSystemDefinition :
* - SchemaDefinition
* - TypeDefinition
* - DirectiveDefinition
*
* TypeDefinition :
* - ScalarTypeDefinition
* - ObjectTypeDefinition
* - InterfaceTypeDefinition
* - UnionTypeDefinition
* - EnumTypeDefinition
* - InputObjectTypeDefinition
*/
parseDefinition(): DefinitionNode {
if (this.peek(TokenKind.BRACE_L)) {
return this.parseOperationDefinition();
}
// Many definitions begin with a description and require a lookahead.
const hasDescription = this.peekDescription();
const keywordToken = hasDescription
? this._lexer.lookahead()
: this._lexer.token;
if (keywordToken.kind === TokenKind.NAME) {
switch (keywordToken.value) {
case 'schema':
return this.parseSchemaDefinition();
case 'scalar':
return this.parseScalarTypeDefinition();
case 'type':
return this.parseObjectTypeDefinition();
case 'interface':
return this.parseInterfaceTypeDefinition();
case 'union':
return this.parseUnionTypeDefinition();
case 'enum':
return this.parseEnumTypeDefinition();
case 'input':
return this.parseInputObjectTypeDefinition();
case 'directive':
return this.parseDirectiveDefinition();
}
if (hasDescription) {
throw syntaxError(
this._lexer.source,
this._lexer.token.start,
'Unexpected description, descriptions are supported only on type definitions.',
);
}
switch (keywordToken.value) {
case 'query':
case 'mutation':
case 'subscription':
return this.parseOperationDefinition();
case 'fragment':
return this.parseFragmentDefinition();
case 'extend':
return this.parseTypeSystemExtension();
}
}
throw this.unexpected(keywordToken);
}
// Implements the parsing rules in the Operations section.
/**
* OperationDefinition :
* - SelectionSet
* - OperationType Name? VariableDefinitions? Directives? SelectionSet
*/
parseOperationDefinition(): OperationDefinitionNode {
const start = this._lexer.token;
if (this.peek(TokenKind.BRACE_L)) {
return this.node<OperationDefinitionNode>(start, {
kind: Kind.OPERATION_DEFINITION,
operation: OperationTypeNode.QUERY,
name: undefined,
variableDefinitions: undefined,
directives: undefined,
selectionSet: this.parseSelectionSet(),
});
}
const operation = this.parseOperationType();
let name;
if (this.peek(TokenKind.NAME)) {
name = this.parseName();
}
return this.node<OperationDefinitionNode>(start, {
kind: Kind.OPERATION_DEFINITION,
operation,
name,
variableDefinitions: this.parseVariableDefinitions(),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
});
}
/**
* OperationType : one of query mutation subscription
*/
parseOperationType(): OperationTypeNode {
const operationToken = this.expectToken(TokenKind.NAME);
switch (operationToken.value) {
case 'query':
return OperationTypeNode.QUERY;
case 'mutation':
return OperationTypeNode.MUTATION;
case 'subscription':
return OperationTypeNode.SUBSCRIPTION;
}
throw this.unexpected(operationToken);
}
/**
* VariableDefinitions : ( VariableDefinition+ )
*/
parseVariableDefinitions(): Array<VariableDefinitionNode> | undefined {
return this.optionalMany(
TokenKind.PAREN_L,
this.parseVariableDefinition,
TokenKind.PAREN_R,
);
}
/**
* VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
*/
parseVariableDefinition(): VariableDefinitionNode {
return this.node<VariableDefinitionNode>(this._lexer.token, {
kind: Kind.VARIABLE_DEFINITION,
variable: this.parseVariable(),
type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),
defaultValue: this.expectOptionalToken(TokenKind.EQUALS)
? this.parseConstValueLiteral()
: undefined,
directives: this.parseConstDirectives(),
});
}
/**
* Variable : $ Name
*/
parseVariable(): VariableNode {
const start = this._lexer.token;
this.expectToken(TokenKind.DOLLAR);
return this.node<VariableNode>(start, {
kind: Kind.VARIABLE,
name: this.parseName(),
});
}
/**
* ```
* SelectionSet : { Selection+ }
* ```
*/
parseSelectionSet(): SelectionSetNode {
return this.node<SelectionSetNode>(this._lexer.token, {
kind: Kind.SELECTION_SET,
selections: this.many(
TokenKind.BRACE_L,
this.parseSelection,
TokenKind.BRACE_R,
),
});
}
/**
* Selection :
* - Field
* - FragmentSpread
* - InlineFragment
*/
parseSelection(): SelectionNode {
return this.peek(TokenKind.SPREAD)
? this.parseFragment()
: this.parseField();
}
/**
* Field : Alias? Name Arguments? Directives? SelectionSet?
*
* Alias : Name :
*/
parseField(): FieldNode {
const start = this._lexer.token;
const nameOrAlias = this.parseName();
let alias;
let name;
if (this.expectOptionalToken(TokenKind.COLON)) {
alias = nameOrAlias;
name = this.parseName();
} else {
name = nameOrAlias;
}
return this.node<FieldNode>(start, {
kind: Kind.FIELD,
alias,
name,
arguments: this.parseArguments(false),
directives: this.parseDirectives(false),
selectionSet: this.peek(TokenKind.BRACE_L)
? this.parseSelectionSet()
: undefined,
});
}
/**
* Arguments[Const] : ( Argument[?Const]+ )
*/
parseArguments(isConst: true): Array<ConstArgumentNode> | undefined;
parseArguments(isConst: boolean): Array<ArgumentNode> | undefined;
parseArguments(isConst: boolean): Array<ArgumentNode> | undefined {
const item = isConst ? this.parseConstArgument : this.parseArgument;
return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
}
/* experimental */
parseFragmentArguments(): Array<FragmentArgumentNode> | undefined {
const item = this.parseFragmentArgument;
return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
}
/**
* Argument[Const] : Name : Value[?Const]
*/
parseArgument(isConst: true): ConstArgumentNode;
parseArgument(isConst?: boolean): ArgumentNode;
parseArgument(isConst: boolean = false): ArgumentNode {
const start = this._lexer.token;
const name = this.parseName();
this.expectToken(TokenKind.COLON);
return this.node<ArgumentNode>(start, {
kind: Kind.ARGUMENT,
name,
value: this.parseValueLiteral(isConst),
});
}
parseConstArgument(): ConstArgumentNode {
return this.parseArgument(true);
}
/* experimental */
parseFragmentArgument(): FragmentArgumentNode {
const start = this._lexer.token;
const name = this.parseName();
this.expectToken(TokenKind.COLON);
return this.node<FragmentArgumentNode>(start, {
kind: Kind.FRAGMENT_ARGUMENT,
name,
value: this.parseValueLiteral(false),
});
}
// Implements the parsing rules in the Fragments section.
/**
* Corresponds to both FragmentSpread and InlineFragment in the spec.
*
* FragmentSpread : ... FragmentName Arguments? Directives?
*
* InlineFragment : ... TypeCondition? Directives? SelectionSet
*/
parseFragment(): FragmentSpreadNode | InlineFragmentNode {
const start = this._lexer.token;
this.expectToken(TokenKind.SPREAD);
const hasTypeCondition = this.expectOptionalKeyword('on');
if (!hasTypeCondition && this.peek(TokenKind.NAME)) {
const name = this.parseFragmentName();
if (
this.peek(TokenKind.PAREN_L) &&
this._options.experimentalFragmentArguments
) {
return this.node<FragmentSpreadNode>(start, {
kind: Kind.FRAGMENT_SPREAD,
name,
arguments: this.parseFragmentArguments(),
directives: this.parseDirectives(false),
});
}
return this.node<FragmentSpreadNode>(start, {
kind: Kind.FRAGMENT_SPREAD,
name,
directives: this.parseDirectives(false),
});
}
return this.node<InlineFragmentNode>(start, {
kind: Kind.INLINE_FRAGMENT,
typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
});
}
/**
* FragmentDefinition :
* - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet
*
* TypeCondition : NamedType
*/
parseFragmentDefinition(): FragmentDefinitionNode {
const start = this._lexer.token;
this.expectKeyword('fragment');
if (this._options.experimentalFragmentArguments === true) {
return this.node<FragmentDefinitionNode>(start, {
kind: Kind.FRAGMENT_DEFINITION,
name: this.parseFragmentName(),
variableDefinitions: this.parseVariableDefinitions(),
typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
});
}
return this.node<FragmentDefinitionNode>(start, {
kind: Kind.FRAGMENT_DEFINITION,
name: this.parseFragmentName(),
typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
});
}
/**
* FragmentName : Name but not `on`
*/
parseFragmentName(): NameNode {
if (this._lexer.token.value === 'on') {
throw this.unexpected();
}
return this.parseName();
}
// Implements the parsing rules in the Values section.
/**
* Value[Const] :
* - [~Const] Variable
* - IntValue
* - FloatValue
* - StringValue
* - BooleanValue
* - NullValue
* - EnumValue
* - ListValue[?Const]
* - ObjectValue[?Const]
*
* BooleanValue : one of `true` `false`
*
* NullValue : `null`
*
* EnumValue : Name but not `true`, `false` or `null`
*/
parseValueLiteral(isConst: true): ConstValueNode;
parseValueLiteral(isConst: boolean): ValueNode;
parseValueLiteral(isConst: boolean): ValueNode {
const token = this._lexer.token;
switch (token.kind) {
case TokenKind.BRACKET_L:
return this.parseList(isConst);
case TokenKind.BRACE_L:
return this.parseObject(isConst);
case TokenKind.INT:
this.advanceLexer();
return this.node<IntValueNode>(token, {
kind: Kind.INT,
value: token.value,
});
case TokenKind.FLOAT:
this.advanceLexer();
return this.node<FloatValueNode>(token, {
kind: Kind.FLOAT,
value: token.value,
});
case TokenKind.STRING:
case TokenKind.BLOCK_STRING:
return this.parseStringLiteral();
case TokenKind.NAME:
this.advanceLexer();
switch (token.value) {
case 'true':
return this.node<BooleanValueNode>(token, {
kind: Kind.BOOLEAN,
value: true,
});
case 'false':
return this.node<BooleanValueNode>(token, {
kind: Kind.BOOLEAN,
value: false,
});
case 'null':
return this.node<NullValueNode>(token, { kind: Kind.NULL });
default:
return this.node<EnumValueNode>(token, {
kind: Kind.ENUM,
value: token.value,
});
}
case TokenKind.DOLLAR:
if (isConst) {
this.expectToken(TokenKind.DOLLAR);
if (this._lexer.token.kind === TokenKind.NAME) {
const varName = this._lexer.token.value;
throw syntaxError(
this._lexer.source,
token.start,
`Unexpected variable "$${varName}" in constant value.`,
);
} else {
throw this.unexpected(token);
}
}
return this.parseVariable();
default:
throw this.unexpected();
}
}
parseConstValueLiteral(): ConstValueNode {
return this.parseValueLiteral(true);
}
parseStringLiteral(): StringValueNode {
const token = this._lexer.token;
this.advanceLexer();
return this.node<StringValueNode>(token, {
kind: Kind.STRING,
value: token.value,
block: token.kind === TokenKind.BLOCK_STRING,
});
}
/**
* ListValue[Const] :
* - [ ]
* - [ Value[?Const]+ ]
*/
parseList(isConst: true): ConstListValueNode;
parseList(isConst: boolean): ListValueNode;
parseList(isConst: boolean): ListValueNode {
const item = () => this.parseValueLiteral(isConst);
return this.node<ListValueNode>(this._lexer.token, {
kind: Kind.LIST,
values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),
});
}
/**
* ```
* ObjectValue[Const] :
* - { }
* - { ObjectField[?Const]+ }
* ```
*/
parseObject(isConst: true): ConstObjectValueNode;
parseObject(isConst: boolean): ObjectValueNode;
parseObject(isConst: boolean): ObjectValueNode {
const item = () => this.parseObjectField(isConst);
return this.node<ObjectValueNode>(this._lexer.token, {
kind: Kind.OBJECT,
fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),
});
}
/**
* ObjectField[Const] : Name : Value[?Const]
*/
parseObjectField(isConst: true): ConstObjectFieldNode;
parseObjectField(isConst: boolean): ObjectFieldNode;
parseObjectField(isConst: boolean): ObjectFieldNode {
const start = this._lexer.token;
const name = this.parseName();
this.expectToken(TokenKind.COLON);
return this.node<ObjectFieldNode>(start, {
kind: Kind.OBJECT_FIELD,
name,
value: this.parseValueLiteral(isConst),
});
}
// Implements the parsing rules in the Directives section.
/**
* Directives[Const] : Directive[?Const]+
*/
parseDirectives(isConst: true): Array<ConstDirectiveNode> | undefined;
parseDirectives(isConst: boolean): Array<DirectiveNode> | undefined;
parseDirectives(isConst: boolean): Array<DirectiveNode> | undefined {
const directives = [];
while (this.peek(TokenKind.AT)) {
directives.push(this.parseDirective(isConst));
}
if (directives.length) {
return directives;
}
return undefined;
}
parseConstDirectives(): Array<ConstDirectiveNode> | undefined {
return this.parseDirectives(true);
}
/**
* ```
* Directive[Const] : @ Name Arguments[?Const]?
* ```
*/
parseDirective(isConst: true): ConstDirectiveNode;
parseDirective(isConst: boolean): DirectiveNode;
parseDirective(isConst: boolean): DirectiveNode {
const start = this._lexer.token;
this.expectToken(TokenKind.AT);
return this.node<DirectiveNode>(start, {
kind: Kind.DIRECTIVE,
name: this.parseName(),
arguments: this.parseArguments(isConst),
});
}
// Implements the parsing rules in the Types section.
/**
* Type :
* - NamedType
* - ListType
* - NonNullType
*/
parseTypeReference(): TypeNode {
const start = this._lexer.token;
let type;
if (this.expectOptionalToken(TokenKind.BRACKET_L)) {
const innerType = this.parseTypeReference();
this.expectToken(TokenKind.BRACKET_R);
type = this.node<ListTypeNode>(start, {
kind: Kind.LIST_TYPE,
type: innerType,
});
} else {
type = this.parseNamedType();
}
if (this.expectOptionalToken(TokenKind.BANG)) {
return this.node<NonNullTypeNode>(start, {
kind: Kind.NON_NULL_TYPE,
type,
});
}
return type;
}
/**
* NamedType : Name
*/
parseNamedType(): NamedTypeNode {
return this.node<NamedTypeNode>(this._lexer.token, {
kind: Kind.NAMED_TYPE,
name: this.parseName(),
});
}
// Implements the parsing rules in the Type Definition section.
peekDescription(): boolean {
return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);
}
/**
* Description : StringValue
*/
parseDescription(): undefined | StringValueNode {
if (this.peekDescription()) {
return this.parseStringLiteral();
}
}
/**
* ```
* SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
* ```
*/
parseSchemaDefinition(): SchemaDefinitionNode {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword('schema');
const directives = this.parseConstDirectives();
const operationTypes = this.many(
TokenKind.BRACE_L,
this.parseOperationTypeDefinition,
TokenKind.BRACE_R,
);
return this.node<SchemaDefinitionNode>(start, {
kind: Kind.SCHEMA_DEFINITION,
description,
directives,
operationTypes,
});
}
/**
* OperationTypeDefinition : OperationType : NamedType
*/
parseOperationTypeDefinition(): OperationTypeDefinitionNode {
const start = this._lexer.token;
const operation = this.parseOperationType();
this.expectToken(TokenKind.COLON);
const type = this.parseNamedType();
return this.node<OperationTypeDefinitionNode>(start, {
kind: Kind.OPERATION_TYPE_DEFINITION,
operation,
type,
});
}
/**
* ScalarTypeDefinition : Description? scalar Name Directives[Const]?
*/
parseScalarTypeDefinition(): ScalarTypeDefinitionNode {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword('scalar');
const name = this.parseName();
const directives = this.parseConstDirectives();
return this.node<ScalarTypeDefinitionNode>(start, {
kind: Kind.SCALAR_TYPE_DEFINITION,
description,
name,
directives,
});
}
/**
* ObjectTypeDefinition :
* Description?
* type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
*/
parseObjectTypeDefinition(): ObjectTypeDefinitionNode {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword('type');
const name = this.parseName();
const interfaces = this.parseImplementsInterfaces();
const directives = this.parseConstDirectives();
const fields = this.parseFieldsDefinition();
return this.node<ObjectTypeDefinitionNode>(start, {
kind: Kind.OBJECT_TYPE_DEFINITION,
description,
name,
interfaces,
directives,
fields,
});
}
/**
* ImplementsInterfaces :
* - implements `&`? NamedType
* - ImplementsInterfaces & NamedType
*/
parseImplementsInterfaces(): Array<NamedTypeNode> | undefined {
return this.expectOptionalKeyword('implements')
? this.delimitedMany(TokenKind.AMP, this.parseNamedType)
: undefined;
}
/**
* ```
* FieldsDefinition : { FieldDefinition+ }
* ```
*/
parseFieldsDefinition(): Array<FieldDefinitionNode> | undefined {
return this.optionalMany(
TokenKind.BRACE_L,
this.parseFieldDefinition,
TokenKind.BRACE_R,
);
}
/**
* FieldDefinition :
* - Description? Name ArgumentsDefinition? : Type Directives[Const]?
*/
parseFieldDefinition(): FieldDefinitionNode {
const start = this._lexer.token;
const description = this.parseDescription();
const name = this.parseName();
const args = this.parseArgumentDefs();
this.expectToken(TokenKind.COLON);
const type = this.parseTypeReference();
const directives = this.parseConstDirectives();
return this.node<FieldDefinitionNode>(start, {
kind: Kind.FIELD_DEFINITION,
description,
name,
arguments: args,
type,
directives,
});
}
/**
* ArgumentsDefinition : ( InputValueDefinition+ )
*/
parseArgumentDefs(): Array<InputValueDefinitionNode> | undefined {
return this.optionalMany(
TokenKind.PAREN_L,
this.parseInputValueDef,
TokenKind.PAREN_R,
);
}
/**
* InputValueDefinition :
* - Description? Name : Type DefaultValue? Directives[Const]?
*/
parseInputValueDef(): InputValueDefinitionNode {
const start = this._lexer.token;
const description = this.parseDescription();
const name = this.parseName();
this.expectToken(TokenKind.COLON);
const type = this.parseTypeReference();
let defaultValue;
if (this.expectOptionalToken(TokenKind.EQUALS)) {
defaultValue = this.parseConstValueLiteral();
}
const directives = this.parseConstDirectives();
return this.node<InputValueDefinitionNode>(start, {
kind: Kind.INPUT_VALUE_DEFINITION,
description,
name,
type,
defaultValue,
directives,
});
}
/**
* InterfaceTypeDefinition :
* - Description? interface Name Directives[Const]? FieldsDefinition?
*/
parseInterfaceTypeDefinition(): InterfaceTypeDefinitionNode {