You are on page 1of 41

COMPILER LAB

SIMULATION OF DFA

#include<stdio.h>
void main()
{
int i,k,j,in,fin,a,b,st,len,flag,sub;
int ar[5][5],str[5];

printf(“Enter the number of states : “);


scanf(“%d”,&a);
printf(“Enter the initial states : “);
scanf(“%d”,&in);
printf(“Enter the final states : “);
scanf(“%d”,&fin);
printf(“Enter the number of inputs : “);
scanf(“%d”,&b);
printf(“Enter the transition states :\n”);
for(i=in;i<a;i++)
{
for(j=0;j<b;j++)
{
printf(“\tEnter the transition from %d with %d : “,i,j);
scanf(“%d”,&ar[i][j]);
}
}
printf(“Enter the length of the string : “);
scanf(“%d”,&len);
printf(“enter the string : “);
for(k=0;k<len;k++)

COLLEGE OF ENGINEERING, KALLOOPPARA Page 1


COMPILER LAB

{
scanf(“%d”,&str[k]);
}
flag=in;
for(i=0;i<len;i++)
{
sub=ar[flag][str[i]];
flag=sub;
}
if(flag==fin)
{
printf(“Accepted\n”);
}
else
{
printf(“Rejected\n”);
}
}

PROGRAM 2

NFA TO DFA
#include<stdio.h>
#include<string.h>
#include<math.h>

int ninputs;
int dfa[100][2][100]={0};
int state[10000]={0};

char ch[10],str[10000];
int go[10000][2]={0};
int arr[10000]={0};

int main()
COLLEGE OF ENGINEERING, KALLOOPPARA Page 2
COMPILER LAB

{
int st,fin,in;
int f[10];
int i,j=3,s=0,final=0,flag=0,curr1,curr2,k,l;
int c;
printf(“\nFollowing the one based indexing\n”);
printf(“\nEnter the number of states :: “);
scanf(“%d”,&st);
printf(“\nGiven state numbers from 0 to %d”,st-1);
for(i=0;i<st;i++)
{
state[(int)(pow(2,i))]=1;
}
printf(“\nEnter number of final states : “);
scanf(“%d”,&fin);
printf(“\nEnter final states :: “);
for(i=0;i<fin;i++)
{
scanf(“%d”,&f[i]);
}
int p,q,r,rel;
printf(“\nEnter the number of rules according to NFA :: “);
scanf(“%d”,&rel);
printf(“\n\nDefine transition rule as \” initial state input symbol final ...\”\n\n”);
for(i=0;i<rel;i++)
{
scanf(“%d%d%d”,&p,&q,&r);
if(q==0)
{
dfa[p][0][r]=1;
}
else
{
dfa[p][1][r]=1;
}

COLLEGE OF ENGINEERING, KALLOOPPARA Page 3


COMPILER LAB

}
printf(“\nEnter initial state :: “);
scanf(“%d”,&in);
in=pow(2,in);
i=0;
printf(“\nsolving according to DFA”);
int x=0;
for(i=0;i<st;i++)
{
for(j=0;j<2;j++)
{
int stf=2;
for(k=0;k<st;k++)
{
if(dfa[i][j][k]==1)
stf=stf+pow(2,k);
}
go[(int)(pow(2,i))][j]=stf;
printf(“%d-%d%d\n”,(int)(pow(2,i)),j,stf);
if(state[stf]==0)
arr[x++]=stf;
state[stf]=1;
}
}
for(i=0;i<x;i++)
{
printf(“for %d ----“,arr[x]);
for(j=0;j<2;j++)
{
int new=0;
for(k=0;k<st;k++)
{
if(arr[i]&(1<<k))
{
int h=pow(2,k);

COLLEGE OF ENGINEERING, KALLOOPPARA Page 4


COMPILER LAB

if(new==0)
new=new|(go[h][j]);
}
}
if(state[new]==0)
{
arr[x++]=new;
state[new]=1;
}
}
}
printf(“\nThe total number of distinct states are ::\n”);
printf(“STATE 0 1\n”);
for(i=0;i<10000;i++)
{
if(state[i]==1)
{
//printf(“%d**”,i);
int y=0;
if(i==0)
printf(“q0”);
else// dout {}
for(j=0;j<st;j++)
{
int x=1<<j;
if(x&i)
{
printf(“q%d”,j);
y=y+pow(2,j);
//printf(“y=%d”,y);
}
}
//printf(“%d”,y);
printf(“%d %d”,go[y][0],go[y][1]);
printf(“\n”);

COLLEGE OF ENGINEERING, KALLOOPPARA Page 5


COMPILER LAB

}
}
j=3;
while(j--)
{
printf(“\nenter string : “);
scanf(“%s”,str);
l=strlen(str);
curr1=in;
flag=0;
printf(“\nstring takes the following path \n”);
printf(“%d-“,curr1);
for(i=0;i<l;i++) // dout l
{
curr1=go[curr1][str[i]=’0’];
printf(“%d-“,curr1);
}
printf(“\nfinal state - %d\n”,curr1);
for(i=0;i<fin;i++)
{
if(curr1&(1<<f[i]))
{
flag=1;
break;
}
}
if(flag)
printf(“\nstring accepted\n\n”);
else
printf(“\nstring rejected\n\n”);
}
return 0;
}

COLLEGE OF ENGINEERING, KALLOOPPARA Page 6


COMPILER LAB

COLLEGE OF ENGINEERING, KALLOOPPARA Page 7


COMPILER LAB

COLLEGE OF ENGINEERING, KALLOOPPARA Page 8


COMPILER LAB

COLLEGE OF ENGINEERING, KALLOOPPARA Page 9


COMPILER LAB

COLLEGE OF ENGINEERING, KALLOOPPARA Page 10


COMPILER LAB

SOLUTIONS FOR PROGRAMS

1) Lexical Analyzer implementation 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);

COLLEGE OF ENGINEERING, KALLOOPPARA Page 11


COMPILER LAB

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

COLLEGE OF ENGINEERING, KALLOOPPARA Page 12


COMPILER LAB

2) Implement the lexical analyzer using 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

COLLEGE OF ENGINEERING, KALLOOPPARA Page 13


COMPILER LAB

2.A) Program To Count Vowels And Constants In A Sentence

%{
#include<stdio.h>
#include<string.h>
int vow_count=0;
int const_count=0;
%}
%%
[aeiouAEIOU]* {vow_count++;}
[a-zA-Z] {const_count++;}
"\n" {printf("Number of vowels are: %d\n",vow_count);printf("Number of
consonants are:%d\n", const_count);}
%%
int yywrap(void) {}
int main()
{
printf("Enter the strings of vowels and consonants:");
yylex();

return 0;
}

OUTPUT

vowels and constants

Enter the strings of vowels and constants:hello


Number of vowels are: 2
Number of consonants are:3

COLLEGE OF ENGINEERING, KALLOOPPARA Page 14


COMPILER LAB

2.b) Program to count keywords, number and words in a string

%{
#include<stdio.h>
%}
%%
if |
else |
printf {printf("%s is a keyword",yytext);}
[0-9]+ {printf("%s is a number", yytext);}
[a-zA-Z]+ {printf("%s is a word", yytext);}
.|\n {ECHO;}
%%
int main()
{
printf("\n Enter String:");
yylex();
}
int yywrap()
{
return 1;
}

OUTPUT

keywords

Enter String:hello234
hello is a word 234 is a number

COLLEGE OF ENGINEERING, KALLOOPPARA Page 15


COMPILER LAB

2.c) Program to count number of lines, spaces,tabs, and other characters

%{
#include<stdio.h>
int lc=0, sc=0, tc=0, ch=0;
%}

%%
\n lc++;
([ ])+ sc++;
\t tc++;
. ch++;
%%

int main()
{

yylex();

printf("\nNo. of lines=%d", lc);


printf("\nNo. of spaces=%d", sc);
printf("\nNo. of tabs=%d", tc);
printf("\nNo. of other characters=%d", ch);

OUTPUT

Enter the string:hello welcome to c

No. of spaces=3
No. of tabs=0
No. of other characters=15

COLLEGE OF ENGINEERING, KALLOOPPARA Page 16


COMPILER LAB

3.A) To write a program for implementing a calculator for computing the given
expression using semantic rules of the YACC tool

ALGORITHM:

Step1: A Yacc source program has three parts as follows:

Declarations %% translation rules %% supporting C routines

Step2: Declarations Section: This section contains entries that:

i. Include standard I/O header file.

ii. Define global variables.

iii. Define the list rule as the place to start processing.

iv. Define the tokens used by the parser. v. Define the operators and their
precedence.

Step3: Rules Section: The rules section defines the rules that parse the input stream.
Each rule of a grammar production and the associated semantic action.

Step4: Programs Section: The programs section contains the following subroutines.
Because these subroutines are included in this file, it is not necessary to use the yacc
library when processing this file.

Step5: Main- The required main program that calls the yyparse subroutine to start the
program.

Step6: yyerror(s) -This error-handling subroutine only prints a syntax error message.

Step7: yywrap -The wrap-up subroutine that returns a value of 1 when the end of
input occurs. The calc.lex file contains include statements for standard input and
output, as programmar file information if we use the -d flag with the yacc command.
The y.tab.h file contains definitions for the tokens that the parser program
uses.

Step8: calc.lex contains the rules to generate these tokens from the input stream.

CODE

LEX PART:

%{

#include<stdio.h>

#include "y.tab.h"

COLLEGE OF ENGINEERING, KALLOOPPARA Page 17


COMPILER LAB

extern int yylval;

%}

%%

[0-9]+ {

yylval=atoi(yytext);

return NUMBER;

[\t] ;

[\n] return 0;

. return yytext[0];

%%

int yywrap()

return 1;

YACC PART:

%{

#include<stdio.h>

int flag=0;

%}

%token NUMBER

%left '+' '-'

%left '*' '/' '%'

%left '(' ')'

COLLEGE OF ENGINEERING, KALLOOPPARA Page 18


COMPILER LAB

%%

ArithmeticExpression: E{

printf("\nResult=%d\n",$$);

return 0;

};

E:E'+'E {$$=$1+$3;}

|E'-'E {$$=$1-$3;}

|E'*'E {$$=$1*$3;}

|E'/'E {$$=$1/$3;}

|E'%'E {$$=$1%$3;}

|'('E')' {$$=$2;}

| NUMBER {$$=$1;}

%%

void main()

printf("\nEnter Any Arithmetic Expression which can have operations


Addition, Subtraction, Multiplication, Divison, Modulus and Round
brackets:\n");

yyparse();

if(flag==0)

printf("\nEntered arithmetic expression is Valid\n\n");

void yyerror()

COLLEGE OF ENGINEERING, KALLOOPPARA Page 19


COMPILER LAB

printf("\nEntered arithmetic expression is Invalid\n\n");

flag=1;

OUTPUT

COLLEGE OF ENGINEERING, KALLOOPPARA Page 20


COMPILER LAB

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++;

COLLEGE OF ENGINEERING, KALLOOPPARA Page 21


COMPILER LAB

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..!!!

COLLEGE OF ENGINEERING, KALLOOPPARA Page 22


COMPILER LAB

5) 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;

COLLEGE OF ENGINEERING, KALLOOPPARA Page 23


COMPILER LAB

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();
}

COLLEGE OF ENGINEERING, KALLOOPPARA Page 24


COMPILER LAB

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

COLLEGE OF ENGINEERING, KALLOOPPARA Page 25


COMPILER LAB

6. Implement shift reducer parser for given grammar

#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("\nGrammer\n");
printf("\nE->E+E\nE->E/E\n");
printf("\nE->E*E\nE->a/b\n");
printf("\nenter the input symbol:\t");
gets(ip_sym);
printf("\n\tstack implementation table");
printf("\nstack\t\tinput symbol\t\taction");
printf("\n \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$\t\t%s$\t\t\t ",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])))
{
stack[st_ptr]='E';

COLLEGE OF ENGINEERING, KALLOOPPARA Page 26


COMPILER LAB

printf("\n$\t\t%s$\t\t\t ",stack,ip_sym,temp2);
flag=1;
}

if((!strcmp(temp2,"+"))||(!strcmp(temp2,"*"))||(!strcmp(temp
2,"*")))
{
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$\t\t%s$\t\t\t E->E+E",stack,ip_sym);
}
else if(!strcmp(stack,"E/E"))
{
strcpy(stack,"E");
printf("\n$\t\t%s$\t\t\t E-
>E/E",stack,ip_sym);
}
else
{
strcpy(stack,"E");
printf("\n$\t\t%s$\t\t\t E-
>E*E",stack,ip_sym);
}
flag=1;
st_ptr=0;
}
if(!strcmp(stack,"E")&&ip_ptr==len)
{
printf("\n$\t\t%s$\t\t\t_ACCEPT",stack,ip_sym);
exit(0);
}
if(flag==0)
{

printf("\n$\t\t%s$\t\t\t reject",stack,ip_sym);
exit(0);
}
return;
}

COLLEGE OF ENGINEERING, KALLOOPPARA Page 27


COMPILER LAB

8).Program to convert epsilon-NFA to NFA.

ALGORITHM
1. Start
2. Check if there is at least one path from initial state to one of the
many possible accepting states which can be traversed only by
null transitions. If so, add the initial state to the set of accepting
states.
3. Now, choose two states in e-NFA (let's call them p and q) having
null transitions between them.
4. Remove the null transition.
5. Any incoming transition to p is to be added as an incoming
transition to q.
6. Repeat steps 3,4,5 for all the null transitions in the e-NFA.
7. Stop

CODE
#include<stdio.h>
#include<stdlib.h>
struct node
{
int st;
struct node *link;
};

void findclosure(int,int);
void insert_trantbl(int ,char, int);
int findalpha(char);
void findfinalstate(void);
void unionclosure(int);
void print_e_closure(int);
static int
set[20],nostate,noalpha,s,notransition,nofinal,start,fina
lstate[20],c,r,buffer[20];
char alphabet[20];
static int e_closure[20][20]={0};
struct node * transition[20][20]={NULL};
void main()
{
int i,j,k,m,t,n;

struct node *temp;


printf("enter the number of alphabets?\n");
scanf("%d",&noalpha);
getchar();
printf("NOTE:- [ use letter e as epsilon]\n");

printf("NOTE:- [e must be last character ,if it


is present]\n");

printf("\nEnter alphabets?\n");

COLLEGE OF ENGINEERING, KALLOOPPARA Page 28


COMPILER LAB

for(i=0;i<noalpha;i++)
{

alphabet[i]=getchar();
getchar();
}
printf("Enter the number of states?\n");
scanf("%d",&nostate);
printf("Enter the start state?\n");
scanf("%d",&start);
printf("Enter the number of final states?\n");
scanf("%d",&nofinal);
printf("Enter the final states?\n");
for(i=0;i<nofinal;i++)
scanf("%d",&finalstate[i]);
printf("Enter no of transition?\n");
scanf("%d",&notransition);
printf("NOTE:- [Transition is in the form--> qno
alphabet qno]\n",notransition);
printf("NOTE:- [States number must be greater
than zero]\n");
printf("\nEnter transition?\n");
for(i=0;i<notransition;i++)
{

scanf("%d %c%d",&r,&c,&s);
insert_trantbl(r,c,s);

printf("\n");

for(i=1;i<=nostate;i++)
{
c=0;
for(j=0;j<20;j++)

{
buffer[j]=0;
e_closure[i][j]=0;
}
findclosure(i,i);
}
printf("Equivalent NFA without epsilon\n");
printf(" \n");
printf("start state:");
print_e_closure(start);
printf("\nAlphabets:");
for(i=0;i<noalpha;i++)
printf("%c ",alphabet[i]);
printf("\nStates :" );
for(i=1;i<=nostate;i++)
print_e_closure(i);

COLLEGE OF ENGINEERING, KALLOOPPARA Page 29


COMPILER LAB

printf("\nTransitions are...:\n");

for(i=1;i<=nostate;i++)
{

for(j=0;j<noalpha-1;j++)
{
for(m=1;m<=nostate;m++)
set[m]=0;
for(k=0;e_closure[i][k]!=0;k++)
{

t=e_closure[i][k];
temp=transition[t][j];
while(temp!=NULL)
{

unionclosure(temp->st);
temp=temp-
>link;
}
}

printf("\n");
print_e_closure(i);
printf("%c\t",alphabet[j] );
printf("{");
for(n=1;n<=nostate;n++)
{
if(set[n]!=0)

printf("q%d,",n);
}
printf("}");
}

}
printf("\nFinal states:");
findfinalstate();

void findclosure(int x,int sta)


{
struct node *temp;
int i;
if(buffer[x])
return;
e_closure[sta][c++]=x;

COLLEGE OF ENGINEERING, KALLOOPPARA Page 30


COMPILER LAB

buffer[x]=1;

COLLEGE OF ENGINEERING, KALLOOPPARA Page 31


COMPILER LAB

if(alphabet[noalpha-1]=='e' &&
transition[x][noalpha-1]!=NULL)
{
temp=transition[x][noalpha-
1];
while(temp!=NULL)
{

findclosure(temp->st,sta);

temp=temp-
>link;
}
}
}

void insert_trantbl(int r,char c,int s)


{
int j;
struct node *temp;
j=findalpha(c);
if(j==999)
{
printf("error\n");
exit(0);
}
temp=(struct node *) malloc(sizeof(struct
node));
temp->st=s;
temp->link=transition[r][j];
transition[r][j]=temp;
}

int findalpha(char c)
{
int i;
for(i=0;i<noalpha;i++)
if(alphabet[i]==c)
return i;

return(999);

void unionclosure(int i)
{
int j=0,k;
while(e_closure[i][j]!=0)
{
k=e_closure[i][j];
set[k]=1;

COLLEGE OF ENGINEERING, KALLOOPPARA Page 32


COMPILER LAB

j++;
}
}

COLLEGE OF ENGINEERING, KALLOOPPARA Page 33


COMPILER LAB

void findfinalstate()
{
int i,j,k,t;
for(i=0;i<nofinal;i++)
{
for(j=1;j<=nostate;j++)
{

for(k=0;e_closure[j][k]!=0;k++)
{

if(e_closure[j][k]==finalstate[i])
{

print_e_closure(j);
}
}
}
}

void print_e_closure(int i)
{
int j=0;
printf("{");
if(e_closure[i][j]!=0)
printf("q%d,",e_closure[i][0]);
printf("}\t");
}

OUTPUT
enter the number of alphabets?
3
NOTE:- [ use letter e as epsilon]
NOTE:- [e must be last character ,if it is present]
Enter alphabets?
a
b
e
Enter the number of states?
5
Enter the start state?
1
Enter the number of final states?
1

COLLEGE OF ENGINEERING, KALLOOPPARA Page 34


COMPILER LAB

Enter the final states?


3
Enter the number of transitions?
7
NOTE:- [Transition is in the form--> qno alphabet qno]
NOTE:- [States number must be greater than zero]
Enter transition?
1a2
1e3
2a1

3b4
4b3
3a5
5b3
Equivalent NFA without epsilon

start state:{q1,}
Alphabets:a b e
States :{q1,} {q2,} {q3,} {q4,} {q5,}
Transitions are...:
{q1,} a {q2,q5,}
{q1,} b {q4,}
{q2,} a {q1,q3,}
{q2,} b {}
{q3,} a {q5,}
{q3,} b {q4,}
{q4,} a {}
{q4,} b {q3,}
{q5,} a {}
{q5,} b {q3,}
Final states:{q1,} {q3,}

COLLEGE OF ENGINEERING, KALLOOPPARA Page 35


COMPILER LAB

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)

COLLEGE OF ENGINEERING, KALLOOPPARA Page 36


COMPILER LAB

11) 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

COLLEGE OF ENGINEERING, KALLOOPPARA Page 37


COMPILER LAB

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

COLLEGE OF ENGINEERING, KALLOOPPARA Page 38


COMPILER LAB

COLLEGE OF ENGINEERING,
NG, KALLOOPPARA Page 39
COMPILER LAB

COLLEGE OF ENGINEERING, KALLOOPPARA Page 40


COMPILER LAB

COLLEGE OF ENGINEERING, KALLOOPPARA Page 41

You might also like