Mercurial > repo
comparison ply-3.8/test/yacc_notok.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_notok.py | |
3 # | |
4 # A grammar, but we forgot to import the tokens list | |
5 # ----------------------------------------------------------------------------- | |
6 | |
7 import sys | |
8 | |
9 if ".." not in sys.path: sys.path.insert(0,"..") | |
10 import ply.yacc as yacc | |
11 | |
12 # Parsing rules | |
13 precedence = ( | |
14 ('left','PLUS','MINUS'), | |
15 ('left','TIMES','DIVIDE'), | |
16 ('right','UMINUS'), | |
17 ) | |
18 | |
19 # dictionary of names | |
20 names = { } | |
21 | |
22 def p_statement_assign(t): | |
23 'statement : NAME EQUALS expression' | |
24 names[t[1]] = t[3] | |
25 | |
26 def p_statement_expr(t): | |
27 'statement : expression' | |
28 print(t[1]) | |
29 | |
30 def p_expression_binop(t): | |
31 '''expression : expression PLUS expression | |
32 | expression MINUS expression | |
33 | expression TIMES expression | |
34 | expression DIVIDE expression''' | |
35 if t[2] == '+' : t[0] = t[1] + t[3] | |
36 elif t[2] == '-': t[0] = t[1] - t[3] | |
37 elif t[2] == '*': t[0] = t[1] * t[3] | |
38 elif t[2] == '/': t[0] = t[1] / t[3] | |
39 | |
40 def p_expression_uminus(t): | |
41 'expression : MINUS expression %prec UMINUS' | |
42 t[0] = -t[2] | |
43 | |
44 def p_expression_group(t): | |
45 'expression : LPAREN expression RPAREN' | |
46 t[0] = t[2] | |
47 | |
48 def p_expression_number(t): | |
49 'expression : NUMBER' | |
50 t[0] = t[1] | |
51 | |
52 def p_expression_name(t): | |
53 'expression : NAME' | |
54 try: | |
55 t[0] = names[t[1]] | |
56 except LookupError: | |
57 print("Undefined name '%s'" % t[1]) | |
58 t[0] = 0 | |
59 | |
60 def p_error(t): | |
61 print("Syntax error at '%s'" % t.value) | |
62 | |
63 yacc.yacc() | |
64 | |
65 | |
66 | |
67 |