Debian Codegraph @

src/graphql/language/schema_coordinate_lexer.py

raw
1 from ..error import GraphQLSyntaxError
2 from .ast import Token
3 from .character_classes import is_name_start
4 from .lexer import Lexer
5 from .token_kind import TokenKind
6
7 __all__ = ["SchemaCoordinateLexer"]
8
9
10 _KIND_FOR_PUNCT = {
11 ".": TokenKind.DOT,
12 "(": TokenKind.PAREN_L,
13 ")": TokenKind.PAREN_R,
14 ":": TokenKind.COLON,
15 "@": TokenKind.AT,
16 }
17
18
19 class SchemaCoordinateLexer(Lexer):
20 """GraphQL Schema Coordinate Lexer
21
22 A SchemaCoordinateLexer is a stateful stream generator in that every time it is
23 advanced, it returns the next token in the Source. Assuming the source lexes, the
24 final Token emitted by the lexer will be of kind EOF, after which the lexer will
25 repeatedly return the same EOF token whenever called.
26
27 Unlike the regular Lexer, this lexer uses a restricted syntax that does not allow
28 any ignored tokens (such as whitespace or comments). Since a schema coordinate may
29 not contain a newline, the line is always 1 and the line start is always 0.
30 """
31
32 def read_next_token(self, start: int) -> Token:
33 """Get the next token from the source starting at the given position.
34
35 This lexes punctuators and names only, raising a syntax error on any other
36 character (including ignored tokens such as whitespace and comments).
37 """
38 body = self.source.body
39 body_length = len(body)
40 position = start
41
42 if position < body_length:
43 char = body[position]
44
45 kind = _KIND_FOR_PUNCT.get(char)
46 if kind:
47 return self.create_token(kind, position, position + 1)
48
49 if is_name_start(char):
50 return self.read_name(position)
51
52 raise GraphQLSyntaxError(
53 self.source,
54 position,
55 f"Invalid character: {self.print_code_point_at(position)}.",
56 )
57
58 return self.create_token(TokenKind.EOF, body_length, body_length)