-
Notifications
You must be signed in to change notification settings - Fork 180
/
Copy pathlexer.py
477 lines (384 loc) · 12.8 KB
/
lexer.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
import json
from six import unichr
from ..error import GraphQLSyntaxError
# Necessary for static type checking
if False: # flake8: noqa
from typing import Optional, Any, List
from .source import Source
__all__ = ["Token", "Lexer", "TokenKind", "get_token_desc", "get_token_kind_desc"]
class Token(object):
__slots__ = "kind", "start", "end", "value"
def __init__(self, kind, start, end, value=None):
# type: (int, int, int, Optional[str]) -> None
self.kind = kind
self.start = start
self.end = end
self.value = value
def __repr__(self):
# type: () -> str
return u"<Token kind={} at {}..{} value={}>".format(
get_token_kind_desc(self.kind), self.start, self.end, repr(self.value)
)
def __eq__(self, other):
# type: (Any) -> bool
return (
isinstance(other, Token)
and self.kind == other.kind
and self.start == other.start
and self.end == other.end
and self.value == other.value
)
class Lexer(object):
__slots__ = "source", "prev_position"
def __init__(self, source):
# type: (Source) -> None
self.source = source
self.prev_position = 0
def next_token(self, reset_position=None):
# type: (Optional[int]) -> Token
if reset_position is None:
reset_position = self.prev_position
token = read_token(self.source, reset_position)
self.prev_position = token.end
return token
class TokenKind(object):
EOF = 1
BANG = 2
DOLLAR = 3
PAREN_L = 4
PAREN_R = 5
SPREAD = 6
COLON = 7
EQUALS = 8
AT = 9
BRACKET_L = 10
BRACKET_R = 11
BRACE_L = 12
PIPE = 13
BRACE_R = 14
NAME = 15
VARIABLE = 16
INT = 17
FLOAT = 18
STRING = 19
ASTERISK = 20 # recursive symbol
def get_token_desc(token):
# type: (Token) -> str
if token.value:
return u'{} "{}"'.format(get_token_kind_desc(token.kind), token.value)
else:
return get_token_kind_desc(token.kind)
def get_token_kind_desc(kind):
# type: (int) -> str
return TOKEN_DESCRIPTION[kind]
TOKEN_DESCRIPTION = {
TokenKind.EOF: "EOF", # end of file
TokenKind.BANG: "!",
TokenKind.DOLLAR: "$",
TokenKind.PAREN_L: "(",
TokenKind.PAREN_R: ")",
TokenKind.SPREAD: "...",
TokenKind.COLON: ":",
TokenKind.EQUALS: "=",
TokenKind.AT: "@",
TokenKind.BRACKET_L: "[",
TokenKind.BRACKET_R: "]",
TokenKind.BRACE_L: "{",
TokenKind.PIPE: "|",
TokenKind.BRACE_R: "}",
TokenKind.NAME: "Name",
TokenKind.VARIABLE: "Variable",
TokenKind.INT: "Int",
TokenKind.FLOAT: "Float",
TokenKind.STRING: "String",
TokenKind.ASTERISK: "RS", # recursion selection
}
def char_code_at(s, pos):
# type: (str, int) -> Optional[int]
if 0 <= pos < len(s):
return ord(s[pos])
return None
PUNCT_CODE_TO_KIND = {
ord("!"): TokenKind.BANG,
ord("$"): TokenKind.DOLLAR,
ord("("): TokenKind.PAREN_L,
ord(")"): TokenKind.PAREN_R,
ord(":"): TokenKind.COLON,
ord("="): TokenKind.EQUALS,
ord("@"): TokenKind.AT,
ord("["): TokenKind.BRACKET_L,
ord("]"): TokenKind.BRACKET_R,
ord("{"): TokenKind.BRACE_L,
ord("|"): TokenKind.PIPE,
ord("}"): TokenKind.BRACE_R,
ord("*"): TokenKind.ASTERISK, # recursive
}
def print_char_code(code):
# type: (Optional[int]) -> str
if code is None:
return "<EOF>"
if code < 0x007F:
return json.dumps(unichr(code))
return '"\\u%04X"' % code
def read_token(source, from_position):
# type: (Source, int) -> Token
"""Gets the next token from the source starting at the given position.
This skips over whitespace and comments until it finds the next lexable
token, then lexes punctuators immediately or calls the appropriate
helper function for more complicated tokens."""
body = source.body
body_length = len(body)
position = position_after_whitespace(body, from_position)
if position >= body_length:
return Token(TokenKind.EOF, position, position) # \n send token
code = char_code_at(body, position)
if code:
if code < 0x0020 and code not in (0x0009, 0x000A, 0x000D):
raise GraphQLSyntaxError(
source, position, u"Invalid character {}.".format(print_char_code(code))
)
kind = PUNCT_CODE_TO_KIND.get(code)
if kind is not None:
return Token(kind, position, position + 1) # send token of 20 - asterisk
if code == 46: # . if token is point
if (
char_code_at(body, position + 1)
== char_code_at(body, position + 2)
== 46
):
return Token(TokenKind.SPREAD, position, position + 3) # this definition of fragments
elif 65 <= code <= 90 or code == 95 or 97 <= code <= 122:
# A-Z, _, a-z
return read_name(source, position)
elif code == 45 or 48 <= code <= 57: # -, 0-9
return read_number(source, position, code)
elif code == 34: # "
return read_string(source, position)
raise GraphQLSyntaxError(
source, position, u"Unexpected character {}.".format(print_char_code(code))
)
ignored_whitespace_characters = frozenset(
[
# BOM
0xFEFF,
# White Space
0x0009, # tab
0x0020, # space
# Line Terminator
0x000A, # new line
0x000D, # carriage return
# Comma
0x002C,
]
)
def position_after_whitespace(body, start_position):
# type: (str, int) -> int
"""Reads from body starting at start_position until it finds a
non-whitespace or commented character, then returns the position of
that character for lexing."""
body_length = len(body)
position = start_position
while position < body_length:
code = char_code_at(body, position)
if code in ignored_whitespace_characters:
position += 1
elif code == 35: # #, skip comments
position += 1
while position < body_length:
code = char_code_at(body, position)
if not (
code is not None
and (code > 0x001F or code == 0x0009)
and code not in (0x000A, 0x000D)
):
break
position += 1
else:
break
return position
def read_number(source, start, first_code):
# type: (Source, int, Optional[int]) -> Token
"""Reads a number token from the source file, either a float
or an int depending on whether a decimal point appears.
Int: -?(0|[1-9][0-9]*)
Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?"""
code = first_code
body = source.body
position = start
is_float = False
if code == 45: # -
position += 1
code = char_code_at(body, position)
if code == 48: # 0
position += 1
code = char_code_at(body, position)
if code is not None and 48 <= code <= 57:
raise GraphQLSyntaxError(
source,
position,
u"Invalid number, unexpected digit after 0: {}.".format(
print_char_code(code)
),
)
else:
position = read_digits(source, position, code)
code = char_code_at(body, position)
if code == 46: # .
is_float = True
position += 1
code = char_code_at(body, position)
position = read_digits(source, position, code)
code = char_code_at(body, position)
if code in (69, 101): # E e
is_float = True
position += 1
code = char_code_at(body, position)
if code in (43, 45): # + -
position += 1
code = char_code_at(body, position)
position = read_digits(source, position, code)
return Token(
TokenKind.FLOAT if is_float else TokenKind.INT,
start,
position,
body[start:position],
)
def read_digits(source, start, first_code):
# type: (Source, int, Optional[int]) -> int
body = source.body
position = start
code = first_code
if code is not None and 48 <= code <= 57: # 0 - 9
while True:
position += 1
code = char_code_at(body, position)
if not (code is not None and 48 <= code <= 57):
break
return position
raise GraphQLSyntaxError(
source,
position,
u"Invalid number, expected digit but got: {}.".format(print_char_code(code)),
)
ESCAPED_CHAR_CODES = {
34: '"',
47: "/",
92: "\\",
98: "\b",
102: "\f",
110: "\n",
114: "\r",
116: "\t",
}
def read_string(source, start):
# type: (Source, int) -> Token
"""Reads a string token from the source file.
"([^"\\\u000A\u000D\u2028\u2029]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
"""
body = source.body
body_length = len(body)
position = start + 1
chunk_start = position
code = 0 # type: Optional[int]
value = [] # type: List[str]
append = value.append
while position < body_length:
code = char_code_at(body, position)
if code in (
None,
# LineTerminator
0x000A,
0x000D,
# Quote
34,
):
break
if code < 0x0020 and code != 0x0009: # type: ignore
raise GraphQLSyntaxError(
source,
position,
u"Invalid character within String: {}.".format(print_char_code(code)),
)
position += 1
if code == 92: # \
append(body[chunk_start : position - 1])
code = char_code_at(body, position)
escaped = ESCAPED_CHAR_CODES.get(code) # type: ignore
if escaped is not None:
append(escaped)
elif code == 117: # u
char_code = uni_char_code(
char_code_at(body, position + 1) or 0,
char_code_at(body, position + 2) or 0,
char_code_at(body, position + 3) or 0,
char_code_at(body, position + 4) or 0,
)
if char_code < 0:
raise GraphQLSyntaxError(
source,
position,
u"Invalid character escape sequence: \\u{}.".format(
body[position + 1 : position + 5]
),
)
append(unichr(char_code))
position += 4
else:
raise GraphQLSyntaxError(
source,
position,
u"Invalid character escape sequence: \\{}.".format(
unichr(code) # type: ignore
),
)
position += 1
chunk_start = position
if code != 34: # Quote (")
raise GraphQLSyntaxError(source, position, "Unterminated string")
append(body[chunk_start:position])
return Token(TokenKind.STRING, start, position + 1, u"".join(value))
def uni_char_code(a, b, c, d):
# type: (int, int, int, int) -> int
"""Converts four hexidecimal chars to the integer that the
string represents. For example, uniCharCode('0','0','0','f')
will return 15, and uniCharCode('0','0','f','f') returns 255.
Returns a negative number on error, if a char was invalid.
This is implemented by noting that char2hex() returns -1 on error,
which means the result of ORing the char2hex() will also be negative.
"""
return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d)
def char2hex(a):
# type: (int) -> int
"""Converts a hex character to its integer value.
'0' becomes 0, '9' becomes 9
'A' becomes 10, 'F' becomes 15
'a' becomes 10, 'f' becomes 15
Returns -1 on error."""
if 48 <= a <= 57: # 0-9
return a - 48
elif 65 <= a <= 70: # A-F
return a - 55
elif 97 <= a <= 102: # a-f
return a - 87
return -1
def read_name(source, position):
# type: (Source, int) -> Token
"""Reads an alphanumeric + underscore name from the source.
[_A-Za-z][_0-9A-Za-z]*"""
body = source.body
body_length = len(body)
end = position + 1
while end != body_length:
code = char_code_at(body, end)
if not (
code is not None
and (
code == 95
or 48 <= code <= 57 # _
or 65 <= code <= 90 # 0-9
or 97 <= code <= 122 # A-Z # a-z
)
):
break
end += 1
return Token(TokenKind.NAME, position, end, body[position:end])