Rename to picalc.*, improve messages slightly
[picalc.git] / picalc.t
1 /*
2  * Copyright (C) 2019 Nick Downing <nick@ndcode.org>
3  * SPDX-License-Identifier: GPL-2.0-only
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the Free
7  * Software Foundation; version 2.
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along with
15  * this program; if not, write to the Free Software Foundation, Inc., 51
16  * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 %{
20   import element
21 %}
22
23 %%
24
25 class Text;
26 class AST {
27   class Expr;
28   class Num: Expr {
29     class Mantissa: Text;
30     class Fraction: Text;
31   };
32   class Add;
33   class Sub;
34   class Mul;
35   class Div;
36   class Neg;
37 };
38
39 %%
40
41 # Copyright (C) 2018 Nick Downing <nick@ndcode.org>
42 # SPDX-License-Identifier: GPL-2.0-only
43 #
44 # This program is free software; you can redistribute it and/or modify it under
45 # the terms of the GNU General Public License as published by the Free Software
46 # Foundation; version 2.
47 #
48 # This program is distributed in the hope that it will be useful, but WITHOUT
49 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
50 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
51 # details.
52 #
53 # You should have received a copy of the GNU General Public License along with
54 # this program; if not, write to the Free Software Foundation, Inc., 51
55 # Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
56
57 def factory(tag, *args, **kwargs):
58   return tag_to_class[tag](*args, **kwargs)
59
60 @method(Text)
61 def get_text(self):
62   return self.text[0]
63 del get_text
64
65 @method(AST.Expr)
66 def eval(self):
67   raise NotImplementedException()
68 @method(AST.Num)
69 def eval(self):
70   mantissa = self.children[0].get_text()
71   fraction = self.children[1].get_text() if len(self.children) >= 2 else ''
72   return int(mantissa + fraction) * 10 ** -len(fraction)
73 @method(AST.Add)
74 def eval(self):
75   return self.children[0].eval() + self.children[1].eval()
76 @method(AST.Sub)
77 def eval(self):
78   return self.children[0].eval() - self.children[1].eval()
79 @method(AST.Mul)
80 def eval(self):
81   return self.children[0].eval() * self.children[1].eval()
82 @method(AST.Div)
83 def eval(self):
84   return self.children[0].eval() / self.children[1].eval()
85 @method(AST.Neg)
86 def eval(self):
87   return -self.children[0].eval()
88 del eval