Compiler Design Lab Manula
Compiler Design Lab Manula
LABORATORY MANUAL
ON
COMPILER DESIGN
Name……………………………………………………………………………………...
Registration Number-………………………………………………………………….
Branch-…………………………………………………….……………………………
Session-…………………………………………………………………………………...
LABORATORY MANUAL
ON
COMPILER DESIGN
Compiled by:
AMBUJA KUMAR PARIDA
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.
Vision
Mission
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
agencies
Programme Outcome
OBJECTIVE
COURSE OUTCOMES
CO4. Learn & use the new tools and technologies used for
designinga compiler.
CO5. Develop program for solving parser problems.
CONTENTS
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.
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.
Figure 2: An illustration of the window for a structure, with three tabs active.
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.
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.
One should eventually see a blank screen that looks like the screen b
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).
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?
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”.
Branch:
Date:
EXPERIMENT- 02
(Design a lexical analyzer for given 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);
}
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++;
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++)<>
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
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.
2. What is lexeme?
LAB ASSIGNMENT
Branch:
Date:
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)
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] == '*')
{
{
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;
}
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;
}
}
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');
}
OUTPUT:
Branch:
Date:
EXPERIMENT – 04
(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;
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); }}
Branch:
Date:
EXPERIMENT – 05
(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++;
}
}
}
if(count==(strlen(string)-1))
{
printf("Input string is a valid identifier");
}
else
{
printf("Input string is not a valid identifier");
}
return 0;
}
Branch:
Date:
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 reads an input stream specifying the lexical analyzer and outputs source code
implementing the lexer in the C programming language
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>
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
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.
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.
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:
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
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);
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.
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.
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;
%}
%%
[\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;
}
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
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.)
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
PROGRAM:
%{
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
int |float |char |double |while |for |do |if |break |continue |void |switch |case |long |struct
|const |typedef |return
/*{printf("\n\n\t%s is a COMMENT\n",yytext);}*/
/* printf("\n\n\t%s is a COMMENT\n",yytext);}*/
{identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s",yytext);}
( ECHO;
%%
if (argc > 1)
FILE *file;
yyin = file;
}
yylex();
printf("\n\n");
return 0;
int yywrap()
return 0;
Input
$vi var.c
#include
main()
int a,b;
Output
$lex lex.l
$cc lex.yy.c
$./a.out var.c
FUNCTION
main (
BLOCK BEGINS
int is a KEYWORD
a IDENTIFIER
b IDENTIFIER
BLOCK ENDS
1. What is Jlex?
2. What is Flex?
Branch:
Date:
EXPERIMENT -08
(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'))
{
} }
return 0;
INPUT & OUTPUT:
Branch:
Date:
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.
PROGRAM:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int count, n = 0;
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;
if (xxx == 1)
continue;
// Function call
findfirst(c, 0, 0);
ptr += 1;
if (first[i] == calc_first[point1][lark])
{
chk = 1;
break;
}
}
if(chk == 0)
{
printf("%c, ", first[i]);
calc_first[point1][point2++] = first[i];
}
}
printf("}\n");
jm = n;
point1++;
}
printf("\n");
printf("-----------------------------------------------\n\n");
char donee[count];
ptr = -1;
// Checking if Follow of ck
// has already been calculated
if (xxx == 1)
continue;
land += 1;
// Function call
follow(ck);
ptr += 1;
void follow(char c)
{
int i, j;
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);
}
}
}
}
break;
}
Output :
First(E)= { (, i, }
First(R)= { +, #, }
First(T)= { (, i, }
First(Y)= { *, #, }
First(F)= { (, i, }
-----------------------------------------------
Follow(E) = { $, ), }
Follow(R) = { $, ), }
Follow(T) = { +, $, ), }
Follow(Y) = { +, $, ), }
Follow(F) = { *, +, $, ), }
Branch:
Date:
COMPILER DESIGN Page 58
DEPARTMENT OF COMPUTER SCIENCEAND ENEEENGINEERING
EXPERIMENT – 10
(To simulate LL(1) parsing using JFLAP)
Now click on Input and then Build LL(1) Parse Table. Your window should look like this
after entering LL(1) Parse Table mode.
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.
Result:- We create LL(1) parse table for a given CFG and hence Simulate LL(1) parsing
Branch:
Date:
EXPERIMENT-11
(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.
1 means that one symbol in the input string is used to help guide the parse.
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.
Result :- We created SLR(1) parse table for a given grammar and Simulated parsing and
output the parse tree proper format.
Branch:
Date: