Lab Manual Compiler Design 2024-25
Lab Manual Compiler Design 2024-25
LABORATORY MANUAL
COMPILER DESIGN LAB
(KCS-552)
Name
Roll No.
Section-Batch
2
PROGRAM OUTCOMES (POS) AND PROGRAM SPECIFIC
OUTCOMES (PSOs)
S. No. Program Outcomes / Program Specific Outcomes
3
CSE DEPARTMENT PROGRAM EDUCATIONAL OBJECTIVES (PEOs)
B. Tech Computer Science & Engineering Department has the following Program Educational
Objectives:
PEO1: Possess core theoretical and practical knowledge in Computer Science and Engineering for
successful career development in industry, pursuing higher studies or entrepreneurship.
PEO2: Ability to imbibe lifelong learning for global challenges to impact society and the
environment.
PEO3: To demonstrate work productivity, leadership and managerial skills, ethics, and human
value in progressive career path.
PEO4: To exhibit communication skill and collaborative skill plan and participate in multidisciplinary
Computer Science & Engineering fields.
B.Tech Computer Science & Engineering Department has the following Program Specific Outcomes:
PSO1: To analyze and demonstrate, the recent engineering practices, ethical values and strategies in
real-time world problems to meet the challenges for the future.
PSO2: To develop adaptive computing system using computational intelligence strategies and
algorithmic design to address diverse data analysis and machine learning challenges.
4
PROGRM OUTCOMES
Engineering Graduates will be able to:
5
GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with
the synopsis / program / experiment details.
Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab session.
Laboratory Record updated up to the last session experiments and other utensils (if
any) needed in the lab.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will
attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if
anybody found loitering outside the lab / class without permission during working hours will
be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system /
seat is kept properly.
4
DETAILS OF THE EXPERIMENTS CONDUCTED
(TO BE USED BY THE STUDENTS IN THEIR RECORDS)
INDEX
10
5
STUDY AND EVALUATION SCHEME
Course Course
Teaching Scheme Credits Assigned
Code Name
Compiler Theory Practical Tutorial Theory Practical Tutorial Total
KCS-552 (P) Design Lab
00 02 00 00 01 00 01
(50
Marks)
6
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science and Engineering
Bloom’s
COURSE OUTCOMES Level
Identify patterns, tokens & regular expressions for lexical analysis. K2,K4
C308.1
Design Lexical analyser for given language using C and LEX /YACC tools’ K3,K5
C308.2
K4, K5
C308.4 Generate the intermediate code.
CO-PO Matrix
Course
PO 1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
Outcome
C308.1 2 2 2 1 2 1 1 1 2 1 2 2 2 1
C308.2 2 2 2 2 2 1 1 1 2 1 1 1 1 2
C308.3 2 2 2 2 1 1 1 1 2 1 1 1 2 1
C308.4 2 2 1 1 1 1 1 1 2 1 1 1 1 2
C308.5 2 2 1 2 1 1 1 1 2 1 1 2 2 2
C308 2.0 2.0 1.6 1.6 1.4 1.0 1.0 1.0 2.0 1.0 1.2 1.4 1.6 1.6
7
LIST OF PROGRAMS
3. Write a program of a grammar, which accepts the odd no. of zero. C308.1
4. Write a program of a grammar, which accepts the even no. of zero. C308.1
6. Write a program to identify that the given grammar is Left recursive or not. C308.3
9. Write program to find Simulate First and Follow of any given grammar. C308.3
14. Implement the back end of the compiler which takes the three-address code C308.5
and produces the 8086 assembly language instructions that can be assembled
and run using an 8086 assembler. The target assembly instructions can be
simple move, add, sub, jump etc.
8
EXPERIMENT NO. - 1
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<string.h
> void main()
{
char a[10];
int
i,l,flag=0;
clrscr();
puts( "Enter the string to be
matched"); gets(a);
l=strlen(a);
if (l>8)
{
for(i=8; i<10 ; i++)
{
a[i]=0;
}
}
if(a[0]>=97 && a[0]<123 || a[0]>=65 && a[0]<91|| a[0]==95)
{
for(i=1;i<=l;i++)
{
if ( a[i]>=97 && a[i]<123 || a[i]>=65 && a[i]<91 || a[i]>=48 && a[i]<58 || a[i]==95)
{
flag=
0;
break;
}
}
if (flag==1)
{
puts(" This is invalid identifier");
exit(0);
}
else
{
puts(" valid
identifier"); getch();
}
}
}
9
Output:
Enter the string to be matched
Abcd
valid identifier
Enter the string to be matched
12abcd
This is invalid identifier .
Viva Questions:
10
EXPERIMENT NO. - 2
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<string.h
> void main()
{
char a[32][10]={"auto","break","case","char","const","continue","default",
"do","double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"
};
char *b; /* here you can also write b[30];*/ int
i,c;
clrscr();
printf("Enter the string to be matched\n");
gets(b);
for(i=0;i<=30;i++ )
{
c=strcmp(a[i],b); if(c==0)
{
printf("This string is valid keyword\n");
getch();
}
}
printf("Given string is invalid keyword\n");
getch();
}
11
Output:
Enter the string to be
matched int
This string is valid keyword
Enter the string to be
matched dfr
Given string is invalid keyword
Viva Questions:
12
EXPERIMENT NO. - 3
AIM: Write a program of a grammar which accepts the odd no. of zero
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<string.h
>
void main()
{
char a[10]; int
s,q0,q1,i;
clrscr();
printf("Enter a binary string:");
gets(a);
s=q0; for(i=0;a[i]!='\0';i++)
{
if(a[i]=='0' && s==q0)
s=q1;
else if(a[i]=='0' && s==q1)
s=q0;
}
if(s==q1)
printf("Grammar is accepted."); else
printf("Grammar is not accepted.");
getch();
}
Output:
Enter a binary string:
01100
Grammar is accepted
Enter a binary
string: 011000
Grammar is not accepted
13
Viva Questions:
1. What will be the regular expression for the language where odd no of 0's
is followed by even no of 1's?
2. How many states are there in a DFA for accepting strings that contains
even number of 0's and odd number of 1's?
3. What will be the minimum number of states for strings with odd number of A's?
4. Does DFA accept empty language?
5. Is DFA a complete system?
14
EXPERIMENT NO. - 4
AIM: Write a program of a grammar which accepts the even no. of zero
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<string.h
> void main()
{
char a[10]; int
s,q0,q1,i;
clrscr();
printf("Enter a binary string:");
gets(a);
s=q0; for(i=0;a[i]!='\0';i++)
{
if(a[i]=='0' && s==q0)
s=q1;
else if(a[i]=='0' && s==q1)
s=q0;
}
if(s==q0)
printf("Grammar is accepted."); else
printf("Grammar is not accepted.");
getch();
}
Output:
Enter a binary string:
011000
Grammar is accepted
Enter a binary
string: 01100
Grammar is not accepted
15
Viva Questions:
1. How many states are there in a DFA for accepting strings that contains
even number of 0's and odd number of 1's?
2. What is DFA?
3. How many number of transitions would take to accept 1001 string over the
input alphabet 0 1?
4. How many no of states are there in a FA which accepts a string which starts
with string 101?
5. It it possible in DFA, that a state has more one outgoing transition for same input.
16
EXPERIMENT NO. - 5
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<string.h
> void main()
{
char a[10];
int s,q0,q1,q2,dead,i;
clrscr();
printf("Enter a binary string:");
gets(a);
s=q0; for(i=0;a[i]!='\0';i++)
{
if(a[i]=='a' && s==q0)
s=q1;
}
if(s==q2)
printf("String is accepted."); else
printf("String is not accepted.");
getch();
}
17
Output:
Enter a binary string
aabbab
String is accepted.
ababa
String is not accepted.
Viva Questions:
18
EXPERIMENT NO. - 6
AIM: Write a program to identify that the given grammar is Left recursive or not.
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<string.h
> void main()
{
char a[10][10],i=-1,flag=0;
clrscr();
printf("Enter the Productions:\n"); do
{ i++;
gets(a[i]);
}
while(a[i][0]!='\0'); printf("Your
Productions:\n"); for(i=0;a[i]
[0]!='\0';i++) puts(a[i]);
for(i=0;a[i][0]!='\0';i++)
{ if(a[i][0]==a[i][3])
flag++;
}
if(flag!=0)
printf("Grammar is Left Recursive."); else
printf("Grammar is not Left Recursive.");
getch();
}
19
Output:
Enter the Productions
AAb|c
Grammar is Left
Recursive Enter the
Productions AB|c
Grammar is not Left Recursive
Viva Questions:
1. How do you check if a grammar is left recursive?
2. How do you know if a grammar is recursive?
3. What makes a grammar left recursive?
4. What is left recursive and right recursive?
5. What is problem in left recursive grammar?
20
EXPERIMENT NO. - 7
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<ctype.h
>
#include<string.h
>
void main()
{
int i=0;
char str[20];
clrscr();
printf(" \n Input the string ::");
gets(str);
printf("Corresponding Tokens are :: ");
while(str[i]!='\0')
{
if((str[i]=='(')||(str[i]=='{'))
{
printf("4");
}
if((str[i]==')')||(str[i]=='}'))
{
printf("5");
}
if(isdigit(str[i]))
{
while(isdigit(str[i]))
{
i++;
}
i--;
printf("1");
}
if(str[i]=='+')
{
printf("2");
21
}
if(str[i]=='*')
{
22
printf("3");
}
i+
+;
getch();
}
Output:
Input the string :: (12+23*34)
Corresponding Tokens are :: 4121315
Viva Questions:
1. In which phase token is given as input?
2. In which phase token is produced as output?
3. What makes a grammar left recursive?
4. What is left recursive and right recursive?
5. Describe problem in left recursive grammar.
23
EXPERIMENT NO. - 8
Code/Method:
#include<stdio.h>
#include<conio.h>
void main() {
char stack[20], ip[20], opt[10][10][1], ter[10]; int
i, j, k, n, top = 0, col, row;
clrscr();
for (i = 0; i < 10; i++)
{ stack[i] = NULL;
ip[i] = NULL;
for (j = 0; j < 10; j++) { opt[i]
[j][1] = NULL;
}
}
printf("Enter the no.of terminals :\n");
scanf("%d", & n);
printf("\nEnter the terminals :\n");
scanf("%s", & ter);
printf("\nEnter the table values :\n"); for
(i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("Enter the value for %c %c:", ter[i], ter[j]);
scanf("%s", opt[i][j]);
}
}
printf("\n**** OPERATOR PRECEDENCE TABLE ****\n"); for
(i = 0; i < n; i++) {
printf("\t%c", ter[i]);
}
printf("\n");
for (i = 0; i < n; i++) {
printf("\n%c", ter[i]);
for (j = 0; j < n; j++)
{
printf("\t%c", opt[i][j][0]);
}
}
stack[top] = '$';
24
printf("\nEnter the input string:");
25
scanf("%s",
ip); i = 0;
printf("\nSTACK\t\t\tINPUT STRING\t\t\tACTION\
n"); printf("\n%s\t\t\t%s\t\t\t", stack, ip);
while (i <= strlen(ip))
{ for (k = 0; k < n; k+
+) { if (stack[top] ==
ter[k])
col = k;
if (ip[i] == ter[k])
row = k;
}
if ((stack[top] == '$') && (ip[i] == '$'))
{ printf("String is accepted\n");
break;
} else if ((opt[col][row][0] == '<') || (opt[col][row][0] == '=')) { stack[+
+top] = opt[col][row][0];
stack[++top] = ip[i];
printf("Shift %c", ip[i]);
i++;
} else {
if (opt[col][row][0] == '>') {
while (stack[top] != '<') {
--top;
}
top = top - 1;
printf("Reduce");
} else {
printf("\nString is not
accepted"); break;
}
}
printf("\n");
for (k = 0; k <= top; k++)
{ printf("%c", stack[k]);
}
printf("\t\t\t");
for (k = i; k < strlen(ip); k++)
{ printf("%c", ip[k]);
}
printf("\t\t\t");
}
getch();
}
26
Output:
Enter the no.of terminals:4
Enter the
terminals:i+*$ Enter
$ i+i*i$ Shift
$<i +i*i$ Reduce
$<i +i*i$ Shift
$<+ i*i$ Shift
$<+<i *i$ Reduce
$<+<i *i$ Shift
$<+<* i$ Shift
$<+<*<i $ Reduce
$<+<*<i $ Reduce
$<+<*<i $ Reduce
$<+<*<i $ String is ACCEPTED
27
Viva Questions:
1. What is parsing?
2. What do you mean by operator precedence parsing?
3. What is operator precedence parser in compiler design?
4. What are properties of operator precedence parser?
5. How the parsing is performed in operator precedence parsing?
28
EXPERIMENT NO. - 9
AIM: Write a program to find out FIRST & FOLLOW of given grammar.
Code/Method:
#include<stdio.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int count, n = 0;
30
strcpy(production[6], "R=om");
strcpy(production[7], "R=ST");
int kay;
char done[count];
int ptr = -1;
if (xxx == 1)
continue;
// Function call
findfirst(c, 0, 0);
ptr += 1;
if (first[i] == calc_first[point1][lark])
{ chk = 1;
break;
}
}
if (chk == 0)
{ printf("%c, ",
31
first[i]);
calc_first[point1][point2++] = first[i];
32
}
}
printf("}\n");
jm = n;
point1++;
}
printf("\n");
printf(" "
"\n\n");
char donee[count];
ptr = -1;
// Checking if Follow of ck
// has already been calculated
for (kay = 0; kay <= ptr; kay+
+)
if (ck ==
donee[kay]) xxx
= 1;
if (xxx == 1)
continue;
land += 1;
// Function call
follow(ck);
ptr += 1;
34
}
if (chk == 0)
{ printf("%c, ",
f[i]);
calc_follow[point1][point2++] = f[i];
}
}
printf(" }\n\
n"); km = m;
point1++;
}
}
void follow(char c)
{
int i, j;
if (production[i][j + 1] == '\0'
&& c != production[i][0]) {
// Calculate the follow of the
// Non-Terminal in the L.H.S. of the
// production
follow(production[i][0]);
}
}
}
}
}
36
for (j = 0; j < count; j++) {
if (production[j][0] == c) {
if (production[j][2] == '#') {
if (production[q1][q2] == '\0')
first[n++] = '#';
else if (production[q1][q2] != '\0'
&& (q1 != 0 || q2 != 0)) {
// Recursion to calculate First of New
// Non-Terminal we encounter after
// epsilon
findfirst(production[q1][q2], q1,
(q2 + 1));
}
else
first[n++] = '#';
}
else if (!isupper(production[j][2]))
{ first[n++] = production[j][2];
}
else {
// Recursion to calculate First of
// New Non-Terminal we encounter
// at the beginning
findfirst(production[j][2], j, 3);
}
}
}
}
Output:
First(X) = { q, n, o, p, #,m}
First(T) = { q, #, }
First(S) = { p, #, }
First(R) = { o, p, q, #, }
Follow(X) = { $, }
Follow(T) = { n, m, }
Follow(S) = { $, q, m, }
Follow(R) = { m, }
Viva Questions:
1. How do you find first of given grammar?
2. How do you find follow of given grammar?
3. In which phase of compiler do we use first and follow?
4. Can we calculate follow of non-terminal?
5. Why is first and follow important?
38
EXPERIMENT NO. -10
AIM: Construct a recursive descent parser for an expression.
#include <stdio.h>
#include <string.h>
#define SUCCESS
1
#define FAILED 0
int E(), Edash(), T(), Tdash(), F();
const char *cursor;
char string[64];
int main()
{
puts("Enter the string");
// scanf("%s", string); sscanf("i+
(i+i)*i", "%s", string); cursor =
string;
puts("");
puts("Input Action");
puts(" ");
int E()
{
printf("%-16s E -> T E'\n", cursor);
if (T()) {
if (Edash())
return SUCCESS;
39
else
40
return FAILED;
} else
return FAILED;
}
int Edash()
{
if (*cursor == '+') {
printf("%-16s E' -> + T E'\n",
cursor); cursor++;
if (T()) {
if (Edash())
return SUCCESS;
else
return FAILED;
} else
return FAILED;
} else {
printf("%-16s E' -> $\n", cursor);
return SUCCESS;
}
}
int T()
{
printf("%-16s T -> F T'\n", cursor);
if (F()) {
if (Tdash())
return SUCCESS;
else
return FAILED;
} else
return FAILED;
}
int Tdash()
{
if (*cursor == '*') {
41
printf("%-16s T' -> * F T'\n",
cursor); cursor++;
if (F()) {
if (Tdash())
return SUCCESS;
else
return FAILED;
} else
return FAILED;
} else {
printf("%-16s T' -> $\n", cursor);
return SUCCESS;
}
}
int F()
{
if (*cursor == '(') {
printf("%-16s F -> ( E )\n", cursor);
cursor++;
if (E()) {
if (*cursor == ')') {
cursor++;
return SUCCESS;
} else
return FAILED;
} else
return FAILED;
} else if (*cursor == 'i') {
cursor++;
printf("%-16s F ->i\n", cursor);
return SUCCESS;
} else
return FAILED;
}
42
Output:
Input Action
Viva Questions:
1. How do you create a recursive descent parser?
2. What is recursive descent parser?
3. How is recursive descent parser different from recursive parser?
4. How is recursive descent parser different from from predictive parsing?
5. What is importance of recursive descent parser?
43
EXPERIMENT NO. -11
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<string.h
>
int k=0,z=0,i=0,j=0,c=0;
char a[16],ac[20],stk[15],act[10];
void check();
void main()
{
clrscr();
puts("GRAMMAR is E->E+E \n E->E*E \n E->(E) \n E->id");
puts("enter input string ");
gets(a); c=strlen(a);
strcpy(act,"SHIFT->"); puts("stack \
t input \t action"); for(k=0,i=0;
j<c; k++,i++,j++)
{
if(a[j]=='i' && a[j+1]=='d')
{
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='\0';
a[j]=' ';
a[j+1]=' ';
printf("\n$%s\t%s$\t%sid",stk,a,act);
check();
}
else
{
stk[i]=a[j];
stk[i+1]='\0';
a[j]=' ';
printf("\n$%s\t%s$\t%ssymbols",stk,a,act); check();
}
}
getch();
}
void check()
{
strcpy(ac,"REDUCE TO E"); for(z=0;
z<c; z++)
if(stk[z]=='i' && stk[z+1]=='d')
{
stk[z]='E';
44
stk[z+1]='\0'; printf("\n$%s\t%s$\t
%s",stk,a,ac); j++;
}
for(z=0; z<c; z++)
if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='E')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0'; printf("\n$%s\t%s$\
t%s",stk,a,ac); i=i-2;
}
for(z=0; z<c; z++)
if(stk[z]=='E' && stk[z+1]=='*' && stk[z+2]=='E')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0'; printf("\n$%s\t%s$\
t%s",stk,a,ac); i=i-2;
}
for(z=0; z<c; z++)
if(stk[z]=='(' && stk[z+1]=='E' && stk[z+2]==')')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0'; printf("\n$%s\t%s$\
t%s",stk,a,ac); i=i-2;
}
}
Output:
Input: 2+3*5
Output: The value of expression is 17
Viva Questions:
1. How is shift reduce parser implemented?
2. What is shift-reduce parsing?
3. What is stack implementation of shift-reduce parsing?
4. What is significance of shift-reduce parsing?
5. Shift-reduce parsing uses which data structure?
45
EXPERIMENT NO. -12
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
for(i=0;i<10;i+=2
)
{
printf("fun(%d)\n",i+1);
printf("fun(%d)\n",i+2);
}
}
Output:
fun(1)
fun(2)
fun(3)
fun(4)
fun(5)
fun(6)
fun(7)
fun(8)
fun(9)
fun(10
)
Viva Questions:
1. What is loop unrolling?
2. What is advantage of loop unrolling?
3. What is disadvantage of loop unrolling?
4. After loop unrolling compile time increased or decreased?
5. Shift-reduce parsing uses which data structure?
46
EXPERIMENT NO. -13
48
{
k[j].pos=i; k[j+
+].op='+';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='-')
{
k[j].pos=i;
k[j+
+].op='-';
}
}
void explore()
{i
=1
;
while(k[i].op!='\0')
{
fleft(k[i].pos);
fright(k[i].pos);
str[k[i].pos]=tmpch--;
printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right); printf("\
n");
i++;
}
fright(-1);
if(no==0)
{
fleft(strlen(str));
printf("\t%s := %s",right,left);
getch();
exit(0);
}
printf("\t%s := %c",right,str[k[--i].pos]);
getch();
}
void fleft(int x)
{
int
w=0,flag=0;
x--;
while(x!=-1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!='- '&&str[x]!
='/'&&str[x]!=':')
{
if(str[x]!='$'&& flag==0)
{
left[w++]=str[x];
left[w]='\0';
str[x]='$';
flag=1;
}
x--;
49
}
}
void fright(int x)
50
{
int
w=0,flag=0;
x++;
while(x!=-1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!=':'&&str[x]!='-
'&&str[x]!='/')
{
if(str[x]!='$'&& flag==0)
{
right[w++]=str[x];
right[w]='\0';
str[x]='$';
flag=1;
}
x+
+;
}
}
Output:
Viva Questions:
1. Illustrate the basic steps for the intermediate code generation.
2. What is intermediate code generation in system programming?
3. What is the need of intermediate code generation and how does it work?
4. Explain the role of intermediate code in compiler design?
5. Is intermediate code equal to assembly code?
51
EXPERIMENT NO. -14
AIM : Implement the back end of the compiler which takes the three address code
and produces the 8086 assembly language instructions that can be assembled and
run using an 8086 assembler. The target assembly instructions can be simple
move, add, sub, jump etc.
Code/Method:
52
OUTPUT:
Viva Questions:
53