I'm trying to parse this syntax:
34 + 1 − 8, 32 * 87 + 6 / 4, 34 / 8
I'm expecting to ground it like this:
(, (- (+ 34 1) 8) (/ (+ (* 32 87) 6) 4) (/ 34 8))
This is the code for BISON:
%token NUMBER
%token COMMA
%token OPERATOR
%left OPERATOR
%left COMMA
%%
term: NUMBER | term op term ;
op: OPERATOR | COMMA;
%%
There is a problem:
test.y: conflicts: 2 shift/reduce
How can I solve it?
The problem is with your definition of term
:
term: NUMBER | term op term ;
When parsing this, at each number, the question is: should I read another token to know if I have the first, or the second form.
A solution could be to define:
term: NUMBER reminder;
reminder: /* empty */ | op term;
The grammar, once adapted, looks like the following:
%token NUMBER
%token COMMA
%token OPERATOR
%left OPERATOR
%left COMMA
%%
term: NUMBER reminder;
reminder: /* empty */ | op term;
op: OPERATOR | COMMA;
%%
compiles without warnings with bison (GNU Bison) 2.4.1
.
To find where the conflicts are, use the --verbose
option and look at the file example.output
where your input file is example.y
. Here is the file I got from your input:
State 7 conflicts: 2 shift/reduce
(omitted)
state 7
2 term: term . op term
2 | term op term .
COMMA shift, and go to state 4
OPERATOR shift, and go to state 5
COMMA [reduce using rule 2 (term)]
OPERATOR [reduce using rule 2 (term)]
$default reduce using rule 2 (term)
op go to state 6
You might not have specified the priority of the operators like,
%left '+' '-'
%left '*' '/'
(in definition section)
来源:https://stackoverflow.com/questions/3264884/where-are-the-shift-reduce-conflicts-in-this-bison-code-coming-from