SIMULATION OF ANSI-C-MACROPROCESSOR
PROGRAM CODE:-
#include<stdio.h>
char line[100][90];
int nn=0,i,j,k,a,b,c;
FILE *fp;
struct macro
{
char name[10];
char param[10][5];
char arg[10][5];
char expr[100],exprs[100];
int pm;
}m[10];
int num=0;
void readline()
{
fp=fopen("ansi.c","r");
if(fp!=NULL)
{
while(fgets(line[nn],90,fp)!=NULL)
{
nn++;
}
}
fclose(fp);
}
void processDefinition()
{
int check=0;char wat[100]; int k=0;
for(i=0;i<nn;i++)
{
check=0;
j=0;
if(line[i][j]=='#')
{
j++;k=0;
while(line[i][j]!=' ')
{
wat[k]=line[i][j];
k++; j++;
}
wat[k]='\0';
if(strcmp(wat,"DEFINE")==0)
{
check=1;
}
int y=0;
if(check==1)
{
check=0;
for(j+=1;line[i][j]!=' ';j++)
{
if(line[i][j]!='(' && check==0)
{
m[num].name[y]=line[i][j]; y++;
}
else if(line[i][j]=='(')
{ m[num].name[y]='\0'; y=0; check=1;}
else if(check==1)
{
int p=0,l=0;
while(line[i][j]!=')')
{
if(line[i][j]!=',')
{ m[num].param[p][l]=line[i][j]; l++; }
else if(line[i][j]==',')
{ m[num].param[p][l]='\0'; p++; l=0; }
j++;
}
m[num].param[p][l]='\0'; p++; m[num].pm=p; l=0;
j++;
while(line[i][j]!='\n')
{
m[num].expr[l]=line[i][j]; l++; j++;
}m[num].expr[l]='\0';
break;
}
}
num++;
}
}
}
return ;
}
void processExpansion()
{
char wat[20]; int aa=0,l=0;
for(i=0;i<nn;i++)
{
for(j=0;line[i][j]!='\n';j++)
{
if(line[i][j]=='#')
break;
for(k=0;k<num;k++)
{
aa=0;
if(line[i][j]==m[k].name[0])
{
l=0; int y=j;
while(l<strlen(m[k].name))
{
wat[l]=line[i][y];l++; y++;
} wat[l]='\0';
if(strcmp(wat,m[k].name)!=0)
continue;
y=y+1;
int p=0,l=0;
while(line[i][y]!=')')
{
if(line[i][y]!=',')
{ m[k].arg[p][l]=line[i][y]; l++; }
else if(line[i][y]==',')
{ m[k].arg[p][l]='\0'; p++; l=0; }
y++;
}
m[k].arg[p][l]='\0'; p++; l=0;
for(a=0;a<strlen(m[k].expr);a++)
{
for(b=0;b<m[k].pm;b++)
{
if(m[k].expr[a]==m[k].param[b][0])
{
p=a;l=0;
while(l<strlen(m[k].param[b]))
{
wat[l]=m[k].expr[p]; l++; p++;
}
wat[l]='\0';
if(strcmp(wat,m[k].param[b])==0)
{
l=0;
while(l<strlen(m[k].arg[b]))
{ m[k].exprs[aa]=m[k].arg[b][l]; l++; aa++; }
break;
}
}
}
if(b==m[k].pm)
{ m[k].exprs[aa]=m[k].expr[a]; aa++; }
}
m[k].exprs[aa]=';'; aa++;
m[k].exprs[aa]='\0';
l=0;
while(l<strlen(m[k].exprs))
{ line[i][j]=m[k].exprs[l]; l++; j++; }
break;
}
}
if(k!=num)
break;
}
}
}
main()
{
readline();
processDefinition();
processExpansion();
for(i=0;i<nn;i++)
{
printf("\n%s",line[i]);
}
}
SAMPLE INPUT-FILE:-
#include<stdio.h>
#DEFINE ABSDIFF(X,Y) (X>Y) ? (X)-(Y) : (Y)-(X)
#DEFINE AS(X) printf("%s",X);
main()
{
char r[10];
ABSDIFF(3,8);
ABSDIFF(6,7);
AS(r);
}
No comments:
Post a Comment