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

Compiler Design Lab File

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Compiler Design Lab File

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

BHAGWANT INSTITUTE OF TECHNOLOGY

17th Milestone Bijnor- Delhi highway, Distt- Muzaffarnagar


Lecture Plan – ODD Sem 2022-23
Department : CSE & CA

Name Of Faculty: Er. URVASHI Subject Name with Compiler Design


CHAUDHARY Code:
IV/VII
Course : B.Tech Year / Semester
Counselor : Ms.Minakshi HOD MR. AJAY SINGH
No. Of Students : Lab Per week

Lecture Topic Planned Execution Fac. Sign. Hod


No. Date Date Sign.

1. 1.Design and implement a lexical 31.08.23


analyzer for given language using C
and the lexical analyzer should
ignore redundant spaces, tabs and
new lines
2. Implementation of Lexical Analyzer 01.09.23
using Lex Tool
3. Generate YACC specification for a 08.09.23
few syntactic categories. a) Program
to recognize a valid arithmetic -
expression that uses operator +, – , * 15.09.23
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 21.09.23
all states of any given NFA with ε
transition.
5. Write program to convert NFA with 22.09.23
ε transition to NFA without ε
transition.
6. Write program to convert NFA to 28.09.23
DFA
7. Write program to minimize any 29.09.23
given DFA
8. Develop an operator precedence 05.09.23
parser for a given language.
9. Write program to find Simulate First 06.10.23
and Follow of any given grammar.
10. Construct a recursive descent parser 12.10.23
for an expression
11. Construct a Shift Reduce Parser for a 13.10.23
given language
12. Write a program to perform loop 19.10.23
unrolling.
13. Write a program to perform constant 20.10.23
propagation
14. Implement Intermediate code 26.10.23
generation for simple expressions

1) Design and implement a lexical analyzer for given language using C and the lexical
analyzer should ignore redundant spaces, tabs and new lines
Solution:

#include<string.h>
#include<ctype.h>
#include<stdio.h>
void keyword(char str[10])
{
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)
printf("\n%s is a keyword",str);
else
printf("\n%s is an identifier",str);
}
main()
{
FILE *f1,*f2,*f3;
char c,str[10],st1[10];
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;
printf("\nEnter the c program");/*gets(st1);*/
f1=fopen("input","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input","r");
f2=fopen("identifier","w");
f3=fopen("specialchar","w");
while((c=getc(f1))!=EOF){
if(isdigit(c))
{
tokenvalue=c-'0';
c=getc(f1);
while(isdigit(c)){
tokenvalue*=10+c-'0';
c=getc(f1);
}
num[i++]=tokenvalue;
ungetc(c,f1);
}
else if(isalpha(c))
{
putc(c,f2);
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
putc(c,f2);
c=getc(f1);
}
putc(' ',f2);
ungetc(c,f1);
}
else if(c==' '||c=='\t')
printf(" ");
else
if(c=='\n')
lineno++;
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\nThe no's in the program are");
for(j=0;j<i;j++)
printf("%d",num[j]);
printf("\n");
f2=fopen("identifier","r");
k=0;
printf("The keywords and identifiersare:");
while((c=getc(f2))!=EOF){
if(c!=' ')
str[k++]=c;
else
{
str[k]='\0';
keyword(str);
k=0;
}
}
fclose(f2);
f3=fopen("specialchar","r");
printf("\nSpecial characters are");
while((c=getc(f3))!=EOF)
printf("%c",c);
printf("\n");
fclose(f3);
printf("Total no. of lines are:%d",lineno);
}

2) Implementation of Lexical Analyzer using Lex Tool


Solution
//Implementation of Lexical Analyzer using Lex tool
%{
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* {printf("\n%s is a preprocessor directive",yytext);}
int |
float |
char |
double |
while |
for |
struct |
typedef |
do |
if |
break |
continue |
void |
switch |
return |
else |
goto {printf("\n\t%s is a keyword",yytext);}
"/*" {COMMENT=1;}{printf("\n\t %s is a COMMENT",yytext);}
{identifier}\( {if(!COMMENT)printf("\nFUNCTION \n\t%s",yytext);}
\{ {if(!COMMENT)printf("\n BLOCK BEGINS");}
\} {if(!COMMENT)printf("BLOCK ENDS ");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT)printf("\n\t %s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n %s is a NUMBER ",yytext);}
\)(\:)? {if(!COMMENT)printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t %s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
int main(int argc, char **argv)
{
FILE *file;
file=fopen("var.c","r");
if(!file)
{
printf("could not open the file");
exit(0);
}
yyin=file;
yylex();
printf("\n");
return(0);
}
int yywrap()
{
return(1);
}

INPUT:
//var.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
a=1;
b=2;
c=a+b;
printf("Sum:%d",c);
}

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
Solution a) #include “y.tab.h”
%}

%%
“=” {printf(“\n Operator is EQUAL”);}
“+” {printf(“\n Operator is PLUS”);}
“-“ {printf(“\n Operator is MINUS”);}
“/” {printf(“\n Operator is DIVISION”);}
“*” {printf(“\n Operator is MULTIPLICATION”);}

[a-z A-Z]*[0-9]* {
printf(“\n Identifier is %s”,yytext);
return ID;
}
return yytext[0];
\n return 0;
%%

int yywrap()
{
return 1;
}

Program Name : arith_id.y

%{
#include
/* This YYAC program is for recognizing the Expression */
%}
%%
statement: A’=’E
|E{
printf(“\n Valid arithmetic expression”);
$$ = $1;
};

E: E’+’ID
| E’-’ID
| E’*’ID
| E’/’ID
| ID
;
%%
extern FILE *yyin;
main()
{
do
{
yyparse();
}while(!feof(yyin));
}

yyerror(char*s)
{
}

b)
%{
#include
/* This YACC program is for recognising the Expression*/
%}
%token ID INT FLOAT DOUBLE
%%
D;T L
;
L:L,ID
|ID
;
T:INT
|FLOAT
|DOUBLE
;
%%
extern FILE *yyin;
main()
{
do
{
yyparse();
}while(!feof(yyin));
}
yyerror(char*s)
{
}

c) %{
/*YACC program for recognising anb(n>=10)*/
%}
%token A B
%%
stmt:A A A A A A A A A A anb'\n'{printf("\n Valid string");
return 0;
}
;
anb:A anb
|A B
;
%%
main()
{
printf("\nEnter some valid string\n");
yyparse();
}

int yyerror(char*s)
{
printf("\nInvalid string\n");
}
d)
%{
#include "y.tab.h" /*defines the tokens*/
#include ,math.h.
%}
%%
/*To recognise a valid number*/
([0-9] + |([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval = atof(yytext);
return NUMBER;}
/*For log no | Log no (log base 10)*/
log | LOG {return LOG;}

/*For ln no (Natural Log)*/


ln {return nLOG;}

/*For sin angle*/


sin | SIN {return SINE;}

/*For cos angle*/


cos | COS {return COS;}

/*For tan angle*/


tan | TAN {return TAN;}
/*For memory*/
mem {return MEM;}

[\t] ; /*Ignore white spaces*/

/*End of input*/
\$ {return 0;}

/*Catch the remaining and return a single character token to


the parser*/
\n| return yytext[0];
%%

4) Write program to find ε – closure of all states of any given NFA with ε transition.
Solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100

char NFA_FILE[MAX_LEN];
char buffer[MAX_LEN];
int zz = 0;

// Structure to store DFA states and their


// status ( i.e new entry or already present)
struct DFA {
char *states;
int count;
} dfa;

int last_index = 0;
FILE *fp;
int symbols;

/* reset the hash map*/


void reset(int ar[], int size) {
int i;

// reset all the values of


// the mapping array to zero
for (i = 0; i < size; i++) {
ar[i] = 0;
}
}

// Check which States are present in the e-closure


/* map the states of NFA to a hash set*/
void check(int ar[], char S[]) {
int i, j;

// To parse the individual states of NFA


int len = strlen(S);
for (i = 0; i < len; i++) {

// Set hash map for the position


// of the states which is found
j = ((int)(S[i]) - 65);
ar[j]++;
}
}

// To find new Closure States


void state(int ar[], int size, char S[]) {
int j, k = 0;

// Combine multiple states of NFA


// to create new states of DFA
for (j = 0; j < size; j++) {
if (ar[j] != 0)
S[k++] = (char)(65 + j);
}

// mark the end of the state


S[k] = '\0';
}

// To pick the next closure from closure set


int closure(int ar[], int size) {
int i;

// check new closure is present or not


for (i = 0; i < size; i++) {
if (ar[i] == 1)
return i;
}
return (100);
}

// Check new DFA states can be


// entered in DFA table or not
int indexing(struct DFA *dfa) {
int i;
for (i = 0; i < last_index; i++) {
if (dfa[i].count == 0)
return 1;
}
return -1;
}

/* To Display epsilon closure*/


void Display_closure(int states, int closure_ar[],
char *closure_table[],
char *NFA_TABLE[][symbols + 1],
char *DFA_TABLE[][symbols]) {
int i;
for (i = 0; i < states; i++) {
reset(closure_ar, states);
closure_ar[i] = 2;

// to neglect blank entry


if (strcmp(&NFA_TABLE[i][symbols], "-") != 0) {

// copy the NFA transition state to buffer


strcpy(buffer, &NFA_TABLE[i][symbols]);
check(closure_ar, buffer);
int z = closure(closure_ar, states);

// till closure get completely saturated


while (z != 100)
{
if (strcmp(&NFA_TABLE[z][symbols], "-") != 0) {
strcpy(buffer, &NFA_TABLE[z][symbols]);

// call the check function


check(closure_ar, buffer);
}
closure_ar[z]++;
z = closure(closure_ar, states);
}
}

// print the e closure for every states of NFA


printf("\n e-Closure (%c) :\t", (char)(65 + i));

bzero((void *)buffer, MAX_LEN);


state(closure_ar, states, buffer);
strcpy(&closure_table[i], buffer);
printf("%s\n", &closure_table[i]);
}
}
/* To check New States in DFA */
int new_states(struct DFA *dfa, char S[]) {

int i;

// To check the current state is already


// being used as a DFA state or not in
// DFA transition table
for (i = 0; i < last_index; i++) {
if (strcmp(&dfa[i].states, S) == 0)
return 0;
}

// push the new


strcpy(&dfa[last_index++].states, S);

// set the count for new states entered


// to zero
dfa[last_index - 1].count = 0;
return 1;
}

// Transition function from NFA to DFA


// (generally union of closure operation )
void trans(char S[], int M, char *clsr_t[], int st,
char *NFT[][symbols + 1], char TB[]) {
int len = strlen(S);
int i, j, k, g;
int arr[st];
int sz;
reset(arr, st);
char temp[MAX_LEN], temp2[MAX_LEN];
char *buff;

// Transition function from NFA to DFA


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

j = ((int)(S[i] - 65));
strcpy(temp, &NFT[j][M]);

if (strcmp(temp, "-") != 0) {
sz = strlen(temp);
g = 0;

while (g < sz) {


k = ((int)(temp[g] - 65));
strcpy(temp2, &clsr_t[k]);
check(arr, temp2);
g++;
}
}
}

bzero((void *)temp, MAX_LEN);


state(arr, st, temp);
if (temp[0] != '\0') {
strcpy(TB, temp);
} else
strcpy(TB, "-");
}

/* Display DFA transition state table*/


void Display_DFA(int last_index, struct DFA *dfa_states,
char *DFA_TABLE[][symbols]) {
int i, j;
printf("\n\n********************************************************\n\
n");
printf("\t\t DFA TRANSITION STATE TABLE \t\t \n\n");
printf("\n STATES OF DFA :\t\t");

for (i = 1; i < last_index; i++)


printf("%s, ", &dfa_states[i].states);
printf("\n");
printf("\n GIVEN SYMBOLS FOR DFA: \t");

for (i = 0; i < symbols; i++)


printf("%d, ", i);
printf("\n\n");
printf("STATES\t");

for (i = 0; i < symbols; i++)


printf("|%d\t", i);
printf("\n");

// display the DFA transition state table


printf("--------+-----------------------\n");
for (i = 0; i < zz; i++) {
printf("%s\t", &dfa_states[i + 1].states);
for (j = 0; j < symbols; j++) {
printf("|%s \t", &DFA_TABLE[i][j]);
}
printf("\n");
}
}
// Driver Code
int main() {
int i, j, states;
char T_buf[MAX_LEN];

// creating an array dfa structures


struct DFA *dfa_states = malloc(MAX_LEN * (sizeof(dfa)));
states = 6, symbols = 2;

printf("\n STATES OF NFA :\t\t");


for (i = 0; i < states; i++)

printf("%c, ", (char)(65 + i));


printf("\n");
printf("\n GIVEN SYMBOLS FOR NFA: \t");

for (i = 0; i < symbols; i++)

printf("%d, ", i);


printf("eps");
printf("\n\n");
char *NFA_TABLE[states][symbols + 1];

// Hard coded input for NFA table


char *DFA_TABLE[MAX_LEN][symbols];
strcpy(&NFA_TABLE[0][0], "FC");
strcpy(&NFA_TABLE[0][1], "-");
strcpy(&NFA_TABLE[0][2], "BF");
strcpy(&NFA_TABLE[1][0], "-");
strcpy(&NFA_TABLE[1][1], "C");
strcpy(&NFA_TABLE[1][2], "-");
strcpy(&NFA_TABLE[2][0], "-");
strcpy(&NFA_TABLE[2][1], "-");
strcpy(&NFA_TABLE[2][2], "D");
strcpy(&NFA_TABLE[3][0], "E");
strcpy(&NFA_TABLE[3][1], "A");
strcpy(&NFA_TABLE[3][2], "-");
strcpy(&NFA_TABLE[4][0], "A");
strcpy(&NFA_TABLE[4][1], "-");
strcpy(&NFA_TABLE[4][2], "BF");
strcpy(&NFA_TABLE[5][0], "-");
strcpy(&NFA_TABLE[5][1], "-");
strcpy(&NFA_TABLE[5][2], "-");
printf("\n NFA STATE TRANSITION TABLE \n\n\n");
printf("STATES\t");

for (i = 0; i < symbols; i++)


printf("|%d\t", i);
printf("eps\n");

// Displaying the matrix of NFA transition table


printf("--------+------------------------------------\n");
for (i = 0; i < states; i++) {
printf("%c\t", (char)(65 + i));

for (j = 0; j <= symbols; j++) {


printf("|%s \t", &NFA_TABLE[i][j]);
}
printf("\n");
}
int closure_ar[states];
char *closure_table[states];

Display_closure(states, closure_ar, closure_table, NFA_TABLE,


DFA_TABLE);
strcpy(&dfa_states[last_index++].states, "-");

dfa_states[last_index - 1].count = 1;
bzero((void *)buffer, MAX_LEN);

strcpy(buffer, &closure_table[0]);
strcpy(&dfa_states[last_index++].states, buffer);

int Sm = 1, ind = 1;
int start_index = 1;

// Filling up the DFA table with transition values


// Till new states can be entered in DFA table
while (ind != -1) {
dfa_states[start_index].count = 1;
Sm = 0;
for (i = 0; i < symbols; i++) {

trans(buffer, i, closure_table, states, NFA_TABLE, T_buf);

// storing the new DFA state in buffer


strcpy(&DFA_TABLE[zz][i], T_buf);

// parameter to control new states


Sm = Sm + new_states(dfa_states, T_buf);
}
ind = indexing(dfa_states);
if (ind != -1)
strcpy(buffer, &dfa_states[++start_index].states);
zz++;
}
// display the DFA TABLE
Display_DFA(last_index, dfa_states, DFA_TABLE);

return 0;
}

5) Write program to convert NFA with ε transition to NFA without ε transition.


Solution-
#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,finalstate[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");
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("\n States :" );
for(i=1;i<=nostate;i++)
print_e_closure(i);

printf("\nTnransitions 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("\n Final states:");
findfinalstate();

void findclosure(int x,int sta)


{
struct node *temp;
int i;
if(buffer[x])
return;
e_closure[sta][c++]=x;
buffer[x]=1;
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;
j++;
}
}
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;
printf("{");
for(j=0;e_closure[i][j]!=0;j++)
printf("q%d,",e_closure[i][j]);
printf("}\t");
}

6)Write program to convert NFA to DFA


#include<stdio.h>

int Fa[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;

int search(int search_var)


{

int i;
for(i=0;i<no_stat;i++)
if(search_var == states[1][i])
return 1;
return 0;
}
int sort(int *arr,int count)
{
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;
}
}
}
return 0;
}

int checkcon(int *arr,int *count) //for doing this {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++;
}
//right shift from ith postion (c-2) th time
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;
return 0;
}

int remove_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;
return 0;
}

int check(int i ,int j,int c,int *name)///for checking is this a new state?
{
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;
return 1;
}
}
return 0;
}

int trans(int i ,int j,int t,int c,int *count,int *arr)//transition o/p for
particular i/p on 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)++;
}
}
return 0;
}

int nfa2dfa(int start,int end)


{
int j,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;
}
}
}

}
return 0;
}
int main()
{

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\nDFA IS : \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("Total Number Of State Is : %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();
return 0;
}

7) Write program to minimize any given DFA


Solution
#include<stdio.h>
#include<string.h>
#define STATES 50
struct Dstate
{
char name;
char StateString[STATES+1];
char trans[10];
int is_final;
}
Dstates[50];
struct tran
{
char sym;
int tostates[50];
int notran;
};
struct state
{
int no;
struct tran tranlist[50];
};
int stackA[100],stackB[100],c[100],Cptr=-1,Aptr=-1,Bptr=-1;
struct state States[10];
char temp[STATES+1],inp[10];
int nos,noi,nof,j,k,nods=-1;

void pushA(int z)
{
stackA[++Aptr]=z;
}
void pushB(int z)
{
stackB[++Bptr]=z;
}
int popA()
{
return stackA[Aptr--];
}
void copy(int i)
{
char temp[STATES+1]=" ";
int k=0;
Bptr=-1;
strcpy(temp,Dstates[i].StateString);
while(temp[k]!='\0')
{
pushB(temp[k]-'0');
k++;
}
}
int popB()
{
return stackB[Bptr--];
}
int peekA()
{
return stackA[Aptr];
}
int peekB()
{
return stackA[Bptr];
}
int seek(int arr[],int ptr,int s)
{
int i;
for(i=0;i<=ptr;i++)
{
if(s==arr[i])
return 1;
}
return 0;
}
void sort()
{
int i,j,temp;
for(i=0;i
{
for(j=0;j<(Bptr-i);j++)
{
if(stackB[j]>stackB[j+1])
{
temp=stackB[j];
stackB[j]=stackB[j+1];
stackB[j+1]=temp;
}
}
}
}

void tostring()
{
int i=0;
sort();
for(i=0;i<=Bptr;i++)
{
temp[i]=stackB[i]+'0';
}
temp[i]='\0';
}
void display_DTran()
{
int i,j;
printf("\n\t\t DFA transition table");
printf("\n\t\t ---------------------------------------------- ");
printf("\n States \tString \tInputs\n");
for(i=0;i<noi;i++)
{
printf("\t %c",inp[i]);
}
printf("\n\t ------------------------------------------------- ");
for(i=0;i<nods;i++)
{
if(Dstates[i].is_final==0)
printf("\n%c",Dstates[i].name);
else
printf("\n*%c",Dstates[i].name);
printf("\t%s",Dstates[i].StateString);
for(j=0;j<noi;j++)
{
printf("\t%c",Dstates[i].trans[j]);
}
}
printf("\n");
}

void move(int st,int j)


{
int ctr=0;
while(ctr<States[st].tranlist[j].notran)
{
pushA(States[st].tranlist[j].tostates[ctr++]);
}
}

void lambda_closure(int st)


{
int ctr=0,in_state=st,curst=st,chk;
while(Aptr!=-1)
{
curst=popA();
ctr=0;
in_state=curst;
while(ctr<=States[curst].tranlist[noi].notran)
{
chk=seek(stackB,Bptr,in_state);
if(chk==0)
pushB(in_state);
in_state=States[curst].tranlist[noi].tostates[ctr++];
chk=seek(stackA,Aptr,in_state);
if(chk==0 && ctr<=States[curst].tranlist[noi].notran)
pushA(in_state);
}
}
}
void main()
{
int i,final[20],start,fin=0;
char c,ans,st[20];
printf("\n Enter no of states in NFA:");
scanf("%d",&nos);
for(i=0;i<nos;i++)
{
States[i].no=i;
}
printf("\n Enter the start states:");
scanf("%d",&start);
printf("Enter the no of final states:");
scanf("%d",&nof);
printf("Enter the final states:\n");
for(i=0;i<nof;i++)
scanf("%d",&final[i]);
printf("\n Enter the no of input symbols:");
scanf("%d",&noi);
c=getchar();
printf("Enter the input symbols:\n");
for(i=0;i<noi;i++)
{
scanf("%c",&inp[i]);
c=getchar();
}
//g1inp[i]='e';
inp=[i]=’e’;
printf("\n Enter the transitions:(-1 to stop)\n");
for(i=0;i<nos;i++)
{
for(j=0;j<=noi;j++)
{
States[i].tranlist[j].sym=inp[j];
k=0;
ans='y';
while(ans=='y')
{
printf("move(%d,%c);",i,inp[j]);
scanf("%d",&States[i].tranlist[j].tostates[k++]);
if((States[i].tranlist[j].tostates[k-1]==-1))
{
k--;
ans='n';
break;
}
}
States[i].tranlist[j].notran=k;
}
}
i=0;nods=0,fin=0;
pushA(start);
lambda_closure(peekA());
tostring();
Dstates[nods].name='A';
nods++;
strcpy(Dstates[0].StateString,temp);
while(i<nods)
{
for(j=0;j<noi;j++)
{
fin=0;
copy(i);
while(Bptr!=-1)
{
move(popB(),j);
}
while(Aptr!=-1)
lambda_closure(peekA());
tostring();
for(k=0;k<nods;k++)
{
if((strcmp(temp,Dstates[k].StateString)==0))
{
Dstates[i].trans[j]=Dstates[k].name;
break;
}
}
if(k==nods)
{
nods++;
for(k=0;k<nof;k++)
{
fin=seek(stackB,Bptr,final[k]);
if(fin==1)
{
Dstates[nods-1].is_final=1;
break;
}
}
strcpy(Dstates[nods-1].StateString,temp);
Dstates[nods-1].name='A'+nods-1;
Dstates[i].trans[j]=Dstates[nods-1].name;
}
}
i++;
}
display_DTran();
}

8) Develop an operator precedence parser for a given language.

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

// function f to exit from the loop


// if given condition is not true
void f()
{
printf("Not operator grammar");
exit(0);
}

void main()
{
char grm[20][20], c;

// Here using flag variable,


// considering grammar is not operator grammar
int i, n, j = 2, flag = 0;

// taking number of productions from user


scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%s", grm[i]);

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


c = grm[i][2];

while (c != '&#092;&#048;') {

if (grm[i][3] == '+' || grm[i][3] == '-'


|| grm[i][3] == '*' || grm[i][3] == '/')
flag = 1;

else {

flag = 0;
f();
}

if (c == '$') {
flag = 0;
f();
}

c = grm[i][++j];
}
}

if (flag == 1)
printf("Operator grammar");
}

9) Develop an operator precedence parser for a given language.


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

// function f to exit from the loop


// if given condition is not true
void f()
{
printf("Not operator grammar");
exit(0);
}

void main()
{
char grm[20][20], c;

// Here using flag variable,


// considering grammar is not operator grammar
int i, n, j = 2, flag = 0;

// taking number of productions from user


scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%s", grm[i]);
for (i = 0; i < n; i++) {
c = grm[i][2];

while (c != '&#092;&#048;') {

if (grm[i][3] == '+' || grm[i][3] == '-'


|| grm[i][3] == '*' || grm[i][3] == '/')

flag = 1;

else {

flag = 0;
f();
}

if (c == '$') {
flag = 0;
f();
}

c = grm[i][++j];
}
}

if (flag == 1)
printf("Operator grammar");
}

10) Construct a recursive descent parser for an expression


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

#define SUCCESS 1
#define FAILED 0

// Function prototypes
int E(), Edash(), T(), Tdash(), F();

const char *cursor;


char string[64];

int main() {
puts("Enter the string");
scanf("%s", string); // Read input from the user
cursor = string;
puts("");
puts("Input Action");
puts("--------------------------------");

// Call the starting non-terminal E


if (E() && *cursor == '\0') { // If parsing is successful and the
cursor has reached the end
puts("--------------------------------");
puts("String is successfully parsed");
return 0;
}
else {
puts("--------------------------------");
puts("Error in parsing String");
return 1;
}
}

// Grammar rule: E -> T E'


int E() {
printf("%-16s E -> T E'\n", cursor);
if (T()) { // Call non-terminal T
if (Edash()) // Call non-terminal E'
return SUCCESS;
else
return FAILED;
}
else
return FAILED;
}

// Grammar rule: E' -> + T E' | $


int Edash() {
if (*cursor == '+') {
printf("%-16s E' -> + T E'\n", cursor);
cursor++;
if (T()) { // Call non-terminal T
if (Edash()) // Call non-terminal E'
return SUCCESS;
else
return FAILED;
}
else
return FAILED;
}
else {
printf("%-16s E' -> $\n", cursor);
return SUCCESS;
}
}

// Grammar rule: T -> F T'


int T() {
printf("%-16s T -> F T'\n", cursor);
if (F()) { // Call non-terminal F
if (Tdash()) // Call non-terminal T'
return SUCCESS;
else
return FAILED;
}
else
return FAILED;
}

// Grammar rule: T' -> * F T' | $


int Tdash() {
if (*cursor == '*') {
printf("%-16s T' -> * F T'\n", cursor);
cursor++;
if (F()) { // Call non-terminal F
if (Tdash()) // Call non-terminal T'
return SUCCESS;
else
return FAILED;
}
else
return FAILED;
}
else {
printf("%-16s T' -> $\n", cursor);
return SUCCESS;
}
}

// Grammar rule: F -> ( E ) | i


int F() {
if (*cursor == '(') {
printf("%-16s F -> ( E )\n", cursor);
cursor++;
if (E()) { // Call non-terminal E
if (*cursor == ')') {
cursor++;
return SUCCESS;
}
else
return FAILED;
}
else
return FAILED;
}
else if (*cursor == 'i') {
printf("%-16s F -> i\n", cursor);
cursor++;
return SUCCESS;
}
else
return FAILED;
}
11) Construct a Shift Reduce Parser for a given language
Solution
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

//Global Variables
int z = 0, i = 0, j = 0, c = 0;

// Modify array size to increase


// length of string to be parsed
char a[16], ac[20], stk[15], act[10];

// This Function will check whether


// the stack contain a production rule
// which is to be Reduce.
// Rules can be E->2E2 , E->3E3 , E->4
void check()
{
// Copying string to be printed as action
strcpy(ac,"REDUCE TO E -> ");

// c=length of input string


for(z = 0; z < c; z++)
{
//checking for producing rule E->4
if(stk[z] == '4')
{
printf("%s4", ac);
stk[z] = 'E';
stk[z + 1] = '\0';

//printing action
printf("\n$%s\t%s$\t", stk, a);
}
}
for(z = 0; z < c - 2; z++)
{
//checking for another production
if(stk[z] == '2' && stk[z + 1] == 'E' &&
stk[z + 2] == '2')
{
printf("%s2E2", ac);
stk[z] = 'E';
stk[z + 1] = '\0';
stk[z + 2] = '\0';
printf("\n$%s\t%s$\t", stk, a);
i = i - 2;
}

for(z=0; z<c-2; z++)


{
//checking for E->3E3
if(stk[z] == '3' && stk[z + 1] == 'E' &&
stk[z + 2] == '3')
{
printf("%s3E3", ac);
stk[z]='E';
stk[z + 1]='\0';
stk[z + 1]='\0';
printf("\n$%s\t%s$\t", stk, a);
i = i - 2;
}
}
return ; //return to main
}

//Driver Function
int main()
{
printf("GRAMMAR is -\nE->2E2 \nE->3E3 \nE->4\n");

// a is input string
strcpy(a,"32423");

// strlen(a) will return the length of a to c


c=strlen(a);

// "SHIFT" is copied to act to be printed


strcpy(act,"SHIFT");

// This will print Labels (column name)


printf("\nstack \t input \t action");

// This will print the initial


// values of stack and input
printf("\n$\t%s$\t", a);

// This will Run upto length of input string


for(i = 0; j < c; i++, j++)
{
// Printing action
printf("%s", act);

// Pushing into stack


stk[i] = a[j];
stk[i + 1] = '\0';

// Moving the pointer


a[j]=' ';

// Printing action
printf("\n$%s\t%s$\t", stk, a);

// Call check function ..which will


// check the stack whether its contain
// any production or not
check();
}

// Rechecking last time if contain


// any valid production then it will
// replace otherwise invalid
check();

// if top of the stack is E(starting symbol)


// then it will accept the input
if(stk[0] == 'E' && stk[1] == '\0')
printf("Accept\n");
else //else reject
printf("Reject\n");
}
12) Write a program to perform constant propagation
Solution
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<conio.h>
void input();
void output();
void change(int p,char *res);
void constant();
struct expr
{
char op[2],op1[5],op2[5],res[5];
int flag;
}arr[10];
int n;
void main()
{
clrscr();
input();
constant();
output();
getch();
}
void input()
{
int i;
printf("\n\nEnter the maximum number of expressions : ");
scanf("%d",&n);
printf("\nEnter the input : \n");
for(i=0;i<n;i++)
{
scanf("%s",arr[i].op);
scanf("%s",arr[i].op1);
scanf("%s",arr[i].op2);
scanf("%s",arr[i].res);
arr[i].flag=0;
}
}
void constant()
{
int i;
int op1,op2,res;
char op,res1[5];
for(i=0;i<n;i++)
{
if(isdigit(arr[i].op1[0]) && isdigit(arr[i].op2[0]) || strcmp(arr[i].op,"=")==0) /*if both digits,
store them in variables*/
{
op1=atoi(arr[i].op1);
op2=atoi(arr[i].op2);
op=arr[i].op[0];
switch(op)
{
case '+':
res=op1+op2;
break;
case '-':
res=op1-op2;
break;
case '*':
res=op1*op2;
break;
case '/':
res=op1/op2;
break;
case '=':
res=op1;
break;
}
sprintf(res1,"%d",res);
arr[i].flag=1; /*eliminate expr and replace any operand below that uses result of this expr */
change(i,res1);
}
}
}
void output()
{
int i=0;
printf("\nOptimized code is : ");
for(i=0;i<n;i++)
{
if(!arr[i].flag)
{
printf("\n%s %s %s %s",arr[i].op,arr[i].op1,arr[i].op2,arr[i].res);
}
}
}
void change(int p,char *res)
{
int i;
for(i=p+1;i<n;i++)
{
if(strcmp(arr[p].res,arr[i].op1)==0)
strcpy(arr[i].op1,res);
else if(strcmp(arr[p].res,arr[i].op2)==0)
strcpy(arr[i].op2,res);
}
}

13) Write a program to perform constant propagation


Solution
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<conio.h>
void input();
void output();
void change(int p,char *res);
void constant();
struct expr
{
char op[2],op1[5],op2[5],res[5];
int flag;
}arr[10];
int n;
void main()
{
clrscr();
input();
constant();
output();
getch();
}
void input()
{
int i;
printf("\n\nEnter the maximum number of expressions : ");
scanf("%d",&n);
printf("\nEnter the input : \n");
for(i=0;i<n;i++)
{
scanf("%s",arr[i].op);
scanf("%s",arr[i].op1);
scanf("%s",arr[i].op2);
scanf("%s",arr[i].res);
arr[i].flag=0;
}
}
void constant()
{
int i;
int op1,op2,res;
char op,res1[5];
for(i=0;i<n;i++)
{
if(isdigit(arr[i].op1[0]) && isdigit(arr[i].op2[0]) || strcmp(arr[i].op,"=")==0) /*if both digits,
store them in variables*/
{
op1=atoi(arr[i].op1);
op2=atoi(arr[i].op2);
op=arr[i].op[0];
switch(op)
{
case '+':
res=op1+op2;
break;
case '-':
res=op1-op2;
break;
case '*':
res=op1*op2;
break;
case '/':
res=op1/op2;
break;
case '=':
res=op1;
break;
}
sprintf(res1,"%d",res);
arr[i].flag=1; /*eliminate expr and replace any operand below that uses result of this expr */
change(i,res1);
}
}
}
void output()
{
int i=0;
printf("\nOptimized code is : ");
for(i=0;i<n;i++)
{
if(!arr[i].flag)
{
printf("\n%s %s %s %s",arr[i].op,arr[i].op1,arr[i].op2,arr[i].res);
}
}
}
void change(int p,char *res)
{
int i;
for(i=p+1;i<n;i++)
{
if(strcmp(arr[p].res,arr[i].op1)==0)
strcpy(arr[i].op1,res);
else if(strcmp(arr[p].res,arr[i].op2)==0)
strcpy(arr[i].op2,res);
}
14) Implement Intermediate code generation for simple expressions

#include<stdio.h>

#include<conio.h>

#include<string.h>

int i=1,j=0,no=0,tmpch=90;

char str[100],left[15],right[15];

void findopr();

void explore();

void fleft(int);

void fright(int);

struct exp

int pos;

char op;

}k[15];

void main()

printf("\t\tINTERMEDIATE CODE GENERATION\n\n");

printf("Enter the Expression :");

scanf("%s",str);

printf("The intermediate code:\n");

findopr();

explore();

void findopr()
{

for(i=0;str[i]!='\0';i++)

if(str[i]==':')

k[j].pos=i;

k[j++].op=':';

for(i=0;str[i]!='\0';i++)

if(str[i]=='/')

k[j].pos=i;

k[j++].op='/';

for(i=0;str[i]!='\0';i++)

if(str[i]=='*')

k[j].pos=i;

k[j++].op='*';

for(i=0;str[i]!='\0';i++)

if(str[i]=='+')

k[j].pos=i;

k[j++].op='+';

}
for(i=0;str[i]!='\0';i++)

if(str[i]=='-')

k[j].pos=i;

k[j++].op='-';

void explore()

i=1;

while(k[i].op!='\0')

fleft(k[i].pos);

fright(k[i].pos);

str[k[i].pos]=tmpch--;

printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right);

printf("\n");

i++;

fright(-1);

if(no==0)

fleft(strlen(str));

printf("\t%s := %s",right,left);

getch();
exit(0);

printf("\t%s := %c",right,str[k[--i].pos]);

getch();

void fleft(int x)

int w=0,flag=0;

x--;

while(x!= -1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!='-'&&str[x]!


='/'&&str[x]!=':')

if(str[x]!='$'&& flag==0)

left[w++]=str[x];

left[w]='\0';

str[x]='$';

flag=1;

x--;

void fright(int x)

int w=0,flag=0;

x++;
while(x!= -1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!=':'&&str[x]!
='-'&&str[x]!='/')

if(str[x]!='$'&& flag==0)

right[w++]=str[x];

right[w]='\0';

str[x]='$';

flag=1;

x++;

You might also like