0 ratings0% found this document useful (0 votes) 42 views29 pages5IT4 22 - Compiler Lab Manual Student
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
EXPERIMENT:
AIM:
Introduction: Objective, scope and outcome ofthe course.
OBJECTIVE:
The laboratory course is intended to make experiments on the basic techniques of compiler construction and
tools that can be used 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.
SCOPE:
‘The scope of this course is to explore the principle, algorithm and data structure involved in the design and
‘construction of compiler.
ourcomes:
‘Upon the completion of Compiler Design practical course, the student willbe able to:
1. Understand the working of lex and yace compiler for debugging of programs.
2, Understand and define the ole of lexical analyzer, use of regular expression and transition diagrams.
3. Understand and use Context free grammar, and parse tre construction.
4, Lear & use the new tools and technologies used for designing a compiler.
5. Develop program for solving parser problems.
6. Leam how to write programs that execute faster.Introduction of Compiler Design
Compiler is a software which converts a program written in high level language (Source Language)
to low level language (Object/Farget/Machine Language).
, Low Level
Compiler aanpanteerd
t
Compilation
Error
High Level
Language
. Cross Compiler that runs on a machine ‘A' and produces a code for another machine “B’. It
is capable of creating code for a platform other than the one on which the compi
Phases of a Compiler —
‘There ate two major phases of compilation, which in turn have many parts. Each of them take input
from the output of the previous level and work in a coordinated way.
hemHigh Level
Language:
ere
Snes
moe
eT az
Generator
Smarty
anne
aoe
Assembly Code
Analysis Phase — An semantic tree representation is created from the
1. Lexical Analyzer
2. Syntax Analyzer
3. Semantic Analyzer
Lexical analyzer divides the program into “tokens”
program using syntax of language and Semant
construct.
‘Syntax analyzer recognizes “sentences” in the
analyzer checks static semantics of each
‘Synthesis Phase - It has three parts :
4, Intermediate Code Generator
5. Code Optimizer
6. Code Generator
Intermediate Code Generator generates “abstract” code, Code Optimizer optimizes the abstract code,
and final Code Generator translates abstract intermediate code into specific machine instructions,
3h.XPERI} 2
AIM:
Program to find whether given string is keyword or not,
PROGRAM:
#include
#include
Hinclude
void main()
char a[5](10}=("printf","scanf”,"if","else","break"); char str{10];
int flag; clrser();
puts("Enter the string
; gett st)
for(i=0;i
Hinclude
#include
#include
Static int count=0;
int isKeyword(char buffert])(
char keywordsf32][10] =
snum","extern","f1
7 igned","sizeof", "static", "struct", "swite
","volatile", "while"
‘union", "unsigned", "voi
fori = 0; 1 < 32; ++i)(
if(stremp(keywordsfi), buffer)
flag = 1;
count+
break;
1
}
return flag;
}
int mainO
char ch, bufferf15] ;
FILE “fp;
int ij=0;
fp = fopen("KESHAV3.C',""");
if({p == NULL) .
printf("error while opening the file\n");
exit(0);}
while((ch = fgetc(fp)) != EOF){
if(isalnum(ch)){
buffer(j++] = ch;
)
else if((ch = 1) && (j= OD
0;
if(isKeyword(buffer) == 1)
print{("%s is keyword\n", buffer);
}
e@
printf("'no of keywords= %d", count);
fclose(fp);
return 0;EXPERIMENT-4
AIM:
Count total no of operators ina file, [Taking file from user] Hinclude
PROGRAM:
#include
#include
Hinclude
static int cout
int main()(
char ch, buffer{15], operatorst
print((“error while opening the file\n");
exit(0);
printf("%6c is operator\n", ch);
countt+;
)
}
)
print{(’no of operators= 9d", count);
felose( fp);
return 0;
38E [ENT-
AIM:
Count total occurrence of each character in a given
PROGRAM:
finclude
include
#include
int main
{
FILE * fp;
char string{100};
int = 0, count(26] = (0 }, x;
fp = fopen ("[Link]", "r"); eo
clser();
while Fscant (fp, "96s", string) != EOF)
(c=0;
‘while (stringfc] != No)
{
[Taking file from user]
/** Considering
rif (stringle]
{
aracters from 'a' to '2' only and ignoring others.
&&e stringle] <="2')
x= stringle]
count{x]++;
}
cH
}
}
for (c= 0; ¢<26; c++)
printf ("%c occurs %d times in the string.\n", ¢ + 'a', count{c]); e
return 0;
38EXPERIMENT-6
AIM:
‘Write a C program to inser, delete and display the entries in Symbol Table.
PROGRAM:
‘tmplementation of symbol table
#include
#includesctype.h>
#include
#includesstring h>
#include
void main()
{
int i=0,j=0.x=0,n
void *p,*addlS];
char chstch,b{15}dL151.¢;
print{(" Expression terminated by $:");
While((c=getchar())!='S')
{
itt;
}
neil;
print{("Given Expression
0;
while(i<=n)
{
printf("%c" bil);
itty
)
print{("\n Symbol Table\n");
printf ("Symbol \t addr \t type’
while(j<=n)
{
=bij)
iffisalpha(toascii(©)))
p=malloc(c);
addlx]=p;
lx}
printf("\n%c \t 96d \t identifier\n",c,p);
xt;
4p=malloc(ch);
add{x}
als}
hi
printf("\n %c \t %d \Coperator\n’,ch,p);
RH;
jes
mnEXP! NT-7
AIM:
‘Write a LEX program to identify following:
L. Valid mobile number
2. Valid url
3. Valid identifier
4, Valid date (ddimm/yyyy)
S. Valid time (hh:mm:ss)
PROGRAM:
[Link] mobile number
6
/* Definition section */
%)
P Rule Section */
4%
[1-9][0-9]{9} {printf(’\nMobile Number Valid\n”);}
+ {printf("\wMobile Number Invalid\n");}
56%
I1 driver code
int main()
{
printf(\nEnter Mobile Number :");
yylex();
printf("\n");
return 0;
}
int yywrap()
{
}
2. Valid url
4%
(Coup ittpys23Wvia-28-20-91(2,\fo-2}(2) ula2A-Z0-9+=2") (prnf(URL Vaido"))
‘> (printf((WURL Invalid\n");}
%%
void main() (
42printf(’\wnEnter URL : ");
yylex();
printf("\n"
)
int yywrap()
(
}
3. Valid identifier
‘fa>zA-Z_lla-2A-Z0-9_}* print{("Valid Identifier");
11 regex for invalid identifiers
‘(a -z A -Z_) printf("Invalid Identifier");
6%
void main() {
printf(’\nEnter Identifier: ");
yylex();
printi(’\n");
int yywrapQ)
{
2
4. Valid date (dd/mmiyyyy)
6%
({0-2}{0-9}}{31(0-1])v((0(113}5)7/8))|(10]12))v(C1-2]{0-9}{0-9]f-0-9]) {valid=1;}
({O-2]{0-9]30)((0(4)6|9))|11)V(L1-2]10-9]{0-9][0-9}) {valid=1;)
({0-1}{0-9}}2{0-8)vo2v((1-2]{0-9}{0-9]{0-9}) {valid=1;}
29VO2V((1-2]{0-9][0-9][0-9]) { while(yytextfi)!=/)i++; i++;while(yytext(i]!
Oryr}#(yytextli++]-0); i(yr%4==O}\ yr
i
%%
void main()
{
yyin=fopen("new",
yylex();
#3{H(valid==1) printf(*H is a valid date
else printf ("It is not a valid date\n");
)
int yywrap()
(
return 1;
!
id time(hh
ht
ide
int i=0,yr=0,vall
%)
%%
({0-2}{0-9]:[0-6][0-9)\:{0-6][0-9]) {print{("%s It is a valid time\
4%
void main()
{
yyin=fopen(“new
yylex
}
int yywrap()
(
retum 1;
)
44Al
Write a lex program to count blank spaces,words,lines in a given file.
PR
9%
EXPERIMENT-8
IM:
OGRAM:
finclude
int Tines=0, words
%6)
4%
\n (lines ++; words +#3)
[ie '"] wordst +;
[A-2] c_letters +5
[a-z] s lewers++;
{0-9} num++;
splchart +;
4%
void main(void)
(
FILE “fp;
char {(50);
print{(“enterfile name \n");
scant("%s"
yyin= fopen(|
yylexOs
‘otal=s_letters*c_letters#num#spl_char;
printi(" This File contains ."); print{(%
‘nd lines", lines); printf"
words", words); printf("int%d small
letters", sewers); printf("w9%d capital
lewters"¢_letters); print{("ni%6d digits",
7
print{("\nt%d special characters" spl_char);
printf("\nithn total 9d characters.\n" total};
}
int yywrap)
{
return(1);
}
45
,c_letters=0, num=0, spl_char=0,totalAIM:
Wate a tex program to count the no, of vowels and consonants in a C file.
PROGRAM:
ot
Hincludesstaio.h>
{nt veount=0,ccount=0;
%)
Lalifeloae|AMO]UT (veount’ +3)
[az A-Z, Cailefoluf|A MOL) 1 {ecomne++
int main)
{
FILE stp:
hae 15
print(Centertite name Wn");
seant(”
yyin= fopen(fy
yylex0s
print{("No, of Vowels :%d\n®,veount);
print((°No, of Consonants :26d\n",ccount);
ret 0;
)
int yywrap)
{
)AIM:
EXP! NT-10
‘Write a YACC program to recognize strings aaab,abbb using a”nb’n, where b>=0.
PROGRAM:
Gm
%( #include "[Link].h" %}
return A;}
(return B;}
0) G)
\n return 05}
- {return yytext{0};)
int yywrap()
{return 1; }
Gmy
96 Hinclude 9%)
S6token A B
stmt: S;
S:ASB
|
6%
void main)
(
print{(“enter \n");
exit(0);
}
void yyerror()
{
printf ("invalid");
exit(0);
}EXPERIMENT-11
AIM:
Write a YAC
PROGRAM:
Expr
%t
include "[Link].h"
extern int yylval;
%)
%%
[0-9}+ {yylval=atoi(yytext);
return number; }
0G)
Dun} {retum 03)
» {return yytext{0};)
%%
int yywrap()
{
return J;
}
Expry
Mf
#include
int res=0;
96}
S6token number
olefe +
‘left '*
%%
‘stmt:expr {res=$$;}
expriexpr'" expr (SS=$1+83;)
lexpr's expr {$$=81-83;)
lexpr'™ expr {S$=$1"83;}
Jexpr'7 expr
else $$=$1/S3;}
program to evaluate an arithmetic expression involving operators +,
and /.Jnumber
6%
void main()
56d" res); exit(O);
y
void yyerror()
{
print{("invalid\n");
exit(O);
1
44PERI
AIM:
Write a YACC program to check validity of a strings abcd, aabbed using grammar
a*nbancdmdam, where n , m>0
PROGRAM:
Grammer.y
%E
Hinclude
iclude
yerror(char*);
int yylex;
%)
token A BC D NEWLINE
%Y%
stmt:
NEWLINE { primt("validin");
return 1;
36%
extern FILE *yyin;
void main()
{
printf(“enter \n");
do
{
yyparseQ
}
while(!feof(yyin));
int yyerror(char* str)
{
5oprintf("invalid ");
return 1;
}
Grammer.
9%
#include'[Link].h”
%)
6%
al
A {retum A;)
cl
€ {return 3)
b]
B (return B;}
al
D {retum D;)
tw)
"vn (retum NEWLINI
{return yytext{O};}
int yywrap()
t
return 1;
)IMENT-13
AIM:
Write a C program to find first of any grammar,
PROGRAM:
#include
Hinclude
void FIRST(char
int count,n=0;
har prodn{10]{10}, first(10};
void main()
{
int ichoice;
char ¢,ch;,
Printf("How many productions ?
scanf("%6q",&ccount);
print{(’Enter 9%d productions epsilon:
for(i=Osiid
c. op> +]
Which ofthe following is true?
op and expr are start symbols,
op and id are terminals
expris start symbol and op is terminal
I. none of these
Ans.
aoee
33. To compute FOLLOW(A) for any
grammar symbol A
a. We must compute FIRST of some
grammar symbols
._Noneed of computing FIRST of some
symbol
c. May compute FIRST of some symbol
4. None of these
Ans.a
34, Which language is generated by the given
grammar S-> 0S1| 01
a, 0OLL
b. O01
c. 0011
d. 0011
Ans.d
(Q35. The space consuming but easy parsing is
5%a. LALR
b. SLR
c LR
._ Predictive parser
Ans. a
Q36. A top down parser generates
a. left-most derivation
b._right-most derivation
._right-most derivation in reverse
4. left-most derivation in reverse
Ans.a
Q37. Synthesized attribute can easily be
simulated by an
LL grammar
Ambiguous grammar
LR grammar
None of the above
aoge
Ans.c
Q38. Choose the false statement
a, LL(K) grammar has to be a CFG
b. LLCk) grammar has to be unambiguous
c. There are LL(K) grammars that are
not Context Free
4. LL grammars cannot have
left recursive non-terminals
Ans.c
Q39. If a grammar is unambiguous then it is
surely be
a. regular
b. LL)
©. Both (a) and (b)
Cannot say
Ans.d
(Q40. Predictive parsing is a special case of
a. top down parsing
b. bottom up parsing
c. recursive descent parsing
4. none of the above
Q41, The prefix form of (A+B)*(C-D) is
a. +AB*C-D.
b. *+-ABCD
c. *#AB-CD
d. *AB+CD
Ans.c
(Q42. Which of the following is true for the flow
of control among procedures during
execution of program?
a. Control flows randomly
b. Control flows line by line
Jumping
cc. Control flows sequentially
a. None of these
Ans.c
Q43. In a syntax directed translation scheme, if
the value of an attribute of a node is a
function of the values of the attributes of its
children, then itis called a
a. Synthesized attribute
b, Inherited attribute
c. Canonical attribute
d. None of the above
Ans.a
Q44. Which of the following is not an
intermediate code form?
Postfix notation
Syntax trees
Three address code
Quadruples
Ans. d
Q45. Three address codes can be implemented
by
a. indirect wiples
b. direct triples
both (a) and (b)
+d. none of the above
‘Ans. a
Q46. In a bottom up evaluation of a syntax
Girected definition, inherited attributes can
bea. always be evaluated
bbe evaluated only if the defini
attributed
c. be evaluated only if the definition has
synthesized attributes
none of the above
nis L-
Ans.¢
Q47. Three address code involves
a, at the most 3 address
b. exactly 3 address
c. no unary operators
d. none of the above
Ans.a
Q48, Inherited attribute is a natural choice in
a. keeping track of variable declaration
b. checking of the correct use of L-values
and R-values
c. both (a) and (b)
4. none of the above10.
ul.
12.
1B.
14.
15.
16.
17.
18,
19.
Practical Exam Sample Paper: Compiler Design Lab
Write a program to develop a lexical analyzer to recognize pattern identifier in C
Write a program to develop a lexical analyzer to recognize pattern constants, comments in C
Write a program to develop a lexical analyzer to recognize pattern constants, operators in C
Write a program to implement recursive descent parser....
Write a program to convert an infix notation into prefix notation
‘Write a program to convert ai
fix notation into postfix notation
Write a program to calculate the value of a postfix notation
Explain all the phases of compiler
‘Write a program to find out whether a given expression is valid or not
Write a program to perform following operations on a link list: Creation, Insertion and Display
Write a program to perform following operations on a link list: Creation, Insertion and Deletion
Generate Lexical Analyzer using LEX
‘Write a program to recognize a valid arithmetic expression that uses operators +,-,"/ using
YACC
Write a program to recognize a valid variable which starts with a letter followed by any
number of letters or digits using YACC
‘Write a program to recognize the grammar a" where n>=10
Explain the concept of LEX and YACC
‘Write a program to find the Macro Statements in a given C file (Use C file as input file)
‘Write a program to find number of white space characters in a C file.
‘Write a program which will ake two input strings. Find all the possible sub common
strings from the small String.Text and Reference Books
Bennett, Jeremy Peter. Introduction to compiling techniques: a first course using ANSI C, LEX
and YACC. McGraw-Hill, Inc., 1996.
Levine, John R., etal. Lex & yacc. " O'Reilly Media, Inc.”, 1992.
Aho, Alfred V., Jeffrey D. Ullman, and R. Sethi. "Principles of Compiler Construction.” (1977).
Louden, Kenneth C, "Compiler construction.” Cengage Learning (1997).