0% encontró este documento útil (0 votos)
56 vistas7 páginas

ANALIZADORSINTACTICO

Este documento describe un analizador léxico y sintáctico para un lenguaje de programación. Define tokens y reglas gramaticales para analizar la sintaxis. El analizador léxico tokeniza cadenas de entrada y el analizador sintáctico valida la gramática mediante funciones que definen producciones. Juntos realizan el análisis sintáctico de un lenguaje.
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
56 vistas7 páginas

ANALIZADORSINTACTICO

Este documento describe un analizador léxico y sintáctico para un lenguaje de programación. Define tokens y reglas gramaticales para analizar la sintaxis. El analizador léxico tokeniza cadenas de entrada y el analizador sintáctico valida la gramática mediante funciones que definen producciones. Juntos realizan el análisis sintáctico de un lenguaje.
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

1 ##ANALIZADOR LEXICO

2 import ply.lex as lex


3
4 # resultado del analisis
5 resultado_lexema = []
6
7 reservada = (
8 # Palabras Reservadas
9 'INCLUDE',
10 'USING',
11 'NAMESPACE',
12 'STD',
13 'COUT',
14 'CIN',
15 'GET',
16 'CADENA',
17 'RETURN',
18 'VOID',
19 'INT',
20 'ENDL',
21 )
22 tokens = reservada + (
23 'IDENTIFICADOR',
24 'ENTERO',
25 'ASIGNAR',
26
27 'SUMA',
28 'RESTA',
29 'MULT',
30 'DIV',
31 'POTENCIA',
32 'MODULO',
33
34 'MINUSMINUS',
35 'PLUSPLUS',
36
37 #Condiones
38 'SI',
39 'SINO',
40 #Ciclos
41 'MIENTRAS',
42 'PARA',
43 #logica
44 'AND',
45 'OR',
46 'NOT',
47 'MENORQUE',
48 'MENORIGUAL',
49 'MAYORQUE',
50 'MAYORIGUAL',
51 'IGUAL',
52 'DISTINTO',
53 # Symbolos
54 'NUMERAL',
55
56 'PARIZQ',
57 'PARDER',
58 'CORIZQ',
59 'CORDER',
60 'LLAIZQ',
61 'LLADER',
62
63 # Otros
64 'PUNTOCOMA',
65 'COMA',
66 'COMDOB',
67 'MAYORDER', #>>
68 'MAYORIZQ', #<<
69 )
70
71 # Reglas de Expresiones Regualres para token de Contexto simple
72
73 t_SUMA = r'\+'
74 t_RESTA = r'-'
75 t_MINUSMINUS = r'\-\-'
76 # t_PUNTO = r'\.'
77 t_MULT = r'\*'
78 t_DIV = r'/'
79 t_MODULO = r'\%'
80 t_POTENCIA = r'(\*{2} | \^)'
81
82 t_ASIGNAR = r'='
83 # Expresiones Logicas
84 t_AND = r'\&\&'
85 t_OR = r'\|{2}'
86 t_NOT = r'\!'
87 t_MENORQUE = r'<'
88 t_MAYORQUE = r'>'
89 t_PUNTOCOMA = ';'
90 t_COMA = r','
91 t_PARIZQ = r'\('
92 t_PARDER = r'\)'
93 t_CORIZQ = r'\['
94 t_CORDER = r'\]'
95 t_LLAIZQ = r'{'
96 t_LLADER = r'}'
97 t_COMDOB = r'\"'
98
99
100
101 def t_INCLUDE(t):
102 r'include'
103 return t
104
105 def t_USING(t):
106 r'using'
107 return t
108
109 def t_NAMESPACE(t):
110 r'namespace'
111 return t
112
113 def t_STD(t):
114 r'std'
115 return t
116
117 def t_COUT(t):
118 r'cout'
119 return t
120
121 def t_CIN(t):
122 r'cin'
123 return t
124
125 def t_GET(t):
126 r'get'
127 return t
128
129 def t_ENDL(t):
130 r'endl'
131 return t
132
133 def t_SINO(t):
134 r'else'
135 return t
136
137 def t_SI(t):
138 r'if'
139 return t
140
141 def t_RETURN(t):
142 r'return'
143 return t
144
145 def t_VOID(t):
146 r'void'
147 return t
148
149 def t_MIENTRAS(t):
150 r'while'
151 return t
152
153 def t_PARA(t):
154 r'for'
155 return t
156
157 def t_ENTERO(t):
158 r'\d+'
159 t.value = int(t.value)
160 return t
161
162 def t_IDENTIFICADOR(t):
163 r'\w+(_\d\w)*'
164 return t
165
166 def t_CADENA(t):
167 r'\"?(\w+ \ *\w*\d* \ *)\"?'
168 return t
169
170 def t_NUMERAL(t):
171 r'\#'
172 return t
173
174 def t_PLUSPLUS(t):
175 r'\+\+'
176 return t
177
178 def t_MENORIGUAL(t):
179 r'<='
180 return t
181
182 def t_MAYORIGUAL(t):
183 r'>='
184 return t
185
186 def t_IGUAL(t):
187 r'=='
188 return t
189
190 def t_MAYORDER(t):
191 r'<<'
192 return t
193
194 def t_MAYORIZQ(t):
195 r'>>'
196 return t
197
198 def t_DISTINTO(t):
199 r'!='
200 return t
201
202 def t_newline(t):
203 r'\n+'
204 t.lexer.lineno += len(t.value)
205
206 def t_comments(t):
207 r'/\*(.|\n)*?\*/'
208 t.lexer.lineno += t.value.count('\n')
209 print("Comentario de multiple linea")
210
211 def t_comments_ONELine(t):
212 r'\/\/(.)*\n'
213 t.lexer.lineno += 1
214 print("Comentario de una linea")
215 t_ignore =' \t'
216
217 def t_error( t):
218 global resultado_lexema
219 estado = "** Token no valido en la Linea {:4} Valor {:16} Posicion {:4}".format(str(t.lineno), str(t.
value),
220 str(t.lexpos))
221 resultado_lexema.append(estado)
222 t.lexer.skip(1)
223
224 # Prueba de ingreso
225 def prueba(data):
226 global resultado_lexema
227
228 analizador = lex.lex()
229 analizador.input(data)
230
231 resultado_lexema.clear()
232 while True:
233 tok = analizador.token()
234 if not tok:
235 break
236 # print("lexema de "+tok.type+" valor "+tok.value+" linea "tok.lineno)
237 estado = "Linea {:4} Tipo {:16} Valor {:16} Posicion {:4}".format(str(tok.lineno),str(tok.type) ,
str(tok.value), str(tok.lexpos) )
238 resultado_lexema.append(estado)
239 return resultado_lexema
240
241 # instanciamos el analizador lexico
242 analizador = lex.lex()
243
244 if __name__ == '__main__':
245 while True:
246 data = input("ingrese: ")
247 prueba(data)
248 print(resultado_lexema)
249
250 ## ANALIZADOR SINTACTICO
251 import ply.yacc as yacc
252 from analizador_lexico import tokens
253 from analizador_lexico import analizador
254
255 # resultado del analisis
256 resultado_gramatica = []
257
258 precedence = (
259 ('right','ASIGNAR'),
260 ('left', 'SUMA', 'RESTA'),
261 ('left', 'MULT', 'DIV'),
262 ('right', 'UMINUS'),
263 )
264 nombres = {}
265
266 def p_declaracion_asignar(t):
267 'declaracion : IDENTIFICADOR ASIGNAR expresion PUNTOCOMA'
268 nombres[t[1]] = t[3]
269
270 def p_declaracion_expr(t):
271 'declaracion : expresion'
272 # print("Resultado: " + str(t[1]))
273 t[0] = t[1]
274
275 def p_expresion_operaciones(t):
276 '''
277 expresion : expresion SUMA expresion
278 | expresion RESTA expresion
279 | expresion MULT expresion
280 | expresion DIV expresion
281 | expresion POTENCIA expresion
282 | expresion MODULO expresion
283
284 '''
285 if t[2] == '+':
286 t[0] = t[1] + t[3]
287 elif t[2] == '-':
288 t[0] = t[1] - t[3]
289 elif t[2] == '*':
290 t[0] = t[1] * t[3]
291 elif t[2] == '/':
292 t[0] = t[1] / t[3]
293 elif t[2] == '%':
294 t[0] = t[1] % t[3]
295 elif t[2] == '**':
296 i = t[3]
297 t[0] = t[1]
298 while i > 1:
299 t[0] *= t[1]
300 i -= 1
301
302 def p_expresion_uminus(t):
303 'expresion : RESTA expresion %prec UMINUS'
304 t[0] = -t[2]
305
306 def p_expresion_grupo(t):
307 '''
308 expresion : PARIZQ expresion PARDER
309 | LLAIZQ expresion LLADER
310 | CORIZQ expresion CORDER
311 '''
312 t[0] = t[2]
313 # sintactico de expresiones logicas
314 def p_expresion_logicas(t):
315 '''
316 expresion : expresion MENORQUE expresion
317 | expresion MAYORQUE expresion
318 | expresion MENORIGUAL expresion
319 | expresion MAYORIGUAL expresion
320 | expresion IGUAL expresion
321 | expresion DISTINTO expresion
322 | PARIZQ expresion PARDER MENORQUE PARIZQ expresion PARDER
323 | PARIZQ expresion PARDER MAYORQUE PARIZQ expresion PARDER
324 | PARIZQ expresion PARDER MENORIGUAL PARIZQ expresion PARDER
325 | PARIZQ expresion PARDER MAYORIGUAL PARIZQ expresion PARDER
326 | PARIZQ expresion PARDER IGUAL PARIZQ expresion PARDER
327 | PARIZQ expresion PARDER DISTINTO PARIZQ expresion PARDER
328 '''
329 if t[2] == "<": t[0] = t[1] < t[3]
330 elif t[2] == ">": t[0] = t[1] > t[3]
331 elif t[2] == "<=": t[0] = t[1] <= t[3]
332 elif t[2] == ">=": t[0] = t[1] >= t[3]
333 elif t[2] == "==": t[0] = t[1] is t[3]
334 elif t[2] == "!=": t[0] = t[1] != t[3]
335 elif t[3] == "<":
336 t[0] = t[2] < t[4]
337 elif t[2] == ">":
338 t[0] = t[2] > t[4]
339 elif t[3] == "<=":
340 t[0] = t[2] <= t[4]
341 elif t[3] == ">=":
342 t[0] = t[2] >= t[4]
343 elif t[3] == "==":
344 t[0] = t[2] is t[4]
345 elif t[3] == "!=":
346 t[0] = t[2] != t[4]
347
348 # print('logica ',[x for x in t])
349
350 # gramatica de expresiones booleanadas
351 def p_expresion_booleana(t):
352 '''
353 expresion : expresion AND expresion
354 | expresion OR expresion
355 | expresion NOT expresion
356 | PARIZQ expresion AND expresion PARDER
357 | PARIZQ expresion OR expresion PARDER
358 | PARIZQ expresion NOT expresion PARDER
359 '''
360 if t[2] == "&&":
361 t[0] = t[1] and t[3]
362 elif t[2] == "||":
363 t[0] = t[1] or t[3]
364 elif t[2] == "!":
365 t[0] = t[1] is not t[3]
366 elif t[3] == "&&":
367 t[0] = t[2] and t[4]
368 elif t[3] == "||":
369 t[0] = t[2] or t[4]
370 elif t[3] == "!":
371 t[0] = t[2] is not t[4]
372
373
374
375 def p_expresion_numero(t):
376 'expresion : ENTERO'
377 t[0] = t[1]
378
379 def p_expresion_cadena(t):
380 'expresion : COMDOB expresion COMDOB'
381 t[0] = t[2]
382
383 def p_expresion_nombre(t):
384 'expresion : IDENTIFICADOR'
385 try:
386 t[0] = nombres[t[1]]
387 except LookupError:
388 print("Nombre desconocido ", t[1])
389 t[0] = 0
390
391 def p_error(t):
392 global resultado_gramatica
393 if t:
394 resultado = "Error sintactico de tipo {} en el valor {}".format( str(t.type),str(t.value))
395 print(resultado)
396 else:
397 resultado = "Error sintactico {}".format(t)
398 print(resultado)
399 resultado_gramatica.append(resultado)
400
401
402
403 # instanciamos el analizador sistactico
404 parser = yacc.yacc()
405
406 def prueba_sintactica(data):
407 global resultado_gramatica
408 resultado_gramatica.clear()
409
410 for item in data.splitlines():
411 if item:
412 gram = parser.parse(item)
413 if gram:
414 resultado_gramatica.append(str(gram))
415 else: print("data vacia")
416
417 print("result: ", resultado_gramatica)
418 return resultado_gramatica
419
420 if __name__ == '__main__':
421 while True:
422 try:
423 s = input(' ingresa dato >>> ')
424 except EOFError:
425 continue
426 if not s: continue
427
428 #gram = parser.parse(s)
429 # print("Resultado ", gram)
430
431 prueba_sintactica(s

También podría gustarte