Question

I have a Shit/reduce conflicts in my bison code :

expression : LBRACKET expression RBRACKET  {$$ = $2;}
       | fct_call                          {}
       | operand                           {}    
       | expression operator_arith expression   {$$ = new NBinaryOperation(*$1, $2, *$3);}
       ;

I can solve it writing :

expression : LBRACKET expression RBRACKET compexp  // {$$ = $2;}
       | fct_call_in_exp compexp               {}
       | operand compexp                       {}
       ;
compexp : /* empty */     {/* Do smthg */}
    | operator_arith expression   {/* Do smthg */}

But it needs to much modification in my Node structure. Thus I'm searching a new way to solve it. Can you help me ?

Have a good day !

Was it helpful?

Solution

This is ambiguous:

expression : expression operator_arith expression

the problem is that if you have more that one infix operator (eg. A + B * C) it can be parsed with either the left operator first (away from the root of the parse tree) or the right operator first.

You need to decide how you want to resolve that ambiguity, and add it to your parser. The usual way is to define precedence levels, saying certain operators are higher precedence than others (so that they should always be parsed first), and for operators of the same level, either the left one or the right one should be first (often referred to a left-recusive and right-recursive).

There are two way of doing this kind of disambiguation. You can introduce more non-terminals (one for each precedence level) and write the grammar with them (there are many example grammars that use term and factor and other related things for these extra levels). Alternately, you can use bison's built in %left and %right declarations to set the precedence of the various operator tokens, and give each production a matching precedence (either by using the token directly, or using %prec). You'll need a separate production for each precedence level (at least), in order to give them different precedences.

Bison's manual contains examples of the latter style.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top