Implicit operator precedence (Sam Thursfield)
30 May 2004 13:34:52 -0400

          From comp.compilers

Related articles
Implicit operator precedence (2004-05-30)
Re: Implicit operator precedence (SM Ryan) (2004-06-06)
Re: Implicit operator precedence (Hans Aberg) (2004-06-15)
| List of all articles for this month |

From: (Sam Thursfield)
Newsgroups: comp.compilers
Date: 30 May 2004 13:34:52 -0400
Keywords: parse, design, comment
Posted-Date: 30 May 2004 13:34:52 EDT

Recently i've been toying with writing a yacc-style (LALR) parser
generator. It's got to the point where it can create a fully working
version of the infix calculator given in the bison manual.

When it came to implementing operator precedence, as a quick hack i
worked out that instead of all the %left DIV MUL business, i could
simply put the rules in order and resolve shift/reduce conflicts by
the number of the rule. it's easier to explain through code:

expr: NUM { $$=$1; }
        | SUB expr { $$=-$2; }
        | expr EXP expr { $$=pow($1, $3); }
        | expr DIV expr { $$=$1/$3; }
        | expr MUL expr { $$=$1*$3; }
        | expr ADD expr { $$=$1+$3; }
        | expr SUB expr { $$=$1-$3; }
        | OPEN expr CLOSE { $$=$2; }

Essentially, this is part of the fully working grammar for the
calculator. No other indication of precedence is needed; the order of
the rules is all the parser generator needs. Initially i was going to
redo this when the whole thing worked and have precedence specified
explicitly, but i've come to like how the current system works. my
question is, can anyone see any obvious problems with this setup? i'm
hardly an expert in the field, so i'd like to see if i'd be making a
huge mistake trying to work with implicit precedence. All I know is
that so far, simply deciding whether to shift or reduce based on which
rule appeares first in the grammar works perfectly for such an
expression calculator.
[How do you tell it that ADD and SUB have the same precedence? -John]

Post a followup to this message

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