| 1 |
from functools import partial |
| 2 |
from typing import Callable, Dict, List, Optional, TypeVar, Union, cast |
| 3 |
|
| 4 |
from ..error import GraphQLError, GraphQLSyntaxError |
| 5 |
from .ast import ( |
| 6 |
ArgumentCoordinateNode, |
| 7 |
ArgumentNode, |
| 8 |
BooleanValueNode, |
| 9 |
ConstArgumentNode, |
| 10 |
ConstDirectiveNode, |
| 11 |
ConstValueNode, |
| 12 |
DefinitionNode, |
| 13 |
DirectiveArgumentCoordinateNode, |
| 14 |
DirectiveCoordinateNode, |
| 15 |
DirectiveDefinitionNode, |
| 16 |
DirectiveExtensionNode, |
| 17 |
DirectiveNode, |
| 18 |
DocumentNode, |
| 19 |
EnumTypeDefinitionNode, |
| 20 |
EnumTypeExtensionNode, |
| 21 |
EnumValueDefinitionNode, |
| 22 |
EnumValueNode, |
| 23 |
FieldDefinitionNode, |
| 24 |
FieldNode, |
| 25 |
FloatValueNode, |
| 26 |
FragmentDefinitionNode, |
| 27 |
FragmentSpreadNode, |
| 28 |
InlineFragmentNode, |
| 29 |
InputObjectTypeDefinitionNode, |
| 30 |
InputObjectTypeExtensionNode, |
| 31 |
InputValueDefinitionNode, |
| 32 |
InterfaceTypeDefinitionNode, |
| 33 |
InterfaceTypeExtensionNode, |
| 34 |
IntValueNode, |
| 35 |
ListTypeNode, |
| 36 |
ListValueNode, |
| 37 |
Location, |
| 38 |
MemberCoordinateNode, |
| 39 |
NamedTypeNode, |
| 40 |
NameNode, |
| 41 |
NonNullTypeNode, |
| 42 |
NullValueNode, |
| 43 |
ObjectFieldNode, |
| 44 |
ObjectTypeDefinitionNode, |
| 45 |
ObjectTypeExtensionNode, |
| 46 |
ObjectValueNode, |
| 47 |
OperationDefinitionNode, |
| 48 |
OperationType, |
| 49 |
OperationTypeDefinitionNode, |
| 50 |
ScalarTypeDefinitionNode, |
| 51 |
ScalarTypeExtensionNode, |
| 52 |
SchemaCoordinateNode, |
| 53 |
SchemaDefinitionNode, |
| 54 |
SchemaExtensionNode, |
| 55 |
SelectionNode, |
| 56 |
SelectionSetNode, |
| 57 |
StringValueNode, |
| 58 |
Token, |
| 59 |
TypeCoordinateNode, |
| 60 |
TypeNode, |
| 61 |
TypeSystemExtensionNode, |
| 62 |
UnionTypeDefinitionNode, |
| 63 |
UnionTypeExtensionNode, |
| 64 |
ValueNode, |
| 65 |
VariableDefinitionNode, |
| 66 |
VariableNode, |
| 67 |
) |
| 68 |
from .directive_locations import DirectiveLocation |
| 69 |
from .lexer import Lexer, is_punctuator_token_kind |
| 70 |
from .schema_coordinate_lexer import SchemaCoordinateLexer |
| 71 |
from .source import Source, is_source |
| 72 |
from .token_kind import TokenKind |
| 73 |
|
| 74 |
__all__ = [ |
| 75 |
"parse", |
| 76 |
"parse_type", |
| 77 |
"parse_value", |
| 78 |
"parse_const_value", |
| 79 |
"parse_schema_coordinate", |
| 80 |
] |
| 81 |
|
| 82 |
T = TypeVar("T") |
| 83 |
|
| 84 |
SourceType = Union[Source, str] |
| 85 |
|
| 86 |
|
| 87 |
def parse( |
| 88 |
source: SourceType, |
| 89 |
no_location: bool = False, |
| 90 |
max_tokens: Optional[int] = None, |
| 91 |
allow_legacy_fragment_variables: bool = False, |
| 92 |
experimental_directives_on_directive_definitions: bool = False, |
| 93 |
) -> DocumentNode: |
| 94 |
"""Given a GraphQL source, parse it into a Document. |
| 95 |
|
| 96 |
Throws GraphQLError if a syntax error is encountered. |
| 97 |
|
| 98 |
By default, the parser creates AST nodes that know the location in the source that |
| 99 |
they correspond to. Setting the ``no_location`` parameter to False disables that |
| 100 |
behavior for performance or testing. |
| 101 |
|
| 102 |
Parser CPU and memory usage is linear to the number of tokens in a document, |
| 103 |
however in extreme cases it becomes quadratic due to memory exhaustion. |
| 104 |
Parsing happens before validation, so even invalid queries can burn lots of |
| 105 |
CPU time and memory. To prevent this, you can set a maximum number of tokens |
| 106 |
allowed within a document using the ``max_tokens`` parameter. |
| 107 |
|
| 108 |
Legacy feature (will be removed in v3.3): |
| 109 |
|
| 110 |
If ``allow_legacy_fragment_variables`` is set to ``True``, the parser will |
| 111 |
understand and parse variable definitions contained in a fragment definition. |
| 112 |
They'll be represented in the |
| 113 |
:attr:`~graphql.language.FragmentDefinitionNode.variable_definitions` field |
| 114 |
of the :class:`~graphql.language.FragmentDefinitionNode`. |
| 115 |
|
| 116 |
This legacy fragment variable syntax is deprecated. Move variable definitions to |
| 117 |
operations for spec-compliant documents; if you need variables or arguments scoped |
| 118 |
to fragments, the more complete experimental fragment-arguments feature in |
| 119 |
graphql-core 3.3 should be used instead. |
| 120 |
|
| 121 |
The syntax is identical to normal, query-defined variables. For example:: |
| 122 |
|
| 123 |
fragment A($var: Boolean = false) on T { |
| 124 |
... |
| 125 |
} |
| 126 |
|
| 127 |
Experimental feature: |
| 128 |
|
| 129 |
If ``experimental_directives_on_directive_definitions`` is set to ``True``, the |
| 130 |
parser will understand and parse directives on directive definitions. This syntax |
| 131 |
is not part of the GraphQL specification and may change. For example:: |
| 132 |
|
| 133 |
directive @foo @bar on FIELD |
| 134 |
""" |
| 135 |
parser = Parser( |
| 136 |
source, |
| 137 |
no_location=no_location, |
| 138 |
max_tokens=max_tokens, |
| 139 |
allow_legacy_fragment_variables=allow_legacy_fragment_variables, |
| 140 |
experimental_directives_on_directive_definitions=( |
| 141 |
experimental_directives_on_directive_definitions |
| 142 |
), |
| 143 |
) |
| 144 |
return parser.parse_document() |
| 145 |
|
| 146 |
|
| 147 |
def parse_value( |
| 148 |
source: SourceType, |
| 149 |
no_location: bool = False, |
| 150 |
max_tokens: Optional[int] = None, |
| 151 |
allow_legacy_fragment_variables: bool = False, |
| 152 |
experimental_directives_on_directive_definitions: bool = False, |
| 153 |
) -> ValueNode: |
| 154 |
"""Parse the AST for a given string containing a GraphQL value. |
| 155 |
|
| 156 |
Throws GraphQLError if a syntax error is encountered. |
| 157 |
|
| 158 |
This is useful within tools that operate upon GraphQL Values directly and in |
| 159 |
isolation of complete GraphQL documents. |
| 160 |
|
| 161 |
Consider providing the results to the utility function: |
| 162 |
:func:`~graphql.utilities.value_from_ast`. |
| 163 |
""" |
| 164 |
parser = Parser( |
| 165 |
source, |
| 166 |
no_location=no_location, |
| 167 |
max_tokens=max_tokens, |
| 168 |
allow_legacy_fragment_variables=allow_legacy_fragment_variables, |
| 169 |
experimental_directives_on_directive_definitions=( |
| 170 |
experimental_directives_on_directive_definitions |
| 171 |
), |
| 172 |
) |
| 173 |
parser.expect_token(TokenKind.SOF) |
| 174 |
value = parser.parse_value_literal(False) |
| 175 |
parser.expect_token(TokenKind.EOF) |
| 176 |
return value |
| 177 |
|
| 178 |
|
| 179 |
def parse_const_value( |
| 180 |
source: SourceType, |
| 181 |
no_location: bool = False, |
| 182 |
max_tokens: Optional[int] = None, |
| 183 |
allow_legacy_fragment_variables: bool = False, |
| 184 |
experimental_directives_on_directive_definitions: bool = False, |
| 185 |
) -> ConstValueNode: |
| 186 |
"""Parse the AST for a given string containing a GraphQL constant value. |
| 187 |
|
| 188 |
Similar to parse_value, but raises a arse error if it encounters a variable. |
| 189 |
The return type will be a constant value. |
| 190 |
""" |
| 191 |
parser = Parser( |
| 192 |
source, |
| 193 |
no_location=no_location, |
| 194 |
max_tokens=max_tokens, |
| 195 |
allow_legacy_fragment_variables=allow_legacy_fragment_variables, |
| 196 |
experimental_directives_on_directive_definitions=( |
| 197 |
experimental_directives_on_directive_definitions |
| 198 |
), |
| 199 |
) |
| 200 |
parser.expect_token(TokenKind.SOF) |
| 201 |
value = parser.parse_const_value_literal() |
| 202 |
parser.expect_token(TokenKind.EOF) |
| 203 |
return value |
| 204 |
|
| 205 |
|
| 206 |
def parse_type( |
| 207 |
source: SourceType, |
| 208 |
no_location: bool = False, |
| 209 |
max_tokens: Optional[int] = None, |
| 210 |
allow_legacy_fragment_variables: bool = False, |
| 211 |
experimental_directives_on_directive_definitions: bool = False, |
| 212 |
) -> TypeNode: |
| 213 |
"""Parse the AST for a given string containing a GraphQL Type. |
| 214 |
|
| 215 |
Throws GraphQLError if a syntax error is encountered. |
| 216 |
|
| 217 |
This is useful within tools that operate upon GraphQL Types directly and |
| 218 |
in isolation of complete GraphQL documents. |
| 219 |
|
| 220 |
Consider providing the results to the utility function: |
| 221 |
:func:`~graphql.utilities.value_from_ast`. |
| 222 |
""" |
| 223 |
parser = Parser( |
| 224 |
source, |
| 225 |
no_location=no_location, |
| 226 |
max_tokens=max_tokens, |
| 227 |
allow_legacy_fragment_variables=allow_legacy_fragment_variables, |
| 228 |
experimental_directives_on_directive_definitions=( |
| 229 |
experimental_directives_on_directive_definitions |
| 230 |
), |
| 231 |
) |
| 232 |
parser.expect_token(TokenKind.SOF) |
| 233 |
type_ = parser.parse_type_reference() |
| 234 |
parser.expect_token(TokenKind.EOF) |
| 235 |
return type_ |
| 236 |
|
| 237 |
|
| 238 |
def parse_schema_coordinate( |
| 239 |
source: SourceType, |
| 240 |
no_location: bool = False, |
| 241 |
max_tokens: Optional[int] = None, |
| 242 |
) -> SchemaCoordinateNode: |
| 243 |
"""Parse the AST for a given string containing a GraphQL schema coordinate. |
| 244 |
|
| 245 |
Throws GraphQLError if a syntax error is encountered. |
| 246 |
|
| 247 |
This is useful within tools that operate upon GraphQL schema coordinates |
| 248 |
(ex. ``Type.field``) directly and in isolation of complete GraphQL documents. |
| 249 |
|
| 250 |
Consider providing the results to the utility function: |
| 251 |
:func:`~graphql.utilities.resolve_ast_schema_coordinate`. Or calling |
| 252 |
:func:`~graphql.utilities.resolve_schema_coordinate` directly with an |
| 253 |
unparsed source. |
| 254 |
""" |
| 255 |
source = cast(Source, source) if is_source(source) else Source(cast(str, source)) |
| 256 |
lexer = SchemaCoordinateLexer(source) |
| 257 |
parser = Parser(source, no_location=no_location, max_tokens=max_tokens, lexer=lexer) |
| 258 |
parser.expect_token(TokenKind.SOF) |
| 259 |
coordinate = parser.parse_schema_coordinate() |
| 260 |
parser.expect_token(TokenKind.EOF) |
| 261 |
return coordinate |
| 262 |
|
| 263 |
|
| 264 |
class Parser: |
| 265 |
"""GraphQL AST parser. |
| 266 |
|
| 267 |
This class is exported only to assist people in implementing their own parsers |
| 268 |
without duplicating too much code and should be used only as last resort for cases |
| 269 |
such as experimental syntax or if certain features couldn't be contributed upstream. |
| 270 |
|
| 271 |
It's still part of the internal API and is versioned, so any changes to it are never |
| 272 |
considered breaking changes. If you still need to support multiple versions of the |
| 273 |
library, please use the `__version_info__` variable for version detection. |
| 274 |
""" |
| 275 |
|
| 276 |
_lexer: Lexer |
| 277 |
_no_location: bool |
| 278 |
_max_tokens: Optional[int] |
| 279 |
_allow_legacy_fragment_variables: bool |
| 280 |
_experimental_directives_on_directive_definitions: bool |
| 281 |
_token_counter: int |
| 282 |
|
| 283 |
def __init__( |
| 284 |
self, |
| 285 |
source: SourceType, |
| 286 |
no_location: bool = False, |
| 287 |
max_tokens: Optional[int] = None, |
| 288 |
allow_legacy_fragment_variables: bool = False, |
| 289 |
experimental_directives_on_directive_definitions: bool = False, |
| 290 |
lexer: Optional[Lexer] = None, |
| 291 |
): |
| 292 |
source = ( |
| 293 |
cast(Source, source) if is_source(source) else Source(cast(str, source)) |
| 294 |
) |
| 295 |
|
| 296 |
# You may override the lexer used to lex the source; this is used by schema |
| 297 |
# coordinates to introduce a lexer with a restricted syntax. |
| 298 |
self._lexer = lexer if lexer is not None else Lexer(source) |
| 299 |
self._no_location = no_location |
| 300 |
self._max_tokens = max_tokens |
| 301 |
self._allow_legacy_fragment_variables = allow_legacy_fragment_variables |
| 302 |
self._experimental_directives_on_directive_definitions = ( |
| 303 |
experimental_directives_on_directive_definitions |
| 304 |
) |
| 305 |
self._token_counter = 0 |
| 306 |
|
| 307 |
def parse_name(self) -> NameNode: |
| 308 |
"""Convert a name lex token into a name parse node.""" |
| 309 |
token = self.expect_token(TokenKind.NAME) |
| 310 |
return NameNode(value=token.value, loc=self.loc(token)) |
| 311 |
|
| 312 |
# Implement the parsing rules in the Document section. |
| 313 |
|
| 314 |
@property |
| 315 |
def token_count(self) -> int: |
| 316 |
"""Get the number of tokens that have been parsed so far.""" |
| 317 |
return self._token_counter |
| 318 |
|
| 319 |
def parse_document(self) -> DocumentNode: |
| 320 |
"""Document: Definition+""" |
| 321 |
start = self._lexer.token |
| 322 |
document = DocumentNode( |
| 323 |
definitions=self.many(TokenKind.SOF, self.parse_definition, TokenKind.EOF), |
| 324 |
loc=self.loc(start), |
| 325 |
) |
| 326 |
# Expose the token count as a (non-traversable) attribute on the document. |
| 327 |
document.token_count = self.token_count |
| 328 |
return document |
| 329 |
|
| 330 |
_parse_type_system_definition_method_names: Dict[str, str] = { |
| 331 |
"schema": "schema_definition", |
| 332 |
"scalar": "scalar_type_definition", |
| 333 |
"type": "object_type_definition", |
| 334 |
"interface": "interface_type_definition", |
| 335 |
"union": "union_type_definition", |
| 336 |
"enum": "enum_type_definition", |
| 337 |
"input": "input_object_type_definition", |
| 338 |
"directive": "directive_definition", |
| 339 |
} |
| 340 |
|
| 341 |
_parse_executable_definition_method_names: Dict[str, str] = { |
| 342 |
**dict.fromkeys(("query", "mutation", "subscription"), "operation_definition"), |
| 343 |
"fragment": "fragment_definition", |
| 344 |
} |
| 345 |
|
| 346 |
_parse_other_definition_method_names: Dict[str, str] = { |
| 347 |
"extend": "type_system_extension", |
| 348 |
} |
| 349 |
|
| 350 |
def parse_definition(self) -> DefinitionNode: |
| 351 |
"""Definition: ExecutableDefinition or TypeSystemDefinition/Extension |
| 352 |
|
| 353 |
ExecutableDefinition: OperationDefinition or FragmentDefinition |
| 354 |
|
| 355 |
TypeSystemDefinition: SchemaDefinition, TypeDefinition or DirectiveDefinition |
| 356 |
|
| 357 |
TypeDefinition: ScalarTypeDefinition, ObjectTypeDefinition, |
| 358 |
InterfaceTypeDefinition, UnionTypeDefinition, |
| 359 |
EnumTypeDefinition or InputObjectTypeDefinition |
| 360 |
""" |
| 361 |
if self.peek(TokenKind.BRACE_L): |
| 362 |
return self.parse_operation_definition() |
| 363 |
|
| 364 |
# Many definitions begin with a description and require a lookahead. |
| 365 |
has_description = self.peek_description() |
| 366 |
keyword_token = ( |
| 367 |
self._lexer.lookahead() if has_description else self._lexer.token |
| 368 |
) |
| 369 |
|
| 370 |
if has_description and keyword_token.kind is TokenKind.BRACE_L: |
| 371 |
raise GraphQLSyntaxError( |
| 372 |
self._lexer.source, |
| 373 |
self._lexer.token.start, |
| 374 |
"Unexpected description," |
| 375 |
" descriptions are not supported on shorthand queries.", |
| 376 |
) |
| 377 |
|
| 378 |
if keyword_token.kind is TokenKind.NAME: |
| 379 |
token_name = cast(str, keyword_token.value) |
| 380 |
method_name = self._parse_type_system_definition_method_names.get( |
| 381 |
token_name |
| 382 |
) |
| 383 |
if method_name: |
| 384 |
return getattr(self, f"parse_{method_name}")() |
| 385 |
|
| 386 |
method_name = self._parse_executable_definition_method_names.get(token_name) |
| 387 |
if method_name: |
| 388 |
return getattr(self, f"parse_{method_name}")() |
| 389 |
|
| 390 |
if has_description: |
| 391 |
raise GraphQLSyntaxError( |
| 392 |
self._lexer.source, |
| 393 |
self._lexer.token.start, |
| 394 |
"Unexpected description," |
| 395 |
" only GraphQL definitions support descriptions.", |
| 396 |
) |
| 397 |
|
| 398 |
method_name = self._parse_other_definition_method_names.get(token_name) |
| 399 |
if method_name: |
| 400 |
return getattr(self, f"parse_{method_name}")() |
| 401 |
|
| 402 |
raise self.unexpected(keyword_token) |
| 403 |
|
| 404 |
# Implement the parsing rules in the Operations section. |
| 405 |
|
| 406 |
def parse_operation_definition(self) -> OperationDefinitionNode: |
| 407 |
"""OperationDefinition""" |
| 408 |
start = self._lexer.token |
| 409 |
if self.peek(TokenKind.BRACE_L): |
| 410 |
return OperationDefinitionNode( |
| 411 |
operation=OperationType.QUERY, |
| 412 |
description=None, |
| 413 |
name=None, |
| 414 |
variable_definitions=[], |
| 415 |
directives=[], |
| 416 |
selection_set=self.parse_selection_set(), |
| 417 |
loc=self.loc(start), |
| 418 |
) |
| 419 |
description = self.parse_description() |
| 420 |
operation = self.parse_operation_type() |
| 421 |
name = self.parse_name() if self.peek(TokenKind.NAME) else None |
| 422 |
return OperationDefinitionNode( |
| 423 |
operation=operation, |
| 424 |
description=description, |
| 425 |
name=name, |
| 426 |
variable_definitions=self.parse_variable_definitions(), |
| 427 |
directives=self.parse_directives(False), |
| 428 |
selection_set=self.parse_selection_set(), |
| 429 |
loc=self.loc(start), |
| 430 |
) |
| 431 |
|
| 432 |
def parse_operation_type(self) -> OperationType: |
| 433 |
"""OperationType: one of query mutation subscription""" |
| 434 |
operation_token = self.expect_token(TokenKind.NAME) |
| 435 |
try: |
| 436 |
return OperationType(operation_token.value) |
| 437 |
except ValueError: |
| 438 |
raise self.unexpected(operation_token) |
| 439 |
|
| 440 |
def parse_variable_definitions(self) -> List[VariableDefinitionNode]: |
| 441 |
"""VariableDefinitions: (VariableDefinition+)""" |
| 442 |
return self.optional_many( |
| 443 |
TokenKind.PAREN_L, self.parse_variable_definition, TokenKind.PAREN_R |
| 444 |
) |
| 445 |
|
| 446 |
def parse_variable_definition(self) -> VariableDefinitionNode: |
| 447 |
"""VariableDefinition: Variable: Type DefaultValue? Directives[Const]?""" |
| 448 |
start = self._lexer.token |
| 449 |
return VariableDefinitionNode( |
| 450 |
description=self.parse_description(), |
| 451 |
variable=self.parse_variable(), |
| 452 |
type=self.expect_token(TokenKind.COLON) and self.parse_type_reference(), |
| 453 |
default_value=( |
| 454 |
self.parse_const_value_literal() |
| 455 |
if self.expect_optional_token(TokenKind.EQUALS) |
| 456 |
else None |
| 457 |
), |
| 458 |
directives=self.parse_const_directives(), |
| 459 |
loc=self.loc(start), |
| 460 |
) |
| 461 |
|
| 462 |
def parse_variable(self) -> VariableNode: |
| 463 |
"""Variable: $Name""" |
| 464 |
start = self._lexer.token |
| 465 |
self.expect_token(TokenKind.DOLLAR) |
| 466 |
return VariableNode(name=self.parse_name(), loc=self.loc(start)) |
| 467 |
|
| 468 |
def parse_selection_set(self) -> SelectionSetNode: |
| 469 |
"""SelectionSet: {Selection+}""" |
| 470 |
start = self._lexer.token |
| 471 |
return SelectionSetNode( |
| 472 |
selections=self.many( |
| 473 |
TokenKind.BRACE_L, self.parse_selection, TokenKind.BRACE_R |
| 474 |
), |
| 475 |
loc=self.loc(start), |
| 476 |
) |
| 477 |
|
| 478 |
def parse_selection(self) -> SelectionNode: |
| 479 |
"""Selection: Field or FragmentSpread or InlineFragment""" |
| 480 |
return ( |
| 481 |
self.parse_fragment if self.peek(TokenKind.SPREAD) else self.parse_field |
| 482 |
)() |
| 483 |
|
| 484 |
def parse_field(self) -> FieldNode: |
| 485 |
"""Field: Alias? Name Arguments? Directives? SelectionSet?""" |
| 486 |
start = self._lexer.token |
| 487 |
name_or_alias = self.parse_name() |
| 488 |
if self.expect_optional_token(TokenKind.COLON): |
| 489 |
alias: Optional[NameNode] = name_or_alias |
| 490 |
name = self.parse_name() |
| 491 |
else: |
| 492 |
alias = None |
| 493 |
name = name_or_alias |
| 494 |
return FieldNode( |
| 495 |
alias=alias, |
| 496 |
name=name, |
| 497 |
arguments=self.parse_arguments(False), |
| 498 |
directives=self.parse_directives(False), |
| 499 |
selection_set=( |
| 500 |
self.parse_selection_set() if self.peek(TokenKind.BRACE_L) else None |
| 501 |
), |
| 502 |
loc=self.loc(start), |
| 503 |
) |
| 504 |
|
| 505 |
def parse_arguments(self, is_const: bool) -> List[ArgumentNode]: |
| 506 |
"""Arguments[Const]: (Argument[?Const]+)""" |
| 507 |
item = self.parse_const_argument if is_const else self.parse_argument |
| 508 |
return self.optional_many( |
| 509 |
TokenKind.PAREN_L, cast(Callable[[], ArgumentNode], item), TokenKind.PAREN_R |
| 510 |
) |
| 511 |
|
| 512 |
def parse_argument(self, is_const: bool = False) -> ArgumentNode: |
| 513 |
"""Argument[Const]: Name : Value[?Const]""" |
| 514 |
start = self._lexer.token |
| 515 |
name = self.parse_name() |
| 516 |
|
| 517 |
self.expect_token(TokenKind.COLON) |
| 518 |
return ArgumentNode( |
| 519 |
name=name, value=self.parse_value_literal(is_const), loc=self.loc(start) |
| 520 |
) |
| 521 |
|
| 522 |
def parse_const_argument(self) -> ConstArgumentNode: |
| 523 |
"""Argument[Const]: Name : Value[Const]""" |
| 524 |
return cast(ConstArgumentNode, self.parse_argument(True)) |
| 525 |
|
| 526 |
# Implement the parsing rules in the Fragments section. |
| 527 |
|
| 528 |
def parse_fragment(self) -> Union[FragmentSpreadNode, InlineFragmentNode]: |
| 529 |
"""Corresponds to both FragmentSpread and InlineFragment in the spec. |
| 530 |
|
| 531 |
FragmentSpread: ... FragmentName Directives? |
| 532 |
InlineFragment: ... TypeCondition? Directives? SelectionSet |
| 533 |
""" |
| 534 |
start = self._lexer.token |
| 535 |
self.expect_token(TokenKind.SPREAD) |
| 536 |
|
| 537 |
has_type_condition = self.expect_optional_keyword("on") |
| 538 |
if not has_type_condition and self.peek(TokenKind.NAME): |
| 539 |
return FragmentSpreadNode( |
| 540 |
name=self.parse_fragment_name(), |
| 541 |
directives=self.parse_directives(False), |
| 542 |
loc=self.loc(start), |
| 543 |
) |
| 544 |
return InlineFragmentNode( |
| 545 |
type_condition=self.parse_named_type() if has_type_condition else None, |
| 546 |
directives=self.parse_directives(False), |
| 547 |
selection_set=self.parse_selection_set(), |
| 548 |
loc=self.loc(start), |
| 549 |
) |
| 550 |
|
| 551 |
def parse_fragment_definition(self) -> FragmentDefinitionNode: |
| 552 |
"""FragmentDefinition""" |
| 553 |
start = self._lexer.token |
| 554 |
description = self.parse_description() |
| 555 |
self.expect_keyword("fragment") |
| 556 |
# Legacy support for defining variables within fragments changes |
| 557 |
# the grammar of FragmentDefinition |
| 558 |
if self._allow_legacy_fragment_variables: |
| 559 |
return FragmentDefinitionNode( |
| 560 |
description=description, |
| 561 |
name=self.parse_fragment_name(), |
| 562 |
variable_definitions=self.parse_variable_definitions(), |
| 563 |
type_condition=self.parse_type_condition(), |
| 564 |
directives=self.parse_directives(False), |
| 565 |
selection_set=self.parse_selection_set(), |
| 566 |
loc=self.loc(start), |
| 567 |
) |
| 568 |
return FragmentDefinitionNode( |
| 569 |
description=description, |
| 570 |
name=self.parse_fragment_name(), |
| 571 |
type_condition=self.parse_type_condition(), |
| 572 |
directives=self.parse_directives(False), |
| 573 |
selection_set=self.parse_selection_set(), |
| 574 |
loc=self.loc(start), |
| 575 |
) |
| 576 |
|
| 577 |
def parse_fragment_name(self) -> NameNode: |
| 578 |
"""FragmentName: Name but not ``on``""" |
| 579 |
if self._lexer.token.value == "on": |
| 580 |
raise self.unexpected() |
| 581 |
return self.parse_name() |
| 582 |
|
| 583 |
def parse_type_condition(self) -> NamedTypeNode: |
| 584 |
"""TypeCondition: NamedType""" |
| 585 |
self.expect_keyword("on") |
| 586 |
return self.parse_named_type() |
| 587 |
|
| 588 |
# Implement the parsing rules in the Values section. |
| 589 |
|
| 590 |
_parse_value_literal_method_names: Dict[TokenKind, str] = { |
| 591 |
TokenKind.BRACKET_L: "list", |
| 592 |
TokenKind.BRACE_L: "object", |
| 593 |
TokenKind.INT: "int", |
| 594 |
TokenKind.FLOAT: "float", |
| 595 |
TokenKind.STRING: "string_literal", |
| 596 |
TokenKind.BLOCK_STRING: "string_literal", |
| 597 |
TokenKind.NAME: "named_values", |
| 598 |
TokenKind.DOLLAR: "variable_value", |
| 599 |
} |
| 600 |
|
| 601 |
def parse_value_literal(self, is_const: bool) -> ValueNode: |
| 602 |
method_name = self._parse_value_literal_method_names.get(self._lexer.token.kind) |
| 603 |
if method_name: # pragma: no cover |
| 604 |
return getattr(self, f"parse_{method_name}")(is_const) |
| 605 |
raise self.unexpected() # pragma: no cover |
| 606 |
|
| 607 |
def parse_string_literal(self, _is_const: bool = False) -> StringValueNode: |
| 608 |
token = self._lexer.token |
| 609 |
self.advance_lexer() |
| 610 |
return StringValueNode( |
| 611 |
value=token.value, |
| 612 |
block=token.kind == TokenKind.BLOCK_STRING, |
| 613 |
loc=self.loc(token), |
| 614 |
) |
| 615 |
|
| 616 |
def parse_list(self, is_const: bool) -> ListValueNode: |
| 617 |
"""ListValue[Const]""" |
| 618 |
start = self._lexer.token |
| 619 |
item = partial(self.parse_value_literal, is_const) |
| 620 |
# noinspection PyTypeChecker |
| 621 |
return ListValueNode( |
| 622 |
values=self.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), |
| 623 |
loc=self.loc(start), |
| 624 |
) |
| 625 |
|
| 626 |
def parse_object_field(self, is_const: bool) -> ObjectFieldNode: |
| 627 |
start = self._lexer.token |
| 628 |
name = self.parse_name() |
| 629 |
self.expect_token(TokenKind.COLON) |
| 630 |
|
| 631 |
return ObjectFieldNode( |
| 632 |
name=name, value=self.parse_value_literal(is_const), loc=self.loc(start) |
| 633 |
) |
| 634 |
|
| 635 |
def parse_object(self, is_const: bool) -> ObjectValueNode: |
| 636 |
"""ObjectValue[Const]""" |
| 637 |
start = self._lexer.token |
| 638 |
item = partial(self.parse_object_field, is_const) |
| 639 |
return ObjectValueNode( |
| 640 |
fields=self.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R), |
| 641 |
loc=self.loc(start), |
| 642 |
) |
| 643 |
|
| 644 |
def parse_int(self, _is_const: bool = False) -> IntValueNode: |
| 645 |
token = self._lexer.token |
| 646 |
self.advance_lexer() |
| 647 |
return IntValueNode(value=token.value, loc=self.loc(token)) |
| 648 |
|
| 649 |
def parse_float(self, _is_const: bool = False) -> FloatValueNode: |
| 650 |
token = self._lexer.token |
| 651 |
self.advance_lexer() |
| 652 |
return FloatValueNode(value=token.value, loc=self.loc(token)) |
| 653 |
|
| 654 |
def parse_named_values(self, _is_const: bool = False) -> ValueNode: |
| 655 |
token = self._lexer.token |
| 656 |
value = token.value |
| 657 |
self.advance_lexer() |
| 658 |
if value == "true": |
| 659 |
return BooleanValueNode(value=True, loc=self.loc(token)) |
| 660 |
if value == "false": |
| 661 |
return BooleanValueNode(value=False, loc=self.loc(token)) |
| 662 |
if value == "null": |
| 663 |
return NullValueNode(loc=self.loc(token)) |
| 664 |
return EnumValueNode(value=value, loc=self.loc(token)) |
| 665 |
|
| 666 |
def parse_variable_value(self, is_const: bool) -> VariableNode: |
| 667 |
if is_const: |
| 668 |
variable_token = self.expect_token(TokenKind.DOLLAR) |
| 669 |
token = self._lexer.token |
| 670 |
if token.kind is TokenKind.NAME: |
| 671 |
var_name = token.value |
| 672 |
raise GraphQLSyntaxError( |
| 673 |
self._lexer.source, |
| 674 |
variable_token.start, |
| 675 |
f"Unexpected variable '${var_name}' in constant value.", |
| 676 |
) |
| 677 |
raise self.unexpected(variable_token) |
| 678 |
return self.parse_variable() |
| 679 |
|
| 680 |
def parse_const_value_literal(self) -> ConstValueNode: |
| 681 |
return cast(ConstValueNode, self.parse_value_literal(True)) |
| 682 |
|
| 683 |
# Implement the parsing rules in the Directives section. |
| 684 |
|
| 685 |
def parse_directives(self, is_const: bool) -> List[DirectiveNode]: |
| 686 |
"""Directives[Const]: Directive[?Const]+""" |
| 687 |
directives: List[DirectiveNode] = [] |
| 688 |
append = directives.append |
| 689 |
while self.peek(TokenKind.AT): |
| 690 |
append(self.parse_directive(is_const)) |
| 691 |
return directives |
| 692 |
|
| 693 |
def parse_const_directives(self) -> List[ConstDirectiveNode]: |
| 694 |
return cast(List[ConstDirectiveNode], self.parse_directives(True)) |
| 695 |
|
| 696 |
def parse_directive(self, is_const: bool) -> DirectiveNode: |
| 697 |
"""Directive[Const]: @ Name Arguments[?Const]?""" |
| 698 |
start = self._lexer.token |
| 699 |
self.expect_token(TokenKind.AT) |
| 700 |
return DirectiveNode( |
| 701 |
name=self.parse_name(), |
| 702 |
arguments=self.parse_arguments(is_const), |
| 703 |
loc=self.loc(start), |
| 704 |
) |
| 705 |
|
| 706 |
# Implement the parsing rules in the Types section. |
| 707 |
|
| 708 |
def parse_type_reference(self) -> TypeNode: |
| 709 |
"""Type: NamedType or ListType or NonNullType""" |
| 710 |
start = self._lexer.token |
| 711 |
type_: TypeNode |
| 712 |
if self.expect_optional_token(TokenKind.BRACKET_L): |
| 713 |
inner_type = self.parse_type_reference() |
| 714 |
self.expect_token(TokenKind.BRACKET_R) |
| 715 |
type_ = ListTypeNode(type=inner_type, loc=self.loc(start)) |
| 716 |
else: |
| 717 |
type_ = self.parse_named_type() |
| 718 |
if self.expect_optional_token(TokenKind.BANG): |
| 719 |
return NonNullTypeNode(type=type_, loc=self.loc(start)) |
| 720 |
return type_ |
| 721 |
|
| 722 |
def parse_named_type(self) -> NamedTypeNode: |
| 723 |
"""NamedType: Name""" |
| 724 |
start = self._lexer.token |
| 725 |
return NamedTypeNode(name=self.parse_name(), loc=self.loc(start)) |
| 726 |
|
| 727 |
# Implement the parsing rules in the Type Definition section. |
| 728 |
|
| 729 |
_parse_type_extension_method_names: Dict[str, str] = { |
| 730 |
"schema": "schema_extension", |
| 731 |
"scalar": "scalar_type_extension", |
| 732 |
"type": "object_type_extension", |
| 733 |
"interface": "interface_type_extension", |
| 734 |
"union": "union_type_extension", |
| 735 |
"enum": "enum_type_extension", |
| 736 |
"input": "input_object_type_extension", |
| 737 |
} |
| 738 |
|
| 739 |
def parse_type_system_extension(self) -> TypeSystemExtensionNode: |
| 740 |
"""TypeSystemExtension""" |
| 741 |
keyword_token = self._lexer.lookahead() |
| 742 |
if keyword_token.kind == TokenKind.NAME: |
| 743 |
method_name = self._parse_type_extension_method_names.get( |
| 744 |
cast(str, keyword_token.value) |
| 745 |
) |
| 746 |
if method_name: # pragma: no cover |
| 747 |
return getattr(self, f"parse_{method_name}")() |
| 748 |
if ( |
| 749 |
keyword_token.value == "directive" |
| 750 |
and self._experimental_directives_on_directive_definitions |
| 751 |
): |
| 752 |
return self.parse_directive_definition_extension() |
| 753 |
raise self.unexpected(keyword_token) |
| 754 |
|
| 755 |
def peek_description(self) -> bool: |
| 756 |
return self.peek(TokenKind.STRING) or self.peek(TokenKind.BLOCK_STRING) |
| 757 |
|
| 758 |
def parse_description(self) -> Optional[StringValueNode]: |
| 759 |
"""Description: StringValue""" |
| 760 |
if self.peek_description(): |
| 761 |
return self.parse_string_literal() |
| 762 |
return None |
| 763 |
|
| 764 |
def parse_schema_definition(self) -> SchemaDefinitionNode: |
| 765 |
"""SchemaDefinition""" |
| 766 |
start = self._lexer.token |
| 767 |
description = self.parse_description() |
| 768 |
self.expect_keyword("schema") |
| 769 |
directives = self.parse_const_directives() |
| 770 |
operation_types = self.many( |
| 771 |
TokenKind.BRACE_L, self.parse_operation_type_definition, TokenKind.BRACE_R |
| 772 |
) |
| 773 |
return SchemaDefinitionNode( |
| 774 |
description=description, |
| 775 |
directives=directives, |
| 776 |
operation_types=operation_types, |
| 777 |
loc=self.loc(start), |
| 778 |
) |
| 779 |
|
| 780 |
def parse_operation_type_definition(self) -> OperationTypeDefinitionNode: |
| 781 |
"""OperationTypeDefinition: OperationType : NamedType""" |
| 782 |
start = self._lexer.token |
| 783 |
operation = self.parse_operation_type() |
| 784 |
self.expect_token(TokenKind.COLON) |
| 785 |
type_ = self.parse_named_type() |
| 786 |
return OperationTypeDefinitionNode( |
| 787 |
operation=operation, type=type_, loc=self.loc(start) |
| 788 |
) |
| 789 |
|
| 790 |
def parse_scalar_type_definition(self) -> ScalarTypeDefinitionNode: |
| 791 |
"""ScalarTypeDefinition: Description? scalar Name Directives[Const]?""" |
| 792 |
start = self._lexer.token |
| 793 |
description = self.parse_description() |
| 794 |
self.expect_keyword("scalar") |
| 795 |
name = self.parse_name() |
| 796 |
directives = self.parse_const_directives() |
| 797 |
return ScalarTypeDefinitionNode( |
| 798 |
description=description, |
| 799 |
name=name, |
| 800 |
directives=directives, |
| 801 |
loc=self.loc(start), |
| 802 |
) |
| 803 |
|
| 804 |
def parse_object_type_definition(self) -> ObjectTypeDefinitionNode: |
| 805 |
"""ObjectTypeDefinition""" |
| 806 |
start = self._lexer.token |
| 807 |
description = self.parse_description() |
| 808 |
self.expect_keyword("type") |
| 809 |
name = self.parse_name() |
| 810 |
interfaces = self.parse_implements_interfaces() |
| 811 |
directives = self.parse_const_directives() |
| 812 |
fields = self.parse_fields_definition() |
| 813 |
return ObjectTypeDefinitionNode( |
| 814 |
description=description, |
| 815 |
name=name, |
| 816 |
interfaces=interfaces, |
| 817 |
directives=directives, |
| 818 |
fields=fields, |
| 819 |
loc=self.loc(start), |
| 820 |
) |
| 821 |
|
| 822 |
def parse_implements_interfaces(self) -> List[NamedTypeNode]: |
| 823 |
"""ImplementsInterfaces""" |
| 824 |
return ( |
| 825 |
self.delimited_many(TokenKind.AMP, self.parse_named_type) |
| 826 |
if self.expect_optional_keyword("implements") |
| 827 |
else [] |
| 828 |
) |
| 829 |
|
| 830 |
def parse_fields_definition(self) -> List[FieldDefinitionNode]: |
| 831 |
"""FieldsDefinition: {FieldDefinition+}""" |
| 832 |
return self.optional_many( |
| 833 |
TokenKind.BRACE_L, self.parse_field_definition, TokenKind.BRACE_R |
| 834 |
) |
| 835 |
|
| 836 |
def parse_field_definition(self) -> FieldDefinitionNode: |
| 837 |
"""FieldDefinition""" |
| 838 |
start = self._lexer.token |
| 839 |
description = self.parse_description() |
| 840 |
name = self.parse_name() |
| 841 |
args = self.parse_argument_defs() |
| 842 |
self.expect_token(TokenKind.COLON) |
| 843 |
type_ = self.parse_type_reference() |
| 844 |
directives = self.parse_const_directives() |
| 845 |
return FieldDefinitionNode( |
| 846 |
description=description, |
| 847 |
name=name, |
| 848 |
arguments=args, |
| 849 |
type=type_, |
| 850 |
directives=directives, |
| 851 |
loc=self.loc(start), |
| 852 |
) |
| 853 |
|
| 854 |
def parse_argument_defs(self) -> List[InputValueDefinitionNode]: |
| 855 |
"""ArgumentsDefinition: (InputValueDefinition+)""" |
| 856 |
return self.optional_many( |
| 857 |
TokenKind.PAREN_L, self.parse_input_value_def, TokenKind.PAREN_R |
| 858 |
) |
| 859 |
|
| 860 |
def parse_input_value_def(self) -> InputValueDefinitionNode: |
| 861 |
"""InputValueDefinition""" |
| 862 |
start = self._lexer.token |
| 863 |
description = self.parse_description() |
| 864 |
name = self.parse_name() |
| 865 |
self.expect_token(TokenKind.COLON) |
| 866 |
type_ = self.parse_type_reference() |
| 867 |
default_value = ( |
| 868 |
self.parse_const_value_literal() |
| 869 |
if self.expect_optional_token(TokenKind.EQUALS) |
| 870 |
else None |
| 871 |
) |
| 872 |
directives = self.parse_const_directives() |
| 873 |
return InputValueDefinitionNode( |
| 874 |
description=description, |
| 875 |
name=name, |
| 876 |
type=type_, |
| 877 |
default_value=default_value, |
| 878 |
directives=directives, |
| 879 |
loc=self.loc(start), |
| 880 |
) |
| 881 |
|
| 882 |
def parse_interface_type_definition(self) -> InterfaceTypeDefinitionNode: |
| 883 |
"""InterfaceTypeDefinition""" |
| 884 |
start = self._lexer.token |
| 885 |
description = self.parse_description() |
| 886 |
self.expect_keyword("interface") |
| 887 |
name = self.parse_name() |
| 888 |
interfaces = self.parse_implements_interfaces() |
| 889 |
directives = self.parse_const_directives() |
| 890 |
fields = self.parse_fields_definition() |
| 891 |
return InterfaceTypeDefinitionNode( |
| 892 |
description=description, |
| 893 |
name=name, |
| 894 |
interfaces=interfaces, |
| 895 |
directives=directives, |
| 896 |
fields=fields, |
| 897 |
loc=self.loc(start), |
| 898 |
) |
| 899 |
|
| 900 |
def parse_union_type_definition(self) -> UnionTypeDefinitionNode: |
| 901 |
"""UnionTypeDefinition""" |
| 902 |
start = self._lexer.token |
| 903 |
description = self.parse_description() |
| 904 |
self.expect_keyword("union") |
| 905 |
name = self.parse_name() |
| 906 |
directives = self.parse_const_directives() |
| 907 |
types = self.parse_union_member_types() |
| 908 |
return UnionTypeDefinitionNode( |
| 909 |
description=description, |
| 910 |
name=name, |
| 911 |
directives=directives, |
| 912 |
types=types, |
| 913 |
loc=self.loc(start), |
| 914 |
) |
| 915 |
|
| 916 |
def parse_union_member_types(self) -> List[NamedTypeNode]: |
| 917 |
"""UnionMemberTypes""" |
| 918 |
return ( |
| 919 |
self.delimited_many(TokenKind.PIPE, self.parse_named_type) |
| 920 |
if self.expect_optional_token(TokenKind.EQUALS) |
| 921 |
else [] |
| 922 |
) |
| 923 |
|
| 924 |
def parse_enum_type_definition(self) -> EnumTypeDefinitionNode: |
| 925 |
"""UnionTypeDefinition""" |
| 926 |
start = self._lexer.token |
| 927 |
description = self.parse_description() |
| 928 |
self.expect_keyword("enum") |
| 929 |
name = self.parse_name() |
| 930 |
directives = self.parse_const_directives() |
| 931 |
values = self.parse_enum_values_definition() |
| 932 |
return EnumTypeDefinitionNode( |
| 933 |
description=description, |
| 934 |
name=name, |
| 935 |
directives=directives, |
| 936 |
values=values, |
| 937 |
loc=self.loc(start), |
| 938 |
) |
| 939 |
|
| 940 |
def parse_enum_values_definition(self) -> List[EnumValueDefinitionNode]: |
| 941 |
"""EnumValuesDefinition: {EnumValueDefinition+}""" |
| 942 |
return self.optional_many( |
| 943 |
TokenKind.BRACE_L, self.parse_enum_value_definition, TokenKind.BRACE_R |
| 944 |
) |
| 945 |
|
| 946 |
def parse_enum_value_definition(self) -> EnumValueDefinitionNode: |
| 947 |
"""EnumValueDefinition: Description? EnumValue Directives[Const]?""" |
| 948 |
start = self._lexer.token |
| 949 |
description = self.parse_description() |
| 950 |
name = self.parse_enum_value_name() |
| 951 |
directives = self.parse_const_directives() |
| 952 |
return EnumValueDefinitionNode( |
| 953 |
description=description, |
| 954 |
name=name, |
| 955 |
directives=directives, |
| 956 |
loc=self.loc(start), |
| 957 |
) |
| 958 |
|
| 959 |
def parse_enum_value_name(self) -> NameNode: |
| 960 |
"""EnumValue: Name but not ``true``, ``false`` or ``null``""" |
| 961 |
if self._lexer.token.value in ("true", "false", "null"): |
| 962 |
raise GraphQLSyntaxError( |
| 963 |
self._lexer.source, |
| 964 |
self._lexer.token.start, |
| 965 |
f"{get_token_desc(self._lexer.token)} is reserved" |
| 966 |
" and cannot be used for an enum value.", |
| 967 |
) |
| 968 |
return self.parse_name() |
| 969 |
|
| 970 |
def parse_input_object_type_definition(self) -> InputObjectTypeDefinitionNode: |
| 971 |
"""InputObjectTypeDefinition""" |
| 972 |
start = self._lexer.token |
| 973 |
description = self.parse_description() |
| 974 |
self.expect_keyword("input") |
| 975 |
name = self.parse_name() |
| 976 |
directives = self.parse_const_directives() |
| 977 |
fields = self.parse_input_fields_definition() |
| 978 |
return InputObjectTypeDefinitionNode( |
| 979 |
description=description, |
| 980 |
name=name, |
| 981 |
directives=directives, |
| 982 |
fields=fields, |
| 983 |
loc=self.loc(start), |
| 984 |
) |
| 985 |
|
| 986 |
def parse_input_fields_definition(self) -> List[InputValueDefinitionNode]: |
| 987 |
"""InputFieldsDefinition: {InputValueDefinition+}""" |
| 988 |
return self.optional_many( |
| 989 |
TokenKind.BRACE_L, self.parse_input_value_def, TokenKind.BRACE_R |
| 990 |
) |
| 991 |
|
| 992 |
def parse_schema_extension(self) -> SchemaExtensionNode: |
| 993 |
"""SchemaExtension""" |
| 994 |
start = self._lexer.token |
| 995 |
self.expect_keyword("extend") |
| 996 |
self.expect_keyword("schema") |
| 997 |
directives = self.parse_const_directives() |
| 998 |
operation_types = self.optional_many( |
| 999 |
TokenKind.BRACE_L, self.parse_operation_type_definition, TokenKind.BRACE_R |
| 1000 |
) |
| 1001 |
if not directives and not operation_types: |
| 1002 |
raise self.unexpected() |
| 1003 |
return SchemaExtensionNode( |
| 1004 |
directives=directives, operation_types=operation_types, loc=self.loc(start) |
| 1005 |
) |
| 1006 |
|
| 1007 |
def parse_scalar_type_extension(self) -> ScalarTypeExtensionNode: |
| 1008 |
"""ScalarTypeExtension""" |
| 1009 |
start = self._lexer.token |
| 1010 |
self.expect_keyword("extend") |
| 1011 |
self.expect_keyword("scalar") |
| 1012 |
name = self.parse_name() |
| 1013 |
directives = self.parse_const_directives() |
| 1014 |
if not directives: |
| 1015 |
raise self.unexpected() |
| 1016 |
return ScalarTypeExtensionNode( |
| 1017 |
name=name, directives=directives, loc=self.loc(start) |
| 1018 |
) |
| 1019 |
|
| 1020 |
def parse_object_type_extension(self) -> ObjectTypeExtensionNode: |
| 1021 |
"""ObjectTypeExtension""" |
| 1022 |
start = self._lexer.token |
| 1023 |
self.expect_keyword("extend") |
| 1024 |
self.expect_keyword("type") |
| 1025 |
name = self.parse_name() |
| 1026 |
interfaces = self.parse_implements_interfaces() |
| 1027 |
directives = self.parse_const_directives() |
| 1028 |
fields = self.parse_fields_definition() |
| 1029 |
if not (interfaces or directives or fields): |
| 1030 |
raise self.unexpected() |
| 1031 |
return ObjectTypeExtensionNode( |
| 1032 |
name=name, |
| 1033 |
interfaces=interfaces, |
| 1034 |
directives=directives, |
| 1035 |
fields=fields, |
| 1036 |
loc=self.loc(start), |
| 1037 |
) |
| 1038 |
|
| 1039 |
def parse_interface_type_extension(self) -> InterfaceTypeExtensionNode: |
| 1040 |
"""InterfaceTypeExtension""" |
| 1041 |
start = self._lexer.token |
| 1042 |
self.expect_keyword("extend") |
| 1043 |
self.expect_keyword("interface") |
| 1044 |
name = self.parse_name() |
| 1045 |
interfaces = self.parse_implements_interfaces() |
| 1046 |
directives = self.parse_const_directives() |
| 1047 |
fields = self.parse_fields_definition() |
| 1048 |
if not (interfaces or directives or fields): |
| 1049 |
raise self.unexpected() |
| 1050 |
return InterfaceTypeExtensionNode( |
| 1051 |
name=name, |
| 1052 |
interfaces=interfaces, |
| 1053 |
directives=directives, |
| 1054 |
fields=fields, |
| 1055 |
loc=self.loc(start), |
| 1056 |
) |
| 1057 |
|
| 1058 |
def parse_union_type_extension(self) -> UnionTypeExtensionNode: |
| 1059 |
"""UnionTypeExtension""" |
| 1060 |
start = self._lexer.token |
| 1061 |
self.expect_keyword("extend") |
| 1062 |
self.expect_keyword("union") |
| 1063 |
name = self.parse_name() |
| 1064 |
directives = self.parse_const_directives() |
| 1065 |
types = self.parse_union_member_types() |
| 1066 |
if not (directives or types): |
| 1067 |
raise self.unexpected() |
| 1068 |
return UnionTypeExtensionNode( |
| 1069 |
name=name, directives=directives, types=types, loc=self.loc(start) |
| 1070 |
) |
| 1071 |
|
| 1072 |
def parse_enum_type_extension(self) -> EnumTypeExtensionNode: |
| 1073 |
"""EnumTypeExtension""" |
| 1074 |
start = self._lexer.token |
| 1075 |
self.expect_keyword("extend") |
| 1076 |
self.expect_keyword("enum") |
| 1077 |
name = self.parse_name() |
| 1078 |
directives = self.parse_const_directives() |
| 1079 |
values = self.parse_enum_values_definition() |
| 1080 |
if not (directives or values): |
| 1081 |
raise self.unexpected() |
| 1082 |
return EnumTypeExtensionNode( |
| 1083 |
name=name, directives=directives, values=values, loc=self.loc(start) |
| 1084 |
) |
| 1085 |
|
| 1086 |
def parse_input_object_type_extension(self) -> InputObjectTypeExtensionNode: |
| 1087 |
"""InputObjectTypeExtension""" |
| 1088 |
start = self._lexer.token |
| 1089 |
self.expect_keyword("extend") |
| 1090 |
self.expect_keyword("input") |
| 1091 |
name = self.parse_name() |
| 1092 |
directives = self.parse_const_directives() |
| 1093 |
fields = self.parse_input_fields_definition() |
| 1094 |
if not (directives or fields): |
| 1095 |
raise self.unexpected() |
| 1096 |
return InputObjectTypeExtensionNode( |
| 1097 |
name=name, directives=directives, fields=fields, loc=self.loc(start) |
| 1098 |
) |
| 1099 |
|
| 1100 |
def parse_directive_definition_extension(self) -> DirectiveExtensionNode: |
| 1101 |
"""DirectiveDefinitionExtension""" |
| 1102 |
start = self._lexer.token |
| 1103 |
self.expect_keyword("extend") |
| 1104 |
self.expect_keyword("directive") |
| 1105 |
self.expect_token(TokenKind.AT) |
| 1106 |
name = self.parse_name() |
| 1107 |
directives = self.parse_const_directives() |
| 1108 |
if not directives: |
| 1109 |
raise self.unexpected() |
| 1110 |
return DirectiveExtensionNode( |
| 1111 |
name=name, |
| 1112 |
directives=directives, |
| 1113 |
loc=self.loc(start), |
| 1114 |
) |
| 1115 |
|
| 1116 |
def parse_directive_definition(self) -> DirectiveDefinitionNode: |
| 1117 |
"""DirectiveDefinition""" |
| 1118 |
start = self._lexer.token |
| 1119 |
description = self.parse_description() |
| 1120 |
self.expect_keyword("directive") |
| 1121 |
self.expect_token(TokenKind.AT) |
| 1122 |
name = self.parse_name() |
| 1123 |
args = self.parse_argument_defs() |
| 1124 |
directives = ( |
| 1125 |
self.parse_const_directives() |
| 1126 |
if self._experimental_directives_on_directive_definitions |
| 1127 |
else [] |
| 1128 |
) |
| 1129 |
repeatable = self.expect_optional_keyword("repeatable") |
| 1130 |
self.expect_keyword("on") |
| 1131 |
locations = self.parse_directive_locations() |
| 1132 |
return DirectiveDefinitionNode( |
| 1133 |
description=description, |
| 1134 |
name=name, |
| 1135 |
arguments=args, |
| 1136 |
directives=directives, |
| 1137 |
repeatable=repeatable, |
| 1138 |
locations=locations, |
| 1139 |
loc=self.loc(start), |
| 1140 |
) |
| 1141 |
|
| 1142 |
def parse_directive_locations(self) -> List[NameNode]: |
| 1143 |
"""DirectiveLocations""" |
| 1144 |
return self.delimited_many(TokenKind.PIPE, self.parse_directive_location) |
| 1145 |
|
| 1146 |
def parse_directive_location(self) -> NameNode: |
| 1147 |
"""DirectiveLocation""" |
| 1148 |
start = self._lexer.token |
| 1149 |
name = self.parse_name() |
| 1150 |
if name.value in DirectiveLocation.__members__: |
| 1151 |
return name |
| 1152 |
raise self.unexpected(start) |
| 1153 |
|
| 1154 |
# Schema Coordinates |
| 1155 |
|
| 1156 |
def parse_schema_coordinate(self) -> SchemaCoordinateNode: |
| 1157 |
"""SchemaCoordinate |
| 1158 |
|
| 1159 |
- Name |
| 1160 |
- Name . Name |
| 1161 |
- Name . Name ( Name : ) |
| 1162 |
- @ Name |
| 1163 |
- @ Name ( Name : ) |
| 1164 |
""" |
| 1165 |
start = self._lexer.token |
| 1166 |
of_directive = self.expect_optional_token(TokenKind.AT) |
| 1167 |
name = self.parse_name() |
| 1168 |
member_name: Optional[NameNode] = None |
| 1169 |
if not of_directive and self.expect_optional_token(TokenKind.DOT): |
| 1170 |
member_name = self.parse_name() |
| 1171 |
argument_name: Optional[NameNode] = None |
| 1172 |
if (of_directive or member_name) and self.expect_optional_token( |
| 1173 |
TokenKind.PAREN_L |
| 1174 |
): |
| 1175 |
argument_name = self.parse_name() |
| 1176 |
self.expect_token(TokenKind.COLON) |
| 1177 |
self.expect_token(TokenKind.PAREN_R) |
| 1178 |
|
| 1179 |
if of_directive: |
| 1180 |
if argument_name: |
| 1181 |
return DirectiveArgumentCoordinateNode( |
| 1182 |
name=name, argument_name=argument_name, loc=self.loc(start) |
| 1183 |
) |
| 1184 |
return DirectiveCoordinateNode(name=name, loc=self.loc(start)) |
| 1185 |
if member_name: |
| 1186 |
if argument_name: |
| 1187 |
return ArgumentCoordinateNode( |
| 1188 |
name=name, |
| 1189 |
field_name=member_name, |
| 1190 |
argument_name=argument_name, |
| 1191 |
loc=self.loc(start), |
| 1192 |
) |
| 1193 |
return MemberCoordinateNode( |
| 1194 |
name=name, member_name=member_name, loc=self.loc(start) |
| 1195 |
) |
| 1196 |
return TypeCoordinateNode(name=name, loc=self.loc(start)) |
| 1197 |
|
| 1198 |
# Core parsing utility functions |
| 1199 |
|
| 1200 |
def loc(self, start_token: Token) -> Optional[Location]: |
| 1201 |
"""Return a location object. |
| 1202 |
|
| 1203 |
Used to identify the place in the source that created a given parsed object. |
| 1204 |
""" |
| 1205 |
if not self._no_location: |
| 1206 |
end_token = self._lexer.last_token |
| 1207 |
source = self._lexer.source |
| 1208 |
return Location(start_token, end_token, source) |
| 1209 |
return None |
| 1210 |
|
| 1211 |
def peek(self, kind: TokenKind) -> bool: |
| 1212 |
"""Determine if the next token is of a given kind""" |
| 1213 |
return self._lexer.token.kind == kind |
| 1214 |
|
| 1215 |
def expect_token(self, kind: TokenKind) -> Token: |
| 1216 |
"""Expect the next token to be of the given kind. |
| 1217 |
|
| 1218 |
If the next token is of the given kind, return that token after advancing the |
| 1219 |
lexer. Otherwise, do not change the parser state and throw an error. |
| 1220 |
""" |
| 1221 |
token = self._lexer.token |
| 1222 |
if token.kind == kind: |
| 1223 |
self.advance_lexer() |
| 1224 |
return token |
| 1225 |
|
| 1226 |
raise GraphQLSyntaxError( |
| 1227 |
self._lexer.source, |
| 1228 |
token.start, |
| 1229 |
f"Expected {get_token_kind_desc(kind)}, found {get_token_desc(token)}.", |
| 1230 |
) |
| 1231 |
|
| 1232 |
def expect_optional_token(self, kind: TokenKind) -> bool: |
| 1233 |
"""Expect the next token optionally to be of the given kind. |
| 1234 |
|
| 1235 |
If the next token is of the given kind, return True after advancing the lexer. |
| 1236 |
Otherwise, do not change the parser state and return False. |
| 1237 |
""" |
| 1238 |
token = self._lexer.token |
| 1239 |
if token.kind == kind: |
| 1240 |
self.advance_lexer() |
| 1241 |
return True |
| 1242 |
|
| 1243 |
return False |
| 1244 |
|
| 1245 |
def expect_keyword(self, value: str) -> None: |
| 1246 |
"""Expect the next token to be a given keyword. |
| 1247 |
|
| 1248 |
If the next token is a given keyword, advance the lexer. |
| 1249 |
Otherwise, do not change the parser state and throw an error. |
| 1250 |
""" |
| 1251 |
token = self._lexer.token |
| 1252 |
if token.kind == TokenKind.NAME and token.value == value: |
| 1253 |
self.advance_lexer() |
| 1254 |
else: |
| 1255 |
raise GraphQLSyntaxError( |
| 1256 |
self._lexer.source, |
| 1257 |
token.start, |
| 1258 |
f"Expected '{value}', found {get_token_desc(token)}.", |
| 1259 |
) |
| 1260 |
|
| 1261 |
def expect_optional_keyword(self, value: str) -> bool: |
| 1262 |
"""Expect the next token optionally to be a given keyword. |
| 1263 |
|
| 1264 |
If the next token is a given keyword, return True after advancing the lexer. |
| 1265 |
Otherwise, do not change the parser state and return False. |
| 1266 |
""" |
| 1267 |
token = self._lexer.token |
| 1268 |
if token.kind == TokenKind.NAME and token.value == value: |
| 1269 |
self.advance_lexer() |
| 1270 |
return True |
| 1271 |
|
| 1272 |
return False |
| 1273 |
|
| 1274 |
def unexpected(self, at_token: Optional[Token] = None) -> GraphQLError: |
| 1275 |
"""Create an error when an unexpected lexed token is encountered.""" |
| 1276 |
token = at_token or self._lexer.token |
| 1277 |
return GraphQLSyntaxError( |
| 1278 |
self._lexer.source, token.start, f"Unexpected {get_token_desc(token)}." |
| 1279 |
) |
| 1280 |
|
| 1281 |
def any( |
| 1282 |
self, open_kind: TokenKind, parse_fn: Callable[[], T], close_kind: TokenKind |
| 1283 |
) -> List[T]: |
| 1284 |
"""Fetch any matching nodes, possibly none. |
| 1285 |
|
| 1286 |
Returns a possibly empty list of parse nodes, determined by the ``parse_fn``. |
| 1287 |
This list begins with a lex token of ``open_kind`` and ends with a lex token of |
| 1288 |
``close_kind``. Advances the parser to the next lex token after the closing |
| 1289 |
token. |
| 1290 |
""" |
| 1291 |
self.expect_token(open_kind) |
| 1292 |
nodes: List[T] = [] |
| 1293 |
append = nodes.append |
| 1294 |
expect_optional_token = partial(self.expect_optional_token, close_kind) |
| 1295 |
while not expect_optional_token(): |
| 1296 |
append(parse_fn()) |
| 1297 |
return nodes |
| 1298 |
|
| 1299 |
def optional_many( |
| 1300 |
self, open_kind: TokenKind, parse_fn: Callable[[], T], close_kind: TokenKind |
| 1301 |
) -> List[T]: |
| 1302 |
"""Fetch matching nodes, maybe none. |
| 1303 |
|
| 1304 |
Returns a list of parse nodes, determined by the ``parse_fn``. It can be empty |
| 1305 |
only if the open token is missing, otherwise it will always return a non-empty |
| 1306 |
list that begins with a lex token of ``open_kind`` and ends with a lex token of |
| 1307 |
``close_kind``. Advances the parser to the next lex token after the closing |
| 1308 |
token. |
| 1309 |
""" |
| 1310 |
if self.expect_optional_token(open_kind): |
| 1311 |
nodes = [parse_fn()] |
| 1312 |
append = nodes.append |
| 1313 |
expect_optional_token = partial(self.expect_optional_token, close_kind) |
| 1314 |
while not expect_optional_token(): |
| 1315 |
append(parse_fn()) |
| 1316 |
return nodes |
| 1317 |
return [] |
| 1318 |
|
| 1319 |
def many( |
| 1320 |
self, open_kind: TokenKind, parse_fn: Callable[[], T], close_kind: TokenKind |
| 1321 |
) -> List[T]: |
| 1322 |
"""Fetch matching nodes, at least one. |
| 1323 |
|
| 1324 |
Returns a non-empty list of parse nodes, determined by the ``parse_fn``. This |
| 1325 |
list begins with a lex token of ``open_kind`` and ends with a lex token of |
| 1326 |
``close_kind``. Advances the parser to the next lex token after the closing |
| 1327 |
token. |
| 1328 |
""" |
| 1329 |
self.expect_token(open_kind) |
| 1330 |
nodes = [parse_fn()] |
| 1331 |
append = nodes.append |
| 1332 |
expect_optional_token = partial(self.expect_optional_token, close_kind) |
| 1333 |
while not expect_optional_token(): |
| 1334 |
append(parse_fn()) |
| 1335 |
return nodes |
| 1336 |
|
| 1337 |
def delimited_many( |
| 1338 |
self, delimiter_kind: TokenKind, parse_fn: Callable[[], T] |
| 1339 |
) -> List[T]: |
| 1340 |
"""Fetch many delimited nodes. |
| 1341 |
|
| 1342 |
Returns a non-empty list of parse nodes, determined by the ``parse_fn``. This |
| 1343 |
list may begin with a lex token of ``delimiter_kind`` followed by items |
| 1344 |
separated by lex tokens of ``delimiter_kind``. Advances the parser to the next |
| 1345 |
lex token after the last item in the list. |
| 1346 |
""" |
| 1347 |
expect_optional_token = partial(self.expect_optional_token, delimiter_kind) |
| 1348 |
expect_optional_token() |
| 1349 |
nodes: List[T] = [] |
| 1350 |
append = nodes.append |
| 1351 |
while True: |
| 1352 |
append(parse_fn()) |
| 1353 |
if not expect_optional_token(): |
| 1354 |
break |
| 1355 |
return nodes |
| 1356 |
|
| 1357 |
def advance_lexer(self) -> None: |
| 1358 |
"""Advance the lexer. |
| 1359 |
|
| 1360 |
Counts every token that is consumed toward ``max_tokens``, including the |
| 1361 |
comment tokens that the lexer skips over between the previously focused token |
| 1362 |
and the new one. Comments are read and allocated as ``Token`` objects (and |
| 1363 |
chained into the token list) but are not returned by the lexer, so counting |
| 1364 |
only the returned tokens would let a comment-padded document bypass |
| 1365 |
``max_tokens`` while still allocating one token per comment. |
| 1366 |
""" |
| 1367 |
lexer = self._lexer |
| 1368 |
token = lexer.advance() |
| 1369 |
# Count the comment tokens that were skipped since the previously focused |
| 1370 |
# token. They are the nodes strictly between ``last_token`` and ``token`` in |
| 1371 |
# the token linked-list (the lexer only ever skips comments). |
| 1372 |
skipped = lexer.last_token.next |
| 1373 |
while skipped is not None and skipped is not token: |
| 1374 |
self._token_counter += 1 |
| 1375 |
skipped = skipped.next |
| 1376 |
if token.kind is not TokenKind.EOF: |
| 1377 |
self._token_counter += 1 |
| 1378 |
max_tokens = self._max_tokens |
| 1379 |
if max_tokens is not None and self._token_counter > max_tokens: |
| 1380 |
raise GraphQLSyntaxError( |
| 1381 |
lexer.source, |
| 1382 |
token.start, |
| 1383 |
f"Document contains more than {max_tokens} tokens. Parsing aborted.", |
| 1384 |
) |
| 1385 |
|
| 1386 |
|
| 1387 |
def get_token_desc(token: Token) -> str: |
| 1388 |
"""Describe a token as a string for debugging.""" |
| 1389 |
value = token.value |
| 1390 |
return get_token_kind_desc(token.kind) + ( |
| 1391 |
f" '{value}'" if value is not None else "" |
| 1392 |
) |
| 1393 |
|
| 1394 |
|
| 1395 |
def get_token_kind_desc(kind: TokenKind) -> str: |
| 1396 |
"""Describe a token kind as a string for debugging.""" |
| 1397 |
return f"'{kind.value}'" if is_punctuator_token_kind(kind) else kind.value |