Can this YACC grammar be unambiguous? expr: ... | expr expr

I am writing a simple calculator in yacc / bison.

The grammar of the expression looks something 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 priority of operators like this.

%left '+' '-'
%left '*' '/'
%nonassoc '('

The problem is the last rule:

expr expr { $$ = $1 $2; }

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

Is it possible to make this grammar unambiguous?

+4
source share
1 answer

The ambiguity arises due to the fact that you allow unary operators ( - expr), so 2 - 2you can analyze it either as a simple subtraction (giving 0) or as an implicit product (2 and -2, yielding - 4).

, ( ), expr: expr expr, expr .

(, , ), , , .

, : , /, . , ab/cd. , , , .

, . , -ab (-a)b, -(ab) ( , ). .

term: NUM
    | '(' expr ')'
unop: term
    | '-' unop
    | '+' unop
conc: unop
    | conc term
prod: conc
    | prod '*' conc
    | prod '/' conc
expr: prod
    | expr '+' prod
    | expr '-' prod
+3

Source: https://habr.com/ru/post/1612117/


All Articles