Compilers PaperI Section I

85
THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI) 1 PAPER I SECTION I COMPILERS INDEX No. Topic Page No. Date Sign 1 Right Linear to Left Linear Grammars 04 08/08/05 2 NFA to DFA 09 23/08/05 3 Removal of Empty State ( ε λ ) 17 30/08/05 4 Minimizing Automata 24 05/09/05 5 Warshall’s Algorithm 38 12/09/05 6 Simple Precedence matrix (SPM) 42 19/09/05 7 Parsing using SPM 49 04/10/05 8 Operator Precedence Matrix (OPM) 57 10/10/05 9 Linearizing a given SPM 71 18/10/05 10 Parsing using Simple Precedence functions 77 25/10/05

description

compilers question paper

Transcript of Compilers PaperI Section I

Page 1: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

1

PAPER I SECTION I COMPILERS

INDEX

No. Topic Page No. Date Sign

1 Right Linear to Left Linear Grammars 04 08/08/05

2 NFA to DFA 09 23/08/05

3 Removal of Empty State ( ελ ) 17 30/08/05

4 Minimizing Automata 24 05/09/05

5 Warshall’s Algorithm 38 12/09/05

6 Simple Precedence matrix (SPM) 42 19/09/05

7 Parsing using SPM 49 04/10/05

8 Operator Precedence Matrix (OPM) 57 10/10/05

9 Linearizing a given SPM 71 18/10/05

10 Parsing using Simple Precedence functions 77 25/10/05

Page 2: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

2

PAPER I SECTION II COMPILERS

INDEX

No. Topic Page No. Date Sign

1 Three-Address code 86 21/11/05

2 Quadruple representation 92 28/11/05

3 Triple Representation 99 06/12/05

4 Indirect Triple representation 106 12/12/05

5 Directed Acyclic Graph (DAG) 113 26/12/05

6 Construct Natural Loop 117 09/01/06

7 Depth First Spanning Tree 121 16/01/06

8 Code Generation 126 24/01/06

9 Postfix to Infix 134 31/01/06

10 Infix to Postfix 137 06/02/06

Page 3: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

3

PAPER II DIGITAL SIGNAL PROCESSING

INDEX

No. Topic Page No. Date Sign

1 Basic Signals 141 17/08/05

2 Frequency, Magnitude and Phase Response 146 24/08/05

3 Z-Transform 148 31/08/05

4 N-DFT 152 07/09/05

5 N-DFT using Twiddle Matrix 155 14/09/05

6 Linear Convolution 157 21/09/05

7 Circular Convolution 159 28/09/05

8 Low-pass FIR filter 162 12/10/05

9 High-pass FIR filter 170 19/10/05

10 High-pass and Low-pass FIR filter on various inputs 177 26/10/05

11 Band-pass and Band-stop FIR filters 183 23/11/05

12 Analog and Digital Filters 185 30/11/05

13 Radix2 DIF FFT Algorithm 191 07/12/05

14 Radix2 DIT FFT Algorithm 194 14/12/05

15 Power Spectral Density 197 21/12/05

16 Remez Exchange Algorithm 200 28/12/05

17 Two-Dimensional Linear Convolution 202 04/01/06

18 Two-Dimensional Cross-correlation and auto-correlation 204 18/01/06

19 Stability 206 25/01/06

20 Bit-reversal Algorithm 208 01/02/06

Page 4: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

4

Practical 01 Write a C-Program to convert a right linear grammar to left linear grammar. Make a provision for 10 productions. You may use the data structure of your choice. Input the following right linear grammar and obtain an output in form of a production table. Grammar G : {N,T,P,S} Productions P:

S a S bU S bR R U R abaU S λ U b U As S λλ Description: Left Linear: A grammar G is said to be left-recursive if it has a non-terminal A such that there is a derivation α⇒ AA for some α . A left-recursive grammar can cause a top-down parser to go into an infinite loop. Right Linear: A grammar G is said to be Right-recursive if it has a non-terminal A such that there is a derivation α⇒ AA for some α . Algorithm :-

Begin 1. Take input of grammar definition. 2. Take input of productions rules. 3. Using following rules convert the Right Linear Grammar to Left Linear

Grammar S is starting symbol then we have λ→S in Left Linear Grammar If bU → then we have bUX '' → in Left Linear Grammar.

If abaUR → then we have '''''''' RU,aYU,bXY,aRX →→→→ in Left

Linear Grammar. 4. Display Left Linear Grammar definition and production rules.

End

Page 5: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

5

Code :- char prod[10][10],NT[100],T[100],RLG[100]; int totalPR=0,posOfProd[100]; void extractGrammarSymbols(); void inputProdRules(); void displayLLGrammarDefination(); void generateLLGrammar(); int charindex(char[], char); void main() {

clrscr();

printf("Enter Right Linear Grammar : "); gets(RLG);

extractGrammarSymbols(); inputProdRules();

displayLLGrammarDefination(); generateLLGrammar();

getch();

} //To extract the Grammar Symbols from the Productions void extractGrammarSymbols() {

int i=2,j=0;

while(RLG[i] != '}') NT[j++]=RLG[i++]; // To Extract NT's From Grammar Definition NT[j]='\0'; i=i+3; j=0; while(RLG[i] != '}') T[j++]=RLG[i++]; // To Extract T's From Grammar Definition T[j]='\0';

} //To input the Production Rules void inputProdRules() {

int i=0,j=0; char hasNext='Y'; while(NT[i] != '\0') // To Take Input Of Production Rules {

printf("\n\nEnter Rules For %c \n",NT[i]); while(hasNext=='y' || hasNext=='Y' ) { printf("\n%c -> ",NT[i]); scanf("%s",prod[j]); totalPR++; printf("Any More Production Rule For %c (Y/N) : ",NT[i]); hasNext=getche();

Page 6: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

6

j++; } posOfProd[i]=j; hasNext='Y'; i++;

} posOfProd[i]='\0';

} //To display the Left Linear Definition void displayLLGrammarDefination() {

int i,j; printf("\n\n Left Linear Grammar is : ({"); for(i=0;i<strlen(NT);i++)

printf("%c'",NT[i]); j=0; for(i=0;i<totalPR;i++)

if(j<strlen(prod[i])) j=strlen(prod[i]);

for(i=0;i<j-1;i++) printf("%c'",(char)88+i);

printf("},{"); for(i=0;i<strlen(T);i++)

printf("%c'",T[i]); printf("},%c',%c')",RLG[strlen(RLG)-4],RLG[strlen(RLG)-2]);

} //To generate the Left Linear Grammar void generateLLGrammar() {

int i,j=0,k=0,temp,exChar=88,singExChar=90;

printf("\n Where P'is : \n"); temp=posOfProd[j]; //Print starting position of production printf("\t%c'->%c\t\t",RLG[strlen(RLG)-2],(char)238); for(i=0;i<totalPR;++i) {

if(temp == i) //Increment per total NT temp=posOfProd[++j];

if(charindex(NT,prod[i][strlen(prod[i])-1])!=-1) // Production have NT {

if(strlen(prod[i])==1) printf("%c'->%c'\t\t",prod[i][0],NT[j]);

else if(strlen(prod[i])>2) //Production have composite state {

//For each letter of composite state for(k=0;k<strlen(prod[i])-1;k++) {

if(k==0) //First letter of composite state printf("%c'->%c'%c\t\t",(char)exChar

,NT[j],prod[i][k]); //Last letter of composite state else if(k==strlen(prod[i])-2)

Page 7: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

7

printf("%c'->%c'%c\t\t" ,prod[i][strlen(prod[i])-1], ,(char)--exChar,prod[i][k]); else//Middle letters of composite state printf("%c'->%c'%c\t\t",(char)exChar ,(char)exChar-1,prod[i][k]); exChar++; } exChar=88; } else //Production have no composite state printf("%c'->%c'%c\t\t",prod[i][strlen(prod[i])-1] ,NT[j],prod[i][0]); } else //Production have no NT in printf("%c'->%c'%s\t\t",(char)singExChar,NT[j],prod[i]); } } //Returns index of given char in string int charindex(char str[],char c) { int i; for(i=0;i<strlen(str);i++) if(str[i]==c) return(i); return(-1); }

Page 8: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

8

Output:- Enter Right Linear Grammar : ({SRU},{ab},P,S) Enter Rules For S : S -> a Any More Production Rule For S (Y/N) : y S -> bU Any More Production Rule For S (Y/N) : y S -> bR Any More Production Rule For S (Y/N) : n Enter Rules For R : R -> abaU Any More Production Rule For R (Y/N) : y R -> U Any More Production Rule For R (Y/N) : n Enter Rules For U : U -> b Any More Production Rule For U (Y/N) : y U -> aS Any More Production Rule For U (Y/N) : n Left Linear Grammar is : ({S'R'U'X'Y'Z'},{a'b'},P',S') Where P'is : S'->ε Z'->S'a U'->S'b R'->S'b X'->R'a Y'->X'b U'->Y'a U'->R' Z'->U'b S'->U'a Declared Variables:- char prod[10][10] - To store the productions in the prod array char NT[100] - To store the Non-Terminal in the NT array char T[100] - To store the Terminal in the T array char RLG[100] - To store the Right Linear Grammar in RLG array int totalPR - To count the total number of productions int posOfProd[100] - To store the position of the productions Declared Functions:- void extractGrammarSymbols() - To extract the Grammar Symbols from the Productions void inputProdRules() - To input the Production Rules void displayLLGrammarDefination() - To display the Left Linear Definition void generateLLGrammar() - To generate the Left Linear Grammar int charindex(char[], char) - Returns index of given char in string

Page 9: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

9

Practical 02 Write a C-Program to convert a NFA to DFA. Represent a transaction as a node, the node being an array of three elements start state (Type int/char), destination state (type int/char) and transition symbol (Type char. Create a linked-list of these nodes. Input the set of transitions of the NFA

Input State a b

A B C B B D C B C D B E E B C

Obtain its DFA and display it suitable form. Algorithm :-

Begin 1. Take input of NFA table 2. Iterate through all the values of NFA table and find the composite state like

(Q,S) in following input 3. If new composite state is found , insert it into DFA table as a new state and

refine each state name 4. Display DFA table

End

Page 10: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

10

Code:- #include <stdio.h> #define STATES 10 #define SYMBOLS 10 int i=0,j=0,count,N_NFA_states, N_DFA_states, N_symbol; char c, G[100], * NFAtab[STATES][SYMBOLS], * DFAtab[STATES][SYMBOLS], * DFAStates[50], * symbols[50],NFA_finals[STATES]; void input_NFA_table(); int isNewState(char *); void mergeNewState(char *); void refine(); void display_DFA_table(); void main() { i=0;j=0;count=0; clrscr(); input_NFA_table(); for(i=0;i<N_DFA_states;i++) { for(j=0;j<N_symbol;j++) {

if(strlen(DFAtab[i][j]) > 1 && isNewState(DFAtab[i][j]) != 0)

mergeNewState(DFAtab[i][j]); } } display_DFA_table(); } //Check whether new state found int isNewState(char * c) { int l=0; char s; for(l=0;l<N_DFA_states;l++) if( strcmp(DFAStates[l],c) == 0) return 0; return 1; } //Merging the compound state void mergeNewState(char * chr) { int j,i; char str[100][100]; DFAStates[N_DFA_states]=chr; for(i=0;i<N_symbol;i++) str[count+i][0]='\0';

Page 11: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

11

for(i=0;i<N_NFA_states;i++) { if(strchr(chr,DFAStates[i][0])) { for(j=0;j<N_symbol;j++) { DFAtab[N_DFA_states][j]= (char *)strcat(str[count+j],DFAtab[i][j]); } } } // Each newly formed state goes in refine method refine(); count=N_symbol+count; N_DFA_states++; } // Sorting and Removing Duplicate in compound state void refine() { int i,j,k,m,n,z; char large,arr[10],temp; for(i=0;i<N_symbol;i++) { if((strlen(DFAtab[N_DFA_states][i]))>1) { for(j=0;j<=(strlen(DFAtab[N_DFA_states][i])-2);j++) { large=DFAtab[N_DFA_states][i][j]; for(z=j+1;z<strlen(DFAtab[N_DFA_states][i]);z++) { if(large>DFAtab[N_DFA_states][i][z]) { temp=DFAtab[N_DFA_states][i][z]; DFAtab[N_DFA_states][i][z]=large; DFAtab[N_DFA_states][i][j]=temp; } } } DFAtab[N_DFA_states][i][z]='\0'; n=0; for(m=0;m<strlen(DFAtab[N_DFA_states][i]);m++) { if(DFAtab[N_DFA_states][i][m]!= DFAtab[N_DFA_states][i][m+1]) { arr[n]=DFAtab[N_DFA_states][i][m]; n++; } } arr[n]='\0'; for(m=0;m<strlen(arr);m++) { DFAtab[N_DFA_states][i][m]=arr[m]; }

Page 12: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

12

DFAtab[N_DFA_states][i][m]='\0'; } } } void input_NFA_table() { int i=0,j=0,k=0,ct=10; char c,str[100][100]; printf("Enter Grammar Definition : "); gets(G); N_NFA_states=-1; N_symbol=-1; j=2; i=0; c=' '; //To Extract States From Grammar Definition while(c!='}') { c=G[j]; if(c!=',') { str[ct][0]=G[j]; str[ct][1]='\0'; DFAStates[i++]=str[ct++]; N_NFA_states++; } j++; } //To Extract Symbols From Grammar Definition j=strchr(G,'}')-(int)G+3; i=0; c=' '; while(c!='}') { c=G[j]; if(c!=',') { str[ct][0]=G[j]; str[ct][1]='\0'; symbols[i++]=str[ct++]; N_symbol++; } j++; } //To Extract Final States From Grammar Definition j=strlen(G)-2; i=0; c=' '; while(c!='{') { c=G[j]; if(c!=',') {

Page 13: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

13

c=G[j]; NFA_finals[i++]=c; } j--; } NFA_finals[--i]='\0'; N_DFA_states=N_NFA_states; //Taking Input As Table i=0; printf("\nInput NFA Table : "); printf("\n\n\t %s",symbols[i++]); while(i<N_symbol) { printf("\t\t%s",symbols[i++]); } printf("\n\t%c",214); for(i=0;i<N_symbol*15;i++) { printf("%c",196); } ct++; for(i=0;i<N_NFA_states;i++) { printf("\n %s \t%c ",DFAStates[i],186); for(j=0;j<N_symbol;j++) { k=0; while(c!=13) { str[ct][k]=getch(); if(str[ct][k]!=13) printf("%c",str[ct][k]); c=str[ct][k++]; if(c==',') k--; } c='\0'; str[ct][k-1]=c; DFAtab[i][j]=str[ct]; ct++; printf("\t\t"); } } } void display_DFA_table() { int i=0,j=0,k=0; char c; printf("\n\nDFA Table is :"); printf("\n\n\t %s",symbols[i++]); while(i<N_symbol) { printf("\t\t%s",symbols[i++]);

Page 14: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

14

} printf("\n\t%c",214); for(i=0;i<N_symbol*15;i++) { printf("%c",196); } for(i=0;i<N_DFA_states;i++) { printf("\n"); k=0; while(DFAStates[i][k]!='\0') { printf("%c",DFAStates[i][k++]); } printf("\t%c ",186); for(j=0;j<N_symbol;j++) { if(DFAtab[i][j][0]!='\0') { k=0; while(DFAtab[i][j][k]!='\0') { printf("%c",DFAtab[i][j][k++]); } printf("\t\t"); } else printf("%c \t\t",237); } } printf("\n\nDFA final States are : "); j=0; for(i=0;i<N_DFA_states;i++) { c=' '; j=0; while(c!='\0') { if(strchr(DFAStates[i],c)!=NULL) { printf("%s,",DFAStates[i]); break; } c=NFA_finals[j++]; } } printf("%c %c",8,8); getch(); }

Page 15: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

15

Output:- Enter Grammar Definition : ({P,Q,R,S},{0,1},{P},{Q,S}) Input NFA Table : 0 1 ------------------------------- P | Q,S Q Q | R Q,R R | S P S | P DFA Table is : 0 1 ------------------------------- P | QS Q Q | R QR R | S P S | Φ P QS | R PQR QR | RS PQR PQR | QRS PQR RS | S P QRS | RS PQR DFA final States are : Q,S,QS,QR,PQR,RS,QRS Enter Grammer Definition : ({A,B,C,D,E},{a,b},{A},{E}) Input NFA Table : a b ------------------------------- A | B C B | B D C | B C D | B E E | B C DFA Table is : a b ------------------------------- A | B C B | B D C | B C D | B E E | B C DFA final States are : E

Page 16: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

16

Declared Variables:- int N_NFA_states - To store number of NFA states int N_DFA_states - To store number of DFA states int N_symbol - To store number of symbols char G[100] - To store the grammar definition char * NFAtab[STATES][SYMBOLS] - To store NFA table char * DFAtab[STATES][SYMBOLS] - To store DFA table char * DFAStates[50] - To store DFA states char * symbols[50] - To store symbols char NFA_finals[STATES] - To store NFA final states Declared Functions:- void input_NFA_table() - To input values in NFA table int isNewState(char *) - Check whether state is newly created void display_DFA_table() - To display DFA table in tabular format void mergeNewState(char *) - Merging and generating new states from composite state void refine() - Refine the newly created state in alphabetical order

Page 17: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

17

Practical 03 Write a C-Program to track transactions to find ελ and to produce a new production without ελ . Obtain all such productions without ελ and print them. Algorithm:-

Begin 1. Take the Transition table with ε -transitions as Input. 2. Compute ε -closure for all States. 3. Compute Transition Table without ε - transition using following Formula

( ) ( )( )( )a,εstate,'δδclosureε symbolinputstate,'δ = 5. Stop

End

Page 18: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

18

Code:- #include<msci.h> /*initialization*/ char *states,*inputsymbols,**eclosure; char iptranstable[10][10][10],optranstable[10][10][10]; int nos=0,noip=0,megactr=0; void print(); void filleclosure(int,int); void filloptranstable(); void fillCell(int,int); void main() { clrscr(); int i=0,j=0,k=0; char c=' '; printf("Removal of EPSILON Transitions...\n\n"); /* Input Data */ printf("No. of States: "); scanf("%d",&nos); states=allocateChar1D(nos); printf("Enter States: "); scanf("%s",states); printf("No. of Input Symbols: "); scanf("%d",&noip); inputsymbols=allocateChar1D(noip); printf("Enter Input Symbols: "); scanf("%s",inputsymbols); /* Append î to inputsymbols */ inputsymbols[noip]='î'; inputsymbols[noip+1]='\0'; printf("\n"); // Taking Input For Transition Table for(i=0;i<nos;i++) { for(j=0;j<=noip;j++) { printf("\nEnter %c,%c: ",states[i],inputsymbols[j]); for(k=0;k<nos;k++) { c=getch(); printf("%c",c); if(c==13) { break; } iptranstable[i][j][k]=c; c=' '; } } } //clrscr(); printf("\n\n"); print(); // Calculating ε -closure

Page 19: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

19

eclosure=allocateChar2D(nos); for(i=0;i<nos;i++) { eclosure[i][megactr]=states[i]; megactr++; filleclosure(i,i); megactr=0; } // Printing ε -closure printf("\n\n"); for(i=0;i<nos;i++) { printf("î-closure of %c: {",states[i]); for(j=0;j<nos;j++) { if(eclosure[i][j]!='\0') printf("%c",eclosure[i][j]); } printf("}"); printf("\n"); } filloptranstable(); getch(); }

Page 20: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

20

void print() { int i=0,j=0,k=0; printf("Removal Of EPSILON Transitions...\n\n"); printf("Input Transition Table:\n\n"); for(i=0;i<=noip;i++) { printf("\t%c",inputsymbols[i]); } printf("\n"); for(i=0;i<nos;i++) { printf("\n%c",states[i]); for(j=0;j<=noip;j++) { printf("\t"); for(k=0;k<nos;k++) { if(iptranstable[i][j][k]!='\0') printf("%c",iptranstable[i][j][k]); } } } } void filleclosure(int row,int stateno) { int k=0,flag=0,m=0; if(megactr<nos) {

while(iptranstable[stateno][noip][k]!='\0'&& iptranstable[stateno][noip][k]!='-')

{ flag=0; m=0; while(m<megactr) {

if(eclosure[row][m]== iptranstable[stateno][noip][k])

flag=1; m++; } if(flag!=1) {

eclosure[row][megactr]= iptranstable[stateno][noip][k];

megactr++; filleclosure(row,findPos(states, iptranstable[stateno][noip][k]));

k++; } else { break; } } } }

Page 21: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

21

void filloptranstable() { int i=0,j=0,k=0; // Fill each cell in Output Transition Table for(i=0;i<nos;i++) { for(j=0;j<noip;j++) { fillCell(i,j); } } // Print Output TRansition Table printf("\n\nOutput Transition Table:\n\n"); for(i=0;i<noip;i++) { printf("\t%c",inputsymbols[i]); } printf("\n"); for(i=0;i<nos;i++) { printf("\n%c",states[i]); for(j=0;j<noip;j++) { printf("\t"); for(k=0;k<nos;k++) { if(optranstable[i][j][k]!='\0') printf("%c",optranstable[i][j][k]); } } } } void fillCell(int row,int col) { int i=0,j=0,pos=0,k=0,m=0,flag=0,z=0; for(i=0;i<nos;i++) { if(eclosure[row][i]!='\0') { pos=findPos(states,eclosure[row][i]); j=0;

while(iptranstable[pos][col][j]!= '\0'&&iptranstable[pos][col][j]!='-')

{ m=0;

Page 22: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

22

while(m<=k) {

if(optranstable[row][col][m] ==iptranstable[pos][col][j])

flag=1; m++; } if(flag!=1) { pos=findPos(states,iptranstable[pos][col][j]); for(z=0;eclosure[pos][z]!='\0';z++) { m=0; while(m<=z) {

if(optranstable[row][col][m] ==eclosure[pos][z])

flag=1; m++; } if(flag!=1) {

optranstable[row][col][k] =eclosure[pos][z];

k++; } flag=0; } k++; flag=0; } j++; } } } }

Page 23: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

23

Output:- Removal of EPSILON Transitions... No. of States: 3 Enter States: ABC No. of Input Symbols: 2 Enter Input Symbols: ab Enter A, a: A Enter A, b: - Enter A, ε : B Enter B, a: B Enter B, b: C Enter B, ε : C Enter C, a: B Enter C, b: C Enter C, ε : AB Removal of EPSILON Transitions... Input Transition Table: A b ε A A - B B B C C C B C AB ε -closure of A: {ABC} ε -closure of B: {BCA} ε -closure of C: {CAB} Output Transition Table: a b A ABC CAB B BCA CAB C BCA CAB Declared Variables:- char *states - To store the States. char *inputsymbols - To store input Symbols. char **eclosure - To store the ε -closure of all States. char iptranstable[10][10][10] - To store the Input Transition Table. char optranstable[10][10][10] - To store the Output Transition Table.

Declared Functions:-

void print() - To print the Input Transition Table. void filleclosure(int,int) - To fill the ε -closure of all States. void filloptranstable() - To fill the Output Transition Table. void fillCell(int,int) - To fill each cell in Output Transition Table.

Page 24: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

24

Practical 04 Write a C-Program to track transactions of suitable size Represent the productions with suitable data structure. Input or code the following number of transition symbols, the transition symbols, the number of DFA states and destination states for all transition symbols on all states.

Input the following transitions and minimize the number of DFA states and print them along with their equivalence and group levels.

Transitions:

A 0B C 0A E 0H G 0G A 1F C 1C E 1F G 1E B 0G D 0C F 0C H 0G B 1C D 1G F 1G H 1C

Algorithm:- Begin

1. Accept the grammar definition and input DFA table. 2. Make all possible pairs using all States. 3. Discard the pairs of Final and Non-Final States. 4. For each remaining pair

a. Check the transition with each input symbol. b. If (X, a) = qm and (Y, a) = qn then Stop. c. If (X, a) = qm , (Y, a) = qm and (X, b) = qn , (Y, b) = qn then Merge X and

Y states together to form One Single State. d. Repeat For all States.

5. Stop. End

Page 25: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

25

Code:- #include <stdio.h> #define STATES 10 #define SYMBOLS 5 int N_DFA_states, N_symbol, totalGroup, totalGrouped; char c, G[100], * DFAtab[STATES][SYMBOLS],* DFAStates[50],

symbols[50], DFA_finals[STATES], DFA_initials[STATES], groupedStates[50], groups[50][50];

void input_DFA_table(); int isGrouped(char); void defineGroup(int); int isStartState(char); int isFinalState(char); void removeFromDFATab(char,char); void display_DFA_table(); void main() { int i=0,j=0; totalGroup=0; totalGrouped=0; clrscr(); input_DFA_table(); // Define new group if state is not grouped for(i=0; i<N_DFA_states; i++) { if( !isGrouped(DFAStates[i][0])) defineGroup(i); } for(i=0; i<totalGroup; i++) { int k; if(strlen(groups[i])>1) { for(j=0; j<(strlen(groups[i])-1); j++) { for(k=j+1;k<strlen(groups[i]);k++) { if(( isFinalState(groups[i][j]) && isFinalState(groups[i][k]) && !isStartState(groups[i][k])) || ( !isFinalState(groups[i][j]) && !isFinalState(groups[i][k]) && !isStartState(groups[i][k])) ) { removeFromDFATab(groups[i][k], groups[i][j]); } } } }

Page 26: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

26

} display_DFA_table(); } int isGrouped(char c) { if(strchr(groupedStates,c)==NULL) return 0; return 1; } void defineGroup(int i) { int m,n,k=0; groups[totalGroup][k++]=DFAStates[i][0]; groups[totalGroup][k]='\0'; groupedStates[totalGrouped++]=DFAStates[i][0]; groupedStates[totalGrouped]='\0'; for(m=i+1; m<N_DFA_states; m++) { for(n=0; n<N_symbol; n++) { if( DFAtab[i][n][0]!=DFAtab[m][n][0]) break; if( n==N_symbol-1 ) { groupedStates[totalGrouped++]=DFAStates[m][0]; groupedStates[totalGrouped]='\0'; groups[totalGroup][k++]=DFAStates[m][0]; groups[totalGroup][k]='\0'; } } } totalGroup++; } int isStartState(char c) { int i; for(i=0; i<strlen(DFA_initials); i++) { if(c==DFA_initials[i] ) return 1; } return 0; } int isFinalState(char c) { int i; for(i=0; i<strlen(DFA_finals); i++) { if(c==DFA_finals[i] ) return 1; } return 0;

Page 27: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

27

} void removeFromDFATab(char c,char cc) { int i,n,j; for(i=0;i<N_DFA_states;i++) { if( DFAStates[i][0]==c ) { //Remove State From State Variable for(j=i;j<N_DFA_states;j++) { DFAStates[j][0]=DFAStates[j+1][0]; } //Remove State From DFA Table for(j=i;j<N_DFA_states;j++) { for(n=0; n<N_symbol; n++) { DFAtab[j][n]=DFAtab[j+1][n]; } } } } //Remove State From DFA Table Other Entry for(j=0;j<N_DFA_states;j++) { for(n=0; n<N_symbol; n++) { if(DFAtab[j][n][0]==c) DFAtab[j][n][0]=cc; } } N_DFA_states--; } void input_DFA_table() { int i=0,j=0,k,ct=10; char c,str[100][100]; printf("Enter Grammar Definition : "); gets(G); N_DFA_states=0; N_symbol=0; j=2; i=0; // To Extract States From Grammar Definition c=' '; while(c!='}') {

Page 28: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

28

c=G[j]; if(c!=',' && c!='}') { str[ct][0]=G[j]; str[ct][1]='\0'; DFAStates[i++]=str[ct++]; N_DFA_states++; } j++; } //To Extract Symbols From Grammar Definition j=j+2; i=0; c=' '; while(c!='}') { c=G[j]; if(c!=',' && c!='}') { str[ct][0]=G[j]; str[ct][1]='\0'; symbols[i++]=str[ct++]; N_symbol++; } j++; } //To Extract Initial States From Grammar Definition j=j+2; i=0; c=' '; while(c!='}') { c=G[j]; if(c!=',' && c!='}') { c=G[j]; DFA_initials[i++]=c; } j++; } DFA_initials[i]='\0'; // To Extract Final States From Grammar Definition j=j+2; i=0; c=' '; while(c!='}') { c=G[j]; if(c!=',' && c!='}') { c=G[j]; DFA_finals[i++]=G[j]; } j++;

Page 29: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

29

} DFA_finals[i]='\0'; // Taking Input As Table i=0; printf("\nInput DFA Table : "); printf("\n\n\t %s",symbols[i++]); while(i<N_symbol) { printf("\t\t%s",symbols[i++]); } printf("\n\t%c",214); for(i=0;i<N_symbol*15;i++) { printf("%c",196); } ct++; for(i=0;i<N_DFA_states;i++) { printf("\n %s \t%c ",DFAStates[i],186); for(j=0;j<N_symbol;j++) { str[ct][0]=getche(); str[ct][1]='\0'; DFAtab[i][j]=str[ct++]; printf(" \t\t"); } } } void display_DFA_table() { int i=0,j=0,k=0; char c; printf("\n\nDFA Table is :"); printf("\n\n\t %s",symbols[i++]); while(i<N_symbol) { printf("\t\t%s",symbols[i++]); } printf("\n\t%c",214); for(i=0;i<N_symbol*15;i++) { printf("%c",196); } for(i=0;i<N_DFA_states;i++) { printf("\n"); k=0; while(DFAStates[i][k]!='\0') { printf(" %c,",DFAStates[i][k++]); } printf("%c %c",8,8); printf("\t%c ",186); for(j=0;j<N_symbol;j++)

Page 30: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

30

{ if(DFAtab[i][j][0]!='\0') { k=0; while(DFAtab[i][j][k]!='\0') { printf("%c,",DFAtab[i][j][k++]); } printf("%c %c",8,8); printf("\t\t"); } else printf("%c \t\t",237); } } // Display Final States In DFA printf("\n\nDFA final States are : "); j=0; for(i=0;i<N_DFA_states;i++) { c=' '; j=0; while(c!='\0') { if(strchr(DFAStates[i],c)!=NULL) { printf("%s,",DFAStates[i]); break; } c=DFA_finals[j++]; } } printf("%c %c",8,8); getch(); }

Page 31: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

31

Output:- Enter Grammar Definition : ({A,B,C,D,E,F,G,H},{0,1},{A},{E}) Input DFA Table : 0 1 ------------------------------- A | B F B | G C C | A C D | C G E | H F F | C G G | G E H | G C DFA Table is : 0 1 ------------------------------- A | B D B | G C C | A C D | C G E | B D G | G E DFA final States are : E Declared Variables:- int N_DFA_states - To store number of DFA states int N_symbol - To store number of symbols int totalGroup - To store number of groups int totalGrouped - To store number of grouped item char G[100] - To store the grammar definition char * DFAtab[STATES][SYMBOLS] - To store DFA table char * DFAStates[50] - To store DFA states char * symbols[50] - To store symbols char DFA_initials[STATES] - To store DFA initial states char DFA_finals[STATES] - To store DFA final states char groupedStates[50] - To store Grouped States Declared Functions:- void input_DFA_table() - To input values in DFA table int isGrouped(char) - To check whether symbol is grouped void defineGroup(int) - To define new group int isStartState(char) - To check whether the state is starting state int isFinalState(char) - To check whether the state is final state void removeFromDFATab(char, char) - To remove state from DFA table void display_DFA_table() - To display values in DFA table

Page 32: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

32

Header File [MSCI.h] #include<math.h> #include<dos.h> #include<stdio.h> #include<conio.h> #include<alloc.h> #include<string.h> #include<stdlib.h> typedef struct { char left; char *right; }Production; int *allocate1D(int dim) { return (int *)malloc(sizeof(int)*dim); } char *allocateChar1D(int dim) { return (char *)malloc(sizeof(char)*dim); } void deAllocate1D(int *p) { free(p); } int **allocate2D(int dim) { int **ptr=NULL,i; ptr=(int **)malloc(dim * sizeof(int *)); for(i=0;i<dim;i++) { ptr[i] = (int *) calloc (dim,sizeof(int)); } return ptr; } int **allocateSPF2D(int row,int col) { int **ptr=NULL,i; ptr=(int **)malloc(row * sizeof(int *)); for(i=0;i<row;i++) { ptr[i] = (int *) calloc (col,sizeof(int)); } return ptr; }

Page 33: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

33

char **allocateSPFChar2D(int row,int col) { char **ptr=NULL,i; ptr=(char **)malloc(row * sizeof(char *)); for(i=0;i<row;i++) { ptr[i] = (char *) calloc (col,sizeof(char)); } return ptr; } char **allocateChar2D(int dim) { char **ptr=NULL,i; ptr=(char **)malloc(dim * sizeof(char *)); for(i=0;i<dim;i++) { ptr[i] = (char *) calloc (dim,sizeof(char)); } return ptr; } char ***allocateChar3D(int val1,int val2,int val3) { char ***ptr=NULL; int i=0,j=0; ptr=(char ***)malloc(val1*sizeof(char **)); for(i=0;i<val1;i++) { ptr[i] = (char **) calloc (val2,sizeof(char *)); } for(i=0;i<val1;i++) { for(j=0;j<val2;j++) { ptr[i][j] = (char *) calloc (val3,sizeof(char)); } } return ptr; } void deAllocate2D(int **p,int dim) { int i; for(i=0;i<dim;i++) free(p[i]); free(p); //free(*p); }

Page 34: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

34

void deAllocateChar2D(char **p,int dim) { int i; for(i=0;i<dim;i++) free(p[i]); free(p); //free(*p); } int **readMatrix(int **p,int dim) { int row=0,col=0; int **result; result = allocate2D(dim); for(row=0;row<dim;row++) { for(col=0;col<dim;col++) { scanf("%d",*(p+row)+col); } } return result; } void printMatrix(int **p,int dim) { int row=0,col=0; for(row=0;row<dim;row++) { for(col=0;col<dim;col++) { printf("%3d ",*(*(p+row)+col)); } printf("\n"); } } void printMatrixSPF(int **p,int rown,int coln) { int row=0,col=0; for(row=0;row<rown;row++) { for(col=0;col<coln;col++) { printf("%3d ",*(*(p+row)+col)); } printf("\n"); } }

Page 35: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

35

int **addMatrix(int **p,int **q,int dim) { int **result; int row=0,col=0; result = allocate2D(dim); for(row=0;row<dim;row++) { for(col=0;col<dim;col++) { *(*(result+row)+col) = *(*(p+row)+col) + *(*(q+row)+col); } } return result; } int **mulMatrix(int **p,int **q,int dim) { int **result; int i=0,j=0,k=0,sum=0; result = allocate2D(dim); for(i=0;i<dim;i++) { for(j=0;j<dim;j++) { sum=0; for(k=0;k<dim;k++) { sum+=*(*(p+i)+k) * *(*(q+k)+j); } *(*(result+i)+j) = sum; } } return result; } int **transposeMatrix(int **p,int dim) { int row=0,col=0; int **result; result = allocate2D(dim); for(row=0;row<dim;row++) { for(col=0;col<dim;col++) { result[row][col] = p[col][row]; } } return result; }

Page 36: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

36

void getProduction(Production *p) { char l; char r[80]; int isError=1; while(isError==1) { isError=0; fflush(stdin); printf("\nEnter the Production (eg A -> B):"); scanf("%c -> %s",&l,&r); if(l < 'A' || l > 'Z') { printf("\nInvalid Production"); isError=1; } } p->left=l; p->right=strdup(r); } int findPos(char *s, char ch) { int i=0; while( s[i] != '\0') { if(s[i] == ch ) return(i); i++; } return(i); } int findPos1(char *s, char ch) { int i=0,j=-1; while( s[i] != '\0') { if(s[i] == ch ) { j=i; break; } i++; } return(j); }

Page 37: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

37

int **Warshall(int **p,int dim) { int i,j,k,**W; W = allocate2D(dim); for(i=0;i<dim;i++) { for(j=0;j<dim;j++) { W[i][j] = p[i][j]; } } for(i=0;i<dim;i++) { for(j=0;j<dim;j++) { if(W[j][i]==1) { for(k=0;k<dim;k++) W[j][k] = W[j][k] | W[i][k] ; } } } return W; } int **MatrixClosure(int **p,int dim) { int i,j; int **T; T=allocate2D(dim); for(i=0;i<dim;i++) for(j=0;j<dim;j++) T[i][j]=p[i][j]; for(i=0;i<dim;i++) T[i][i] = 1; return(T); }

Page 38: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

38

Practical 05 You are given Warshall’s Algorithm. Write a C-Program to accept the following initial matrix.

⎟⎟⎟⎟⎟⎟⎟⎟

⎜⎜⎜⎜⎜⎜⎜⎜

000010000001000010010000001000010000

Perform the steps of Warshall’s Algorithm and output the final matrix. Algorithm:- Begin

1. Set a new Matrix A = B. 2. Set i = 1. 3. For all j is A[j, i] = 1 then i = 1,…….,n.

Set A[j, k] = A[j, k] + A[i, k]. 4. Add 1 to i 5. If i <= n then goto step 3

Else stop. End

Page 39: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

39

Code:- #include<stdio.h> #include<conio.h> #include<math.h> #include<stdlib.h> int **WARSHALL(int **b,int n); void main() { int **b,**c,n=6,i,j; clrscr(); //Dynamic Allocation c=(int**)malloc(n*sizeof(int)); b=(int**)malloc(n*sizeof(int)); for(i=0;i<n;i++) { *(c+i)=(int*)malloc(n*sizeof(int)); *(b+i)=(int*)malloc(n*sizeof(int)); } for(i=0;i<n;i++) { for(j=0;j<n;j++) { *(*(c+i)+j)=0; *(*(b+i)+j)=0; } } //Input To Matrix printf("\nEnter any Matrix:\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { scanf("%d",&b[i][j]); } } //Printing the Entered Matrix printf("\nEntered Matrix"); for(i=0;i<n;i++) { printf("\n"); for(j=0;j<n;j++) { printf(" %d",b[i][j]); } } printf("\nWarshall's Matrix"); for(i=0;i<n;i++) { printf("\n"); for(j=0;j<n;j++) { printf(" %d",c[i][j]); } } c=WARSHALL(b,n); for(i=0;i<n;i++)

Page 40: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

40

{ printf("\n"); for(j=0;j<n;j++) { printf(" %d",c[i][j]); } } return 0; getch(); } int **WARSHALL(int **b,int n) { int i=0,j,k,**a; a=(int**)malloc(n*2); for(i=0;i<n;i++) *(a+i)=(int*)malloc(n*2); for(i=0;i<n;i++) { for(j=0;j<n;j++) { *(*(a+i)+j)=*(*(b+i)+j); } } i=0; do { for(j=0;j<n;j++) { if(*(*(a+j)+i)==1) { for(k=0;k<n;k++) { *(*(a+j)+k)=*(*(a+j)+k)|*(*(a+i)+k); } } } i++; }while(i<n); return a; }

Page 41: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

41

Output:- Enter any Matrix: 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 Entered Matrix 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 Warshall's Matrix 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0 1 0 0 0 1 0 0 1 0 1 0 0 1 0 0 0 1 0 0 1 0 1 0 0 Declared Variables:- int **b - To store the input matrix B. int **c - To store the matrix C after applying warshall’s algorithm on matrix B. int n - To define dimension of the matrices B and C. Declared Functions:- int **WARSHALL(int **b,int n) - To implement the Warshall algorithm.

Page 42: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

42

Practical 06 You have been given the following rules to obtain the ‘Less-Than’ and ‘Greater-Than’ Matrices. Less Than =(FIRST)+

Greater Than (LAST+)T=(FIRST*) Write a C-Program to extract the FIRST, EQUAL and LAST matrices from the following Grammar. By using the above rules obtain the ‘LessThan’, ‘GreaterThan’ matrices and by superimposition of the three matrices obtain and print the SPM. Grammar G : {N,T,P,S} Productions P:

Z bMb M (L M a L Ma) Algorithm:-

Begin 1. Take input Symbols. 2. Take input Productions rules. 3. Compute Equal Matrix. 4. Compute First Matrix. 5. Compute First+ Matrix. 6. Compute First* Matrix. 7. Compute Last Matrix. 8. Compute Last+ Matrix. 9. Compute (Last+)T Matrix. 10. Compute Less Than Matrix using formula :

Less Than =(FIRST)+ 11. Compute Less Than Matrix using formula :

Greater Than (LAST+)T=(FIRST*) 12. To compute the final SPM matrix superimpose the EQUAL, LESS

THAN, GREATER THAN matrix End

Page 43: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

43

Code:- #include "MSCI.h" void main() { /*Initialization*/ int **input,**result,**equal,**first,**firstplus,**firststar; int **last,**lastplus,**lastplustrans; int **lessthan,**greaterthan,**temp,**spm; Production prod[10]; int row=0,col=0,i=0,j=0,k=0,pos1=0,pos2=0; int nos,nop; char *symbol; clrscr(); /*Accepting Data*/ printf("PROGRAM: SIMPLE PRECEDENCE MATRIX..\n"); printf("Enter number of Symbols : "); scanf("%d",&nos); symbol = (char *)malloc((nos+1)*sizeof(char)); printf("Enter the Symbols: (NTs followed by Ts): "); scanf("%s",symbol); printf("Enter no of Productions : "); scanf("%d",&nop); for(i=0;i<nop;i++) { getProduction(&prod[i]); } clrscr(); /*Printing Productions*/ printf("PROGRAM: SIMPLE PRECEDENCE MATRIX..\n"); printf("The productions Entered are: "); for(i=0;i<nop;i++) { printf("\n %c -> %s ",prod[i].left,prod[i].right); } /*Calculating EQUAL Matrix*/ equal=allocate2D(nos); for(i=0;i<nop;i++) { for(j=0;j<strlen(prod[i].right)-1;j++) { pos1=findPos(symbol,prod[i].right[j]); pos2=findPos(symbol,prod[i].right[j+1]); equal[pos1][pos2]=1; } } printf("\nThe Equal Matrix Is:\n"); printMatrix(equal,nos); getch(); /*Calculating FIRST Matrix*/ first = allocate2D(nos); firstplus=allocate2D(nos); firststar=allocate2D(nos); for(i=0;i<nop;i++) { pos1=findPos(symbol,prod[i].left);

Page 44: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

44

pos2=findPos(symbol,prod[i].right[0]); first[pos1][pos2]=1; firstplus[pos1][pos2]=1; //Copying Required firststar[pos1][pos2]=1; //Values From First Matrix } printf("\nThe First Matrix Is:\n"); printMatrix(first,nos); getch(); /*Calculating FIRST+ Matrix*/ for(i=0;i<nos;i++) { for(j=0;j<nos;j++) { if(firstplus[i][j]==1) { for(k=0;k<nos;k++) { if(firstplus[j][k]==1) { firstplus[i][k]=1; //Copying Required Values //From First+ Matrix firststar[i][k]=1; } } } } } printf("\nThe First+ Matrix Is:\n"); printMatrix(firstplus,nos); getch(); /*Calculating FIRST* Matrix*/ for(i=0;i<nos;i++) { firststar[i][i]=1; } printf("\nThe First* Matrix Is : \n"); printMatrix(firststar,nos); getch(); /*Calculating LAST Matrix*/ last = allocate2D(nos); lastplus = allocate2D(nos); for(i=0;i<nop;i++) { pos1 = findPos(symbol,prod[i].left); pos2 = findPos(symbol,prod[i].right[strlen(prod[i].right)-1]); last[pos1][pos2] = 1; // Filling Reqd Values In LAST+ Matrix lastplus[pos1][pos2] = 1; } printf("\nThe Last Matrix Is:\n"); printMatrix(last,nos); getch(); /*Calculating LAST+ Matrix*/ for(i=0;i<nos;i++) { for(j=0;j<nos;j++)

Page 45: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

45

{ if(lastplus[i][j]==1) { for(k=0;k<nos;k++) { if(lastplus[j][k]==1) { lastplus[i][k]=1; } } } } } printf("\nThe Last+ Matrix Is:\n"); printMatrix(lastplus,nos); getch(); /*Calculating (LAST+)T Matrix*/ lastplustrans=allocate2D(nos); lastplustrans=transposeMatrix(lastplus,nos); printf("\nThe (Last+)T Matrix Is:\n"); printMatrix(lastplustrans,nos); getch(); /*Calculating LessThan Matrix*/ lessthan = allocate2D(nos); lessthan = mulMatrix(equal,firstplus,nos); printf("\nThe LessThan Matrix Is:\n"); printMatrix(lessthan,nos); greaterthan = allocate2D(nos); temp = allocate2D(nos); temp = mulMatrix(lastplustrans,equal,nos); greaterthan = mulMatrix(temp,firststar,nos); printf("\nThe GreaterThan Matrix Is:\n"); printMatrix(greaterthan,nos); getch(); /*---------SPM---------*/ spm=allocate2D(nos); printf("\n SPM Is:\n"); for(i=0;i<nos;i++) { printf("\n%c",symbol[i]); for(j=0;j<nos;j++) { spm[i][j]=0; if(equal[i][j]==1) { printf("\t="); } else if(lessthan[i][j]==1) { printf("\t<"); } else if(greaterthan[i][j]==1) { printf("\t>"); } else {

Page 46: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

46

printf("\t%d",spm[i][j]); } } } getch(); /*Deallocation*/ deAllocate2D(equal,nos); deAllocate2D(first,nos); deAllocate2D(firstplus,nos); deAllocate2D(firststar,nos); deAllocate2D(last,nos); deAllocate2D(lastplus,nos); deAllocate2D(lastplustrans,nos); deAllocate2D(lessthan,nos); deAllocate2D(greaterthan,nos); deAllocate2D(temp,nos); deAllocate2D(spm,nos); getch(); }

Page 47: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

47

Output:- PROGRAM: SIMPLE PRECEDENCE MATRIX.. Enter number of Symbols : 7 Enter the Symbols: (NTs followed by Ts): ZMLab() Enter no of Productions : 4 Enter the Production (eg A -> B):Z->bMb Enter the Production (eg A -> B):M->(L Enter the Production (eg A -> B):M->a Enter the Production (eg A -> B):L->Ma) PROGRAM: SIMPLE PRECEDENCE MATRIX.. The productions Entered are: Z -> bMb M -> (L M -> a L -> Ma) The Equal Matrix Is: 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 The First Matrix Is: 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 The First+ Matrix Is: 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 The First* Matrix Is : 1 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 1 1 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1

Page 48: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

48

The Last Matrix Is: 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 The Last+ Matrix Is: 0 0 0 0 1 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 The (Last+)T Matrix Is: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 The LessThan Matrix Is: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 The GreaterThan Matrix Is: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 SPM Is: Z 0 0 0 0 0 0 0 M 0 0 0 = = 0 0 L 0 0 0 > > 0 0 a 0 0 0 > > 0 = b 0 = 0 < 0 < 0 ( 0 < = < 0 < 0 ) 0 0 0 > > 0 0

Page 49: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

49

Practical 07 You are given a SPM of order mxm (m = 7, 8, 9, 10). Write a C-Program to implement the parsing algorithm for the SPM. Input the following Grammar and parse the strings given below: Grammar G : {N,T,P,S} Productions P:

Z bMb M (L M a L Ma)

SPM:

00000)000(0000b

0000a00000L00000M0000000Z)(baLMZ

>><<=<<<=

=>>>>==

Strings: b(aa)b b((aa)a)b b((aaa)a)b

Output the step-by-step reduction.

Algorithm:-

Begin 1. Take input of grammar definition. 2. Take input of production used. 3. Take input of SPM. 4. Take input string to be parsed. 5. Store the string with precedence relation using SPM. 6. Search handle and replace it with respective NT. 7. If we reach to start symbol of grammar, then string is valid else invalid.

End

Page 50: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

50

Code:- #include "MSCI.h" /*Initialization*/ char **spm; Production prod[10]; int i=0,j=0,less=0,greater=0,nos=0,nop=0; char *symbol,c,inputstr[50],handleStart,handleEnd,*handle,*h,*handle1; void print(); void parseString(); char compare(char,char); char* createHandle(); void checkNreplace(char *); void main() { clrscr(); /*Accepting Data*/ printf("PROGRAM: SIMPLE PRECEDENCE MATRIX..\n"); printf("Enter number of Symbols : "); scanf("%d",&nos); symbol = (char *)malloc((nos+1)*sizeof(char)); printf("Enter the Symbols: (NTs followed by Ts): "); scanf("%s",symbol); printf("Enter no of Productions : "); scanf("%d",&nop); for(i=0;i<nop;i++) { getProduction(&prod[i]); } clrscr(); /*Printing Productions*/ printf("PROGRAM: SIMPLE PRECEDENCE MATRIX..\n"); printf("The productions Entered are: "); for(i=0;i<nop;i++) { printf("\n %c -> %s ",prod[i].left,prod[i].right); } spm=allocateChar2D(nos); /* Input SPM Matrix */ printf("\nEnter SPM:\n"); printf("\nEnter each row separated by tabs:\n"); for(i=0;i<nos;i++) { printf("\t%c",symbol[i]); } printf("\n"); for(i=0;i<nos;i++) { printf("%c",symbol[i]); for(j=0;j<nos;j++) { printf("\t"); c=getch(); if(c!=13) {

Page 51: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

51

printf("%c",c); spm[i][j]=c; } } printf("\n"); } /* Input String To Be Parsed */ printf("Enter the string to be parsed: "); scanf("%s",inputstr); clrscr(); /* Print SPM and string to be Parsed */ for(i=0;i<nos;i++) { printf("\t%c",symbol[i]); } printf("\n"); for(i=0;i<nos;i++) { printf("%c\t",symbol[i]); for(j=0;j<nos;j++) { printf("%c\t",spm[i][j]); } printf("\n"); } printf("String to be parsed : %s\n",inputstr); getch(); parseString(); getch(); deAllocateChar2D(spm,nos); getch(); } void parseString() { int ctr1=0; for(ctr1=0;ctr1<strlen(inputstr)-1;ctr1++) { if(strcmp(inputstr,prod[0].right)==0) { printf("\nFound Starting Symbol : %c\n",prod[0].left); printf("\n\nString Successfully Parsed\n"); getch(); exit(0); } /* Start Handle Here */ if(compare(inputstr[ctr1],inputstr[ctr1+1])=='<') { handleStart=inputstr[ctr1+1]; less=ctr1+1; continue; } /* End Handle Here */ if(compare(inputstr[ctr1],inputstr[ctr1+1])=='>') { handleEnd=inputstr[ctr1]; greater=ctr1; h=createHandle();

Page 52: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

52

checkNreplace(h); ctr1=-1; i=0; continue; } } printf("\nString Parsed Unsuccessfully..\n"); } char compare(char a,char b) { int val1=findPos(symbol,a); int val2=findPos(symbol,b); char val; val=spm[val1][val2]; return val; } /* Create Handle */ char* createHandle() { int val1=less; int val2=greater; int a=0,b=0,ctr1=0; free(handle); handle=(char *)malloc((abs(val2-val1)+1)*sizeof(char)); if(val1>val2) { a=val2; b=val1; } if(val1<val2) { a=val1; b=val2; } if(val1==val2) { a=val1; b=val2; } for(;a<=b;a++) { handle[ctr1]=inputstr[a]; ctr1++; } handle[ctr1]='\0'; printf("\nHandle is : %s.\n",handle); return(handle); } /* Check Handle In Parse String And Replace By NT */ void checkNreplace(char *handle) { int ctr1=0; free(handle1); handle1[0]='\0';

Page 53: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

53

for(ctr1=0;ctr1<nop;ctr1++) { if(strcmp(handle,prod[ctr1].right)==0) { free(handle1); handle1=(char *)calloc(2,sizeof(char)); handle1[0]=prod[ctr1].left; break; } } /* If No NT Found then unsucessful parse */ if(handle1[0]=='\0') { printf("Unsuccessful..........."); exit(0); } handle1[1]='\0'; printf("\nReplacing by : %s.\n",handle1); char temp[50]; int ctr2=0; /* Replace Algorithm (Creating New Input String) */ for(ctr1=0;ctr1<50;ctr1++) { if(ctr1==less) { temp[ctr2]=handle1[0]; ctr2++; while(less<=greater) { ctr1++; less++; } temp[ctr2]=inputstr[ctr1]; ctr2++; } else { temp[ctr2]=inputstr[ctr1]; ctr2++; } } temp[ctr2]='\0'; ctr1=0; while(temp[ctr1]!='\0') { inputstr[ctr1]=temp[ctr1]; ctr1++; } inputstr[ctr1]='\0'; printf("\nNew Input String: %s\n",inputstr); getch(); }

Page 54: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

54

Output:- PROGRAM: SIMPLE PRECEDENCE MATRIX.. The productions Entered are: Z -> bMb M -> (L M -> a L -> Ma) Enter SPM: Enter each row separated by tabs:

Z M L a b ( ) Z 0 0 0 0 0 0 0 M 0 0 0 = = 0 0 L 0 0 0 > > 0 0 a 0 0 0 > > 0 = b 0 = 0 < 0 < 0 ( 0 < = < 0 < 0 ) 0 0 0 > > 0 0 Enter the string to be parsed: b(aa)b

Z M L a b ( ) Z 0 0 0 0 0 0 0 M 0 0 0 = = 0 0 L 0 0 0 > > 0 0 a 0 0 0 > > 0 = b 0 = 0 < 0 < 0 ( 0 < = < 0 < 0 ) 0 0 0 > > 0 0 String to be parsed : b(aa)b Handle is : a. Replacing by : M. New Input String: b(Ma)b Handle is : Ma). Replacing by : L. New Input String: b(Lb Handle is : (L. Replacing by : M. New Input String: bMb Found Starting Symbol : Z String Successfully Parsed

Page 55: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

55

NEW STRING String to be parsed : b((aa)a)b Handle is : a. Replacing by : M. New Input String: b((Ma)a)b Handle is : Ma). Replacing by : L. New Input String: b((La)b Handle is : (L. Replacing by : M. New Input String: b(Ma)b Handle is : Ma). Replacing by : L. New Input String: b(Lb Handle is : (L. Replacing by : M. New Input String: bMb String Successfully Parsed NEW STRING String to be parsed : b((aaa)a)b Handle is : a. Replacing by : M. New Input String: b((Maa)a)b Handle is : Ma. Unsuccessful...........

Page 56: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

56

Declared Variables:- char **spm - To store the SPM matrix Production prod[10] - To store the Production rules int nos - To store no of states int nop - To store no of productions char *symbol - To store the symbols char inputstr[50] - To store the string to be parsed char *handle - To store the handle found Declared Functions:- void print() - Prints the SPM matrix void parseString() - Parses the string which is input char compare(char,char) - Returns a value from SPM matrix char* createHandle() - It creates new handle from input string void checkNreplace(char *) - It checks the handle with each production and

replaces it with appropriate NT

Page 57: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

57

Practical 08

Input an operator grammar. Peform the following on it a. Compute Less-Than precedence matrix (<) b. Computer Greater-Than precedence matrix (>) c. Computer Equal precedence matrix (=) d. OPM (Operator Precedence Matrix)

Grammar G : {N,T,P,S} Productions P: E E+T E T T T*F T F F (E) F id Algorithm:-

Begin 1. Take input productions of given Grammar. 2. Compute Leading (First Terminal) for each NT. 3. Compute Trailing (Last Terminal) for each NT. 4. In the Leading entries of NT following the T in each production put ‘<’ sign

row wise. 5. In the Trailing entries of NT following the T in each production put ‘>’ sign column wise. 6. Put ‘<’ sign in row of $ in the Leading entries of the Start Symbol. 7. Put ‘>’ sign in column of $ in the Trailing entries of the Start Symbol. 8. Put ‘=’ sign in the corresponding row column entry of terminals which

enclose the single NT or ε . End

Page 58: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

58

Code:- #include<stdio.h> #include<stdlib.h> #include<string.h> #include<conio.h> int t, nt, prod,lead,trail,top, ltop,res,Lflag[10], Tflag[10]; char NT[10], // List Of Non Terminals T[10], // List of Terminals PROD[10][15], // List of Productions LEAD[10][10], // LEADING Terminals TRAIL[10][10], // TRAILING Terminals stack[10], Lstack[10], // To store incomplete LEADING & TRAILING grammer[10][10],// To store operator precedence grammer gram, // Starting symbol of the grammer strng[15]; // The string void initial(); void input(); void push(char ch); char pop(); void Lpush(char ch); char Lpop(); int match_T(char ch); int match_NT(char ch); void LEADING(); void TRAILING(); void init_lead(int i); void init_trail(int i); void oper_prec_grammer(); void display(); void string_accept(); int present(int i,char ch); void initial() { int i,j; for(i=0 ; i<10 ; i++) { for(j=0 ; j<10 ; j++) { PROD[i][j] = '\0'; LEAD[i][j] = '\0'; TRAIL[i][j] ='\0'; grammer[i][j] = '\0'; } } for(i=0 ; i<10 ; i++) { Lflag[i] = 0; Tflag[i] = 0; NT[i] = '\0'; T[i] = '\0';

Page 59: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

59

stack[i] = '\0'; Lstack[i] = '\0'; strng[i] = '\0'; } top = -1; t = 0; nt = 0; prod = 0; lead = 0; trail = 0; ltop = -1; gram = '\0'; } void input() { int i,j; printf("Enter Starting Symbol of grammar : "); scanf("%c",&gram); printf("\nEnter No. of Productions : "); scanf("%d",&prod); printf("\nEnter No. of Non Terminals : "); scanf("%d",&nt); printf("\nEnter Non Terminals : "); scanf("%s",NT); printf("\nEnter No. of Terminals : "); scanf("%d",&t); printf("\nEnter Terminals : "); scanf("%s",T); printf("\nEnter Productions : "); for(i=1;i<=prod;i++) { scanf("%s",&PROD[--i]); i++; } } void push(char ch) { top = top + 1; stack[top] = ch; } char pop() { char ch; ch = stack[top]; top = top - 1; return(ch); } void Lpush(char ch) {

Page 60: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

60

ltop = ltop + 1; Lstack[ltop] = ch; } char Lpop() { char ch; ch = Lstack[ltop]; ltop =ltop - 1; return(ch); } //Match input symbol with all terminal symbols & return is position //in array if present, otherwise return -1 int match_T(char ch) { int i; for( i=0 ; i<t ; i++ ) if( ch == T[i] ) return(i); // if not present in array return(-1); } int match_NT(char ch) { int i; for( i=0 ; i<nt ; i++ ) if( ch == NT[i] ) return(i); return(-1); } void init_lead(int i) { int j; for( j=1 ; j<10 ; j++ ) LEAD[i][j] = '\0'; } void init_trail(int i) { int j; for( j=1 ; j<10 ; j++ ) TRAIL[i][j] = '\0'; } void LEADING() { char ch, ch1; int i, j, k, resp,flag; //For all NTs find LEADING(NT) for( i=0 ; i<nt ; i++ ) { lead = 0; //First entry in LEAD is NT for which LEAD[i][0] = NT[i];

Page 61: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

61

//LEADING is to be find for( j=0 ; j<prod ; j++ ) { if( PROD[j][0] == NT[i]) { //First symbol in jth production ch = PROD[j][3]; resp = match_T(ch); //First symbol is Terminal if( resp != -1 ) { lead++ ; LEAD[i][lead] = ch; } else //First symbol is not Terminal { resp = match_NT(ch); if( resp != -1 ) //First symbol is NT { ch1 = PROD[j][4]; //Symbol is not Empty or Epsilon if( ch1 != '\0' ) { resp = match_T(ch1); //Symbol followed by NT is T

if( resp != -1 ) {

lead++; LEAD[i][lead] = ch1; } else {

printf("\nError, Production Is not Correct."); // NT must be followed by //either T or Epsilon

exit(0); } } if( ch != LEAD[i][0] ) { lead++; // store NT temporarily in LEADING LEAD[i][lead] = ch; } } else { printf("Error, Production Is not Correct.");

// First symbol in Production //is either T or NT

exit(0); } } }

Page 62: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

62

}//Inner For loop ends }//Outer For Loop ends //Find NT's (& set Lflag = 1 for them) for which LEADING is successfully //calculated i.e.its LEADING has only terminals & others are put into LSTACK. for( i=0 ; i<nt ; i++ ) { j = 1; flag = 1; ch = LEAD[i][j]; while( ch != '\0' ) { resp = match_T(ch); if( resp != -1 ) ch = LEAD[i][++j]; else { flag = 0; Lpush(LEAD[i][0] ); //Push in Lstack to find LEADING break; } } if( flag == 1 ) //LEADING(symb) is successfully done Lflag[i] = 1; } //Calculate LEADING for symbols which still contains NTs //(for simplicity start from end position) if( ltop != -1 ) { do { ch = Lpop(); flag = 1; resp = match_NT(ch); i = resp; j = 1; ch = LEAD[i][j]; while( ch != '\0' ) { push(ch); ch = LEAD[i][++j]; } //Initialize the LEAD array to '\0' starting init_lead(i); j = 0; //From first position while( top != -1 ) { ch = pop(); resp = match_T(ch); if( resp != -1 ) LEAD[i][++j] = ch; else {

Page 63: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

63

resp = match_NT(ch); //LEADING is completely done

if( Lflag[resp] == 1 ) {

k = 1; ch1 = LEAD[resp][k]; while( ch1 != '\0' )

//Put everything in LEAD(B) { //to LEAD(A) if A->B... LEAD[i][++j] = ch1; ch1 = LEAD[resp][++k]; } } else { //Put everything present in stack //back to LEAD so as to calculate while( top != -1 ) { LEAD[i][++j] = ch;

//LEAD next time ch = pop(); } flag = 0; Lpush(LEAD[i][0]); break; } } }//While ends if( flag == 1 ) Lflag[i] = 1; }while( ltop >= 0 );//Do while ends }//If ends printf("\nLEADING"); for( i=0 ; i<nt ; i++ ) { printf("\n"); for( j=0 ; j<5 ; j++ ) printf("\t%c",LEAD[i][j]); } } void TRAILING() { char ch, ch1; int i, j, k, end, resp, flag; for( i=0 ; i<nt ; i++ ) //For all NTs find TRAILING(NT) { trail = 0; //First entry in TRAIL is NT for which //TRAILING is to be find TRAIL[i][0] = NT[i]; for( j=0 ; j<prod ; j++ ) {

Page 64: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

64

if( PROD[j][0] == NT[i] ) { end = 0; while( PROD[j][end] != '\0' ) end++; end--; ch = PROD[j][end]; //Last symbol resp = match_T(ch); if( resp != -1 ) //Last symbol is T { trail++ ; TRAIL[i][trail] = ch; } else //Last symbol is not T { resp = match_NT(ch); if( resp != -1 ) //Last symbol is NT { ch1 = PROD[j][end-1]; if( ch1 != '>' ) //i.e. not -> { resp = match_T(ch1); //Symbol followed by NT is T

if( resp != -1 ) {

trail++; TRAIL[i][trail] = ch1; } } res = present(i,ch); if( res == 0) { trail++; TRAIL[i][trail] = ch;

//Store NT temporarily in TRAILING

} } else {

printf("\nError, Production Is not Correct.");

// First symbol in Production is either T or NT

exit(0); } } } } }

Page 65: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

65

//Find NT's (& set Tflag = 1 for them) for which TRAILING is successfully //calculated i.e.its TRAILING hasonly terminals & others are put into LSTACK for( i=0 ; i< nt ; i++ ) { j = 1; flag = 1; ch = TRAIL[i][j]; while( ch != '\0' ) { resp = match_T(ch); if( resp != -1 ) ch = TRAIL[i][++j]; else { flag = 0;

Lpush(TRAIL[i][0] ); //Push in Lstack to find LEADING

break; } } if( flag == 1 ) //TRAILING(symb) is successfully done Tflag[i] = 1; } //Calculate TRAILING for symbols which still contains NTs //(for simplicity start from end position if( ltop != -1 ) { do { ch = Lpop(); flag = 1; resp = match_NT(ch); i = resp; j = 1; ch = TRAIL[i][j]; while( ch != '\0' ) { push(ch); ch = TRAIL[i][++j]; } init_trail(i); //Initialize the TRAIL array to '\0' starting j = 0; //from first position while( top != -1 ) { ch = pop(); resp = match_T(ch); if( resp != -1 ) TRAIL[i][++j] = ch;

Page 66: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

66

else { resp = match_NT(ch); if( Tflag[resp] == 1 )

// TRAILING is completely done { k = 1; ch1 = TRAIL[resp][k]; while( ch1 != '\0' )

//Put everything in TRAIL(B) { //to TRAIL(A) if A->B... TRAIL[i][++j] = ch1; ch1 = TRAIL[resp][++k]; } } else { while(top != -1)

//Put everything present in stack {

//back to TRAIL so as to calculate TRAIL[i][++j] = ch;

//TRAIL next time ch = pop(); } flag = 0; Lpush(TRAIL[i][0]); break; } } } if( flag == 1 ) Tflag[i] = 1; }while( ltop >= 0 ); } printf("\n\nTRAILING"); for( i=0 ; i<nt ; i++ ) { printf("\n"); for( j=0 ; j<5 ; j++ ) printf("\t%c",TRAIL[i][j]); } } int present(int i, char ch) { int j; for( j=0 ; j<10 ; j++ ) if( TRAIL[i][j] == ch ) return(1); return(0); } void oper_prec_grammer() { int i, i1, i2, i3, i4, len, j, k, resp; char ch1, ch2, ch3, ch;

Page 67: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

67

for( i=0 ; i<prod ; i++ ) //For each production { len = strlen(PROD[i]); for( j=3 ; j<len-1 ; j++ ) //Because prod. is of form A->B { //0123 ch1 = PROD[i][j]; ch2 = PROD[i][j+1]; i1 = match_T(ch1); if( i1 != -1 ) { i2 = match_T(ch2); if( i2 != -1 ) grammer[i1][i2] = '='; else //ch2 is NT { if(j<len-2) { ch3 = PROD[i][j+2]; i3 = match_T(ch3); if( i3 != -1 ) // if ch(i+2) is terminal grammer[i1][i3] = '='; } //if ch1 is T & ch2 is NT k = 1; i2 = match_NT(ch2) ; //ch2 is NT ch = LEAD[i2][k]; while( ch != '\0' ) { i4 = match_T(ch); grammer[i1][i4] = '<'; ch = LEAD[i2][++k]; } } } else // ch1 is NT { i1 = match_NT(ch1); i2 = match_T(ch2); k =1; ch = TRAIL[i1][k]; while( ch != '\0') { i4 = match_T(ch); grammer[i4][i2] = '>'; ch = TRAIL[i1][++k]; } } } } resp = match_NT(gram); i = resp; k = 1; ch = LEAD[i][k]; while( ch != '\0' ) {

Page 68: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

68

i1 = match_T(ch); grammer[t][i1] = '<'; ch = LEAD[i][++k]; } k = 1; ch = TRAIL[i][k]; while(ch != '\0' ) { i1 = match_T(ch); grammer[i1][t] = '>'; ch = TRAIL[i][++k]; } } void display() { int i,j; printf("\n\nThe Operator Precedence Grammar Is :\n "); for(i=0 ; i<t ; i++) printf("\t%c",T[i]); printf("\t$"); for(i=0 ; i< t ; i++) { printf("\n%c",T[i]); for(j=0 ; j<=t ; j++) { if(grammer[i][j] == '\0' ) printf("\t"); else printf("\t%c",grammer[i][j]); } } printf("\n$"); for( j=0 ; j<=t ; j++ ) printf("\t%c",grammer[t][j]); }

Page 69: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

69

void main() { clrscr(); initial(); input(); clrscr(); LEADING(); TRAILING(); getch(); clrscr(); oper_prec_grammer(); display(); getch(); } Output:- Enter Starting Symbol of grammar : E Enter No. of Productions : 6 Enter No. of Non Terminals : 3 Enter Non Terminals : ETF Enter No. of Terminals : 5 Enter Terminals : +*()i Enter Productions : E->E+T E->T T->T*F T->F F->(E) F->i LEADING E ( i * + T ( i * F ( i TRAILING E ) i * + T ) i * F ) i The Operator Precedence Grammar Is : + * ( ) I $ + > < < > < > * > > < > < > ( < < < = < ) > > > > I > > > > $ < < < <

Page 70: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

70

Practical 09 Write a C program which accepts the following SPM and Linearize it to obtain SPM functions (f and g) and display them in suitable format. SPM: Z M L a b ( ) ______________________________________ Z | M | = = L | > > a | > > = b | = < < ( | < = < < ) | > >

Algorithm:-

Begin 1. Take input of grammar definition. 2. Take input of SPM. 3. Generate Matrix B[][] using following Algorithm

• Set Upper Left and Lower Right Quarter Matrix element to 0’s. • Place Less-Than matrix to Lower Left Quarter. • Place Greater-Than matrix to Upper Left Quarter. • Set diagonal elements of Matrix to 1.

4. Apply Warshall’s Algorithm on Matrix B[][]. 5. Calculate f and g using output matrix of Warshall’s algorithm. 6. Stop.

End

Page 71: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

71

Code:- #include <stdio.h> char G[50], NTs[20], Ts[20], SPMEntry[100]; int N_Ts, N_NTs, SPM[50][50], B[100][100], SPF[50][50]; void input(); char relation(char, char); void main() { int i,j,n,k,l; clrscr(); input(); n=strlen(SPMEntry); for(i=0;i<n;i++) { for(j=0;j<n;j++) { B[i][j]=0; // Upper Left Quarter B[i+n][n+j]=0; // Lower Right Quarter if(relation(SPMEntry[i],SPMEntry[j])=='>'

||relation(SPMEntry[i],SPMEntry[j])=='=') B[i][n+j]=1; // Upper Right Quarter if(relation(SPMEntry[i],SPMEntry[j])=='<'

||relation(SPMEntry[i],SPMEntry[j])=='=') B[j+n][i]=1; // Lower Left Quarter if(i==j) // Diagonally { B[j][i]=1; B[j+n][i+n]=1; } } } printf("\n\nMatrix B : \n"); //Display Matrix B for(i=0;i<n*2;i++) { printf("\n"); for(j=0;j<n*2;j++) printf(" %d ",B[i][j]); } //Warshall's Alogorithm On Matrix B for (k = 0; k < n*2; k++) { for (i = 0; i < n*2; i++) { for (j = 0; j < n*2; j++) { if (! B[i][j]) B[i][j] = B[i][k] && B[k][j]; } } } //Calculate f and g for(i=0;i<n*2;i++) { SPF[0][i]=0;

Page 72: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

72

SPF[1][i]=0; for(j=0;j<n*2;j++) { if(i<n) { SPF[0][i]=SPF[0][i]+B[i][j]; } else { SPF[1][i-n]=SPF[1][i-n]+B[i][j]; } } } printf("\n\nSimple Precedence Function Table Is :”); printf(“\n\n f\tg\n _________\n"); for(i=0;i<n;i++) { printf("\n%c| %d\t%d",SPMEntry[i],SPF[0][i],SPF[1][i]); } getch(); } // To return the relation between symbols in SPM char relation(char c1, char c2) { int i,j; for(i=0;i<N_Ts+N_NTs;i++) { if(SPMEntry[i]==c1) { for(j=0;j<N_Ts+N_NTs;j++) { if(SPMEntry[j]==c2) return(SPM[i][j]); } } } return(' '); } //To Extract NT's From Grammar Definition void input() { int i=2,j=0,k=0; printf("Enter Grammar Definition : "); gets(G); while(G[i] != '}') { if(G[i++]!=',') { NTs[j++]=G[i-1]; SPMEntry[k++]=G[i-1]; } } NTs[j]='\0'; N_NTs=j; //To Extract T's From Grammar Definition i=i+3;

Page 73: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

73

j=0; while(G[i] != '}') { if(G[i++]!=',') { Ts[j++]=G[i-1]; SPMEntry[k++]=G[i-1]; } } Ts[j]='\0'; SPMEntry[k]='\0'; N_Ts=j; printf("\n\nEnter Simple Precedence Matrix : \n\n "); for(i=0;i<N_Ts+N_NTs;i++) printf(" %c",SPMEntry[i]); printf("\n "); for(i=0;i<((N_Ts+N_NTs)*5);i++) printf("_"); for(i=0;i<N_Ts+N_NTs;i++) { printf("\n%c | ",SPMEntry[i]); for(j=0;j<N_Ts+N_NTs;j++) { printf(" "); SPM[i][j]=getche(); } } }

Page 74: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

74

Output:- Enter Grammar Definition: ({Z, M, L}, {a, b, (,)}, {Z}, {M}) Enter Simple Precedence Matrix: Z M L a b ( ) ______________________________________ Z | M | = = L | > > a | > > = b | = < < ( | < = < < ) | > > Matrix B: 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 Simple Precedence Function Table Is: f g _____________ Z | 1 1 M | 7 4 L | 8 2 A | 9 7 B | 4 7 ( | 2 5 ) | 8 9

Page 75: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

75

Declared Variables:- char G[] - To store the Grammer Definition. char NTs[] - To store the NTs extracted from Grammar. char Ts[] - To store the Ts extracted from Grammar. char SPMEntry[] - To store the Simple Precedance Matrix entries. int N_Ts - To store the number of Terminals. int N_NTs - To store the number of Non Terminals. char SPM[][] - To store the Simple Precedance Matrix. int B[][] - To Matrix Manipulation. intSPF[][] - To store the SPF Matrix. Declared Functions:- Void input() - To take Input. Char relation(char,char) - To return the relation between symbols in SPM.

Page 76: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

76

Practical 10 Write a C-program which accepts the following Simple Precedence functions and parse the strings given below and display them.

Z M L a b ( ) f 1 7 8 9 4 2 8 g 1 4 2 7 7 5 9

Grammar G: {N, T, P, S} Productions P: Z bMb M (L M a L Ma)

Strings:

i. b(aa)b ii. b((aa)a)b

iii. b((aaa)a)b Show step-by-step reduction. Algorithm:-

Begin 8. Take input of grammar definition. 9. Take input of production used. 10. Take input of f and g functions. 11. Take input string to be parsed. 12. Searche handle in Input String and replace it with respective NT. 13. If we reach to start symbol of grammar, then string is valid else invalid.

End

Page 77: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

77

Code:- #include "MSCI.h" /*Initialization*/ int *inputf,*inputg; Production prod[10]; int i=0,j=0,k=0,less=0,greater=0; int nos,nop; char *symbol,c,inputstr[50],handleStart,handleEnd,*handle,*handle1; void print(); void parseString(); char compare(char,char); void createHandle(); void checkNreplace(char *); void main() { clrscr(); printf("PROGRAM: SIMPLE PRECEDENCE FUNCTIONS..\n"); // Taking Input printf("Enter number of Symbols : "); scanf("%d",&nos); symbol = (char *)malloc((nos+1)*sizeof(char)); printf("Enter the Symbols: (NTs followed by Ts): "); scanf("%s",symbol); printf("Enter no of Productions : "); scanf("%d",&nop); for(i=0;i<nop;i++) { getProduction(&prod[i]); } inputf=(int *)malloc((nos+1)*sizeof(int)); inputg=(int *)malloc((nos+1)*sizeof(int)); fflush(stdin); for(i=0;i<nos;i++) { printf("Enter f(%c): ",symbol[i]); scanf("%d",&inputf[i]); } for(i=0;i<nos;i++) { printf("Enter g(%c): ",symbol[i]); scanf("%d",&inputg[i]); } printf("Enter The String To Be Parsed: "); scanf("%s",&inputstr); printf("Please Wait"); sleep(1); printf("."); sleep(1); printf("."); sleep(1); clrscr(); // Printing Input print(); parseString(); getch();

Page 78: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

78

} void print() { printf("PROGRAM: SIMPLE PRECEDENCE FUNCTIONS..\n\n"); printf("Symbols: %s\n\n",symbol); printf("\t"); for(i=0;i<nos;i++) { printf("%c\t",symbol[i]); } printf("\n\n"); printf("%c\t",'f'); for(i=0;i<nos;i++) { printf("%d\t",inputf[i]); } printf("\n%c\t",'g'); for(i=0;i<nos;i++) { printf("%d\t",inputg[i]); } printf("\n\nString To Be Parsed: %s\n\n",inputstr); getch(); } void parseString() { int ctr1=0; for(ctr1=0;ctr1<strlen(inputstr)-1;ctr1++) { // If Starting Symbol Found if(strcmp(inputstr,prod[0].right)==0) { printf("\nFound Starting Symbol : %c\n",prod[0].left); printf("\n\nString Successfully Parsed\n"); getch(); exit(0); } // Start Handle if(compare(inputstr[ctr1],inputstr[ctr1+1])=='<') { handleStart=inputstr[ctr1+1]; less=ctr1+1; continue; } // Handle End if(compare(inputstr[ctr1],inputstr[ctr1+1])=='>') { handleEnd=inputstr[ctr1]; greater=ctr1; createHandle(); checkNreplace(handle); ctr1=-1; i=0; continue; } } printf("\nString Parsed Unsuccessfully..\n");

Page 79: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

79

} // Return Value From SPM Matrix char compare(char a,char b) { int val1=findPos(symbol,a); int val2=findPos(symbol,b); val1=inputf[val1]; val2=inputg[val2]; if(val1==val2) return '='; if(val1<val2) return '<'; if(val1>val2) return '>'; else return ' '; } // Create Handle void createHandle() { int val1=less; int val2=greater; int a=0,b=0,ctr1=0; free(handle); handle=(char *)malloc((abs(val2-val1)+1)*sizeof(char)); if(val1>val2) { a=val2; b=val1; } if(val1<val2) { a=val1; b=val2; } if(val1==val2) { a=val1; b=val2; } for(;a<=b;a++) { handle[ctr1]=inputstr[a]; ctr1++; } handle[ctr1]='\0'; printf("\nHandle is : %s.\n",handle); } // Check Handle In Input String And Replace It With Appropriate NT void checkNreplace(char *handle) { int ctr1=0; free(handle1); handle1[0]='\0'; for(ctr1=0;ctr1<nop;ctr1++) { if(strcmp(handle,prod[ctr1].right)==0)

Page 80: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

80

{ free(handle1); handle1=(char *)calloc(2,sizeof(char)); handle1[0]=prod[ctr1].left; break; } } handle1[1]='\0'; printf("\nReplacing by : %s.\n",handle1); char temp[50]; int ctr2=0; for(ctr1=0;ctr1<50;ctr1++) { if(ctr1==less) { temp[ctr2]=handle1[0]; ctr2++; while(less<=greater) { ctr1++; less++; } temp[ctr2]=inputstr[ctr1]; ctr2++; } else { temp[ctr2]=inputstr[ctr1]; ctr2++; } } temp[ctr2]='\0'; ctr1=0; while(temp[ctr1]!='\0') { inputstr[ctr1]=temp[ctr1]; ctr1++; } inputstr[ctr1]='\0'; printf("\nNew Input String: %s\n",inputstr); getch(); }

Page 81: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

81

Output:- PROGRAM: SIMPLE PRECEDENCE FUNCTIONS.. Enter number of Symbols : 7 Enter the Symbols: (NTs followed by Ts): ZMLab() Enter no of Productions : 4 Enter the Production (eg A -> B):Z -> bMb Enter the Production (eg A -> B):M -> (L Enter the Production (eg A -> B):M -> a Enter the Production (eg A -> B):L -> Ma) Enter f(Z): 1 Enter f(M): 7 Enter f(L): 8 Enter f(a): 9 Enter f(b): 4 Enter f((): 2 Enter f()): 8 Enter g(Z): 1 Enter g(M): 4 Enter g(L): 2 Enter g(a): 7 Enter g(b): 7 Enter g((): 5 Enter g()): 9 Enter The String To Be Parsed: b(aa)b Please Wait.. <<THE SCREEN IS CLEARED>> PROGRAM: SIMPLE PRECEDENCE FUNCTIONS.. Symbols: ZMLab() Z M L a b ( ) f 1 7 8 9 4 2 8 g 1 4 2 7 7 5 9 String To Be Parsed: b(aa)b Handle is : a. Replacing by : M. New Input String: b(Ma)b Handle is : Ma). Replacing by : L. New Input String: b(Lb

Page 82: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

82

Handle is : (L. Replacing by : M. New Input String: bMb Found Starting Symbol : Z String Successfully Parsed PROGRAM: SIMPLE PRECEDENCE FUNCTIONS.. Enter number of Symbols : 7 Enter the Symbols: (NTs followed by Ts): ZMLab() Enter no of Productions : 4 Enter the Production (eg A -> B):Z -> bMb Enter the Production (eg A -> B):M -> (L Enter the Production (eg A -> B):M -> a Enter the Production (eg A -> B):L -> Ma) Enter f(Z): 1 Enter f(M): 7 Enter f(L): 8 Enter f(a): 9 Enter f(b): 4 Enter f((): 2 Enter f()): 8 Enter g(Z): 1 Enter g(M): 4 Enter g(L): 2 Enter g(a): 7 Enter g(b): 7 Enter g((): 5 Enter g()): 9 Enter The String To Be Parsed: b((aa)a)b Please Wait.. <<THE SCREEN IS CLEARED>> PROGRAM: SIMPLE PRECEDENCE FUNCTIONS.. Symbols: ZMLab() Z M L a b ( ) f 1 7 8 9 4 2 8 g 1 4 2 7 7 5 9 String To Be Parsed: b((aa)a)b Handle is : a. Replacing by : M.

Page 83: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

83

New Input String: b((Ma)a)b Handle is : Ma). Replacing by : L. New Input String: b((La)b Handle is : (L. Replacing by : M. New Input String: b(Ma)b Handle is : Ma). Replacing by : L. New Input String: b(Lb Handle is : (L. Replacing by : M. New Input String: bMb Found Starting Symbol : Z String Successfully Parsed PROGRAM: SIMPLE PRECEDENCE FUNCTIONS.. Enter number of Symbols : 7 Enter the Symbols: (NTs followed by Ts): ZMLab() Enter no of Productions : 4 Enter the Production (eg A -> B):Z -> bMb Enter the Production (eg A -> B):M -> (L Enter the Production (eg A -> B):M -> a Enter the Production (eg A -> B):L -> Ma) Enter f(Z): 1 Enter f(M): 7 Enter f(L): 8 Enter f(a): 9 Enter f(b): 4 Enter f((): 2 Enter f()): 8 Enter g(Z): 1 Enter g(M): 4 Enter g(L): 2 Enter g(a): 7 Enter g(b): 7 Enter g((): 5

Page 84: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

84

Enter g()): 9 Enter The String To Be Parsed: b((aaa)a)b Please Wait.. <<THE SCREEN IS CLEARED>> PROGRAM: SIMPLE PRECEDENCE FUNCTIONS.. Symbols: ZMLab() Z M L a b ( ) f 1 7 8 9 4 2 8 g 1 4 2 7 7 5 9 String To Be Parsed: b(aaa)a)b Handle is : a. Replacing by : M. New Input String: b(Maa)a)b Handle is : Ma. Replacing by : . New Input String: b( String Parsed Unsuccessfully..

Page 85: Compilers PaperI Section I

THAKUR COLLEGE OF SCIENCE & COMMERCE (UNIVERSITY OF MUMBAI)

85

Declared Variables:- int *inputf - Stores f(Symbol) values int *inputg - Stores g(Symbol) values Production prod[10] - Stores the Production rules int nos - Stores the no of Symbols int nop - Stores the no of Productions char *symbol - Stores the Symbols char inputstr[50] - Stores the string to be parsed char *handle - Stores the handle found Declared Functions:- void print() - Prints the data input void parseString() - Parses the Input String char compare(char,char) - Returns value from SPM Matrix void createHandle() - Creates Handle from Input String void checkNreplace(char *) - Replaces Handle from Input String with

appropriate NT