From ce3d82fcd2d1bf59ca6effac687b70ce2c73e466 Mon Sep 17 00:00:00 2001 From: Dimitar Trendafilov Date: Mon, 24 Oct 2022 23:31:13 +0300 Subject: Demo parser to show associativity with bison --- demo/bison/associativity/parser.y | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 demo/bison/associativity/parser.y (limited to 'demo/bison/associativity/parser.y') diff --git a/demo/bison/associativity/parser.y b/demo/bison/associativity/parser.y new file mode 100644 index 0000000..3852e39 --- /dev/null +++ b/demo/bison/associativity/parser.y @@ -0,0 +1,59 @@ +%{ +#include +int yylex(); +int yyerror(const char* error); +#define YYDEBUG 0 +#include +#include +using namespace std::string_literals; +%} + +%start input +%define api.value.type {std::string} + +%token NUMBER +%token IDENT +%token PLUS +%token MINUS +%token MULT +%token DIV +%token ASSIGN + +/* Define both - precedence and associativity */ +%right ASSIGN +%left PLUS MINUS +%left MULT DIV + +%% + +input: /* empty */ + | expr { std::cout << $1 << std::endl; } + ; + +expr: NUMBER { $$ = $1; } + | IDENT { $$ = $1; } + | '(' expr ')' { $$ = "( "s + $2 + " )"; } + | expr PLUS expr { $$ = "{ "s + $1 + " + " + $3 + " }"; } + | expr MINUS expr { $$ = "{ "s + $1 + " - " + $3 + " }"; } + | expr MULT expr { $$ = "{ "s + $1 + " * " + $3 + " }"; } + | expr DIV expr { $$ = "{ "s + $1 + " / " + $3 + " }"; } + | expr ASSIGN expr { $$ = "{ "s + $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() +{ +#if YYDEBUG + yydebug = 1; +#endif + + yyparse(); + return 0; +} -- cgit v1.3.1-26-gb76a