0% found this document useful (0 votes)
142 views

CD Lab - Program

The document contains code for several programs related to compiler design: 1. A lexical analyzer program that tokenizes an input string and identifies the tokens as identifiers, operators, keywords, etc. 2. A recursive descent parser program that parses an input string according to a context-free grammar and produces a parse tree. 3. Programs for a simple calculator compiler including lexical analysis and parsing specifications (lex and yacc files) and driver code to run the lexer and parser. 4. An intermediate code generator program that takes an infix expression and generates equivalent postfix intermediate code.

Uploaded by

api-434094364
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
142 views

CD Lab - Program

The document contains code for several programs related to compiler design: 1. A lexical analyzer program that tokenizes an input string and identifies the tokens as identifiers, operators, keywords, etc. 2. A recursive descent parser program that parses an input string according to a context-free grammar and produces a parse tree. 3. Programs for a simple calculator compiler including lexical analysis and parsing specifications (lex and yacc files) and driver code to run the lexer and parser. 4. An intermediate code generator program that takes an infix expression and generates equivalent postfix intermediate code.

Uploaded by

api-434094364
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

1.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<string.h>
#include<math.h>
#include<ctype.h>
void main()
{ inti=0,j=0,x=0,n,flag=0; void *p,*add[15];
charch,srch,b[15],d[15],c;
printf("expression terminated by $:");
while((c=getchar())!='$')
{ b[i]=c;
i++;
}
n=i-1;
printf("given expression:");
i=0;
while(i<=n)
{ printf("%c",b[i]);
i++;
}
printf("symbol table\n");
printf("symbol\taddr\ttype\n");
while(j<=n)
{ c=b[j];
if(isalpha(toascii(c)))
{ if(j==n)
{ p=malloc(c);
add[x]=p;
d[x]=c;
printf("%c\t%d\tidentifier\n",c,p);
}
else
{ ch=b[j+1];
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{ p=malloc(c);
add[x]=p;
d[x]=c;
printf("%c\t%d\tidentifier\n",c,p);
x++; } }
}
j++;
}
printf("the symbol is to be searched\n");
srch=getch();
for(i=0;i<=x;i++)
{ if(srch==d[i])
{ printf("symbol found\n"); printf("%c%s%d\n",srch,"@address",add[i]); flag=1; }}
if(flag==0)
printf("symbol not found\n");
getch();
}
2.PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void main()
{
FILE *fi,*fo,*fop,*fk;
int flag=0,i=1;
char c,t,a[15],ch[15],file[20];
clrscr();
printf("\n Enter the File Name:\n");
fi=fopen("input.c","r");
fo=fopen("inter.c","w");
fop=fopen("oper.c","r");
fk=fopen("key.c","r");
c=getc(fi);
while(!feof(fi))
{
if(isalpha(c)||isdigit(c)||(c=='['||c==']'||c=='.')==1)
fputc(c,fo);
else
{
if(c=='\n')
fprintf(fo,"\t$\t");
else
fprintf(fo,"\t%c\t",c);
}
c=getc(fi);
}
fclose(fi);
fclose(fo);
fi=fopen("input.c","r");
printf("\n Lexical Analysis\n\n");
fscanf(fi,"%s",a);
while(!feof(fi))
{
fscanf(fop,"%s",ch);
while(!feof(fop))
{
if(strcmp(ch,a)==0)
{
fscanf(fop,"%s",ch);
printf("\t\t%s\t:\t%s\n\n",a,ch);
flag=1;
} fscanf(fop,"%s",ch);
}
rewind(fop);
fscanf(fk,"%s",ch);
while(!feof(fk))
{
if(strcmp(ch,a)==0)
{
fscanf(fk,"%k",ch);
printf("\t\t%s\t:\tKeyword\n\n",a);
flag=1;
}
fscanf(fk,"%s",ch);
}
rewind(fk);
if(flag==0)
{
if(isdigit(a[0]))
printf("\t\t%s\t:\tConstant\n\n",a);
else
printf("\t\t%s\t:\tIdentifier\n\n",a);
}
flag=0;
fscanf(fi,"%s",a);
}
getch();
}
Key.c
int
void
main
char
if
for
while
else
printf
scanf
FILE
Include
stdio.h
conio.h
iostream.h

oper.c
( open para
) closepara
{ openbrace
} closebrace
<lesser
>greater
" doublequote
' singlequote
: colon
; semicolon
# preprocessor
= equal
== asign
% percentage
& reference
* star
+ add
- sub
\ backslash
/ slash
3.PROGRAM:
%
{
#include<math.h>
#include<stdlib.h>
%
}
DIGIT [0-9]
ID [a-z][a-z 0-9]*
%%
{DIGIT}+
{
printf("An integer:%s(%d)\n",yytext,atoi(yytext));
}
{DIGIT}+"."{DIGIT}*
{
printf("A float:%s(%g)\n",yytext,atof(yytext));
}
if|then|begin|end|procedure|function
{
printf("A keywoard:%s\n",yytext);
}
{ID} printf("Identifier:%s\n",yytext);
"+"|"-"|"*"|"/" printf("operator:%s\n",yytext);
[\t\n]+ printf("Unrecognized character:%s\n",yytext);
%%
main(argc,argv)
intargc;
char **argv;
{
++argv,--argc;
if(argc> 0)
yyin=fopen(argv[0],"r");
else
yyin=stdin;
yylex();
}
4. PROGRAM:

#include "stdio.h"
#include "conio.h"
char input[100];
char prod[100][100];
intpos=-1,l,st=-1;
charid,num;
void E();
void T();
void F();
void advance();
void Td();
void Ed();
void advance()
{ pos++;
if(pos<l)
{ if(input[pos]>='0'&& input[pos]<='9')
{ num=input[pos];
id='\0'; }
if((input[pos]>='a' || input[pos]>='A')&&(input[pos]<='z' || input[pos]<='Z'))
{id=input[pos];
num='\0'; } } }
void E()
{ strcpy(prod[++st],"E->TE'");
T(); Ed(); }
void Ed()
{ int p=1;
if(input[pos]=='+')
{ p=0;
strcpy(prod[++st],"E'->+TE'");
advance();
T(); Ed(); }
if(input[pos]=='-')
{ p=0;
strcpy(prod[++st],"E'->-TE'");
advance();
T(); Ed(); }
// Recursive Descent Parser
if(p==1)
{ strcpy(prod[++st],"E'->null"); }
}
void T()
{ strcpy(prod[++st],"T->FT'");
F(); Td(); }
void Td()
{ int p=1;
if(input[pos]=='*')
{ p=0;
strcpy(prod[++st],"T'->*FT'");
advance();
F(); Td();
}
if(input[pos]=='/')
{ p=0;
strcpy(prod[++st],"T'->/FT'");
advance();
F(); Td(); }
if(p==1)
strcpy(prod[++st],"T'->null");
}
void F()
{ if(input[pos]==id)
{ strcpy(prod[++st],"F->id");
advance(); }
if(input[pos]=='(')
{ strcpy(prod[++st],"F->(E)");
advance();
E();
if(input[pos]==')')
{ //strcpy(prod[++st],"F->(E)");
advance(); }
}
if(input[pos]==num)
{ strcpy(prod[++st],"F->num");
advance(); } }
int main()
{
inti;
printf("Enter Input String ");
scanf("%s",input);
l=strlen(input);
input[l]='$';
advance();
E();
if(pos==l)
{ printf("String Accepted\n");
for(i=0;i<=st;i++)
{ printf("%s\n",prod[i]); } }
else
{ printf("String rejected\n"); }
getch();
return 0;
5. A.LEX SPECIFICATION

%{
#include”y.tab.h”
#include<math.h>
%}
%%
([0-9]+|([0-9]*\.[0-9]+)([eE][\-+]?[0-9]+)?){
yylval.dval=atof(yytext);
return NUMBER;
}
log |
LOG { return LOG; }
ln { return nLOG; }
sin |
SIN { return SINE; }
cos |
COS { return COS; }
tan |
TAN { return TAN; }
mem |
MEM { return MEM; }
[\t];
\$ { return 0; }
\n |
. { returnyytext[0]; }
%%

B.YACC SPECIFICATION

%{
doublememvar;
%}
%union
{
doubledval;
}
%token <dval> NUMBER;
%token <dval> MEM;
%token LOG SINE LOG COS TAN
%left ’-‘’+’
%left ‘*’’/’
%right ‘^’
%left LOG SINE LOG COS TAN
%nonassoc UMINUS
%type <dval>expression
%%
start:statement’\n’
| start statement’\n’
;
statement: MEM ‘=’ expression { memvar=$3; }
| expression { printf(“Answer=%g\n”,$1); }
;
expression: expression ‘+’ expression { $$=$1 + $3; }
|expression ‘-‘ expression { $$ = $1 - $3; }
|expression ‘*’ expression { $$ = $1 * $3; }
|expression ‘/’ expression
{
if( $3 == 0)
yyerror(“Divide by zero”);
else
$$ = $1 / $3;
}
|expression ‘^’ expression { $$=pow($1,$3); }
expression:’-‘ expression %prec UMINUS ( $$=-$2; }
|’(‘expression’)’ { $$=$2; }
|LOG expression { $$=log($2)/log(10); }
|nLOG expression { $$=log($2); }
|SINE expression { $$=sin($2*3.141592654/180; }
|COS expression { $$=cos($2*3.141592654/180); }
|TAN expression { $$=tan($2=tan($2*3.141592654/180); }
|NUMBER { $$=$1; }
|MEM { $$=memvar; }
;
%%
main()
{
printf(“\n Enter expression:”);
yyparse();
}
intyyerror(char *error)
{
fprintf(“%s\n”,error);
}
6.PROGRAM :
Cal.l
%{
#include<stdio.h>
#include<math.h>
#include"y.tab.h"
%}
%%

([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval=atof(yytext);
return NUMBER;}
MEM {return MEM;}
[\t];
\$ {return 0;}
\n {return yytext[0];}
. {returnyytext[0];}
%%
Cal.y
%{
#include<stdio.h>
#include<math.h>
doublememvar;
%}
%union
{
doubledval;
}
%token<dval> NUMBER
%token<dval> MEM
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
return 0;
}
7. PROGRAM:

#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
void small();
void dove(int );
int p[5]={0,1,2,3,4},c=1,i,k,l,m,pi;
char sw[5]={'=','-','+','/','*'},j[20],a[5],b[5],ch[2];
void main()
{
clrscr();
printf("Enter the expression:");
scanf("%s",j);
printf("\n\n\tThe Intermediate code is:\n");
small();
}
void dove(inti)
{
a[0]='\0';b[0]='\0';

I f(!isdigit(j[i+2]) && !isdigit(j[i-2]))


{
a[0]=j[i-1];
b[0]=j[i+1];
}
if(isdigit(j[i+2]))
{
a[0]=j[i-1];
b[0]='t';
b[1]=j[i+2];
}
if(isdigit(j[i-2]))
{ b[0]=j[i+1];
a[0]='t';
a[1]=j[i-2];
b[1]='\0'; }
if(isdigit(j[i+2]) &&isdigit(j[i-2]))
{ a[0]='t';
b[0]='t';
a[1]=j[i-2];
b[1]=j[i+2];
itoa(c,ch,10);
j[i+2]=j[i-2]=ch[0]; }
if(j[i]=='*')
printf("\tt%d=%s*%s\n",c,a,b);
if(j[i]=='/')
printf("\tt%d=%s/%s\n",c,a,b);
if(j[i]=='+')
printf("\tt%d=%s+%s\n",c,a,b);
if(j[i]=='-')
printf("\tt%d=%s-%s\n",c,a,b);
if(j[i]=='=')
printf("\t%c=t%d",j[i-1],--c);
itoa(c,ch,10);
j[i]=ch[0];
c++;
small();
}

void small()
{ pi=0;l=0;
for(i=0;i<strlen(j);i++)
{ for(m=0;m<5;m++)
if(j[i]==sw[m])
if(pi<=p[m])
{
pi=p[m];
l=1;
k=i;
} }
if(l==1)
dove(k);
else
{
getch();
exit (0);
}}
8. PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void main()
{
char code[7][10]={"sta","mul","div","add","sub","mov"};
charopr[7]={'=','*','/','+','-','_'};
char *a,*a1,*b;
intvar=0,i,j,len,k=0,reg,reg1;
FILE *fp,*fp1;
clrscr();
fp=fopen("codein.txt","r");
fp1=fopen("codeout.txt","w");
fprintf(fp1,"\n\n\t\tCODE GENERATION");
while(!feof(fp))
{
char found=0,first=0,second=0;
var++;
fscanf(fp,"%s",a1);
strcpy(a,a1);
len=strlen(a);
fprintf(fp1,"\n\n\tEXPRESSION : %s\n",a);
for(i=0;i<len;i++)
{
if(isalpha(a[i]) || isdigit(a[i]))
{
if(a[i+1] != '=' && !found)
{
if(!first)
{
reg=k;
fprintf(fp1,"\nmov id%d,r%d",var,k);
found=1;
first=1;
}
if(!found && first)
{
fprintf(fp1,"\nmov id%d,r%d",var,k);
reg=k;
found=1;
}
k++;
}
}
if(!isalpha(a[i]))
{
if(found && first)
{
found=0;
for(j=0;j<7;j++)
{
if(a[i] == opr[j])
{
if(!second)
{
fprintf(fp1,"\n%s id%d,r%d",code[j],var+1,reg);
second=1;
i++;
var++;
break;
}
if(second)
{
fprintf(fp1,"\nmov id%d,r%d",var+1,++reg);
fprintf(fp1,"\n%s r%d,r%d",code[j],reg1,reg);
reg1=reg;
var++;
break;
}
}
}
found=1;
reg1=reg;
}
}
}
fprintf(fp1,"\nsta r%d,id%d",reg1,var+1);
var++;
}
getch();
}
9. PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{char table[20][20][20],ter[20],stack[20],ip[20],st1[20],pro[20][20],num;
int i,j,t,k,top=0,st,col,row,pop,np,no,len;
clrscr();
for(i=0;i<20;i++){
ter[i]=NULL;
stack[i]=NULL;
ip[i]=NULL;
st1[i]=NULL;
for(j=0;j<20;j++){
pro[i][j]=NULL;
for(k=0;k<20;k++)
{ table[i][j][k]=NULL; } } }
printf("Enter the no of productions:");
scanf("%d",&np);
printf("Enter the productions:");
for(i=0;i<np;i++)
{ scanf("%s",pro[i]); }
printf("Enter the no.of states:");
scanf("%d",&st);
printf("Enter the states:");
scanf("%s",st1);
printf("Enter the no of terminals:");
scanf("%d",&t);
printf("Enter the terminals:");
scanf("%s",ter);
for(i=0;i<st;i++)
{ for(j=0;j<t;j++)
{ printf("\nEnter the value for %c %c:",st1[i],ter[j]);
scanf("%s",table[i][j]); } }
printf("\nSLR TABLE:\n");
for(i=0;i<t;i++)
{ printf("\t%c",ter[i]); }
for(i=0;i<st;i++)
{ printf("\n\n%c",st1[i]);
for(j=0;j<t;j++)
{ printf("\t%s",table[i][j]); } }
stack[top]='a';
printf("\nEnter the input string:");
scanf("%s",ip);
i=0;
printf("\n\nSTACK\t\tINPUT STRING\t\tACTION\n");
printf("\n%s\t\t%s\t\t",stack,ip);
while(i<=strlen(ip) )
{ for(j=0;j<st;j++)
{ if(stack[top]==st1[j])
col=j;
}
for(j=0;j<t;j++)
{ if(ip[i]==ter[j])
{ row=j; } }
if((stack[top]=='b')&&(ip[i]=='$')){printf("\nString accepted");break;}
else if(table[col][row][0]=='s')
{ top++;
stack[top]=ter[row];
top++;
stack[top]=table[col][row][1];
i++;
printf("Shift %c %d\n",ter[row],table[col][row][1]);
}
else if(table[col][row][0]=='r')
{ no=(int)table[col][row][1];
no=no-48;
len=strlen(pro[no]);
len=len-3;
pop=2*len;
printf("POP %d",pop);
for(j=0;j<pop;j++)
{ top=top-1; }
top++;
stack[top]=pro[no][0];
k=top;
k=k-1;
printf(" Push [%c,",pro[no][0]);
for(j=0;j<st;j++)
{ if(stack[k]==st1[j])
{ col=j; } }
k++;
for(j=0;j<t;j++)
{ if(stack[k]==ter[j])
{ row=j; } }
top++;
stack[top]=table[col][row][0];
printf("%c]\n",table[col][row][0]);
}
else{printf("\nError\nThe string not accepted.");break;
}
printf("\n");
for(j=0;j<=top;j++)
{
printf("%c",stack[j]);
}
printf("\t\t");
for(j=i;j<strlen(ip);j++)
{
printf("%c",ip[j]);
}
printf("\t\t");
}
getch();
}
10. PROGRAM:

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{ charstr[25],stk[25];
inti,j,t=0,l,r;
clrscr();
printf("Enter the String : ");
scanf("%s",&str);
l=strlen(str);
str[l]='$';
stk[t]='$';
printf("Stack\t\tString\t\tAction\n-----------------------------------\n ");
for(i=0;i<l;i++)
{ if(str[i]=='i')
{ t++;
stk[t]=str[i];
stk[t+1]=str[i+1];
for(j=0;j<=t+1;j++)
printf("%c",stk[j]);
printf("\t\t ");
for(j=i+2;j<=l;j++)
printf("%c",str[j]);
printf("\t\tShift");
printf("\n ");
stk[t]='E'; i++;
}else
{ t++; stk[t]=str[i]; }
for(j=0;j<=t;j++)
printf("%c",stk[j]);
printf("\t\t ");
for(j=i+1;j<=l;j++)
printf("%c",str[j]);
if(stk[t]=='+' || stk[t]=='*')
printf("\t\tShift");
else
printf("\t\tReduce");
printf("\n ");
}while(t>1)
{ if(stk[t]=='E' && (stk[t-1]=='+' || stk[t-1]=='*') &&stk[t-2]=='E')
{ t-=2;
for(j=0;j<=t;j++)
printf("%c",stk[j]);
printf("\t\t");
printf(" %c",str[l]);
printf("\t\tReduce\n "); }
else t-=2; }
if(t==1 &&stk[t]!='+' &&stk[t]!='*')
printf("\nThe Given String is Valid\n\n");
else printf("\nThe Given String is Invalid\n\n");
getch();
}

You might also like