Trouble with %prec in yacc

Dave Jones djones at megatest.UUCP
Fri Jul 15 06:48:08 AEST 1988


>From article <237 at h-three.UUCP>, by ned at h-three.UUCP (ned):
...

 
> /* start of doesn't work */
> %token NAME MULT ADD
> %left PREC_ADD
> %left PREC_MULT
> %start expr
> 
> %%
> 
> expr	:	expr MULT expr %prec PREC_MULT
> 	|	expr ADD expr %prec PREC_ADD
> 	|	NAME
> 	;
> /* end of doesn't work */
> 
> doesn't (and compiles with 4 shift/reduce conflicts).  Anyone know
> what I'm doing wrong?  Thanks in advance.
> 
> -- Ned Robie

I'm confused also.

It looks to me as though the above should give ADD and MULT the
same precedence.  (That's probably not what you intended.)

The PREC_ADD and PREC_MULT productions both have 
higher priorities than ADD and MULT.  So reductions should always be
prefered to shifts, right?

I don't see why there should be shift/reduce conflicts.

Here is part of the y.output file:

5: shift/reduce conflict (shift 3, red'n 1) on MULT
5: shift/reduce conflict (shift 4, red'n 1) on ADD
state 5
        expr :  expr_MULT expr
        expr :  expr MULT expr_    (1)
        expr :  expr_ADD expr

        MULT  shift 3
        ADD  shift 4
        .  reduce 1

I don't get it.  Why does it not reduce by

    expr <= expr MULT expr

on either ADD or MULT, each of which has a lower priority than
PREC_MULT?  Looks like a bug to me.

Here's the way %prec is commonly used:

%token NAME
%left '+' '-'
%left '*' '/'

%start expr

%%

expr    :       expr mulop expr %prec '*'
        |       expr addop expr %prec '+'
        |       NAME
        ;

mulop   : '*'
        | '/'
        ;

addop   : '+'
        | '-'
        ;



More information about the Comp.unix.wizards mailing list