%left and %right in yacc

Arjun K P picture Arjun K P · Oct 13, 2012 · Viewed 19.1k times · Source
{%
#include<stdio.h>
#include<stdlib.h>
%}

%token ID NUM IF THEN LE GE EQ NE OR AND ELSE

%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'

%%

Mentioned Above is a part in the yacc program for a simple IF ELSE program.... i m just a beginner and don't understand what do we mean by %right and %left terms...... plz help me on this occasion...

Answer

Gustavo Vargas picture Gustavo Vargas · Jan 11, 2016

I know this is an old question but in case some one else is looking for this information :

%left, %right and %nonassoc, defines how yacc will solve repetition of operators. In case you have:

1 + 2 + 3

both operators have the same precedence level ( they are the same :) ), in this case yacc can solve:

// using %left
(1 + 2) + 3

or:

// using %right
1 + (2 + 3)

and finally:

//using %nonassoc
1 + 2 + 3 is considered illegal and a syntax error!

you can read more in here.