-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathast.py
539 lines (457 loc) · 17.2 KB
/
ast.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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
from values import *
from simbolos import *
import tkinter
from tkinter import simpledialog
from tkinter.messagebox import showinfo
import re
errorSemantico = []
class Nodo:
def ejecutar(self,metodos,ts):
pass
def graficar(self, metodos, ts):
pass
class Root(Nodo):
def __init__(self,inst):
self.inst = inst
def ejecutar(self,metodos, ts):
for x,y in self.inst.items():
metodos.metodos[x] = y
nodo = self.inst.get("main")
if(nodo!=None):
v = 0
for x,y in self.inst.items():
if(x=="main"):
flag =1
if(flag==1):
v = y.ejecutar(ts,ts)
if(v==1):
break
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="ROOT "] \n '
for x,y in self.inst.items():
v+="n"+str(node)+"->"+y.ast()
return v
def getHash(obj):
return hash(obj)
def calcularArreglo(var,indx,args,metodos,ts,val):
v = var.ejecutar(metodos,ts)
i = args[indx].ejecutar(metodos,ts)
if(i.tipo==TIPO.ENTERO or i.tipo == TIPO.STRING):
if(indx==len(args)-1):
if(v.tipo==TIPO.STRING):
v.value = v.value[:i.value]+val.value+v.value[i.value+1:]
elif(v.tipo==TIPO.ARRAY):
v.value[i.value] = val
else:
if(v.tipo==TIPO.ARRAY):
if(i.value) in v.value:
v.value[i.value] = calcularArreglo(v.value[i.value],indx+1,args,metodos,ts,val)
else:
v.value[i.value] = Valor({},TIPO.ARRAY)
v.value[i.value] = calcularArreglo(v.value[i.value],indx+1,args,metodos,ts,val)
else:
return Valor("Indice no es numero ni String.",TIPO.ERROR)
return v
class Tag(Nodo):
# Esta clase permite guardar las instrucciones de las clases
def __init__(self, nombre, instrucciones, linea):
self.instrucciones = instrucciones
self.nombre = nombre
self.linea = linea
def ejecutar(self, metodos, ts):
print(self.nombre," :")
for inst in self.instrucciones:
print(inst)
a = inst.ejecutar(metodos,ts)
if(isinstance(inst,Salto)):
return 1
if(isinstance(inst,Exit)):
return 1
if(isinstance(inst,Si)and(a==1)):
return 1
return 0
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="ETIQUETA: '+ self.nombre+'"] \n '
for x in self.instrucciones:
v+="n"+str(node)+"->"+x.ast()
return v
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido Etiqueta '''+ self.nombre +''' </td> </tr>
<tr>
<td> <p>ListaInstrucciones => ListaInstrucciones PC ";"<br/> | Instrucciones PC ";"<br/> </p></td>
<td><p>
if(len(t)==3):<br/>
t[0] = []<br/>
t[0].append(t[1])<br/><br/>
if(len(t)==4):<br/>
t[0] = t[1]<br/>
t[0].append(t[2]) </p></td>
</tr>
<tr>
<td> Intrucciones => asignacion<br/>
| iff<br/>
| jump<br/>
| printt<br/>
| ext<br/>
| uns<br/> </td> <td> <p> t[0] = t[1] </p> </td>
</tr>\n''')
for x in (self.instrucciones):
try:
v+=x.grammarASC()
except Exception as ex:
print("ERrrrrrroooooooorrrrrrrrrrrrrr: "+ str(ex))
return v
class Print(Nodo):
#Esta clase permite imprimir un valor.
def __init__(self, valor, linea):
self.valor = valor
self.linea = linea
def ejecutar(self,metodos,ts):
if(self.valor==None):
metodos.errores.append(Simbolo("Error Semantico: No existe un valor para el Print, viene un valor Nulo!",self.linea))
return
v = self.valor.ejecutar(metodos,ts)
if(v.tipo==TIPO.ERROR):
metodos.errores.append(Simbolo("Error Semantico: No existe un valor para Imprimir!\n"+v.value,self.linea))
return
metodos.mensajes.append(v.value)
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="PRINT()"] \n '
v+="n"+str(node)+"->"+self.valor.ast()
return v
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido PRINT '''+ " " +''' </td> </tr>
<tr>
<td> <p>Print => PRINT LEFTPAR "(" ID2 ")" <br/> ID2 => ID LArray <br/> | ID <br/> LArray => IZQLLAVE"[" Expresion DERLLAVE"]" </p></td>
<td><p> t[0] = Print()</p></td>
</tr>\n'''+self.valor.grammarASC())
return v
class Unset(Nodo):
#Esta clase permite imprimir un valor.
def __init__(self, valor, linea):
self.valor = valor
self.linea = linea
def ejecutar(self,metodos,ts):
if self.valor.valor in metodos.variables:
del metodos.variables[self.valor.valor]
else:
metodos.errores.append(Simbolo("Error Semantico: No existe la variable en la tabla de simbolos! No se puede hacer Pop",self.linea))
return 0
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Unset()"] \n '
v+="n"+str(node)+"->"+self.valor.ast()
return v
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido Unset '''+ " " +''' </td> </tr>
<tr>
<td> <p>Unset => Unset LEFTPAR "(" ID2 ")" <br/> ID2 => ID LArray <br/> | ID <br/> LArray => IZQLLAVE"[" Expresion DERLLAVE"]" </p></td>
<td><p> t[0] = Unset(t[3]</p></td>
</tr>\n''')
return v
class Array(Nodo):
#Esta clase permite imprimir un valor.
def __init__(self):
pass
def ejecutar(self,metodos,ts):
return Valor({},TIPO.ARRAY)
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Array()"] \n '
return v
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido ARRAY '''+ " " +''' </td> </tr>
<tr>
<td> <p>arry => ARRAY LEFTPAR "(" DERPAR ")" <br/> </td>
<td><p> Se crea un objeto de tipo Array. </p></td>
</tr>\n''')
return v
class Leer(Nodo):
#Esta clase permite imprimir un valor.
def __init__(self):
pass
def ejecutar(self,metodos,ts):
tk = tkinter.Tk() # Create the object
tk.withdraw()
name = simpledialog.askstring("Information","Mensaje")
tk.destroy()
print("Read >>> ",name)
metodos.mensajes.append("Read>>> "+str(name))
if(re.match(r'-?\d+\.\d+',name)!=None):
print("----------- VALOR DOBLE------------")
return Valor(float(name),TIPO.DOBLE)
if(re.match(r'-?\d+',name)!=None):
print(".---------- VALOR ENTERO ---------------")
return Valor(int(name),TIPO.ENTERO)
return Valor(name,TIPO.STRING)
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Read()"] \n '
return v
v
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido READ '''+ " " +''' </td> </tr>
<tr>
<td> <p>arry => Read LEFTPAR "(" DERPAR ")" <br/> </td>
<td><p> t[0] = Leer(). </p></td>
</tr>\n''')
return v
class Exit(Nodo):
#Esta clase permite imprimir un valor.
def __init__(self):
pass
def ejecutar(self,metodos,ts):
return 1
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Exit"] \n '
return v
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido EXIT '''+ " " +''' </td> </tr>
<tr>
<td> <p>ext => exit </p></td>
<td><p> t[0] = Exit() </p></td>
</tr>\n''')
return v
class Asignacion(Nodo):
#Esta clase representa una asignación
def __init__(self,variable, expresion, linea):
self.variable = variable
self.expresion = expresion
self.linea = linea
def ejecutar(self, metodos, ts):
if(self.expresion==None):
metodos.errores.append(Simbolo("Error Semantico: No existe un valor, viene un valor Nulo!",self.linea))
return
v1 = self.expresion.ejecutar(metodos,ts)
if(v1.tipo==TIPO.ERROR):
metodos.errores.append(Simbolo("Error Semantico: No se puede asignar, hay un error\n"+v1.value,self.linea))
return
if self.variable.args == None:
if self.variable.valor in metodos.variables:
metodos.añadirVariable(self.variable.valor,v1,"1,1")
else:
metodos.añadirVariable(self.variable.valor,v1,"1,1")
else:
for x in self.variable.args:
print(x.ejecutar(metodos,ts).value)
if self.variable.valor in metodos.variables:#HAY UNA VARIABLE
v = metodos.variables.get(self.variable.valor).valor
v = calcularArreglo(v,0,self.variable.args,metodos,ts,v1)
metodos.añadirVariable(self.variable.valor,v,"1,1")
else: #CREAR ARREGLO
v = Valor({},TIPO.ARRAY)
v = calcularArreglo(v,0,self.variable.args,metodos,ts,v1)
metodos.añadirVariable(self.variable.valor,v,"1,1")
if(v1!=None):
print("La variable ",self.variable.valor," = ",v1.value)
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido ASIGNACION '''+ " " +''' </td> </tr>
<tr>
<td> <p>asignacion => var2 IGUAL exp </p></td>
<td><p> t[0] = Asignacion(t[1],t[3]) </p></td>
</tr>
<tr>
<td> var2 => VAR arr <br/> arr </td> <td>
if(len(t)==3): <br/>
t[0] = NodoVariable(t[1],t[2]) <br/>
else: <br/>
t[0] = NodoVariable(t[1],None) </td>
</tr>
<tr>
<td> arr => arr IZQLLAVE E DERLLAVE <br/> | IZQLLAVE E DERLLAVE</td> <td> if(len(t)==5):<br/>
lar = t[1]<br/>
lar.append(t[3])<br/>
t[0] = lar <br/>
else:<br/>
lar = []<br/>
lar.append(t[2])<br/>
t[0] = lar </td><br/>
</tr>\n'''+self.expresion.grammarASC())
return v
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Asignacion: '+ self.variable.valor+'"] \n n'+str(node)+" ->"+self.expresion.ast()
return v
class Si(Nodo):
#Esta clase representa un salto condicional
def __init__(self, condicion, etiqueta, linea):
self.condicion = condicion
self.etiqueta = etiqueta
self.linea = linea
def ejecutar(self, metodos, ts):
if(self.condicion==None):
metodos.errores.append(Simbolo("Error Semantico: No existe un valor, viene un valor Nulo!",self.linea))
return
cond = self.condicion.ejecutar(metodos,ts)
if(cond.tipo==TIPO.ERROR):
metodos.errores.append(Simbolo("Error Semantico: No se puede asignar, hay un error\n"+cond.value,self.linea))
return
if(cond.value == 1):
flag = 0
v = 1
for x,y in metodos.metodos.items():
if(x==self.etiqueta):
flag =1
if(flag==1):
v = y.ejecutar(metodos,ts)
if(v==1):
break
if(flag==1):
return 1
else:
print("Error Semantico: No existe la etiqueta!")
return 1
else:
print("No se cumplio la condición")
return 0
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido SALTO CONDICIONAL '''+ " " +''' </td> </tr>
<tr>
<td> <p>iff => if IZQPAR "(" exp DERPAR ")" goto ID</p></td>
<td><p> t[0] = Si(t[3],t[6]) </p></td>
</tr>\n'''+self.condicion.grammarASC())
return v
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Salto Condicional A: '+ self.etiqueta+'"] \n n'+str(node)+" ->"+self.condicion.ast()
return v
class Salto(Nodo):
#Esta clase representa un salto normal
def __init__(self,etiqueta, linea):
self.etiqueta = etiqueta
self.linea = linea
def ejecutar(self, metodos, ts):
flag = 0
v = 1
for x,y in metodos.metodos.items():
if(x==self.etiqueta):
flag =1
if(flag==1):
v = y.ejecutar(metodos,ts)
if(v==1):
return 1
def grammarASC(self):
v =('''<tr> <td colspan=2 class="et" > Contenido SALTO '''+ " " +''' </td> </tr>
<tr>
<td> <p>jump => goto ID";" </p></td>
<td><p> t[0] = Salto(t[2]) </p></td>
</tr>\n''')
return v
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Goto: '+ self.etiqueta+'"] \n '
return v
class NodoEntero(Nodo):
#Esta clase representa cuando viene un valor entero
def __init__(self, valor):
self.valor = valor
def ejecutar(self, metodos, ts):
return Valor(self.valor, TIPO.ENTERO)
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Entero: '+ str(self.valor)+'"] \n '
return v
def grammarASC(self):
v =('''
<tr>
<td> <p>E => ENTERO <br/> </p></td>
<td><p>t[0] = NodoEntero(t[1]) </p></td>
</tr>''')
return v
class NodoDouble(Nodo):
#Esta clase representa cuando viene un valor entero
def __init__(self, valor):
self.valor = valor
def ejecutar(self, metodos, ts):
return Valor(self.valor, TIPO.DOBLE)
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Doble: '+ str(self.valor)+'"] \n '
return v
def grammarASC(self):
v =('''
<tr>
<td> <p>E => DOBLE <br/> </p></td>
<td><p>t[0] = NodoDouble(t[1]) </p></td>
</tr>''')
return v
class NodoCadena(Nodo):
#Esta clase representa cuando viene un valor entero
def __init__(self, valor):
self.valor = valor
def ejecutar(self, metodos, ts):
return Valor(self.valor, TIPO.STRING)
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Cadena: '+ self.valor+'"] \n '
return v
def grammarASC(self):
v =('''
<tr>
<td> <p>E => CADENA <br/> </p></td>
<td><p>t[0] = NodoCadena(t[1]) </p></td>
</tr>''')
return v
class NodoArreglo(Nodo):
#Esta clase representa cuando viene un valor entero
def __init__(self, valor):
pass
class NodoVariable(Nodo):
#Esta clase representa cuando viene un valor entero
def __init__(self, valor, args):
self.valor = valor
self.args = args
def ejecutar(self, metodos, ts):
try:
v = metodos.variables.get(self.valor).valor
val = v
if(self.args!=None):
for x in self.args:
if(v.tipo == TIPO.ARRAY):
v = v.value.get(x.ejecutar(metodos,ts).value)
elif(v.tipo == TIPO.STRING):
v = Valor(v.value[x.ejecutar(metodos,ts).value],TIPO.STRING)
else:
v = v
val = v
if(val.tipo== TIPO.PUNTERO):
val = metodos.variables.get(val.value).valor
return val
except Exception as e:
return Valor("Error Semantico: No se encontro la variable!",TIPO.ERROR)
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="Variable: '+ self.valor+'"] \n '
return v
def grammarASC(self):
v =('''
<tr>
<td> <p>E => ID <br/>| ID LCOR <br/> LCOR => LCOR [E] <br/> | [E] </p></td>
<td><p> t[0] = NodoVariable(t[1]) </p></td>
</tr>''')
return v
class NodoPuntero(Nodo):
#Esta clase representa cuando viene un valor entero
def __init__(self, valor):
self.valor = valor
def ejecutar(self, metodos, ts):
try:
v = metodos.variables.get(self.valor).valor
return Valor(self.valor,TIPO.PUNTERO)
except Exception as e:
return Valor("Error Semantico: No se encontro la variable!",TIPO.ERROR)
def ast(self):
node = abs(hash(self))
v = "n"+str(node)+"\nn"+str(node)+'[label="PUNTERO : '+ self.valor+'"] \n '
return v
def grammarASC(self):
v =('''
<tr>
<td> <p>E => PUNTERO "&" ID <br/> </p></td>
<td><p>t[0] = NodoPuntero(t[1],t[3]) </p></td>
</tr>''')
return v