Analisis-Lenguaje_Robot / semantico.py
Ethgoin
Migraci贸n completa a Python
d02548d
raw
history blame
1.83 kB
class AnalizadorSemantico:
def __init__(self, ast):
self.ast = ast
self.tabla_simbolos = {}
self.errores = []
def analizar(self):
for nodo in self.ast:
self.analizar_instruccion(nodo)
return {
"variables_declaradas": self.tabla_simbolos,
"errores_semanticos": self.errores
}
def analizar_instruccion(self, nodo):
if nodo["type"] == "assign":
tipo_valor = self.analizar_expresion(nodo["value"])
self.tabla_simbolos[nodo["var"]] = tipo_valor
elif nodo["type"] == "if":
tipo_condicion = self.analizar_expresion(nodo["condition"])
if tipo_condicion != "int":
self.errores.append(
f"Condici贸n del IF debe ser de tipo int, pero se encontr贸 '{tipo_condicion}'"
)
for instr in nodo["body"]:
self.analizar_instruccion(instr)
def analizar_expresion(self, expr):
if expr["type"] == "num":
return "float" if "." in expr["value"] else "int"
elif expr["type"] == "var":
nombre = expr["value"]
if nombre not in self.tabla_simbolos:
self.errores.append(f"Variable '{nombre}' usada sin ser declarada.")
return "error"
return self.tabla_simbolos[nombre]
elif expr["type"] == "binop":
tipo_izq = self.analizar_expresion(expr["left"])
tipo_der = self.analizar_expresion(expr["right"])
if tipo_izq != tipo_der:
self.errores.append(f"Tipos incompatibles: {tipo_izq} y {tipo_der}")
return "error"
return tipo_izq
else:
self.errores.append(f"Expresi贸n no reconocida: {expr}")
return "error"