0% found this document useful (0 votes)
43 views41 pages

Compiler Design Lab Practicles 1

Uploaded by

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

Compiler Design Lab Practicles 1

Uploaded by

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

TABLE OF CONTENTS

Sl.
Name of the Program
No
Design a lexical analyzer for given language and the lexical
1
analyzer should ignore redundant spaces, tabs and new lines

2 Simulate First and Follow of a Grammar.

3 Develop an operator precedence parser for a given language.

4 Construct a recursive descent parser for an expression.

5 Construct a LL(1) parser for an expression

6 Design predictive parser for the given language

7 Implementation of shift reduce parsing algorithm.

8 Design a LALR bottom up parser for the given language.

Implement the lexical analyzer using JLex, flex or lex or other


9
lexical analyzer generating tools

10 Write a program to perform loop unrolling.

Convert the BNF rules into YACC form and write code to generate
11
abstract syntax tree.

12 Write a program for constant propagation.

1
SOLUTIONS FOR PROGRAMS

1) Lexical Analyzer implimentation by using C program

#include<string.h>
#include<conio.h>
#include<ctype.h>
#include<stdio.h>

void main()
{
FILE *f1;
char c,str[10];
int lineno=1,num=0,i=0;
clrscr();
printf("\nEnter the c program\n");
f1=fopen("input.txt","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input.txt","r");
while((c=getc(f1))!=EOF) // TO READ THE GIVEN FILE
{
if(isdigit(c)) // TO RECOGNIZE NUMBERS
{
num=c-48;
c=getc(f1);
while(isdigit(c))
{
num=num*10+(c-48);
c=getc(f1);
}
printf("%d is a number \n",num);
ungetc(c,f1);
}
else if(isalpha(c)) // TO RECOGNIZE KEYWORDS AND IDENTIFIERS
{
str[i++]=c;
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
str[i++]=c;
c=getc(f1);
}
str[i++]='\0';
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||
strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||
strcmp("double",str)==0||strcmp("static",str)==0||
strcmp("switch",str)==0||strcmp("case",str)==0) // TYPE 32 KEYWORDS
printf("%s is a keyword\n",str);

2
else
printf("%s is a identifier\n",str);
ungetc(c,f1);
i=0;
}
else if(c==' '||c=='\t') // TO IGNORE THE SPACE
printf("\n");
else if(c=='\n') // TO COUNT LINE NUMBER
lineno++;
else // TO FIND SPECIAL SYMBOL
printf("%c is a special symbol\n",c);

}
printf("Total no. of lines are: %d\n",lineno);
fclose(f1);
getch();
}

OUTPUT

Enter the c program


int main()
{
int a=10,20;
charch;
float f;
}^Z

The numbers in the program are: 10 20


The keywords and identifiersare:
int is a keyword
main is an identifier
int is a keyword
a is an identifier
char is a keyword
ch is an identifier
float is a keyword
f is an identifier
Special characters are ( ) { = , ; ; ; }
Total no. of lines are:5

3
2) Simulate First and Follow of a Grammar.
a) FIRST
#include<stdio.h>
#include<ctype.h>
void FIRST(char[],char );
void result(char[],char);
intnop;
char prod[10][10];
void main()
{
int i;
char choice;
char c;
char res1[20];
clrscr();
printf("How many number of productions ? :");
scanf(" %d",&nop);
printf("enter the production string like E=E+T\n");
for(i=0;i<nop;i++)
{
printf("Enter productions Number %d : ",i+1);
scanf(" %s",prod[i]);
}
do
{
printf("\n Find the FIRST of :");
scanf(" %c",&c);
memset(res1,’0’,sizeof(res));
FIRST(res1,c);
printf("\n FIRST(%c)= { ",c);
for(i=0;res1[i]!='\0';i++)
printf(" %c ",res1[i]);
printf("}\n");
printf("press 'y' to continue : ");
scanf(" %c",&choice);
}
while(choice=='y'||choice =='Y');
}

void FIRST(char res[],char c)


{
inti,j,k;
char subres[5];
int eps;
subres[0]='\0';
res[0]='\0';
memset(res,’0’,sizeof(res));
memset(subres,’0’,sizeof(res));
if(!(isupper(c)))
{

4
result(res,c);
return ;
}
for(i=0;i<nop;i++)
{
if(prod[i][0]==c)
{
if(prod[i][2]=='$')
result(res,'$');
else
{
j=2;
while(prod[i][j]!='\0')
{
eps=0;
FIRST(subres,prod[i][j]);
for(k=0;subres[k]!='\0';k++)
result(res,subres[k]);
for(k=0;subres[k]!='\0';k++)
if(subres[k]=='$')
{
eps=1;
break;
}
if(!eps)
break;
j++;
}
}
}
}
return ;
}
void result(char res[],char val)
{
int k;
for(k=0 ;res[k]!='\0';k++)
if(res[k]==val)
return;
res[k]=val;
res[k+1]='\0';
}

OUTPUT
How many number of productions ?:8
enter the production string like E=E+T
Enter productions Number 1 : E=TX
Enter productions Number 2 : X=+TX
Enter productions Number 3 : X=$
Enter productions Number 4 : T=FY

5
Enter productions Number 5 : Y=*FY
Enter productions Number 6 : Y=$
Enter productions Number 7 : F=(E)
Enter productions Number 8 : F=i

Find the FIRST of :X

FIRST(X)= { + $ }
press 'y' to continue : Y

Find the FIRST of :F

FIRST(F)= { ( i }
press 'y' to continue : Y

Find the FIRST of :Y

FIRST(Y)= { * $ }
press 'y' to continue : Y

Find the FIRST of :E

FIRST(E)= { ( i }
press 'y' to continue : Y

Find the FIRST of :T

FIRST(T)= { ( i }
press 'y' to continue : N

6
b) FOLLOW

#include<stdio.h>
#include<string.h>
intnop,m=0,p,i=0,j=0;
char prod[10][10],res[10];
void FOLLOW(char c);
void first(char c);
void result(char);

void main()
{
int i;
int choice;
charc,ch;
printf("Enter the no.of productions: ");
scanf("%d", &nop);
printf("enter the production string like E=E+T\n");
for(i=0;i<nop;i++)
{
printf("Enter productions Number %d : ",i+1);
scanf(" %s",prod[i]);
}
do
{
m=0;
memset(res,’0’,sizeof(res));
printf("Find FOLLOW of -->");
scanf(" %c",&c);
FOLLOW(c);
printf("FOLLOW(%c) = { ",c);
for(i=0;i<m;i++)
printf("%c ",res[i]);
printf(" }\n");
printf("Do you want to continue(Press 1 to continue ... )?");
scanf("%d%c",&choice,&ch);
}
while(choice==1);
}

void FOLLOW(char c)
{
if(prod[0][0]==c)
result('$');
for(i=0;i<nop;i++)
{
for(j=2;j<strlen(prod[i]);j++)
{
if(prod[i][j]==c)
{

7
if(prod[i][j+1]!='\0')
first(prod[i][j+1]);
if(prod[i][j+1]=='\0'&&c!=prod[i][0])
FOLLOW(prod[i][0]);
}
}
}
}

void first(char c)
{
int k;
if(!(isupper(c)))
result(c);
for(k=0;k<nop;k++)
{
if(prod[k][0]==c)
{
if(prod[k][2]=='$')
FOLLOW(prod[i][0]);
else if(islower(prod[k][2]))
result(prod[k][2]);
else
first(prod[k][2]);
}
}
}

void result(char c)
{
int i;
for( i=0;i<=m;i++)
if(res[i]==c)
return;
res[m++]=c;
}

OUTPUT
Enter the no.of productions: 8
enter the production string like E=E+T
Enter productions Number 1 : E=TX
Enter productions Number 2 : X=+TX
Enter productions Number 3 : X=$
Enter productions Number 4 : T=FY
Enter productions Number 5 : Y=*FY
Enter productions Number 6 : Y=$
Enter productions Number 7 : F=(E)
Enter productions Number 8 : F=i
Find FOLLOW of -->X
FOLLOW(X) = { $ ) }

8
Do you want to continue(Press 1 to continue ... )?1
Find FOLLOW of -->E
FOLLOW(E) = {$ ) }
Do you want to continue(Press 1 to continue ... )?1
Find FOLLOW of -->Y
FOLLOW(Y) = { + $ ) }
Do you want to continue(Press 1 to continue ... )?1
Find FOLLOW of -->T
FOLLOW(T) = { +$ ) }
Do you want to continue(Press 1 to continue ... )?1
Find FOLLOW of -->F
FOLLOW(F) = { * + $ ) }
Do you want to continue(Press 1 to continue ... )?2

9
3) Develop an operator precedence parser for a given language.
#include<stdio.h>
#include<conio.h>

void main()
{
char stack[20],ip[20],opt[10][10][1],ter[10];
inti,j,k,n,top=0,row,col;
clrscr();
for(i=0;i<10;i++)
{
stack[i]=NULL;
ip[i]=NULL;
for(j=0;j<10;j++)
{
opt[i][j][1]=NULL;
}
}
printf("Enter the no.of terminals:");
scanf("%d",&n);
printf("\nEnter the terminals:");
scanf("%s",ter);
printf("\nEnter the table values:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Enter the value for %c %c:",ter[i],ter[j]);
scanf("%s",opt[i][j]);
}
}
printf("\nOPERATOR PRECEDENCE TABLE:\n");
for(i=0;i<n;i++)
{
printf("\t%c",ter[i]);
}
printf("\n ");
printf("\n");
for(i=0;i<n;i++)
{
printf("\n%c |",ter[i]);
for(j=0;j<n;j++)
{
printf("\t%c",opt[i][j][0]);
}
}
stack[top]='$';
printf("\n\nEnter the input string(append with $):");
scanf("%s",ip);
i=0;

10
printf("\nSTACK\t\t\tINPUT STRING\t\t\tACTION\n");
printf("\n%s\t\t\t%s\t\t\t",stack,ip);
while(i<=strlen(ip))
{
for(k=0;k<n;k++)
{
if(stack[top]==ter[k])
row=k;
if(ip[i]==ter[k])
col=k;
}
if((stack[top]=='$')&&(ip[i]=='$'))
{
printf("String is ACCEPTED");
break;
}
else if((opt[row][col][0]=='<') ||(opt[row][col][0]=='='))
{
stack[++top]=opt[row][col][0];
stack[++top]=ip[i];
ip[i]=' ';
printf("Shift %c",ip[i]);
i++;
}
else
{
if(opt[row][col][0]=='>')
{
while(stack[top]!='<')
{
--top;
}
top=top-1;
printf("Reduce");
}
else
{
printf("\nString is not accepted");
break;
}
}
printf("\n");
printf("%s\t\t\t%s\t\t\t",stack,ip);
}
getch();
}

11
OUTPUT
Enter the no.of terminals:4

Enter the terminals:i+*$

Enter the table values:


Enter the value for i i:
-
Enter the value for i +:>
Enter the value for i *:>
Enter the value for i $:>
Enter the value for + i:<
Enter the value for + +:>
Enter the value for + *:<
Enter the value for + $:>
Enter the value for * i:<
Enter the value for * +:>
Enter the value for * *:>
Enter the value for * $:>
Enter the value for $ i:<
Enter the value for $ +:<
Enter the value for $ *:<
Enter the value for $ $:-

OPERATOR PRECEDENCE TABLE:


i + * $

i| - > > >


+| < > < >
*| < > > >
$| < < < -

Enter the input string(append with $):i+i*i$

STACK INPUT STRING ACTION

$ i+i*i$ Shift
$<i +i*i$ Reduce
$<i +i*i$ Shift
$<+ i*i$ Shift
$<+<i *i$ Reduce
$<+<i *i$ Shift
$<+<* i$ Shift
$<+<*<i $ Reduce
$<+<*<i $ Reduce
$<+<*<i $ Reduce
$<+<*<i $ String is ACCEPTED

12
4) Construct a recursive descent parser for an expression.

#include<stdio.h>
#include<string.h>

char input[10];
int i=0,error=0;
void E();
void T();
voidEprime();
voidTprime();
void F();

void main()
{
clrscr();
printf("Enter an arithmetic expression :\n");
gets(input);
E();
if(strlen(input)==i&&error==0)
printf("\nAccepted..!!!");
else
printf("\nRejected..!!!");
getch();
}
void E()
{
T();
Eprime();
}
voidEprime()
{
if(input[i]=='+')
{
i++;
T();
Eprime();
}
}
void T()
{
F();
Tprime();
}
voidTprime()
{
if(input[i]=='*')
{
i++;

13
F();
Tprime();
}
}
void F()
{
if(input[i]=='(')
{
i++;
E();
if(input[i]==')')
i++;
}
else if(isalpha(input[i]))
{
i++;
while(isalnum(input[i])||input[i]=='_')
i++;
}
else
error=1;
}
OUTPUT
1)
Enter an arithmetic expression :
sum+month*interest

Accepted..!!!

2)
Enter an arithmetic expression :
sum+avg*+interest

Rejected..!!!

14
5) Construct a LL(1) parser for an expression

#include<stdio.h>
#include<string.h>
char str[25],st[25],*temp,v,ch,ch1;
char t[5][6][10]={"$","$","TX","TX","$","$",
"+TX","$","$","$","e","e",
"$","$","FY","FY","$","$",
"e","*FY","$","$","e","e",
"$","$","i","(E)","$","$"};
int i,k,n,top=-1,r,c,m,flag=0;
void push(char t)
{
top++;
st[top]=t;
}
char pop()
{
ch1=st[top];
top--;
return ch1;
}
main()
{
printf("enter the string:\n");
scanf("%s",str);
n=strlen(str);
str[n++]='$';
i=0;
push('$');
push('E');
printf("stack\tinput\toperation\n");
while(i<n)
{
for(k=0;k<=top;k++)
printf("%c",st[k]);
printf("\t");
for(k=i;k<n;k++)
printf("%c",str[k]);
printf("\t");
if(flag==1)
printf("pop");
if(flag==2)
printf("%c->%s",ch,t[r][c]);
if(str[i]==st[top])
{
flag=1;

15
ch=pop();
i++;
}
else
{
flag=2;
if(st[top]=='E')
r=0;
else if(st[top]=='X')
r=1;
else if(st[top]=='T')
r=2;
else if(st[top]=='Y')
r=3;
else if(st[top]=='F')
r=4;
else
break;
if(str[i]=='+')
c=0;
else if(str[i]=='*')
c=1;
else if(str[i]=='i')
c=2;
else if(str[i]=='(')
c=3;
else if(str[i]==')')
c=4;
else if(str[i]=='$')
c=5;
else
break;
if(strcmp(t[r][c],"$")==0)
break;
ch=pop();
temp=t[r][c];
m=strlen(temp);
if(strcmp(t[r][c],"e")!=0)
{
for(k=m-1;k>=0;k--)
push(temp[k]);
}
}
printf("\n");
}
if(i==n)
printf("\nparsed successfully");

16
else
printf("\nnot parsed");
}
OUTPUT
1)
Enter any String(Append with $)i+i*i$
Stack Input Output
$E i+i*i$
$HT i+i*i$ E->TH
$HUF i+i*i$ T->FU
$HUi i+i*i$ F->i
$HU +i*i$ POP
$H +i*i$ U->ε
$HT+ +i*i$ H->+TH
$HT i*i$ POP
$HUF i*i$ T->FU
$HUi i*i$ F->i
$HU *i$ POP
$HUF* *i$ U->*FU
$HUF i$ POP
$HUi i$ F->i
$HU $ POP
$H $ U->ε
$ $ H->ε

Given String is accepted


2)

Enter any String(Append with $)i+i**i$


Stack Input Output

$E i+i**i$
$HT i+i**i$ E->TH
$HUF i+i**i$ T->FU
$HUii+i**i$ F->i
$HU +i**i$ POP
$H +i**i$ U->ε
$HT+ +i**i$ H->+TH
$HT i**i$ POP
$HUF i**i$ T->FU
$HUi i**i$ F->i
$HU **i$ POP
$HUF* **i$ U->*FU
$HUF *i$ POP
$HU$ *i$ F->$
Syntax Error
Given String is not accepted

17
6) Design predictive parser for the given language

#include<stdio.h>
#include<string.h>
# define SIZE 30
charst[100];
int top=-1;
int s1(char),ip(char);
int n1,n2;
charnt[SIZE],t[SIZE];
/*Function to return variable index*/
int s1(char c)
{
int i;
for(i=0;i<n1;i++)
{
if(c==nt[i])
return i;
}
}
/*Function to return terminal index*/
intip(char c)
{
int i;
for(i=0;i<n2;i++)
{
if(c==t[i])
return i;
}
}
void push(char c)
{
top++;
st[top]=c;
return;
}
void pop()
{
top--;
return;
}
main()
{
char table[SIZE][SIZE][10],input[SIZE];
intx,f,s,i,j,u;
printf("Enter the number of variables:");
scanf("%d",&n1);
printf("\nUse single capital letters for variables\n");
for(i=0;i<n1;i++)
{

18
printf("Enter the %d nonterminal:",i+1);
scanf("%c",&nt[i]);
}
printf("Enter the number of terminals:");
scanf("%d",&n2);
printf("\nUse single small letters for terminals\n");
for(i=0;i<n2;i++)
{
printf("Enter the %d terminal:",i+1);
scanf("%c",&t[i]);
}
/*Reading the parsing table*/
printf("Please enter only right sides of productions\n");
printf("Use symbol n to denote no entry and e to epsilon\n");
for(i=0;i<n1;i++)
{
for(j=0;j<n2;j++)
{
printf("\nEnter the entry for %c under %c:",nt[i],t[j]);
scanf("%s",table[i][j]);
}
}
/*Printing the parsing taable*/
for(i=0;i<n2;i++)
printf("\t%c",t[i]);
printf("\n \n");
for(i=0;i<n1;i++)
{
printf("\n%c|\t",nt[i]);
for(j=0;j<n2;j++)
{
if(!strcmp(table[i][j],"n"))
printf("\t");
else
printf("%s\t",Table[i][j]);
}
printf("\n");
}
printf("Enter the input:");
scanf("%s",input);
/*Initialising the stack*/
top++;
st[top]='$';
top++;
st[top]=nt[0];
printf("STACK content INPUT content PRODUCTION used\n");
printf(" \n");
i=0;
printf("$%c\t\t\t%s\n\n",st[top],input);
while(st[top]!='$')

19
{
x=0;
f=s1(st[top]);
s=ip(input[i]);
if(!strcmp(table[f][s],"n"))
{
printf("'String not accepted");
}
else
if(!strcmp(table[f][s],"e"))
{
pop();
}
else
if(st[top]==input[i])
{
x=1;
pop();
i++;
}
else
{
pop();
for(j=strlen(table[f][s])-1;j>0;j--)
{
{
push(table[f][s][j]);
}
}
for(u=0;u<=top;u++)
printf("%c",st[u]);
printf("\t\t\t");
for(u=i;input[u]!='\0';u++)
printf("%c",input[u]);
printf("\t\t\t");
if(x==0)
printf("%c->%s\n\n",nt[f],table[f][s]);
printf("'\n\n");
}
printf("\n\nThus string is accepted");
}
}

20
OUTPUT:
Enter the number of variables:5
Use single capital letters for the variables
Enter the 1 non terminal:E
Enter the 2 non terminal:A
Enter the 3 non terminal:T
Enter the 4 non terminal:B
Enter the 5 non terminal:F
Enter the number of terminals:6
Use only single small letter for the terminals
Enter the 1 terminal:+
Enter the 2 terminal:*
Enter the 3 terminal:(
Enter the 4 terminal:)
Enter the 5 terminal:i
Enter the 6 terminal:$
Please enter only the right sides of productions.
Use symbol n to denote noentry and e to epsilon
Enter the entry for E under $: n
Enter the entry for E under +: n
Enter the entry for E under *: n
Enter the entry for E under (: TA
Enter the entry for E under ): n
Enter the entry for E under i: TA
Enter the entry for A under +: +TA
Enter the entry for A under *: n
Enter the entry for A under (: n
Enter the entry for A under ): e
Enter the entry for A under i: n
Enter the entry for A under $: e
Enter the entry for T under +: n
Enter the entry for T under *: n
Enter the entry for T under (: FB
Enter the entry for T under ): n
Enter the entry for T under i: FB
Enter the entry for T under $: n
Enter the entry for B under +: e
Enter the entry for B under *: *FB
Enter the entry for B under (: n
Enter the entry for B under ): e
Enter the entry for B under i: n
Enter the entry for B under $: e
Enter the entry for F under +: n
Enter the entry for F under *: n
Enter the entry for F under (: (E)
Enter the entry for F under ): n
Enter the entry for F under i: i
Enter the entry for F under $: n
+*()i$

21
E| TA TA
A| +TA e e
T| FB FB
B| e *FB e e
F| (E) i
Enter the input: i+i*i$
Stack content Input content Production used

$E i+i*i$
$A i+i*i$ E->TA
$AB i+i*i$ T->FB
$AB i+i*i$ F->i
$A +i*i$
$ +i*i$ B->e
$AT +i*i$ A->+TA
$A i*i$
$AB i*i$ T->FB
$AB i*i$ F->i
$A *i$
$ABF *i$ B->*FB
$AB i$
$AB i$ F->i
$A $
$ $ B->e
$ A->e
Thus string is accepted

22
7) Implementation of shift reduce parsing algorithm.

#include"stdio.h"
#include"stdlib.h"
#include"string.h"
char ip_sym[15],stack[15];
int ip_ptr=0,st_ptr=0,len,i;
char temp[2],temp2[2];
char act[15];
void check();
void main()
{
printf("\n\t\t SHIFT REDUCE PARSER\n");
printf("\n GRAMMER\n");
printf("\n E->E+E\n E->E/E");
printf("\n E->E*E\n E->a/b");
printf("\n enter the input symbol:\t");
gets(ip_sym);
printf("\n\t stack implementation table");
printf("\n stack\t\t input symbol\t\t action");
printf("\n \t\t \t\t \n");
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++;
}
check();
}
void check()
{
int flag=0;
temp2[0]=stack[st_ptr];
temp2[1]='\0';
if((isalpha(temp2[0])))
{

23
stack[st_ptr]='E';
printf("\n $%s\t\t%s$\t\t\tE->%s",stack,ip_sym,temp2);
flag=1;
}
if((!strcmp(temp2,"+"))||(!strcmp(temp2,"*"))||(!strcmp(temp2,"/")))
{
flag=1;
}
if((!strcmp(stack,"E+E"))||(!strcmp(stack,"E/E"))||(!strcmp(stack,"E*E")))
{
if(!strcmp(stack,"E+E"))
{
strcpy(stack,"E");
printf("\n $%s\t\t%s$\t\t\tE->E+E",stack,ip_sym);
}
else if(!strcmp(stack,"E/E"))
{
strcpy(stack,"E");
printf("\n $%s\t\t %s$\t\t\tE->E/E",stack,ip_sym);
}
else
{
strcpy(stack,"E");
printf("\n $%s\t\t%s$\t\t\tE->E*E",stack,ip_sym);
}
flag=1;
st_ptr=0;
}
if(!strcmp(stack,"E")&&ip_ptr==len)
{
printf("\n $%s\t\t%s$\t\t\tACCEPT",stack,ip_sym);
exit(0);
}
if(flag==0)
{
printf("\n $%s\t\t%s$\t\t\tReject",stack,ip_sym);
exit(0);
}
return;
}
OUTPUT:
1)
SHIFT REDUCE PARSER GRAMMER
E->E+E
E->E/E
E->E*E
E->E-E
E->id
enter the input symbol: a+b*c
stack implementation table

24
stack input symbol action

$ a+b*c$ --
$a +b*c$ shift a
$E +b*c$ E->a
$E+ b*c$ shift +
$E+b *c$ shift b
$E+E *c$ E->b
$E *c$ E->E+E
$E* c$ shift *
$E*c $ shift c
$E*E $ E->c
$E $ E->E*E
$E $ ACCEPT

2) SHIFT REDUCE PARSER GRAMMER


E->E+E
E->E/E
E->E*E
E->E-E
E->id
enter the input symbol: a+b*+c
stack implementation table
stack input symbol action

$ a+b*+c$ --
$a +b*+c$ shift a
$E +b*+c$ E->a
$E+ b*+c$ shift +
$E+b *+c$ shift b
$E+E *+c$ E->b
$E *+c$ E->E+E
$E* +c$ shift *
$E*+ c$ shift +
$E*+c $ shift c
$E*+E $ E->c
$E*+E reject

25
8) Design a LALR bottom up parser for the given language.
{%
#nclude<stdio.h>
#include<conio.h>
intyylex(void);
%}
%token ID
%start line
%%
line:expr '\n', {printf("%d",S1);}
expr:expr'+'term {SS=S1+S3;}
|term
term:term'*'factor {SS=S1+S3;}
|factor
factor:'('expr')' {SS=S2;}
|ID
%%

yylex()
{
char c[10],i;
gets(c);
if(isdigit(c))
{
yylval=c;
return ID;
}
return c;
}

Output:
$vi lalr.y
$yacc –v lalr.y
$vi y.output
y.output contains the ouput

1 line : expr '\n'


2 expr : expr '+' term
3 | term
4 term : term '*' factor
5 | factor
6 factor : '(' expr ')'
7 | ID
^L
state 0
$accept : . line $end (0)
ID shift 1
'(' shift 2
. error
line goto 3

26
exprgoto 4
term goto 5
state 1
factor : ID . (7)
. reduce 7
state 2
factor : '(' . expr ')' (6)
ID shift 1
'(' shift 2
. error
exprgoto 7
term goto 5
factor goto 6
state 3
$accept : line . $end (0)
$end accept
state 4
line :expr . '\n' (1)
expr :expr . '+' term (2)
'\n' shift 8
'+' shift 9
. error
state 5
expr : term . (3)
term : term . '*' factor (4)
'*' shift 10
'\n' reduce 3
'+' reduce 3
')' reduce 3
state 6
term : factor . (5)
. reduce 5
state 7
expr :expr . '+' term (2)
factor : '(' expr . ')' (6)
'+' shift 9
')' shift 11
. error
state 8
line :expr '\n' . (1)
. reduce 1
state 9
expr :expr '+' . term (2)
ID shift 1
'(' shift 2
. error
term goto 12
factor goto 6
state 10
term : term '*' . factor (4)

27
ID shift 1
'(' shift 2
. error
factor goto 13
state 11
factor : '(' expr ')' . (6)
. reduce 6
state 12
expr :expr '+' term . (2)
term : term . '*' factor (4)
'*' shift 10
'\n' reduce 2
'+' reduce 2
')' reduce 2
state 13
term : term '*' factor . (4)
. reduce 4
8 terminals, 5 nonterminals
8 grammar rules, 14 states

28
9) Implement the lexical analyzer using JLex, flex or lex or other lexical analyzer
generating tools

// Program name as “lexicalfile.l”


%{
#include<stdio.h>
%}

delim [\t]
ws {delim}+
letter [A-Za-z]
digit [0-9]
id {letter}({letter}|{digit})*
num {digit}+(\.{digit}+)?(E[+|-]?{digit}+)?

%%
ws {printf("no action");}
if|else|then {printf("%s is a keyword",yytext);} // TYPE 32 KEYWORDS
{id} {printf("%s is a identifier",yytext);}
{num} {printf(" it is a number");}
"<" {printf("it is a relational operator less than");}
"<=" {printf("it is a relational operator less than or equal");}
">" {printf("it is a relational operator greater than");}
">=" {printf("it is a relational operator greater than");}
"==" {printf("it is a relational operator equal");}
"<>" {printf("it is a relational operator not equal");}
%%

main()
{
yylex();
}

OUTPUT

lexlexicalfile.l
cc lex.yy.c -ll
if
if is a keyword
number
number is a identifier
254
It is a number
<>
it is a relational operator not equal
^Z

29
10) Write a program to perform loop unrolling.

#include<stdio.h>
int main()
{
int i;
for(i=0;i<10;i+=2)
{
printf("fun(%d)\n",i+1);
printf("fun(%d)\n",i+2);

}
}

OUTPUT
fun(1)
fun(2)
fun(3)
fun(4)
fun(5)
fun(6)
fun(7)
fun(8)
fun(9)
fun(10)

30
11) Convert the BNF rules into YACC form and write code to generate abstract syntax
tree.

<int.l>
%{
#include"y.tab.h"
#include<stdio.h>****
#include<string.h>
int LineNo=1;
%}
identifier [a-zA-Z][_a-zA-Z0-9]*
number [0-9]+|([0-9]*\.[0-9]+)
%%
main\(\) return MAIN;
if return IF;
else return ELSE;
while return WHILE;
int |
char |
float return TYPE;
{identifier} {strcpy(yylval.var,yytext);
return VAR;}
{number} {strcpy(yylval.var,yytext);
return NUM;}
\< |
\> |
\>= |
\<= |
== {strcpy(yylval.var,yytext);
return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%

31
int yywrap()
{
return 1;
}
<int.y>
%{
#include<string.h>
#include<stdio.h>
struct quad
{
char op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
{
int items[100];
int top;
}stk;
int Index=0,tIndex=0,StNo,Ind,tInd;
extern int LineNo;
%}
%union
{
char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP
%left '-' '+'
%left '*' '/'
%%
PROGRAM : MAIN BLOCK

32
;
BLOCK: '{' CODE '}'
;
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;
STATEMENT: DESCT ';'
| ASSIGNMENT ';'
| CONDST
| WHILEST
;
DESCT: TYPE VARLIST
;
VARLIST: VAR ',' VARLIST
| VAR
;
ASSIGNMENT: VAR '=' EXPR{
strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
strcpy($$,QUAD[Index++].result);
}
;
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}
| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}
| EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);}
| EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);}
| '-' EXPR {AddQuadruple("UMIN",$2,"",$$);}
| '(' EXPR ')' {strcpy($$,$2);}
| VAR
| NUM
;

33
CONDST: IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST
;
IFST: IF '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
};
ELSEST: ELSE{
tInd=pop();
Ind=pop();
push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
};

34
CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);
StNo=Index-1;
}
| VAR
| NUM
;
WHILEST: WHILELOOP{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
WHILELOOP: WHILE '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
;
%%
extern FILE *yyin;
int main(int argc,char *argv[])
{

35
FILE *fp;
int i;
if(argc>1)
{
fp=fopen(argv[1],"r");
if(!fp)
{
printf("\n File not found");
exit(0);
}
yyin=fp;
}
yyparse();
printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result" "\n\t\t -------
");
for(i=0;i<Index;i++)
{
printf("\n\t\t %d\t %s\t %s\t %s\t
%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);
}
printf("\n\t\t ");
printf("\n\n");
return 0;
}
void push(int data)
{
stk.top++;
if(stk.top==100)
{
printf("\n Stack overflow\n");
exit(0);
}
stk.items[stk.top]=data;
}

36
int pop()
{
int data;
if(stk.top==-1)
{
printf("\n Stack underflow\n");
exit(0);
}
data=stk.items[stk.top--];
return data;
}
void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10])
{
strcpy(QUAD[Index].op,op);
strcpy(QUAD[Index].arg1,arg1);
strcpy(QUAD[Index].arg2,arg2);
sprintf(QUAD[Index].result,"t%d",tIndex++);
strcpy(result,QUAD[Index++].result);
}
yyerror()
{
printf("\n Error on line no:%d",LineNo);
}
Input:
$vi test1.c
main()
{
int a,b,c;
if(a<b)
{
a=a+b;
}
while(a<b)
{

37
a=a+b;
}
if(a<=b)
{
c=a-b;
}
else
{
c=a+b;
}
}
Output:
$lex int.l
$yacc –d –v int.y
$gcc lex.yy.c y.tab.c –lm
$./a.out test1.c

38
12) Write a program for constant propagation.
#include<stdio.h>

int main()

int x, y, z;

x = 10;

y = x + 45;

z = y + 4;

printf("The value of z = %d", z);

return 0;

OUTPUT:

$ vi test.c

$ cc –c –S test.c

$ vi test.s //before optimization assembly code

main:

pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $32, %esp
movl $10, 20(%esp)
movl 20(%esp), %eax
addl $45, %eax
movl %eax, 24(%esp)
movl 24(%esp), %eax
addl $4, %eax
movl %eax, 28(%esp)
movl $.LC0, %eax
movl 28(%esp), %edx
movl %edx, 4(%esp)
movl %eax, (%esp)
call printf
movl $0, %eax
leave

39
ret
$ cc –c –S -O2 test.c

$ vi test.s //after optimization assembly code

main:

pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $16, %esp
movl $59, 4(%esp)
movl $.LC0, (%esp)
call printf
xorl %eax, %eax
leave
ret

40
41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy