I'm working in a UI for a Typescript code analyzer and I want to get error syntax from code input. I have this in my sintactico.py:
sintactico.py
error = ""
def p_error(p):
global error
error = ""
if p:
error = p
print("sintactico.py IF -> Error en token ", p)
else:
error = "EOF"
print("sintactico.py IF -> Error: se encontró EOF")
print("sintactico.py -> ", error)
syntax = yacc.yacc()
So in here I'm getting error assigned with the detected error in code, but error keeps the first error it detects, then I call it in main.py where the code for the UI is:
main.py
import sintactico
#codigo is a list of strings
for code in codigo:
# ANÁLISIS SINTÁCTICO
parser = sintactico.syntax.parse(code)
r_error = sintactico.error #keeps the first error parser returns
print("main.py -> ", r_error)
item_syn = QListWidgetItem(code)
if r_error == "EOF":
texto = code +"\nError en linea "+str(linea)+"\nPosible error: EOF inesperado"
item_syn = QListWidgetItem(texto)
item_syn.setForeground(QColor(255,0,0))
elif r_error != "":
token_p = sintactico.error
texto = code +"\nError en linea "+str(token_p.lineno)+"\nPosible error: "+str(token_p.value)
item_syn = QListWidgetItem(texto)
item_syn.setForeground(QColor(255,0,0))
self.list_syn.addItem(item_syn)
print(parser)
linea += 1
r_error = ""
self.inp_codigo.clear()
Even if the code has no syntax error, it keeps showing the first syntax error. I don't know why it doesn't change the value although code is different in every iteration and it does parse a different code.
The problem with your logic is that you only reset the global error
(i.e. sintactico.error
) in the function p_error
. Since p_error
is only called by Ply when a syntax error is encountered, that means that the previous error is only cleared at the next error. The result is that if you parse an input with an error and then parse another input without an error, sintactico.error
still refers to the original error, which is precisely the problem you reported ("Even if the code has no syntax error, it keeps showing the first syntax error").