Whenever I add '(' term ')' { $$=$2; }
I got shift reduce conflict
the operation that I'm trying to do is: (5) + (5)
,
(5.5) + (5)
,
((5.5) + (5)) - (5)
,
((5.5) / (5.5)) * (5)
, etc
I'm a bit confused about shift reduce parsing, our professor only teaches us how to shift reduce parsing in an example grammar, but not on how to apply it on cpp.
I'm using bison.
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern int yylex();
#define YYERROR_VERBOSE
void yyerror(const char *msg){
printf("ERROR(PARSER): %s\n", msg);
}
double vars[26];
%}
%union{
double dvalue;
int varindex;
}
%token <dvalue> NUMBER
%token <varindex> NAME
%type <dvalue> expression
%type <dvalue> term
%type <dvalue> varornum
%%
statementlist : statement '\n'
| statement '\n' statementlist
;
statement : NAME '=' expression { vars[$1] = $1;}
| expression { printf("ANS: %f\n", $1); }
;
expression: '(' expression ')' { $$ = $2;}
| expression '+' term { $$ = $1 + $3;}
| expression '-' term { $$ = $1 - $3;}
| term { $$ = $1; }
;
term : '(' term ')' { $$ = $2;}
| term '*' varornum { $$ = $1 * $3;}
| term '/' varornum {
if ($3==0) {
printf("ERROR: Divide %f by zero\n", $1);
} else {
$$ = $1 / $3;
}
}
| varornum { $$ = $1; }
;
varornum : NUMBER { $$ = $1; }
| NAME { $$ = vars[$1];}
;
%%
main(){
yyparse();
}