0% found this document useful (0 votes)
26 views42 pages

Compiler Design Lab Manual

COMPILER DESIGN

Uploaded by

Aamina Khatoon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views42 pages

Compiler Design Lab Manual

COMPILER DESIGN

Uploaded by

Aamina Khatoon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

JAHANGIRABAD INSTITUTE OF TECHNOLOGY

Department of Computer science and engineering

Dr. A.P.J. Abdul Kalam Technical University, Lucknow

SubjectCode: (KCS-552)

Subject Name: COMPILER DESIGN


LIST OF EXPERIMENTS

1. Design and implement a lexical analyzer for given language using C and the lexical
analyzer should ignore redundant
spaces, tabs and new lines.
2. Implementation of Lexical Analyzer using Lex Tool
3. Generate YACC specification for a few syntactic categories.
a) Program to recognize a valid arithmetic expression that uses operator +,–,* and
/.
b) Program to recognize a valid variable which starts with a letter followed by any number of
letters or digits.
c) Implementation of Calculator using LEX and YACC
d) Convert the BNF rules into YACC form and write code to generate abstract syntax tree
4. Write program to find ε–closure of all states of any given NFA with ε transition.
5. Write program to convert NFA with ε transition to NFA without ε transition.
6. Write program to convert NFA to DFA
7. Write program to minimize any given DFA.
8. Develop an operator precedence parser for a given language.
9. Write program to find Simulate First and Follow of any given grammar.
10. Construct a recursive scent parser for an expression.
11. Construct a Shift Reduce Parser for a given language.
12. Write a program to perform loop unrolling.
13. Write a program to perform constant propagation.
14. Implement Intermediate code generation for simple expressions.
15. Implement the back end of the compiler which takes the three address code and produces
the 8086 assembly language
Instructions that can be assembled and run using an 8086 assembler. The target assembly
instructions can be simple move, add, sub, jump etc
.
List of Experiments

Serial Bloom’s
Experiment CO
No. Level
Write a c program to recognize string Under „a*‟,‟a*b+‟,‟abb‟.
1 CO1 K3
Write a lex program to cheak weather input string is verb or not.(list
of verb Are given)
2 CO2 K3
Write a program to check input identifier is valid or not.
3 CO2 K3
Write a lex program to count number of character and number of
lines.
4 CO2 K3
Write a yacc program to implement grammer for a simple calculator.
5 CO3 K3
Write a yacc program to implement if- then-else statement.
6 CO3 K3
Write a yacc program to implement for loop.

7 CO3 K3
Write a c program to implement recursive ecent parser for
grammar:- e->e+t|t T->t*f|f
8 F->id CO3 K3
Write a program to design lalr bottom up parser.
9 CO3 K3
10 Write a program to convert nfa into dfa. CO3 K3
11 Write a program fo implementation of Shift reduce CO3 K3
parsing algorithm
Write a c program to generate machine code from
12 abstract syntax tree generated by the parser. the CO5 K3
instruction set specified may be considered as the
Target code.
PROGRAM NO:-1

OBJECT:write a c program to recognize string under „a*‟,‟a*b+‟,‟abb‟.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>voi
d main()
{
char s[20],c;
intstate=0,i=0;
printf("\nenterastring:");
scanf("\n%s",s);
while(s[i]!='\0')
{
switch(state)
{
case0:
c=s[i++];
if(c=='a')
state =1;
elseif(c=='b')
state=2;
else
state=6;
break;
case1:
c=s[i++];
if(c=='a')
state=3;
elseif(c=='b')
state=4;
else
state=6;
break;
case2:
c=s[i++];
if(c=='a')
state=6;
else if(c=='b')
state=2;
else
state=6;
break;
case3:
c=s[i++];
if(c=='a')
state=3;
elseif(c=='b')
state=2;
else
state=6;
break;
case4:
c=s[i++];
if(c=='a')
state=6;
elseif(c=='b')
state=5;
else
state=6;
break;
case5:
c=s[i++];
if(c=='a')
state=6;
elseif(c=='b')
state=2;
else
state=6;
break;
case6:
printf("%sisnotrecognised.",s);
exit(0);
}
}
if((state==1)||(state==3)||(state==0)) printf("\
n%s is accepted under rule'a*'",s); else
if((state==2)||(state==4))
printf("\n%sis accepted under rule'a*b+'",s);
else if(state==5)

printf("\n%s is accepted under rule' abb'",s);

}
PROGRAM N0: 02
OBJECT:write a lex program to cheak weather input string is verb or not.(list of
verb are given)
%%
[\t]+
is |
am|
are|
was|
were{printf(“%s:isaverb”,yytext);}
[a-zA-Z]+{printf(“%s:isnotaverb,yytext);}
%%
main()
{
yylex();
}

OUTPUT:$./a.out
are
are:isa verb
PROGRAM N0 : 03

OBJECT: write a program to check input identifier is valid or not.

%{
#include<stdio.h>
%}
digit[0-9]
letter[a-zA-Z]
%%
{letter}({letter}|{digit})*printf("id:%s\n",yytext);
\nprintf("newline\n");
%%
main()
{
yylex();

OUTPUT:>./a.out
abhishek
id:abhishek

newline

555

555newline
PROGRAM NO :04

Object: write a lex program to count number of character and number of lines.

%{
#include<stdio.h>
intnum_lines=0,num_chars=0;
%}
%%
\n{++num_lines;++num_chars;}
.{++num_chars;}
%%
intmain()
{
yylex();
printf("There are%dlinesand%dcharacters.\n",num_lines,num_chars); return 0;
}

OUTPUT:>./a.out
Compiler Design.
Thereare1 lines and17 characters.
PROGRAM NO:05

Object:write a yacc program to implement grammer for a simple calculator.

%{
#defineYYSTYPEdouble
#include "cal.tab.h"
#include <stdlib.h>
%}
white [ \t]+
digit [0-9]
integer{digit}+
exponent[eE][+-]?{integer}
real{integer}("."{integer})?{exponent}?

%%

{white}{}
{real}{yylval=atof(yytext);
return NUMBER;
}

"+" return PLUS;


"-"returnMINUS;
"*"return TIMES;
"/" return DIVIDE;
"^"returnPOWER;
"(" return LEFT;
")" return RIGHT;
"\n" return END;

%{
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#defineYYSTYPEdouble
%}
%tokenNUMBER
%tokenPLUSMINUSTIMESDIVIDEPOWER
%tokenLEFTRIGHT
%tokenEND

%leftPLUS MINUS
%leftTIMES DIVIDE
%leftNEG
%rightPOWER

%startInput
%%

Input:

|InputLine;

Line:
END
|ExpressionEND{printf("Result:%f\n",$1);}
;

Expression:
NUMBER{$$=$1;}
|ExpressionPLUSExpression{$$=$1+$3;}
|ExpressionMINUSExpression{$$=$1-$3;}
|ExpressionTIMESExpression{$$=$1*$3;}
|ExpressionDIVIDEExpression{$$=$1/$3;}
|MINUSExpression%precNEG{$$=-$2;}
|ExpressionPOWERExpression{$$=pow($1,$3);}
|LEFTExpressionRIGHT{$$=$2;}
;

%%

intyyerror(char*s)
{ printf("%s\n", s);
}

int main()
{ if(yyparse(
))
fprintf(stderr,"Successfulparsing.\n");
else
fprintf(stderr,"errorfound.\n");
}

OUTPUT:>./a.out
12*34-67+23

Result:364.000000
PROGRAM NO:06
Object: write a yacc program to implement if-then-else statement.

CREATEIFTE.L FILE-
alpha[A-Za-z]
digit [0-9]
%%
[\t\n]
if return IF;
then return THEN;
else returnELSE;
{digit}+({alpha}|{digit})*returnID;
"<="return LE;
">="return GE;
"=="return EQ; "!
=" return NE;
"||" return OR;
"&&"returnAND;
. returnyytext[0];
%%
CREATEIFTE.YFILE-
%{
#include<stdio.h>
#include<stdlib.h>
%}
%tokenIDNUMIFTHENLEGEEQNEORANDELSE
%right'='
%leftANDOR
%left'<''>'LEGEEQNE
%left'+''-'
%left'*''/'
%rightUMINUS
%left'|'
%%

S:ST{printf("InputAccepted.\n");exit(0);};
ST:IF'('E2 ')'THENST1';'ELSEST1 ';'
|IF'('E2')'THEN ST1';'
;
ST1 :ST
|E
;
E: ID'='E
|E'+'E
|E'-'E
|E'*'E
|E'/'E
|E'<'E
|E'>'E
|ELE E
|EGEE
|EEQE
|ENEE
|EORE
|EANDE
|ID|NUM;
E2: E'<'E
|E'>'E
|ELEE
|EGEE
|EEQE
|ENEE
|EOR E
|EANDE
|ID
|NUM
;
%%
#include"lex.yy.c"
main()
{
printf("EnterTheExpression:");
yyparse();
}
OUTPUT:

> ./a.out

EnterExpression:if(i==0)thenx=2;elsey=2; Input
Accepted.

> ./a.out
EnterExpression:if(i==0)thenx=2elsey=2;
Syntax error.
PROGRAMNO:07

Object: write a yacc program to implement for loop.

CREATEFORLP.LFILE-

alpha[A-Za-z]
digit [0-9]
%%
[\t\n]
forreturnFOR;
{digit}+returnNUM;
{alpha}({alpha}|{digit})*returnID;
"<=" return LE;
">="returnGE;
"=="returnEQ;
"!=" return NE;
"||" return OR;
"&&"returnAND;
.return yytext[0];

%%

CREATEFORLP.YFILE-

%{

#include<stdio.h>

#include<stdlib.h>

%}

%tokenIDNUMFORLEGEEQNEOR AND

%right'=' UMINUS

%leftANDOR'<''>'LEGEEQNE'+''-''*''/''!'

%%
S:ST{printf("InputAccepted.\n");exit(0);};

ST:FOR'('E';'E2';'E')'DEF; DEF:'{'

BODY '}'

|E';'

|ST

BODY:BODYBODY

|E';'

|ST

E:ID'='E

|E'+'E

|E'-'E

|E'*'E

|E'/'E

|E'<'E

|E'>'E

|ELE E

|EGEE

|EEQE

|ENEE

|EORE

|EANDE
|E'+''+'

|E'-''-'

|ID

|NUM

E2:E'<'E

|E'>'E

|ELE E

|EGEE

|EEQE

|ENEE

|EORE

|EANDE

|ID

|NUM

%%

#include"lex.yy.c"

main()

printf("EnterExpression:");

yyparse();

OUTPUT:

> ./a.out
EnterExpression:for(i=10;i<20;i++)
{
x=x*i;
}
InputAccepted.
> ./a.out
EnterExpression:for(i=10;i<20,i++)
syntax error

abhishek@abhiskek-HP-Notebook:~$./a.out
Enter Expression: for(i=10;i<20;i++)
{
for(j=2;j<5;j++)
{
x=i+j;
}

}
InputAccepted.
PROGRAM NO:08

Object:write a c program to implement recursive decent parser for grammar:-e-


>e+t|t
T->t*f|f
F->id

#include<stdio.h>
#include<string.h>
#include<ctype.h>i
nt i,err;
charinp[10];
void E();
voidE1();
voidT();
voidT1();
void F();
voidmain()
{
i=0,err=0;printf("Enter
String:");
scanf("%s",inp);
E();
if(strlen(inp)==i&&err==0)
printf("\t\t*****STRINGACCEPTED!!!!!!!!!*****\n\n");
else
printf("\t\t*****STRINGNOTACCEPTED!!!!*****\n\n");
}
voidE()
{
T();
E1();
}
voidE1()
{
if(inp[i]=='+')
{
i++;
T();
E1();
}
}
voidT()
{
F();
T1();
}
voidT1()
{
if(inp[i]=='*')
{
i++;
F();
T1();
}
}
voidF()
{
if(isalnum(inp[i]))
i++;
else if(inp[i]=='(')
{
i++;
E();
if(inp[i]==')')
i++;
else err=1;
}
else

err=1;
}

OUTPUT:>./a.out
EnterExpression:5+3*7
*****STRINGACCEPTED!!!!!!!!!*****
> ./a.out
EnterExpression:5*(6+8)
*****STRINGACCEPTED!!!!!!!!!*****
> ./a.out
EnterExpression:5*(6+*)
*****STRINGNOTACCEPTED!!!!*****
>:~$./a.out
EnterExpression:5*(6+8(
*****STRINGNOTACCEPTED!!!!*****
PROGRAM NO:9

Object: Write a program to Design LALR Bottom up Parser.

/*LALRPARSER
E->E+T
E->T
T->T*F
T->F
F->(E)
F->i
*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
voidpush(char*,int*,char);
char stacktop(char *);
voidisproduct(char,char);
int ister(char);

int isnter(char);
intisstate(char);
void error();
voidisreduce(char,char);
char pop(char *,int *);
voidprintt(char*,int*,char[],int);
void rep(char [],int);
structaction
{
charrow[6][5];
};

conststructactionA[12]={
{"sf","emp","emp","se","emp","emp"},
{"emp","sg","emp","emp","emp","acc"},
{"emp","rc","sh","emp","rc","rc"},
{"emp","re","re","emp","re","re"},
{"sf","emp","emp","se","emp","emp"},
{"emp","rg","rg","emp","rg","rg"},
{"sf","emp","emp","se","emp","emp"},
{"sf","emp","emp","se","emp","emp"},
{"emp","sg","emp","emp","sl","emp"},
{"emp","rb","sh","emp","rb","rb"},
{"emp","rb","rd","emp","rd","rd"},
{"emp","rf","rf","emp","rf","rf"}
};
structgotol
{
charr[3][4];
};
conststructgotolG[12]={
{"b","c","d"},
{"emp","emp","emp"},
{"emp","emp","emp"},
{"emp","emp","emp"},
{"i","c","d"},
{"emp","emp","emp"},
{"emp","j","d"},
{"emp","emp","k"},
{"emp","emp","emp"},
{"emp","emp","emp"},

};
char ter[6]={'i','+','*',')','(','$'};
char nter[3]={'E','T','F'};
charstates[12]={'a','b','c','d','e','f','g','h','m','j','k','l'};
char stack[100];
int top=-1;
char temp[10];
structgrammar
{

char left;
charright[5];
};

conststructgrammarrl[6]={
{'E',"e+T"},
{'E',"T"},
{'T',"T*F"},
{'T',"F"},
{'F',"(E)"},
{'F',"i"},
};
voidmain()
{
charinp[80],x,p,dl[80],y,bl='a';
int i=0,j,k,l,n,m,c,len;
clrscr();
printf("Entertheinput:");
scanf("%s",inp);
len=strlen(inp);
inp[len]='$';
inp[len+1]='\0';
push(stack,&top,bl); printf("\
nstack\t\t\tinput");
printt(stack,&top,inp,i);
do
{
x=inp[i];p=stacktop(stack);
isproduct(x,p);
if(strcmp(temp,"emp")==0)
error();

if(strcmp(temp,"acc")==0)
break;
else
{
if(temp[0]=='s')
{
push(stack,&top,inp[i]);
push(stack,&top,temp[1]);
i++;
27
}
else
{
if(temp[0]=='r')
{
j=isstate(temp[1]);
strcpy(temp,rl[j-2].right);
dl[0]=rl[j-2].left;
dl[1]='\0';
n=strlen(temp);
for(k=0;k<2*n;k++)
pop(stack,&top);
for(m=0;dl[m]!='\0';m++)
push(stack,&top,dl[m]);
l=top;
y=stack[l-1];
isreduce(y,dl[0]);
for(m=0;temp[m]!='\0';m++)
push(stack,&top,temp[m]);
}
}

}
printt(stack,&top,inp,i);
}while(inp[i]!='\0');
if(strcmp(temp,"acc")==0)
printf("\naccepttheinput");
else
printf("\ndonotaccepttheinput");
getch();
}
voidpush(char*s,int*sp,charitem)

{
if(*sp==100)
printf("stackisfull");
else
{
*sp=*sp+1;

s[*sp]=item;
}
}
charstacktop(char *s)
{
char i;
i=s[top];
return i;
}
voidisproduct(charx,charp)
{
int k,l;
k=ister(x);
l=isstate(p);
strcpy(temp,A[l-1].row[k-1]);
}
intister(charx)
{
int i;
for(i=0;i<6;i++)
if(x==ter[i])
return i+1;
return 0;
}
intisnter(charx)
{
int i;
for(i=0;i<3;i++)
if(x==nter[i])
return i+1;
return 0;
}
intisstate(charp)
{

int i;
for(i=0;i<12;i++)
if(p==states[i])

returni+1;
return 0;
}
voiderror()
{
printf("errorintheinput");
exit(0);
}
voidisreduce(charx,charp)
{
int k,l;
k=isstate(x);
l=isnter(p);
strcpy(temp,G[k-1].r[l-1]);
}
charpop(char*s,int*sp)
{
char item;
if(*sp==-1)
printf("stackisempty");
else
{
item=s[*sp];
*sp=*sp-1;
}
returnitem;
}
voidprintt(char*t,int*p,charinp[],int i)
{
int r; printf("\
n");
for(r=0;r<=*p;r++)
rep(t,r); printf("\t\t\
t");
for(r=i;inp[r]!='\0';r++)

printf("%c",inp[r]);
}
voidrep(chart[],intr)
{
char c;
c=t[r];
switch(c)
{
case'a':printf("0");
break;
case'b':printf("1");
break;
case'c':printf("2");
break;
case'd':printf("3");
break;
case'e':printf("4");
break;
case'f':printf("5");
break;
case'g':printf("6");
break;
case'h':printf("7");
break;
case'm':printf("8");
break;
case'j':printf("9");
break;
case'k':printf("10");
break;
case'l':printf("11");
break;
default:printf("%c",t[r]);
break;
}}
PROGRAM NO:10

Object: Write a program to convert NFA to DFA

#include<stdio.h>

intFa[10][10][10],states[2][10],row=0,col=0,sr=0,sc=0,th=0,
in,stat,new_state[10][10],max_inp=-1,no_stat;
FILE*fp;

intsearch(intsearch_var)
{

int i;
for(i=0;i<no_stat;i++)
if(search_var==states[1][i])
return 1;
return0;
}

intsort(int*arr,intcount)
{
int temp,i,j;
for(i=0;i<count-1;i++)
{
for(j=i+1;j<count;j++)
{
if(arr[i]>=arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
return0;
}

intcheckcon(int*arr,int*count)//fordoingthis{4,1}={1,2,1}=={1,2}
{
int i,temp,j,k,c,t,m;
for(i=0;i<*count;i++)
{
if(arr[i]>row)
{
temp=arr[i];
c=0;
t=0;
while(new_state[arr[i]][t]!=-1)
{
t++; c+
+;
}
//rightshiftfromithpostion(c-2)thtime
for(k=0;k<=c-2;k++)
{
for(j=9;j>=i+1+k;j--)
{
arr[j]=arr[j-1];
}
}

t=0;
for(j=i;j<c;j++)
{
arr[j]=new_state[temp][t]; t+
+;
}
}
}
c=0;
for(i=0;arr[i]!=-1;i++) c+
+;
*count=c;
return0;
}

intremove_duplicate(int*arr,int*count)
{
int i,j=0;
for(i=1;i<*count;i++)
{
if(arr[i]!=arr[j])
{
j++;
arr[j]=arr[i];
}
}
*count=j+1;
return0;
}

intcheck(inti,intj,intc,int*name)///forcheckingisthisanewstate?
{
int t,l,f;
for(l=0;l<=stat;l++)
{
t=0;f=0;
while(Fa[i][j][t]!=-1)
{
if(Fa[i][j][t]==new_state[l][t])
t++;
else
{ f=
1;
break;
}
}
if((t==c)&&!f)
{
*name=l;
return1;
}
}
return0;
}

inttrans(inti,intj,intt,intc,int*count,int*arr)//transitiono/pforparticulari/pon states
{
int k=0,co,temp;
*count=0;
for(k=0;k<c;k++)
{
temp=Fa[i][j][k];
co=0;
while(Fa[temp][t][co]!=-1)
{
arr[*count]=Fa[temp][t][co++]; (*count)+
+;
}
}
return0;
}

intnfa2dfa(intstart,int end)
{
intj,t,c,i,k,count,arr[10],name,l;
for(i=start;i<=end;i++)
{
for(j=0;j<=max_inp;j++)
{
c=0;t=0;
while(Fa[i][j][t]>=0)
{ t+
+; c+
+;
}
if(c>1)
{
if(check(i,j,c,&name)==0)
{
for(k=0;k<c;k++)
{
new_state[stat][k]=Fa[i][j][k];
for(l=0;states[1][l]!=-1;l++)
if(new_state[stat][k]==states[1][l]&&!search(stat)) states[1][no_stat+
+]=stat;
}

for(t=0;t<=max_inp;t++)
{
count=0;
for(k=0;k<10;k++)
arr[k]=-1;
trans(i,j,t,c,&count,arr);

checkcon(arr,&count);

sort(arr,count);
remove_duplicate(arr,&count);

for(k=0;k<count;k++)
Fa[stat][t][k]=arr[k];
}
Fa[i][j][0]=stat++;
for(t=1;t<c;t++)
Fa[i][j][t]=-1;
}
else
{
Fa[i][j][0]=name;
for(t=1;t<c;t++)
Fa[i][j][t]=-1;
}
}
}

}
return0;
}
intmain()
{

int i,j,k,flag=0,start,end;
char c,ch;
fp=fopen("Nfa_ip.txt","r+");

for(i=0;i<2;i++)
for(j=0;j<10;j++)
states[i][j]=-1;
for(i=0;i<10;i++)
for(j=0;j<10;j++)
new_state[i][j]=-1;

for(i=0;i<10;i++)
for(j=0;j<10;j++)
for(k=0;k<10;k++)
Fa[i][j][k]=-1;

while(fscanf(fp,"%d",&in)!=EOF)
{
fscanf(fp,"%c",&c);

if(flag)
{
states[sr][sc++]=in;
if(c=='\n')
{
sr++;
sc=0;
}
}
else if(c=='#')
{
flag=1; Fa[row][col]
[th]=in;

}
else if(!flag)
{
Fa[row][col][th]=in;
if(c==',')
{
th++;
}
else if(c=='\n')
{
if(max_inp<col)
max_inp=col;
col=0;
row++;
th=0;
}
else if(c!=',')
{
col++;
th=0;
}
}

}
no_stat=0;
i=0;
while(states[1][i++]!=-1)
no_stat++;stat=row+1;
start=0;end=row;
while(1)
{
nfa2dfa(start,end);
start=end+1;
end=row;
if(start>end)
break;
}

printf("\n\nDFAIS:\n\n\n");
for(i=0;i<=max_inp;i++)
printf("\t%d",i);
printf("\n");
printf(" \n");

for(i=0;i<stat;i++)
{
printf("%d->|",i);
for(j=0;j<=max_inp;j++)
{
printf("%2d ",Fa[i][j][0]);
}
printf("\n");
}
printf("\n\n");
printf("TotalNumberOfStateIs:%d\n\n",stat);
printf("Final States Are : "); for(i=0;states[1][i]!
=-1;i++)
printf("%d",states[1][i]);

printf("\n\n");
getch();
return0;
}
PROGRAMNO:11

OBJECT: To write a C program to implement the shift-reduce parsing algorithm

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
charip_sym[15],stack[15];
int ip_ptr=0,st_ptr=0,len,i;
char temp[2],temp2[2];
char act[15];
voidcheck();
void main()
{
clrscr();
printf("\n\n\tShiftReduceParser\n");
printf("\n\t***** ****** ******");
printf("\n Grammar\n\n");
printf("E->E+E\nE->E/E\n");
printf("E->E*E\nE->a/b");
printf("\nEntertheInputSymbol:\t");
gets(ip_sym);
printf("\n\n\t Stack Implementation Table");
printf("\nStack\t\tInputSymbol\t\tAction");
printf("\n $\t\t %s$\t\t\t --",ip_sym);
strcpy(act,"shift");
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
strcat(act,temp);
len=strlen(ip_sym);
for(i=0;i<=len-1;i++)
{
stack[st_ptr]=ip_sym[ip_ptr];
stack[st_ptr+1]='\0';
ip_sym[ip_ptr]='';
ip_ptr++; printf("\n$%s\t\t%s$\t\t\t
%s",stack,ip_sym,act); strcpy(act,"shift");
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
strcat(act,temp);check();
st_ptr++;
}
st_ptr++;
check();
getch();
}

voidcheck()
{
int flag=0;
temp2[0]=stack[st_ptr];
temp[1]='\0';
if((!strcmpi(temp2,"a"))||(!strcmpi(temp2,"b")))
{
stack[st_ptr]='E'; if(!
strcmpi(temp2,"a"))
printf("\n$%s\t\t%s$\t\t\tE->a",stack,ip_sym);
else
printf("\n$%s\t\t%s$\t\t\tE->a",stack,ip_sym);
flag=1;
}
if((!strcmpi(temp2,"+"))||(strcmpi(temp2,"*"))||(!strcmpi(temp2,"/")))
{
flag=1;
}
if((!strcmpi(stack,"E+E"))||(!strcmpi(stack,"E/E"))||(!strcmpi(stack,"E*E")))
{
strcpy(stack,"E");
st_ptr=0;
if(!strcmpi(stack,"E+E")) printf("\n$%s\t\t%s$\t\t\
tE->E+E",stack,ip_sym); else
if(!strcmpi(stack,"E/E")) printf("\n$%s\t\t\t%s$\t\
tE->E/E",stack,ip_sym); else
printf("\n$%s\t\t%s$\t\t\tE->E*E",stack,ip_sym);
flag=1;
}
if(!strcmpi(stack,"E")&&ip_ptr==len)
{
printf("\n$%s\t\t%s$\t\t\tAccept",ip_sym);
getch();
exit(0);
}
if(flag==0)
{
printf("\n%s\t\t\t%s\t\t Reject",stack,ip_sym);
}
return;
}

SampleInput&Output:
ShiftReduceParser
****************
Grammar
E->E+E
E->E/E
E->E*E
E->a/b
Entertheinputsymbol:if(a*b)
Stack Implementation Table
Stack InputSymbol Action
$ if(a*b)$ --
$i f(a*b)$ (a*b) shift i
$if $ shiftf
$if( a*b)$ shift(
$if(a *b)$ shifta
$if(E *b)$ E->a
$if(E* b)$ shift*
if(E* b) reject
PROGRAMNO:12

Object: Write a C program to generate machine code from abstract syntax tree
generatedbytheparser.Theinstructionsetspecifiedmaybeconsideredasthe target
code.

Consider the following mini language ,a simple procedural high –level language,
only operating on integer data, with a syntax looking vaguely like a simple C
crossed with pascal. The syntax of the language is defined by the following
grammar.

<program>::=<block>
<block>::={<variabledefinition><slist>}
|{<slist>}
<variabledefinition>::=int<vardeflist>
<vardec>::=<identifier>|<identifier>[<constant>]
<slist>::=<statement>|<statement>;<slist>
<statement>::=<assignment>|<ifstament>|<whilestatement>
|<block>|<printstament>|<empty>
<assignment>::=<identifier>=<expression>
|<identifier>[<expression>]=<expression>
<if statement>::=if<bexpression>then<slist>else<slist>endif
|if<bexpression>then<slisi>endif
<whilestatement>::=while<bexpreession>do<slisi>enddo
<printstatement>:;=print(<expression>)
<expression>::=<expression>::=<expression><addingop><term>|<term>|<addingo
p>
<term>
<bexprssion>::=<expression><relop><expression>
<relop>::=<|<=|==|>=|>|!=
<addingop>::=+|-
<term>::=<term><multop><factor>|<factor>
<Multop>::=*|/
<factor>::=<constant>|<identifier>|<identifier>[<expression>]
|(<expression>)
<constant>::=<digit>|<digit><constant>
<identifier>::=<identifier><letterordigit>|<letter>
<letterordigit>::=<letter>|<digit>
<letter>:;=a|b|c|d|e|f|g|h|I|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z
<digit>::=0|1|2|3|4|5|^|7|8|9
<empty>::=hastheobviousmeaning

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int label[20];
int no=0;
intmain()
{
FILE*fp1,*fp2;
charfname[10],op[10],ch;
charoperand1[8],operand2[8],result[8];
int i=0,j=0;
printf("\nEnterfilenameoftheintermediatecode");
scanf("%s",&fname);
fp1=fopen(fname,"r");
fp2=fopen("target.txt","w");
if(fp1==NULL||fp2==NULL)
{
printf("\nErroropeningthefile");
exit(0);
} w hile(!
feof(fp1))
{
45
fprintf(fp2,"\n");fscanf(fp1,"%s",op); i+
+; if(check_label(i)) fprintf(fp2,"\
nlabel#%d",i); if(strcmp(op,"print")==0)
{
fscanf(fp1,"%s",result);
fprintf(fp2,"\n\tOUT%s",result);
}
if(strcmp(op,"goto")==0)
{
fscanf(fp1,"%s %s",operand1,operand2); fprintf(fp2,"\n\
tJMP%s,label#%s",operand1,operand2); label[no+
+]=atoi(operand2);
}i
f(strcmp(op,"[]=")==0)
{
fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\
n\tSTORE%s[%s],%s",operand1,operand2,result);
}
if(strcmp(op,"uminus")==0)
{fs
canf(fp1,"%s %s",operand1,result);
fprintf(fp2,"\n\tLOAD-%s,R1",operand1);
fprintf(fp2,"\n\t STORE R1,%s",result);
}
switch(op[0])
{
case'*':fscanf(fp1,"%s%s%s",operand1,operand2,result);
fprintf(fp2,"\n \t
LOAD",operand1);
fprintf(fp2,"\n\tLOAD
%s,R1",operand2); fprintf(fp2,"\
n\tMULR1,R0"); fprintf(fp2,"\
n \t STORE R0,%s",result);
break;
case'+':fscanf(fp1,"%s%s%s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n\tLOAD%s,R1",operand2);
fprintf(fp2,"\n \t ADD R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case'-':fscanf(fp1,"%s%s%s",operand1,operand2,result);fprintf(fp2,"\n\tLOAD
%s,R0",operand1);
fprintf(fp2,"\n\tLOAD%s,R1",operand2);fprintf(fp2,"\n\tSUBR1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case'/':fscanf(fp1,"%s%ss",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\
n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t DIV
R1,R0");
fprintf(fp2,"\n\tSTORER0,%s",result);
break;
case'%':fscanf(fp1,"%s%s%s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n\tLOAD%s,R1",operand2); fprintf(fp2,"\n \t
DIV R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '=': fscanf(fp1,"%s %s",operand1,result);
fprintf(fp2,"\n\tSTORE%s%s",operand1,result);
break;
case'>': j++;
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\
n\tJGT%s,label#%s",operand2,result); label[no+
+]=atoi(result);
break;
case'<':fscanf(fp1,"%s%s%s",operand1,operand2,result);
fprintf(fp2,"\n\tLOAD%s,R0",operand1);fprintf(fp2,"\n\t
JLT %s,label#%d",operand2,result); label[no+
+]=atoi(result);
break;
}
}
fclose(fp2); fclose(fp1);
fp2=fopen("target.txt","r");
if(fp2==NULL)
{
printf("Erroropeningthefile\n");
exit(0);
}
do
{
ch=fgetc(fp2);
printf("%c",ch);
}while(ch!=EOF);
fclose(fp1);
return0;
47
}i
ntcheck_label(intk)
{i
nti;
for(i=0;i<no;i++)
{
if(k==label[i])
return 1;
}
return0;
}

You might also like