Vous êtes sur la page 1sur 36

EX NO: 1

CONSTRUCTION OF NFA

AIM: To construct NFA for the given regular expression. ALGORITHM: Step 1: Get the regular expression. Step 2: Mark the initial state with a line and final state with double circle. Step 3: Mark the intermediate states with a single circle and a line connecting previous state and current state with an arrow towards the current state. Step 4: Display the input above the arrow for every transition. Step 5: Initial state must have no incoming states and final state should not have any outgoing states. Step 6: The input is, A REGULAR EXPRESSION r OVER AN ALPHABET E. Step 7: The output is , AN NFA N ACCEPTING L(r). Step 8: Parse r into the sub expressions. Step 9: Using the rules construct NFA for each of the basic symbols in r. CODING: #include<stdio.h> #include<conio.h> #include<dos.h> #include<graphics.h> #include<math.h> void a(int,int); void p(); void main() { int ch; int gd=DETECT, gm; initgraph(&gd,&gm,"d:\\tc\\bgi"); while(ch!=6) { printf("Menu \n 1. Empty Input \n 2. a \n 3. a|b \n 4. ab\n 5. (a|b)^* \n 6. Exit \nEnter the exp "); scanf("%d", &ch); switch(ch) { case 1: a(150,150); circle(210,150,15); outtextxy(180,135,"e"); outtextxy(125,147,">"); line(115,150,140,150); getch(); cleardevice(); break;

case 2: a(150,150); circle(210,150,15); line(115,150,140,150); outtextxy(125,147,">"); outtextxy(180,135,"a"); getch(); cleardevice(); break; case 3: circle(245,200,15); p(); getch(); cleardevice(); break; case 4: a(150,150); a(275,150); line(220,150,265,150); circle(335,150,15); outtextxy(175,140,"a"); outtextxy(300,140,"b"); outtextxy(235,140,"e"); outtextxy(125,147,">"); line(110,150,140,150); line(315,150,310,145); line(245,150,240,145); line(245,150,240,155); getch(); cleardevice(); break; case 5: p(); circle(300,200,10); circle(300,200,15); circle(65,200,10); line(25,200,55,200); line(255,200,285,200); outtextxy(65,200,"I"); outtextxy(35,197,">"); outtextxy(300,200,"F"); arc(185,215,180,0,120); outtextxy(185,332,">"); outtextxy(265,185,"e"); outtextxy(265,197,">"); outtextxy(85,185,"e");

outtextxy(185,110,"e"); outtextxy(185,320,"e"); getch(); cleardevice(); break; case 6: exit(0); break; } } getch(); closegraph(); } void a(int x, int y) { int ch; circle(x,y,10); circle(x+60,y,10); line(x+10,y,x+50,y); outtextxy(x,y,"1"); outtextxy(x+60,y,"2"); line(185,y,180,y-5); line(185,y,180,y+5); } void p() { a(150,150); a(150,250); circle(125,200,10); outtextxy(120,170,"e"); outtextxy(85,197,">"); outtextxy(120,220,"e"); outtextxy(240,170,"e"); outtextxy(240,220,"e"); outtextxy(180,135,"a"); outtextxy(180,260,"b"); line(75,200,115,200); line(125,190,140,155); line(125,210,145,240); circle(245,200,10); line(220,155,240,185); line(240,215,220,250); outtextxy(125,200,"5"); outtextxy(245,200,"6"); }

INPUT / OUTPUT: Menu 1. Empty Input 2. a 3. a|b 4. ab 5. (a|b)^* Enter the exp 1

>

>

Enter the exp 4

RESULT: Thus the program for Constructing NFA for the given regular expression is executed successfully.

EX NO: 2

CONSTRUCTION OF MINIMIZED DFA FROM A GIVEN REGULAR EXPRESSION

AIM: To construct a minimized DFA from a given regular expression. ALGORITHM: Step 1: Get the regular expression. Step 2: Mark the initial state with a line and final state with double circle. Step 3: Mark the intermediate states with a single circle and a line connecting previous state and current state with an arrow towards the current state. Step 4: Display the input above the arrow for every transition. Step 5: Initial state must have no incoming states and final state should not have any outgoing states. Step 6: The input is, A REGULAR EXPRESSION r OVER AN ALPHABET E. Step 7: The output is , AN NFA N ACCEPTING L(r). Step 8: Parse r into the sub expressions. Step 9: Using the rules construct NFA for each of the basic symbols in r.

CODING: #include <stdio.h> #include <string.h> #define STATES #define SYMBOLS

99 20

int N_symbols; int N_DFA_states; char *DFA_finals; int DFAtab[STATES][SYMBOLS]; char StateName[STATES][STATES+1]; int N_optDFA_states; int OptDFA[STATES][SYMBOLS]; char NEW_finals[STATES+1]; void print_dfa_table(int tab[][SYMBOLS],int nstates,int nsymbols,char *finals) { int i, j; puts("\nDFA: STATE TRANSITION TABLE"); printf(" | "); for (i = 0; i < nsymbols; i++) printf(" %c ", '0'+i);

printf("\n-----+--"); for (i = 0; i < nsymbols; i++) printf("-----"); printf("\n"); for (i = 0; i < nstates; i++) { printf(" %c | ", 'A'+i); for (j = 0; j < nsymbols; j++) printf(" %c ", tab[i][j]); printf("\n"); } printf("Final states = %s\n", finals); } void load_DFA_table() { DFAtab[0][0] = 'B'; DFAtab[0][1] = 'D'; DFAtab[1][0] = 'B'; DFAtab[1][1] = 'C'; DFAtab[2][0] = 'D'; DFAtab[2][1] = 'E'; DFAtab[3][0] = 'D'; DFAtab[3][1] = 'E'; DFAtab[4][0] = 'B'; DFAtab[4][1] = 'C'; DFA_finals = "CE"; N_DFA_states = 5; N_symbols = 2; DFAtab[0][0] = 'F'; DFAtab[0][1] = 'B'; DFAtab[1][0] = 'E'; DFAtab[1][1] = 'D'; DFAtab[2][0] = 'C'; DFAtab[2][1] = 'F'; DFAtab[3][0] = 'D'; DFAtab[3][1] = 'A'; DFAtab[4][0] = 'B'; DFAtab[4][1] = 'C'; DFAtab[5][0] = 'A'; DFAtab[5][1] = 'E'; DFA_finals = "AF"; N_DFA_states = 6; N_symbols = 2; DFAtab[0][0] = 'B'; DFAtab[0][1] = 'C'; DFAtab[1][0] = 'E'; DFAtab[1][1] = 'F'; DFAtab[2][0] = 'A'; DFAtab[2][1] = 'A'; DFAtab[3][0] = 'F'; DFAtab[3][1] = 'E'; DFAtab[4][0] = 'D'; DFAtab[4][1] = 'F'; DFAtab[5][0] = 'D'; DFAtab[5][1] = 'E'; DFA_finals = "EF"; N_DFA_states = 6; N_symbols = 2; } void get_next_state(char *nextstates, char *cur_states,int dfa[STATES][SYMBOLS], int symbol) {

int i, ch; for (i = 0; i < strlen(cur_states); i++) *nextstates++ = dfa[cur_states[i]-'A'][symbol]; *nextstates = '\0'; } char equiv_class_ndx(char ch, char stnt[][STATES+1], int n) { int i; for (i = 0; i < n; i++) if (strchr(stnt[i], ch)) return i+'0'; return -1; } char is_one_nextstate(char *s) { char equiv_class; while (*s == '@') s++; equiv_class = *s++; while (*s) { if (*s != '@' && *s != equiv_class) return 0; s++; } return equiv_class; } int state_index(char *state, char stnt[][STATES+1], int n, int *pn,int cur) { int i; char state_flags[STATES+1]; if (!*state) return -1; for (i = 0; i < strlen(state); i++) state_flags[i] = equiv_class_ndx(state[i], stnt, n); state_flags[i] = '\0'; printf(" %d:[%s]\t--> [%s] (%s)\n",cur, stnt[cur], state, state_flags); if (i=is_one_nextstate(state_flags)) return i-'0'; else { strcpy(stnt[*pn], state_flags); return (*pn)++; } } int init_equiv_class(char statename[][STATES+1], int n, char *finals) { int i, j; if (strlen(finals) == n) {

strcpy(statename[0], finals); return 1; } strcpy(statename[1], finals); for (i=j=0; i < n; i++) { if (i == *finals-'A') { finals++; } else statename[0][j++] = i+'A'; } statename[0][j] = '\0'; return 2; } int get_optimized_DFA(char stnt[][STATES+1], int n,int dfa[][SYMBOLS], int n_sym, int newdfa[][SYMBOLS]) { int n2=n; int i, j; char nextstate[STATES+1]; for (i = 0; i < n; i++) { for (j = 0; j < n_sym; j++) { get_next_state(nextstate, stnt[i], dfa, j); newdfa[i][j] = state_index(nextstate, stnt, n, &n2, i)+'A'; } } return n2; } void chr_append(char *s, char ch) { int n=strlen(s); *(s+n) = ch; *(s+n+1) = '\0'; } void sort(char stnt[][STATES+1], int n) { int i, j; char temp[STATES+1]; for (i = 0; i < n-1; i++) for (j = i+1; j < n; j++) if (stnt[i][0] > stnt[j][0]) { strcpy(temp, stnt[i]); strcpy(stnt[i], stnt[j]);

strcpy(stnt[j], temp); } } int split_equiv_class(char stnt[][STATES+1],int i1,int i2,int n,int n_dfa) { char *old=stnt[i1], *vec=stnt[i2]; int i, n2, flag=0; char newstates[STATES][STATES+1]; for (i=0; i < STATES; i++) newstates[i][0] = '\0'; for (i=0; vec[i]; i++) chr_append(newstates[vec[i]-'0'], old[i]); for (i=0, n2=n; i < n_dfa; i++) { if (newstates[i][0]) { if (!flag) { strcpy(stnt[i1], newstates[i]); flag = 1; } else strcpy(stnt[n2++], newstates[i]); } } sort(stnt, n2); return n2; } int set_new_equiv_class(char stnt[][STATES+1], int n,int newdfa[][SYMBOLS], int n_sym, int n_dfa) { int i, j, k; for (i = 0; i < n; i++) { for (j = 0; j < n_sym; j++) { k = newdfa[i][j]-'A'; if (k >= n) return split_equiv_class(stnt, i, k, n, n_dfa); } } return n; } void print_equiv_classes(char stnt[][STATES+1], int n) {

int i; printf("\nEQUIV. CLASS CANDIDATE ==>"); for (i = 0; i < n; i++) printf(" %d:[%s]", i, stnt[i]); printf("\n"); } int optimize_DFA(int dfa[][SYMBOLS],int n_dfa,int n_sym,char *finals,char stnt[][STATES+1],int newdfa[][SYMBOLS]) { char nextstate[STATES+1]; int n; int n2; n = init_equiv_class(stnt, n_dfa, finals); while (1) { print_equiv_classes(stnt, n); n2 = get_optimized_DFA(stnt, n, dfa, n_sym, newdfa); if (n != n2) n = set_new_equiv_class(stnt, n, newdfa, n_sym, n_dfa); else break; } return n; } int is_subset(char *s, char *t) { int i; for (i = 0; *t; i++) if (!strchr(s, *t++)) return 0; return 1; } void get_NEW_finals(char *newfinals,char *oldfinals,char stnt[][STATES+1],int n) { int i; for (i = 0; i < n; i++) if (is_subset(oldfinals, stnt[i])) *newfinals++ = i+'A'; *newfinals++ = '\0'; } void main() { load_DFA_table(); clrscr(); print_dfa_table(DFAtab, N_DFA_states, N_symbols, DFA_finals); N_optDFA_states = optimize_DFA(DFAtab, N_DFA_states,N_symbols, DFA_finals, StateName, OptDFA); get_NEW_finals(NEW_finals, DFA_finals, StateName, N_optDFA_states); print_dfa_table(OptDFA, N_optDFA_states, N_symbols, NEW_finals);

getch(); } OUTPUT:
DFA: STATE TRANSITION TABLE | 0 1 -----+-----------A | B C B | E F C | A A D | F E E | D F F | D E Final states = EF EQUIV. CLASS CANDIDATE ==> 0:[ABCD] 1:[EF] 0:[ABCD] --> [BEAF] (0101) 0:[ABCD] --> [CFAE] (0101) 1:[EF] --> [DD] (00) 1:[EF] --> [FE] (11) EQUIV. CLASS CANDIDATE ==> 0:[AC] 1:[BD] 2:[EF] 0:[AC] --> [BA] (10) 0:[AC] --> [CA] (00) 1:[BD] --> [EF] (22) 1:[BD] --> [FE] (22) 2:[EF] --> [DD] (11) 2:[EF] --> [FE] (22) EQUIV. CLASS CANDIDATE ==> 0:[A] 1:[BD] 2:[C] 3:[EF] 0:[A] --> [B] (1) 0:[A] --> [C] (2) 1:[BD] --> [EF] (33) 1:[BD] --> [FE] (33) 2:[C] --> [A] (0) 2:[C] --> [A] (0) 3:[EF] --> [DD] (11) 3:[EF] --> [FE] (33) DFA: STATE TRANSITION TABLE | 0 1 -----+-----------A | B C B | D D C | A A D | B D Final states = D

RESULT:

Thus the program for constructing a minimized DFA from a given regular expression is executed successfully. EX.NO.3 LEXICAL ANALYSER USING LEX TOOLS

AIM: To write a program for lexical analyzer using lex tools. PROCEDURE: 1. Start the program 2. The regular expression rules for finding the identifier, keyword, preprocessor directives and operators are defined. 3. The input file is scanned as a set of string 4. The strings are applied to the regular expression to find its type. 5. The token and its types are printed as the output 6. Stop the program. CODING: /* program name is lexp.l */ %{ /*program to recognize a cprogram*/ int COMMENT=0; %} identifier [a-zA-Z][a-zA-Z0-9]* %% #,* {printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);} int | float | char | double | while | for | do | if | break | continue | void | switch | case | long | struct | const | typedef |

Else | goto {printf("\n\t%s is a KEYWORD",yytext);} "/*" {COMMENT = 1;} {identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s",yytext \{ {if(COMMENT) printf("\n BLOCK BEGINS");} \} {if(COMMENT) printf("\n BLOCK ENDS");} {identifier}(\[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER", \".*\" {if(!COMMENT) printf("\n\t%s is a STRING",yytext);} [0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER",yytext);} \)(\;)? {if(!COMMENT) printf("\n\t");ECHO;printf("\n");} \( ECHO; = {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yy \<= | \>= | \< | == | \> {if(COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yyt %% int main(int argc,char **argv) { if (argc >1) { FILE *file; file = fopen(argv[1],"r"); if(!file) { printf("Could not open %s \n",argv[1]); exit(0); } yyin = file;} yylex(); printf("\n\n"); return 0;} int yywrap() { return 0; } INPUT FILE (INPUT.C): #include<stdio.h> #include<conio.h> Void main() { int a,b; char d; a=8;

b=7; } OUTPUT: $ lex lexip.l $ cc lex.yy.c $ ./a.out input.c # is a PREPROCESSOR DIRECTIVE # is a PREPROCESSOR DIRECTIVE void is a KEYWORD FUNCTION main( ) int is a KEYWORD a IDENTIFIER, b IDENTIFIER; char is a KEYWORD d IDENTIFIER; a IDENTIFIER = is an ASSIGNMENT OPERATOR 8 is a NUMBER; b IDENTIFIER = is an ASSIGNMENT OPERATOR 7 is a NUMBER;

RESULT: Thus the program for lexical analyzer using lex tools has been executed and verified successfully.

EX.NO.4 AIM:

SYMBOL TABLE

To write a c program to create a symbol table. PROCEDURE: 1. A 2D array is created for storing the data types. 2. An input file and output file is created. 3. The input file contents are scanned as strings. 4. The Symbols are stored as character and printed in the output file. 5. If the input string is equal to data types, then it is printed in the output and Corresponding values are printed. 6. If the identifier is not initialized, then NULL is printed in output. 7. This continues till EOF. 8. Stop the program. CODING: #include<stdio.h> #include<conio.h> #include<string.h> void main() { char dtype[4][6]={"int","double","float","char"}; char str[30],ch,val[10],temp[10]; int f=0,j=0,i,k,m; FILE *fp,*fp1; clrscr(); fp=fopen("IN.txt","r"); fp1=fopen("out.txt","w"); for(i=0;i<30;i++) str[i]=NULL; fprintf(fp1,"\n\t\t dtype\tidentifier\t\tvalue"); fscanf(fp,"%s",str); while(!feof(fp)) { for(m=0;m<4;m++) { if(!strcmpi(str,dtype[m])) { f++; break; }} if(f>=1) {

fscanf(fp,"%c%c",&ch,&ch); while(ch!=i) { f=j=k=0; for(i=0;i<10;i++) { temp[i]=NULL; val[i]=NULL; } if(isalpha(ch)) { while(isalpha(ch)||isdigit(ch)) { temp[j]=ch; fscanf(fp,"%c",&ch); j++; } fprintf(fp1,"\n\t\t%s\t\t%s",dtype[m],temp); if(ch=='=') { fscanf(fp,"%c",&ch); while(isdigit(ch)) { val[k]=ch; fscanf(fp,"%c",&ch); } fprintf(fp1,"\t\t%s",val); } else { fprintf(fp1,"\t\tNULL"); } } if(ch==';') break; fscanf(fp,"%c",&ch); } } for(i=0;i<30;i++) str[i]=NULL; fscanf(fp,"%s",str); } fclose(fp); fclose(fp1); getch(); }

IN.TXT FILE: #include<stdio.h> #include<conio.h> void main() { clrscr(); int a=5; int b=8,c; c=a+b; printf("value ofc:%d",c); getch(); }

OUTPUT: OUT.TXT FILE:

dtype int int int

identifier a b c

value 5 8 NULL

RESULT: Thus the C program to create a symbol table has been executed and verified successfully.

EX NO: 5
AIM:

OPERATOR PRECEDENCE PARSE TABLE

To write a c program to using operator precedence parsing. PROCEDURE: 1. Start the program. 2.Enter the expression as an input. 3.Using stack perform operator precedence parsing. 4.If the given expression is correct ,then the string is accepted. 5.Otherwise it will display that given string is not accepted. 6. Stop the program. CODING: #include<stdio.h> #include<conio.h> void main() { char a,b,table[10][10],popped=' ',stack[20],input[30]; int top=0,ippointer=0,r,c,i,j,l; clrscr(); table[0][0]=NULL; table[0][1]='a'; table[0][2]='('; table[0][3]=')'; table[0][4]=','; table[0][5]='$'; table[1][0]='a'; table[1][1]=NULL; table[1][2]=NULL; table[1][3]='>'; table[1][4]='>'; table[1][5]='>'; table[2][0]='('; table[2][1]='<'; table[2][2]='<'; table[2][3]='='; table[2][4]='<'; table[2][5]=NULL; table[3][0]=')'; table[3][1]=NULL; table[3][2]=NULL; table[3][3]='>';

table[3][4]='>'; table[3][5]='>'; table[4][0]=','; table[4][1]='<'; table[4][2]='<'; table[4][3]='>'; table[4][4]='>'; table[4][5]=NULL; table[5][0]='$'; table[5][1]='<'; table[5][2]='<'; table[5][3]=NULL; table[5][4]=NULL; table[5][5]=NULL; for(i=0;i<20;i++) { stack[i]=NULL; input[i]=NULL; } stack[0]='$'; printf("enter the expression\n"); scanf("%s",input); l=strlen(input); input[l]='$'; printf("\nSTACK\t\tINPUT\t\tPOPPED\n"); while(1) { a=stack[top]; b=input[ippointer]; printf("\n%s\t\t%c\t\t%c",stack,b,popped); if(a=='$'&&b=='$') { printf("\n\n given expresssion is accepted\n\n"); break; } else { for(i=0;a!=table[i][0];i++); for(j=0;b!=table[0][j];j++); if(table[i][j]=='<'||table[i][j]=='=') { stack[++top]=b; printf("\n%s\t\t%c\t\t%c",stack,b,popped); ippointer=ippointer+1; } else

if(table[i][j]=='>') { do { popped=stack[top]; stack[top]=NULL; printf("\n%s\t\t%c\t\t%c",stack,b,popped); top=top-1; for(i=0;stack[top]!=table[i][0];i++); for(j=0;popped!=table[0][j];j++); } while(table[i][j]!='<'); } else { printf("\n given expression is wrong\n"); break; } } } getch(); } INPUT: enter the expression (a,a) OUTPUT: enter the expression (a) STACK INPUT POPPED $ ( $( ( $( a $(a a $(a ) $( ) a $( ) a $() ) a $() $ a $( $ ) $ $ ( $ $ ( given expresssion is accepted

RESULT:

Thus the C program to create a operator precedence table has been executed and verified successfully.

EX.NO.6 AIM:

IMPLEMENTATION OF PARSER USING LEX AND YACC

To implement Parser using Lex and Yacc PROCEDURE: 1. A Yacc source program has three parts as follows. Declarations %% translation rules %% supporting C routines 2. Declarations Section This section contains entries that: Include standard I/O header file. Define global variables. Define the list rule as the place to start processing. Define the tokens used by the parser. Define the operators and their precedence. 3. Rules Section The rules section defines the rules that parse the input stream. Each rule consists of a grammar production and the associated semantic action. 4. In a Yacc production, a quoted single character is taken to be terminal and unquoted strings of letters and digits not declared to be tokens are taken to be nonterminals. A vertical bar can separate alternative right sides and a semicolon follows each left side with its alternatives and semantic actions. The first left side is taken to be the start symbol. 5. Programs Section The programs section contains the following subroutines. Because these subroutines are included in this file, it is not necessary to use the yacc library when processing this file. Main The required main program that calls the yyparse subroutine to start the program. yyerror(s) This error-handling subroutine only prints a syntax error message. Yywrap The wrap-up subroutine that returns a value of 1 when the end of input occurs. 6. yylex( ) contains the rules to generate the tokens from the input stream.

CODING: %{ #include<stdio.h> #include"y.tab.h" #include<math.h>

#include<ctype.h> int regs[26]; int base; %} %token DIGIT LETTER %left '|' %left '&' %left '+','-' %left '*','/','%' %% list : | list S '\n' ; S :expr { printf("\nstring accepted");} | LETTER '=' expr {printf("\nstring accepted");} ; expr : expr '+' expr { $$=$1+$3;} | expr '*' expr {$$=$1*$3;} | expr '/' expr {$$=$1/$3;} | '('expr')' {$$=$2;} | number | LETTER ; number : DIGIT {$$=$1; base=($1==0)?8:10;} | number DIGIT {$$=base*$1+$2;} ; %% yylex() { int c; extern int yylval; c=getchar(); if (isdigit(c)) {yylval=c-'0';return DIGIT;} if (isalpha(c)){yylval=c-'a';return LETTER;} return c;

} main() { return (yyparse()); } yyerror(s) char *s; { printf("%s\n",s); } yywrap() { return(1); }

OUTPUT : [idhaya@linuxserver idhaya]$ yacc -d parser.y [idhaya@linuxserver idhaya]$ cc y.tab.c [idhaya@linuxserver idhaya]$ ./a.out E*T string accepted E) syntax error

RESULT: Thus the implementation of Parser using Lex and Yacc is executed successfully.

EX NO: 7
AIM:

SHIFT REDUCED PARSING

To write a c program for shift reduced parsing. PROCEDURE: 1. Start the program. 2. Enter the expression as an input. 3. Check for the production as per the rules and parse the given grammer. 4. Stop the program. CODING: #include<stdio.h> void main() { char left[10],stack[15],input[20],start,a,store[20],right[10][10]; int top=0,ipptr,n,l,i,loop,x,j,k,equal=0; for(i=0;i<=15;i++) stack[i]=NULL; for(i=0;i<20;i++) input[i]=NULL; for(i=0;i<10;i++) { store[i]=NULL; left[i]=NULL; for(j=0;j<10;j++) right[i][j]=NULL; } stack[0]='$'; top=0; ipptr=0; clrscr(); printf("\nenter the number of expressions\n"); scanf("%d",&n); printf("\nenter the grammer\n"); for(i=0;i<n;i++) { scanf("\n%c->%s",&left[i],&right[i]); } start=left[0]; printf("\nenter the input symbols\n"); scanf("%s",input); l=strlen(input);

input[l]='$'; while(l) { a=input[ipptr]; if(a=='$'&&stack[top]==start&&top==1) { printf("\nGIVEN EXPRESSION IS ACCEPTED\n"); break; } else { if(a=='$'&&top>1) { printf("incorrect input"); break; } else { loop=1; if(a!='$') { stack[++top]=a; printf("\nstack:%s",stack); } a: for(i=0;i<n;i++) { equal=1; x=strlen(right[i]); for(j=x-1,k=top;j>=0;j--,k--) { if(right[i][j]!=stack[k]) { equal=0; break; } } if(equal==1) break; } if(equal==1) { for(j=0;j<strlen(right[i][j]);j++) { stack[top]=NULL; printf("\nstack:%s",stack);

top=top-1; } top=top+1; stack[top]=left[i]; printf("\nstack%s",stack); if(loop==1) { loop=0; goto a; } } } } if(a!='$') ipptr=ipptr+1; } getch(); } INPUT: enter the number of expressions 4 enter the grammer E->E+E E->E*E E->(E) E->a enter the input symbols a+a OUTPUT: stack:$a stack:$ stack$E stack:$E+ stack:$E+a stack:$E+ stack$E+E stack:$E+ stack:$E stack:$ stack$E GIVEN EXPRESSION IS ACCEPTED

RESULT:

Thus the program for shift reduced parsing is executed successfully.

EX NO: 8
AIM:

IMPLEMENTATION OF LR PARSING

To write a C program to implement simple 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 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"); 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; } 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); 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') { 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]); } } INPUT: ENTER THE INPUT... (i)$ OUTPUT: STACK 0(4 0(4i5 0(4F3 0(4T2 0(4E8 0(4E8)b 0F3 0T2 0E1 VALID... INPUT i)$$ )$$ )$$ )$$ )$$ $$ $$ $$ $$ OPERATION Shift Shift Reduced by F->i Reduced by T->F Reduced by E->T Shift Reduced by F->(E) Reduced by T->F Reduced by E->T

RESULT: Thus the above program is compiled and executed successfully and output is verified.

EX.NO.9
AIM:

INTERMEDIATE CODE GENERATION

To the generate the code for a given intermediate code using C program PROCEDURE: 1. Start the program. 2. Enter the expression as an input. 3. Generate the Intermediate Code for given input.txt. 4. Stop the program. CODING: #include<stdio.h> int main() { FILE*f; char str[25]; int flag=0,count=0,i,label,lab,f1,ct=1,ff=0; char store[20][25]; clrscr(); f=fopen("Input.txt","r"); printf("THREE ADDRESS CODE:\n\n"); while(!feof(f)) {flag=0; label=1; lab=1; f1=0; fscanf(f,"%s",str); if(!strcmp(str,";")) { for(i=0;i<count;i++) { if(!strcmp(store[i],"=")) { flag=1; break; }} if(flag==1) {flag=0; if(count==3) printf("\t%s=%s\n\n",store[0],store[2]); else if(!strcmp(store[0],"while")) { ff=1;

f1=1; printf("L%d;\t if %s goto L %d\n",lab,store[1],(lab+1)); printf("\t goto Lnext\n\n"); if(!strcmp(store[3],"if")) {printf("L%d:\t if %s goto L%d\n",(lab+1),store[4],(lab+2)); printf("\t goto L%d\n\n",(lab+3)); printf("L%d: ",(lab+2)); } else printf("L%d:",(lab+1)); goto a; } else if(!strcmp(store[0],"else")) { f1=1; printf("L%d:",(lab+4)); goto a; } else { a: for(i=0;i<count;i++) if(!strcmp(store[i],"*")) { flag=1; break; } if(flag) { flag=0; printf("\tt%d%d=",label,ct); printf("%s * %s\n",store[i-1],store[i+1]); for(i=0;i<count;i++) if(!strcmp(store[i],"+")) { flag=1; break; } if(flag) { flag=0; printf("\tt%d%d=",(label+1),ct); printf("%s+ t%d%d\n",store[i-1],label,ct); for(i=0;i<count;i++) if(!strcmp(store[i],"=")) { flag=1; break;

}printf("\t%s = t%d%d",store[i-1],(label+1),ct); }} if(f1) printf("\n\tgoto L1\n\n"); else printf("\n\n"); ct++; }} count=0; } else strcpy(store[count++],str); } if(ff) printf("L next:\n\n\n"); getch(); return 0; }

Input.txt
x = 10 y = 20 z = y + x * 10 OUTPUT: THREE ADDRESS CODE: x=10 y=20 t11=x * 10 t21=y+ t11 z = t21

RESULT: Thus the C program has been executed and intermediate code generated successfully.

EX NO: 10 AIM:

CODE OPTIMIZATION TECHNIQUES

To implement code optimization techniques of compiler using C program PROCEDURE: 1. Initialize the file pointer f. 2. The array of elements of three dimensional array are dimensional. 3. The file is opened in read mode and comparison of string method. 4. The loop is executed until the array of elements are reached. 5. The backend code is printed on the output by getting values from array of pointer. 6. The different operators + for add - for sub and * for multiplication is pointed. 7. The file is closed by fclose(). 8. Stop the program. CODING: #include<stdio.h> int main() { FILE *f,*fp1; char store[25][10][10]; int count=0,i=0,arr[25],a=0,j,flag,m; clrscr(); f=fopen("second.txt","r"); fp1=fopen("output.txt","w"); while(!feof(f)) { fscanf(f,"%s",store[count][i]); if(!strcmp(store[count][i++],";")) { arr[a++]=i; count++; i=0; } } printf("\n\n"); for(i=0;i<count;i++) { if(arr[i]!=4) { flag=0; for(j=0;j<arr[i];j++) { if(!strcmp(store[i][j],"goto")) flag=1; if(!strcmp(store[i][j],"if"))

flag=1; } if(!flag) { for(j=0;j<arr[i];j++) if(!strcmp(store[i][j],"=")) break; m=j; if(!strcmp(store[i][j],":")) fprintf(fp1,"\n%s%s",store[i][0],store[i][1]); fprintf(fp1,"\n\tMOV%s,R0",store[i][j+1]); if(!strcmp(store[i][j+2],"+")) fprintf(fp1,"\n\t ADD%s,R0",store[i][j+3]); if(!strcmp(store[i][j+2],"*")) fprintf(fp1,"\n\tMUL%s,R0",store[i][j+3]); fprintf(fp1,"\n\tMOV R0,%s\n\n",store[i][j-1]); } else { if(arr[i]==3) fprintf(fp1,"\n\t%s%s\n\n",store[i][0],store[i][1]); else { fprintf(fp1,"\n\n%s%s\t",store[i][0],store[i][1]); fprintf(fp1,"MOV %c,R0\n\t",store[i][3][1]); fprintf(fp1,"SUB %c,R0\n\t",store[i][3][3]); fprintf(fp1,"CJ%c%s\n\t",store[i][3][2],store[i][5]); fprintf(fp1,"J%s\n\n",store[i][7]); }}} else { fprintf(fp1,"\n\tMOV %s,R0",store[i][2]); fprintf(fp1,"\n\tMOV R0,%s",store[i][0]); }} fclose(f); fclose(fp1); return 0; } INPUT FILE: Y=10; X=20; T11=x*20; T21=y+t11; L1:if(z<x) goto l2 Goto lnext;

L2: Lnext: OUTPUT FILE: MOV R0,Y MOV 20,R0 MOV R0,X MOV X,R0 MUL10 ,R0 MOV R0,T11 MOV Y,R0 ADD T11,R0 MOV R0,T21 L1: MOV SUB CJ< J> ,R0 ,R0

RESULT: Thus the C-program for code optimization techniques is executed successfully.