1 /* Simple parser and scanner in Java. -*- Java -*-
3 Copyright (C) 2018-2021 Free Software Foundation, Inc.
5 This file is part of Bison, the GNU Compiler Compiler.
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <https://www.gnu.org/licenses/>. */
22 %define api.parser.class
{Calc
}
23 %define api.parser.public
25 %define parse.
error verbose
28 import java.io.IOException
;
29 import java.io.InputStream
;
30 import java.io.InputStreamReader
;
31 import java.io.Reader
;
32 import java.io.StreamTokenizer
;
36 public
static void main
(String
[] args
) throws IOException
{
37 CalcLexer l
= new CalcLexer
(System.in
);
44 /* Bison Declarations */
45 %token
<Integer
> NUM
"number"
48 %nonassoc
'=' /* comparison */
51 %precedence NEG
/* negation--unary minus */
52 %right
'^' /* exponentiation */
63 | exp
'\n' { System.out.println
($exp); }
71 if
($1.intValue
() != $3.intValue
())
72 yyerror("calc: error: " + $1 + " != " + $3);
74 | exp
'+' exp
{ $$
= $1 + $3; }
75 | exp
'-' exp
{ $$
= $1 - $3; }
76 | exp
'*' exp
{ $$
= $1 * $3; }
77 | exp
'/' exp
{ $$
= $1 / $3; }
78 |
'-' exp %prec NEG
{ $$
= -$2; }
79 | exp
'^' exp
{ $$
= (int) Math.pow
($1, $3); }
80 |
'(' exp
')' { $$
= $2; }
81 |
'(' error ')' { $$
= 1111; }
82 |
'!' { $$
= 0; return
YYERROR; }
83 |
'-' error { $$
= 0; return
YYERROR; }
88 class CalcLexer implements Calc.Lexer
{
92 public CalcLexer
(InputStream is
) {
93 st
= new StreamTokenizer
(new InputStreamReader
(is
));
95 st.eolIsSignificant
(true
);
96 st.whitespaceChars
('\t', '\t');
97 st.whitespaceChars
(' ', ' ');
98 st.wordChars
('0', '9');
101 public
void yyerror(String s
) {
102 System.err.println
(s
);
107 public Object getLVal
() {
111 public
int yylex() throws IOException
{
112 int ttype
= st.nextToken
();
114 case StreamTokenizer.TT_EOF
:
116 case StreamTokenizer.TT_EOL
:
118 case StreamTokenizer.TT_WORD
:
119 yylval = new Integer
(st.sval
);