0

I was doing a simple C parser project. This problem occurred when I was writing the grammar for if-else construct.

the grammar that I have written is as following:

iexp:   IF OP exp CP block eixp END{
                printf("Valid if-else ladder\n");
        };

eixp:
        |ELSE iexp
        |ELSE block;

exp:     id
        |NUMBER
        |exp EQU  exp
        |exp LESS exp
        |exp GRT  exp
        |OP exp CP;

block:  statement
        |iexp
        |OCP statement CCP
        |OCP iexp CCP;

statement: id ASSIGN NUMBER SEMICOL;

id:     VAR;

where the lex part looks something like this

"if"            {return IF;}
"else"          {return ELSE;}
[0-9]+          {return NUMBER;}
">"             {return GRT;}
"<"             {return LESS;}
"=="            {return EQU;}
"{"             {return OCP;}
"}"             {return CCP;}
"("             {return OP;}
")"             {return CP;}
"$"             {return END;}
";"             {return SEMICOL;}
"="             {return ASSIGN;}
[a-zA-Z]+       {return VAR;}
.               {;}

I am getting o/p as

yacc: 9 shift/reduce conflicts, 1 reduce/reduce conflict.

When I eliminate the left recursion on exp derivation the conflicts vanish but why it's so ?

the revised grammar after eliminating left recursion was :

exp:     id
        |NUMBER
        |id EQU  exp
        |id LESS exp
        |id GRT  exp
        |OP exp CP;

I was able to parse successfully the grammar for the evaluation of arithmetic expressions. Is it so that %right, %left made it successful

%token ID
%left  '+' '-'
%left  '*' '/'
%right NEGATIVE
%%

S:E {
        printf("\nexpression : %s\nResult=%d\n", buf, $$);
        buf[0] = '\0';
 };
E: E '+' E {
        printf("+");
        ($$ = $1 + $3);
 } |
   E '-' E {
        printf("-");
        ($$ = $1 - $3);
 } |
   E '*' E {
        printf("*");
        ($$ = $1 * $3);
 } |
   E '/' E {
        printf("/");
        ($$ = $1 / $3);
 } |
   '(' E ')' {
        ($$ = $2);
 } |
   ID {
        /*do nothing done by lex*/
 };
Cœur
  • 37,241
  • 25
  • 195
  • 267
Madhusoodan P
  • 681
  • 9
  • 20
  • 1
    Your original grammar is ambiguous: Should `a > b > c` parse as `(a > b) > c` or `a > (b > c)`? – melpomene Sep 08 '16 at 05:17
  • 2
    The answer to the question in your title is 'yes'. – user207421 Sep 08 '16 at 06:33
  • Yacc not only handles left-recursive grammars, but it handles them better than right-recursive. Right-recursive productions build a Yacc stack depth in proportion to the recursion depth, after which a cascade of reductions occurs. Left-recursive productions do not; they reduce progressively. – Kaz Sep 13 '16 at 23:35

0 Answers0