0% found this document useful (0 votes)
3 views45 pages

CD File

The document is a laboratory file for the Compiler Design Lab (BCS-652) at IMS Engineering College for B.Tech III Year students. It outlines the vision and mission of the institute and department, program outcomes, specific outcomes, educational objectives, and general laboratory instructions. Additionally, it includes a list of experiments and their corresponding course outcomes for students to conduct during the lab sessions.

Uploaded by

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

CD File

The document is a laboratory file for the Compiler Design Lab (BCS-652) at IMS Engineering College for B.Tech III Year students. It outlines the vision and mission of the institute and department, program outcomes, specific outcomes, educational objectives, and general laboratory instructions. Additionally, it includes a list of experiments and their corresponding course outcomes for students to conduct during the lab sessions.

Uploaded by

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

IMS ENGINEERING COLLEGE

LABORATORY FILE
COMPILER DESIGN LAB
(BCS-652)

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
KUNAL BISHT CSE-2 2201430100139

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
KUNAL BISHT CSE-2 2201430100139

PROGRAM OUTCOMES (POS) AND PROGRAM SPECIFIC


OUTCOMES (PSOs)
S. No. Program Outcomes / Program Specific Outcomes

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


PO1. 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 specified
PO3.
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
PO4. and research methods including design of experiments, analysis and interpretation
of data, and synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources,
PO5. and modern engineering and IT tools including prediction and modelling to
complex engineering activities with an understanding of the limitations.
The engineer and society: apply reasoning informed by the contextual knowledge to
PO6. 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
with the engineering community and with society at large, such as, being able to
PO10.
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
the engineering and management principles and apply these to one’s own work, as a
PO11.
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.
To analyze and demonstrate, the recent engineering practices, ethical values and
PSO1.
strategies in real-time world problems to meet the challenges for the future.
To develop adaptive computing system using computational intelligence strategies
and algorithmic design to address diverse data analysis and machine learning
PSO2.
challenges.

3
KUNAL BISHT CSE-2 2201430100139

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
KUNAL BISHT CSE-2 2201430100139

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
KUNAL BISHT CSE-2 2201430100139

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
KUNAL BISHT CSE-2 2201430100139

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
KUNAL BISHT CSE-2 2201430100139

STUDY AND EVALUATION SCHEME

Course Course
Teaching Scheme Credits Assigned
Code Name
Compiler Theory Practical Tutorial Theory Practical Tutorial Total
BCS-652 (P) Design Lab
00 02 00 00 01 00 01
(50
Marks)

6
KUNAL BISHT CSE-2 2201430100139

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: BCS-652


Semester / Year: 6th /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
KUNAL BISHT CSE-2 2201430100139

LIST OF PROGRAMS

Subject: Compiler Design Lab Code: BCS-652

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
KUNAL BISHT CSE-2 2201430100139

EXPERIMENT NO. - 1

AIM: Implement Lexical Analyzer to identify the identifiers.

Code/Method:

#include <stdio.h>
#include <string.h>

void main() {
char a[10];
int i, l, flag = 0;

printf("Enter the string to be matched: ");


fgets(a, sizeof(a), stdin);
a[strcspn(a, "\n")] = '\0';

l = strlen(a);

if (l > 8) {
a[8] = '\0';
l = 8;
}

if ((a[0] >= 'a' && a[0] <= 'z') || (a[0] >= 'A' && a[0] <= 'Z') || a[0] == '_') {
for (i = 1; i < l; i++) {
if (!( (a[i] >= 'a' && a[i] <= 'z') ||
(a[i] >= 'A' && a[i] <= 'Z') ||
(a[i] >= '0' && a[i] <= '9') ||
a[i] == '_')) {
flag = 1;
break;
}
}

if (flag == 1) {
printf("This is an invalid identifier\n");
} else {
printf("Valid identifier\n");
}
} else {
printf("This is an invalid identifier\n");
}
}

9
KUNAL BISHT CSE-2 2201430100139

Output:

10
KUNAL BISHT CSE-2 2201430100139

EXPERIMENT NO. - 2

AIM: Implement Lexical Analyzer to identify the keywords.

Code/Method:

#include<stdio.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[10];
int i, c;

printf("Enter the string to be matched: ");


fgets(b, sizeof(b), stdin);
b[strcspn(b, "\n")] = '\0'; // Remove newline character if present

for(i = 0; i < 32; i++) {


c = strcmp(a[i], b);
if(c == 0) {
printf("This string is a valid keyword\n");
return;
}
}

printf("Given string is an invalid keyword\n");


}

Output:

11
KUNAL BISHT CSE-2 2201430100139

EXPERIMENT NO. - 3

AIM: Write a program of a grammar which accepts the odd no. of zero

Code/Method:

#include <stdio.h>
#include <string.h>
void main() {
char a[10];
int s, q0, q1, i;
q0 = 0;
q1 = 1;
s = q0;
printf("Enter a binary string: ");
fgets(a, sizeof(a), stdin);
a[strcspn(a, "\n")] = '\0';

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.\n");
} else {
printf("Grammar is not accepted.\n");
}
}

Output:

12
EXPERIMENT NO. - 4

AIM: Write a program of a grammar which accepts the even no. of zero

Code/Method:

#include <stdio.h>
#include <string.h>

void main()
{
char a[10];
int s, q0 = 0, q1 = 1, i;
printf("Enter a binary string: ");
gets(a); // Warning: gets() is unsafe, but left unchanged per your request

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

Output:

13
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 <string.h>

int main()
{
char a[100]; // Increased buffer size for safety
int s, q0 = 0, q1 = 1, q2 = 2, dead = 3, i;

printf("Enter a binary string: ");


fgets(a, sizeof(a), stdin);

a[strcspn(a, "\n")] = '\0';

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;

else
s = dead;
}

if(s == q2)
printf("String is accepted.\n");
else
printf("String is not accepted.\n");

return 0;}

14
Output:

15
EXPERIMENT NO. - 6

AIM: Write a program to identify that the given grammar is Left recursive or
not.

Code/Method:
#include <stdio.h>
#include <string.h>

int main()
{
char a[10][20];
int i = -1, flag = 0;

printf("Enter the Productions:\n");

do
{
i++;
fgets(a[i], sizeof(a[i]), stdin);
a[i][strcspn(a[i], "\n")] = '\0'; // Remove newline
} while(a[i][0] != '\0');

// Only print entered productions (no repeat)


for(int j = 0; j < i; j++)
printf("%s\n", a[j]);

// Check for left recursion


for(int j = 0; j < i; j++)
{
char *arrow = strstr(a[j], "->");
if (!arrow)
arrow = strstr(a[j], "→");

if (arrow && a[j][0] == arrow[2])


flag++;
}

if(flag != 0)
printf("Grammar is Left Recursive.\n");
else
printf("Grammar is not Left Recursive.\n");

return 0;
}

16
Output:

17
EXPERIMENT NO. - 7

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

Code/Method:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char str[100];
int i = 0;

printf("Input the string :: ");


fgets(str, sizeof(str), stdin);

str[strcspn(str, "\n")] = '\0';

printf("Corresponding Tokens are :: ");

while (str[i] != '\0')


{
if ((str[i] == '(') || (str[i] == '{'))
{
printf("4");
}
else if ((str[i] == ')') || (str[i] == '}'))
{
printf("5");
}
else if (isdigit(str[i]))
{
while (isdigit(str[i]))
{
i++;
}
i--; // Step back after loop
printf("1");
}
else if (str[i] == '+')
{
printf("2");
}
else if (str[i] == '*')
{
printf("3");
}
i++;
18
}

printf("\n");

return 0;
}

Output:

19
EXPERIMENT NO. - 8

AIM: Develop an operator precedence parser for a given language

Code/Method:

#include <stdio.h>
#include <string.h>

int main() {
char stack[50], ip[50], opt[10][10][1], ter[10];
int i, j, k, n, top = 0, col = -1, row = -1;

// Initialize
for (i = 0; i < 10; i++) {
stack[i] = '\0';
ip[i] = '\0';
for (j = 0; j < 10; j++) {
opt[i][j][0] = '\0';
}
}
printf("Enter the number of terminals:\n");
scanf("%d", &n);

printf("Enter the terminals (as one string, e.g., +-*/):\n");


scanf("%s", ter);

printf("Enter the table values (<, >, = or blank):\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(" %c", &opt[i][j][0]); // space before %c to skip newline
}
}

printf("\n**** OPERATOR PRECEDENCE TABLE ****\n\t");


for (i = 0; i < n; i++) {
printf("%c\t", ter[i]);
}
printf("\n");

for (i = 0; i < n; i++) {


printf("%c\t", ter[i]);
for (j = 0; j < n; j++) {
printf("%c\t", opt[i][j][0]);
}
printf("\n");
}

stack[top] = '$';
20
printf("Enter the input string (append $ at end):\n");
scanf("%s", ip);

i = 0;
printf("\nSTACK\t\tINPUT STRING\t\tACTION\n");

while (i <= strlen(ip)) {


printf("\n");
for (k = 0; k <= top; k++) {
printf("%c", stack[k]);
}
printf("\t\t");
for (k = i; k < strlen(ip); k++) {
printf("%c", ip[k]);
}
printf("\t\t");

// Find position of top terminal in stack and current input symbol


col = row = -1;
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 (col != -1 && row != -1 && (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 (col != -1 && row != -1 && opt[col][row][0] == '>') {
while (stack[top] != '<' && top > 0) {
top--;
}
if (stack[top] == '<') {
top--; // pop '<'
printf("Reduce");
} else {
printf("Error: No matching '<' found.");
break;
}
} else {
printf("String is not accepted");
break;
}
}

return 0;
}
21
Output

22
EXPERIMENT NO. - 9

AIM: Write a program to find out FIRST & FOLLOW of given grammar.

Code/Method:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
void followfirst(char, int, int);
void follow(char c);
void findfirst(char, int, int);
int count = 8, n = 0, m = 0;
char calc_first[10][100];
char calc_follow[10][100];
char production[10][10];
char f[10], first[10];
int k;
char ck;

int main() {
int i, choice;
char c, done[count], donee[count];
int ptr = -1, jm = 0, km = 0;
int point1 = 0, point2, kay, xxx;
// 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");
23
strcpy(production[5], "S=#");
strcpy(production[6], "R=om");
strcpy(production[7], "R=ST");
// Initialize calc_first
for (k = 0; k < count; k++)
for (kay = 0; kay < 100; kay++)
calc_first[k][kay] = '!';
for (k = 0; k < count; k++) {
c = production[k][0];
point2 = 0;
xxx = 0;
for (kay = 0; kay <= ptr; kay++)
if (c == done[kay])
xxx = 1;
if (xxx == 1) continue;
findfirst(c, 0, 0);
ptr += 1;
done[ptr] = c;
printf("First(%c) = { ", c);
calc_first[point1][point2++] = c;
for (i = jm; i < n; i++) {
int found = 0;
for (int lark = 0; lark < point2; lark++) {
if (first[i] == calc_first[point1][lark]) {
found = 1;
break;
}
}
if (!found) {
printf("%c, ", first[i]);
calc_first[point1][point2++] = first[i];
}
24
}
printf("}\n");
jm = n;
point1++;
}
printf("\n");
// Initialize calc_follow
ptr = -1;
point1 = 0;
for (k = 0; k < count; k++)
for (kay = 0; kay < 100; kay++)
calc_follow[k][kay] = '!';
for (int e = 0; e < count; e++) {
ck = production[e][0];
point2 = 0;
xxx = 0;
for (kay = 0; kay <= ptr; kay++)
if (ck == donee[kay])
xxx = 1;
if (xxx == 1) continue;
follow(ck);
ptr += 1;
donee[ptr] = ck;
printf("Follow(%c) = { ", ck);
calc_follow[point1][point2++] = ck;
for (i = km; i < m; i++) {
int found = 0;
for (int lark = 0; lark < point2; lark++) {
if (f[i] == calc_follow[point1][lark]) {
found = 1;
break;
}
25
}
if (!found) {
printf("%c, ", f[i]);
calc_follow[point1][point2++] = f[i];
}
}
printf("}\n");
km = m;
point1++;
}
return 0;
}

void follow(char c) {
int i, j;
// Add $ to Follow of start symbol
if (production[0][0] == c) {
f[m++] = '$';
}
for (i = 0; i < count; i++) {
for (j = 2; j < strlen(production[i]); j++) {
if (production[i][j] == c) {
if (production[i][j + 1] != '\0') {
followfirst(production[i][j + 1], i, j + 2);
}
if (production[i][j + 1] == '\0' && c != production[i][0]) {
follow(production[i][0]);
}
}
}
}
}
26
void findfirst(char c, int q1, int q2) {
int j;
if (!isupper(c)) {
first[n++] = c;
return;
}
for (j = 0; j < count; j++) {
if (production[j][0] == c) {
if (production[j][2] == '#') {
if (production[q1][q2] == '\0')
first[n++] = '#';
else
findfirst(production[q1][q2], q1, q2 + 1);
} else if (!isupper(production[j][2])) {
first[n++] = production[j][2];
} else {
findfirst(production[j][2], j, 3);
}
}
}
}
void followfirst(char c, int c1, int c2) {
if (!isupper(c)) {
f[m++] = c;
return;
}
int i = 0, j = 1;
for (i = 0; i < count; i++) {
if (calc_first[i][0] == c)
break;
}
27
while (calc_first[i][j] != '!') {
if (calc_first[i][j] != '#') {
f[m++] = calc_first[i][j];
} else {
if (production[c1][c2] == '\0') {
follow(production[c1][0]);
} else {
followfirst(production[c1][c2], c1, c2 + 1);
}
}
j++;
}
}
Output:

28
EXPERIMENT NO. -10
AIM: Construct a recursive descent parser for an expression.
Code:

#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() {
printf("Enter the string: ");
scanf("%s", string);

cursor = string;

printf("\n%-16s %s\n", "Input", "Action");


printf("---------------- ----------------------------\n");

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


printf("\nString is successfully parsed\n");
return 0;
} else {
printf("\nError in parsing string\n");
return 1;
}
}

int E() {
printf("%-16s E -> T E'\n", cursor);
if (T()) {
if (Edash())
return SUCCESS;
else
return FAILED;
}
return FAILED;
}

int Edash() {
if (*cursor == '+') {
printf("%-16s E' -> + T E'\n", cursor);
cursor++;
if (T()) {
if (Edash())
return SUCCESS;
29
else
return FAILED;
} else return FAILED;
} else {
printf("%-16s E' -> epsilon\n", cursor);
return SUCCESS;
}
}

int T() {
printf("%-16s T -> F T'\n", cursor);
if (F()) {
if (Tdash())
return SUCCESS;
else
return FAILED;
}
return FAILED;
}

int Tdash() {
if (*cursor == '*') {
printf("%-16s T' -> * F T'\n", cursor);
cursor++;
if (F()) {
if (Tdash())
return SUCCESS;
else
return FAILED;
} else return FAILED;
} else {
printf("%-16s T' -> epsilon\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') {
printf("%-16s F -> i\n", cursor);
cursor++;
return SUCCESS;
} else return FAILED;
}
30
Output

31
EXPERIMENT NO. -11

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

Code/Method:
#include <stdio.h>
#include <string.h>
int k = 0, z = 0, i = 0, j = 0, c = 0;
char a[100], ac[20], stk[100], act[20];
void check();
int main() {
printf("GRAMMAR is:\nE -> E+E\nE -> E*E\nE -> (E)\nE -> id\n");
printf("Enter input string: ");
fgets(a, sizeof(a), stdin);
// Remove trailing newline from fgets
a[strcspn(a, "\n")] = '\0';
c = strlen(a);
strcpy(act, "SHIFT");
printf("\n%-10s %-15s %s\n", "Stack", "Input", "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] = ' ';
j++;
printf("\n$%-9s %-15s %s id", stk, a, act);
check();
} else {
stk[i] = a[j];
stk[i + 1] = '\0';
32
a[j] = ' ';
printf("\n$%-9s %-15s %s symbol", stk, a, act);
check();
}
}
return 0;
}
void check() {
strcpy(ac, "REDUCE TO E");
// Reduce id -> E
for (z = 0; z < c; z++) {
if (stk[z] == 'i' && stk[z + 1] == 'd') {
stk[z] = 'E';
stk[z + 1] = '\0';
printf("\n$%-9s %-15s %s", stk, a, ac);
break;
}
}
// Reduce E + E -> E
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$%-9s %-15s %s", stk, a, ac);
i -= 2;
break;
}
}
// Reduce E * E -> E
for (z = 0; z < c; z++) {
if (stk[z] == 'E' && stk[z + 1] == '*' && stk[z + 2] == 'E') {

33
stk[z] = 'E';
stk[z + 1] = '\0';
stk[z + 2] = '\0';
printf("\n$%-9s %-15s %s", stk, a, ac);
i -= 2;
break;
}
}
// Reduce ( E ) -> E
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 + 2] = '\0';
printf("\n$%-9s %-15s %s", stk, a, ac);
i -= 2;
break;
}
}
}

Output:

34
EXPERIMENT NO. -12

AIM : Write a program to perform loop unrolling.

Code/Method:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i += 2) {
printf("fun(%d)\n", i + 1);
printf("fun(%d)\n", i + 2);
}
return 0;
}

Output:

35
EXPERIMENT NO. - 13

AIM: Implement intermediate code generation for simple expression.

Code/Method:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int i = 0, j = 0, no = 0, tmpch = 90;


char str[100], left[15], right[15];

struct exp {
int pos;
char op;
int precedence;
} k[15];

void findopr();
void explore();
void fleft(int);
void fright(int);
void reverse(char *s);
void sortByPrecedence();

int precedence(char op) {


if (op == '*' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
if (op == '=') return 0;
return -1;
}

int main() {
printf("INTERMEDIATE CODE GENERATION\n\n");
printf("Enter the Expression: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';

printf("The intermediate code:\n");


findopr();
sortByPrecedence(); // sort by precedence before exploring
explore();

return 0;
}

void findopr() {
j = 0;
for (i = 0; str[i] != '\0'; i++) {
if (strchr("=/*+-", str[i])) {
k[j].pos = i;
k[j].op = str[i];
k[j].precedence = precedence(str[i]);
j++;
}
}
k[j].op = '\0';
}

void sortByPrecedence() {
// Simple bubble sort to order operators by precedence (descending)
for (int x = 0; x < j - 1; x++) {
for (int y = 0; y < j - x - 1; y++) {
if (k[y].precedence < k[y + 1].precedence) {
struct exp temp = k[y];
k[y] = k[y + 1];
k[y + 1] = temp;
}
}
}
}

void explore() {
i = 0;
while (k[i].op != '\0') {
fleft(k[i].pos);
fright(k[i].pos);
str[k[i].pos] = tmpch--;
printf("\t%c := %s %c %s\n", str[k[i].pos], left, k[i].op, right);
no++;
i++;
}

// Final assignment for '='


if (no > 0) {
char result[2] = {str[0], '\0'};
printf("\t%s := %c\n", result, str[k[i - 1].pos]);
}
}

void fleft(int x) {
int w = 0;
x--;
memset(left, 0, sizeof(left));
while (x >= 0 && !strchr("=:+-/*", str[x])) {
if (str[x] != '$') {
left[w++] = str[x];
str[x] = '$';
break;
}
x--;
}
left[w] = '\0';
reverse(left);
}

void fright(int x) {
int w = 0;
x++;
memset(right, 0, sizeof(right));
while (x < strlen(str) && !strchr("=:+-/*", str[x])) {
if (str[x] != '$') {
right[w++] = str[x];
str[x] = '$';
break;
}
x++;
}
right[w] = '\0';
}

void reverse(char *s) {


int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
char temp = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = temp;
}
}
Output:
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 <string.h>

int main() {

char icode[10][30], str[30], opr[10];

int i = 0;

printf("\nEnter the set of intermediate code (terminated by 'exit'):\n");

// Input loop for intermediate code

do {

scanf("%s", icode[i]);

} while (strcmp(icode[i++], "exit") != 0);

printf("\nTarget Code Generation");

printf("\n************************\n");

i = 0;
while (strcmp(icode[i], "exit") != 0) {

strcpy(str, icode[i]);

// Example format: a=b+c --> str[0]=a, str[2]=b, str[3]=op, str[4]=c

switch (str[3]) {

case '+': strcpy(opr, "ADD"); break;

case '-': strcpy(opr, "SUB"); break;

case '*': strcpy(opr, "MUL"); break;

case '/': strcpy(opr, "DIV"); break;

default:

printf("Unsupported operator in: %s\n", str);

i++;

continue;

printf("\tMOV %c, R%d\n", str[2], i);

printf("\t%s %c, R%d\n", opr, str[4], i);

printf("\tMOV R%d, %c\n", i, str[0]);

i++;

return 0;

}
Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy