-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
392 lines (327 loc) · 10.4 KB
/
main.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
import config as cfg
import glob, sys
try:
from colorama import init
init()
except ModuleNotFoundError:
if cfg.colors:
print("\n\nError, colorama module not found, color codes may display weird characters.")
print("If you don't want to install colorama: set 'colors' to False in the file 'config.py'")
print("If you want colors please install colorama use the command")
print("pip install colorama\n\n")
"""TODO
- Sistemare i file di esempio
- Assegnamento esplicito delle celle della memoria all'inizio (solo un idea, non ha impatti sul funzionamento del codice)
SCARTATA, dato che si può semplicemente fare
#FILE main.code
...
END
Celle:
0 somma
1 media
2 valore letto
"""
#colors
class col:
HEADER = '\033[95m' * cfg.colors
CYAN = '\033[96m' * cfg.colors
GREEN = '\033[92m' * cfg.colors
WARNING = '\033[93m' * cfg.colors
FAIL = '\033[91m' * cfg.colors
ENDC = '\033[0m' * cfg.colors
BOLD = '\033[1m' * cfg.colors
class vars:
nIstruzioni = 0
accumulatore = 0
linea = 0
fileInputStrings = []
def getFileNextInput():
try:
return vars.fileInputStrings.pop(0)
except IndexError:
print(f"{col.FAIL}ERROE: Il file {cfg.inputFile} non ha abbastanza input{col.ENDC}")
sys.exit(0)
def incIst():
vars.nIstruzioni += 1
#i/o instructions
def read(prompt = ''):
vars.incIst()
if(cfg.useFileInput):
inp = vars.getFileNextInput()
else:
inp = input(f'{col.CYAN}input ({prompt})> ')
try: #ensures to store an int if the value is a number
vars.accumulatore = int(inp)
except:
vars.accumulatore = inp
print(col.ENDC, end = '')
def write():
vars.incIst()
nastroScr = vars.accumulatore
print(f'{col.GREEN}output > {nastroScr}')
print(col.ENDC, end = '')
def load(x, mem):
vars.incIst()
vars.accumulatore = mem[int(x)]
def store(x, mem):
vars.incIst()
mem[int(x)] = vars.accumulatore
#arithmetic instructions
def add(x, mem):
vars.incIst()
vars.accumulatore += mem[int(x)]
def sub(x, mem):
vars.incIst()
vars.accumulatore -= mem[int(x)]
def mult(x, mem):
vars.incIst()
vars.accumulatore *= mem[int(x)]
def div(x, mem):
vars.incIst()
vars.accumulatore //= mem[int(x)]
def loadEq(x):
vars.incIst()
vars.accumulatore = x
def addEq(x):
vars.incIst()
vars.accumulatore += x
def subEq(x):
vars.incIst()
vars.accumulatore -= x
def multEq(x):
vars.incIst()
vars.accumulatore *= x
def divEq(x):
vars.incIst()
vars.accumulatore //= x
#logic instructions
def br(x): #BRanch (unconditioned)
vars.incIst()
vars.linea = int(x)
def beq(x): #BranchEQual (if [ACC] == 0)
vars.incIst()
if (vars.accumulatore == 0):
vars.linea = int(x)
def bge(x): #BranchGreaterEqual (if [ACC] >= 0)
vars.incIst()
if (vars.accumulatore >= 0):
vars.linea = int(x)
def bg(x): #BranchGreater (if [ACC] > 0)
vars.incIst()
if (vars.accumulatore > 0):
vars.linea = int(x)
def ble(x): #BranchLowerEqual (if [ACC] <= 0)
vars.incIst()
if (vars.accumulatore <= 0):
vars.linea = int(x)
def bl(x): #BranchLower (if [ACC] < 0)
vars.incIst()
if (vars.accumulatore < 0):
vars.linea = int(x)
def loadAt(x, mem): #Load [memoria[x]]
vars.incIst()
addr = mem[x]
load(int(addr), mem)
def storeAt(x, mem): #Store [memoria[x]]
vars.incIst()
addr = mem[x]
store(int(addr), mem)
#script-related
def parseLine(line):
line = line.split(cfg.commentChar, 1)[0] #remove comments (line is string)
x = line.split() #split string for management (x is list)
return x
def exceptionCatch(live): # handles exceptions below
if live:
print(f"{col.WARNING}l'ultima istruzione sarà ignorata, riscrivila correttamente.{col.ENDC}")
vars.linea -= 1
else:
exit()
# --- Script Start ---
def main():
files = [] #Stores .code dirs
live = False #toggles live interpreter
if(cfg.fileName == ''): #if fileName is blank: look for *.code and ask which to open
x = 0
for file in glob.glob("*.code"):
files.append(file)
print(f"[{x}]{file}")
x+=1
files.append(0) #Last option is live interpreter
print(f"{col.CYAN}[{x}] Interprete live{col.ENDC}")
print("\nQuale file vuoi aprire?") #Query user for file input !
res = int(input("[int] > "))
if(res == len(files)-1): #Live interpreter
live = True
#print('Live interpreter settings:') COMBAK
else: #.code file
cfg.fileName = files[res]
if(cfg.useFileInput and live): #toggles stdin from file/user input
with open(cfg.inputFile) as f:
vars.fileInputStrings = f.read().splitlines()
with open(cfg.outputFile, "w") as f: #Resets output file
f.write('')
#init vars
nastroScr = 0 #stdin
memoria = {} #ram structure: memoria{addr: val}
#system vars
rawCode = [] #to be parsed
code = {} #structure: code{x: [istr, val]} (val has int casts for specific use cases)
#es: code{0: ['LOAD', '1']} (eg. mem addr can't be string)
if not live: #if not live -> parse .code file
#open and read istructions
with open(cfg.fileName) as f:
rawCode = f.readlines()
#separate istructions from arguments, and remove comments
i = 0
for line in rawCode:
x = parseLine(line) #x is list (eg. x -> ['load=', '120'])
#store commands in dict {row:[istr, arg]} row always starts at 0
if(x != []): #if row is not comment
try: #has args
code[i] = [x[0].upper(), x[1]] #[istr, arg]
except IndexError: #has no args
code[i] = [x[0].upper()] #[istr]
i+=1
hadLnstrt = 0
hadEnd = 1
for x in code:
if(code[x][0] == 'LNSTRT'):
cfg.startLine = int(code[x][1])
hadLnstrt = x
if(code[x][0] == 'END'):
hadEnd = 0
if(hadLnstrt): #if it had LNSTRT delete the dict key containing that instruction
del code[hadLnstrt]
del hadLnstrt
if(hadEnd): #if it had no END instruction add it at the end
code[len(code)] = ['END']
#mainloop
while True: #until END instruction
istrLn = vars.linea #si riferisce all'istruzione in linea vars.linea
vars.linea += 1
if live: #[ISTR ln: linea-1 | ACC: acc]
code[istrLn] = parseLine(input(f'{col.BOLD}{col.GREEN}[ISTR {col.WARNING}ln: {istrLn} | ACC: {vars.accumulatore}{col.GREEN}]{col.ENDC} > '))
code[istrLn][0] = code[istrLn][0].upper()
try:
istr = code[istrLn][0] #command x
except IndexError:
istr = None
try:
arg = code[istrLn][1] #arg x
arg = int(arg)
except IndexError: # arg does not exist
arg = None
except ValueError: # arg is not a number
arg = arg
def printDebug():
if(cfg.showDebug):
print(f' [DEBUG]---------{col.BOLD}istr:{vars.nIstruzioni}{col.ENDC}-------[ln:{istrLn+cfg.startLine}]')
print(f' [ACC]: {vars.accumulatore}')
print(f' [MEM]: {memoria}')
print(f' istr:{col.WARNING} {istr}{col.ENDC}; arg:{col.WARNING} {arg}{col.ENDC}')
if(not cfg.minimalOutput and cfg.outputFile != ''):
with open(cfg.outputFile, "a") as f:
f.write(f'[DEBUG]---------istr:{vars.nIstruzioni}-------[ln:{istrLn+cfg.startLine}]\n')
f.write(f'[ACC]: {vars.accumulatore}\n')
f.write(f'[MEM]: {memoria}\n')
f.write(f'istr: {istr}; arg: {arg}\n')
if not(istr == 'STORE' or istr == 'LOAD' or istr == 'STORE@' or istr == 'LOAD@' or istr == 'LOAD='): #prints debug before READ||WRITE instruction (to avoid confusion)
printDebug()
#instructions
try:
if(istr == 'READ'):#i/o
read(arg)
elif(istr == 'WRITE'):
write()
elif(istr == 'LOAD'):#memory
load(arg, memoria)
elif(istr == 'STORE'):
store(arg, memoria)
elif(istr == 'LOAD@'):
loadAt(arg, memoria)
elif(istr == 'STORE@'):
storeAt(arg, memoria)
elif(istr == 'ADD'):#arithmetic
add(arg, memoria)
elif(istr == 'SUB'):
sub(arg, memoria)
elif(istr == 'MULT'):
mult(arg, memoria)
elif(istr == 'DIV'):
div(arg, memoria)
elif(istr == 'LOAD='):
loadEq(arg)
elif(istr == 'ADD='):
addEq(arg)
elif(istr == 'SUB='):
subEq(arg)
elif(istr == 'MULT='):
multEq(arg)
elif(istr == 'DIV='):
divEq(arg)
elif(istr == 'BR'):#logic
br(arg-cfg.startLine)
elif(istr == 'BEQ'):
beq(arg-cfg.startLine)
elif(istr == 'BGE'):
bge(arg-cfg.startLine)
elif(istr == 'BG'):
bg(arg-cfg.startLine)
elif(istr == 'BLE'):
ble(arg-cfg.startLine)
elif(istr == 'BL'):
bl(arg-cfg.startLine)
elif (istr == 'END'):
break #exits 'while True'
else:
print(f'{col.FAIL}ERROR, command not found')
print(f' ->"{istr}"')
print(f'{col.BOLD} line:{istrLn+cfg.startLine}{col.ENDC}')
except KeyError: #Could be triggered by x in: LOAD x; STORE x; LOAD@ x; STORE@ x;
print(f'{col.FAIL}ERROR, address in memory does not exit')
print(f' AT LINE: {istrLn+cfg.startLine}')
print(f' [MEM]: {memoria}')
print(f' istr -> istr:{col.WARNING} {istr}{col.FAIL}; arg:{col.WARNING} {arg}{col.ENDC}')
exceptionCatch(live)
except ZeroDivisionError:
print(f'{col.FAIL}ERROR, Division by 0')
print(f' AT LINE: {istrLn+cfg.startLine}')
print(f' [MEM]: {memoria}')
print(f' istr -> istr:{col.WARNING} {istr}{col.FAIL}; arg:{col.WARNING} {arg}{col.ENDC}')
exceptionCatch(live)
except TypeError:
print(f'{col.FAIL}ERROR, (probabile) InputError')
print(f" L'input inserito non è valido!")
print(f' AT LINE: {istrLn+cfg.startLine}')
print(f' [ACC]: {vars.accumulatore}')
print(f' [MEM]: {memoria}')
print(f' istr -> istr:{col.WARNING} {istr}{col.FAIL}; arg:{col.WARNING} {arg}{col.ENDC}')
exceptionCatch(live)
except ValueError:
print(f'{col.FAIL}ERROR, (probabile) Invalid Argument')
print(f" L'argomento inserito non è valido!")
print(f' AT LINE: {istrLn+cfg.startLine}')
print(f' [ACC]: {vars.accumulatore}')
print(f' [MEM]: {memoria}')
print(f' istr -> istr:{col.WARNING} {istr}{col.FAIL}; arg:{col.WARNING} {arg}{col.ENDC}')
exceptionCatch(live)
#prints debug after instruction if istr is not READ or WRITE (to avoid confusion with instructions like STORE)
if (istr == 'STORE' or istr == 'LOAD' or istr == 'STORE@' or istr == 'LOAD@' or istr == 'LOAD='):
printDebug()
#print output
print(' -- FINAL OUTPUT --')
print(f'[MEM]: {memoria}')
print(f'tot: {vars.nIstruzioni} istruzioni {col.ENDC}')
print(f'{col.HEADER}{col.BOLD}[ACC]: {vars.accumulatore}{col.GREEN}{col.ENDC}\n')
if(not cfg.minimalOutput and cfg.outputFile != ''):
with open(cfg.outputFile, "a") as f:
f.write(' -- FINAL OUTPUT --\n')
f.write(f'[MEM]: {memoria}\n')
f.write(f'tot: {vars.nIstruzioni} istruzioni\n')
f.write(f'[ACC]: {vars.accumulatore}\n')
elif(cfg.outputFile != ''):
with open(cfg.outputFile, "a") as f:
f.write(f'{vars.accumulatore}')
if __name__ == "__main__":
main()