Postfix Expression Evaluation - Compiler Design - YACC Program

Program:

// Lex file: pos.l

DIGIT [0-9]
%%
{DIGIT}+    {yylval=atoi(yytext);return ID;}
[-+*/]        {return yytext[0];}
. ;
\n         yyterminate();

// Yacc File: pos.y

%{
    #include<stdio.h>
    #include<assert.h>
    void push(int val);
%}

%token ID

%%

S     : E  {printf("= %d\n",top());}
      ;
E     : E E '+' {push(pop()+pop());}
     | E E '-' {int temp=pop();push(pop()-temp);}
     | E E '*' {push(pop()*pop());}
     | E E '/' {int temp=pop();push(pop()/temp);}
     | ID    {push(yylval);}
     ;

%%
#include"lex.yy.c"

int st[100];
int i=0;

void push(int val)
{
    assert(i<100);
    st[i++]=val;
   
}

int pop()
{
    assert(i>0);
    return st[--i];

}

int top()
{
    assert(i>0);
    return st[i-1];
}
int main()
{
    yyparse();
    return 0;
}

Output:

nn@linuxmint ~ $ lex pos.l
nn@linuxmint ~ $ yacc pos.y
nn@linuxmint ~ $ gcc y.tab.c -ll -ly
nn@linuxmint ~ $ ./a.out
5 5 -
= 0
nn@linuxmint ~ $

5 comments:

  1. i was waitin' for this type of article and i have gained some useful information from this site. thanks for sharing this information.

    www.n8fan.net

    ReplyDelete
  2. I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.


    edupdf.org

    ReplyDelete
  3. I read your blog.I thought it was great.. Hope you have a great day. God bless.

    Camille
    www.imarksweb.org

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...