Mercurial > repo
comparison ply-3.8/test/yacc_nop.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_nop.py | |
3 # | |
4 # Possible grammar rule defined without p_ prefix | |
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 # dictionary of names | |
21 names = { } | |
22 | |
23 def p_statement_assign(t): | |
24 'statement : NAME EQUALS expression' | |
25 names[t[1]] = t[3] | |
26 | |
27 def statement_expr(t): | |
28 'statement : expression' | |
29 print(t[1]) | |
30 | |
31 def p_expression_binop(t): | |
32 '''expression : expression PLUS expression | |
33 | expression MINUS expression | |
34 | expression TIMES expression | |
35 | expression DIVIDE expression''' | |
36 if 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 elif t[2] == '/': t[0] = t[1] / t[3] | |
40 | |
41 def p_expression_uminus(t): | |
42 'expression : MINUS expression %prec UMINUS' | |
43 t[0] = -t[2] | |
44 | |
45 def p_expression_group(t): | |
46 'expression : LPAREN expression RPAREN' | |
47 t[0] = t[2] | |
48 | |
49 def p_expression_number(t): | |
50 'expression : NUMBER' | |
51 t[0] = t[1] | |
52 | |
53 def p_expression_name(t): | |
54 'expression : NAME' | |
55 try: | |
56 t[0] = names[t[1]] | |
57 except LookupError: | |
58 print("Undefined name '%s'" % t[1]) | |
59 t[0] = 0 | |
60 | |
61 def p_error(t): | |
62 print("Syntax error at '%s'" % t.value) | |
63 | |
64 yacc.yacc() | |
65 | |
66 | |
67 | |
68 |