Hello I have just started doing some parsing in bison/yacc. Now my first program already fails. What went wrong? I am using an example from:
original source of tutorial
%{
#include <stdio.h>
int yylex(void);
void yyerror(char *);
%}
%token INTEGER
%%
program:
program expr '\n' { printf("%d\n", $2); }
|
;
expr:
INTEGER { $$ = $1; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
;
%%
void yyerror(char *s) {
fprintf(stderr, "%s\n", s);
}
int main(void) {
yyparse();
return 0;
}
Using version 2.4.1 of bison I get this error:
conflicts: 4 shift/reduce
Try that:
bison/yacc don’t like right recursion. If the input is
1+2+3, when the parser reaches1+2+it can’t decide either to reduce1+2toexpror to shift another token in order to reduce2+3toexpr. By specifyingINTEGERon the right, it can decide to reduce as soon as it sees1+2leaving onlyexpr + 3then reducing again.You can also solve the issue by specifying that
+and-are left associative, thus giving a higher priority to reducing1+2over shifting new tokens. Add that line in your preamble:Hope it helps.