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. Wonderful thanks for sharing an amazing idea. keep it...

    Looking for Hadoop Admin Training in Bangalore, learn from Softgen Infotech provide Hadoop Admin Training on online training and classroom training. Join today!

    ReplyDelete
  4. I recommend only good and reliable information, so see it: Bitcoin QR Code

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...