Debian Codegraph @

src/yapps3/examples/calc.g

raw
1 # This calculator supports the usual (numbers, add, subtract,
2 # multiply, divide), global variables (stored in a global variable in
3 # Python), and local variables (stored in an attribute passed around
4 # in the grammar).
5
6
7 globalvars = {} # We will store the calculator's variables here
8
9 def lookup(map, name):
10 for x,v in map:
11 if x == name: return v
12 if not globalvars.has_key(name): print 'Undefined (defaulting to 0):', name
13 return globalvars.get(name, 0)
14
15 %%
16 parser Calculator:
17 ignore: "[ \r\t\n]+"
18 token END: "$"
19 token NUM: "[0-9]+"
20 token VAR: "[a-zA-Z_]+"
21
22 # Each line can either be an expression or an assignment statement
23 rule goal: expr<<[]>> END {{ print '=', expr }}
24 {{ return expr }}
25 | "set" VAR expr<<[]>> END {{ globalvars[VAR] = expr }}
26 {{ print VAR, '=', expr }}
27 {{ return expr }}
28
29 # An expression is the sum and difference of factors
30 rule expr<<V>>: factor<<V>> {{ n = factor }}
31 ( "[+]" factor<<V>> {{ n = n+factor }}
32 | "-" factor<<V>> {{ n = n-factor }}
33 )* {{ return n }}
34
35 # A factor is the product and division of terms
36 rule factor<<V>>: term<<V>> {{ v = term }}
37 ( "[*]" term<<V>> {{ v = v*term }}
38 | "/" term<<V>> {{ v = v/term }}
39 )* {{ return v }}
40
41 # A term is a number, variable, or an expression surrounded by parentheses
42 rule term<<V>>:
43 NUM {{ return atoi(NUM) }}
44 | VAR {{ return lookup(V, VAR) }}
45 | "\\(" expr "\\)" {{ return expr }}
46 | "let" VAR "=" expr<<V>> {{ V = [(VAR, expr)] + V }}
47 "in" expr<<V>> {{ return expr }}
48 %%
49 if __name__=='__main__':
50 print 'Welcome to the calculator sample for Yapps 2.'
51 print ' Enter either "<expression>" or "set <var> <expression>",'
52 print ' or just press return to exit. An expression can have'
53 print ' local variables: let x = expr in expr'
54 # We could have put this loop into the parser, by making the
55 # `goal' rule use (expr | set var expr)*, but by putting the
56 # loop into Python code, we can make it interactive (i.e., enter
57 # one expression, get the result, enter another expression, etc.)
58 while 1:
59 try: s = raw_input('>>> ')
60 except EOFError: break
61 if not strip(s): break
62 parse('goal', s)
63 print 'Bye.'