Lab - Manual Compiler
Lab - Manual Compiler
Aim
Write a C program to design a Lexical analyzer to recognize the tokens defined by the given
grammar.
Algorithm
1) Start
2) Declare an array of characters, an input file to store the input;
3) Read the character from the input file and put it into character type of variable, say
‘c’.
4) If ‘c’ is blank then do nothing.
5) If ‘c’ is new line character line=line+1.
6) If ‘c’ is digit, set token Val, the value assigned for a digit and return the ‘NUMBER’.
7) If ‘c’ is proper token then assign the token value.
8) Print the complete table with
9) Token entered by the user,
10) Associated token value.
11) Stop
Program
#include<string.h>
#include<conio.h>
#include<ctype.h>
#include<stdio.h>
void main()
{
FILE *f1;
char c,str[10];
int lineno=1,num=0,i=0;
clrscr();
printf("\nEnter the c program\n");
f1=fopen("input.txt","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input.txt","r");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
num=c-48;
c=getc(f1);
while(isdigit(c))
{
num=num*10+(c-48);
c=getc(f1);
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 2
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
}
printf("%d is a number \n",num);
ungetc(c,f1);
}
else if(isalpha(c))
{
str[i++]=c;
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
str[i++]=c;
c=getc(f1);
}
str[i++]='\0';
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||
strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||
strcmp("double",str)==0||strcmp("static",str)==0||
strcmp("switch",str)==0||strcmp("case",str)==0)
printf("%s is a keyword\n",str);
else
printf("%s is a identifier\n",str);
ungetc(c,f1);
i=0;
}
else if(c==' '||c=='\t')
printf("\n");
else if(c=='\n')
lineno++;
else
printf("%c is a special symbol\n",c);
}
printf("Total no. of lines are: %d\n",lineno);
fclose(f1);
getch();
}
OUTPUT
Aim
To Implement the Recursive Descent Parser for the given grammar / language
Algorithm
1) Start.
2) Read the input string.
3) Write procedures for the non terminals
4) Verify the next token equals to non terminals if it satisfies match the non terminal.
5) If the input string does match print string accepted.
6) Else print string not accepted.
7) Stop.
Program
#include<stdio.h>
//#include<conio.h>
#include<string.h>
#define epsilon 238
int flag=0,len,pt=0;
char st[25];
void E();
void T();
void F();
void EPRIME();
void TPRIME();
void ADVANCE();
int main()
{
//clrscr();
printf("\nRecursive Descent parser\n");
printf("\nE ->TE'\nE' ->+TE' /%c\nT ->FT'\nT' ->*FT'/%c\nF -> (E)/a\n",epsilon,epsilon);
printf("enter the string :");
scanf("%s",st);
len=strlen(st);
E();
if((flag==0)&&(len==pt))
printf("\n\nstringis accepted\n\n");
else
printf("\nstring rejected\n");
//getch();
return 0;
}
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 5
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
void E()
{
T();
EPRIME();
}
void T()
{
F();
TPRIME();
}
void EPRIME()
{
if(st[pt]=='+')
{
ADVANCE();
T();
EPRIME();
}
}
void TPRIME()
{
if(st[pt]=='*')
{
ADVANCE();
F();
TPRIME();
}
}
void F()
{
if(st[pt]=='(')
{
ADVANCE();
E();
if(st[pt]==')')
ADVANCE();
else
flag=1;
}
else if(st[pt]=='a')
ADVANCE();
else
flag=1;
}
void ADVANCE()
{
pt++;
}
Output
Algorithm
To compute First(X) for all grammar symbol X, apply the following rules.
Program
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
int ister(char);
void first(char);
void follow(char);
char grammar[20][20]={"E->TX","X->+TX","X->i","T->FY","Y->*FY","Y->i","F-
>(E)","F->i"};
char ter[]={'+','*','(',')','i'};
char nonter[]={'E','X','T','Y','F'};
char FIRST[10],FOLLOW[10];
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 8
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
int fi,fo;
void main()
{
int i,j;
clrscr();
cout<<"\n\n\n\t\t\tGRAMMAR\n\t\t\t----\n";
cout<<"\n\t\t\tE->TX"<<"\n\n\t\t\tX->+TX"<<"\n\n\t\t\tX->i";
cout<<"\n\n\t\t\tT->FY"<<"\n\n\t\t\tY->*FY"<<"\n\n\t\t\tY->i";
cout<<"\n\n\t\t\tF->(E)"<<"\n\n\t\t\tF->i";
printf("\n\n\t\tFIRST\n\t\t-----\n");
for(i=0;i<5;i++)
{
fi=0;
for(j=0;j<10;j++)
FIRST[j]='\0';
printf("\n\tFIRST(%c)={ ",nonter[i]);
first(nonter[i]);
for(j=0;j<strlen(FIRST);j++)
printf("%c,",FIRST[j]);
printf("\b }");
}
printf("\n\t\tFOLLOW\n\t\t------\n");
for(i=0;i<5;i++)
{
fo=0;
for(j=0;j<10;j++)
FOLLOW[j]='\0';
printf("\n\tFOLLOW(%c)={ ",nonter[i]);
follow(nonter[i]);
for(j=0;j<strlen(FOLLOW);j++)
printf("%c,",FOLLOW[j]);
printf("\b }");
}
getch();
}
void first(char x)
{
int i;
if(ister(x))
{
FIRST[fi]=x;
fi++;
}
else
for(i=0;i<8;i++)
if(grammar[i][0]==x)
if(grammar[i][3]=='i')
{
FIRST[fi]='i';
fi++;
}
else
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 9
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
first(grammar[i][3]);
}
void follow(char x)
{
int i,j,k,flag;
if(x=='E')
{
FOLLOW[fo]='$';
fo++;
}
for(i=0;i<8;i++)
for(j=4;grammar[i][j]!='\0';j++)
if(grammar[i][j]==x)
if(grammar[i][j+1]=='\0')
{
follow(grammar[i][0]);
return;
}
else
{
fi=flag=0;
first(grammar[i][j+1]);
for(k=0;k<fi;k++)
if(FIRST[k]!='i')
{
FOLLOW[fo]=FIRST[k];
fo++;
}
else
flag=1;
if(flag)
{
follow(grammar[i][0]);
return;
}
}
}
int ister(char a)
{
int i;
for(i=0;i<5;i++)
if(ter[i]==a)
return 1;
return 0;
}
Output
Algorithm
1) Start.
2) Read the input file.
3) Read character by character.
4) If the read character in new line or end of line, increment the counter for number of
lines.
5) If the read character in space, tab, new line or end of line, increment the counter for
number of words.
6) If the number of characters read is greater than zero then print the values of word
counter and line counter.
7) Stop.
Program
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
printf("Enter source file path: ");
scanf("%s", path);
file = fopen(path, "r");
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
characters = words = lines = 0;
Output
Algorithm
1) Invoke a function getreg to find out the location L where the result of computation b
op c should be stored.
2) Consult the address description for y to determine y'. If the value of y currently in
memory and register both then prefer the register y' . If the value of y is not already in
L then generate the instruction MOV y' , L to place a copy of y in L.
3) Generate the instruction OP z' , L where z' is used to show the current location of z. if
z is in both then prefer a register to a memory location. Update the address descriptor
of x to indicate that x is in location L. If x is in L then update its descriptor and
remove x from all other descriptor.
4) If the current value of y or z have no next uses or not live on exit from the block or in
register then alter the register descriptor to indicate that after execution of x : = y op z
those register will no longer contain y or z.
Program
#include<stdio.h>
#include<stdlib.h>
//#include<conio.h>
#include<math.h>
#include<ctype.h>
#include<string.h>
char in[25],post[25],stack[25],st[25][25],three[10][10],u[5];
int i,s,p,r,item,top,b,th=0,tr=0;
int pre(char t)
{
int r;
if((t=='+')||(t=='-'))
r=1;
if((t=='*')||(t=='/'))
r=2;
if(t=='^')
r=3;
if((t=='(')||(t==')'))
r=0;
return(r);
}
int main()
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 14
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
{
int j,k,p,q,a,b;
char *buff;
//clrscr();
r=1;
printf("\t\tOUTPUT\n");
printf("****************************************\n");
printf("Enter the expression:\n");
scanf("%s",in);
s=1;
p=0;
stack[0]='(';
for(i=2;in[i]!='\0';i++)
{
if((in[i]!='+')&&(in[i]!='-')&&(in[i]!='*')&&(in[i]!='/')&&(in[i]!='^')&&(in[i]!='(')&&(in[i]!
=')'))
{
post[p]=in[i];
p++;
}
else
{
if(in[i]=='(')
{
stack[s]=in[i];
s++;
}
else
{
if(in[i]==')')
{
while(stack[s-1]!='(')
{
post[p]=stack[s-1];
stack[s-1]=' ';
s--;
p++;
}
stack[s-1]=' ';
s--;
}
else
{
a=pre(in[i]);
b=pre(stack[s-1]);
j=p;
while(a<=b)
{
post[j]=stack[s-1];
stack[s-1]=' ';
s--;
j++;
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 15
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
p=j;
b=pre(stack[s-1]);
}
stack[s]=in[i];
s++;
}}}}
for(i=s-1;i>0;i--)
if(stack[i]!='(')
{
post[p]=stack[i];
p++;
}
printf("\n\nThe postfix notation for the given expression:\n\n");
for(p=0;post[p]!='\0';p++)
printf("%c",post[p]);
printf("\n\nThree address code\n\n");
top=0;
for(p=0;post[p]!='\0';p++)
{
if((post[p]!='+')&&(post[p]!='-')&&(post[p]!='*')&&(post[p]!='/')&&(post[p]!='^'))
{
st[top][0]=post[p];
st[top][1]='\0';
top++;
}
else
{
printf("t%d=%s%c%s\n",tr,st[top-2],post[p],st[top-1]);
top--;
top--;
snprintf (u, sizeof(u), "%d",tr);
//itoa(tr,u,10);
strcpy(st[top],"t");
strcat(st[top],u);
tr++;
top++;
}}
printf("%c=%s",in[0],st[0]);
//getch();
}
Output
Algorithm
1) Start the program
2) Open the source file and store the contents as quadruples.
3) Check for operators, in quadruples, if it is an arithmetic operator generator it or if
assignment operator generates it, else perform unary minus on register C.
4) Write the generated code into output definition of the file in outp.c
5) Print the output.
6) Stop the program.
Program
#include<stdio.h>
#include<string.h>
int main()
{
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 17
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
char icode[10][30],str[20],opr[10];
int i=0;
//clrscr();
printf("\n Enter the set of intermediate code (terminated by exit):\n");
do
{
scanf("%s",icode[i]);
} while(strcmp(icode[i++],"exit")!=0);
printf("\n target code generation");
printf("\n************************");
i=0;
do
{
strcpy(str,icode[i]);
switch(str[3])
{
case '+':
strcpy(opr,"ADD");
break;
case '-':
strcpy(opr,"SUB");
break;
case '*':
strcpy(opr,"MUL");
break;
case '/':
strcpy(opr,"DIV");
break;
}
printf("\n\tMov %c,R%d",str[2],i);
printf("\n\t%s%c,R%d",opr,str[4],i);
printf("\n\tMov R%d,%c",i,str[0]);
}while(strcmp(icode[++i],"exit")!=0);
//getch();
return 0;
}
Output
Algorithm
1) Start the program
2) Lex program consists of three parts.
3) Declaration %%
4) Translation rules %%
5) Auxiliary procedure.
6) The declaration section includes declaration of variables, main test, constants and regular
definitions.
7) Translation rule of lex program are statements of the form
8) P1{action}
9) P2{action}
10) …..
11) …..
12) Pn{action}
13) Write program in the vi editor and save it with .1 extension.
14) Compile the lex program with lex compiler to produce output file as lex.yy.c.
15) Eg. $ lex filename.1
16) $gcc lex.yy.c-11
17) Compile that file with C compiler and verify the output.
Program
math[+|-|*|/|^]
eq[=|>|<|]
sp[,|;]
%%
"if"|"else"|"int"|"char"|"double" printf("\n%s\t is a keyword",yytext);
[a-zA-Z][a-zA-Z0-9]* printf("\n%s\t is an identifier",yytext);
[0-9] printf("\n%s\t is a constant",yytext);
{sp} printf("\n%s\t is a special character",yytext);
{math} printf("\n%s\t is an arithmetic operator",yytext);
{eq} printf("\n%s\t is an equality operator",yytext);
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 19
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
%%
int yywrap()
{
return 1;
}
int main(int argc, char **argv)
{
yyin=fopen(argv[1],"r");
yylex();
fclose(yyin);
return 0;
}
Output
Algorithm
1) Start the program.
2) Write code for the parser. l in the declaration part.
3) Write code for the ‘y’ parser.
4) Also write code for validating the input variable name.
5) Write additional code to print the result of computation.
6) Execute and verify it.
7) Stop the program.
Program
Lex File
%{
#include "y.tab.h"
%}
%%
[a-zA-Z][a-zA-Z0-9]* return letter;
[0-9] return digit;
. return yytext[0];
\n return 0;
%%
int yywrap()
{
return 1;
}
YACC File
%{
#include<stdio.h>
int valid=1;
%}
%token digit letter
%%
start : letter s
s : letter s
| digit s
|
;
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 21
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
%%
int yyerror()
{
printf("\nIt is not a valid variable!\n");
valid=0;
return 0;
}
int main()
{
printf("\nEnter a variable name.\n ");
yyparse();
if(valid)
{
printf("\nIt is a valid variable!\n");
}
}
Output
Algorithm
1) Start the program.
2) Write code for the parser. l in the declaration part.
3) Write code for the ‘y’ parser.
4) Also write the code for different arithmetical operations.
5) Write additional code to print the result of computation.
6) Execute and verify it.
7) Stop the program.
Program
Lex File
%{
#include "y.tab.h"
%}
%%
[a-zA-Z] {return ID;}
[0-9]+ {return NUMBER;}
[\t] {;}
\n {return 0;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}
Yacc File
%{
#include<stdio.h>
%}
%token ID NUMBER
%left '+''-'
%left '*''/'
%%
stmt:expr
;
expr: expr'+'expr
|expr'-'expr
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 23
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
|expr'*'expr
|expr'/'expr
|'('expr')'
|NUMBER
|ID
;
%%
void main()
{
printf("\n Enter an expression : \n");
yyparse();
printf("\n Valid expression \n");
exit(0);
}
void yyerror()
{
printf("\n Invalid expression \n");
exit(0);
}
Output
Algorithm
1) Start the program.
2) Write code for the parser. l in the declaration part.
3) Write code for the ‘y’ parser.
4) Also write the code for different arithmetical operations.
5) Write additional code to print the result of computation.
6) Execute and verify it.
7) Stop the program.
Program
Lex File
%{
#include<stdio.h>
#include"y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {
yylval=atoi(yytext);
return NUMBER;
}
[\t];
[\n] return 0;
. return yytext[0];
%%
int yywrap()
{
return 1;
}
Yacc File
%{
#include<stdio.h>
int flag=0;
%}
%token NUMBER;
%left '+''-'
%left '*''/''%'
%left '('')'
%%
ArithmeticExpression: E{
printf("\nResult=%d\n",$$);
return 0;
};
E:E'+'E {$$=$1+$3;}
|E'-'E {$$=$1-$3;}
|E'*'E {$$=$1*$3;}
|E'/'E {$$=$1/$3;}
|E'%'E {$$=$1%$3;}
|'('E')' {$$=$2;}
|NUMBER {$$=$1;}
;
%%
void main()
{
printf("\nEnter any arithmetic expression:\n");
yyparse();
if(flag==0)
printf("\nEntered arithmetic expression is valid\n\n");
}
void yyerror()
{
printf("\nEntered arithmetic expression is invalid\n\n");
flag=1;
}
Output
Algorithm
worklist = all statements in SSA
while worklist ≠ ∅
remove some statement S from worklist
if S is x = phi(c,c,…c) for some constant c
replace S with v = c
if S is x = c for some constant c
delete S form the program
for each statement T that uses v, substitute c for x in T
worklist = worklist union {T}
Program
#include<stdio.h>
#include<string.h>
#include<ctype.h>
//#include<conio.h>
void input();
void output();
void change(int p,char *res);
void constant();
struct expr
{
char op[2],op1[5],op2[5],res[5];
int flag;
}arr[10];
int n;
int main()
{
//clrscr();
input();
constant();
output();
//getch();
return 0;
}
void input()
{
int i;
printf("\n\nEnter the maximum number of expressions : ");
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 27
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
scanf("%d",&n);
printf("\nEnter the input : \n");
for(i=0;i<n;i++)
{
scanf("%s",arr[i].op);
scanf("%s",arr[i].op1);
scanf("%s",arr[i].op2);
scanf("%s",arr[i].res);
arr[i].flag=0;
}
}
void constant()
{
int i;
int op1,op2,res;
char op,res1[5];
for(i=0;i<n;i++)
{
if(isdigit(arr[i].op1[0]) && isdigit(arr[i].op2[0]) || strcmp(arr[i].op,"=")==0)
{
for(i=0;i<n;i++)
{
if(!arr[i].flag)
{
printf("\n%s %s %s %s",arr[i].op,arr[i].op1,arr[i].op2,arr[i].res);
}
}
}
void change(int p,char *res)
{
int i;
for(i=p+1;i<n;i++)
{
if(strcmp(arr[p].res,arr[i].op1)==0)
strcpy(arr[i].op1,res);
else if(strcmp(arr[p].res,arr[i].op2)==0)
strcpy(arr[i].op2,res);
}
}
Output
Algorithm
loop forever:
for top-of-stack symbol, s, and next input symbol, a
case action of T[s,a]
shift x: (x is a STATE number)
push a, then x on the top of the stack and advance ip to point to the
next input symbol.
reduce y: (y is a PRODUCTION number)
assume that the production is of the form
A => beta
pop 2 * |beta| symbols of the stack. At this point the top of the stack
should be a state number, say s’. Push A, then goto of T[s’,A] (a state
number) on the top of the stack. Output the production
A =>beta
accept:
return --- a successful parse.
default:
error --- the input string is not in the language.
Program
#include<stdio.h>
#include<stdlib.h>
//#include<conio.h>
#include<string.h>
char ip_sym[15],stack[15];
int ip_ptr=0,st_ptr=0,len,i;
char temp[2],temp2[2];
char act[15];
void check();
int main()
{
//clrscr();
stack[st_ptr]=ip_sym[ip_ptr];
stack[st_ptr+1]='\0';ip_sym[ip_ptr]=' ';
ip_ptr++;
printf("\n $%s\t\t%s$\t\t\t%s",stack,ip_sym,act);
strcpy(act,"shift");
temp[0]=ip_sym[ip_ptr];temp[1]='\0';strcat(act,temp);check();
st_ptr++;
st_ptr++;check();
}
void check()
{
int flag=0;temp2[0]=stack[st_ptr];temp2[1]='\0';
if((!strcmp(temp2,"a"))||(!strcmp(temp2,"b")))
stack[st_ptr]='E';if(!strcmp(temp2,"a"))
printf("\n$%s\t\t%s$\t\t\tE->a",stack,ip_sym);
else
printf("\n $%s\t\t%s$\t\t\tE->b",stack,ip_sym);
flag=1;
}
if((!strcmp(temp2,"+"))||(strcmp(temp2,"*"))||(!strcmp(temp2,"/")))
flag=1;
if((!strcmp(stack,"E+E"))||(!strcmp(stack,"E\E"))||(!strcmp(stack,"E*E")))
{
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 31
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
strcpy(stack,"E");
st_ptr=0;
if(!strcmp(stack,"E+E"))
printf("\n$%s\t\t%s$\t\t\tE->E+E",stack,ip_sym);
else
if(!strcmp(stack,"E\E"))
printf("\n$%s\t\t%s$\t\t\tE->E\E",stack,ip_sym);
else
if(!strcmp(stack,"E*E"))
printf("\n $%s\t\t%s$\t\t\tE->E*E",stack,ip_sym);
else
printf("\n $%s\t\t%s$\t\t\tE->E+E",stack,ip_sym);
flag=1;
}
if(!strcmp(stack,"E")&&ip_ptr==len)
printf("\n $%s\t\t%s$\t\t\tACCEPT",stack,ip_sym);
//getch());
exit(0);
if(flag==0)
printf("\n%s\t\t\t%s\t\t reject",stack,ip_sym);exit(0);
}
Output
GRAMMAR is –
E->2E2
E->3E3
E->4
stack input action
$ 32423$ SHIFT
$3 2423$ SHIFT
$3E 3$ SHIFT
$E $ Accept
Algorithm
Program
%{
int v=0;
int c=0;
%}
%%
[aeiouAEIOU] {v++;}
[a-zA-Z] {c++;}
"\n" { printf("Number of vowels are: %d\n",v); v=0;
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 34
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
int main()
{
printf("Enter the string of vowels and consonents:");
yylex();
return 0;
}
int yywrap()
{
return 1;
}
Output
Algorithm
1) Initially Q’= φ
2) Add q0 for NFA to Q’. Then find the transitions from this start state.
3) In Q’, Find the possible set of states for each input symbol. If this set of states is not
in Q’, then add it to Q’.
4) In DFA, the find state will be all the states which contain F (final states of NFA)
Program
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
int ninputs;
int dfa[100][2][100] = {0};
int state[10000] = {0};
char ch[10], str[1000];
int go[10000][2] = {0};
int arr[10000] = {0};
int main()
{
int st, fin, in;
int f[10];
int i,j=3,s=0,final=0,flag=0,curr1,curr2,k,l;
int c;
for(i=0;i<st;i++)
state[(int)(pow(2,i))] = 1;
int p,q,r,rel;
in = pow(2,in);
i=0;
int x=0;
for(i=0;i<st;i++)
{
for(j=0;j<2;j++)
{
int stf=0;
for(k=0;k<st;k++)
{
if(dfa[i][j][k]==1)
stf = stf + pow(2,k);
}
go[(int)(pow(2,i))][j] = stf;
printf("%d-%d-->%d\n",(int)(pow(2,i)),j,stf);
if(state[stf]==0)
arr[x++] = stf;
state[stf] = 1;
}
if(new==0)
new = go[h][j];
new = new | (go[h][j]);
}
}
if(state[new]==0)
{
arr[x++] = new;
state[new] = 1;
}
}
}
printf("STATE 0 1\n");
for(i=0;i<10000;i++)
{
if(state[i]==1)
{
//printf("%d**",i);
int y=0;
if(i==0)
printf("q0 ");
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 38
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
else
for(j=0;j<st;j++)
{
int x = 1<<j;
if(x&i)
{
printf("q%d ",j);
y = y+pow(2,j);
//printf("y=%d ",y);
}
}
//printf("%d",y);
printf(" %d %d",go[y][0],go[y][1]);
printf("\n");
}
}
j=3;
while(j--)
{
printf("\nEnter string");
scanf("%s",str);
l = strlen(str);
curr1 = in;
flag = 0;
printf("\nString takes the following path-->\n");
printf("%d-",curr1);
for(i=0;i<l;i++)
{
curr1 = go[curr1][str[i]-'0'];
printf("%d-",curr1);
}
for(i=0;i<fin;i++)
{
if(curr1 & (1<<f[i]))
{
flag = 1;
break;
}
}
if(flag)
printf("\nString Accepted");
else
printf("\nString Rejected");
CS-341 COMPILER DESIGN LAB LAB MANUAL
Page 39
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
return 0;
}
Output
Algorithm
Program
#include<stdio.h>
#include<string.h>
void display(int n) {
int k = 0;
printf("Epsilon closure of %s = { ", copy);
while (k < n) {
printf(" %s", result[k]);
k++;
}
printf(" } nnn");
}
int main() {
FILE * INPUT;
INPUT = fopen("input.dat", "r");
char state[3];
int end, i = 0, n, k = 0;
char state1[3], input[3], state2[3];
printf("Enter the no of states: ");
scanf("%d", & n);
printf("Enter the states");
for (k = 0; k < 3; k++) {
scanf("%s", states[k]);
if (strcmp(state, state1) == 0) {
if (strcmp(input, "e") == 0) {
add_state(state2, i++);
strcpy(state, state2);
}
}
}
display(i);
rewind(INPUT);
}
return 0;
}
Output
1. What is a compiler?
A compiler is a program that reads a program written in one language –the source
language and translates it into an equivalent program in another language-the target
language. The compiler reports to its user the presence of errors in the source
program.
Load-and-go
15. Mention the various notational shorthands for representing regular expressions.
One or more instances (+)
Zero or one instance (?)
Character classes ([abc] where a,b,c are alphabet symbols denotes the regular
expressions a | b | c.)
Non regular sets
18. List the various error recovery strategies for a lexical analysis.
Possible error recovery actions are:
Panic mode recovery
Deleting an extraneous character
Inserting a missing character
Replacing an incorrect character by a correct character
Transposing two adjacent characters
Left factoring
Ambiguity
39. What is the intermediate code representation for the expression a or b and not c?
The intermediate code representation for the expression a or b and not c is the three
address sequence
t1 := not c
t2 := b and t1
t3 := a or t2
40. What are the various methods of implementing three address statements?
The three address statements can be implemented using the following methods.
Quadruple : a structure with atmost four fields such as operator(OP),arg1,arg2,result.
Triples : the use of temporary variables is avoided by referring the pointers in the
symbol table.
Indirect triples : the listing of triples has been done and listing pointers are used
instead of using statements.
47. How would you represent the following equation using DAG?
a:=b*-c+b*-c