Repository navigation
Expand file tree
/
Copy pathParserTP.py
More file actions
551 lines (453 loc) · 15.7 KB
/
Copy pathParserTP.py
File metadata and controls
551 lines (453 loc) · 15.7 KB
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
540
541
542
543
544
545
546
547
548
549
550
551
from tkinter import END
import ply.yacc as yacc
from MainLex import tokens
import sys
# Colaborado con Gemini
error_stats = {
'sintactico': 0,
'semantico': 0
}
scopes = [{}]
closed_scopes = []
loop_control_vars = []
def enter_scope():
scopes.append({})
print("DEBUG: Se entra a un nuevo scope")
def declare_symbol(name, symbol_type, value=None, params=None, kind='var'):
current_scope = scopes[-1]
if name in current_scope:
print(f"Error semantico: '{name}' ya declarado.")
error_stats['semantico'] += 1
else:
current_scope[name] = {
'nombre': name,
'tipo': symbol_type,
'atributo': [value] if value is not None else [],
'scope_type': 'global' if len(scopes) == 1 else 'local',
'kind': kind,
'params': params or []
}
def lookup_symbol(name):
for scope in reversed(scopes):
if name in scope:
return scope[name]
return None
def get_symbol_info(name):
for scope in reversed(scopes):
if name in scope:
return scope[name]
return None
def get_symbol_scope(name):
sym = get_symbol_info(name)
return sym['scope_type'] if sym else None
def get_symbol_kind(name):
sym = get_symbol_info(name)
return sym.get('kind') if sym else None
def get_symbol_value(name):
sym = get_symbol_info(name)
if not sym:
return None
attrs = sym.get('atributo', [])
if isinstance(attrs, list):
return attrs[-1] if attrs else None
return attrs
def normalize_type_name(type_name):
if type_name is None:
return None
return str(type_name).strip().lower()
def infer_value_type(value):
if isinstance(value, bool):
return 'boolean'
if isinstance(value, int) and not isinstance(value, bool):
return 'integer'
if isinstance(value, float):
return 'real'
if isinstance(value, str):
return 'string'
return None
def infer_expression_type(expr):
if isinstance(expr, bool):
return 'boolean'
if isinstance(expr, int):
return 'integer'
if isinstance(expr, float):
return 'real'
if isinstance(expr, str):
sym = lookup_symbol(expr)
if sym:
return normalize_type_name(sym.get('tipo'))
return 'string'
if isinstance(expr, tuple) and len(expr) == 3:
left, op, right = expr
left_type = infer_expression_type(left)
right_type = infer_expression_type(right)
if op in ('+', '-', '*', '/'):
if left_type == 'real' or right_type == 'real':
return 'real'
if left_type == 'integer' and right_type == 'integer':
return 'integer'
return None
if op in ('>', '<', '>=', '<=', '<>', '='):
return 'boolean'
return None
return None
def is_assignment_compatible(target_type, value_or_type):
target = normalize_type_name(target_type)
source_type = None
if isinstance(value_or_type, str) and value_or_type in ['integer', 'real', 'char', 'boolean', 'string']:
source_type = normalize_type_name(value_or_type)
else:
source_type = infer_value_type(value_or_type)
if target is None or source_type is None:
return True
if target == source_type:
return True
if target == 'real' and source_type == 'integer':
return True
return False
def is_variable_reference(actual):
if not isinstance(actual, str):
return False
sym = lookup_symbol(actual)
return sym is not None and sym.get('kind') == 'var'
def validate_call_arguments(name, actuals):
sym = lookup_symbol(name)
if sym is None:
return
params = sym.get('params', [])
if not params:
return
if len(actuals) != len(params):
print(f"Error semántico: '{name}' espera {len(params)} argumentos y recibió {len(actuals)}.")
error_stats['semantico'] += 1
return
for param, actual in zip(params, actuals):
if param.get('byref') and not is_variable_reference(actual):
print(f"Error semántico: El parámetro var '{param['name']}' requiere una variable, no una constante o expresión.")
error_stats['semantico'] += 1
def exit_scope():
if len(scopes) > 1:
closed_scopes.append(scopes.pop())
print("DEBUG: Se sale de un scope")
def update_symbol_value(name, value):
for scope in reversed(scopes):
if name in scope:
if isinstance(scope[name]['atributo'], list):
if not scope[name]['atributo'] or scope[name]['atributo'][-1] != value:
scope[name]['atributo'].append(value)
break
def push_loop_control_var(name):
loop_control_vars.append(name)
def pop_loop_control_var():
if loop_control_vars:
loop_control_vars.pop()
def is_loop_control_var(name):
return name in loop_control_vars
def evaluate_expression(expr):
if isinstance(expr, (int, float)):
return expr
if isinstance(expr, str):
sym = get_symbol_info(expr)
if sym and sym.get('atributo') is not None:
return get_symbol_value(expr)
try:
return float(expr)
except Exception:
return None
if isinstance(expr, tuple) and len(expr) == 3:
left, op, right = expr
lval = evaluate_expression(left)
rval = evaluate_expression(right)
if lval is None or rval is None:
return None
try:
if op == '+': return lval + rval
if op == '-': return lval - rval
if op == '*': return lval * rval
if op == '/': return lval / rval if rval != 0 else None
except Exception:
return None
return None
def print_symbol_table():
print(f"{'NOMBRE':<15} {'TIPO':<30} {'SCOPE':<10} {'HISTORIAL DE VALORES':<30}")
for scope in closed_scopes + scopes:
for name, info in scope.items():
attr = info['atributo']
scope_type = info.get('scope_type', 'global')
attr_str = ", ".join(map(str, attr)) if isinstance(attr, list) else str(attr)
if isinstance(attr, list):
for val in attr_str.split(', '):
print(f"{info['nombre']:<15} {info['tipo']:<30} {scope_type:<10} {val:<30}")
else:
print(f"{info['nombre']:<15} {info['tipo']:<30} {scope_type:<10} {attr_str:<30}")
def print_error_report():
print("RESUMEN DE ERRORES")
print(f"Errores Sintácticos: {error_stats['sintactico']}")
print(f"Errores Semánticos: {error_stats['semantico']}")
print(f"Total de Errores: {sum(error_stats.values())}")
def p_program(p):
'program : PROGRAM ID SEMICOLON uses_clause declaration_sections compound_stmt DOT'
print("\n--- ANÁLISIS SEMANTICO COMPLETO ---")
print_symbol_table()
print_error_report()
def p_uses_clause(p):
'''uses_clause : USES id_list SEMICOLON
| empty'''
pass
def p_id_list(p):
'''id_list : ID
| id_list COMMA ID'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[3]]
def p_declaration_sections(p):
'''declaration_sections : declaration_sections section
| empty'''
pass
def p_section(p):
'''section : const_section
| type_section
| var_section
| procedure_declaration
| function_declaration'''
pass
def p_const_section(p):
'const_section : CONST const_list'
pass
def p_const_list(p):
'''const_list : const_list ID EQUALS expression SEMICOLON
| ID EQUALS expression SEMICOLON'''
if len(p) == 6:
name = p[2]
expr = p[4]
else:
name = p[1]
expr = p[3]
value = evaluate_expression(expr)
if value is None:
value = expr
declare_symbol(name, infer_value_type(value) or 'const', value=value)
if name in scopes[-1]:
scopes[-1][name]['kind'] = 'const'
def p_type_section(p):
'type_section : TYPE type_list'
pass
def p_type_list(p):
'''type_list : type_list ID EQUALS type_specifier SEMICOLON
| ID EQUALS type_specifier SEMICOLON'''
if len(p) == 6:
name = p[2]
specifier = p[4]
else:
name = p[1]
specifier = p[3]
declare_symbol(name, specifier)
if name in scopes[-1]:
scopes[-1][name]['kind'] = 'type'
def p_var_section(p):
'var_section : VAR var_list'
pass
def p_var_list(p):
'''var_list : var_list id_list COLON type_specifier SEMICOLON
| id_list COLON type_specifier SEMICOLON'''
if len(p) == 6:
ids, data_type = p[2], p[4]
else:
ids, data_type = p[1], p[3]
for name in ids:
declare_symbol(name, data_type)
def p_type_specifier(p):
'''type_specifier : type_base
| ARRAY LBRACKET range RBRACKET OF type_base
| STRING LBRACKET NUMBER RBRACKET'''
if len(p) == 2:
p[0] = p[1]
elif len(p) == 7:
p[0] = f"array of {p[6]}"
else:
p[0] = "string"
def p_type_base(p):
'''type_base : INTEGER
| REAL
| CHAR
| BOOLEAN'''
p[0] = p[1]
def p_range(p):
'''range : NUMBER DOT DOT NUMBER'''
p[0] = (p[1], p[4])
def p_procedure_declaration(p):
'procedure_declaration : PROCEDURE ID LPAREN enter_args args RPAREN SEMICOLON compound_stmt SEMICOLON'
if len(scopes) > 1:
exit_scope()
declare_symbol(p[2], 'procedure', params=p[5], kind='procedure')
def p_function_declaration(p):
'function_declaration : FUNCTION ID LPAREN enter_args args RPAREN COLON type_base SEMICOLON compound_stmt SEMICOLON'
if len(scopes) > 1:
exit_scope()
declare_symbol(p[2], f"function returning {p[8]}", params=p[6], kind='function')
def p_enter_args(p):
'enter_args :'
enter_scope()
def p_compound_stmt(p):
'''compound_stmt : BEGIN statement_list END
| var_section BEGIN statement_list END'''
pass
def p_statement_list(p):
'''statement_list : statement_list statement
| statement
| empty'''
pass
def p_statement(p):
'''statement : call_stmt SEMICOLON
| assignment_stmt SEMICOLON
| compound_stmt
| if_stmt
| for_stmt'''
pass
def p_if_stmt(p):
'''if_stmt : IF LPAREN expression RPAREN THEN statement
| IF LPAREN expression RPAREN THEN statement ELSE statement'''
pass
def p_for_stmt(p):
'for_stmt : FOR ID ASSIGN expression TO expression DO loop_guard statement'
var_name = p[2]
inicio = evaluate_expression(p[4])
fin = evaluate_expression(p[6])
if lookup_symbol(var_name) is None:
print(f"Error semántico: Variable de control '{var_name}' no declarada.")
error_stats['semantico'] += 1
else:
if inicio is not None and fin is not None:
scope_type = get_symbol_scope(var_name)
for i in range(inicio, fin + 1):
update_symbol_value(var_name, i)
print(f"DEBUG: Bucle FOR para '{var_name}' ({scope_type}), valor actual: {i}")
pop_loop_control_var()
def p_loop_guard(p):
'loop_guard :'
push_loop_control_var(p[-6])
def p_assignment_stmt(p):
'assignment_stmt : ID ASSIGN expression'
if lookup_symbol(p[1]) is None:
print(f"Error semántico: Variable '{p[1]}' usada antes de su declaración.")
error_stats['semantico'] += 1
else:
if get_symbol_kind(p[1]) in ('const', 'type'):
print(f"Error semántico: '{p[1]}' no es asignable.")
error_stats['semantico'] += 1
return
if is_loop_control_var(p[1]):
print(f"Error semántico: No se puede modificar la variable de control '{p[1]}' dentro del bucle FOR.")
error_stats['semantico'] += 1
return
val = evaluate_expression(p[3])
expr_type = infer_expression_type(p[3])
if expr_type is not None:
if not is_assignment_compatible(get_symbol_info(p[1]).get('tipo'), expr_type):
print(f"Error semántico: Incompatibilidad de tipos en la asignación a '{p[1]}'.")
error_stats['semantico'] += 1
return
elif val is not None:
if not is_assignment_compatible(get_symbol_info(p[1]).get('tipo'), val):
print(f"Error semántico: Incompatibilidad de tipos en la asignación a '{p[1]}'.")
error_stats['semantico'] += 1
return
if val is not None:
update_symbol_value(p[1], val)
scope_type = get_symbol_scope(p[1])
print(f"DEBUG: Asignado {val} a {p[1]} ({scope_type})")
def p_call_stmt(p):
'''call_stmt : ID LPAREN expression_list RPAREN
| ID'''
name = p[1]
if lookup_symbol(name) is None:
if name.lower() not in ['write', 'writeln', 'readln']:
print(f"Error semántico: Función o procedimiento '{name}' no definido.")
error_stats['semantico'] += 1
elif len(p) == 5:
validate_call_arguments(name, p[3])
else:
sym = lookup_symbol(name)
if sym and sym.get('params'):
print(f"Error semántico: '{name}' espera argumentos.")
error_stats['semantico'] += 1
p[0] = name
def p_args(p):
'''args : arg_list
| empty'''
p[0] = p[1] if p[1] is not None else []
def p_arg_list(p):
'''arg_list : arg_spec
| arg_list SEMICOLON arg_spec'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[3]]
def p_arg_spec(p):
'''arg_spec : ID COLON type_base
| VAR ID COLON type_base'''
if len(p) == 4:
param = {'name': p[1], 'type': p[3], 'byref': False}
declare_symbol(p[1], p[3])
else:
param = {'name': p[2], 'type': p[4], 'byref': True}
declare_symbol(p[2], p[4])
p[0] = param
def p_expression_list(p):
'''expression_list : expression_list COMMA expression
| expression'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[3]]
def p_expression(p):
'''expression : term
| expression PLUS term
| expression MINUS term
| expression GREATER term
| expression LESS term
| expression GREATEREQUAL term
| expression LESSEQUAL term
| expression NOTEQUAL term'''
if len(p) == 2:
p[0] = p[1]
else:
p[0] = (p[1], p[2], p[3])
def p_term(p):
'''term : factor
| term TIMES factor
| term DIVIDE factor'''
if len(p) == 2:
p[0] = p[1]
else:
p[0] = (p[1], p[2], p[3])
def p_factor(p):
'''factor : NUMBER
| STRING
| call_stmt
| LPAREN expression RPAREN'''
if len(p) == 2:
if p.slice[1].type == 'NUMBER' and isinstance(p[1], str):
p[0] = float(p[1]) if '.' in p[1] else int(p[1])
else:
p[0] = p[1]
else: p[0] = p[2]
def p_empty(p):
'empty :'
pass
def p_error(p):
error_stats['sintactico'] += 1
if p:
print(f"Error de sintaxis en la línea {p.lineno}: Token inesperado '{p.value}'")
else:
print("Error: Fin de archivo inesperado")
parser = yacc.yacc(start='program')
if __name__ == '__main__':
fin = sys.argv[1] if len(sys.argv) > 1 else 'Prueba.pas'
with open(fin, 'r') as f:
data = f.read()
try:
parser.parse(data, tracking=True)
except Exception as e:
print(f"Error de ejecución: {e}")