Rename to picalc.*, improve messages slightly
[picalc.git] / picalc.y
1 /*
2  * Copyright (C) 2018 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 t_def
21   import sys
22 %}
23
24 %locations
25
26 %token NUM
27
28 %left '+' '-'
29 %left '*' '/'
30 %right UMINUS
31
32 %%
33
34 S : S E '\n' {
35     sys.stdout.write('Answer: {0:g}\nEnter an expression:\n'.format($2))
36   }
37   | S '\n'
38   |
39   | error '\n' {
40   yyerror('Error, please try again:\n')
41   yyerrok()
42 }
43   ;
44 E : %space (?E{t_def.AST.Add}E '+' E) {
45     $$ = $1 + $3
46   }
47   | %space (?E{t_def.AST.Sub}E '-' E) {
48     $$ = $1 - $3
49   }
50   | %space (?E{t_def.AST.Mul}E '*' E) {
51     $$ = $1 * $3
52   }
53   | %space (?E{t_def.AST.Div}E '/' E) {
54     $$ = $1 / $3
55   }
56   | '(' E ')' {
57     $$ = $2
58   }
59   | %space (?E{t_def.AST.Neg}'-' E) %prec UMINUS {
60     $$ = -$2
61   }
62   | NUM
63   ;
64 %%
65
66 def yyerror(s):
67   sys.stdout.write('{0:s}\n'.format(s))
68   sys.exit(1)