# Is it possible to make this grammar unambiguous? expr: … | expr expr [closed]

I am writing a simple calculator in yacc / bison.

The grammar for an expression looks somewhat like this:

expr
: NUM
| expr '+' expr { $$= 1 + 3; } | expr '-' expr {$$ = $1 -$3; }
| expr '*' expr { $$= 1 * 3; } | expr '/' expr {$$ = $1 /$3; }
| '+' expr %prec '*' { $$= 1; } | '-' expr %prec '*' {$$ = $1; } | '(' expr ')' { $$= 2; } | expr expr {$$ =$1 '*' $2; } ;  I have declared the precedence and associativity of the operators like this. %left '+' '-' %left '*' '/' %nonassoc '('  The problem is with the last rule: expr expr {$$=$1 \$2; }


I want this rule because I want to be able to write expressions like 5(3+4)(3-24) in my calculator.

Is it possible to make this grammar unambiguous?

## closed as off-topic by D.W.♦Oct 19 '15 at 7:31

• This question does not appear to be about computer science within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

• Try adding %prec '*' or some other precedence to this rule. – Yuval Filmus Oct 18 '15 at 11:34
• @YuvalFilmus: That can't work. By the time expr expr has been reached, the damage has been done. Consider 2+2; precedence won't help disambiguate that from 2 implicit-multiply +2 – rici Oct 18 '15 at 23:05
• I answered this question in StackOverflow where it was originally asked. I don't believe "how do I use bison precedence declarations" really qualifies as a theoretical CS issue. – rici Oct 18 '15 at 23:06
• Also posted on SO. Please do not post the same question on multiple sites. Each community should have an honest shot at answering without anybody's time being wasted. If you don't get a satisfying answer after a week or so, feel free to flag for migration. – D.W. Oct 19 '15 at 7:28
• I'm voting to close this question as off-topic because it was cross-posted on multiple Stack Exchange sites, which violates Stack Exchange rules. The copy on Stack Overflow was answered, so it seems appropriate to close the copy here. – D.W. Oct 19 '15 at 7:31