2014-07-08 64 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") 

當我輸入的預期結束,我不能繼續解析。

謝謝