Reputation:
I have a lot of error using PLY. The error happens when I try to add this to the code:
def p_assign(p):
'''assign : NAME EQUALS expr'''
p[0] = ('ASSIGN',p[1],p[3])
def p_expr_plus(p):
'''expr : expr PLUS term'''
p[0] = ('+',p[1],p[3])
def p_term_mul(p):
'''term : term TIMES factor'''
p[0] = ('*',p[1],p[3])
def p_term_factor(p):
'''term : factor'''
p[0] = p[1]
def p_factor(p):
'''factor : NUMBER'''
p[0] = ('NUM',p[1])
But I get this error:
ERROR: C:\Users\-user-\Desktop\dw_parser.py:9: Symbol 'EQUALS' used, but not defined as a token or a rule
WARNING: Token 'COLON' defined, but not used
WARNING: Token 'DIVIDE' defined, but not used
WARNING: Token 'EQUAL' defined, but not used
WARNING: Token 'EQUAL_TO' defined, but not used
WARNING: Token 'GREATER' defined, but not used
WARNING: Token 'GREATER_EQL' defined, but not used
WARNING: Token 'LESS' defined, but not used
WARNING: Token 'LESS_EQL' defined, but not used
WARNING: Token 'LPAREN' defined, but not used
WARNING: Token 'MINUS' defined, but not used
WARNING: Token 'QUOTATION' defined, but not used
WARNING: Token 'REMAINDER' defined, but not used
WARNING: Token 'RPAREN' defined, but not used
WARNING: Token 'SEMICOLON' defined, but not used
WARNING: Token 'STRING' defined, but not used
WARNING: There are 15 unused tokens
ERROR: Infinite recursion detected for symbol 'assign'
ERROR: Infinite recursion detected for symbol 'expr'
Traceback (most recent call last):
File "C:\Users\-user-\Desktop\dw_parser.py", line 35, in <module>
parser = yacc.yacc()
File "C:\Program Files\Python37\lib\site-packages\ply-3.11-py3.7.egg\ply\yacc.py", line 3432, in yacc
raise YaccError('Unable to build parser')
ply.yacc.YaccError: Unable to build parser
There is the full parser code: https://pastebin.com/bPrwDQEK I can't put the parser code directly here, because code sample doesn't works too.
Upvotes: 0
Views: 3107
Reputation: 241721
The only production you define for expr
is
expr : expr PLUS term
Since there is no other production, expr
cannot ever produce a finite sentence. Contrast this with your productions for term
:
term : factor TIMES term
term : factor
Here, there is a non-recursive production so the recursion can terminate.
Because of the way PLY works, you do not need a separate parsing action function to add the expr : term
production; you can use the same function as for term : factor
(and for other similar unit productions):
def p_unit(p):
'''expr : term
term : factor
'''
p[0] = p[1]
assign
is also flagged because its only production uses expr
and expr
only leads to infinite recursion. Hopefully the other errors and warnings are self-explanatory.
Upvotes: 2