4

I am making a simple compiler for expressions, however I am stuck figuring out how to use Bison's precedence keywords

In my lexer I define the following check:

'-'     {ECHO;return(MINUS);}

However, I noticed that when evaluating expressions, '-' can have two meanings, 1) for subtraction and 2) for negation of an number, and both have different precedences.

In my parser file how would I account for this by using %left and %right to define associativity?

I know I can do

%left PLUS
%left MINUS
... and so on

For each such token, but since negation has right associativity and higher precedence, how would I include that in here, since I do not think I can do

%left PLUS
%left MINUS
%right MINUS /* This is the negation one */

Thanks for your help!

Timofei Davydik
  • 7,244
  • 7
  • 33
  • 59
Nice-kun
  • 81
  • 1
  • 2
  • 9

1 Answers1

4

Quoting from http://dinosaur.compilertools.net/yacc/:

[...] unary operators must, in general, be given a precedence. Sometimes a unary operator and a binary operator have the same symbolic representation, but different precedences. An example is unary and binary '-'; unary minus may be given the same strength as multiplication, or even higher, while binary minus has a lower strength than multiplication. The keyword, %prec, changes the precedence level associated with a particular grammar rule. %prec appears immediately after the body of the grammar rule, before the action or closing semicolon, and is followed by a token name or literal. It causes the precedence of the grammar rule to become that of the following token name or literal. For example, to make unary minus have the same precedence as multiplication the rules might resemble:

    %left  '+'  '-'
    %left  '*'  '/'

    %%

    expr    :       expr  '+'  expr
            |       expr  '-'  expr
            |       expr  '*'  expr
            |       expr  '/'  expr
            |       '-'  expr      %prec  '*'
            |       NAME
            ;
Edward
  • 6,964
  • 2
  • 29
  • 55