| 1 |
from typing import List, NamedTuple, Optional |
| 2 |
|
| 3 |
from ..error import GraphQLSyntaxError |
| 4 |
from .ast import Token |
| 5 |
from .block_string import dedent_block_string_lines |
| 6 |
from .character_classes import is_digit, is_name_start, is_name_continue |
| 7 |
from .source import Source |
| 8 |
from .token_kind import TokenKind |
| 9 |
|
| 10 |
__all__ = ["Lexer", "is_punctuator_token_kind"] |
| 11 |
|
| 12 |
|
| 13 |
class EscapeSequence(NamedTuple): |
| 14 |
"""The string value and lexed size of an escape sequence.""" |
| 15 |
|
| 16 |
value: str |
| 17 |
size: int |
| 18 |
|
| 19 |
|
| 20 |
class Lexer: |
| 21 |
"""GraphQL Lexer |
| 22 |
|
| 23 |
A Lexer is a stateful stream generator in that every time it is advanced, it returns |
| 24 |
the next token in the Source. Assuming the source lexes, the final Token emitted by |
| 25 |
the lexer will be of kind EOF, after which the lexer will repeatedly return the same |
| 26 |
EOF token whenever called. |
| 27 |
""" |
| 28 |
|
| 29 |
def __init__(self, source: Source): |
| 30 |
"""Given a Source object, initialize a Lexer for that source.""" |
| 31 |
self.source = source |
| 32 |
self.token = self.last_token = Token(TokenKind.SOF, 0, 0, 0, 0) |
| 33 |
self.line, self.line_start = 1, 0 |
| 34 |
|
| 35 |
def advance(self) -> Token: |
| 36 |
"""Advance the token stream to the next non-ignored token.""" |
| 37 |
self.last_token = self.token |
| 38 |
token = self.token = self.lookahead() |
| 39 |
return token |
| 40 |
|
| 41 |
def lookahead(self) -> Token: |
| 42 |
"""Look ahead and return the next non-ignored token, but do not change state.""" |
| 43 |
token = self.token |
| 44 |
if token.kind != TokenKind.EOF: |
| 45 |
while True: |
| 46 |
if token.next: |
| 47 |
token = token.next |
| 48 |
else: |
| 49 |
# Read the next token and form a link in the token linked-list. |
| 50 |
next_token = self.read_next_token(token.end) |
| 51 |
token.next = next_token |
| 52 |
next_token.prev = token |
| 53 |
token = next_token |
| 54 |
if token.kind != TokenKind.COMMENT: |
| 55 |
break |
| 56 |
return token |
| 57 |
|
| 58 |
def print_code_point_at(self, location: int) -> str: |
| 59 |
"""Print the code point at the given location. |
| 60 |
|
| 61 |
Prints the code point (or end of file reference) at a given location in a |
| 62 |
source for use in error messages. |
| 63 |
|
| 64 |
Printable ASCII is printed quoted, while other points are printed in Unicode |
| 65 |
code point form (ie. U+1234). |
| 66 |
""" |
| 67 |
body = self.source.body |
| 68 |
if location >= len(body): |
| 69 |
return TokenKind.EOF.value |
| 70 |
char = body[location] |
| 71 |
# Printable ASCII |
| 72 |
if "\x20" <= char <= "\x7e": |
| 73 |
return "'\"'" if char == '"' else f"'{char}'" |
| 74 |
# Unicode code point |
| 75 |
point = ord( |
| 76 |
body[location : location + 2] |
| 77 |
.encode("utf-16", "surrogatepass") |
| 78 |
.decode("utf-16") |
| 79 |
if is_supplementary_code_point(body, location) |
| 80 |
else char |
| 81 |
) |
| 82 |
return f"U+{point:04X}" |
| 83 |
|
| 84 |
def create_token( |
| 85 |
self, kind: TokenKind, start: int, end: int, value: Optional[str] = None |
| 86 |
) -> Token: |
| 87 |
"""Create a token with line and column location information.""" |
| 88 |
line = self.line |
| 89 |
col = 1 + start - self.line_start |
| 90 |
return Token(kind, start, end, line, col, value) |
| 91 |
|
| 92 |
def read_next_token(self, start: int) -> Token: |
| 93 |
"""Get the next token from the source starting at the given position. |
| 94 |
|
| 95 |
This skips over whitespace until it finds the next lexable token, then lexes |
| 96 |
punctuators immediately or calls the appropriate helper function for more |
| 97 |
complicated tokens. |
| 98 |
""" |
| 99 |
body = self.source.body |
| 100 |
body_length = len(body) |
| 101 |
position = start |
| 102 |
|
| 103 |
while position < body_length: |
| 104 |
char = body[position] # SourceCharacter |
| 105 |
|
| 106 |
if char in " \t,\ufeff": |
| 107 |
position += 1 |
| 108 |
continue |
| 109 |
elif char == "\n": |
| 110 |
position += 1 |
| 111 |
self.line += 1 |
| 112 |
self.line_start = position |
| 113 |
continue |
| 114 |
elif char == "\r": |
| 115 |
if body[position + 1 : position + 2] == "\n": |
| 116 |
position += 2 |
| 117 |
else: |
| 118 |
position += 1 |
| 119 |
self.line += 1 |
| 120 |
self.line_start = position |
| 121 |
continue |
| 122 |
|
| 123 |
if char == "#": |
| 124 |
return self.read_comment(position) |
| 125 |
|
| 126 |
if char == '"': |
| 127 |
if body[position + 1 : position + 3] == '""': |
| 128 |
return self.read_block_string(position) |
| 129 |
return self.read_string(position) |
| 130 |
|
| 131 |
kind = _KIND_FOR_PUNCT.get(char) |
| 132 |
if kind: |
| 133 |
return self.create_token(kind, position, position + 1) |
| 134 |
|
| 135 |
if is_digit(char) or char == "-": |
| 136 |
return self.read_number(position, char) |
| 137 |
|
| 138 |
if is_name_start(char): |
| 139 |
return self.read_name(position) |
| 140 |
|
| 141 |
if char == ".": |
| 142 |
if body[position + 1 : position + 3] == "..": |
| 143 |
return self.create_token(TokenKind.SPREAD, position, position + 3) |
| 144 |
|
| 145 |
message = ( |
| 146 |
"Unexpected single quote character (')," |
| 147 |
' did you mean to use a double quote (")?' |
| 148 |
if char == "'" |
| 149 |
else ( |
| 150 |
f"Unexpected character: {self.print_code_point_at(position)}." |
| 151 |
if is_unicode_scalar_value(char) |
| 152 |
or is_supplementary_code_point(body, position) |
| 153 |
else f"Invalid character: {self.print_code_point_at(position)}." |
| 154 |
) |
| 155 |
) |
| 156 |
|
| 157 |
raise GraphQLSyntaxError(self.source, position, message) |
| 158 |
|
| 159 |
return self.create_token(TokenKind.EOF, body_length, body_length) |
| 160 |
|
| 161 |
def read_comment(self, start: int) -> Token: |
| 162 |
"""Read a comment token from the source file.""" |
| 163 |
body = self.source.body |
| 164 |
body_length = len(body) |
| 165 |
|
| 166 |
position = start + 1 |
| 167 |
while position < body_length: |
| 168 |
char = body[position] |
| 169 |
if char in "\r\n": |
| 170 |
break |
| 171 |
if is_unicode_scalar_value(char): |
| 172 |
position += 1 |
| 173 |
elif is_supplementary_code_point(body, position): |
| 174 |
position += 2 |
| 175 |
else: |
| 176 |
break # pragma: no cover |
| 177 |
|
| 178 |
return self.create_token( |
| 179 |
TokenKind.COMMENT, |
| 180 |
start, |
| 181 |
position, |
| 182 |
body[start + 1 : position], |
| 183 |
) |
| 184 |
|
| 185 |
def read_number(self, start: int, first_char: str) -> Token: |
| 186 |
"""Reads a number token from the source file. |
| 187 |
|
| 188 |
This can be either a FloatValue or an IntValue, |
| 189 |
depending on whether a FractionalPart or ExponentPart is encountered. |
| 190 |
""" |
| 191 |
body = self.source.body |
| 192 |
position = start |
| 193 |
char = first_char |
| 194 |
is_float = False |
| 195 |
|
| 196 |
if char == "-": |
| 197 |
position += 1 |
| 198 |
char = body[position : position + 1] |
| 199 |
if char == "0": |
| 200 |
position += 1 |
| 201 |
char = body[position : position + 1] |
| 202 |
if is_digit(char): |
| 203 |
raise GraphQLSyntaxError( |
| 204 |
self.source, |
| 205 |
position, |
| 206 |
"Invalid number, unexpected digit after 0:" |
| 207 |
f" {self.print_code_point_at(position)}.", |
| 208 |
) |
| 209 |
else: |
| 210 |
position = self.read_digits(position, char) |
| 211 |
char = body[position : position + 1] |
| 212 |
if char == ".": |
| 213 |
is_float = True |
| 214 |
position += 1 |
| 215 |
char = body[position : position + 1] |
| 216 |
position = self.read_digits(position, char) |
| 217 |
char = body[position : position + 1] |
| 218 |
if char and char in "Ee": |
| 219 |
is_float = True |
| 220 |
position += 1 |
| 221 |
char = body[position : position + 1] |
| 222 |
if char and char in "+-": |
| 223 |
position += 1 |
| 224 |
char = body[position : position + 1] |
| 225 |
position = self.read_digits(position, char) |
| 226 |
char = body[position : position + 1] |
| 227 |
|
| 228 |
# Numbers cannot be followed by . or NameStart |
| 229 |
if char and (char == "." or is_name_start(char)): |
| 230 |
raise GraphQLSyntaxError( |
| 231 |
self.source, |
| 232 |
position, |
| 233 |
"Invalid number, expected digit but got:" |
| 234 |
f" {self.print_code_point_at(position)}.", |
| 235 |
) |
| 236 |
|
| 237 |
return self.create_token( |
| 238 |
TokenKind.FLOAT if is_float else TokenKind.INT, |
| 239 |
start, |
| 240 |
position, |
| 241 |
body[start:position], |
| 242 |
) |
| 243 |
|
| 244 |
def read_digits(self, start: int, first_char: str) -> int: |
| 245 |
"""Return the new position in the source after reading one or more digits.""" |
| 246 |
if not is_digit(first_char): |
| 247 |
raise GraphQLSyntaxError( |
| 248 |
self.source, |
| 249 |
start, |
| 250 |
"Invalid number, expected digit but got:" |
| 251 |
f" {self.print_code_point_at(start)}.", |
| 252 |
) |
| 253 |
|
| 254 |
body = self.source.body |
| 255 |
body_length = len(body) |
| 256 |
position = start + 1 |
| 257 |
while position < body_length and is_digit(body[position]): |
| 258 |
position += 1 |
| 259 |
return position |
| 260 |
|
| 261 |
def read_string(self, start: int) -> Token: |
| 262 |
"""Read a single-quote string token from the source file.""" |
| 263 |
body = self.source.body |
| 264 |
body_length = len(body) |
| 265 |
position = start + 1 |
| 266 |
chunk_start = position |
| 267 |
value: List[str] = [] |
| 268 |
append = value.append |
| 269 |
|
| 270 |
while position < body_length: |
| 271 |
char = body[position] |
| 272 |
|
| 273 |
if char == '"': |
| 274 |
append(body[chunk_start:position]) |
| 275 |
return self.create_token( |
| 276 |
TokenKind.STRING, |
| 277 |
start, |
| 278 |
position + 1, |
| 279 |
"".join(value), |
| 280 |
) |
| 281 |
|
| 282 |
if char == "\\": |
| 283 |
append(body[chunk_start:position]) |
| 284 |
escape = ( |
| 285 |
( |
| 286 |
self.read_escaped_unicode_variable_width(position) |
| 287 |
if body[position + 2 : position + 3] == "{" |
| 288 |
else self.read_escaped_unicode_fixed_width(position) |
| 289 |
) |
| 290 |
if body[position + 1 : position + 2] == "u" |
| 291 |
else self.read_escaped_character(position) |
| 292 |
) |
| 293 |
append(escape.value) |
| 294 |
position += escape.size |
| 295 |
chunk_start = position |
| 296 |
continue |
| 297 |
|
| 298 |
if char in "\r\n": |
| 299 |
break |
| 300 |
|
| 301 |
if is_unicode_scalar_value(char): |
| 302 |
position += 1 |
| 303 |
elif is_supplementary_code_point(body, position): |
| 304 |
position += 2 |
| 305 |
else: |
| 306 |
raise GraphQLSyntaxError( |
| 307 |
self.source, |
| 308 |
position, |
| 309 |
"Invalid character within String:" |
| 310 |
f" {self.print_code_point_at(position)}.", |
| 311 |
) |
| 312 |
|
| 313 |
raise GraphQLSyntaxError(self.source, position, "Unterminated string.") |
| 314 |
|
| 315 |
def read_escaped_unicode_variable_width(self, position: int) -> EscapeSequence: |
| 316 |
body = self.source.body |
| 317 |
point = 0 |
| 318 |
size = 3 |
| 319 |
max_size = min(12, len(body) - position) |
| 320 |
# Cannot be larger than 12 chars (\u{00000000}). |
| 321 |
while size < max_size: |
| 322 |
char = body[position + size] |
| 323 |
size += 1 |
| 324 |
if char == "}": |
| 325 |
# Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. |
| 326 |
if size < 5 or not ( |
| 327 |
0 <= point <= 0xD7FF or 0xE000 <= point <= 0x10FFFF |
| 328 |
): |
| 329 |
break |
| 330 |
return EscapeSequence(chr(point), size) |
| 331 |
# Append this hex digit to the code point. |
| 332 |
point = (point << 4) | read_hex_digit(char) |
| 333 |
if point < 0: |
| 334 |
break |
| 335 |
|
| 336 |
raise GraphQLSyntaxError( |
| 337 |
self.source, |
| 338 |
position, |
| 339 |
f"Invalid Unicode escape sequence: '{body[position: position + size]}'.", |
| 340 |
) |
| 341 |
|
| 342 |
def read_escaped_unicode_fixed_width(self, position: int) -> EscapeSequence: |
| 343 |
body = self.source.body |
| 344 |
code = read_16_bit_hex_code(body, position + 2) |
| 345 |
|
| 346 |
if 0 <= code <= 0xD7FF or 0xE000 <= code <= 0x10FFFF: |
| 347 |
return EscapeSequence(chr(code), 6) |
| 348 |
|
| 349 |
# GraphQL allows JSON-style surrogate pair escape sequences, but only when |
| 350 |
# a valid pair is formed. |
| 351 |
if 0xD800 <= code <= 0xDBFF: |
| 352 |
if body[position + 6 : position + 8] == "\\u": |
| 353 |
trailing_code = read_16_bit_hex_code(body, position + 8) |
| 354 |
if 0xDC00 <= trailing_code <= 0xDFFF: |
| 355 |
return EscapeSequence( |
| 356 |
(chr(code) + chr(trailing_code)) |
| 357 |
.encode("utf-16", "surrogatepass") |
| 358 |
.decode("utf-16"), |
| 359 |
12, |
| 360 |
) |
| 361 |
|
| 362 |
raise GraphQLSyntaxError( |
| 363 |
self.source, |
| 364 |
position, |
| 365 |
f"Invalid Unicode escape sequence: '{body[position: position + 6]}'.", |
| 366 |
) |
| 367 |
|
| 368 |
def read_escaped_character(self, position: int) -> EscapeSequence: |
| 369 |
body = self.source.body |
| 370 |
value = _ESCAPED_CHARS.get(body[position + 1]) |
| 371 |
if value: |
| 372 |
return EscapeSequence(value, 2) |
| 373 |
raise GraphQLSyntaxError( |
| 374 |
self.source, |
| 375 |
position, |
| 376 |
f"Invalid character escape sequence: '{body[position: position + 2]}'.", |
| 377 |
) |
| 378 |
|
| 379 |
def read_block_string(self, start: int) -> Token: |
| 380 |
"""Read a block string token from the source file.""" |
| 381 |
body = self.source.body |
| 382 |
body_length = len(body) |
| 383 |
line_start = self.line_start |
| 384 |
|
| 385 |
position = start + 3 |
| 386 |
chunk_start = position |
| 387 |
current_line = "" |
| 388 |
|
| 389 |
block_lines = [] |
| 390 |
while position < body_length: |
| 391 |
char = body[position] |
| 392 |
|
| 393 |
if char == '"' and body[position + 1 : position + 3] == '""': |
| 394 |
current_line += body[chunk_start:position] |
| 395 |
block_lines.append(current_line) |
| 396 |
|
| 397 |
token = self.create_token( |
| 398 |
TokenKind.BLOCK_STRING, |
| 399 |
start, |
| 400 |
position + 3, |
| 401 |
# return a string of the lines joined with new lines |
| 402 |
"\n".join(dedent_block_string_lines(block_lines)), |
| 403 |
) |
| 404 |
|
| 405 |
self.line += len(block_lines) - 1 |
| 406 |
self.line_start = line_start |
| 407 |
return token |
| 408 |
|
| 409 |
if char == "\\" and body[position + 1 : position + 4] == '"""': |
| 410 |
current_line += body[chunk_start:position] |
| 411 |
chunk_start = position + 1 # skip only slash |
| 412 |
position += 4 |
| 413 |
continue |
| 414 |
|
| 415 |
if char in "\r\n": |
| 416 |
current_line += body[chunk_start:position] |
| 417 |
block_lines.append(current_line) |
| 418 |
|
| 419 |
if char == "\r" and body[position + 1 : position + 2] == "\n": |
| 420 |
position += 2 |
| 421 |
else: |
| 422 |
position += 1 |
| 423 |
|
| 424 |
current_line = "" |
| 425 |
chunk_start = line_start = position |
| 426 |
continue |
| 427 |
|
| 428 |
if is_unicode_scalar_value(char): |
| 429 |
position += 1 |
| 430 |
elif is_supplementary_code_point(body, position): |
| 431 |
position += 2 |
| 432 |
else: |
| 433 |
raise GraphQLSyntaxError( |
| 434 |
self.source, |
| 435 |
position, |
| 436 |
"Invalid character within String:" |
| 437 |
f" {self.print_code_point_at(position)}.", |
| 438 |
) |
| 439 |
|
| 440 |
raise GraphQLSyntaxError(self.source, position, "Unterminated string.") |
| 441 |
|
| 442 |
def read_name(self, start: int) -> Token: |
| 443 |
"""Read an alphanumeric + underscore name from the source.""" |
| 444 |
body = self.source.body |
| 445 |
body_length = len(body) |
| 446 |
position = start + 1 |
| 447 |
|
| 448 |
while position < body_length: |
| 449 |
char = body[position] |
| 450 |
if not is_name_continue(char): |
| 451 |
break |
| 452 |
position += 1 |
| 453 |
|
| 454 |
return self.create_token(TokenKind.NAME, start, position, body[start:position]) |
| 455 |
|
| 456 |
|
| 457 |
_punctuator_token_kinds = frozenset( |
| 458 |
[ |
| 459 |
TokenKind.BANG, |
| 460 |
TokenKind.DOLLAR, |
| 461 |
TokenKind.AMP, |
| 462 |
TokenKind.PAREN_L, |
| 463 |
TokenKind.PAREN_R, |
| 464 |
TokenKind.DOT, |
| 465 |
TokenKind.SPREAD, |
| 466 |
TokenKind.COLON, |
| 467 |
TokenKind.EQUALS, |
| 468 |
TokenKind.AT, |
| 469 |
TokenKind.BRACKET_L, |
| 470 |
TokenKind.BRACKET_R, |
| 471 |
TokenKind.BRACE_L, |
| 472 |
TokenKind.PIPE, |
| 473 |
TokenKind.BRACE_R, |
| 474 |
] |
| 475 |
) |
| 476 |
|
| 477 |
|
| 478 |
def is_punctuator_token_kind(kind: TokenKind) -> bool: |
| 479 |
"""Check whether the given token kind corresponds to a punctuator. |
| 480 |
|
| 481 |
For internal use only. |
| 482 |
""" |
| 483 |
return kind in _punctuator_token_kinds |
| 484 |
|
| 485 |
|
| 486 |
_KIND_FOR_PUNCT = { |
| 487 |
"!": TokenKind.BANG, |
| 488 |
"$": TokenKind.DOLLAR, |
| 489 |
"&": TokenKind.AMP, |
| 490 |
"(": TokenKind.PAREN_L, |
| 491 |
")": TokenKind.PAREN_R, |
| 492 |
":": TokenKind.COLON, |
| 493 |
"=": TokenKind.EQUALS, |
| 494 |
"@": TokenKind.AT, |
| 495 |
"[": TokenKind.BRACKET_L, |
| 496 |
"]": TokenKind.BRACKET_R, |
| 497 |
"{": TokenKind.BRACE_L, |
| 498 |
"}": TokenKind.BRACE_R, |
| 499 |
"|": TokenKind.PIPE, |
| 500 |
} |
| 501 |
|
| 502 |
|
| 503 |
_ESCAPED_CHARS = { |
| 504 |
'"': '"', |
| 505 |
"/": "/", |
| 506 |
"\\": "\\", |
| 507 |
"b": "\b", |
| 508 |
"f": "\f", |
| 509 |
"n": "\n", |
| 510 |
"r": "\r", |
| 511 |
"t": "\t", |
| 512 |
} |
| 513 |
|
| 514 |
|
| 515 |
def read_16_bit_hex_code(body: str, position: int) -> int: |
| 516 |
"""Read a 16bit hexadecimal string and return its positive integer value (0-65535). |
| 517 |
|
| 518 |
Reads four hexadecimal characters and returns the positive integer that 16bit |
| 519 |
hexadecimal string represents. For example, "000f" will return 15, and "dead" |
| 520 |
will return 57005. |
| 521 |
|
| 522 |
Returns a negative number if any char was not a valid hexadecimal digit. |
| 523 |
""" |
| 524 |
# read_hex_digit() returns -1 on error. ORing a negative value with any other |
| 525 |
# value always produces a negative value. |
| 526 |
return ( |
| 527 |
read_hex_digit(body[position]) << 12 |
| 528 |
| read_hex_digit(body[position + 1]) << 8 |
| 529 |
| read_hex_digit(body[position + 2]) << 4 |
| 530 |
| read_hex_digit(body[position + 3]) |
| 531 |
) |
| 532 |
|
| 533 |
|
| 534 |
def read_hex_digit(char: str) -> int: |
| 535 |
"""Read a hexadecimal character and returns its positive integer value (0-15). |
| 536 |
|
| 537 |
'0' becomes 0, '9' becomes 9 |
| 538 |
'A' becomes 10, 'F' becomes 15 |
| 539 |
'a' becomes 10, 'f' becomes 15 |
| 540 |
|
| 541 |
Returns -1 if the provided character code was not a valid hexadecimal digit. |
| 542 |
""" |
| 543 |
if "0" <= char <= "9": |
| 544 |
return ord(char) - 48 |
| 545 |
elif "A" <= char <= "F": |
| 546 |
return ord(char) - 55 |
| 547 |
elif "a" <= char <= "f": |
| 548 |
return ord(char) - 87 |
| 549 |
return -1 |
| 550 |
|
| 551 |
|
| 552 |
def is_unicode_scalar_value(char: str) -> bool: |
| 553 |
"""Check whether this is a Unicode scalar value. |
| 554 |
|
| 555 |
A Unicode scalar value is any Unicode code point except surrogate code |
| 556 |
points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and |
| 557 |
0xE000 to 0x10FFFF. |
| 558 |
""" |
| 559 |
return "\x00" <= char <= "\ud7ff" or "\ue000" <= char <= "\U0010ffff" |
| 560 |
|
| 561 |
|
| 562 |
def is_supplementary_code_point(body: str, location: int) -> bool: |
| 563 |
""" |
| 564 |
Check whether the current location is a supplementary code point. |
| 565 |
|
| 566 |
The GraphQL specification defines source text as a sequence of unicode scalar |
| 567 |
values (which Unicode defines to exclude surrogate code points). |
| 568 |
""" |
| 569 |
try: |
| 570 |
return ( |
| 571 |
"\ud800" <= body[location] <= "\udbff" |
| 572 |
and "\udc00" <= body[location + 1] <= "\udfff" |
| 573 |
) |
| 574 |
except IndexError: |
| 575 |
return False |