Parser for Infix Expression to Postfix Expression - YACC Program - Compiler Lab

Program:

(Lex program: ip.l)

ALPHA [A-Z a-z]
DIGIT [0-9]
%%
{ALPHA}({ALPHA}|{DIGIT})*    return ID;
{DIGIT}+                                      {yylval=atoi(yytext); return ID;}
[\n \t]                                              yyterminate();
.                                                      return yytext[0];
%%

(Yacc program: ip.y)
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token    ID
%left    '+' '-'
%left    '*' '/'
%left    UMINUS

%%

S    :    E
E    :    E'+'{A1();}T{A2();}
      |    E'-'{A1();}T{A2();}
      |    T
      ;
T    :    T'*'{A1();}F{A2();}
      |    T'/'{A1();}F{A2();}
      |    F
      ;
F    :    '('E{A2();}')'
      |    '-'{A1();}F{A2();}
      |    ID{A3();}
      ;

%%

#include "lex.yy.c"
char st[100];
int top=0;

main()
{
    printf("Enter infix expression:  ");
    yyparse();
    printf("\n");
}

A1()
{
    st[top++]=yytext[0];
}

A2()
{
    printf("%c",st[--top]);
}

A3()
{
    printf("%c",yytext[0]);
}

Output:
nn@linuxmint ~ $ lex ip.l
nn@linuxmint ~ $ yacc ip.y
nn@linuxmint ~ $ gcc y.tab.c -ll -ly
nn@linuxmint ~ $ ./a.out
Enter infix expression:  (3+5)*(6-2)
35+62-*
nn@linuxmint ~ $ 

5 comments:

  1. Awesome.!! Thank you very much!! Was looking for this only.
    --cheers

    ReplyDelete
  2. Am I Missing Something?

    ask.l: In function ‘yylex’:
    ask.l:4:8: error: ‘ID’ undeclared (first use in this function)
    ask.l:4:8: note: each undeclared identifier is reported only once for each function it appears in
    ask.l:5:2: error: ‘yylval’ undeclared (first use in this function)

    Thanks ! :)

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...