0% found this document useful (0 votes)
100 views65 pages

Compiler Design Lab Manula

Compiler
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)
100 views65 pages

Compiler Design Lab Manula

Compiler
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/ 65

DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

LABORATORY MANUAL
ON

COMPILER DESIGN

Name……………………………………………………………………………………...

Registration Number-………………………………………………………………….

Branch-…………………………………………………….……………………………

Session-…………………………………………………………………………………...

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ARYAN INSTITUTE OF ENGINEERING AND TECHNOLOGY (AIET)


Bhubaneswar
(Approved by AICTE, New Delhi &Affiliated to BPUT, Odisha)
An ISO 9001:2008 Certified Institute

COMPILER DESIGN Page 1


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

LABORATORY MANUAL
ON
COMPILER DESIGN
Compiled by:
AMBUJA KUMAR PARIDA
Dept. of CSE Engg.

Proof Reading & Editing by:


PRAKASH DEHURY
HOD, Dept. of CSE Engg.

Edition:
Fou rth E dition: 2022

Published by:
ARYAN INSTITUE OF ENGINEERING AND TECHNOLOGY(AIET)
Bhubaneswar, Odisha

Copyright by:
ARYAN INSTITUE OF ENGINEERING AND TECHNOLOGY(AIET), BHUBANESWAR

No part of this manual may be reproduced in any form or by any means without permission from
Aryan Institute Of Engineering and Technology, Bhubaneswar.

COMPILER DESIGN Page 2


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

ARYAN INSTITUE OF ENGINEERING AND TECHNOLOGY, BHUBANESWAR

Vision

 To become a leading engineering institution of the state by imparting


quality technical education at affordable costs to create skilled and
motivated graduates to serve the technological requirements of society in
different ways.

 To provide quality education and groom students into confident and


competent professionals imbibed with ethical values to successfully meet
the challenges of a highly competitive environment in a global arena.

Mission

 To impart contemporary technical education and skills to students of


different socio-economic background.

 To equip students with analytical learning and real-life problem solving.

 To make learning a continuous endeavour compatible with market needs.

 To promote the spirit of leadership, entrepreneurship, innovation and


ethics.

 To spread knowledge in the field of Engineering & Technology.

COMPILER DESIGN Page 3


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

VISION
 To produce the professionals of highest grade, bearing the ability to face
the challenges posed by the latest comp paradigms, founded by intuitive
quality of education and driven by culture of critical thinking and creativity,
towards the betterment of humankind.
MISSION
 To advance knowledge of computing and educate students in major

paradigms of Computer Science

 To develop distinctive culture of research and innovation among the

budding engineers with collaboration of faculties, technocrats, funding

agencies

 To invite experts from other premier institutes for generating a pool of

eco-preneurs with the ability to address industry and social problems.

COMPILER DESIGN Page 4


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

Programme Educational Objectives (PEOs)


PEO 1: PEO 2: PEO 3:
To gain adequate To foster the ability to analyze Will have ability to exhibit
mathematical, computing real life problems, perform professionalism, technical
and engineering principles in required research and design skills, communication skills,
order to advance in computing systems, in accor- team work and humanitarian
dance to its solutions that are
professional career or obtain skills in their profession and
technically sound, economi-
better response in higher adapt to current changes by
cally viable and socially ad-
studies platforms. mired and adaptable. inculcating habit of life long
learning.

Programme Outcome

PO 1 Graduate would be able to apply knowledge of computing, mathematics, science


and basic engineering for finding solutions of complex engineering
problems.
PO 2 Graduate would be able to identify & design solutions for complex engineering
problems through required mathematical principles, natural sciences and
specialized knowledge in computer science and engineering.
PO 3 Graduate would be able to conduct investigation by using research based
knowledge, prepare appropriate experimental setups and able to analyze,
interpret and synthesize the data generated for finding suitable solutions.
PO 4 Graduate would be able to simulate or model complex computing systems by
selecting and using modern IT tools & techniques.
PO 5 Graduate would be able to understand the impact of professional engineering
solutions in societal, cultural, safety standards, legal issues, environment and
various other sustainability issues with due adherence to ethical principles and
ethics.
PO 6 Graduate would be able to exercise various management principles at individual
as well as in a team level and should be able to effectively communicate their
deliverables to engineering community.
PO 7 Graduate would be able to recognize the need of progressive benefits of lifelong
learning in order to adapt to the technical changes.

COMPILER DESIGN Page 5


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

PROGRAMME OUTCOMES OF COMPUTER SCIENCE & ENGINEERING


PO 1 Application Knowledge : Apply the knowledge of mathematics, science and an
software application technology to the solution of complex problems.
PO 2 Problem Analysis : Identify, formulate, review research literature, and analyze
complex problems reaching substantiated conclusions using first principles of
mathematics and natural sciences.
PO 3 Design/development of Solutions :Design solutions for complex problems and
design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and thecultural, societal,
and environmental considerations.
PO 4 Conduct Investigations of Complex Problems : Use research - based knowledge
and research methods including design of experiments, analysisand interpretation
of data, and synthesis of the information to provide valid conclusions.
PO 5 Modern Tool Usage : Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
PO 6 The Developer 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 practice.
PO 7 Environment and Sustainability :Understand the impact of the professional
problem solutions in societal and environmental contexts, and demonstratethe
knowledge of, and need for sustainable development.
PO 8 Ethics : Apply ethical principles and commit to professional ethics and
responsibilities and norms of the practice.
PO 9 Individual and Team Work : Function effectively as an individual, and asa member
or leader in diverse teams, and in multidisciplinary settings.
PO10 Communication :Communicate effectively on complex problematic activities with
the community and with society at large, such as, being ableto comprehend and
write effective reports and design documentation, make effective presentations,
and give and receive clear instructions.
PO 11 Project Management and Finance : Demonstrate knowledge and under standing of
the and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multi disciplinary environments.
PO 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 Page 6


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

OBJECTIVE

This laboratory course is intended to make the students experiment


on the basic techniques of compiler construction and tools that
caused to perform syntax-directed translation of a high-level
programming language into an executable code. Students will design
and implement language processors in C by using tools to automate
parts of the implementation process. This will provide deeper
insights into the more advanced semantics aspects of programming
languages, code generation, machine independent optimizations,
dynamic memory allocation, and object orientation.

COURSE OUTCOMES

Upon the completion of Compiler Design practical course,


thestudent will be able to :
CO1. Understand the working of lex and Yacc compiler for
debuggingof programs.

CO2. Understand and define the role of lexical analyzer, use of


regular expression and transition diagrams.

CO3. Understand and use Context free grammar, and parse


treeconstruction.

CO4. Learn & use the new tools and technologies used for
designinga compiler.
CO5. Develop program for solving parser problems.

CO6. Learn how to write programs that execute faster.

COMPILER DESIGN Page 7


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

CONTENTS

EXP. NO. NAME OF THE EXPERIMENT PAGE NO


Introduction to JFLAP and JFLAP Manual. 10 13
01 Using JFLAP, Create a NFA from a given expression. 14 16
Convert NFA to DFA and minimized the DFA.
02 Design a lexical analyzer for given language and the 17 23
lexical analyzer should ignore redundant spaces,
tabs and new lines. It should also ignore comments.
Although the syntax specification states that
identifiers can be arbitrarily long, you may restrict
the length to some
reasonable value. Simulate the same in C language.
03 Read regular expression and convert it to postfix 24 30
form to check its validity. Scan a string and check it
for the givenregular expression.

04 Write a C program to recognize strings under ‘a’, 31 32


‘a*b+’, ‘abb’..
05 Write a C program to test whether a given 33 34
identifier isvalid or not.
06 Study of LEX and YACC Tool 35 42

07 Implement the lexical analyzer using JLex, flex or other 43 47


lexical analyzer generating tools.
08 Write a C program to simulate lexical analyzer for 48 49
validating operators
09 Using JFLAP to Find out the FIRST and FOLLOW function 50 58
of all the Variables from a Context Free Grammar.
10 Using JFLAP create LL(1) parsing table for a given CFG 59 62
and simulate the LL(1) parsing.
11 Using JFLAP create SLR(1) parsing table for a given CFG 63 65
and simulate the SLR(1) parsing .

COMPILER DESIGN Page 8


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

RULES AND REGULATIONS


1. Each student must maintain a logbook for each laboratory module, recording their
individual work and results for each exercise. The logbook is the primary record of
the student’s work, and is used for the assessment of the module.
2. For most lab modules you will be assigned to a lab group . Each group typically
consists of five students, who are required to complete each exercise as a
team. The detailed organisation of work within a group should be agreed upon by
the group members themselves. Every student is required to be familiar with all
aspects of each exercise, toparticipate actively in carrying it out, and to maintain
his / her own individual logbook. Any disagreements over the organisation of
group work should be referred to the demonstrator.
3. It is essential for the student to study the lab manual, in detail, in advance of each
experiment.
4. Students are required to attend all scheduled laboratory sessions. If you fail to
attend a particular session, then you should contact theconcerned
demonstrator (in advance,
if possible), providing appropriate documentary evidence (medical certificate
etc.). You willhave to complete the exercise at a later date (usually outside the
normal laboratory time). Itis the responsibility of the student to contact the
demonstrator in such circumstances, and then complete the rescheduled exercise.
Neither the demonstrators nor the academic supervisors are responsible for
contacting you . Missing even a single session without explanation will normally
mean that you will be deemed to have failed in the entire laboratory module,
which means you will be required either to repeat the year, or to withdraw from
the programme entirely.

5. Come prepared with your lead kits, tools, pens, pencils, scales and calculator.
6. Treat the equipment with care and respect, and use only for the purpose intended.
Never (for example) use the mains lead or the signal leads to lift, pull or
disconnect any equipment.
7. The safety and productivity of laboratory work depends on the behaviour of all
students. It is impossible to make rules for every eventuality; but you should
display common sense, exercise care, and conduct yourself in a responsible
manner at all times in the lab.
8. Students are 100% financially responsible for loss or damage to equipment assigned
them.

COMPILER DESIGN Page 9


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

INTRODUCTION
JFLAP is software for experimenting with formal languages topics including nondeterministic
finiteautomata, nondeterministic pushdown automata, multi-tape Turing machines, several
types of grammars, parsing, and L-systems. In addition to constructing and testing examples for
these, JFLAP allows one to experiment with construction proofs from one form to another, such
as converting an NFA to a DFA to a minimal state DFA to a regular expression or regular
grammar.

JFLAP is a package of graphical tools which can be used as an aid in learning the basic concepts
of Formal Languages and Automata Theory.

OBJECTIVE:
Introduction to JFLAP.

JFLAP
JFLAP is software for experimenting with formal languages topics including nondeterministic
finiteautomata, nondeterministic pushdown automata, multi-tape Turing machines, several
types of grammars, parsing, and L-systems. In addition to constructing and testing examples for
these, JFLAP allows one to experiment with construction proofs from one form to another, such
as converting an NFA to a DFA to a minimal state DFA to a regular expression or regular
grammar.

Running JFLAP
Download JFLAP and the files referenced in this book from www.jflap. org to get started. JFLAP is
written in Java to allow it to run on a range of platforms. JFLAP requires that your computer have
Java SE 1.4 or later installed. JFLAP works with Java 1.5. For the latest version, visit http://
java.sun.com/ . Mac OS X’s latest Java release, if not already preinstalled, is available from http:/
/www.apple. com/j ava/, or from Software Update. With Java SE 1.4 or later installed on your
computer, you may attempt to run JFLAP. JFLAP is distributed as an executable .jar (Java ARchive)
file. JFLAP may be run as either an application or applet. The following table lists how to run the
JFLAP. jar executable .jar as an application on your platform of choice.

Windows Double click on JFLAP. jar; the file will appear as JFLAP if suffix
hidingis on.

Unix & Linux From a shell with the JFLAP. jar file m the current directory, enter
thecommand java -jar JFLAP. jar.

Mac OS X The Windows and Unix directions will work on a Mac.

COMPILER DESIGN Page 10


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

JFLAP Interface Primer


We cover universal elements of the JFLAP interface here. To begin, start JFLAP. When JFLAP
has finished loading, a window will appear similar to that shown in Figure 1. This window offers a
choice of major structures if you wish to create a new structure; alternatively, the File menu
allows you to open an existing saved structure or quit JFLAP. Throughout this book we shall review
the creation of these structures. However, right now we are going to open a JFLAP saved file of an
existing finite automaton (FA) . From the File menu, choose Open. JFLAP allows users to save and
open files that contain a single structure. Select and open the file ex0.1a. A new window will
appear with an FA. We refer to all the things you can do to a structure as operators. (It is not
necessary to understand what the operators are doing at this point; our purpose is to describe
JFLAP’s interface.)

Figure 1: The window that appears when you start JFLAP


Operators are typically activated through the menu items. Choose the menu item Test: High light
Nondeterminism. (This activates an operator that shades nondeterministic states in an automaton,
in this case q0 and q1) .Next choose the menu item Test: High light ë-transition. This activates an
operator that highlights ë-transitions in an automaton; in this case the arc labeled ë).We chose
these two operators because they require no intervention from the user.

Figure 2: An illustration of the window for a structure, with three tabs active.

COMPILER DESIGN Page 11


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

The window for a structure consists of a menu bar that contains operators you may apply to
thestructure and a tabbed interface below the menu bar. Note that JFLAP keeps everything
related toa structure in a single window, and uses tabs to manage multiple operators
active at the sametime. The results of the two operators we invoked are displayed in tabs,
so there are currently three tabs: Editor, Nondeterminism, and A-Transitions. In Figure 2,
the Nondeterminism tab isselected, indicating that the interface for the “highlight
nondeterminism” operator is currently active and displayed. To switch to another operator,
click on its tab. (Note that you cannot switchto the Editor tab at this time. This is because the
other two currently active operators depend onthe automaton not changing .)We will now
remove the Nondeterminism and ë -Transitions tabs.To get rid of a tab, select the menu
item File : Dismiss Tab. This will remove the currently activetab. When it is gone, remove the
other tab as well . (JFLAP prevents removal of the Editor tab.)As a last step, peruse the
contents of the File menu. Use New when you want to create a new structure . When New is
selected JFLAP will display. the window shown in Figure 1 that allows youto choose a type of
structure to create. The Open, Save, and Save As menu items allow you to readand write
structures to files like any other application that deals with documents. The Close itemwill
close the window of the structure. The Print item will print the currently active tab. Quit will
stop JFLAP entirely.

COMPILER DESIGN Page 12


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

COMPILER DESIGN Page 13


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT- 01
(Using JFLAP, Create a NFA from a given expression. Convert NFA to DFA
and minimized the DFA.)

AIM OF THE EXPERIMENT :- Using JFLAP, Create a NFA from a given expression. Convert
NFA to DFA and minimized theDFA.

Creating a Regular Expression


To create a new regular expression, start JFLAP and click the Regular Expression option from
the menu, as shown below:

One should eventually see a blank screen that looks like the screen b

COMPILER DESIGN Page 14


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

Now one can enter whatever expression that one wishes. Note that there should be no blanks
in the regular expression, as any blank will be processed as a symbol of Ó. One such expression
is in the screen below. One can either type it in directly, or load the file regExprToNfa.jff.

Converting to a NFA
After typing in an expression, there is nothing else that can be done in this editor window
besides converting it to an NFA, so let’s proceed to that. Click on the “Convert ’! Convert to
NFA” menu option. If one uses the example provided earlier, this screen should come up (after
resizing the window a little).

COMPILER DESIGN Page 15


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

Now, click on the “(D)e-expressionify Transition” button (third from the left, to the immediate
left of the “Do Step” button). Then, click on the transition from “q0” to “q1”. You should now
see, perhaps with a little resizing, a screen like this...

Assignment Questions:

Q1. Define JFLAP? How to run a JFLAP program in windows operating system?

Q2. What is a regular Grammar and context-free grammar?

Q3. Define NFA AND DFA?

Q4. Design an NFA with ∑ = {0, 1} in which double '1' is followed by double '0'.

Q5. Draw a deterministic and non-deterministic finite automata which accept a string
containing “the” anywhere in a string of {a-z}, e.g., “there” but not “those”.

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:

COMPILER DESIGN Page 16


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT- 02
(Design a lexical analyzer for given language)

AIM OF THE EXPERIMENT:


Design a lexical analyzer for given language and the lexical analyzer should ignore
redundant spaces, tabs and new lines. It should also ignore comments. Although the syntax
specification states that identifiers can be arbitrarily long, you may restrict the length to
some reasonable value. Simulate the same in C language.

RESOURCE:
Linux, Ubuntu / gcc compiler

PROGRAM LOGIC:
1. Read the input Expression
2. Check whether input is alphabet or digits then store it as identifier
3. If the input is is operator store it as symbol
4. Check the input for keywords

PROCEDURE:
Go to terminal ,Open vi editor ,vi filename.c , gcc filename.c , ./a.out

PROGRAM:

#include
#include
#include
void keyword(char str[10])
{
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||
strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||strcmp("double",str)==0
||

strcmp("static",str)==0||strcmp("switch",str)==0||strcmp("case",str)==0)
printf("\n%s is a keyword",str);
else
printf("\n%s is an identifier",str);
}

COMPILER DESIGN Page 17


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

main()
{
FILE *f1,*f2,*f3;
char c,str[10],st1[10];
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;
printf("\nEnter the c program");/*gets(st1);*/
f1=fopen("input","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input","r");
f2=fopen("identifier","w");
f3=fopen("specialchar","w");
while((c=getc(f1))!=EOF){
if(isdigit(c))
{
tokenvalue=c-'0';
c=getc(f1);
while(isdigit(c)){
tokenvalue*=10+c-'0';
c=getc(f1);
}
num[i++]=tokenvalue;
ungetc(c,f1);
}
else if(isalpha(c))
{
putc(c,f2);
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
putc(c,f2);
c=getc(f1);
}
putc(' ',f2);
ungetc(c,f1);
}
else if(c==' '||c=='\t')
printf(" ");
else
if(c=='\n')
lineno++;

COMPILER DESIGN Page 18


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\nThe no's in the program are");
for(j=0;j<i;j++)< span="" style="box-sizing: border-box;">
printf("%d",num[j]);
printf("\n");
f2=fopen("identifier","r");
k=0;
printf("The keywords and identifiersare:");
while((c=getc(f2))!=EOF){
if(c!=' ')
str[k++]=c;
else
{
str[k]='\0';
keyword(str);
k=0;
}
}
fclose(f2);
f3=fopen("specialchar","r");
printf("\nSpecial characters are");
while((c=getc(f3))!=EOF)
printf("%c",c);
printf("\n");
fclose(f3);
printf("Total no. of lines are:%d",lineno);
}</i;j++)<>

COMPILER DESIGN Page 19


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

Input:
Enter Program $ for termination:
{
int a[3],t1,t2;
t1=2; a[0]=1; a[1]=2; a[t1]=3;
t2=-(a[2]+t1*6)/(a[2]-t1);
if t2>5 then
print(t2);
else {
int t3;
t3=99;
t2=-25;
print(-t1+t2*t3); /* this is a comment on 2 lines */
} endif
}
(cntrl+z)

Output:
Variables : a[3] t1 t2 t3
Operator : - + * / >
Constants : 2 1 3 6 5 99 -25
Keywords : int if then else endif
Special Symbols : , ; ( ) { }
Comments : this is a comment on 2 lines

COMPILER DESIGN Page 20


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

CONCLUSION:
The students were able to find out the lexical analyzer errors and find out the various
types of keywords and literals used in any given program.

QUESTIONS & ANSWERS


1. What is token?

2. What is lexeme?

3. What is the difference between token and lexeme?

4. Define phase and pass?

5. What is the difference between phase and pass?

COMPILER DESIGN Page 21


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

6. What is the difference between compiler and interpreter?

7. What is lexical analyzer?

8. Which compiler is used for lexical analyzer?

9. What is the output of Lexical analyzer?

10. What is LEX source Program?

COMPILER DESIGN Page 22


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

LAB ASSIGNMENT FOR PRACTICE

LAB ASSIGNMENT

1. Write a program to recognize identifiers.


2. Write a program to recognize constants.
3. Write a program to recognize keywords and identifiers.
4. Write a program to ignore the comments in the given input source program.

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:

COMPILER DESIGN Page 23


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT- 03
(Read regular expression and convert it to postfix form to check its validity. Scan
a string and check it for the given regular expression)

AIM OF THE EXPERIMENT: -


Read regular expression and convert it to postfix form to check its validity. Scan a
stringand check it for the given regular expression

RESOURCE : -
LINUX, Ubuntu/gcc compiler

PROGRAM LOGIC :-
1. Read the input expression
2. Convert to postfix(operand1, operand2, operator)
3. Take a string of specific length
4. By applying loop check whether the string is valid or not

PROGRAM : -
#include <stdio.h>
#include <string.h>
#define MATCH printf("\nThe Text Matches The Regular Expression");
#define NOTMATCH printf("\nThe Text Doesn't match the Regular Expression");
char reg[20], text[20];
int main()
{
int i, rlen, tlen, f = 0;
char ans;

do {
printf("\nEnter the Regular Expression\n");
scanf(" %[^\n]s", reg);
for (rlen = 0; reg[rlen] != '\0';rlen++);
printf("\nEnter the text\n");
scanf(" %[^\n]s", text);
for (tlen = 0;text[tlen] != '\0' ; tlen++);
if (reg[0] == '*')
{

COMPILER DESIGN Page 24


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

printf("\nInvalid regular expression");


}
if ((reg[0] >= 65 && reg[0] <= 90) || (reg[0] >= 97 && reg[0] <=122))
{
if (reg[0] == text [0])
{
switch (reg[1])
{
case '.' :
switch (reg[2])
{
case '*':
if (tlen != 1)
{
if (reg[3] == text[tlen-1])
{
MATCH;
}
else
{
NOTMATCH;
}
}
else
{
NOTMATCH;
}
break;
case '+':
if (text[1] != reg[3])
{
if (reg[3] == text[tlen - 1])
{
MATCH;
}
else
{
NOTMATCH;
}
}
break;
case '?':
if (text[1] == reg[3] || text[2] == reg[3])

COMPILER DESIGN Page 25


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

{
if (text[1] == reg[3] || text[2] == reg[3])
{
MATCH;
}
else
{
NOTMATCH;
}
}
else
{
NOTMATCH;
}
break;
}
break;
case '*':
if (reg[rlen-1] == text[tlen-1])
{
for (i = 0;i <= tlen-2;i++)
{
if(text[i] == reg[0])
{
f = 1;
}
else
{
f = 0;
}
}
if ( f == 1)
{
MATCH;
}
else
{
NOTMATCH;
}
}
else
{
NOTMATCH;

COMPILER DESIGN Page 26


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

}
break;
case '+' :
if (tlen <= 2)
{
NOTMATCH;
}
else if (reg[rlen-1] == text[tlen-1])
{
for (i = 0;i < tlen-2;i++)
{
if (text[i] == reg[0])
{
f = 1;
}
else
{
f = 0;
}
}

if (f == 1)
{
MATCH;
}
else
{
NOTMATCH;
}
}
break;
case '?':
if (reg[rlen -1] == text[tlen-1])
{
MATCH;
}
else
{
NOTMATCH;
}
break;
}

COMPILER DESIGN Page 27


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

}
else
printf("Does not match");
}
/*
*If Regular Expression starts with '^'
*/
else if (reg[0] == '^')
{
if (reg[1] == text[0])
{
MATCH;
}
else
{
NOTMATCH;
}
}
/*
*If Regular Expression Ends with '$'
*/
else if (reg[rlen-1] == '$')
{
if (reg[rlen-2] == text[rlen-1])
{
MATCH;
}
else
{
NOTMATCH;
}
}
else
printf("Not Implemented");
printf("\nDo you want to continue?(Y/N)");
scanf(" %c", &ans);
} while (ans == 'Y' || ans == 'y');
}

COMPILER DESIGN Page 28


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

OUTPUT:

Enter the Regular Expression


C.*g

Enter the text


Cprogramming

The Text Matches The Regular Expression


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

Enter the Regular Expression


C*g

Enter the text


Cprogramming
The Text Doesn't match the Regular Expression
Do you want to continue?(Y/N)y

Enter the Regular Expression


C?.*g

Enter the text


Cprogramming

The Text Matches The Regular Expression


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

Enter the Regular Expression


C.?g

Enter the text


Cprogramming

The Text Doesn't match the Regular Expression


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

Enter the Regular Expression


C.+g

COMPILER DESIGN Page 29


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

Enter the text


Cprogramming

The Text Matches The Regular Expression


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

Enter the Regular Expression


C+g

Enter the text


Cprogramming

The Text Doesn't match the Regular Expression


Do you want to continue?(Y/N)y
Enter the Regular Expression
^C.*
Enter the text
Cprogramming
The Text Matches The Regular Expression
Do you want to continue?(Y/N)y

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:

COMPILER DESIGN Page 30


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT – 04
(Write a C program to recognize strings under ‘a’,‘a*b+’, ‘abb’..)

AIM OF THE EXPERIMENT:


Write a C program to recognize strings under ‘a’,‘a*b+’, ‘abb’..

RESOURCE:
Linux, Ubantu / gcc compiler

PROGRAM LOGIC:

#include<stdio.h>
#include<stdlib.h>
void main()
{char s[20],c;
int state=0,i=0;
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=5;
else state=6;
break;
case 1: c=s[i++];
if(c=='a') state=2;
else if (c=='b') state=3;
else state=6;
break;
case 2: c=s[i++];
if(c=='a‘) state=2;
else if(c==‘b‘) state=5;
else state=6;
break;
case 3: c=s[i++];
if (c=='b') state=4;
else state=6;
break;

COMPILER DESIGN Page 31


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

case 4: c=s[i++];
if (c=='b') state=5;
else state=6;
break;
case 5: c=s[i++];
if (c=='b') state=5;
else state=6;
break;
case 6: printf("\n %s is not recognised.",s);
exit(0); }}

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:

COMPILER DESIGN Page 32


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT – 05
(Write a C program to test whether a given identifier is valid or not)

AIM OF THE EXPERIMENT:


Write a C program to test whether a given identifier is valid or not.

RESOURCE:
Linux, Ubantu / gcc compiler

PROGRAM LOGIC:
Read the given input string.
Check the initial character of the string is numerical or any special character except ‘_’
then print it is not a valid identifier.
Otherwise print it as valid identifier if remaining characters of string doesn’t contains any
special characters except ‘_’.

PROCEDURE:
Go to terminal ,Open vi editor ,vi filename.c , gcc filename.c , ./a.out

PROGRAM:
#include<stdio.h>

#include<stdlib.h>
#include<string.h>
int main()
{
char string[50];
int count=0,i;
printf("Enter the String: ");
gets(string);
//int len=strlen(string);
//printf("length:%d",len);
if((string[0]>='a'&&string[0]<='z') || (string[0]>='A'&&string[0]<='Z') || (string[0]=='_') ||
(string[0]=='$'))
{
for(i=1;i<=strlen(string);i++)
{
if((string[i]>='a'&& string[i]<='z') || (string[i]>='A' && string[i]<='Z') ||
(string[i]>='0'&& string[i]<='9') || (string[i]=='_'))
{
count++;

COMPILER DESIGN Page 33


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

}
}
}
if(count==(strlen(string)-1))
{
printf("Input string is a valid identifier");
}
else
{
printf("Input string is not a valid identifier");
}
return 0;
}

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:

COMPILER DESIGN Page 34


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT – 06
(Study of LEX and YACC Tool)
AIM OF THE EXPERIMENT: -
Study the LEX and YACC tool and 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.].

DESCRIPTION:-

LEX-A Lexical analyzer generator:


Lex is a computer program that generates lexical analyzers ("scanners" or "lexers").Lex
is commonly used with the yacc parser generator.

Lex reads an input stream specifying the lexical analyzer and outputs source code
implementing the lexer in the C programming language

1. A lexer or scanner is used to perform lexical analysis, or the breaking up of an


input stream into meaningful units, or tokens.
2. For example, consider breaking a text file up into individual words.
3. Lex: a tool for automatically generating a lexer or scanner given a lex specification (.l
file).

Structure of a Lex file

The structure of a Lex file is intentionally similar to that of a yacc file; files are divided
up into threesections, separated by lines that contain only two percent signs, as
follows:

Definition section:
%%
Rules section:
%%
C code section:
<statements>

COMPILER DESIGN Page 35


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

 The definition section is the place to define macros and to import header
files written in C. It is also possible to write any C code here, which will be
copied verbatim into the generated source file.
 The rules section is the most important section; it associates patterns
with C statements. Patterns are simply regular expressions. When the
lexer sees some text in the input matching a given pattern, it executes the
associated C code. This is the basis of how Lex operates.
 The C code section contains C statements and functions that are copied
verbatim to thegenerated source file. These statements presumably
contain code called by the rules in the rules section. In large programs it is
more convenient to place this code in a separate file and link it in at
compile time.

Description:-
The lex command reads File or standard input, generates a C language program, and writes
it to a file named lex.yy.c. This file, lex.yy.c, is a compilable C language program. A C++
compiler also can compile the output of the lex command. The -C flag renames the output
file to lex.yy.C for the C++ compiler. The C++ program generated by the lex command can
use either STDIO or
IOSTREAMS. If the cpp define _CPP_IOSTREAMS is true during a C++ compilation, the
program uses IOSTREAMS for all I/O. Otherwise, STDIO is used.

The lex command uses rules and actions contained in File to generate a program,
lex.yy.c,which can be compiled with the cc command. The compiled lex.yy.c can then
receive input, break the input into the logical pieces defined by the rules in File, and run
program fragments contained in the actions in File.

The generated program is a C language function called yylex. The lex command stores the
yylex function in a file named lex.yy.c. You can use the yylex function alone to recognize
simple one-word input, or you can use it with other C language programs to perform more
difficult input analysis functions. For example, you can use the lex command to generate a
program that simplifies an input stream before sending it to a parser program generated by
the yacc command.
The yylex function analyzes the input stream using a program structure called a finite
state machine. This structure allows the program to exist in only one state (or condition)
at a time. There is a finite number of states allowed. The rules in File determine how the

COMPILER DESIGN Page 36


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

program moves from one state to another. If you do not specify a File, the lex command
reads standard input. It treats multiple files as a single file.
Note: Since the lex command uses fixed names for intermediate and output files, you can
have only oneprogram generated by lex in a given directory.

Regular Expression Basics


. : matches any single character except \n
* : matches 0 or more instances of the preceding regular expression
+ : matches 1 or more instances of the preceding regular expression
? : matches 0 or 1 of the preceding regular expression
| : matches the preceding or following regular
expression[ ] : defines a character class
() : groups enclosed regular expression into a new regular expression
“…”: matches everything within the “ “ literally

Special Functions
• yytext
– where text matched most recently is stored
• yyleng
– number of characters in text most recently matched
• yylval
– associated value of current token
• yymore()
– append next string matched to current contents of yytext
• yyless(n)
– remove from yytext all but the first n characters
• unput(c)
– return character c to input stream
• yywrap()
– may be replaced by user
– The yywrap method is called by the lexical analyser whenever it inputs an EOF as the
first character when trying to match a regular expression

Files
y.output--Contains a readable description of the parsing tables and a report on conflicts
generated by grammar ambiguities.
y.tab.c ---- Contains an output file.
y.tab.h ----- Contains definitions for token names.
yacc.tmp ---- Temporary file.

COMPILER DESIGN Page 37


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

yacc.debug ---Temporary file.


yacc.acts ---- Temporary file.
/usr/ccs/lib/yaccpar - Contains parser prototype for C programs.
/usr/ccs/lib/liby.a--- Contains a run-time library.

YACC: Yet Another Compiler-Compiler


Yacc is written in portable C. The class of specifications accepted is a very general
one:LALR(1) grammars with disambiguating rules.

Basic specification
Names refer to either tokens or non-terminal symbols. Yacc requires tokens names to be
declared as such. In addition, for reasons discussed in section 3, it is often desirable to
include the lexical analyzer as part of the specification file, I may be useful to include other
programs as well. Thus, the sections are separated by double percent “%%” marks. (the
percent‟%‟ is generally used in yacc specifications as an escape character). In other words,
a full specification file looks like.
In other words a full specification file
looks likeDeclarations
%%
Rules
%%
Programs
The declaration section may be empty. More over if the programs section is omitted, the
second %% mark may be omitted also thus the smallest legal yacc specification is
%%
Rules
Blanks, tabs and newlines are ignored except that they may not appear in
names or multi-character reserved symbols. Comments may appear wherever legal,
they are enclosed in /*….*/ as in C and PL/l
The rules section is made up of one or more grammar rule has
the form: A:BODY:

COMPILER DESIGN Page 38


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

USING THE LEX PROGRAM WITH THE YACC PROGRAM

The Lex program recognizes only extended regular expressions and formats them into
character packages called tokens, as specified by the input file. When using the Lex
program to make a lexical analyzer for a parser, the lexical analyzer (created from the Lex
command) partitions the input stream. The parser(from the yacc command) assigns
structure to the resulting pieces. You can also use other programs along with programs

generated by Lex or yacc commands.

A token is the smallest independent unit of meaning as defined by either the parser or
the lexical analyzer. A token can contain data, a language keyword, an identifier or the
parts of language syntax.
The yacc program looks for a lexical analyzer subroutine named yylex, which is generated
by the lex command. Normally the default main program in the Lex library calls the yylex
subroutines. However if the yacc command is loaded and its main program is used , yacc
calls the yylex subroutines. In this case each Lex rule should end with:
return (token);

Where the appropriate token value is returned


The yacc command assigns an integer value to each token defined in the yacc grammar
file through a # define preprocessor statement.
The lexical analyzer must have access to these macros to return the tokens to the parser.
Use the yacc –d option to create a y.tab.h file and include the y.tab.h file in the Lex
specification file by adding the following lines to the definition section of the Lex
specification file:
%{
#include “y.tab.h”
%}

COMPILER DESIGN Page 39


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

Alternatively you can include the lex.yy.c file the yacc output file by adding the following
lines after thesecond %% (percent sign, percent sign) delimiter in the yacc grammar file:
#include”lex.yy.c”
The yacc library should be loaded before the Lex library to get a main program that
invokes the yacc parser. You can generate Lex and yacc programs in either order.

Evaluating Arithmetic Expression using different Operators (Calculator)

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

COMPILER DESIGN Page 40


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

[\t] ;

%%
int yywrap(void)
{
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 Page 41


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:
COMPILER DESIGN Page 42
DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT – 07
(Implement the lexical analyzer using JLex, flex or other lexical analyzer
generating tools.)

AIM OF THE EXPERIMENT: -


Implement the lexical analyzer using JLex, flex or other lexical analyzer generating
tools.

RESOURCE:
Linux using Putty

PROGRAM LOGIC:
Read the input string.
Check whether the string is identifier/ keyword /symbol by using the rules of
identifier and keywords using LEX Tool

PROCEDURE: Go to terminal .Open vi editor ,Lex lex.l , cc lex.yy.c , ./a.out

PROGRAM:

%{

/* program to recognize a c program */

int COMMENT=0;

%}

identifier [a-zA-Z][a-zA-Z0-9]*

%%

#.* { printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}

int |float |char |double |while |for |do |if |break |continue |void |switch |case |long |struct
|const |typedef |return

|else |goto {printf("\n\t%s is a KEYWORD",yytext);}

"/*" {COMMENT = 1;}

COMPILER DESIGN Page 43


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

/*{printf("\n\n\t%s is a COMMENT\n",yytext);}*/

"*/" {COMMENT = 0;}

/* printf("\n\n\t%s is a COMMENT\n",yytext);}*/

{identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s",yytext);}

{ {if(!COMMENT) printf("\n BLOCK BEGINS");} } {if(!COMMENT) printf("\n BLOCK ENDS");}

{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);} ".*\" {if(!COMMENT)


printf("\n\t%s is a STRING",yytext);}

[0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER",yytext);} {if(!COMMENT)


printf("\n\t");ECHO;printf("\n");}

( ECHO;

{if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}

<= |>= |< |== |> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}

%%

int main(int argc,char **argv)

if (argc > 1)

FILE *file;

file = fopen(argv[1],"r"); if(!file)

printf("could not open %s \n",argv[1]); exit(0);

COMPILER DESIGN Page 44


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

yyin = file;

}
yylex();

printf("\n\n");

return 0;

int yywrap()

return 0;

Input

$vi var.c

#include

main()

int a,b;

COMPILER DESIGN Page 45


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

Output

$lex lex.l

$cc lex.yy.c

$./a.out var.c

#include is a PREPROCESSOR DIRECTIVE

FUNCTION

main (

BLOCK BEGINS

int is a KEYWORD

a IDENTIFIER

b IDENTIFIER

BLOCK ENDS

COMPILER DESIGN Page 46


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

QUESTIONS & ANSWERS

1. What is Jlex?

2. What is Flex?

3. What is lexical analyzer generator?

4. What is the input for LEX Compiler?

5. What is the output of LEX compiler?

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:

COMPILER DESIGN Page 47


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT -08
(Write a C program to simulate lexical analyzer for validating operators.)

AIM OF THE EXPERIMENT OF THE EXPERIMENT:


Write a C program to simulate lexical analyzer for validating operators.

RESOURCE:
Linux, ubuntu / gcc compiler

PROGRAM LOGIC:
Read the given input.
If the given input matches with any operator
symbol, Then display in terms of words of the
particular symbol.Else print not a operator.
PROCEDURE:
Go to terminal, Open vi editor, vi filename.c , gcc filename.c , ./a.out

PROGRAM
#include <stdio.h>
#include <string.h>
int main ()
{
char arithmetic[5]={'+','-','*','/','%'};
char relational[4]={'<','>','!','='};
char bitwise[5]={'&','^','~','|'};
char str[2]={' ',' '};
printf ("Enter value to be identified: ");
scanf ("%s",&str);
int i;
if(((str[0]=='&' || str[0]=='|') && str[0]==str[1]) || (str[0]=='!' && str[1]=='\0'))
{
printf("\nIt is Logical operator");
}
for(i=0;i<4;i++)
{
if(str[0]==relational[i]&&(str[1]=='='||str[1]=='\0'))
{

COMPILER DESIGN Page 48


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

printf("\n It is releational Operator"); break;


} }
for(i=0;i<4;i++)
{
if((str[0]==bitwise[i] && str[1]=='\0') || ((str[0]=='<' || str[0]=='>') && str[1]==str[0]))
{
printf("\n It is Bitwise Operator"); break;
} }
if(str[0]=='?' && str[1]==':')
printf("\nIt is ternary operator");
for(i=0;i<5;i++)
{
if((str[0]=='+' || str[0]=='-') && str[0]==str[1])
{
printf("\nIt is unary operator"); break;
}
else if((str[0]==arithmetic[i] && str[1]=='=') || (str[0]=='=' && str[1]==' '))
{
printf("\nIt is Assignment operator"); break;
}
else if(str[0]==arithmetic[i] && str[1]=='\0')
{
printf("\nIt is arithmetic operator"); break;

} }
return 0;
INPUT & OUTPUT:

Input Enter any operator: *


Output Multiplication

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:
Date:

COMPILER DESIGN Page 49


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT -09
(To find the FIRST and FOLLOW sets from a given grammar.)
AIM OF THE EXPERIMENT:-
To find the FIRST and FOLLOW sets from a given grammar.
PROCEDURE:-

We will begin by loading the grammar. You can either enter the grammar (shown below) or
loadthe file grammar ToLL.jff.

Now click on Input and then Build LL (1) Parse Table. Your window should look like this
afterentering LL (1) Parse Table mode.

COMPILER DESIGN Page 50


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

PROGRAM:
#include<stdio.h>
#include<ctype.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], "E=TR");
strcpy(production[1], "R=+TR");

COMPILER DESIGN Page 51


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

strcpy(production[2], "R=#");
strcpy(production[3], "T=FY");
strcpy(production[4], "Y=*FY");
strcpy(production[5], "Y=#");
strcpy(production[6], "F=(E)");
strcpy(production[7], "F=i");

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;

COMPILER DESIGN Page 52


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

// 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, ", first[i]);
calc_first[point1][point2++] = first[i];
}
}
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

COMPILER DESIGN Page 53


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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])
{
chk = 1;
break;
}
}
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;

COMPILER DESIGN Page 54


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

// 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(!(isupper(c))) {
first[n++] = c;
}
for(j = 0; j < count; j++)
{
if(production[j][0] == c)
{

COMPILER DESIGN Page 55


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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)

COMPILER DESIGN Page 56


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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
{
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++;
}
}
}

COMPILER DESIGN Page 57


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

Output :
First(E)= { (, i, }
First(R)= { +, #, }
First(T)= { (, i, }
First(Y)= { *, #, }
First(F)= { (, i, }

-----------------------------------------------

Follow(E) = { $, ), }
Follow(R) = { $, ), }
Follow(T) = { +, $, ), }
Follow(Y) = { +, $, ), }
Follow(F) = { *, +, $, ), }

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:
COMPILER DESIGN Page 58
DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT – 10
(To simulate LL(1) parsing using JFLAP)

AIM OF THE EXPERIMENT:-


To simulate LL(1) parsing using JFLAP
RESOURSE:
Linux /Windows
PROCEDURE:
Definition
The type of LL parsing in JFLAP is LL(1) Parsing. The first L means the input string is processed
from left to right. The second L means the derivation will be a leftmost derivation (the leftmost
variable is replaced at each step). 1 means that one symbol in the input string is used to help
guide the parse.
How to Build LL(1) Parse Table
First the grammar is entered or the file grammar is loaded ToLL.jff.

Now click on Input and then Build LL(1) Parse Table. Your window should look like this
after entering LL(1) Parse Table mode.

COMPILER DESIGN Page 59


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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

COMPILER DESIGN Page 60


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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

COMPILER DESIGN Page 61


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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

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

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:

COMPILER DESIGN Page 62


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

EXPERIMENT-11
(To simulate SLR(1) parsing using JFLAP)

AIM OF THE EXPERIMENT: -


To simulate SLR(1) parsing using JFLAP

RESOURSE:
Linux /Windows

PROCEDURE:
Definition: The type of LR parsing in JFLAP is SLR(1) Parsing.
S stands for simple LR.

L means the input string is processed from left to right, as in LL(1) parsing.

R means the derivation will be a rightmost derivation (the rightmost variable is


replaced at each step).

1 means that one symbol in the input string is used to help guide the parse.

How to Build SLR(1) Parse Table


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

COMPILER DESIGN Page 63


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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

COMPILER DESIGN Page 64


DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING

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

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

Signature of the faculty: Signature of the student:

Date: Registration Number:

Branch:

Date:

COMPILER DESIGN Page 65

You might also like