1 /* Parser for lexcalc. -*- C -*-
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/>. */
20 // Prologue (directives).
23 // Emitted in the header file, after the definition of YYSTYPE.
26 // Tell Flex the expected prototype of yylex.
28 yytoken_kind_t
yylex (YYSTYPE* yylval, YYLTYPE *yylloc, int *nerrs
)
31 void yyerror (YYLTYPE *loc
, int *nerrs
, const char *msg
);
34 // Emitted on top of the implementation file.
37 #include <stdio.h> // printf.
38 #include <stdlib.h> // getenv.
41 // Include the header in the implementation rather than duplicating it.
42 %define api.header.include
{"parse.h"}
44 // Don't share global variables between the scanner and the parser.
47 // To avoid name clashes (e.g., with C's EOF) prefix token definitions
48 // with TOK_ (e.g., TOK_EOF).
49 %define api.token.prefix
{TOK_
}
51 // %token and %type use genuine types (e.g., "%token <int>"). Let
52 // %bison define YYSTYPE as a union of all these types.
53 %define api.value.type
union
55 // Generate detailed error messages.
56 %define parse.
error detailed
61 // Enable debug traces (see yydebug in main).
64 // Error count, exchanged between main, yyparse and yylex.
77 %token
<int> NUM
"number"
79 %printer
{ fprintf
(yyo
, "%d", $$
); } <int>
81 // Precedence (from lowest to highest) and associativity.
93 exp EOL
{ printf
("%d\n", $exp); }
94 |
error EOL
{ yyerrok; }
98 exp
"+" exp
{ $$
= $1 + $3; }
99 | exp
"-" exp
{ $$
= $1 - $3; }
100 | exp
"*" exp
{ $$
= $1 * $3; }
105 yyerror (&@$
, nerrs
, "error: division by zero");
111 |
"(" exp
")" { $$
= $2; }
115 // Epilogue (C code).
117 void yyerror (YYLTYPE *loc
, int *nerrs
, const char *msg
)
119 YY_LOCATION_PRINT
(stderr
, *loc
);
120 fprintf
(stderr
, ": %s\n", msg
);
127 // Possibly enable parser runtime debugging.
128 yydebug = !!getenv
("YYDEBUG");
130 // Exit on failure if there were errors.