-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathparser.py
1274 lines (1110 loc) · 46.1 KB
/
parser.py
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
"""GraphQL parser"""
from __future__ import annotations
from functools import partial
from typing import Callable, List, Mapping, TypeVar, Union, cast
from ..error import GraphQLError, GraphQLSyntaxError
from .ast import (
ArgumentNode,
BooleanValueNode,
ConstArgumentNode,
ConstDirectiveNode,
ConstValueNode,
DefinitionNode,
DirectiveDefinitionNode,
DirectiveNode,
DocumentNode,
EnumTypeDefinitionNode,
EnumTypeExtensionNode,
EnumValueDefinitionNode,
EnumValueNode,
ErrorBoundaryNode,
FieldDefinitionNode,
FieldNode,
FloatValueNode,
FragmentDefinitionNode,
FragmentSpreadNode,
InlineFragmentNode,
InputObjectTypeDefinitionNode,
InputObjectTypeExtensionNode,
InputValueDefinitionNode,
InterfaceTypeDefinitionNode,
InterfaceTypeExtensionNode,
IntValueNode,
ListNullabilityOperatorNode,
ListTypeNode,
ListValueNode,
Location,
NamedTypeNode,
NameNode,
NonNullAssertionNode,
NonNullTypeNode,
NullabilityAssertionNode,
NullValueNode,
ObjectFieldNode,
ObjectTypeDefinitionNode,
ObjectTypeExtensionNode,
ObjectValueNode,
OperationDefinitionNode,
OperationType,
OperationTypeDefinitionNode,
ScalarTypeDefinitionNode,
ScalarTypeExtensionNode,
SchemaDefinitionNode,
SchemaExtensionNode,
SelectionNode,
SelectionSetNode,
StringValueNode,
Token,
TypeNode,
TypeSystemExtensionNode,
UnionTypeDefinitionNode,
UnionTypeExtensionNode,
ValueNode,
VariableDefinitionNode,
VariableNode,
)
from .directive_locations import DirectiveLocation
from .lexer import Lexer, is_punctuator_token_kind
from .source import Source, is_source
from .token_kind import TokenKind
try:
from typing import TypeAlias
except ImportError: # Python < 3.10
from typing_extensions import TypeAlias
__all__ = ["parse", "parse_type", "parse_value", "parse_const_value"]
T = TypeVar("T")
SourceType: TypeAlias = Union[Source, str]
def parse(
source: SourceType,
no_location: bool = False,
max_tokens: int | None = None,
allow_legacy_fragment_variables: bool = False,
experimental_client_controlled_nullability: bool = False,
) -> DocumentNode:
"""Given a GraphQL source, parse it into a Document.
Throws GraphQLError if a syntax error is encountered.
By default, the parser creates AST nodes that know the location in the source that
they correspond to. The ``no_location`` option disables that behavior for
performance or testing.
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.
Legacy feature (will be removed in v3.3):
If ``allow_legacy_fragment_variables`` is set to ``True``, the parser will
understand and parse variable definitions contained in a fragment definition.
They'll be represented in the
:attr:`~graphql.language.FragmentDefinitionNode.variable_definitions` field
of the :class:`~graphql.language.FragmentDefinitionNode`.
The syntax is identical to normal, query-defined variables. For example::
fragment A($var: Boolean = false) on T {
...
}
EXPERIMENTAL:
If enabled, the parser will understand and parse Client Controlled Nullability
Designators contained in Fields. They'll be represented in the
:attr:`~graphql.language.FieldNode.nullability_assertion` field
of the :class:`~graphql.language.FieldNode`.
The syntax looks like the following::
{
nullableField!
nonNullableField?
nonNullableSelectionSet? {
childField!
}
}
Note: this feature is experimental and may change or be removed in the future.
"""
parser = Parser(
source,
no_location=no_location,
max_tokens=max_tokens,
allow_legacy_fragment_variables=allow_legacy_fragment_variables,
experimental_client_controlled_nullability=experimental_client_controlled_nullability,
)
return parser.parse_document()
def parse_value(
source: SourceType,
no_location: bool = False,
max_tokens: int | None = None,
allow_legacy_fragment_variables: bool = False,
) -> ValueNode:
"""Parse the AST for a given string containing a GraphQL 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.
Consider providing the results to the utility function:
:func:`~graphql.utilities.value_from_ast`.
"""
parser = Parser(
source,
no_location=no_location,
max_tokens=max_tokens,
allow_legacy_fragment_variables=allow_legacy_fragment_variables,
)
parser.expect_token(TokenKind.SOF)
value = parser.parse_value_literal(False)
parser.expect_token(TokenKind.EOF)
return value
def parse_const_value(
source: SourceType,
no_location: bool = False,
max_tokens: int | None = None,
allow_legacy_fragment_variables: bool = False,
) -> ConstValueNode:
"""Parse the AST for a given string containing a GraphQL constant value.
Similar to parse_value, but raises a arse error if it encounters a variable.
The return type will be a constant value.
"""
parser = Parser(
source,
no_location=no_location,
max_tokens=max_tokens,
allow_legacy_fragment_variables=allow_legacy_fragment_variables,
)
parser.expect_token(TokenKind.SOF)
value = parser.parse_const_value_literal()
parser.expect_token(TokenKind.EOF)
return value
def parse_type(
source: SourceType,
no_location: bool = False,
max_tokens: int | None = None,
allow_legacy_fragment_variables: bool = False,
) -> TypeNode:
"""Parse the AST for a given string containing a GraphQL 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:
:func:`~graphql.utilities.value_from_ast`.
"""
parser = Parser(
source,
no_location=no_location,
max_tokens=max_tokens,
allow_legacy_fragment_variables=allow_legacy_fragment_variables,
)
parser.expect_token(TokenKind.SOF)
type_ = parser.parse_type_reference()
parser.expect_token(TokenKind.EOF)
return type_
class Parser:
"""GraphQL AST parser.
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 couldn't be contributed upstream.
It's 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 `__version_info__` variable for version detection.
"""
_no_location: bool
_max_tokens: int | None
_allow_legacy_fragment_variables: bool
_experimental_client_controlled_nullability: bool
_lexer: Lexer
_token_counter: int
def __init__(
self,
source: SourceType,
no_location: bool = False,
max_tokens: int | None = None,
allow_legacy_fragment_variables: bool = False,
experimental_client_controlled_nullability: bool = False,
) -> None:
if not is_source(source):
source = Source(cast(str, source))
self._no_location = no_location
self._max_tokens = max_tokens
self._allow_legacy_fragment_variables = allow_legacy_fragment_variables
self._experimental_client_controlled_nullability = (
experimental_client_controlled_nullability
)
self._lexer = Lexer(source)
self._token_counter = 0
def parse_name(self) -> NameNode:
"""Convert a name lex token into a name parse node."""
token = self.expect_token(TokenKind.NAME)
return NameNode(value=token.value, loc=self.loc(token))
# Implement the parsing rules in the Document section.
def parse_document(self) -> DocumentNode:
"""Document: Definition+"""
start = self._lexer.token
return DocumentNode(
definitions=self.many(TokenKind.SOF, self.parse_definition, TokenKind.EOF),
loc=self.loc(start),
)
_parse_type_system_definition_method_names: Mapping[str, str] = {
"schema": "schema_definition",
"scalar": "scalar_type_definition",
"type": "object_type_definition",
"interface": "interface_type_definition",
"union": "union_type_definition",
"enum": "enum_type_definition",
"input": "input_object_type_definition",
"directive": "directive_definition",
}
_parse_other_definition_method_names: Mapping[str, str] = {
**dict.fromkeys(("query", "mutation", "subscription"), "operation_definition"),
"fragment": "fragment_definition",
"extend": "type_system_extension",
}
def parse_definition(self) -> DefinitionNode:
"""Definition: ExecutableDefinition or TypeSystemDefinition/Extension
ExecutableDefinition: OperationDefinition or FragmentDefinition
TypeSystemDefinition: SchemaDefinition, TypeDefinition or DirectiveDefinition
TypeDefinition: ScalarTypeDefinition, ObjectTypeDefinition,
InterfaceTypeDefinition, UnionTypeDefinition,
EnumTypeDefinition or InputObjectTypeDefinition
"""
if self.peek(TokenKind.BRACE_L):
return self.parse_operation_definition()
# Many definitions begin with a description and require a lookahead.
has_description = self.peek_description()
keyword_token = (
self._lexer.lookahead() if has_description else self._lexer.token
)
if keyword_token.kind is TokenKind.NAME:
token_name = cast(str, keyword_token.value)
method_name = self._parse_type_system_definition_method_names.get(
token_name
)
if method_name:
return getattr(self, f"parse_{method_name}")()
if has_description:
raise GraphQLSyntaxError(
self._lexer.source,
self._lexer.token.start,
"Unexpected description,"
" descriptions are supported only on type definitions.",
)
method_name = self._parse_other_definition_method_names.get(token_name)
if method_name:
return getattr(self, f"parse_{method_name}")()
raise self.unexpected(keyword_token)
# Implement the parsing rules in the Operations section.
def parse_operation_definition(self) -> OperationDefinitionNode:
"""OperationDefinition"""
start = self._lexer.token
if self.peek(TokenKind.BRACE_L):
return OperationDefinitionNode(
operation=OperationType.QUERY,
name=None,
variable_definitions=[],
directives=[],
selection_set=self.parse_selection_set(),
loc=self.loc(start),
)
operation = self.parse_operation_type()
name = self.parse_name() if self.peek(TokenKind.NAME) else None
return OperationDefinitionNode(
operation=operation,
name=name,
variable_definitions=self.parse_variable_definitions(),
directives=self.parse_directives(False),
selection_set=self.parse_selection_set(),
loc=self.loc(start),
)
def parse_operation_type(self) -> OperationType:
"""OperationType: one of query mutation subscription"""
operation_token = self.expect_token(TokenKind.NAME)
try:
return OperationType(operation_token.value)
except ValueError as error:
raise self.unexpected(operation_token) from error
def parse_variable_definitions(self) -> list[VariableDefinitionNode]:
"""VariableDefinitions: (VariableDefinition+)"""
return self.optional_many(
TokenKind.PAREN_L, self.parse_variable_definition, TokenKind.PAREN_R
)
def parse_variable_definition(self) -> VariableDefinitionNode:
"""VariableDefinition: Variable: Type DefaultValue? Directives[Const]?"""
start = self._lexer.token
return VariableDefinitionNode(
variable=self.parse_variable(),
type=self.expect_token(TokenKind.COLON) and self.parse_type_reference(),
default_value=self.parse_const_value_literal()
if self.expect_optional_token(TokenKind.EQUALS)
else None,
directives=self.parse_const_directives(),
loc=self.loc(start),
)
def parse_variable(self) -> VariableNode:
"""Variable: $Name"""
start = self._lexer.token
self.expect_token(TokenKind.DOLLAR)
return VariableNode(name=self.parse_name(), loc=self.loc(start))
def parse_selection_set(self) -> SelectionSetNode:
"""SelectionSet: {Selection+}"""
start = self._lexer.token
return SelectionSetNode(
selections=self.many(
TokenKind.BRACE_L, self.parse_selection, TokenKind.BRACE_R
),
loc=self.loc(start),
)
def parse_selection(self) -> SelectionNode:
"""Selection: Field or FragmentSpread or InlineFragment"""
return (
self.parse_fragment if self.peek(TokenKind.SPREAD) else self.parse_field
)()
def parse_field(self) -> FieldNode:
"""Field: Alias? Name Arguments? Directives? SelectionSet?"""
start = self._lexer.token
name_or_alias = self.parse_name()
if self.expect_optional_token(TokenKind.COLON):
alias: NameNode | None = name_or_alias
name = self.parse_name()
else:
alias = None
name = name_or_alias
return FieldNode(
alias=alias,
name=name,
arguments=self.parse_arguments(False),
# Experimental support for Client Controlled Nullability changes
# the grammar of Field:
nullability_assertion=self.parse_nullability_assertion(),
directives=self.parse_directives(False),
selection_set=self.parse_selection_set()
if self.peek(TokenKind.BRACE_L)
else None,
loc=self.loc(start),
)
def parse_nullability_assertion(self) -> NullabilityAssertionNode | None:
"""NullabilityAssertion (grammar not yet finalized)
# Note: Client Controlled Nullability is experimental and may be changed or
# removed in the future.
"""
if not self._experimental_client_controlled_nullability:
return None
start = self._lexer.token
nullability_assertion: NullabilityAssertionNode | None = None
if self.expect_optional_token(TokenKind.BRACKET_L):
inner_modifier = self.parse_nullability_assertion()
self.expect_token(TokenKind.BRACKET_R)
nullability_assertion = ListNullabilityOperatorNode(
nullability_assertion=inner_modifier, loc=self.loc(start)
)
if self.expect_optional_token(TokenKind.BANG):
nullability_assertion = NonNullAssertionNode(
nullability_assertion=nullability_assertion, loc=self.loc(start)
)
elif self.expect_optional_token(TokenKind.QUESTION_MARK):
nullability_assertion = ErrorBoundaryNode(
nullability_assertion=nullability_assertion, loc=self.loc(start)
)
return nullability_assertion
def parse_arguments(self, is_const: bool) -> list[ArgumentNode]:
"""Arguments[Const]: (Argument[?Const]+)"""
item = self.parse_const_argument if is_const else self.parse_argument
return self.optional_many(
TokenKind.PAREN_L, cast(Callable[[], ArgumentNode], item), TokenKind.PAREN_R
)
def parse_argument(self, is_const: bool = False) -> ArgumentNode:
"""Argument[Const]: Name : Value[?Const]"""
start = self._lexer.token
name = self.parse_name()
self.expect_token(TokenKind.COLON)
return ArgumentNode(
name=name, value=self.parse_value_literal(is_const), loc=self.loc(start)
)
def parse_const_argument(self) -> ConstArgumentNode:
"""Argument[Const]: Name : Value[Const]"""
return cast(ConstArgumentNode, self.parse_argument(True))
# Implement the parsing rules in the Fragments section.
def parse_fragment(self) -> FragmentSpreadNode | InlineFragmentNode:
"""Corresponds to both FragmentSpread and InlineFragment in the spec.
FragmentSpread: ... FragmentName Directives?
InlineFragment: ... TypeCondition? Directives? SelectionSet
"""
start = self._lexer.token
self.expect_token(TokenKind.SPREAD)
has_type_condition = self.expect_optional_keyword("on")
if not has_type_condition and self.peek(TokenKind.NAME):
return FragmentSpreadNode(
name=self.parse_fragment_name(),
directives=self.parse_directives(False),
loc=self.loc(start),
)
return InlineFragmentNode(
type_condition=self.parse_named_type() if has_type_condition else None,
directives=self.parse_directives(False),
selection_set=self.parse_selection_set(),
loc=self.loc(start),
)
def parse_fragment_definition(self) -> FragmentDefinitionNode:
"""FragmentDefinition"""
start = self._lexer.token
self.expect_keyword("fragment")
# Legacy support for defining variables within fragments changes
# the grammar of FragmentDefinition
if self._allow_legacy_fragment_variables:
return FragmentDefinitionNode(
name=self.parse_fragment_name(),
variable_definitions=self.parse_variable_definitions(),
type_condition=self.parse_type_condition(),
directives=self.parse_directives(False),
selection_set=self.parse_selection_set(),
loc=self.loc(start),
)
return FragmentDefinitionNode(
name=self.parse_fragment_name(),
type_condition=self.parse_type_condition(),
directives=self.parse_directives(False),
selection_set=self.parse_selection_set(),
loc=self.loc(start),
)
def parse_fragment_name(self) -> NameNode:
"""FragmentName: Name but not ``on``"""
if self._lexer.token.value == "on":
raise self.unexpected()
return self.parse_name()
def parse_type_condition(self) -> NamedTypeNode:
"""TypeCondition: NamedType"""
self.expect_keyword("on")
return self.parse_named_type()
# Implement the parsing rules in the Values section.
_parse_value_literal_method_names: Mapping[TokenKind, str] = {
TokenKind.BRACKET_L: "list",
TokenKind.BRACE_L: "object",
TokenKind.INT: "int",
TokenKind.FLOAT: "float",
TokenKind.STRING: "string_literal",
TokenKind.BLOCK_STRING: "string_literal",
TokenKind.NAME: "named_values",
TokenKind.DOLLAR: "variable_value",
}
def parse_value_literal(self, is_const: bool) -> ValueNode:
method_name = self._parse_value_literal_method_names.get(self._lexer.token.kind)
if method_name: # pragma: no cover
return getattr(self, f"parse_{method_name}")(is_const)
raise self.unexpected() # pragma: no cover
def parse_string_literal(self, _is_const: bool = False) -> StringValueNode:
token = self._lexer.token
self.advance_lexer()
return StringValueNode(
value=token.value,
block=token.kind == TokenKind.BLOCK_STRING,
loc=self.loc(token),
)
def parse_list(self, is_const: bool) -> ListValueNode:
"""ListValue[Const]"""
start = self._lexer.token
item = partial(self.parse_value_literal, is_const)
# noinspection PyTypeChecker
return ListValueNode(
values=self.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),
loc=self.loc(start),
)
def parse_object_field(self, is_const: bool) -> ObjectFieldNode:
start = self._lexer.token
name = self.parse_name()
self.expect_token(TokenKind.COLON)
return ObjectFieldNode(
name=name, value=self.parse_value_literal(is_const), loc=self.loc(start)
)
def parse_object(self, is_const: bool) -> ObjectValueNode:
"""ObjectValue[Const]"""
start = self._lexer.token
item = partial(self.parse_object_field, is_const)
return ObjectValueNode(
fields=self.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),
loc=self.loc(start),
)
def parse_int(self, _is_const: bool = False) -> IntValueNode:
token = self._lexer.token
self.advance_lexer()
return IntValueNode(value=token.value, loc=self.loc(token))
def parse_float(self, _is_const: bool = False) -> FloatValueNode:
token = self._lexer.token
self.advance_lexer()
return FloatValueNode(value=token.value, loc=self.loc(token))
def parse_named_values(self, _is_const: bool = False) -> ValueNode:
token = self._lexer.token
value = token.value
self.advance_lexer()
if value == "true":
return BooleanValueNode(value=True, loc=self.loc(token))
if value == "false":
return BooleanValueNode(value=False, loc=self.loc(token))
if value == "null":
return NullValueNode(loc=self.loc(token))
return EnumValueNode(value=value, loc=self.loc(token))
def parse_variable_value(self, is_const: bool) -> VariableNode:
if is_const:
variable_token = self.expect_token(TokenKind.DOLLAR)
token = self._lexer.token
if token.kind is TokenKind.NAME:
var_name = token.value
raise GraphQLSyntaxError(
self._lexer.source,
variable_token.start,
f"Unexpected variable '${var_name}' in constant value.",
)
raise self.unexpected(variable_token)
return self.parse_variable()
def parse_const_value_literal(self) -> ConstValueNode:
return cast(ConstValueNode, self.parse_value_literal(True))
# Implement the parsing rules in the Directives section.
def parse_directives(self, is_const: bool) -> list[DirectiveNode]:
"""Directives[Const]: Directive[?Const]+"""
directives: list[DirectiveNode] = []
append = directives.append
while self.peek(TokenKind.AT):
append(self.parse_directive(is_const))
return directives
def parse_const_directives(self) -> list[ConstDirectiveNode]:
return cast(List[ConstDirectiveNode], self.parse_directives(True))
def parse_directive(self, is_const: bool) -> DirectiveNode:
"""Directive[Const]: @ Name Arguments[?Const]?"""
start = self._lexer.token
self.expect_token(TokenKind.AT)
return DirectiveNode(
name=self.parse_name(),
arguments=self.parse_arguments(is_const),
loc=self.loc(start),
)
# Implement the parsing rules in the Types section.
def parse_type_reference(self) -> TypeNode:
"""Type: NamedType or ListType or NonNullType"""
start = self._lexer.token
type_: TypeNode
if self.expect_optional_token(TokenKind.BRACKET_L):
inner_type = self.parse_type_reference()
self.expect_token(TokenKind.BRACKET_R)
type_ = ListTypeNode(type=inner_type, loc=self.loc(start))
else:
type_ = self.parse_named_type()
if self.expect_optional_token(TokenKind.BANG):
return NonNullTypeNode(type=type_, loc=self.loc(start))
return type_
def parse_named_type(self) -> NamedTypeNode:
"""NamedType: Name"""
start = self._lexer.token
return NamedTypeNode(name=self.parse_name(), loc=self.loc(start))
# Implement the parsing rules in the Type Definition section.
_parse_type_extension_method_names: Mapping[str, str] = {
"schema": "schema_extension",
"scalar": "scalar_type_extension",
"type": "object_type_extension",
"interface": "interface_type_extension",
"union": "union_type_extension",
"enum": "enum_type_extension",
"input": "input_object_type_extension",
}
def parse_type_system_extension(self) -> TypeSystemExtensionNode:
"""TypeSystemExtension"""
keyword_token = self._lexer.lookahead()
if keyword_token.kind == TokenKind.NAME:
method_name = self._parse_type_extension_method_names.get(
cast(str, keyword_token.value)
)
if method_name: # pragma: no cover
return getattr(self, f"parse_{method_name}")()
raise self.unexpected(keyword_token)
def peek_description(self) -> bool:
return self.peek(TokenKind.STRING) or self.peek(TokenKind.BLOCK_STRING)
def parse_description(self) -> StringValueNode | None:
"""Description: StringValue"""
if self.peek_description():
return self.parse_string_literal()
return None
def parse_schema_definition(self) -> SchemaDefinitionNode:
"""SchemaDefinition"""
start = self._lexer.token
description = self.parse_description()
self.expect_keyword("schema")
directives = self.parse_const_directives()
operation_types = self.many(
TokenKind.BRACE_L, self.parse_operation_type_definition, TokenKind.BRACE_R
)
return SchemaDefinitionNode(
description=description,
directives=directives,
operation_types=operation_types,
loc=self.loc(start),
)
def parse_operation_type_definition(self) -> OperationTypeDefinitionNode:
"""OperationTypeDefinition: OperationType : NamedType"""
start = self._lexer.token
operation = self.parse_operation_type()
self.expect_token(TokenKind.COLON)
type_ = self.parse_named_type()
return OperationTypeDefinitionNode(
operation=operation, type=type_, loc=self.loc(start)
)
def parse_scalar_type_definition(self) -> ScalarTypeDefinitionNode:
"""ScalarTypeDefinition: Description? scalar Name Directives[Const]?"""
start = self._lexer.token
description = self.parse_description()
self.expect_keyword("scalar")
name = self.parse_name()
directives = self.parse_const_directives()
return ScalarTypeDefinitionNode(
description=description,
name=name,
directives=directives,
loc=self.loc(start),
)
def parse_object_type_definition(self) -> ObjectTypeDefinitionNode:
"""ObjectTypeDefinition"""
start = self._lexer.token
description = self.parse_description()
self.expect_keyword("type")
name = self.parse_name()
interfaces = self.parse_implements_interfaces()
directives = self.parse_const_directives()
fields = self.parse_fields_definition()
return ObjectTypeDefinitionNode(
description=description,
name=name,
interfaces=interfaces,
directives=directives,
fields=fields,
loc=self.loc(start),
)
def parse_implements_interfaces(self) -> list[NamedTypeNode]:
"""ImplementsInterfaces"""
return (
self.delimited_many(TokenKind.AMP, self.parse_named_type)
if self.expect_optional_keyword("implements")
else []
)
def parse_fields_definition(self) -> list[FieldDefinitionNode]:
"""FieldsDefinition: {FieldDefinition+}"""
return self.optional_many(
TokenKind.BRACE_L, self.parse_field_definition, TokenKind.BRACE_R
)
def parse_field_definition(self) -> FieldDefinitionNode:
"""FieldDefinition"""
start = self._lexer.token
description = self.parse_description()
name = self.parse_name()
args = self.parse_argument_defs()
self.expect_token(TokenKind.COLON)
type_ = self.parse_type_reference()
directives = self.parse_const_directives()
return FieldDefinitionNode(
description=description,
name=name,
arguments=args,
type=type_,
directives=directives,
loc=self.loc(start),
)
def parse_argument_defs(self) -> list[InputValueDefinitionNode]:
"""ArgumentsDefinition: (InputValueDefinition+)"""
return self.optional_many(
TokenKind.PAREN_L, self.parse_input_value_def, TokenKind.PAREN_R
)
def parse_input_value_def(self) -> InputValueDefinitionNode:
"""InputValueDefinition"""
start = self._lexer.token
description = self.parse_description()
name = self.parse_name()
self.expect_token(TokenKind.COLON)
type_ = self.parse_type_reference()
default_value = (
self.parse_const_value_literal()
if self.expect_optional_token(TokenKind.EQUALS)
else None
)
directives = self.parse_const_directives()
return InputValueDefinitionNode(
description=description,
name=name,
type=type_,
default_value=default_value,
directives=directives,
loc=self.loc(start),
)
def parse_interface_type_definition(self) -> InterfaceTypeDefinitionNode:
"""InterfaceTypeDefinition"""
start = self._lexer.token
description = self.parse_description()
self.expect_keyword("interface")
name = self.parse_name()
interfaces = self.parse_implements_interfaces()
directives = self.parse_const_directives()
fields = self.parse_fields_definition()
return InterfaceTypeDefinitionNode(
description=description,
name=name,
interfaces=interfaces,
directives=directives,
fields=fields,
loc=self.loc(start),
)
def parse_union_type_definition(self) -> UnionTypeDefinitionNode:
"""UnionTypeDefinition"""
start = self._lexer.token
description = self.parse_description()
self.expect_keyword("union")
name = self.parse_name()
directives = self.parse_const_directives()
types = self.parse_union_member_types()
return UnionTypeDefinitionNode(
description=description,
name=name,
directives=directives,
types=types,
loc=self.loc(start),
)
def parse_union_member_types(self) -> list[NamedTypeNode]:
"""UnionMemberTypes"""
return (
self.delimited_many(TokenKind.PIPE, self.parse_named_type)
if self.expect_optional_token(TokenKind.EQUALS)
else []
)
def parse_enum_type_definition(self) -> EnumTypeDefinitionNode:
"""UnionTypeDefinition"""
start = self._lexer.token
description = self.parse_description()
self.expect_keyword("enum")
name = self.parse_name()
directives = self.parse_const_directives()
values = self.parse_enum_values_definition()
return EnumTypeDefinitionNode(
description=description,
name=name,
directives=directives,
values=values,
loc=self.loc(start),
)
def parse_enum_values_definition(self) -> list[EnumValueDefinitionNode]:
"""EnumValuesDefinition: {EnumValueDefinition+}"""
return self.optional_many(
TokenKind.BRACE_L, self.parse_enum_value_definition, TokenKind.BRACE_R
)
def parse_enum_value_definition(self) -> EnumValueDefinitionNode:
"""EnumValueDefinition: Description? EnumValue Directives[Const]?"""
start = self._lexer.token
description = self.parse_description()
name = self.parse_enum_value_name()
directives = self.parse_const_directives()
return EnumValueDefinitionNode(
description=description,
name=name,
directives=directives,
loc=self.loc(start),
)
def parse_enum_value_name(self) -> NameNode:
"""EnumValue: Name but not ``true``, ``false`` or ``null``"""
if self._lexer.token.value in ("true", "false", "null"):
raise GraphQLSyntaxError(
self._lexer.source,
self._lexer.token.start,
f"{get_token_desc(self._lexer.token)} is reserved"
" and cannot be used for an enum value.",
)
return self.parse_name()
def parse_input_object_type_definition(self) -> InputObjectTypeDefinitionNode:
"""InputObjectTypeDefinition"""
start = self._lexer.token
description = self.parse_description()
self.expect_keyword("input")
name = self.parse_name()
directives = self.parse_const_directives()
fields = self.parse_input_fields_definition()
return InputObjectTypeDefinitionNode(
description=description,
name=name,
directives=directives,
fields=fields,
loc=self.loc(start),
)
def parse_input_fields_definition(self) -> list[InputValueDefinitionNode]:
"""InputFieldsDefinition: {InputValueDefinition+}"""
return self.optional_many(
TokenKind.BRACE_L, self.parse_input_value_def, TokenKind.BRACE_R
)
def parse_schema_extension(self) -> SchemaExtensionNode:
"""SchemaExtension"""
start = self._lexer.token
self.expect_keyword("extend")
self.expect_keyword("schema")
directives = self.parse_const_directives()
operation_types = self.optional_many(
TokenKind.BRACE_L, self.parse_operation_type_definition, TokenKind.BRACE_R
)
if not directives and not operation_types:
raise self.unexpected()
return SchemaExtensionNode(
directives=directives, operation_types=operation_types, loc=self.loc(start)
)
def parse_scalar_type_extension(self) -> ScalarTypeExtensionNode:
"""ScalarTypeExtension"""
start = self._lexer.token
self.expect_keyword("extend")
self.expect_keyword("scalar")
name = self.parse_name()
directives = self.parse_const_directives()
if not directives:
raise self.unexpected()
return ScalarTypeExtensionNode(
name=name, directives=directives, loc=self.loc(start)
)
def parse_object_type_extension(self) -> ObjectTypeExtensionNode:
"""ObjectTypeExtension"""
start = self._lexer.token
self.expect_keyword("extend")
self.expect_keyword("type")
name = self.parse_name()
interfaces = self.parse_implements_interfaces()
directives = self.parse_const_directives()
fields = self.parse_fields_definition()
if not (interfaces or directives or fields):
raise self.unexpected()
return ObjectTypeExtensionNode(
name=name,
interfaces=interfaces,
directives=directives,
fields=fields,
loc=self.loc(start),
)
def parse_interface_type_extension(self) -> InterfaceTypeExtensionNode:
"""InterfaceTypeExtension"""
start = self._lexer.token
self.expect_keyword("extend")