Re: Yacc precedence bug

Lars Henrik Mathiesen <>
Fri, 11 Jan 91 20:23:44 +0100

          From comp.compilers

Related articles
Yacc precedence bug (S Voogd10 Jan 91 11:20 GMT) (1991-01-10)
Re: Yacc precedence bug megatest! (1991-01-11)
Re: Yacc precedence bug corbett@road.Eng.Sun.COM (1991-01-11)
Re: Yacc precedence bug (Stephen Adams) (1991-01-11)
Re: Yacc precedence bug (Lars Henrik Mathiesen) (1991-01-11)
Re: Yacc precedence bug (Klaus Thalhofer) (1991-01-14)
| List of all articles for this month |

Newsgroups: comp.compilers
From: Lars Henrik Mathiesen <>
Keywords: yacc, parse, debug
Organization: Compilers Central
References: <>
Date: Fri, 11 Jan 91 20:23:44 +0100

In article <>, (S
Voogd) writes:
>You can give a token a precedence and associativity by
>declaring this in the declaration-part of a YACC-file
>According to the manual you can also change the precedence
>and associativity of a token in the grammar-rules by
>using the '%prec'-mechanism.

This is not exactly correct, and therein lies your problem. The precedence
and associativity (p+a) feature of YACC resolves shift/reduce conflicts by
comparing the p+a of a production (grammar rule) with the p+a of the next
token on the input. Usually, a production has the p+a of its first
terminal (if any), but it can be specified explicitly with %prec.

>We enclose a simple desk calculator and reverse the usual
>precedence of '+' with '*' using the '%prec'-mechanism.
>It seems that the associativity of tokens can be changed.(?)
>But their precedence levels are now the same.

You have changed the p+a for the _productions_. Those of the tokens
themselves are unchanged. In "a*b+c", the p+a of "+" is compared to itself
to determine the parsing, and since it is left associative, the "wrong"
parsing results. (If it was right associative, "a+b*c" would go "wrong".)

>If it is a bug, is there a way of changing the prec. and
>ass. of tokens ? (We really need it!)

The p+a of tokens are determined by their declaration and cannot be
changed. Only the p+a of productions can be changed. You need to specify
%prec so that the p+a of each production stands in the correct relation to
the p+a of all relevant following tokens (those that cause shift/reduce

A very common way of doing this is to introduce some extra tokens whose
only purpose is to carry a needed p+a; see the use of UMINUS in Appendix A
of the YACC reference. You could also drop the precedence kludgery and
write your grammar out in full (it might become quite large, however).

Lars Mathiesen, DIKU, U of Copenhagen, Denmark [uunet!]mcsun!diku!thorinn
Institute of Datalogy -- we're scientists, not engineers.

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.