简体   繁体   中英

PLY lex yacc: Errors handling

I am using PLY to parse a file. I have to print a message to the user when I have an error on a line.

A message like 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()

But it is not working. I have the error

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

Is there another is more suitable way to do that?

I encountered the same problem a while ago. It is caused by unexpected end of input .

Just test if p (which is actually a token in p_error ) is None .

Your code would look something like this:

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

Hope this helps.

I resolved the problem. My problem was that I always reinitialise the parser.

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

The good function is

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

When I have an expected end of input, I must not continue parsing.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM