-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lexer.py
524 lines (380 loc) · 17 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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
from enum import Enum
from functools import reduce
from typing import List, Union, Tuple
import re
import ATPTools
class RegexMap(Enum):
VAR = "[a-zA-Z]+([a-zA-Z0-9])*" # Starts with a letter, optionally followed by any number or letter
VAL = "([-+]?)(\d*)(\.?\d*)" # optional sign, followed by any amount of numbers, optionally a floating point number
WHITESPACE = "\s+" # One or more whitespace characters
VAR_OR_CONST = "(" + str(VAR) + "|" + str(VAL) + ")" # Combines the VAR and VAL regexes, matching either one.
LABEL = "\.[a-zA-Z0-9]+" # Starts with a dot, followed by one or more letters
VAR_CONST_OR_STRING = "(" + str(VAR) + "|" + str(
VAL) + "|\"[\w\d\s\?\.\!\,\\\/\-\`\+\%\#\'\@\&\^\$\~\*\(\)\_\{\}\[\]\;\:\<\>]*\")"
COMMENT = "(\#{1}[\w\d\s\?\.\!\,\\\/\-\+\%\#\'\@\&\^\$\~\*\(\)\_\{\}\[\]\;\:\<\>\`]*)?"
class Instruction:
regex = None
def __init__(self):
self.parameters = []
def __str__(self) -> str:
return "Instruction"
class Jump(Instruction):
regex = None
def __init__(self):
super().__init__()
def __str__(self) -> str:
return "Jump"
class SetSimple(Instruction):
regex = "^SET[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target"]
def __str__(self) -> str:
return "SET {target}"
class Set(Instruction):
regex = "^SET[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "SET {target} {value}"
class Declare(Instruction):
regex = "^DECL[ \t]+(?P<label>\." + str(RegexMap.VAR.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["label"]
def __str__(self) -> str:
return "DECL {label}"
class Increment(Instruction):
regex = "^INC[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target"]
def __str__(self) -> str:
return "INC {target}"
class Decrement(Instruction):
regex = "^DEC[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target"]
def __str__(self) -> str:
return "DEC {target}"
class AddSimple(Instruction):
regex = "^ADD[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "ADD {target} {var|value}"
class Add(Instruction):
regex = "^ADD[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "ADD {target} {var|value} {var|value}"
class SubtractSimple(Instruction):
regex = "^SUB[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "SUB {target} {var|value}"
class Subtract(Instruction):
regex = "^SUB[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "SUB {target} {var|value} {var|value}"
class MultiplySimple(Instruction):
regex = "^MUL[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "MUL {target} {var|value}"
class Multiply(Instruction):
regex = "^MUL[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "MUL {target} {var|value} {var|value}"
class DivideSimple(Instruction):
regex = "^DIV[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "DIV {target} {var|value}"
class Divide(Instruction):
regex = "^DIV[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "DIV {target} {left} {right}"
class ModuloSimple(Instruction):
regex = "^MOD[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "MOD {target} {right}"
class Modulo(Instruction):
regex = "^MOD[ \t]+(?P<target>" + str(RegexMap.VAR.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "MOD {target} {left} {right"
class JumpEqualSimple(Jump):
regex = "^JE[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "JE {target} {right}"
class JumpEqual(Jump):
regex = "^JE[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*(" + str(RegexMap.COMMENT.value) + "[ \t]*)$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "{target} {right}"
class JumpNotEqualSimple(Jump):
regex = "^JNE[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "JNE {target} {left} {right}"
class JumpNotEqual(Jump):
regex = "^JNE[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "JNE {target} {left} {right}"
class JumpLessThanSimple(Jump):
regex = "^JL[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "JL {target} {right}"
class JumpLessThan(Jump):
regex = "^JL[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "JL {target} {left} {right}"
class JumpGreaterThanSimple(Jump):
regex = "^JG[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "JG {target} {right}"
class JumpGreaterThan(Jump):
regex = "^JG[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "JG {target} {left} {right}"
class JumpGreaterOrEqualSimple(Jump):
regex = "^JGE[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "JGE {target} {right}"
class JumpGreaterOrEqual(Jump):
regex = "^JGE[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "JGE {target} {left} {right}"
class JumpLessOrEqualSimple(Jump):
regex = "^JLE[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "right"]
def __str__(self) -> str:
return "JLE {target} {right}"
class JumpLessOrEqual(Jump):
regex = "^JLE[ \t]+(?P<target>" + str(RegexMap.LABEL.value) + ")[ \t]+(?P<left>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]+(?P<right>" + str(
RegexMap.VAR_OR_CONST.value) + ")[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = ["target", "left", "right"]
def __str__(self) -> str:
return "JLE {target} {left} {right}"
class Nop(Instruction):
regex = "^(NOP|$|[ \t]*| *$)[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = []
def __str__(self) -> str:
return "NOP"
class Dump(Instruction):
regex = "^(DUMP)[ \t]*" + str(RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
self.parameters = []
def __str__(self) -> str:
return "DUMP"
class Print(Instruction):
regex = "^PRINT[ \t]+(?P<right>" + str(RegexMap.VAR_CONST_OR_STRING.value) + ")[ \t]*" + str(
RegexMap.COMMENT.value) + "[ \t]*$"
def __init__(self):
super().__init__()
super().__init__()
self.parameters = ["right"]
def __str__(self) -> str:
return "PRINT {value}"
# strToList :: str -> [str]
@ATPTools.copyParameters
def strToList(input_string: str) -> List[str]:
"""
Explodes a string into a list of individual characters
:param input_string: the input
:return: a list of characters
"""
if input_string.find(' ') == -1:
return [input_string]
return [input_string[:input_string.index(" ")]] + strToList(input_string[input_string.index(" ") + 1:])
# stringToLines :: str -> [str]
@ATPTools.copyParameters
def strToLines(input_string: str) -> List[str]:
"""
Explodes a string on newlines and returns each line as an element of a list.
:param input_string: The input
:return: list of lines
"""
if input_string.find('\n') == -1:
return [input_string]
return [input_string[:input_string.index('\n')]] + strToLines(input_string[input_string.index('\n') + 1:])
# mapDataTypes :: dict -> dict
@ATPTools.copyParameters
def mapDataTypes(input_dict: dict) -> dict:
"""
Maps the value of each parameter to a python datatype for execution
:param input_dict: the parameters of the current line
:return: the variables of the current line cast to their correct datatype
"""
# We casten het resultaat van de map functie naar een dict omdat het resultaat van map maar een keer gebruikt kan
# worden doordat het een generator teruggeeft. Door het in een dict te stoppen behouden we alle informatie en
# kan het resultaat meerdere keren gebruikt worden.
return dict(map(lambda kv: (kv[0], strToDataType(kv[1])), input_dict.items()))
# regexTest :: Instruction -> str -> Either dict None
@ATPTools.copyParameters
def regexTest(instruction_type: Instruction, string: str) -> Union[dict, None]:
"""
Test an instruction type's regex on the current line, if it matches it returns the instruction and it's parameters
cast to the correct python data type
:param instruction_type: the class to test
:param string: the line to match
:return: Either the parameters of the line or None if the regex did not match
"""
pattern = re.compile(instruction_type.regex)
match = re.fullmatch(pattern, string)
return mapDataTypes(match.groupdict()) if match is not None else None
# strToDataType :: str -> Either str float int
@ATPTools.copyParameters
def strToDataType(input_string: str) -> Union[str, float, int]:
"""
Tries to cast the given input string to a float and an int.
If the cast succeeds we return the cast result, if no conversion is possible to either float or int we assume that
the value is a string and return the string variant.
:param input_string:
:return:
"""
try:
float(input_string)
return float(input_string)
except ValueError:
try:
int(input_string)
return int(input_string)
except ValueError:
return input_string
# matchToken :: str -> Either Tuple[Instruction, dict] None
@ATPTools.copyParameters
def matchToken(input_string: str) -> Union[Tuple[Instruction, dict], None]:
"""
Match a line to an instruction and extract the parameters.
:param input_string: The line of a program
:return: A tuple containing the instruction type and it's parameters or None is no match is found
"""
instruction_map = [
SetSimple, Set,
Declare, Increment, Decrement,
AddSimple, Add,
SubtractSimple, Subtract,
MultiplySimple, Multiply,
DivideSimple, Divide,
ModuloSimple, Modulo,
JumpEqualSimple, JumpEqual,
JumpNotEqualSimple, JumpNotEqual,
JumpLessThanSimple, JumpLessThan,
JumpGreaterThanSimple, JumpGreaterThan,
JumpGreaterOrEqualSimple, JumpGreaterOrEqual,
JumpLessOrEqualSimple, JumpLessOrEqual,
Nop, Print, Dump
]
return reduce(
lambda x, y: x if x[1] is not None else y,
map(
lambda x: (x, regexTest(x, input_string)),
instruction_map
)
)
# lexInput :: [str] -> [Tuple[Instruction, dict]]
@ATPTools.copyParameters
def lexInput(input_program: List[str]) -> List[Tuple[Instruction, dict]]:
"""
Convert an input program to a list of instructions with their associated parameters.
:param input_program: the program as a list of lines (strings)
:return: a list of tuples containing the instructions and their parameters
"""
if len(input_program) == 0:
return []
return [matchToken(input_program[0])] + lexInput(input_program[1:])