Intermediate Code Generator for Arithmetic Expression - Yacc Program - Compiler Lab

Program:

(Lex Program : intar.l)

ALPHA [A-Za-z]
DIGIT [0-9]
%%

{ALPHA}({ALPHA}|{DIGIT})* return ID;
{DIGIT}+ {yylval=atoi(yytext); return NUM;}
[\n\t] yyterminate();
. return yytext[0];
%%

(Yacc Program : intar.y)

%token ID NUM
%right '='
%left '+' '-'
%left '*' '/'
%left UMINUS
%%

S : ID{push();} '='{push();} E{codegen_assign();}
   ;
E : E '+'{push();} T{codegen();}
   | E '-'{push();} T{codegen();}
   | T
   ;
T : T '*'{push();} F{codegen();}
   | T '/'{push();} F{codegen();}
   | F
   ;
F : '(' E ')'
   | '-'{push();} F{codegen_umin();} %prec UMINUS
   | ID{push();}
   | NUM{push();}
   ;
%%

#include "lex.yy.c"
#include<ctype.h>
char st[100][10];
int top=0;
char i_[2]="0";
char temp[2]="t";

main()
 {
 printf("Enter the expression : ");
 yyparse();
 }

push()
{
  strcpy(st[++top],yytext);
 }

codegen()
 {
 strcpy(temp,"t");
 strcat(temp,i_);
  printf("%s = %s %s %s\n",temp,st[top-2],st[top-1],st[top]);
  top-=2;
 strcpy(st[top],temp);
 i_[0]++;
 }

codegen_umin()
 {
 strcpy(temp,"t");
 strcat(temp,i_);
 printf("%s = -%s\n",temp,st[top]);
 top--;
 strcpy(st[top],temp);
 i_[0]++;
 }

codegen_assign()
 {
 printf("%s = %s\n",st[top-2],st[top]);
 top-=2;
 }


Output:

nn@linuxmint ~ $ lex intar.l
nn@linuxmint ~ $ yacc intar.y
nn@linuxmint ~ $ gcc y.tab.c -ll -ly
nn@linuxmint ~ $ ./a.out
Enter the expression : a=(k+8)*(c-s)
t0 = k + 8
t1 = c - s
t2 = t0 * t1
a = t2
nn@linuxmint ~ $

4 comments:

  1. For the long input, after t9 , t10 is not displayed (t:).

    ch@ubuntu:~$ ./a.out
    Enter the expression : a=b*c+d*c-c/5+2*8-5+5*5/8-8
    t0 = b * c
    t1 = d * c
    t2 = t0 + t1
    t3 = c / 5
    t4 = t2 - t3
    t5 = 2 * 8
    t6 = t4 + t5
    t7 = t6 - 5
    t8 = 5 * 5
    t9 = t8 / 8
    t: = t7 + t9
    t; = t: - 8
    a = t;
    nn@linuxmint ~ $

    How to solve this problem?

    ReplyDelete
  2. Please check this...

    http://2k8618.blogspot.com/2011/08/intermediate-code-generator-for.html

    ReplyDelete
  3. I appreciate that you produced this wonderful article to help us get more knowledge about this topic.
    I know, it is not an easy task to write such a big article in one day, I've tried that and I've failed. But, here you are, trying the big task and finishing it off and getting good comments and ratings. That is one hell of a job done!

    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium interview questions and answers

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...