Re: Yacc and a calculator (Pasquale Foggia)
16 Feb 1996 23:35:39 -0500

          From comp.compilers

Related articles
Yacc and a calculator (Dan Weinlader) (1996-02-13)
Re: Yacc and a calculator (1996-02-14)
Re: Yacc and a calculator (1996-02-16)
| List of all articles for this month |

From: (Pasquale Foggia)
Newsgroups: comp.compilers
Date: 16 Feb 1996 23:35:39 -0500
Organization: Compilers Central
References: 96-02-143
Keywords: yacc, parse

Dan Weinlader <> wrote:
> I have been reading the lex & yacc book by Levine, Mason and Brown and have
> a question on how to extend the calculator example. Suppose I wish to allow
> the user to enter 8 5 and have it parsed as 8*5, how do I do that?

if your grammar doesn't contain any unary operator with the same
token as a binary operator, you can use a %left directive together with
%prec, as in the following grammar:

        %left '+'
        %left DUMMY


        program: expr '\n' ;

        expr: digit
                        | expr '+' expr
                        | expr expr %prec DUMMY
                        | '(' expr ')'

        digit: '0' | '1' | '2';

and ignore the shift/reduce conflicts. I've tried this grammar and
everything works fine. On the other hand, if you have, for example,
an unary + operator it could be a good idea tryng to disambiguate
things at lexer level. I remember SNOBOL used the following
convention: if an operator was followed by a space, it was a binary
operator, else if was a unary one. I hope this can help you.

Pasquale Foggia, PhD student | #include <disclaimer.h>
University of Naples "Federico II" | finger for
Naples, Italy | complete address, PGP key, geek code etc.

Post a followup to this message

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