Mercurial > repo
comparison ply-3.8/test/yacc_error6.py @ 7267:343ff337a19b
<ais523> ` tar -xf ply-3.8.tar.gz
author | HackBot |
---|---|
date | Wed, 23 Mar 2016 02:40:16 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
7266:61a39a120dee | 7267:343ff337a19b |
---|---|
1 # ----------------------------------------------------------------------------- | |
2 # yacc_error6.py | |
3 # | |
4 # Panic mode recovery test | |
5 # ----------------------------------------------------------------------------- | |
6 import sys | |
7 | |
8 if ".." not in sys.path: sys.path.insert(0,"..") | |
9 import ply.yacc as yacc | |
10 | |
11 from calclex import tokens | |
12 | |
13 # Parsing rules | |
14 precedence = ( | |
15 ('left','PLUS','MINUS'), | |
16 ('left','TIMES','DIVIDE'), | |
17 ('right','UMINUS'), | |
18 ) | |
19 | |
20 def p_statements(t): | |
21 'statements : statements statement' | |
22 pass | |
23 | |
24 def p_statements_1(t): | |
25 'statements : statement' | |
26 pass | |
27 | |
28 def p_statement_assign(p): | |
29 'statement : LPAREN NAME EQUALS expression RPAREN' | |
30 print("%s=%s" % (p[2],p[4])) | |
31 | |
32 def p_statement_expr(t): | |
33 'statement : LPAREN expression RPAREN' | |
34 print(t[1]) | |
35 | |
36 def p_expression_binop(t): | |
37 '''expression : expression PLUS expression | |
38 | expression MINUS expression | |
39 | expression TIMES expression | |
40 | expression DIVIDE expression''' | |
41 if t[2] == '+' : t[0] = t[1] + t[3] | |
42 elif t[2] == '-': t[0] = t[1] - t[3] | |
43 elif t[2] == '*': t[0] = t[1] * t[3] | |
44 elif t[2] == '/': t[0] = t[1] / t[3] | |
45 | |
46 def p_expression_uminus(t): | |
47 'expression : MINUS expression %prec UMINUS' | |
48 t[0] = -t[2] | |
49 | |
50 def p_expression_number(t): | |
51 'expression : NUMBER' | |
52 t[0] = t[1] | |
53 | |
54 def p_error(p): | |
55 if p: | |
56 print("Line %d: Syntax error at '%s'" % (p.lineno, p.value)) | |
57 # Scan ahead looking for a name token | |
58 while True: | |
59 tok = parser.token() | |
60 if not tok or tok.type == 'RPAREN': | |
61 break | |
62 if tok: | |
63 parser.restart() | |
64 return None | |
65 | |
66 parser = yacc.yacc() | |
67 import calclex | |
68 calclex.lexer.lineno=1 | |
69 | |
70 parser.parse(""" | |
71 (a = 3 + 4) | |
72 (b = 4 + * 5 - 6 + *) | |
73 (c = 10 + 11) | |
74 """) | |
75 | |
76 | |
77 | |
78 | |
79 | |
80 |