-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocks-interpreter.py
279 lines (232 loc) · 9.94 KB
/
locks-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
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
import sys
import argparse
import os
import tkinter as tk
from time import time
from locks.lexer.lexer import Lexer
from locks.parser.parser import Parser
from locks.analyzer.analyzer import SemanticAnalyzer
from locks.interpreter.interpreter import Interpeter
from locks.compiler.compiler import Compiler
from locks.assembler.asm import Assembler
from locks.vm.vm import VirtualMachine
from locks.error import Error
from locks.visualizeAST.gendot import VisualizeAST
def main():
# setup CLI
argParser = argparse.ArgumentParser(
description="locks-py: the locks interpreter"
)
argParser.add_argument(
'path',
metavar='path',
type=str,
help='path to a locks(.lks) file'
)
argParser.add_argument(
'-d',
'--debug',
action='store_true',
help='Use the tree walk interpreter instead of the locks VM to execute code.',
)
argParser.add_argument(
'-b',
'--bytecode',
metavar="<output-filename>",
help='Store code generated by compiler in specified file.',
)
argParser.add_argument(
'-v',
'--viewBytecode',
action='store_true',
help='Output code generated by compiler to stdout.',
)
argParser.add_argument(
'-g',
'--genASTdot',
metavar="<output-filename>",
help='Generate a graphviz dot file to visualize AST. Generated code will be stored in specified file.',
)
args = argParser.parse_args()
# open and read locks file
try:
program = open(args.path, 'r', encoding='unicode_escape').read()
except FileNotFoundError:
print(f"Error: file '{args.path}' not found")
return 1
except Exception as e:
print(f"Error opening file '{args.path}'")
print(f"Error: {e}")
return 1
# lexer - split into tokens
l = Lexer(program)
tokl = l.getTokens()
if l.hadError:
for e in l.getErrorList():
print(e)
if args.debug:
input("\nPress Enter to continue...")
return -1
# parser - pass in token list and construct ast
p = Parser(tokl)
ast = p.getAST()
if p.hadError:
for i in p.getError():
print(i)
if args.debug:
input("\nPress Enter to continue...")
return -1
# visualize AST
if args.genASTdot:
vis = VisualizeAST()
vis.visit(ast)
dot = vis.getDot()
try:
f = open(args.genASTdot, 'w')
except (IsADirectoryError, NotADirectoryError):
print("Please enter a valid filename or a path to a file. Note that if the file is in a subdirectory, the subdirectory must already exist. If the specified file does not exist, it will be created.")
input("\nPress Enter to continue...")
return -1
except Exception as e:
print(f"Unable to open '{args.genASTdot}'. Please enter a valid filename or make sure that the script has enough permissions.")
print(f"Error: {e}")
input("\nPress Enter to continue...")
return -1
try:
import requests
except ModuleNotFoundError:
f.write(dot)
f.close()
print(f"'requests' module was not installed or found. A dot file was written to {args.genASTdot}. Install the requests module with 'pip install requests', or visit https://github.com/1Hibiki1/locks-py#visualizing-the-ast for more information.")
input("\nPress Enter to continue...")
return -1
except Exception as e:
f.write(dot)
f.close()
print(f"An unexpected error occured when importing the 'requests' module. A dot file was written to {args.genASTdot}. For more information, visit https://github.com/1Hibiki1/locks-py#visualizing-the-ast.")
print(f"Error: {e}")
input("\nPress Enter to continue...")
return -1
finally:
f.write(dot)
f.close()
f = open(f"{os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.svg", 'w')
try:
print("Working on it...\n")
r = requests.get(f'https://quickchart.io/graphviz?&graph={requests.utils.quote(dot)}', timeout=15)
except (requests.ConnectionError, requests.Timeout):
print(f"Unable to render {args.genASTdot}. Either there is no internet connection, or the generated dot file was too large (> 2048 characters). Visit https://github.com/1Hibiki1/locks-py#visualizing-the-ast for more information about how to render the generated dot file.\n")
input("\nPress Enter to continue...")
return -1
f.write(r.text)
f.close()
try:
import cairosvg
except ModuleNotFoundError:
print(f"'cariosvg' module was not installed or found. An svg file was written to {os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.svg. You can open this svg file to view the image generated from the AST. For more information, visit https://github.com/1Hibiki1/locks-py#visualizing-the-ast.")
input("\nPress Enter to continue...")
return -1
except Exception as e:
print(f"An unexpected error occured when importing the 'cairosvg' module. An svg file was written to {os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.svg. You can open this svg file to view the image generated from the AST. For more information, visit https://github.com/1Hibiki1/locks-py#visualizing-the-ast.")
print(f"Error: {e}")
input("\nPress Enter to continue...")
return -1
try:
cairosvg.svg2png(
url=f'{os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.svg',
write_to=f"{os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.png",
scale=0.5
)
except Exception as e:
print(f"An unexpected error occured while converting {args.genASTdot} to svg. Visit https://github.com/1Hibiki1/locks-py#visualizing-the-ast for more information about how to render the generated dot file. If the dot file doesn't render correctly, open an issue.\n")
print(f"Error: {e}")
input("\nPress Enter to continue...")
return -1
try:
from PIL import Image, ImageTk
except ModuleNotFoundError:
print(f"'Pillow' module was not installed or found. An png file was written to {os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.png. You can open this png file to view the image generated from the AST. For more information, visit https://github.com/1Hibiki1/locks-py#visualizing-the-ast.")
input("\nPress Enter to continue...")
return -1
except Exception as e:
print(f"An unexpected error occured when importing the 'Pillow' module. An png file was written to {os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.png. You can open this png file to view the image generated from the AST. For more information, visit https://github.com/1Hibiki1/locks-py#visualizing-the-ast.")
print(f"Error: {e}")
input("\nPress Enter to continue...")
return -1
wnd = tk.Tk()
img = Image.open(f'{os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.png')
pimg = ImageTk.PhotoImage(img)
size = img.size
frame = tk.Canvas(wnd, width=size[0], height=size[1])
frame.pack()
frame.create_image(0,0,anchor='nw',image=pimg)
print(f"\nIf the complete image doesn't fit in the window, try opening it with an external image viewer. The image was saved at '{os.path.dirname(args.genASTdot)}/{os.path.basename(args.genASTdot)}.png'.\n")
wnd.mainloop()
input("\nPress enter to continue...")
return 0
# semantic analyser - check ast for static semantic errors
s = SemanticAnalyzer()
s.visit(ast)
if s.hadError:
for e in s.getErrorList():
print(e)
if args.debug:
input("\nPress Enter to continue...")
return -1
# -b specified, output generated code
if args.bytecode:
c = Compiler()
c.visit(ast)
code = c.getCode()
outputf = open(args.bytecode, "w")
outputf.write(code)
outputf.close()
return 0
if args.viewBytecode:
c = Compiler()
c.visit(ast)
print(c.getCode())
return 0
# -d specified, use tree walk interpreter
if args.debug:
try:
t0 = time()
i = Interpeter()
i.visit(ast)
print(f"\nProcess finished in {time() - t0} seconds with return code 0")
input("Press Enter to continue...")
except KeyboardInterrupt:
print("\nKeyboard Interrupt")
print(f"\nProcess finished in {time() - t0} seconds with return code -1")
input("Press Enter to continue...")
return -1
except Error as e:
print(e)
print(f"\nProcess finished in {time() - t0} seconds with return code -1")
input("Press Enter to continue...")
return -1
except:
print("The interpreter crashed! Check the Known Bugs sections in the Locks github repository (https://github.com/1Hibiki1/locks-py) or open an issue.")
return -1
# run VM
else:
try:
c = Compiler()
c.visit(ast)
code = c.getCode()
except:
print("\n Compile Error. Exiting...")
return -1
try:
a = Assembler(code)
b = a.getBytecodeList()
#for i in b:
# print(hex(i), end=' ')
v = VirtualMachine(b)
v.run()
except Error as e:
print(e)
return -1
return 0
if __name__ == '__main__':
main()