Search code examples
bisonambiguityshift-reduce-conflict

shift/reduce conflicts error


I receive a 20 shift/reduce conflicts error. I handled the operator precedence by declaring them separately. I'm not sure about exprList and propertyList, I tried different versions of them but the error would not change.

%#include<studio.h>


void yyerror( const char *s)
{
printf("%s\n",s);
}
%}
%token tFOR tIN tFUNCTION tSEMICOLON tLPAR tLBRKT tLBRACE tCOLON tINT 
tREAL tSTRING tWHILE tVAR tELSE tCOMMA tRPAR tRBRKT tRBRACE tEQ tNOT tIF  
tIDENT
%token tGT
%token tLT
%token tEQCHECK
%left tPLUS tMINUS
%left tSTAR
%%
statementList:statement|statementList statement | statementList 
tSEMICOLON statement;
statement: assign | if | expr |statementBlock | while |for | functionCall 
| functionDeclaration;
assign: tIDENT tEQ expr | tVAR tIDENT tEQ expr;
if: ifPart elsePart;
ifPart: tIF tLPAR expr tRPAR statementBlock;
elsePart: tELSE statementBlock;
while: tWHILE tLPAR expr tRPAR statementBlock;
for: tFOR tLPAR tVAR tIDENT tIN expr tRPAR statementBlock | tFOR tLPAR 
expr tRPAR statementBlock;
functionDeclaration: tFUNCTION tIDENT tLPAR exprList tRPAR statementBlock
                        | tFUNCTION tIDENT tLPAR tRPAR statementBlock;
statementBlock: tLBRACE statementList tRBRACE;
functionCall:tIDENT tLPAR exprList tRPAR | tIDENT tLPAR tRPAR;
expr: tIDENT | tSTRING |tLBRKT tRBRKT | tLBRKT exprList tRBRKT
        |tLBRACE tRBRACE | tLBRACE propertyList tRBRACE | tNOT expr |
 expr tPLUS term | expr tMINUS term | term |
 expr tEQCHECK expr | expr tLT expr | expr tGT expr;
exprList: expr | exprList tCOMMA expr;
propertyList: tIDENT tCOLON expr
                | propertyList tCOMMA tIDENT tCOLON expr;
term:term tSTAR factor | factor;
factor: tREAL| tINT;

%%

Solution

  • %token does not declare a precedence value for an operator. So tLT, tGT and tEQCHECK do not have precedence declarations. (And neither does tNOT, as I realised afterwards.)

    On the other hand, you have declared precedence for tPLUS, tMINUS and tSTAR, but those definitions are unnecessary (and unused) because your grammar is already explicit about their precedences.

    However, I believe there is an error in your definition of factor: it is at the bottom of the precedence chain, so it should include all operand syntaxes. That doesn't seem to be the case; indeed, I don't see any production which would accept a parenthesized expression (such as 2 * (3 + 4)), and I have no idea how you expect expressions to include function calls.

    You should probably decide whether or not you will use precedence declarations, and either do so consistently (which is often easier) or not at all. Reviewing your course material on this subject may help; if not, there are many examples on the web.