Fricken Hamster
Fricken Hamster

Reputation: 569

Bison parse can't tell between variable declaration and assignment

So I have rules for my grammar,

Method     : METHODNAME Params ')' ':' Types '{' VarsDecs Statements RETURN Returns '}' ';'
           ;
           ;
VarsDecs   : VarDec VarsDecs 
           | 
           ;
VarDec     : VARNAME ':' Types ';'
           ;
Statements : Statement Statements
           |
           ;
Statement  : Assignment
           | Print
           | If
           ;                            
Assignment : VARNAME '=' Expression ';'
           ;

And my parser cannot tell when the variable declaration stops and statements start when assignment is the first statement found because assignment also starts with VARNAME.

How would I go about fixing this?

Upvotes: 0

Views: 848

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126243

The basic problem is that it needs to reduce an empty rule before it can start parsing statements, but when it sees VARNAME as the lookahead, it can't tell if its at the end of the variables delcarations yet, as it needs more lookahead to differentiate between a VarDec and a Statement.

You can improve things a bit by making it left recursive instead of right recursive, but that won't solve the problem completely. To actually get rid of the problem you need to get rid of the empty statements rule:

Statements : Statements Statement
           | Statement

and then change the Method rule to have two versions, one with statements and one without:

Method     : METHODNAME Params ')' ':' Types '{' VarsDecs Statements RETURN Returns '}' ';'
           | METHODNAME Params ')' ':' Types '{' VarsDecs RETURN Returns '}' ';'

Upvotes: 1

waTeim
waTeim

Reputation: 9235

The grammar isn't all here, so it's hard to test directly, but use of right recursion instead of the normal left recursion may be be part of it.

Statements : Statement Statements
VarsDecs   : VarDec VarsDecs 

try making it left recursive

Statements : Statements Statement
VarsDecs   : VarsDecs VarDec 

Upvotes: 0

Related Questions