2
votes

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?

2

2 Answers

4
votes

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.

1
votes

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