0% found this document useful (0 votes)
39 views40 pages

Nba - CD Lab Manual

The document provides information about a Compiler Design lab at Raadjhani Engineering College including its vision, mission, program outcomes, educational objectives, specific outcomes, course outcomes, and safety precautions. The lab covers various phases of compilers and parser design, intermediate code representations, storage allocation strategies, optimization techniques, and code generation.

Uploaded by

rajatkumar88478
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)
39 views40 pages

Nba - CD Lab Manual

The document provides information about a Compiler Design lab at Raadjhani Engineering College including its vision, mission, program outcomes, educational objectives, specific outcomes, course outcomes, and safety precautions. The lab covers various phases of compilers and parser design, intermediate code representations, storage allocation strategies, optimization techniques, and code generation.

Uploaded by

rajatkumar88478
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/ 40

RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR

RCS6C202 COMPILER DESIGN LAB

LABORATORY MANUAL

COMPILER DESIGN LAB


SUBJECT CODE: RCS6C202

DEPARTMENT COMPUTER SCIENCE & ENGINEERING


RAAJDHANI ENGGINEERING COLLEGE
BHUBANESWAR

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

VISION
 To impart high quality professional training with an emphasis on basic principles of computer
science and engineering
 To strengthen links with industry through partnerships and collaborative development works
 To attain self-sustainability and overall development through research, consultancy and
development activities
 To make the students as for as possible industry ready to enhance their employability in the
industries
 To improve department industry collaboration through internship program and interaction with
professional society through seminar/workshops

MISSION
 To enhance knowledge and skills of students in science, technology and humanbehavior that will
serve the nation.
 To create an ambience for new idea, research, innovation and entrepreneurial attitude, with a
high level of ethics, communication and leadership qualities.
 To develop ability and passion to work wisely, creatively, and effectively in each member of
college for the betterment of the mankind and all living beings

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Program Outcomes (POs)


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

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Program Educational Objectives (PEOs)

PE01: Graduates will have a thorough grounding in the key principles and practices of computing, and will have
applied their software development skills and knowledge of foundational principles to the design and
implementation of practical systems consisting of software and/or hardware components to meet customer
requirements.
PEO2: Graduates will be successfully employed in the computing profession, and will be actively engaged in
learning, understanding, and applying new ideas and technologies as the field evolves; or will have successfully
completed, or be actively pursuing, graduate studies in computing.
PEO3: To impart science-based engineering education to develop professional skills that will prepare the
students for immediate employment in the relevant branch of engineering in industry, as against the model that
just prepares them for post-graduate education.
PEO4: To develop the design capability among students so that they have the ability to participate in creative,
synthetic and integrative activities of the relevant branch of engineering
PEO5: To develop among students breadth of knowledge so that they have familiarity with many
important technical areas

Program Specific Outcomes (PSOs)

Students:

PSO 1: To develop among students ability to apply in depth knowledge of one or more
specializations within the relevant branch of engineering.

PSO 2: To develop communication skills so that the students are able to express ideas clearly and
persuasively, in written and oral forms.

PSO 3: To develop among students the awareness of, and the competence to be savvy users of
information Technology

PSO 4: To develop ability to design and perform experiments in the relevant discipline, and to
acquire the ability to interpret and evaluate experimental results.

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Course Outcomes (COs)


CO1: Discuss the major phases of compilers and use the knowledge of the Lex tool.
CO2: Develop the parsers and experiment with the knowledge of different parsers design without
automated tools.
CO3: Describe intermediate code representations using syntax trees and DAG’s as well as use this
knowledge to generate intermediate code in the form of three address code representations.
CO4: Classify various storage allocation strategies and explain various data structures used in
symbol tables
CO5: Summarize various optimization techniques used for dataflow analysis and generate
machine code from the source code of a novel language.
CO6: To design the compiler given the features of the languages and Code optimization and Data
flow analysis

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

RULESANDREGULATIONS

1. When entering a laboratory for an experiment, be aware of the zone in which the experiment will be
conducted and use the PPEs accordingly. Students are required to come with appropriate attire and
shoes for the experiment. No dangling objects (e.g., necklace), loose-fit garments, and slippers are
allowed.
2. Each laboratory is equipped with a first-aid box and fire extinguishers to be used in an emergency.
The safety guides with emergency contact telephone numbers will be made available to all students.
A safety telephone directory will also be available near the laboratory telephones for quick access..
3. Be cognizant about the emergency exits, fire exits, and assembly areas when you are working in a
laboratory.
4. In an emergency, seek professional help. Consult the laboratory staff who have been trained to
provide professional help. Do not attend to any safety operation if you are not trained.
5. If you come across any defective equipment with potential risks, inform the laboratory staff
immediately.
6. In case of any type of accident and/or if someone is hurt, seek help immediately. Behave as a
responsible citizen in case of serious accidents and report to the concerned authorities. Breaching of
safety rules during an experiment will not be tolerated.
7. After finishing each experiment, they must get the staff member in charge to sign the laboratory
record

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

SAFETYPRECAUTIONS

1. All staff, students and others who work in laboratory must understand and agree to the information
in this document. All procedures which need to be conducted alone or after-hours need to be
reviewed for hazards and must be

2. Approved by the in charge laboratory. Know location of all exits, evacuation route, first aid kit, eye
wash, fire extinguisher.

3. Shoes must completely cover the foot. No sandals or any other shoes are allowed.

4. No food or drink of any kind in the laboratory.

5. No equipment may be operated without proper training or demonstrated competency.

6. All work space must be kept clear of clutter. All exits, fire extinguishers, electrical disconnects,
eye.

7. Washes and safety showers must remain accessible at all times. All equipment guards must remain
in place. You may not modify equipment without approval of the in charge laboratory.

8. Any unsafe or dangerous behavior must be reported to the in charge laboratory.

9. Any electrical work must be reviewed by an electrician prior to energization.

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

CONTENTS
SL NAMEOFTHE EXPERIMENTS PAGE NO
NO
1 Using JFLAP, create a DFA from a given regular expression. All types 11
of error must be checked during the conversion.
2 Read a regular expression in standard form and check its validity by 15
converting it to postfix form. Scan a string and check whether the
string matches against the given regular expression or not.
3 (Tokenizing). A programs that reads a source code in C/C++ from an 19
unformatted file and extract various types of tokens from it (e.g.
keywords/variable names, operators, constant values).
4 Read a regular expression in its standard form and find out an Ɛ-NFA 23
from it. Need to use adjacency list data structure of graph to store
NFA. Thompson’s construction needs to be used too.
5 Evaluate an arithmetic expression with parentheses, unary and binary 26
operators using Flex and Yacc.
6 (Tokenizing) Use Lex and yacc to extract tokens from a given source 29
code.
7 Write a suitable data structure to store a Context Free Grammar. 33
Prerequisite is to eliminate left recursion from the grammar before
storing. Write functions to find FIRST and FOLLOW of all the
variables.
8 Using JFLAP create LL(1) parse table for a given CFG and hence 36
Simulate LL(1) parsing.
9 Using JFLAP create SLR(1) parse table for a given grammar. Simulate 38
parsing and output the parse tree proper format.

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

INDEXSHEET/VALUATIONSHEET

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

SL NO. EXPERIMENT Attendance


Lab Record Lab Final ExperimentSignature With Date
(20) Viva & Viva (50)
&performance (10)
(20)

1.
Using JFLAP, create a DFA from a given
regular expression. All types of error must be
checked during the conversion.

2. Read a regular expression in standard


form and check its validity by converting it
to postfix form. Scan a string and check
whether the string matches against the
given regular expression or not.

3. (Tokenizing). A programs that reads a source


code in C/C++ from an unformatted file and
extract various types of tokens from it (e.g.
keywords/variable names, operators, constant
values).
4. Read a regular expression in its standard
form and find out an Ɛ-NFA from it. Need to
use adjacency list data structure of graph to
store NFA. Thompson’s construction needs to
be used too.
5.
Evaluate an arithmetic expression with
parentheses, unary and binary operators
using Flex and Yacc.
6.
(Tokenizing) Use Lex and yacc to extract
tokens from a given source code.
7. Write a suitable data structure to store a
Context Free Grammar. Prerequisite is to
eliminate left recursion from the grammar
before storing. Write functions to find FIRST
and FOLLOW of all the variables.
8. Using JFLAP create LL(1) parse table for a
given CFG and hence Simulate LL(1) parsing.

9.
Using JFLAP create SLR(1) parse table for a
given grammar. Simulate parsing and output
the parse tree proper format.

PRACTICAL/SESSIONAL EVALUTION SCHEME


COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Pass mark will be 50% which means students have to score 50 out of 100

Evaluation Scheme
Attendance & Daily performance 20
Lab manual 20
Lab quiz 10
Final experiment & viva 50
Total 100

All lab examination is to be completed one week before the end semester examination and
marks are to be displayed on the collage notice board.

AIM OF THE EXPERIMENT- 1


Using JFLAP, create a DFA from a given regular expression. All types of error must be checked during the conversion

Apparatus Required

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

A desktop computer
Marker pen /Paper / notebook
JFLAP program

Procedure:
What is JFLAP: -

JFLAP program makes it possible to create and simulate automata. Learning about automata with pen
and paper can be difficult, time consuming and error-prone. With JFLAP we can create automata of
different types and it is easy to change them as we want. JFLAP supports creation of DFA and NFA,
Regular Expressions, PDA, Turing Machines, Grammars and more.

Setup: -

JFLAP is available from the homepage: (www.JFLAP.org). From there press “Get FLAP” and follow the
instructions. You will notice that JFLAP have a .JAR extension. This means that you need Java to run
JFLAP. With Java correctly installed you can simply select the program to run it. You can also use a
command console run it from the files current directory with, Java –jar JFLAP.jar.

Using JFLAP: -

When you first start JFLAP you will see a small menu with a selection of eleven different automata and rule
sets. Choosing one of them will open the editor where you create chosen type of automata. Usually you
can create automata containing states and transitions but there is also creation of Grammar and Regular
Expression which is made with a text editor.

DFA from a given regular expression: -


First, we need to select Regular Expression from the JFLAP Menu.

Now you should have an empty window in front of you. You will have a couple of tools and features at your
disposal

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

The toolbar contains six tools, which are used to edit automata.

Attribute Editor Tool, changes properties and position of existing states and transitions.
State Creator Tool, creates new states.
Transition Creator Tool, creates transitions.
Deletion Tool, deletes states and transitions.
Undo/Redo, changes the selected object prior to their history.

Regular Expressions can be typed into JFLAP to be converted to an NFA

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Choose Regular Expression in the main menu, then just type the expression in the textbox. Definitions
for Regular Expressions in JFLAP:
Correctly written expressions can then be converted to an NFA. To convert your expression select Convert
→ Convert to NFA. The conversion will begin with two states and a transition with your Regular
Expression. With the (D)e-expressionify Transition tool you can break down the Regular Expression into
smaller parts. Each transition will contain a sub expression. The next step is to link every rule with lambda
transitions. Add new transition between states that should be connected with the Transition Tool. If you
are unsure what to do you can select Do Step to automatically make the next step. If you want the NFA
immediately Do All creates the whole NFA for you.

You can notice how the conversion differs depending on how the Regular Expression looks. For
example the expression a+b results in a fork, were either ‘a’ or ‘b’ can be chosen.

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Now finally convert NFA to DFA:-

Input & Output / Conclusion:

Input : Enter a String: aaaabbbbb Output: aaaabbbbb is accepted under rule 'a*b+

AIM OF THE EXPERIMENT - 2


Read a regular expression in standard form and check its validity by converting it to postfix form. Scan a string and
check whether the string matches against the given regular expression or not.
Apparatus Required

A desktop computer
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Marker pen /Paper / notebook


JFLAP program

Procedure:

1. /*
2. * C Program to Implements Regular Expression Matching
3. */
4. #include <stdio.h>
5. #include <string.h>
6. #define MATCH printf("\nThe Text Matches The Regular Expression");
7. #define NOTMATCH printf("\nThe Text Doesn't match the Regular
Expression");
8.
9. char reg[20], text[20];
10.
11. int main()
12. {
13. int i, rlen, tlen, f = 0;
14. char ans;
15.
16. do {
17. printf("\nEnter the Regular Expression\n");
18. scanf(" %[^\n]s", reg);
19. for (rlen = 0; reg[rlen] != '\0';rlen++);
20. printf("\nEnter the text\n");
21. scanf(" %[^\n]s", text);
22. for (tlen = 0;text[tlen] != '\0' ; tlen++);
23. if (reg[0] == '*')
24. {
25. printf("\nInvalid regular expression");
26. }
27. /*
28. *If the regular expression starts with Alphabet
29. */
30. if ((reg[0] >= 65 && reg[0] <= 90) || (reg[0] >= 97
&& reg[0] <=122))
31. {
32. if (reg[0] == text [0])
33. {
34. switch (reg[1])
35. {
36. case '.' :
37. switch (reg[2])
38. {
39. case '*':
40. if (tlen != 1)
41. {
42. if (reg[3] == text[tlen-1])
43. {
44. MATCH;
45. }
46. else
47. {
48. NOTMATCH;

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB
49. }
50. }
51. else
52. {
53. NOTMATCH;
54. }
55. break;
56. case '+':
57. if (text[1] != reg[3])
58. {
59. if (reg[3] == text[tlen - 1])
60. {
61. MATCH;
62. }
63. else
64. {
65. NOTMATCH;
66. }
67. }
68. break;
69. case '?':
70. if (text[1] == reg[3] || text[2] ==
reg[3])
71. {
72. if (text[1] == reg[3] || text[2]
== reg[3])
73. {
74. MATCH;
75. }
76. else
77. {
78. NOTMATCH;
79. }
80. }
81. else
82. {
83. NOTMATCH;
84. }
85. break;
86. }
87. break;
88. case '*':
89. if (reg[rlen-1] == text[tlen-1])
90. {
91. for (i = 0;i <= tlen-2;i++)
92. {
93. if(text[i] == reg[0])
94. {
95. f = 1;
96. }
97. else
98. {
99. f = 0;
100. }
101. }
102. if ( f == 1)
103. {
104. MATCH;
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB
105. }
106. else
107. {
108. NOTMATCH;
109. }
110. }
111. else
112. {
113. NOTMATCH;
114. }
115. break;
116. case '+' :
117. if (tlen <= 2)
118. {
119. NOTMATCH;
120. }
121. else if (reg[rlen-1] == text[tlen-1])
122. {
123. for (i = 0;i < tlen-2;i++)
124. {
125. if (text[i] == reg[0])
126. {
127. f = 1;
128. }
129. else
130. {
131. f = 0;
132. }
133. }
134.
135. if (f == 1)
136. {
137. MATCH;
138. }
139. else
140. {
141. NOTMATCH;
142. }
143. }
144. break;
145. case '?':
146. if (reg[rlen -1] == text[tlen-1])
147. {
148. MATCH;
149. }
150. else
151. {
152. NOTMATCH;
153. }
154. break;
155. }
156.
157. }
158. else
159. printf("Does not match");
160. }
161. /*
162. *If Regular Expression starts with '^'
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB
163. */
164. else if (reg[0] == '^')
165. {
166. if (reg[1] == text[0])
167. {
168. MATCH;
169. }
170. else
171. {
172. NOTMATCH;
173. }
174. }
175. /*
176. *If Regular Expression Ends with '$'
177. */
178. else if (reg[rlen-1] == '$')
179. {
180. if (reg[rlen-2] == text[rlen-1])
181. {
182. MATCH;
183. }
184. else
185. {
186. NOTMATCH;
187. }
188. }
189.
190. else
191. printf("Not Implemented");
192. printf("\nDo you want to continue?(Y/N)");
193. scanf(" %c", &ans);
194. } while (ans == 'Y' || ans == 'y');
195. }

Input & Output / Conclusion

Enter the Regular Expression


C.*g

Enter the text


Cprogramming

The Text Matches The Regular Expression


Do you want to continue?(Y/N)y

AIM OF THE EXPERIMENT - 3


(Tokenizing). A programs that reads a source code in C/C++ from an unformatted file and extract various types of
tokens from it (e.g. keywords/variable names, operators, constant values).
Apparatus Required

A desktop computer
Marker pen /Paper / notebook
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

JFLAP program

Procedure:

Lexical analysis is the process of converting a sequence of characters (such as in a computer program of
web page) into a sequence of tokens (strings with an identified “meaning”). A program that perform
lexical analysis may be called a lexer, tokenize or scanner.

Algorithm:-

1. Start the program


2. Include the header files.
3. Allocate memory for the variable by dynamic memory allocation function.
4. Use the file accessing functions to read the file.
5. Get the input file from the user.
6. Separate all the file contents as tokens and match it with the functions.
7. Define all the keywords in a separate file and name it as key.c
8. Define all the operators in a separate file and name it as open.c
9. Give the input program in a file and name it as input.c
10. Finally print the output after recognizing all the tokens.
11. Stop the program.

Program:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void main()
{
FILE *fi,*fo,*fop,*fk;
int flag=0,i=1;
char c,t,a[15],ch[15],file[20];
clrscr();
printf("\n Enter the File Name:");
scanf("%s",&file);
fi=fopen(file,"r");
fo=fopen("inter.c","w");
fop=fopen("oper.c","r");
fk=fopen("key.c","r");
c=getc(fi);
while(!feof(fi))

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

{
if(isalpha(c)||isdigit(c)||(c=='['||c==']'||c=='.'==1))
fputc(c,fo);
else
{
if(c=='\n')
fprintf(fo,"\t$\t");
else fprintf(fo,"\t%c\t",c);
}
c=getc(fi);
}
fclose(fi);
fclose(fo);
fi=fopen("inter.c","r");
printf("\n Lexical Analysis");
fscanf(fi,"%s",a);
printf("\n Line: %d\n",i++);
while(!feof(fi))
{
if(strcmp(a,"$")==0)
{
printf("\n Line: %d \n",i++);
fscanf(fi,"%s",a);
}
fscanf(fop,"%s",ch);
while(!feof(fop))
{
if(strcmp(ch,a)==0)
{
fscanf(fop,"%s",ch);
printf("\t\t%s\t:\t%s\n",a,ch);
flag=1;
} fscanf(fop,"%s",ch);
}
rewind(fop);
fscanf(fk,"%s",ch);
while(!feof(fk))
{
if(strcmp(ch,a)==0)
{

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

fscanf(fk,"%k",ch);
printf("\t\t%s\t:\tKeyword\n",a);
flag=1;
}
fscanf(fk,"%s",ch);
}
rewind(fk);
if(flag==0)
{
if(isdigit(a[0]))
printf("\t\t%s\t:\tConstant\n",a);
else
printf("\t\t%s\t:\tIdentifier\n",a);
}
flag=0;
fscanf(fi,"%s",a); }
getch();
}
Input Files:
Oper.c
( open para
) closepara
{ openbrace }
closebrace <
lesser
> greater
" doublequote ' singlequote :
colon
; semicolon
# preprocessor =
equal
== asign
% percentage ^
bitwise
& reference *
star
+ add -
sub
\ backslash /
slash

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Key.C
int
void
main
char
if
for
while
else
printf
scanf
FILE
Include
stdio.h
conio.h
iostream.h

Input.c
#include "stdio.h"
#include "conio.h"
void main()
{
int a=10,b,c;
a=b*c;
getch();
}
Input & Output / Conclusion :

AIM OF THE EXPERIMENT- 4

Read a regular expression in its standard form and find out an Ɛ-NFA from it. Need to use adjacency list data structure
of graph to store NFA. Thompson’s construction needs to be used too.
Apparatus Required

A desktop computer
Marker pen /Paper / notebook
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

JFLAP program

Procedure:

INPUT STRING : to recognize strings under 'a*', 'a*b+', 'abb'.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char s[20],c;
int state=0,i=0;
clrscr();
printf("\n Enter a string:");
gets(s);
while(s[i]!='\0')
{
switch(state)
{
case 0: c=s[i++];
if(c=='a')
state=1;
else if(c=='b')
state=2;
else
state=6;
break;
case 1: c=s[i++];
if(c=='a')
state=3;
else if(c=='b')
state=4;
else
state=6;
break;
case 2: c=s[i++];
if(c=='a')
state=6;
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

else if(c=='b')
state=2;
else
state=6;
break;
case 3: c=s[i++];
if(c=='a')
state=3;
else if(c=='b')
state=2;
else
state=6;
break;
case 4: c=s[i++];
if(c=='a')
state=6;

else if(c=='b')
state=5;
else
state=6;
break;
case 5: c=s[i++];
if(c=='a')
state=6;
else if(c=='b')
state=2;
else
state=6;
break;
case 6: printf("\n %s is not recognised.",s);
exit(0);
}
}
f(state==1)
printf("\n %s is accepted under rule 'a'",s);
else if((state==2)||(state==4))
printf("\n %s is accepted under rule 'a*b+'",s);
else if(state==5)
printf("\n %s is accepted under rule 'abb'",s);

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

getch();
}

Input & Output / Conclusion:

Input :

Enter a String: aaaabbbbb

Output:

aaaabbbbb is accepted under rule 'a*b+'

Enter a string: cdgs

cdgs is not recognized

AIM OF THE EXPERIMENT - 5

Evaluate an arithmetic expression with parentheses, unary and binary operators using Flex and Yacc.[Need to write
yylex() function and to be used with Lex and yacc.]
Apparatus Required

A desktop computer
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Marker pen /Paper / notebook


JFLAP program

Procedure:

Algorithm:
1) Get the input from the user and Parse it token by token.

2) First identify the valid inputs that can be given for a program.

3) The Inputs include numbers, functions like LOG, COS, SIN, TAN, etc. and operators.

4) Define the precedence and the associatively of various operators like +,-,/,* etc.

5) Write codes for saving the answer into memory and displaying the result on the screen.

6) Write codes for performing various arithmetic operations.

7) Display the possible Error message that can be associated with this calculation.

8) Display the output on the screen else display the error message on the screen.

Program:

CALC.L

%{
#include<stdio.h>
#include<stdlib.h>
void yyerror(char *);
#include "y.tab.h"
int yylval;
%}
%%
[a-z] {yylval=*yytext='&'; return VARIABLE;}
[0-9]+ {yylval=atoi(yytext); return INTEGER;}
CALC.Y
[\t] ;
%%
int yywrap(void)
{
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

return 1;
}
%token INTEGER VARIABLE
%left '+' '-'
%left '*' '/'
%{
int yylex(void);
void yyerror(char *);
int sym[26];
%}
%%
PROG:
PROG STMT '\n'
;
STMT: EXPR {printf("\n %d",$1);}
| VARIABLE '=' EXPR {sym[$1] = $3;}
;
EXPR: INTEGER
| VARIABLE {$$ = sym[$1];}
| EXPR '+' EXPR {$$ = $1 + $3;}
| '(' EXPR ')' {$$ = $2;}
%%
void yyerror(char *s)
{
printf("\n %s",s);
return;
}
int main(void)
{
printf("\n Enter the Expression:");
yyparse();
return 0;
}

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Input & Output / Conclusion

$ lex calc.l
$ yacc -d calc.y
$ cc y.tab.c lex.yy.c -ll -ly -lm
$ . / a . out
Enter the Expression: ( 5 + 4 ) * 3
Answer: 27

AIM OF THE EXPERIMENT - 6

(Tokenizing) Use Lex and yacc to extract tokens from a given source code.
Apparatus Required

A desktop computer
Marker pen /Paper / notebook
JFLAP program
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Procedure:

Algorithm:
1. First, a specification of a lexical analyzer is prepared by creating a program lexp.l in the
LEX language.
2. The Lexp.l program is run through the LEX compiler to produce an equivalent code in C
language named Lex.yy.c
3. The program lex.yy.c consists of a table constructed from the Regular Expressions of
Lexp.l, together with standard routines that uses the table to recognize lexemes.
Finally, lex.yy.c program is run through the C Compiler to produce an object program a.out, which is the
lexical analyzer that transforms an input stream into a sequence of tokens.
Program:
lexp.l
%{
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* {printf ("\n %s is a Preprocessor Directive",yytext);}
int |
float |
main |
if |
else |
printf |
scanf |
for |
char |
getch |
while {printf("\n %s is a Keyword",yytext);}
"/*" {COMMENT=1;}
"*/" {COMMENT=0;}
{identifier}\( {if(!COMMENT) printf("\n Function:\t %s",yytext);} \
{ {if(!COMMENT) printf("\n Block Begins"); \} {if(!COMMENT)
printf("\n Block Ends");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s is an
Identifier",yytext);} \".*\" {if(!COMMENT) printf("\n %s is a String",yytext);}
[0-9]+ {if(!COMMENT) printf("\n %s is a Number",yytext);} \)
(\;)? {if(!COMMENT) printf("\t");ECHO;printf("\n");} \( ECHO;

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

= {if(!COMMENT) printf("\n%s is an Assmt oprtr",yytext);} \


<= | \>= | \< |
== {if(!COMMENT) printf("\n %s is a Rel. Operator",yytext);}
.|\n
%%
int main(int argc, char **argv)
{
if(argc>1)
{
FILE *file;
file=fopen(argv[1],"r");
if(!file)
{
printf("\n Could not open the file: %s",argv[1]);
exit(0);
}
yyin=file;
}
yylex();
printf("\n\n");
return 0;
}
int yywrap()
{
return 0;
}
Output:
test.c
#include<stdio.h>
main()
{
int fact=1,n;
for(int i=1;i<=n;i++)
{ fact=fact*i; }
printf("Factorial Value of N is", fact);
getch();
}
$ lex lexp.l
$ cc lex.yy.c
$ ./a.out test.c

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

#include<stdio.h> is a Preprocessor Directive


Function: main( )
Block Begins
int is a Keyword
fact is an Identifier
= is an Assignment Operator
1 is a Number
n is an Identifier
Function: for(
int is a Keyword
i is an Identifier
= is an Assignment Operator
1 is a Number i is
an Identifier
<= is a Relational Operator n
is an Identifier
i is an Identifier );
Block Begins
fact is an Identifier
= is an Assignment Operator
fact is an Identifier
i is an Identifier
Block Ends
Function: printf(
"Factorial Value of N is" is a String
fact is an Identifier ); Function:
getch( );
Block Ends

Input & Output / Conclusion:

test.c
#include<stdio.h>
main()
{
int fact=1,n;
for(int i=1;i<=n;i++)
{ fact=fact*i; }
printf("Factorial Value of N is", fact);
getch();
}
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

$ lex lexp.l
$ cc lex.yy.c
$ ./a.out test.c
#include<stdio.h> is a Preprocessor Directive
Function: main( )
Block Begins
int is a Keyword
fact is an Identifier
= is an Assignment Operator
1 is a Number
n is an Identifier
Function: for(
int is a Keyword
i is an Identifier
= is an Assignment Operator
1 is a Number i is
an Identifier
<= is a Relational Operator n
is an Identifier
i is an Identifier );
Block Begins
fact is an Identifier
= is an Assignment Operator
fact is an Identifier
i is an Identifier
Block Ends
Function: printf(
"Factorial Value of N is" is a String
fact is an Identifier ); Function:
getch( );
Block Ends
AIM OF THE EXPERIMENT - 7
Write a suitable data structure to store a Context Free Grammar. Prerequisite is to eliminate left recursion from the
grammar before storing. Write functions to find FIRST and FOLLOW of all the variables.[May use unformatted file /
array to store the result].
Apparatus Required

A desktop computer
Marker pen /Paper / notebook
JFLAP program

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Procedure:

Algorithm:

First ()-

If x is a terminal, then FIRST(x) = { ‘x’ }


If x-> Є, is a production rule, then add Є to FIRST(x).
If X->Y1 Y2 Y3….Yn is a production,
FIRST(X) = FIRST(Y1)
If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }
If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X).

Follow ()-

FOLLOW(S) = { $ } // where S is the starting Non-Terminal


If A -> pBq is a production, where p, B and q are any grammar symbols,
then everything in FIRST(q) except Є is in FOLLOW(B).
If A->pB is a production, then everything in FOLLOW(A) is in FOLLOW(B).
If A->pBq is a production and FIRST(q) contains Є,
then FOLLOW(B) contains { FIRST(q) – Є } U FOLLOW(A)

Program:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
int n,m=0,p,i=0,j=0;
char a[10][10],f[10];
void follow(char c);
void first(char c);
int main(){
int i,z;
char c,ch;
clrscr();
printf("Enter the no of prooductions:\n");
scanf("%d",&n);
printf("Enter the productions:\n");
for(i=0;i<n;i++)
scanf("%s%c",a[i],&ch);
do{
m=0;
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

printf("Enter the elemets whose fisrt & follow is to be found:");


scanf("%c",&c);
first(c);
printf("First(%c)={",c);
for(i=0;i<m;i++)
printf("%c",f[i]);
printf("}\n");
strcpy(f," ");
//flushall();
m=0;
follow(c);
printf("Follow(%c)={",c);
for(i=0;i<m;i++)
printf("%c",f[i]);
printf("}\n");
printf("Continue(0/1)?");
scanf("%d%c",&z,&ch);
}while(z==1);
return(0);
}
void first(char c)
{
int k;
if(!isupper(c))
f[m++]=c;
for(k=0;k<n;k++)
{
if(a[k][0]==c)
{
if(a[k][2]=='$')
follow(a[k][0]);
else if(islower(a[k][2]))
f[m++]=a[k][2];
else first(a[k][2]);
}
}
}
void follow(char c)
{
if(a[0][0]==c)
f[m++]='$';
for(i=0;i<n;i++)

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

{
for(j=2;j<strlen(a[i]);j++)
{
if(a[i][j]==c)
{
if(a[i][j+1]!='\0')
first(a[i][j+1]);
if(a[i][j+1]=='\0' && c!=a[i][0])
follow(a[i][0]);
}
}
}
Input & Output / Conclusion

AIM OF THE EXPERIMENT - 8


Using JFLAP create LL(1) parse table for a given CFG and hence Simulate LL(1) parsing.
Apparatus Required

A desktop computer
Marker pen /Paper / notebook
JFLAP program

Procedure:

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Implementation: -

Step 1. Choose the grammar from JFLAP and insert grammar you want to create LL(1) parsing table.

Step 2: - Select the Input from Menu and select Build LL(1) parsing table from it.

Step 3: - Now select parse to use that table to create parse tree from it.

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Input & Output / Conclusion:

We create LL(1) parse table for a given CFG and hence Simulate LL(1) parsing

AIM OF THE EXPERIMENT - 9


Using JFLAP create SLR(1) parse table for a given grammar. Simulate parsing and output the parse tree proper format.
Apparatus Required

A desktop computer
Marker pen /Paper / notebook
JFLAP program

Procedure:
COMPILER DESIGN LAB
RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Implementation:
Step 1: - Choose the grammar from JFLAP and insert grammar you want to create SLR(1) parsing table.

Step 2: - Select the Input from Menu and select Build SLR (1) parsing table from it.

Step 3: - Now select parse to use that table to create parse tree from it.

COMPILER DESIGN LAB


RAAJDHANI ENGINEERING COLLEGE (B-Tech), BHUBANESWAR
RCS6C202 COMPILER DESIGN LAB

Input & Output / Conclusion:

We created SLR(1) parse table for a given grammar and Simulated parsing and output the parse
tree proper format

COMPILER DESIGN LAB

You might also like