0

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();
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
larca
  • 9
  • 2
  • 7

1 Answers1

1

You already have '(' expr ')' { $$=$2; } in your grammar. Adding '(' term ')' { $$=$2; } creates a conflict with this rule. You only need one of them. Is an expr a term or is a term an expr?

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • term is suppose to be expression – larca Sep 16 '15 at 04:17
  • You still have two identical rules, one with term and one with expression. You only need one of those. – 1201ProgramAlarm Sep 16 '15 at 04:19
  • then is there a rule how to read first variable and second variable with parentheses, like this (5) + (5.5)? – larca Sep 16 '15 at 04:20
  • Since a term is an expression, you don't need the `'(' term ')'` rule since the `'(' expression ')'` rule will include it. – 1201ProgramAlarm Sep 16 '15 at 04:24
  • (5 + 5) + 5 or (5 * 5) + 5 does not have errors but (5 + 5) / 5 or (5 + 5) * 5 – larca Sep 17 '15 at 04:38
  • need helkp please, division and multiplication outside the parentheses results in error – larca Sep 17 '15 at 04:39
  • I'm being a bit vague because this is school work, but the problem with the parentheses is that the entire parenthesized expression is a term, but what goes inside it is an expression. Make this change to your grammar. – 1201ProgramAlarm Sep 18 '15 at 04:22