Sunteți pe pagina 1din 66

1

bdghEX. NO: 1 DATE:

CONSTRUCTION OF NFA FROM A GIVEN REGULAR EXPRESSION


AIM:erwhyerh
To write a C program to convert the regular expression to NFA.

ALGORITHM:
1. Start the program 2. Get the regular expression from the user 3. Build a finite automatgfon with one final state (and one start state) 4. Use the recursisgdfve definition of regular expressions to build a finite automaton for a compound expressiofgfn from the finite automata for the base expressions 5. Repeat the procedure to construct the NFA for the given regular expression 6. Display the NFA structure. 7. Stop the program

PROGRAM:
#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<strifgdfng.h> #include<ctfsdfggfdsgg58ype.h> struct s1 { int from,to; }; typedef struct s1 s2; struct ed {

sgfdint from[30],to[30],n; char on[30]; }; typedef struct ed edg; int top=0,start,end; s2 s3[100]; edg edg1,edg2; s2 pop() { top--; return s3[top]; } void push(s2 a) {fgs3[top]=a; top++; } int f(char a) { if(a=='/') return 1; if(a=='.') return 3; if(isalnum(a)) return 5; if(a=='(') return 7; if(a==')') return 0; return -1; } int g(cfdgshar a) { if(a=='/') return 2; if(a=='.') return 4; if(isalnfgdfgum(a)) return 6; if(a=='(') return 0;

if(a==')') return 8; return -1; } char *postfix(char in1[]) { int i=0,j=0,top=0,a,l,t=0; g l=strlen(in1); in=malloc(100); for(;t<l;t++) in[t]=in1[t]; in[l]=')'; in[l+1]='\0'; s[top]='('; while(AGDSFin[i]!='\0') { if(top<0) { printf("\n ERROR"); exit(0); } if(in[i]=='*') { s[++top]='*'; i++;GASFDG conASGtinue; } while(1) { a=0;AF char s[100],*out,*in;

if(s[toGNWTHSRp]=='*') a=1; SS else { out[j++]=s[top-a]; if(a) out[j++]=s[top]; top-=(a+1); } } if(f(in[i])!=g(s[top])) s[++top]=in[i]; elseHSDGH { toSDGHp--; if(in[i+1]=='*') { out[j++]='*'; i++; } } i++; } if(toDHSFHp!=-1) { printf("\n ERROR"); exit(1QSDFH0)DFHSH; } out[j]='\0'; reDFHSZFHrhgasfturn out; } grcon(char *v)

{ int i=0,l=0,k; ssdfhszdfh2 a,b; edgdsafhsh1.n=0; whsdzghshile(v[i]) { if(isasdfhlnum(v[i])) { edg1.fsfdhromdfhszfh[edg1.n]=++l; edg1.to[dfhsdfhedg1.n]=++l; edg1.osdfhdfhn[edg1.n]=v[i]; a.from=edg1.from[edg1.n]; a.tsfhsdfho=edg1.to[edg1.n]; edgdfhszdfh1.n++; pdfshdfush(a); } elsdhfe fdhsif(v[i]=='*') { a=psdfhsop(); edg1dhfsdf.from[edg1.n]=a.to; edg1.dsfhdfhto[edg1.n]=a.from; edgsdfhsdfh1.on[edg1.n]='E'; edg1.n++; edg1.fshfdhsdfhdhrom[edg1.n]=++l; edg1.to[edg1.n]=a.from; edg1.on[edg1.n]='E'; edshfdhg1.n++; eddshsdhg1.from[edg1.n]=a.to; edhsdg1.to[edg1.n]=++l; edgshdfh1.on[edg1.n]='E'; eddfhg1.n++;

edsdfhg1.from[edg1.n]=l-1; edsfdhg1.tsdho[edg1.n]=l; edfsdhg1sdfhhfdhs.on[edg1.n]='E'; edsdfhg1.n++; a.fdhsfdhfrom=l-1; a.thssdfho=l; pufdshsdfsh(a); } else if(v[i]=='.') { b=pop(); a=pop(); for(k=0;k<edg1.n;k++) { if(edg1.from[k]==a.to) edg1.from[k]=b.from; if(edg1.to[k]==a.to) edg1.to[k]=b.from; } a.to=b.to; push(a); } else if(v[i]=='/') { b=pop(); a=pop(); edg1.from[edg1.n]=++l; edg1.to[edg1.n]=a.from; edg1.on[edg1.n]='E'; edg1.n++; edg1.from[edg1.n]=l;

edg1.to[edg1.n]=b.from; edg1.on[edg1.n]='E'; edg1.n++; edg1.from[edg1.n]=b.to; edg1.to[edg1.n]=++l; edg1.on[edg1.n]='E'; edg1.n++; edg1.from[edg1.n]=a.to; edg1.to[edg1.n]=l; edg1.on[edg1.n]='E'; edg1.n++; a.from=l-1; a.to=l; push(a); } i++; } a=pop(); start=a.from; end=a.to; return 0; }

void main() { int i; char re[20]; clrscr(); printf(" Enter the Expression\t:"); scanf("%s",re);

grcon(postfix(re)); printf("\n START =%d \n FINAL =%d ",start,end); printf("\n\n Here E is considered as epsilon\n"); for(i=0;i<edg1.n;i++) printf("\n %2d %2d %c",edg1.from[i],edg1.to[i],edg1.on[i]); getch(); }

OUTPUT:
Enter the Expression : (a/b)* START =7 FINAL =8 Here E is considered as epsilon 1 2 a

3 5 5 4 2 6 7 6 7

4 1 3 6 6 5 5 8 8

b E E E E E E E E

RESULT:
Thus the C program for construction of NFA from Regular expression is executed and verified.

EX. NO: 2 DATE:

MINIMIZATION OF DFA FROM REGULAR EXPRESSION


AIM:
To write a C program for minimization of DFA from regular expression

ALGORITHM:

10

1. Start the program. 2. Get the regular expression from user. 3. Construct the Postfix for the given expression. 4. Convert the regular expression to DFA using conversion algorithm. 5. Display the result. 6. Stop the Program.

PROGRAM:
#include <stdio.h> #include <conio.h> #include <string.h> #include <ctype.h> #define N 30 int Pos[N],Posct,Lng, Rlnk[N], Llnk[N], Root, Nl[N]; char Str[N], Type[N], FoPos[N][N], FPos[N][N], LPos[N][N]; char Inp[N], Sym[N], DSts[N+N][N]; int DStct, DTran[N+N][N]; int IsTerm (char c) { return (isalpha (c) || c == '#'); } int Val (char c) { return (int)c - (int)'0'; } char State (int c) { if (c == -1) return '-'; return (char) ((int) 'A' + c); }

11

void Sort (char s[]) { int i,l, c = 1; char ch; for ( l=0; s[l]!='\0'; l++); while (c) { c=0; for (i=1; i<l; i++) if (s[i] < s[i-1]) { ch = s[i]; s[i] = s[i-1]; s[i-1] = ch; c++; } } } void Add (char s1[], char s2[]) { int fnd,l1,i,j; for ( l1=0; s1[l1]!='\0'; l1++); for ( i=0; s2[i]!='\0'; i++) { fnd = 0; for ( j=0; j<l1; j++) { if (s1[j] == s2[i])

12

{ fnd = 1; j = l1; } } if (fnd == 0) s1[l1++] = s2[i]; } s1[l1] = '\0'; Sort (s1); } void Find (int Nd) { if (Nd == -1) return; if (IsTerm (Str[Nd])) { Nl[Nd] = 0; FPos[Nd][0] = LPos[Nd][0] = (char) (Pos[Nd] + (int) '0'); FPos[Nd][1] = LPos[Nd][1] = '\0'; } else { int Left = Llnk[Nd], Right = Rlnk[Nd]; Find (Left); Find (Right); if (Str[Nd] == '/') { Nl[Nd] = (Nl[Left] || Nl[Right]) ? 1 : 0; strcpy (FPos[Nd], FPos[Left]); Add (FPos[Nd], FPos[Right]); strcpy (LPos[Nd], LPos[Left]); Add (LPos[Nd], LPos[Right]);

13

} else if (Str[Nd] == '.') { Nl[Nd] = (Nl[Left] && Nl[Right]) ? 1 : 0; strcpy (FPos[Nd], FPos[Left]); if (Nl[Left]) Add (FPos[Nd], FPos[Right]); strcpy (LPos[Nd], LPos[Right]); if (Nl[Right]) Add (LPos[Nd], LPos[Left]); } else if (Str[Nd] == '*') { Nl[Nd] = 1; strcpy (FPos[Nd], FPos[Left]); strcpy (LPos[Nd], LPos[Left]); } } } void FolPos (int Nd) { int Left = Llnk[Nd], Right = Rlnk[Nd]; int i; if (Nd == -1) return; if (IsTerm (Str[Nd])) return; FolPos (Left); FolPos (Right); if (Str[Nd] == '.') { for ( i=0; LPos[Left][i]!='\0'; i++) Add (FoPos[Val (LPos[Left][i])], FPos[Right]);

14

} else if (Str[Nd] == '*') { for ( i=0; LPos[Left][i]!='\0'; i++) Add (FoPos[Val (LPos[Left][i])], FPos[Left]); } } void ConvPostFix () { char s[N], St[N]; int Top = -1, i, j, k; strcpy (s, Str); for (i=j=0; i<Lng; i++) { if (IsTerm (s[i])) Str[j++] = s[i]; else if (s[i] == '(') St[++Top] = '('; else if (s[i] == ')') { while (St[Top] != '(') Str[j++] = St[Top--]; Top--; } else if (s[i] == '*') Str[j++] = '*'; else if (Str[i] == '/') St[++Top] = s[i]; else if (s[i] == '.') {

15

while (Top >= 0 && St[Top] != '(') Str[j++] = St[Top--]; St[++Top] = s[i]; } } while (Top >= 0) Str[j++] = St[Top--]; Str[j] = '\0'; Lng = j; } void FormTree () { char c[2]; int i; int Asgn[N], Ct = 0; c[1] = '\0'; for ( i=0; i<Lng; i++) { if (IsTerm (Str[i])) { c[0] = Str[i]; Add (Inp, c); Sym[Posct] = Str[i]; Pos[i] = Posct++; } else Pos[i] = -1; } Root = Lng - 1;

16

for (i=0; i<Lng; i++) { Llnk[i] = Rlnk[i] = -1; if (IsTerm(Str[i])) Asgn[Ct++] = i; else { if (Str[i] == '*') Llnk[i] = Asgn[--Ct]; else { Rlnk[i] = Asgn[--Ct]; Llnk[i] = Asgn[--Ct]; } Asgn[Ct++] = i; } } } void FindN_F_L () { int i; Find (Root); for (i=0; i<Posct; i++) FoPos[i][0] = '\0'; FolPos (Root); } void GetRE(char s[]) { char ss[N]; int loop=1,i,j; strcat (s, "#");

17

Str[0] = s[0]; ss[0] = s[0]; while (loop) { loop = 0; for ( i=1,j=1; s[i]!='\0';i++) { ss[j++] = s[i]; if (s[i] ==')' && s[i-1] == '(') { loop++; j -= 2; } } ss[j] = '\0'; } for ( i=1; s[i] != '\0'; i++) { if ((IsTerm (s[i]) && (IsTerm (s[i-1]) || s[i-1] == '*' || s[i-1] == ')')) || (s[i] == '(' && s[i-1] != '(' && s[i-1] != '/')) Str[++Lng] = '.'; Str[++Lng] = s[i]; } Str[++Lng] = '\0'; ConvPostFix (); } void ConDFA () { char c[N];

18

int fnd,i,j,k; FormTree (); FindN_F_L (); strcpy(DSts[0], FPos[Root]); DStct = 1; for ( i=0; i<DStct; i++) { for ( j=1; Inp[j]!='\0'; j++) { DTran[i][j] = -1; strcpy (c, ""); for ( k=0; DSts[i][k] != '\0'; k++) if (Sym[Val (DSts[i][k])] == Inp[j]) Add (c, FoPos[Val (DSts[i][k])]); if (strcmp (c, "")) { fnd = 0; for (k=0; k<DStct; k++) if (!strcmp (DSts[k], c)) { DTran[i][j] = k; fnd++; break; } if (fnd == 0) { strcpy (DSts[DStct], c); DTran[i][j] = DStct++; }

19

} } } } void Print () { int i,j; printf(" \nPostFix Form : " ); printf( "%s",Str); printf( "\n\nState\t"); for ( i=1; Inp[i]!='\0'; i++) printf("%c\t",Inp[i]);// printf("\t"); printf( "\n-"); for (i=1; Inp[i]!='\0'; i++) printf( "--------"); for (i=0; i<DStct; i++) { printf("\n"); printf( "%c\t",State (i)); for ( j=1; Inp[j]!='\0'; j++) printf("%c\t", State (DTran[i][j]) ); if (i == 0) printf( "Start Sate "); if (Val (DSts[i][strlen (DSts[i])-1]) == Posct - 1) printf("Final State"); } } void main () { char *s; clrscr (); printf("Enter the Regular Expression : "); scanf("%s",s);

20

GetRE (s); ConDFA (); Print (); getch (); }

OUTPUT:
Enter the Regular Expression: (a/b)*abb PostFix Form: ab/*a.b.b.#. State A B C D a B B B B b A C D A Final State Start State

---------------------------------------

21

RESULT:
Thus the C program for construction of DFA from a Regular expression is executed and verified.

EX. NO: 3 DATE:

IMPLEMENTATION OF LEXICAL ANALYSIS USING LEX TOOL


AIM:
To write a C program to implement lexical analysis using LEX tool.

ALGORITHM:
1. Start the program. 2. Lex program consists of three parts. Declaration %% Translation rules %% Auxilary procedure. 3. The declaration section includes declaration of variables, maintest, constants and regular definitions. 4. Translation rule of lex program are statements of the form P1 {action} P2 {action}

22

Pn {action} 5. Write a program in the vi editor and save it with .l extension. 6. Compile the lex program with lex compiler to produce output file as lex.yy.c. Eg: $ lex filename.l $ cc lex.yy.c -ll 7. Compile that file with C compiler and verify the output. Eg: $ ./a.out inputfilename.c 8. Stop the program.

PROGRAM:
%{ %} digit[0-9]+ identifier[a-zA-Z][a-zA-Z0-9]* %% #.* printf("%s is a preprocessor directive\n",yytext); int | float | double | if | char | goto printf("%s is a keyword\n",yytext); {identifier}\(\) printf("%s is a function \n",yytext); \{ printf("%s block begin\n",yytext); \} printf("%s block end \n",yytext); {identifier}(\[0-9]*\])? printf("%s is identifier\n",yytext); \"+\" printf("%s is string\n",yytext); -{digit} printf("%s is anegative number\n",yytext); "+"?{digit} printf("%s is a positive number\n",yytext);

23

\; | \( | \) printf("%s is a special operator\n",yytext); \= printf("%s is a assignment operator\n",yytext); \< | \> | \<= | \>= printf("%s is a relation operator\n",yytext); %% int main(int argc,char *argv[]) { if(argc>1) { FILE *fp; fp=fopen(argv[1],"r"); if(!fp) { printf("cant open"); exit(0); } yyin=fp; yylex(); } return(0); }

INPUT:
#include<stdio.h> void main()

24

{ int a,b; a=10; b=20; }

OUTPUT:
[cse4@localhost ~]$ lex cse.l [cse4@localhost ~]$ cc lex.yy.c -ll [cse4@localhost ~]$ ./a.out input.c #include<stdio.h> is a preprocessor directive void is identifier main() is a function { block begin int is a keyword a is identifier ,b is identifier ; is a special operator a is identifier = is a assignment operator 10 is a positive number ; is a special operator b is identifier = is a assignment operator 20 is a positive number ; is a special operator

25

} block end

RESULT:
Thus the program for implementation of lexical analysis using lex tool is executed and verified.

EX. NO: 4 DATE:

IMPLEMENTATION OF SYMBOL TABLE


AIM:
To write a C program to implement the symbol table.

ALGORITHM:
1. Start the program 2. Declare the variables 3. Display the menu for the user 1. Insert the user. 5. Index and next position is generated by the values of token, attribute and position 6. To delete a value in the symbol table, get the value of token. 7. To search a token, get the value of token and search it in symbol table. 8. Stop the program. 2. Delete 3. Lookup 4. Exit 4. To insert a value in the symbol table, get the values of token, attribute and position from

PROGRAM:
#include<stdio.h> #include<conio.h> #include<alloc.h>

26

#include<string.h> #include<stdlib.h> #define NULL 0 int size=0; void insert(); void del(); int search(char lab[]); void display(); void dis(char le[]); struct symtab { char label[10]; char att[10]; int addr; struct symtab *next; }; struct symtab *first,*last; void main() { int op; int y; char la[10]; clrscr(); do { printf("\n SYMBOL TABLE IMPLEMENTATION \n") ; printf("\n 1.Insert \n"); printf("\n 2.Delete \n"); printf("\n 3.Lookup \n"); printf("\n 4.Exit \n"); printf("\n Enter your choice: \n");

27

scanf("%d",&op); switch(op) { case 1: insert(); display(); break; case 2: del(); display(); break; case 3: printf("\n Enter the label to be searched:"); scanf("%s",&la); y=search(la); if(y==1) { printf("\n The label is present in the symbol table"); dis(la); } else printf("\n The lable is not found in the symbol table"); break; case 4: break; } } while(op<4); getch(); } void insert()

28

{ int n; char l[10]; printf("\n Enter the token:"); scanf("%s",&l); n=search(l); if(n==1) printf("\n The token is already exists duplicate can't be inserted \n"); else { struct symtab *p; p=malloc(sizeof(struct symtab)); strcpy(p->label,l); printf("\n Enter the position:"); scanf("%d",&p->addr); printf("\n Enter the attribute:"); scanf("%s",&p->att); p->next=NULL; if(size==0) { first=p; last=p; } else { last->next=p; last=p; } size++; } }

29

void display() { int i; struct symtab *p; p=first; printf("\n Index \t Next \t Token \t Attribute \t Position \n"); for(i=0;i<size;i++) { printf("\n %d \t %d \t %s \t %s \t %d \n",i,i+1,p->label,p->att,p->addr); p=p->next; } } int search(char lab[]) { int i,flag=0; struct symtab *p; p=first; for(i=0;i<size;i++) { if(strcmp(p->label,lab)==0) { flag=1; } p=p->next; } return flag; } void del() { int a; char l[10];

30

struct symtab *p,*q; p=first; printf("\n Enter the label to be deleted: \n"); scanf("%s",l); a=search(l); if(a==0) printf("\n The label is not found"); else { if(strcmp(first->label,l)==0) { first=first->next; } else if(strcmp(last->label,l)==0) { q=p->next; while(strcmp(q->label,l)!=0) { p=p->next; q=q->next; } p->next=NULL; last=p; } else { q=p->next; while(strcmp(q->label,l)!=0) { p=p->next;

31

q=q->next; } p->next=q->next; } size--; } } void dis(char le[]) { int i; struct symtab *p; p=first; printf("\n Index \t Next \t Token \t Attribute \t Position \n"); for(i=0;i<size;i++) { if(strcmp(p->label,le)==0) { printf("\n %d \t %d \t %s \t %s \t %d \n",i,i+1,p->label,p->att,p->addr); break; } else p=p->next; } }

OUTPUT:

32

SYMBOL TABLE IMPLEMENTATION 1. Insert 2. Delete 3. Lookup 4. Exit Enter your choice: 1 Enter the token: c Enter the position: 4 Enter the attribute: identifier Index Next Token Attribute 0 1 2 3 4 1 2 3 4 5 a = b + c identifier operator identifier operator identifier Position 1 2 0 3 0

SYMBOL TABLE IMPLEMENTATION 1. Insert 2. Delete 3. Lookup 4. Exit Enter your choice: 2 Enter the label to be deleted: c

Index Next Token Attribute 0 1 a Identifier

Position 1

33

1 2 3

2 3 4

= b +

operator identifier operator

2 0 3

SYMBOL TABLE IMPLEMENTATION 1. Insert 2. Delete 3. Lookup 4. Exit Enter your choice: 3 Enter the label to be searched: a The label is present in the symbol table Index Next Token Attribute 0 1 a identifier Position 1

SYMBOL TABLE IMPLEMENTATION 1. Insert 2. Delete 3. Lookup 4. Exit Enter your choice: 4

RESULT:
Thus the program for implementation of symbol table is executed and verified.

EX. NO: 5 DATE:

34

IMPLEMENTATION OF OPERATOR PRECENDENCE PARSING


AIM:
To write a C program to implement operator precedence parsing algorithm.

ALGORITHM:
Input: An input string w and a table of precedence relations. Output: If w is well formed, a skeletal parse tree, with a placeholder nonterminal E labeling all interior nodes; otherwise, an error indication. Method: Initially, the stack contains $ and the input buffer the string w$. set ip to point to the first symbol of w$; repeat forever if $ is on top of the stack and ip points to $ then return else begin let a be the topmost terminal symbol on the stack and let b be the symbol pointed to by ip; if a < b or a = b then begin push b onto the stack; advance ip to the next input symbol; end; else if a> b then repeat pop the stack until the top stack terminal is related by < to the terminal most recently popped else error() end

35

PROGRAM:
#include<stdio.h> #include<conio.h> #define msize 40 struct stack { int top; char item[msize]; }s; void main() { int i,j,re; char *in; char c1,c2; s.top=-1; clrscr(); printf("Enter the input language\n"); scanf("%s",in); printf("\nStack \t\tInput\t\tActions\n\n"); push(&s,'$'); printf("$\t\t\t"); for(i=0;in[i];i++) printf("%c",in[i]); printf("$\tInitial\n"); for(i=0;in[i];i++) { re=check(s.item[s.top],in[i]); if(re==1)

36

{ push(&s,in[i]); for(j=0;j<=s.top;j++) printf("%c",s.item[j]); printf("\t\t\t"); for(j=i+1;in[j];j++) printf("%c",in[j]); printf("$\t\t"); printf("push(%c<%c)\n",s.item[s.top-1],in[i]); } else { pop(&s); for(j=0;j<=s.top;j++) printf("%c",s.item[j]); printf("\t\t\t"); for(j=i;in[j];j++) printf("%c",in[j]); printf("$\t\t"); printf("pop(%c>%c)\n",s.item[s.top+1],in[i]); while(re==0) { c1=s.item[s.top]; c2=s.item[s.top+1]; re=check(c1,c2); if(re==1) { re=check(s.item[s.top],in[i]); if(re==1) { push(&s,in[i]);

37

for(j=0;j<=s.top;j++) printf("%c",s.item[j]); printf("\t\t\t"); for(j=i+1;in[j];j++) printf("%c",in[j]); printf("$\t\t"); printf("push(%c<%c)\n",s.item[s.top-1],in[i]); break; } else { pop(&s); for(j=0;j<=s.top;j++) printf("%c",s.item[j]); printf("\t\t\t"); for(j=i;in[j];j++) printf("%c",in[j]); printf("$\t\t"); printf("pop(%c>%c)\n",s.item[s.top+1],in[i]); } } } } if(in[i+1]==NULL) while(s.item[s.top]!='$') { re=check(s.item[s.top],'$'); if(re==0) pop(&s); for(j=0;j<=s.top;j++) printf("%c",s.item[j]);

38

printf("\t\t\t"); printf("$"); printf("\t\tpop(%c>$)\n",s.item[s.top+1]); } } if(s.top==0) printf("\nACCEPTED"); else printf("\nERROR"); getch(); } int check(char st,char ip) { char id[8]={'+','-','*','i','$','/','(',')'}; char pre[8][8]={{'=','>','<','<','>','<','<','>'}, {'>','=','<','<','>','<','<','>'}, {'>','>','=','<','>','>','<','>'}, {'>','>','>','=','>','>','0','>'}, {'<','<','<','<','=','<','<','0'}, {'>','>','>','<','>','=','<','>'}, {'<','<','<','<','0','<','<','>'}, {'>','>','>','0','>','>','0','>'}}; int i,t1,t2; for(i=0;i<8;i++) { if(st==id[i]) t1=i; if(ip==id[i]) t2=i; }

39

if(pre[t1][t2]=='>') return 0; else return 1; } push(ps,x) struct stack *ps; char x; { ps->item[++(ps->top)]=x; return; } pop(ps) struct stack *ps; { ps->item[--(ps->top)]; return; }

OUTPUT:
Enter the input language i*i+(i/i) Stack $ $i $ Input i*i+(i/i)$ *i+(i/i)$ *i+(i/i)$ Actions Initial push($<i) pop(i>*)

40

$* $*i $* $ $+ $+( $+(i $+( $+(/ $+(/i $+(/ $+( $+ $ $) $ ACCEPTED

i+(i/i)$ +(i/i)$ +(i/i)$ +(i/i)$ (i/i)$ i/i)$ /i)$ /i)$ i)$ )$ )$ )$ )$ )$ $ $

push($<*) push(*<i) pop(i>+) pop(*>+) push($<+) push(+<() push((<i) pop(i>/) push((</) push(/<i) pop(i>)) pop(/>)) pop((>)) pop(+>)) push($<)) pop()>$)

RESULT:
Thus the C program for implementation of operator precedence parsing is executed and verified.

EX. NO: 6 DATE:

IMPLEMENTATION OF SYNTAX ANALYSIS USING YACC TOOL


AIM:
Write a program to implement a syntax analysis using Yacc tool.

ALGORITHM:

41

1. Start the program. 2. Yacc program consists of three parts namely Declarations %% Transition Rule %% Supporting C routines. 3. Declaration part consists of two sections, first section contains only include statements and the second statements contains declaration of the grammar tokens. 4. Each rule in set of transition rules consists of grammar production and semantic action. The set of productions are of the form <left side>: <alt 1> {semantic action 1} | <alt 2> {semantic action 2} .. | <alt n> {semantic action n} ; 5. In the third part, error recovery routines are added. 6. The program is typed using vi editor, and saved with .y extension. 7. It is first compiled with the yacc compiler to produce the C code for C compiler (yacc filename.y). 8. After that compile that program with C compiler (cc y.tab.c ly ). 9. See the output using ./a.out. 10. Stop the program.

PROGRAM:
%{ #include<stdio.h> #include<ctype.h> #define YYSTYPE double %}

42

%token number %left '+''-' %left '*''/' %right uminus %% lines: expr'\n'{printf("The Result is : \t %g\n",$$);} expr:expr'+'expr{$$=$1+$3;} |expr'-'expr{$$=$1-$3;} |expr'*'expr{$$=$1*$3;} |expr'/'expr{$$=$1/$3;} |'('expr')'{$$=$2;} |'-'expr%prec uminus{$$=-$2;} |number ; %% int yylex() { char c; while((c=getchar())=='\0'); if((c=='.')||(isdigit(c))) { ungetc(c,stdin); scanf("%lf",&yylval); return number; } return c; } main() { printf("Enter The Expression : \t"); yyparse();

43

} void yyerror() { printf("\n Error....Invalid expression"); return; }

OUTPUT:
[cse4@localhost ~]$ yacc cse1.y [cse4@localhost ~]$ cc y.tab.c [cse4@localhost ~]$ ./a.out Enter The Expression : 2+4*7-4/2 The Result is : 28

RESULT:
Thus the program for syntax analysis using YACC tool is executed and verified.

EX. NO: 7 DATE:

IMPLEMENTATION OF SHIFT REDUCE PARSING


AIM:
To write a C program to implement the shift reduce parsing.

ALGORITHM:
1. Start the program. 2. Get the input string from the user. 3. Push $ onto top of the stack. 4. Set ip to point to the first input symbol.

44

5. If there is any production which can be used to reduce the input symbol reduce the string otherwise push it to the top of the stack. 6. Set ip to point to next input symbol. 7. Repeat the above steps until the top of the stack contains the $ and the starting symbol. If so, then the string is valid, otherwise the string is invalid, return an error message. 8. Stop the program.

PROGRAM:
#include<stdio.h> #include<conio.h> void pus(char); void reduce(); char inp1[5][10]={"E+E","E*E","(E)","a"},stk[50],inpt1[10],stk1[50]; int ct=0; void main() { int k,len; char inpt[10]; clrscr(); printf("Enter the input string\n\n"); gets(inpt); printf("\n\n"); printf("STACK\tINPUT \tACTION"); printf("\n\n"); len=strlen(inpt); inpt[len++]='$'; inpt[len]='\0'; strcpy(inpt1,inpt); len=strlen(inpt); inpt[len++]='$'; inpt[len++]='\0';

45

pus('$'); pus(inpt[0]); for(k=1;k<len-1;k++) { if(!isupper(inpt[k-1])) { reduce(); if(inpt[k]!='$') pus(inpt[k]); } } if(stk[0]=='$'&&stk[1]=='E'&&stk[2]=='0'&&inpt1[0]=='$') printf("\n\n\n\n\tString Accepted"); else printf("\n\n\n \t Not Accepted"); getch(); } void pus(char inpt) { int i,n; n=strlen(inpt1); if(ct>0) { for(i=0;i<n;i++) inpt1[i-1]=inpt1[i]; inpt1[n-1]='\0'; } stk[ct++]=inpt; i=0; while(stk[i]!='0'&&stk[i]!='\0') printf("%c",stk[i++]); printf("\t %s\t Shift \n",inpt1);

46

} void reduce() { int j=0,ct1,i,ct2,t,ct3,true=0; char temp[10],tmp; strcpy(stk1,stk); for(i=0;i<5;i++) { if(stk[ct-1]==inp1[i][0]) { if(stk[ct-1]!='('&&stk[ct-1]!=')') stk[ct-1]='E'; i=0; while(stk[i]!='0'&&stk[i]!='\0') printf("%c",stk[i++]); printf("\t %s\t Reduce\n",inpt1); true=1; } } for(i=0;i<4;i++) { j=0; ct1=ct-strlen(inp1[i]); ct2=ct1; ct3=0; while(ct1<ct&&ct1>0&&stk[ct1]!=0) temp[j++]=stk[ct1++]; temp[j]='\0'; if(strcmp(temp,inp1[i]==0)) { stk[ct2]='E';

47

t=ct2; while(ct2<=ct) stk[++ct2]='0'; ct=t; ct++; true=0; } } i=0; while(stk[i]!='0'&&stk[i]!='\0'&&true==0) printf("%c",stk[i++]); if(true==0) printf("\t %s\t Reduce \n",inpt1); }

OUTPUT:
Enter the input string : (a*a)+a STACK INPUT ACTION $ $( $( $E $Ea $EE $EE $EE* $E $Ea $EE $EE (a*a)+a$ a*a)+a$ a*a)+a$ a*a)+a$ *a)+a$ *a)+a$ *a)+a$ a)+a$ a)+a$ )+a$ )+a$ )+a$ Shift Shift Reduce Reduce Shift Reduce Reduce Shift Reduce Shift Reduce Reduce

48

$EE) $E $E+ $EE $EEa $EEE $E $E $E

+a$ +a$ a$ a$ $ $ $ $ $

Shift Reduce Shift Reduce Shift Reduce Reduce Reduce Reduce

String Accepted

RESULT:
Thus the program for implementations of shift reduce parsing is executed and verified.

EX. NO: 8 DATE:

IMPLEMENTATION OF LR PARSING
AIM:
To write a C program to implement LR parsing algorithm.

ALGORITHM:
Input: An input string w and an LR parsing table with functions action and goto for a grammar G. Output: If w is in L(G), a bottom up parse for w; otherwise an error indication. Method: Initially, the parser has s0 on its stack, s0 is the initial state, and w$ in the input buffer. The parser then executes the program until accept or error action is encountered. set ip to point to the first symbol of w$; repeat forever begin

49

let s be the state on the top of the stack and a the symbol pointed to by ip; if action [s, a] = shift s then begin push a then s on the top of the stack; advance ip to the next input symbol end else if action [s, a] = reduce A then begin pop 2*|| symbols off the stack; let s be the state now on top of the stack; push A then goto [s, A] on top of the stack; output the production A end else if action [s, a] = accept then return else error() end PROGRAM: char stk[10],inp[10],pat[20][20][20],prod[10][10],ipsymb[10]; int sp,ip,tp; char c,v; int i,k,t; void gettable() { int i,j,k,n; char c; strcpy(pat[0][0],"s5");strcpy(pat[0][3],"s4");strcpy(pat[0][6],"1"); strcpy(pat[0][7],"2");strcpy(pat[0][8],"3"); strcpy(pat[1][5],"A"); strcpy(pat[1][1],"s6");

50

strcpy(pat[2][1],"r2");strcpy(pat[2][2],"s7");strcpy(pat[2][4],"r2"); strcpy(pat[2][5],"r2"); strcpy(pat[3][1],"r4");strcpy(pat[3][2],"r4");strcpy(pat[3][4],"r4"); strcpy(pat[3] [5],"r4"); strcpy(pat[4][0],"s5");strcpy(pat[4][3],"s4");strcpy(pat[4][6],"8"); strcpy(pat[4][7],"2");strcpy(pat[4][8],"3"); strcpy(pat[5][2],"r6");strcpy(pat[5][1],"r6");strcpy(pat[5][4],"r6"); strcpy(pat[5][5],"r6"); strcpy(pat[6][0],"s5");strcpy(pat[6][3],"s4");strcpy(pat[6][7],"9"); strcpy(pat[6][8],"3"); strcpy(pat[7][0],"s5");strcpy(pat[7][3],"s4");strcpy(pat[7][8],"a"); strcpy(pat[8][1],"s6");strcpy(pat[8][4],"sb"); strcpy(pat[9][1],"r1");strcpy(pat[9][2],"s7");strcpy(pat[9][4],"r1"); strcpy(pat[9][5],"r1"); strcpy(pat[10][1],"r3");strcpy(pat[10][2],"r3");strcpy(pat[10][4],"r3"); strcpy(pat[10][5],"r3"); strcpy(pat[11][1],"r5");strcpy(pat[11][2],"r5");strcpy(pat[11][4],"r5"); strcpy(pat[11][5],"r5"); ipsymb[0]='i';ipsymb[1]='+';ipsymb[2]='*';ipsymb[3]='(';ipsymb[4]=')'; ipsymb[5]='$';ipsymb[6]='E';ipsymb[7]='T';ipsymb[8]='F'; strcpy(prod[0],"E'->E");strcpy(prod[1],"E->E+T");strcpy(prod[2],"E->T"); strcpy(prod[3],"T->T*F");strcpy(prod[4],"T->F"); strcpy(prod[5],"F->(E)");strcpy(prod[6],"F->i"); } int ipnum(char c) { int i; for(i=0;i<strlen(ipsymb);i++) { if(ipsymb[i]==c) break;

51

} return i; } int stknum(char c) { char t[10]; int i; if(c<='9') { t[0]=c;t[1]='\0'; return atoi(t); } else { return(c-97+10); } } void shift() { char t; t=pat[i][k][1]; stk[++sp]=inp[ip++]; stk[++sp]=t; } void reduce() { int b,prev,z; char t,pr[10],subs[10]; t=pat[i][k][1]; strcpy(pr,prod[t-48]); b=2*(strlen(pr)-3);

52

sp=sp-b; t=stk[sp]; prev=stknum(t); stk[++sp]=pr[0]; z=ipnum(pr[0]); stk[++sp]=pat[prev][z][0]; stk[sp+1]='\0'; } void main() { int q; clrscr(); printf("ENTER THE INPUT..."); scanf("%s",inp); t=strlen(inp); inp[t]='$'; inp[t+1]='\0'; stk[0]='0'; gettable(); printf("\n\n\nSTACK\t\tINPUT\t\tOPERATION\n"); while(1) { c=inp[ip]; v=stk[sp]; k=ipnum(c); i=stknum(v); if(pat[i][k][0]=='s') shift(); else if(pat[i][k][0]=='r') reduce(); else if(pat[i][k][0]=='A')

53

{ printf("\n\nVALID..."); getch(); exit(0); } else { printf("\n\nINVALID..."); getch(); exit(0); } printf("%s\t\t",stk); q=ip; while(inp[q]!='\0') printf("%c",inp[q++]); if(pat[i][k][0]=='s') printf("\t\tShift\n"); else if(pat[i][k][0]=='r') printf("\t\tReduced by %s\n",prod[pat[i][k][1]-48]); } }

54

OUTPUT: ENTER THE INPUT: (i*i)+i STACK 0(4 0(4i5 0(4F3 0(4T2 0(4T2*7 0(4T2*7i5 0(4T2*7Fa 0(4T2 0(4E8 0(4E8)bFa 0F3 0T2 0E1 0E1+6)bFa 0E1+6i5Fa 0E1+6F3 0E1+6T9 INPUT i*i)+i$ *i)+i$ *i)+i$ *i)+i$ i)+i$ )+i$ )+i$ )+i$ )+i$ +i$ +i$ +i$ +i$ i$ $ $ $ OPERATION Shift Shift Reduced by F->i Reduced by T->F Shift Shift Reduced by F->i Reduced by T->T*F Reduced by E->T Shift Reduced by F->(E) Reduced by T->F Reduced by E->T Shift Shift Reduced by F->i Reduced by T->F

55

0E1 VALID...

Reduced by E->E+T

RESULT:
Thus the program for construction of LR parsing is executed and verified.

EX. NO: 9 DATE:

IMPLEMENTATION OF CODE GENERATION AIM:


To write a C program to implement the code generation algorithm.

ALGORITHM:
1. The code generation algorithm takes as input a sequence of three address statements constituting a basic block. 2. For each three address statement of the form x := y op z we perform the following actions: Invoke a function getreg to determine the location L where the result of the computation y op z should be stored. L will usually be a register, but it could also be a memory location. We shall describe getreg shortly. Consult the address descriptor for y to determine y, (one of) the current location(s) of y. prefer the register for y if the value of y is currently both in memory and a register. If the value of y is not already in L, generate the instruction MOV y , L to place a copy of y in L. Generate the instruction OP z, L where z is a current location of z. Again, prefer a register to a memory location if z is in both. Update the address descriptor of x to

56

indicate that x is in location L. If L is a register, update its descriptor to indicate that it contains the value of x, and remove x from all other register descriptors. If the current values of y and/or z have no next users, are not live on exit from the block, and are in register descriptor to indicate that, after execution of x := y op z, those registers no longer will contain y and/or z, respectively. 4. Stop the program.

PROGRAM:
#include<stdio.h> #include<conio.h> #include<string.h> char exp[10][10],*ope; int i,j,n,s[10],flag2,flag3,r1,r2; void check(); void oper(); void main() { clrscr(); printf("\nEnter no of Expression:\n"); scanf("%d",&n); printf("\nEnter the expression(In Three Address code):\n"); for(i=0;i<n;i++) { scanf("%s",exp[i]); s[i]=i; } printf("\n\nGenerated code is:\n\n"); oper(); getch(); }

57

void oper() { for(i=0;i<n;i++) { flag2=0; flag3=0; if(exp[i][3]=='*') ope="MUL"; if(exp[i][3]=='/') ope="DIV"; if(exp[i][3]=='+') ope="ADD"; if(exp[i][3]=='-') ope="SUB"; check(); printf("MOV R%d,%c \t(Result Moved To %c)\n",s[i],exp[i][0],exp[i][0]); } } void check() { for(j=0;j<i;j++) { if(exp[1][2]==exp[j][0]) { flag2=1; r1=s[j]; } if(exp[1][4]==exp[j][0]) { flag3=1; r2=s[j];

58

} } if(flag2==1 && flag3==1) { s[i]=0; printf("%sR%d,R%d \t(Result In R%d)\n",ope,r2,r1,r1); } else if(flag2==1&&flag3!=1) { s[i]=r1; printf("%s %c,R%d \t(Result In R%d)\n",ope,exp[i][4],r1,r1); } else if(flag2!=1&&flag3==1) { s[i]=r2; printf("%s %c,R%d \t(Result In R%d)\n",ope,exp[i][2],r2,r2); } else { printf("MOV %c,R%d \t(%c Moved To R%d)\n",exp[i][2],s[i],exp[i][2],s[i]); printf("%s %c,R%d \t(Result In R%d)\n",ope,exp[i][4],s[i],s[i]); } }

59

OUTPUT: Enter no of Expression: 4 Enter the expression (In Three Address code): A=b+c B=d-e C=f*g D=h/i Generated code is: MOV b,R0 ADD c,R0 MOV R0,A MOV d,R1 SUB e,R1 MOV R1,B MOV f,R2 MUL g,R2 MOV R2,C MOV h,R3 DIV i,R3 MOV R3,D (b Moved To R0) (Result In R0) (Result Moved To A) (d Moved To R1) (Result In R1) (Result Moved To B) (f Moved To R2) (Result In R2) (Result Moved To C) (h Moved To R3) (Result In R3) (Result Moved To D)

60

RESULT:
Thus the program for implementation of code optimization is executed and verified.

EX. NO: 10 DATE:


IMPLEMENTATION OF CODE OPTIMIZATION TECHNIQUE

AIM:
To write a C program to implement code optimization technique.

ALGORITHM:
1. Start the program. 2. Enter the expression for which intermediate code is to be generated. 3. If the length of the string is greater than 3, then call the procedure to return the precedence among the operands. 4. Assign the operand to exp array and operators to the array. 5. Create the three address code using quadruple structure. 6. Reduce the no of temporary variables. 7. Continue this process until we get an output. 8. Stop the program.

PROGRAM:
#include<stdio.h> #include<conio.h> #include<string.h> char s[20],o[20]; void main() { int i=0,j=0,k,f1=1,f=1,k1=0; void part(); clrscr();

61

printf("\n Enter the input string\n"); scanf("%s",o); strlen(o); while(o[k1]!='\0') { I f((o[k1]=='=')==1) { break; } k1++; } for(j=k1+1;j<strlen(o);j++) { s[i]=o[j]; i++; } s[i]='\0'; i=strlen(s); j=0; printf("\n Three address code is\n"); if(i>3) { while(s[j]!='\0') { if((s[j]=='*')==1||(s[j]=='/')==1) { k=j; if(f1!=0) { printf("t1=%c\n",s[k+1]); printf("t2=%c%ct1",s[k-1],s[k]);

62

} else { if(k>3) { printf("t2=t1%c%c\n",s[k],s[k+1]); } else { printf("\t2=t1%c%c\n",s[k],s[k-1]); } } f=0; break; } j++; } j=0; while(s[j]!='\0') { if((s[j]=='+')==1||(s[j]=='-')==1) { k=j; if(f==0) { if(k<3) { printf("\nt3=t2%c%c\n",s[k],s[k-1]); } else {

63

printf("\nt3=t2%c%c\n",s[k],s[k+1]); } } else { printf("t1=%c%c%c\n",s[k-1],s[k],s[k+1]); } f1=0; } j++; } printf("%c=t3",o[0]); } else { printf("t1=%s\n",s); printf("%c=t1",o[0]); } part(); getch(); } void part() { int i=0,j=0,k,f1=1,f=1,k1=0; while(o[k1]!='\0') { if((o[k1]=='=')==1) { break; } k1++;

64

} for(j=k1+1;j<strlen(o);j++) { s[i]=o[j]; i++; } s[i]='\0'; i=strlen(s); j=0; printf("\n OPTIMIZED CODE\n"); if(i>3) { while(s[j]!='\0') { if((s[j]=='*')==1||(s[j]=='/')==1) { k=j; if(f1!=0) { printf("t1=%c%c%c\n",s[k-1],s[k],s[k+1]); } else { if(k>3) { printf("t2=t1%c%c\n",s[k],s[k+1]); } else { printf("\t2=t1%c%c\n",s[k],s[k-1]); }

65

} f=0; break; } j++; } j=0; while(s[j]!='\0') { if((s[j]=='+')==1||(s[j]=='-')==1) { k=j; if(f==0) { if(k<3) { printf("t2=t1%c%c\n",s[k],s[k-1]); } else { printf("t2=t1%c%c\n",s[k],s[k+1]); } } else { printf("t1=%c%c%c\n",s[k-1],s[k],s[k+1]); } f1=0; } j++; }

66

printf("%c=t2",o[0]); } else { printf("t1=%s\n",s); printf("%c=t1",o[0]); } }

OUTPUT:
Enter the input string a=b+c*d Three address code is t1=d t2=c*t1 t3=t2+b a=t3 OPTIMIZED CODE t1=c*d t2=t1+b a=t2

RESULT:
Thus the program fogegsfadgsdfggr implementation of code optimizegerfgdfgdfgdfation is executed and verified.

S-ar putea să vă placă și