forked from dabeaz/ply
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yacc_error7.py
80 lines (61 loc) · 1.75 KB
/
yacc_error7.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# -----------------------------------------------------------------------------
# yacc_error7.py
#
# Panic mode recovery test using deprecated functionality
# -----------------------------------------------------------------------------
import sys
if ".." not in sys.path: sys.path.insert(0,"..")
import ply.yacc as yacc
from calclex import tokens
# Parsing rules
precedence = (
('left','PLUS','MINUS'),
('left','TIMES','DIVIDE'),
('right','UMINUS'),
)
def p_statements(t):
'statements : statements statement'
pass
def p_statements_1(t):
'statements : statement'
pass
def p_statement_assign(p):
'statement : LPAREN NAME EQUALS expression RPAREN'
print("%s=%s" % (p[2],p[4]))
def p_statement_expr(t):
'statement : LPAREN expression RPAREN'
print(t[1])
def p_expression_binop(t):
'''expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression'''
if t[2] == '+' : t[0] = t[1] + t[3]
elif t[2] == '-': t[0] = t[1] - t[3]
elif t[2] == '*': t[0] = t[1] * t[3]
elif t[2] == '/': t[0] = t[1] / t[3]
def p_expression_uminus(t):
'expression : MINUS expression %prec UMINUS'
t[0] = -t[2]
def p_expression_number(t):
'expression : NUMBER'
t[0] = t[1]
def p_error(p):
if p:
print("Line %d: Syntax error at '%s'" % (p.lineno, p.value))
# Scan ahead looking for a name token
while True:
tok = parser.token()
if not tok or tok.type == 'RPAREN':
break
if tok:
parser.restart()
return None
parser = yacc.yacc()
import calclex
calclex.lexer.lineno=1
parser.parse("""
(a = 3 + 4)
(b = 4 + * 5 - 6 + *)
(c = 10 + 11)
""")