0
%token A B
%%
start:  {printf("Starting…\n");} A A
 | A B;

My book says that there is a shift-reduce conflict when the token is A because yacc converts to code to this.

%token A B
%%
start: empty A A
 | A B;
empty: {printf("Starting…\n");} ; 

I didn't get this. Here the second rule of start shifts, empty rule reduces. The first rule of start shifts too, So the first input expects A, while the second rule expects B. How is that a conflict? As far as I know,one rule must reduce, other should shift,than the two rules should expect the same token for an input for such conflict. However, one rule both shifts and reduces here(first rule), while the second rule only shifts, also they expect different tokes after those operations.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
BoraKurucu
  • 39
  • 1
  • 1
  • 8
  • Note that in the post-conversion code, the action goes on the `empty` rule -- that's the point of the transform; it moves all actions to the ends of rules. – Chris Dodd Oct 21 '19 at 22:27

1 Answers1

1

The conflict is that it doesn't know whether or not to reduce the empty rule (run the action) before shifting the A. Both rules expect an A as the first token, so you get a shift/reduce conflict. Which should be done depends on the second token, so the grammar is not ambiguous and the conflict could be resolved by using more lookahead (using a GLR or backtracking parser).

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • So a shift/reduce always conflict occurs when any two rules expect the same token at the same time? Shouldn't there be a relationship with one rule reducing and one rule shifting here? Becayse I believe if that printf statement were not there,there will no conflict even if they expect the same token? @Chris – BoraKurucu Oct 21 '19 at 22:24
  • only if they need to do different actions -- if they both just need to shift, then no problem (and no conflict). If you remove the initial action from the first rule, then both need to shift. – Chris Dodd Oct 21 '19 at 22:25
  • Where can I study this topic? I couldn't find any good book, they barely describe it. @Chris – BoraKurucu Oct 21 '19 at 22:27
  • The classic [Dragon Book](https://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools) has a section on LR shift/reduce parsing. – Chris Dodd Oct 21 '19 at 22:48