Website Summary Files Commits Branches @commit @diff @stats
path: root / demo / bison / associativity / parser.y
diff options
context:
space:
mode:
Commitce3d82fcd2d1bf59ca6effac687b70ce2c73e466 (patch)
Author
 Dimitar Trendafilov <trendafilov.dn@gmail.com>
2022-10-24 23:31:13 +0300
Committer
 Dimitar Trendafilov <trendafilov.dn@gmail.com>
2022-10-24 23:31:13 +0300
Files3a5473976be743af18ef2fe6e8516f8db753f10b /demo/bison/associativity/parser.y
IPL-ce3d82fcd2d1bf59ca6effac687b70ce2c73e466.tar
IPL-ce3d82fcd2d1bf59ca6effac687b70ce2c73e466.tar.gz
IPL-ce3d82fcd2d1bf59ca6effac687b70ce2c73e466.zip
Parent6c73a13855d76ed32c067564beee9d474f0d7bc1 (diff)
Demo parser to show associativity with bison
1 files changed, 59 insertions, 0 deletions
-rw-r--r--demo/bison/associativity/parser.y59
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 <stdio.h>
+int yylex();
+int yyerror(const char* error);
+#define YYDEBUG 0
+#include <iostream>
+#include <string>
+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;
+}