From 0b31a8d9326e23c9718b0d2f7dd949b06651b619 Mon Sep 17 00:00:00 2001 From: Dimitar Trendafilov Date: Sun, 21 Oct 2018 12:17:26 +0300 Subject: Added bison calculator as a demo --- demo/bison/calc/parser.y | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 demo/bison/calc/parser.y (limited to 'demo/bison/calc/parser.y') diff --git a/demo/bison/calc/parser.y b/demo/bison/calc/parser.y new file mode 100644 index 0000000..7a9aefb --- /dev/null +++ b/demo/bison/calc/parser.y @@ -0,0 +1,46 @@ +%{ +#include +int yylex(); +int yyerror(const char* error); +%} + +%start input +%define api.value.type {float} + +%token NUMBER +%token PLUS +%token MINUS +%token MULT +%token DIV + +/* Define both - precedence and associativity */ +%left PLUS MINUS +%left MULT DIV + +%% + +input: /* empty */ + | expr { printf("%f\n", $1); } + ; + +expr: NUMBER { $$ = $1; } + | '(' expr ')' { $$ = $2; } + | expr PLUS expr { $$ = $1 + $3; } + | expr MINUS expr { $$ = $1 - $3; } + | expr MULT expr { $$ = $1 * $3; } + | expr DIV expr { $$ = $1 / $3; } + +%% + +int yyerror(const char* error) +{ + extern int current_line; + fprintf(stderr, "input:%d: error: %s\n", current_line, error); + return 0; +} + +int main() +{ + yyparse(); + return 0; +} -- cgit v1.3.1-26-gb76a