Implementing Code Generator in C++

Here is implementation of Code generation stage of complier in C++. You have to provide input in AIP.TXT file and the output will be stored in ANOP.TXT file.

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
clrscr();
char op1[10],op2[10],op3[10],op4[10];
FILE *ip, *op;
ip=fopen("aip.txt","r");
if(!ip)
{
cout<<"error in opening file";
}
op=fopen("anop.txt","w");
while(!feof(ip))
{
 fscanf(ip,"%s%s%s%s",&op1,&op2,&op3,&op4);
 //fscanf(ip,"%c",&op1[0]);

 if(strcmp(op1,"+")==0)
 {
  fprintf(op,"MOV AX, %s\n",op2);
  fprintf(op,"MOV BX, %s\n",op3);
  fprintf(op,"ADD AX, BX\n");
  fprintf(op,"MOV %s, AX\n",op4);
 }

 if(strcmp(op1,"-")==0)
 {
  fprintf(op,"MOV AX, %s\n",op2);
  fprintf(op,"MOV BX, %s\n",op3);
  fprintf(op,"SUB AX, BX\n");
  fprintf(op,"MOV %s, AX\n",op4);
 }

 if(strcmp(op1,"*")==0)
 {
  fprintf(op,"MOV AX, %s\n",op2);
  fprintf(op,"MOV BX, %s\n",op3);
  fprintf(op,"MUL AX, BX\n");
  fprintf(op,"MOV %s, AX\n",op4);
 }

 if(strcmp(op1,"/")==0)
 {
  fprintf(op,"MOV AX, %s\n",op2);
  fprintf(op,"MOV BX, %s\n",op3);
  fprintf(op,"DIV AX, BX\n");
  fprintf(op,"MOV %s, AX\n",op4);
 }

 if(strcmp(op1,"=")==0)
 {
  fprintf(op,"MOV %s, %s\n",op2,op3);
 }

}
fclose(ip);
fclose(op);
cout<<"\n Code generation successful";
getch();
}

Input (AIP.TXT)

+ o1 o2 o3
- o3 o1 o3
* o1 o2 o3
/ o3 o1 o3
= o5 o6 %

Output (ANOP.TXT)

MOV AX, o1
MOV BX, o2
ADD AX, BX
MOV o3, AX
MOV AX, o3
MOV BX, o1
SUB AX, BX
MOV o3, AX
MOV AX, o1
MOV BX, o2
MUL AX, BX
MOV o3, AX
MOV AX, o3
MOV BX, o1
DIV AX, BX
MOV o3, AX
MOV o5, o6

Leave a Reply

Your email address will not be published. Required fields are marked *