2
$\begingroup$

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?

$\endgroup$

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.

  • 1
    $\begingroup$ Try adding %prec '*' or some other precedence to this rule. $\endgroup$ – Yuval Filmus Oct 18 '15 at 11:34
  • $\begingroup$ @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 $\endgroup$ – rici Oct 18 '15 at 23:05
  • 1
    $\begingroup$ 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. $\endgroup$ – rici Oct 18 '15 at 23:06
  • $\begingroup$ 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. $\endgroup$ – D.W. Oct 19 '15 at 7:28
  • $\begingroup$ 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. $\endgroup$ – D.W. Oct 19 '15 at 7:31