2014-07-08 65 views
1

我正在使用PLY解析文件。当我在一条线上发生错误时,我必须向用户打印一条消息。PLY lex yacc:处理错误

类似Error at the line 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' 

有没有另一种更合适的方法来做到这一点?

回答

1

我刚才遇到同样的问题。它是由意外的输入端引起的。

只要测试p(实际上是p_error中的令牌)是None

您的代码将是这个样子:

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

希望这有助于。

+0

我那么几天前,但它不工作。解析器无限期地执行else语句。 – dimele

+0

我解决了这个问题。 – dimele

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") 

当我输入的预期结束,我不能继续解析。

谢谢