0% found this document useful (0 votes)
5 views55 pages

Lab Manual Compiler Design 2024-25

The document is a laboratory manual for the Compiler Design Lab course at IMS Engineering College, detailing the vision and mission of the institute and department, program outcomes, and specific educational objectives. It includes general laboratory instructions, a list of experiments, and course outcomes related to compiler design. The manual aims to guide students in practical applications of compiler design principles and ensure adherence to academic standards.

Uploaded by

noconed316
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views55 pages

Lab Manual Compiler Design 2024-25

The document is a laboratory manual for the Compiler Design Lab course at IMS Engineering College, detailing the vision and mission of the institute and department, program outcomes, and specific educational objectives. It includes general laboratory instructions, a list of experiments, and course outcomes related to compiler design. The manual aims to guide students in practical applications of compiler design principles and ensure adherence to academic standards.

Uploaded by

noconed316
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

IMS ENGINEERING COLLEGE

LABORATORY MANUAL
COMPILER DESIGN LAB
(KCS-552)

B.TECH – III YEAR


(Even SEM, 2024-2025)

Name

Roll No.

Section-Batch

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

IMS ENGINEERING COLLEGE


(Affiliated to Dr A P J Abdul Kalam Technical University, Lucknow )
Approved by AICTE - Accredited by NAAC – ‘A’ Grade
NH#24, Adhyatmik Nagar, Ghaziabad, UP, India
www.imsec.ac.in
VISION AND MISSION OF THE INSTITUTE AND DEPARTMENT

VISION OF THE INSTITUTE


To make IMSEC an Institution of Excellence for empowering students through technical education,
incorporating human values, and developing engineering acumen for innovations and leadership
skills to upgrade society.

MISSION OF THE INSTITUTE


 To promote academic excellence by continuous learning in core and emerging
Engineering domains using innovative teaching and learning methodologies.

 To inculcate values and ethics among the learners.

 To promote industry interactions and cultivate young minds for entrepreneurship.

 To create a conducive learning ecosystem and research environment on a perpetual basis to


develop students as technology leaders and entrepreneurs who can address tomorrow’s societal needs.

VISION OF THE DEPARTMENT


To provide globally competent professionals in Computer Science & Engineering embedded with
sound technical knowledge, aptitude for research and innovation, and nurture future leaders with
ethical values to cater to industrial & societal needs.

MISSION OF THE DEPARTMENT


Mission 1: To provide quality education in the theoretical and applied foundations of Computer
Science & Engineering.
Mission 2: To Conduct research in Computer Science & Engineering resulting in innovations thereby
nurturing entrepreneurial thinking.
Mission 3: To inculcate team-building skills and promote life-long learning with high societal and
ethical values.

2
PROGRAM OUTCOMES (POS) AND PROGRAM SPECIFIC
OUTCOMES (PSOs)
S. No. Program Outcomes / Program Specific Outcomes

Engineering knowledge: Apply the knowledge of mathematics, science,


PO1. engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze
PO2. complex engineering problems reaching substantiated conclusions using
first principles of mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the
PO3.
specified needs with appropriate consideration for the public health and safety,
and the cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based
knowledge and research methods including design of experiments, analysis
PO4.
and interpretation of data, and synthesis of the information to provide valid
conclusions.
Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
PO5.
modelling to complex engineering activities with an understanding of the
limitations.
The engineer and society: apply reasoning informed by the contextual knowledge
PO6. to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
PO7. engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and
PO8.
responsibilities and norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member
PO9.
or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities
PO10 with the engineering community and with society at large, such as, being able to
. comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of
PO11 the engineering and management principles and apply these to one’s own work, as a
. member and leader in a team, to manage projects and in multidisciplinary
environments.
Life-long learning: Recognize the need for, and have the preparation and
PO12 ability to engage in independent and life-long learning in the broadest context
. of technological change.
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.
To develop adaptive computing system using computational intelligence strategies
PSO2 and algorithmic design to address diverse data analysis and machine learning
. challenges.

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.

CSE DEPARTMENT PROGRAM SPECIFIC OUTCOMES (PSOs)

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:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

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.

3.Student should enter into the laboratory with:

 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.

 Proper Dress code and Identity card.

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

S.No TITLE OF THE EXPERIMENT DATE OF FACULTY


SUBMISSION SIGNATURE

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

Course Name: Compiler Design Lab Course Code: KCS-552


Semester / Year: 5th /3rd NBA Code: C 308

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

Design and analyze top down and bottom up parsers. K4, K5


C308.3

K4, K5
C308.4 Generate the intermediate code.

Generate machine code from the intermediate code forms K3, K4


C308.5

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

Subject: Compiler Design Lab Code: KCS-552

S.NO. NAME OF EXPERIMENT MAPPING


WITH CO
1. Implement Lexical Analyzer to identify the identifiers. C308.2

2. Implement Lexical Analyzer to identify the keywords. C308.2

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

5. Write a program to convert a given regular expression a (a|b)*b in to C308.3


deterministic finite automata.

6. Write a program to identify that the given grammar is Left recursive or not. C308.3

7. Write a program to generate tokens for the given grammar. C308.1

8. Develop an operator precedence parser for a given language. C308.3

9. Write program to find Simulate First and Follow of any given grammar. C308.3

10. Construct a recursive descent parser for an expression. C308.3

11. Construct a Shift Reduce Parser for a given language. C308.3

12. Write a program to perform loop unrolling. C308.3

13. Implement intermediate code generation for simple expression. C308.4

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

AIM: Implement Lexical Analyzer to identify the identifiers.

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:

1. What does lexical analyzer identify?


2. For what purpose lexical Analyser is used?
3. How do you identify an identifier?
4. What is another name for lexical analyser?
5. What is the output of lexical analyser?

10
EXPERIMENT NO. - 2

AIM: Implement Lexical Analyzer to identify the keywords.

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:

1. How do we implement lexical analyzer?


2. How a lexical analyzer identify the comments in the code?
3. How does lexical analysis identify tokens?
4. What program creates lexical analyzer?
5. What is output of lexical analyzer?

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

AIM: Write a program to convert a given regular expression a (a|b)*b in to


deterministic finite automata.

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;

else if(a[i]=='b' && s==q0) s=dead;

else if(a[i]=='a' && s==q1)


s=q1;

else if(a[i]=='b' && s==q1)


s=q2;

else if(a[i]=='a' && s==q2)


s=q1;

else if(a[i]=='b' && s==q2)


s=q2;

}
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:

1. What is regular expression?


2. How do you construct a DFA for the regular expression a B * ABB?
3. How do you convert a regular expression to an NFA?
4. How will you construct non-deterministic finite automata from a
regular expression?
5. Explain the conversion of regular expression to finite automata?

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
AAb|c
Grammar is Left
Recursive Enter the
Productions AB|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

AIM: Write a program to generate tokens for the given grammar.

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

AIM: Develop an operator precedence parser for a given language

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

the table values:


Enter the value for i i:
Enter the value for i +:>
Enter the value for i *:>
Enter the value for i $:>
Enter the value for + i:<
Enter the value for + +:>
Enter the value for + *:<
Enter the value for + $:>
Enter the value for * i:<
Enter the value for * +:>
Enter the value for * *:>
Enter the value for * $:>
Enter the value for $ i:<
Enter the value for $ +:<
Enter the value for $ *:<
Enter the value for $ $:-

OPERATOR PRECEDENCE TABLE:


i + * $

i| - > > >


+| < > < >
*| < > > >
$| < < < -

Enter the input string(append with $):i+i*i$

STACK INPUT STRING ACTION

$ 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>

// Functions to calculate Follow


void followfirst(char, int, int);
void follow(char c);

// Function to calculate First


void findfirst(char, int, int);

int count, n = 0;

// Stores the final result


// of the First Sets
char calc_first[10][100];

// Stores the final result


// of the Follow Sets
char calc_follow[10][100]; int
m = 0;

// Stores the production rules


char production[10][10];
char f[10], first[10];
int k; char
ck; int
e;

int main(int argc, char** argv)


{
int jm = 0;
int km = 0;
int i,
choice;
char c, ch;
count = 8;

// The Input grammar


strcpy(production[0], "X=TnS");
strcpy(production[1], "X=Rm");
strcpy(production[2], "T=q");
strcpy(production[3], "T=#");
strcpy(production[4], "S=p");
29
strcpy(production[5], "S=#");

30
strcpy(production[6], "R=om");
strcpy(production[7], "R=ST");

int kay;
char done[count];
int ptr = -1;

// Initializing the calc_first array


for (k = 0; k < count; k++) {
for (kay = 0; kay < 100; kay++)
{ calc_first[k][kay] = '!';
}
}
int point1 = 0, point2, xxx;

for (k = 0; k < count; k++)


{ c = production[k][0];
point2 = 0;
xxx = 0;

// Checking if First of c has


// already been calculated
for (kay = 0; kay <= ptr; kay++)
if (c == done[kay])
xxx = 1;

if (xxx == 1)
continue;

// Function call
findfirst(c, 0, 0);
ptr += 1;

// Adding c to the calculated list


done[ptr] = c;
printf("\n First(%c) = { ", c);
calc_first[point1][point2++] =
c;

// Printing the First Sets of the grammar


for (i = 0 + jm; i < n; i++) {
int lark = 0, chk = 0;

for (lark = 0; lark < point2; lark++) {

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;

// Initializing the calc_follow array


for (k = 0; k < count; k++) {
for (kay = 0; kay < 100; kay++)
{ calc_follow[k][kay] = '!';
}
}
point1 = 0;
int land =
0;
for (e = 0; e < count; e++) {
ck = production[e][0];
point2 = 0;
xxx = 0;

// 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;

// Adding ck to the calculated list


donee[ptr] = ck;
printf(" Follow(%c) = { ", ck);
calc_follow[point1][point2++] = ck;

// Printing the Follow Sets of the grammar


for (i = 0 + km; i < m; i++) {
int lark = 0, chk = 0;
for (lark = 0; lark < point2; lark++) {
if (f[i] == calc_follow[point1][lark])
33
{ chk = 1;
break;
}

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;

// Adding "$" to the follow


// set of the start symbol
if (production[0][0] == c)
{ f[m++] = '$';
}
for (i = 0; i < 10; i++)
{ for (j = 2; j < 10; j+
+) {
if (production[i][j] == c) {
if (production[i][j + 1] != '\0') {
// Calculate the first of the next
// Non-Terminal in the production
followfirst(production[i][j + 1], i,
(j + 2));
}

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]);
}
}
}
}
}

void findfirst(char c, int q1, int q2)


{
int j;

// The case where we


// encounter a
Terminal if (!
35
(isupper(c))) {
first[n++] = c;
}

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);
}
}
}
}

void followfirst(char c, int c1, int c2)


{
int k;

// The case where we encounter


// a Terminal
if (!(isupper(c)))
f[m++] = c;
else {
int i = 0, j = 1;
for (i = 0; i < count; i++) {
if (calc_first[i][0] == c)
break;
}

// Including the First set of the


// Non-Terminal in the Follow of
// the original query
while (calc_first[i][j] != '!') {
if (calc_first[i][j] != '#')
{ f[m++] = calc_first[i][j];
}
else {
37
if (production[c1][c2] == '\0') {
// Case where we reach the
// end of a production
follow(production[c1][0]);
}
else {
// Recursion to the next symbol
// in case we encounter a "#"
followfirst(production[c1][c2], c1,
c2 + 1);
}
}
j++;
}
}
}

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(" ");

if (E() && *cursor == '\0') {


puts(" ");
puts("String is successfully parsed");
return 0;
} else {
puts(" ");
puts("Error in parsing String");
return 1;
}
}

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:

Enter the string

Input Action

i+(i+i)*i E -> T E'


i+(i+i)*i T -> F T'
+(i+i)*i F ->i
+(i+i)*i T' -> $
+(i+i)*i E' -> + T E'
(i+i)*i T -> F T'
(i+i)*i F -> ( E )
i+i)*i E -> T E'
i+i)*i T -> F T'
+i)*i F ->i
+i)*i T' -> $
+i)*i E' -> + T E'
i) *i T -> F T'
)*i F ->i
)*i T' -> $
)*i E' -> $
*i T' -> * F
T' F ->i
T' -> $
E' -> $

String is successfully parsed

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

AIM 11: Construct a shift reduce parser for a given language.

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

AIM : Write a program to perform loop unrolling. Code/Method:

#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

AIM : Write a program to implement intermediate code generation for simple


expression.
Code/Method:
#include<stdio.h>
#include<conio.h
>
#include<string.h
>
int i=1,j=0,no=0,tmpch=90; char
str[100],left[15],right[15];
void findopr();
void explore();
void fleft(int);
void
fright(int);
struct exp
{
int pos; char
op;
}k[15];
void main()
{
printf("\t\tINTERMEDIATE CODE GENERATION\n\n"); printf("Enter
the Expression :");
scanf("%s",str);
printf("The intermediate code:\n");
findopr();
explore();
}
void findopr()
{
for(i=0;str[i]!='\0';i++)
if(str[i]==':')
{
k[j].pos=i; k[j+
+].op=':';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='/')
{
k[j].pos=i; k[j+
+].op='/';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='*')
{
k[j].pos=i; k[j++].op='*';
}
47
for(i=0;str[i]!='\0';i++)
if(str[i]=='+')

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:

#include <stdio.h >


#include <stdio.h >
#include<conio.h>
#include <string.h >
void main() {
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();
}

52
OUTPUT:

Enter the set of intermediate code (terminated by exit):


a=a*b
c=f*h
g=a*h
f=Q+
w
t=q-j
exit

target code generation


************************
Mov a,R0
MUL b,R0
Mov R0,a
Mov f,R1
MUL
h,R1
Mov R1,c
Mov a,R2
MUL
h,R2
Mov R2,g
Mov
Q,R3
ADD
w,R3
Mov
R3,f
Mov
q,R4
SUB
j,R4
Mov R4,t

Viva Questions:

1. What is a backend in compiler?


2. Describe assembly language instructions?
3. What are the types of assembly language?
4. How is assembly code executed?
5. What do you mean by an assembler?

53

You might also like