so I'm doing a thesis where I am making my own programming language. I am currently trying to make a simple calculator language that allows you to assign ints to variables and then do operations/print them out.
However I ran across the situation that bison treats everything with the same precedence unless told otherwise (so 1 + 2 * 3 gives 9 instead of 7).
I looked around and I was told doing something like
%left ADD SUB
%left MUL DIV
would give me the expected output, but it doesn't. Can anyone help me figure out what is going wrong?
here's my flex file
%{
#include <stdio.h>
#include <stdlib.h>
#include "Parser.tab.h"
%}
%%
print {return PRINT;}
exit {return EXIT;}
[a-zA-Z] {yylval.name = yytext[0]; return ID;}
[0-9]+ {yylval.data = atoi(yytext); return NUMBER;}
[;\n] {return NEWLINE;}
[ \t] {;}
"-" {return SUB;}
"+" {return ADD;}
"*" {return MUL;}
"/" {return DIV;}
. {return UNKNOWN;}
%%
int yywrap(void) { return -1; }
here's my bison file
%{
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "Test.h"
void yyerror(const char* err);
int size = 52;
int vars[52];
extern int yylex();
%}
%define parse.error verbose
%union {
char name;
int data;
}
%token EXIT UNKNOWN NEWLINE
%token <data> PRINT
%token <name> ID
%token <data> NUMBER
%type <data> line exp term prog
%type <name> assignment
%start line
%left ADD SUB
%left MUL DIV
%%
term: NUMBER {
$$ = $1;
}
| ID {
$$ = GetVar($1, vars);
}
;
exp: term
| exp MUL term {
$$ = $1 * $3;
}
| exp DIV term {
$$ = $1 / $3;
}
| exp ADD term {
$$ = $1 + $3;
}
| exp SUB term {
$$ = $1 - $3;
}
;
assignment: ID '=' exp NEWLINE {
UpdateVar($1, $3, vars);
}
;
prog: assignment {;}
| PRINT exp NEWLINE {
printf("%d\n", $2);
}
| EXIT NEWLINE {
return 0;
}
| NEWLINE { ; }
;
line: prog | line prog
%%
void yyerror(const char* err) {
printf("Error happened: %s\n", err);
}
int main() {
for(int i = 0; i < size; i++) {
vars[i] = 0;
}
return yyparse();
}