0

i have the following rules and when implementing them with bison i get 5 shift/reduce warnings.

a part of the Rules are:

Type---->        BOOL   
    |   INT 
    |   CHAR    
    |   DOUBLE  
    |   ID  
    |   INT '['']'
;
rule:           VarDec rule
    |   VarDec
;
VarDec: Type ID ';'
;

and the Parser.output give me the warning in this state:

**state 25**

4 rule: VarDec . rule
5     | VarDec .

BOOL        shift, and go to state 3
INT         shift, and go to state 4
CHAR        shift, and go to state 5
DOUBLE      shift, and go to state 6
ID          shift, and go to state 7

BOOL        [reduce using rule 5 (rule)]
INT         [reduce using rule 5 (rule)]
CHAR        [reduce using rule 5 (rule)]
DOUBLE      [reduce using rule 5 (rule)]
ID          [reduce using rule 5 (rule)]
$default    reduce using rule 5 (rule)

rule            go to state 28
VarDec          go to state 25
Type            go to state 27

can anyone help me how to solve this, i have read many articles but i wasn't able to figure out what's wrong, and thanks in advance to every one... :)

Yaser Jaradeh
  • 322
  • 1
  • 6
  • 27

2 Answers2

1

The above example is not enough to reproduce the shift/reduce conflicts. You probably have an instance of rule somewhere else that is followed by VarDec or the tokens it starts with.

If I add the following rule, I can reproduce the conflicts:

decl : rule VarDec;

That rule is causing your problems.

Bryan Olivier
  • 5,207
  • 2
  • 16
  • 18
0

The conflict occurs in a state where there is a VarDec on top of the parse stack, and the next token is a BOOL, INT, CHAR, DOUBLE, or ID. The parser would then need to look at least two tokens ahead to determine whether it's looking at another VarDec -- in which case the correct action right now is to shift in anticipation of later reducing the following tokens to a 'rule' -- or whether it's looking at something else -- in which case the correct action is to reduce the VarDec currently on top of the stack to a 'rule'.

It should be possible to resolve this particular conflict by changing your 'rule' rule like so:

rule: rule VarDec
  | VarDec
;

to use left recursion instead of right recursion. That's well, too, because you should always use left recursion instead of right recursion in Bison rules. That ensures you can parse any input with bounded stack space.

The actual states identified by Bison might differ a bit with that change, but in the likely event that there were still one having a VarDec on top of the stack and one of BOOL, INT, CHAR, DOUBLE, or ID as the next token, there will be only one possible action (with only the rules presented): reduce the VarDec on the stack to a 'rule'. There's no other possible parse, even if the upcoming tokens later turn out not to reduce to a VarDec.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157