d444f2c6502a69697a0904fcbddb34a3dbb7b97c
[nit.git] / contrib / nitcc / examples / calc.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Example of a calculation used nitcc
16 # see `calc.sablecc` for the grammar
17 module calc
18
19 # Reuse the test program to simplify the code
20 import calc_test_parser
21
22 # The main evaluator, as a visitiopn that stack values
23 class Calulator
24 super Visitor
25
26 # The stack of values
27 var stack = new Array[Int]
28
29 redef fun visit(n) do n.accept_calculator(self)
30 end
31
32 redef class Node
33 # Default caculation is to visit the childrens
34 fun accept_calculator(v: Calulator) do visit_children(v)
35 end
36
37 redef class Nint
38 redef fun accept_calculator(v) do v.stack.push(text.to_i)
39 end
40
41 redef class Ne_add
42 redef fun accept_calculator(v) do
43 super
44 v.stack.push(v.stack.pop+v.stack.pop)
45 end
46 end
47
48 redef class Ne_sub
49 redef fun accept_calculator(v) do
50 super
51 var n1 = v.stack.pop
52 v.stack.push(v.stack.pop-n1)
53 end
54 end
55
56 redef class Ne_neg
57 redef fun accept_calculator(v) do
58 super
59 v.stack.push(-v.stack.pop)
60 end
61 end
62
63 redef class Ne_mul
64 redef fun accept_calculator(v) do
65 super
66 v.stack.push(v.stack.pop*v.stack.pop)
67 end
68 end
69
70 redef class Ne_div
71 redef fun accept_calculator(v) do
72 super
73 var n1 = v.stack.pop
74 v.stack.push(v.stack.pop/n1)
75 end
76 end
77
78 var t = new TestParser_calc
79 var n = t.main
80 var v = new Calulator
81 v.enter_visit(n)
82 print v.stack.pop