-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter.py
87 lines (67 loc) · 2.73 KB
/
Interpreter.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
class Interpreter:
def __init__(self, statements):
self.statements = statements
def format_code(self, source_code):
depth = 0
formated_source_code = ""
for line in source_code.split("\n"):
prefix = ""
if "end" in line and not "append" in line:
depth -= 1
line = line.replace("end", "")
for i in range(depth):
prefix += "\t"
if "while" in line:
depth += 1
formated_source_code += prefix + line + "\n"
return formated_source_code
def generate_code(self):
source_code = ""
for statement in self.statements:
# print variable
if statement.startswith("print"):
source_code += f"print({statement.replace('print', '').strip()})\n"
continue
# end loop
if statement.startswith("end"):
source_code += statement
continue
# while loop
if statement.startswith("while"):
if "! =" in statement:
statement = statement.replace("! =", "!=")
source_code += f"{statement.replace('do', ':')}\n"
continue
# list datastructure
if "+=" in statement:
statement_split = statement.split("+=")
var_name = statement_split[0]
var_value = statement_split[1]
declaration = False
variable_declaration = var_name + " = "
if variable_declaration in source_code:
declaration = True
if not declaration:
source_code += f"{var_name} = [{var_value}]\n"
else:
source_code += f"{var_name}.append({var_value})\n"
continue
# assignment statement
elif "+" in statement or "-" in statement:
operator = "+" if "+" in statement else "-"
line = ""
lhs, rhs_operator = map(str.strip, statement.split("="))
rhs, remainder = map(str.strip, rhs_operator.split(operator, 1))
declaration = False
variable_declaration = lhs + " = "
if variable_declaration not in source_code:
declaration = True
if not declaration:
if lhs == rhs:
line = f"{lhs} {operator}= {remainder}"
else:
line = statement
else:
line = f"{lhs} = {remainder}"
source_code += f"{line}\n"
return self.format_code(source_code)