-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.py
More file actions
289 lines (242 loc) · 10.4 KB
/
Copy pathlexer.py
File metadata and controls
289 lines (242 loc) · 10.4 KB
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
# Each of these can be sequence of alphabetic characters
#
KEYWORD = {'print', 'printNum', 'printStr', 'printRepr', 'get', 'getNum', 'getStr'}
# These must be only one character long.
#
DELIMITER = {'(', ')', '[', ']', '{', '}'}
SPECIAL = set()
SEPARATOR = {',', ';'}
# STRING_LEFT and STRING_RIGHT may be more than one character long,
# but the ESCAPE_CHARACTER must be only one character long.
STRING_LEFT = '"'
STRING_RIGHT = '"'
ESCAPE_CHARACTER = '\\'
# This may be more than one character long.
#
COMMENT = '#'
# These may be more than one character long.
#
OPERATOR = {'!', '@', '$', '%', '^', '&', '*', '-', '+', '|', '_',
#'!!', '@@', '$$', '%%', '^^', '&&', '**', '--', '++', '||', '__',
#'!=', '@=', '$=', '%=', '^=', '&=', '*=', '-=', '+=', '|=',
'<', '>', '.', '=', ':', '?', '/', '\\', '~',
#'<<', '>>', '..', '==', '::', '??', '//', '\\\\',
# '.=', ':=', '?=', '/=', '\\=', '~=',
#'<<<', '>>>', '...', '===',
':=',
#'/\\', '\\/', '<>', '</>', '<:', ':>', '<-<', '>->',
# '=/=', '<~', '~>',
# '<=>', '<|', '|>',
'<-', '->', '=<', '>=', '=<<', '>>=', '↑',
'←', '→', '<=', '=>', '<<=', '=>>', '↓',
# '≤', '≥',
'×', '÷', '⋅', '∘'}
#'×=', '÷=', '⋅=', '∘='}
# Characters that are part of an operator but may also appear as part of a name.
# (These must be only one character long.)
#
MID_WORD_SYMBOL = set()
END_WORD_SYMBOL = set()
########################################################################
WHITESPACE = {' ', '\t', '\r', '\n', '\f', '\v'}
STRING_START = STRING_LEFT[0]
COMMENT_START = COMMENT[0]
OPERATOR_START = set(opr[0] for opr in OPERATOR)
# Words may not contain the following characters; these will terminate a word.
#
NON_WORD = ( (DELIMITER | SPECIAL | SEPARATOR | OPERATOR_START
| {STRING_START, COMMENT_START}
) - MID_WORD_SYMBOL
) | END_WORD_SYMBOL | WHITESPACE
SORTED_OPERATOR = list(reversed(sorted(OPERATOR, key = len)))
import re
ws_regex = re.compile(r"\s+")
num_regex = re.compile(r"\d+")
################################################################################
class Token:
def __init__(self, text, line, column, token_value, token_class):
self.txt = text
self.ln = line
self.col = column
self.val = token_value
self.cls = token_class
def __eq__(self, other):
if not isinstance(other, Token):
return False
return (self.val == other.val and self.cls == other.cls)
def isexactly(self, other):
if not isinstance(other, Token):
return False
return (self.txt == other.txt and \
self.ln == other.ln and \
self.col == other.col and \
self.val == other.val and \
self.cls == other.cls )
def __repr__(self):
tk = "\x1B[38;5;42mToken\x1B[39m"
if self.val is None:
value = "_"
elif isinstance(self.val, str):
value = '"' + self.val.replace("\n", "\\n") + '"'
else:
value = str(self.val)
return f"⟨{tk} {value} : {self.cls} @ {self.ln},{self.col}⟩"
class TokenStream:
# text := text to be tokenized
# more := nullary function that will be called to get more text
def __init__(self, text, more = None):
self.text = text
self.more = more
self.line = 1
self.column = 1
self.last_emitted_newline = False
self.log = text
def _advance(self, string):
newlines = string.count("\n")
if newlines == 0:
self.column = self.column + len(string)
else:
self.line = self.line + newlines
self.column = len(string) - string.rindex("\n")
def __next__(self): ########################################################
while True:
# Strip leading whitespace or return a newline #################
match = ws_regex.match(self.text)
if match is not None:
whitespace, self.text = match.group(), self.text[match.end():]
tok_line, tok_column = self.line, self.column
self._advance(whitespace)
if ("\n" in whitespace) and not self.last_emitted_newline:
self.last_emitted_newline = True
return Token(whitespace, tok_line, tok_column, None, 'newline')
# Is the text empty? ###########################################
if self.text == "":
if self.more is None:
return None
continuation = self.more()
self.text += continuation
self.log += continuation
continue
# Is this a comment? ###########################################
if self.text.startswith(COMMENT):
while True:
try:
end_of_comment = self.text.index("\n")
self.text = self.text[end_of_comment:]
break
except Exception:
self.text = ""
if self.more is None:
return None
continuation = self.more()
self.text += continuation
self.log += continuation
continue
################################################################
# At this point, we're guaranteed not to return a newline,
# so go ahead and preëmptively change last_emitted_newline.
self.last_emitted_newline = False
tok_line, tok_column = self.line, self.column
# Is the next token a natural number? #########################
# TODO support 0x, 0o, and 0b notation
match = num_regex.match(self.text)
if match is not None:
numstr = match.group()
num = int(numstr)
self._advance(numstr)
self.text = self.text[match.end():]
return Token(numstr, tok_line, tok_column, num, 'natural')
# Is the next token a string? ##################################
if self.text.startswith(STRING_LEFT):
self._advance(STRING_LEFT)
self.text = self.text[len(STRING_LEFT):]
idx = 0
while True:
try:
jdx = self.text.index(STRING_RIGHT, idx)
if jdx > 0 and self.text[jdx-1] == ESCAPE_CHARACTER:
idx = jdx + 1
else:
idx = jdx
break
except Exception:
if self.more is None:
raise Exception("unterminated string")
continuation = self.more()
self.text += continuation
self.log += continuation
string = self.text[:idx]
self._advance(string+STRING_RIGHT)
self.text = self.text[idx+len(STRING_RIGHT):]
literal = STRING_LEFT + string + STRING_RIGHT
string = string.replace('\\"', '"')
string = string.replace('\\n', '\n')
# TODO support other escape sequences
# (and actually do it properly)
return Token(literal, tok_line, tok_column, string, 'string')
# Is the next token a delimr, special char, sepr, or opr? ######
value = self.text[0]
if value in (DELIMITER | SPECIAL | SEPARATOR | OPERATOR_START):
if value in DELIMITER:
tok_class = 'delimiter'
elif value in SPECIAL:
tok_class = 'special'
elif value in SEPARATOR:
tok_class = 'separator'
else:
tok_class = 'operator'
for opr in SORTED_OPERATOR:
if self.text.startswith(opr):
value = opr
break
self._advance(value)
self.text = self.text[len(value):]
return Token(value, tok_line, tok_column, value, tok_class)
# The next token must be a name or keyword #####################
idx = 0
while not (idx == len(self.text) or (self.text[idx] in NON_WORD)):
idx += 1
idx -= 1
while self.text[idx] in MID_WORD_SYMBOL:
idx -=1
idx += 1
if idx < len(self.text) and self.text[idx] in END_WORD_SYMBOL:
word = self.text[:idx+1]
self._advance(word)
self.text = self.text[idx+1:]
else:
word = self.text[:idx]
self._advance(word)
self.text = self.text[idx:]
tok_class = ('keyword' if word in KEYWORD else 'name')
return Token(word, tok_line, tok_column, word, tok_class)
class TokenBuffer:
# stream := text or instance of TokenStream
# more := nullary function that will be called to get more text
def __init__(self, stream, more = None):
if isinstance(stream, str):
self.stream = TokenStream(stream, more)
else:
self.stream = stream
self.buffer = []
self.length = float('inf')
def __len__(self):
if isinstance(self.length, int):
return self.length
else:
raise Exception("length unknown because buffer has not been completed")
def __getitem__(self, idx):
if idx < 0:
return None
if idx >= self.length:
return None
if idx >= len(self.buffer):
for _ in range(idx - len(self.buffer) + 1):
self.buffer.append(next(self.stream))
return self.buffer[idx]
def freeze(self):
self.length = len(self.buffer)
def complete(self):
while (tok := next(self.stream)) is not None:
self.buffer.append(tok)
self.length = len(self.buffer)