Showing posts with label Infix to Postfix Expression. Show all posts
Showing posts with label Infix to Postfix Expression. Show all posts

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 ~ $

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 ~ $ 
Related Posts Plugin for WordPress, Blogger...