PLY lex yacc: 错误处理

2 投票
2 回答
3724 浏览
提问于 2025-04-18 12:28

我正在使用PLY来解析一个文件。当我在某一行遇到错误时,我需要给用户打印一条消息。

比如像这样的一条消息:第4行出错

def p_error(p):
    flag_for_error = 1
    print ("Erreur de syntaxe sur la ligne %d" % (p.lineno))
    yacc.errok()

但是这并没有成功。我遇到了这个错误:

print ("Erreur de syntaxe sur la ligne %d" % (p.lineno))
AttributeError: 'NoneType' object has no attribute 'lineno'

有没有其他更合适的方法来做到这一点呢?

2 个回答

1

我解决了这个问题。我的问题是我总是重新初始化解析器。

def p_error(p):
    global flag_for_error
    flag_for_error = 1

    if p is not None:
        errors_list.append("Erreur de syntaxe à la ligne %s"%(p.lineno))
        yacc.errok()
    else:
        print("Unexpected end of input")
        yacc.errok()

好的函数是

def p_error(p):
    global flag_for_error
    flag_for_error = 1

    if p is not None:
        errors_list.append("Erreur de syntaxe à la ligne %s"%(p.lineno))
        yacc.errok()
    else:
        print("Unexpected end of input")

当我预期输入结束时,我就不应该继续解析了。

谢谢

4

我之前也遇到过同样的问题。这个问题是因为出现了意外的输入结束

你可以先检查一下p(其实它是p_error中的一个标记)是否是None

你的代码大概可以写成这样:

def p_error(token):
    if token is not None:
        print ("Line %s, illegal token %s" % (token.lineno, token.value))
    else:
        print('Unexpected end of input')

希望这对你有帮助。

撰写回答