-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpeterparser_predictivo.py
242 lines (185 loc) · 9.53 KB
/
peterparser_predictivo.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
from lexer import lexer
"""
Implementación procedural de analizador sintáctico descendente predictivo.
Esta version es predictiva ya que se tienen los simbolos directrices de las producciones de la gramatica
"""
'''
__
/ l
.' : __.....__..._ ____
/ / \ _.-" "-. "" "-.
(`-: .---: .--.' _....J. "-.
"""y \,.' \ __..--"" `+""--. `.
: .'/ .-"""-. _. `. "-. `._.._
; _.'.' .-j `. \ "-. "-._`.
: / .-" : \ `-. `- "-. \
; /.' ; :; ." \ `,
:_:/ ::\ ;: ( / .-" .') ;
;-" ; "-. / ; .^. .' .' / .-"
/ .- : `. '. : .- / __.-j.'.' .-" /.---'
/ / `,\. .' "":' /-" .' \__.'
: : ,\"" ; .' .' .-""
_J ; ; `. /.' _/ \.-"
/ "-: /"--.b-..-' .' ;
/ / ""-..' .--'.-'/ , :
:`. : / : bug `-i" ,',_: _ \
: \ '._ :__; .'.-"; ; ; j `.l
\ \ "-._ `" :_/ :_/
`.;\ "-._
:_"-._ "-.
`. l "-. ) `.
""^--""^-. : \
"; \
: `._
; / \ `._ ""---.
/ / _ `.--.__.'
: : / ; :". \
; ; : : ; `. `.
/ ; : ; : `. `.
/ /: ; : ; "-'
:_.' ; ; ; :
/ / :_l
`-'
'''
# Gramática posta LL(1) con los terminales como texto
SD = {
'Program' : {"si" : ['ListaSentencias'],"func" : ['ListaSentencias'],
"repetir" : ['ListaSentencias'], "leer" : ['ListaSentencias'],
"mostrar" : ['ListaSentencias'],"id" : ['ListaSentencias']},
'ListaSentencias' : {"si" : ['Sentencia','ListaSentenciasPrima'],
"func" : ['Sentencia','ListaSentenciasPrima'], "repetir" : ['Sentencia','ListaSentenciasPrima'],
"leer" : ['Sentencia','ListaSentenciasPrima'], "mostrar" : ['Sentencia','ListaSentenciasPrima'],
"id" : ['Sentencia','ListaSentenciasPrima']},
'ListaSentenciasPrima' : { "sino" : [], "finsi" : [], "finfunc" : [''],
"hasta" : [], ";" : [";", 'Sentencia', 'ListaSentenciasPrima'],'#':[]},
'Sentencia' : {"si" : ['SentenciaSi'],"func" : ['SentenciaFun'], "repetir" : ['SentenciaRepetir'],
"leer" : ['SentenciaLeer'], "mostrar" : ['SentenciaMostrar'],
"id" : ['SentenciaAsig']},
'SentenciaSi' : {"si" : ["si", 'Expresion', "entonces", 'ListaSentencias', 'SentenciaSiPrima']},
'SentenciaSiPrima' : { "sino" : ["sino", 'ListaSentencias', "finsi"], "finsi" : ["finsi"]},
'SentenciaRepetir' : { "repetir" : ["repetir", 'ListaSentencias', "hasta", 'Expresion']},
'SentenciaAsig' : {"id" : ["id", "equal", 'Expresion']},
'SentenciaLeer' : { "leer" : ["leer", "id"]},
'SentenciaMostrar' : {"mostrar" : ["mostrar", 'Expresion']},
'SentenciaFun' : {"func" : ["func", 'Proc', "finfunc"]},
'Proc' : {"id" : ["id", "(", 'ListaPar', ")", 'ListaSentencias']},
'ListaPar' : {"id" : ["id", 'ListaParPrima']},
'ListaParPrima' : {")" : [],";" : [";", "id" ,'ListaParPrima']},
'Expresion' : {"id" : ['Expresion2', 'ExpresionPrima'], "num" : ['Expresion2', 'ExpresionPrima'],
"(" : ['Expresion2', 'ExpresionPrima']},
'ExpresionPrima' : {"sino" : [], "entonces" : [], "finsi" : [], "finfunc" : [],
"hasta" : [], "oprel" : ["oprel", 'Expresion2'], ")" : [],
";" : [],'#':[]},
'Expresion2' : {"id" : ['Termino', 'Expresion2Prima'], "num" : ['Termino', 'Expresion2Prima'],
"(" : ['Termino', 'Expresion2Prima']},
'Expresion2Prima' : {"sino" : [], "entonces" : [], "finsi" : [], "finfunc" : [],
"hasta" : [], "oprel" : [], ")" : [],
";" : [] , "opsuma" : ["opsuma", 'Termino', 'Expresion2Prima'],'#':[] },
'Factor' : {"id" : ["id"], "num" : ["num"],
"(" : ["(", 'Expresion', ")"]},
'Termino' : {"id" : ['Factor', 'TerminoPrima'], "num" : ['Factor', 'TerminoPrima'],
"(" : ['Factor', 'TerminoPrima']},
'TerminoPrima' : {"sino" : [], "entonces" : [], "finsi" : [], "finfunc" : [],
"hasta" : [],"oprel" : [],")" : [],
";" : [] , "opsuma" : [], "opmult" : ["opmult", 'Factor', 'TerminoPrima'],'#':[]}
}
no_terminales = ['Program','ListaSentencias','ListaSentenciasPrima', 'Sentencia', 'SentenciaSi', 'SentenciaSiPrima',
'SentenciaRepetir', 'SentenciaAsig', 'SentenciaLeer', 'SentenciaMostrar',
'SentenciaFun', 'Proc', 'ListaPar', 'ListaParPrima', 'Expresion', 'ExpresionPrima', 'Expresion2', 'Expresion2Prima',
'Factor', 'Termino', 'TerminoPrima']
terminales = ["si","sino","entonces","finsi","finfunc",
"func","repetir","hasta","leer","mostrar",
"equal","id","num","oprel","(",
")",";","opsuma","opmult",'#']
# Gloriosa programacion orientada a objetos
class Error:
def __init__(self):
self.__error = False
def activar(self):
self.__error = True
def desactivar(self):
self.__error = False
def obtener(self):
return self.__error
class Puntero:
def __init__(self):
self.__t = 0 # Puntero de la cadena de entrada
def avanzar(self):
self.__t = self.__t + 1
def obtener(self):
return self.__t
def main(cadena):
# Definimos los objetos globales transversales a los procedimientos
error = Error()
puntero = Puntero()
# Comprueba que el puntero ya este "apuntando" al fin de la cadena
def fin_de_cadena(cadena):
return cadena[puntero.obtener()] == '#'
def PNI(noTerminal):
#derivaciones = []
# Obtiene en que puede derivar el no terminal
#derivaciones = gramatica['P'][noTerminal]
error.desactivar()
t = puntero.obtener()
simboloApuntado = cadena[t]
# simbolosDirectricesGramatica.get(VN) devuelve los directrices de cada derivacion de VN
# sd es el simbolo directriz
# i es el indice de la derivacion a la cual pertenece el simbolo directriz
# Ejemplo:
# S -> (B) | a
# simbolos directrices de S: ['(', 'a']
# si simboloApuntado es '(' entonces i = 0 ya que '(' pertenece a la primera derivacion
if simboloApuntado in SD[noTerminal].keys():
parteDerecha = SD [noTerminal][simboloApuntado]
procesar(parteDerecha)
else:
error.activar()
return
def procesar(produccion):
for j in range(0, len(produccion)):
t = puntero.obtener()
# Obtengo el simbolo de la produccion en la posicion j
xj = produccion[j]
# Si es un terminal
if xj in terminales:
if cadena[t] == xj:
puntero.avanzar()
else:
error.activar()
break
# Si es un no terminal
if xj in no_terminales:
PNI(xj)
if error.obtener():
break
PNI('Program')
if not error.obtener() and fin_de_cadena(cadena):
print('PETER PARSER: Cadena aceptada')
else:
print('PETER PARSER: Cadena rechazada. No se puede derivar en el terminal "' + str(lista[puntero.obtener()]) + '" de la posición ' + str(puntero.obtener()) + '.')
# Pruebas
# Cadena de texto de entrada
#cadena = 'si vgAuxi==7, entonces vgAuxi igual 1, sino leer libro. FinSi.'
cadena = "si 6>7 entonces leer id finsi"
# Lista de tokens devuelta por Hannibal Lexer
lista = [token[1] for token in lexer(cadena)]
print('Cadena de tokens: ' + str(lista))
main(lista)
# Cadena de texto de entrada
cadena = 'función y(x): y equal (x * 2) + 3. Finfunción;\nz iqual y'
# Lista de tokens devuelta por Hannibal Lexer
lista = [token[1] for token in lexer(cadena)]
print('Cadena de tokens: ' + str(lista))
main(lista)
# Cadena de texto de entrada
cadena = 'si vgAuxi == 7 entonces vgAuxi equal 1 sino mostrar demostración. FinSi.'
# Lista de tokens devuelta por Hannibal Lexer
lista = [token[1] for token in lexer(cadena)]
print('Cadena de tokens: ' + str(lista))
main(lista)
# Cadena de texto de entrada
cadena = 'func y(x) leer y finfuncion; Repetir x equal x + 1 hasta x>=y.'
# Lista de tokens devuelta por Hannibal Lexer
lista = [token[1] for token in lexer(cadena)]
print('Cadena de tokens: ' + str(lista))
main(lista)