I am trying to solve the r/r and s/r conflicts in the following bison grammar
%right TOK_IF TOK_ELSE
%right '='
%left TOK_EQ TOK_NE '<' TOK_LE '>' TOK_GE
%left '+' '-'
%left '*' '/' '%'
%right TOK_POS TOK_NEG '!' TOK_NEW
%left TOK_BLK '.' TOK_CALL
%precedence TOK_PARENT
%start start
expr : expr BINOP expr {$$=$2->adopt($1,$2);}
| UNOP {$$ = $1;}
| allocator {$$ = $1;}
| call {$$ = $1;}
| expr '[' expr ']' %prec TOK_BLK {
destroy($4);
$$ = $2->adopt($1,$3);}
| '(' expr ')' %prec TOK_PARENT {$$ = $2;}
| expr '.' expr {$$ = $2->adopt($1,$3);}
| variable {$$= $1;}
| constant {$$ = $1;}
;
BINOP : TOK_IF {$$ = $1;}
| TOK_ELSE {$$ = $1;}
| '=' {$$ = $1;}
| TOK_EQ {$$ = $1;}
| TOK_NE {$$ = $1;}
| '<' {$$ = $1;}
| TOK_LE {$$ = $1;}
| '>' {$$ = $1;}
| TOK_GE {$$ = $1;}
| '+' {$$ = $1;}
| '-' {$$ = $1;}
| '*' {$$ = $1;}
| '/' {$$ = $1;}
| '%' {$$ = $1;}
;
UNOP : '+' expr %prec TOK_POS {
$1->swap_token_code(TOK_POS);
$$ = $1->adopt($2);
}
| '-' expr %prec TOK_NEG{
$1->swap_token_code(TOK_NEG);
$$ = $1->adopt($2);
}
| '!' expr {$$ = $1->adopt($2);}
;
allocator : TOK_NEW TOK_IDENT '('')' {
destroy($3);
$2->swap_token_code(TOK_TYPEID);
$$ = $1->adopt($2);
}
| TOK_NEW TOK_STRING '(' expr ')'{
}
| TOK_NEW basetype '[' expr ']'{
destroy($3);destroy($5);
$1->swap_token_code(TOK_NEWARRAY);
$$ = $1->adopt($2,$4);
}
;
call : TOK_IDENT '(' exprs ')' %prec TOK_CALL{
destroy($4);
$2->swap_token_code(TOK_CALL);
$$ = ($2->adopt($1))->cannibalize($3);
}
;
exprs : exprs expr {$$ = $1->adopt($2);}
| {$$ = new astree ('{',{0,0,0}, "}");}
;
variable : TOK_IDENT {$$ = $1;}
| expr '[' expr ']'{
destroy($4);
$$ = $2->adopt($1,$3);
}
| expr '.' TOK_IDENT {$$ = $2->adopt($1,$3);}
;
constant :TOK_INTCON {$$ = $1;}
|TOK_CHARCON {$$ = $1;}
|TOK_STRINGCON {$$ = $1;}
|TOK_NULL {$$ = $1;}
;
%%
I think the problem is the rule expr : expr BINOP expr because when I get rid of it, it stops showing these conflicts. I have declared the precedence rules above to avoid shift/reduce conflicts, but it looks like it's not working. Can someone give me shortcuts in debugging an ambiguous grammar?. Disregard the semantic rules.
parser.y: warning: 24 shift/reduce conflicts [-Wconflicts-sr]
parser.y: warning: 56 reduce/reduce conflicts [-Wconflicts-rr]
parser.y:140.14-143.12: warning: rule useless in parser due to conflicts [-Wother]
| expr '[' expr ']'{
^^^^^^^^^^^
parser.y:144.14-56: warning: rule useless in parser due to conflicts [-Wother]
| expr '.' TOK_IDENT {$$ = $2->adopt($1,$3);}
UPDATE: I detected a problem in my understanding
Although I am getting the right results, my compiler keeps telling that there is a shift/reduce conflict in the following grammar. I think there shouldn't be conflicts because I specified precedence and associativity properly.
%left '+'
%left '*'
%%
expr : expr BINOP expr
| TOK_INTCON
BINOP : '+'
| '*'
%%
], or to provide the binary operator as an argument toadopt(). - user207421