Compiler Design Lab Manual Final
Compiler Design Lab Manual Final
ENGINEERING
LAB MANUAL
B.Tech. V Semester
TABLE OF CONTENTS
PAGE
S NO NAME OF EXPERIMENT
NO
5 Count total occurrence of each character in a given file. [Taking file from user] 10-15
6 Write a C program to insert, delete and display the entries in Symbol Table. 16-22
9 Write a lex program to count the no. of vowels and consonants in a C file. 27-28
10 Write a YACC program to recognize strings aaab,abbb using a^nb^n, where 29-31
b>=0.
11 Write a YACC program to evaluate an arithmetic expression involving 32-33
operators +,-,* and /.
12 Write a YACC program to check validity of a strings abcd,aabbcd using 34-35
grammar a^nb^nc^md^m, where n , m>0
13 Write a C program to find first of any grammar 36-45
Vision
To produce well trained professionals and leaders for serving society
and world at large through excellence in academics, research,
development and innovations.
Mission
M1: To provide state of the art facility for academic excellence that
caters to regional, national and global challenges.
M2: To identify emerging areas of technology that can provide
innovative and sustainable solutions to global challenges.
M3: To provide an environment of industry oriented research and
development
M4: To inculcate core values of professional ethics, team-work, inter
personal skills and life-Long learning for sustainable development
of the society.
Vision
To create competent software professionals and leaders for serving
society and world at large through excellence in academics, research,
development and innovations.
Mission
M1: Provide strong theoretical and practical computer based skills to
meet the global technological changes.
M2: Provide a learning environment to enhance complex problem
solving skills, research based projects/activities and innovation.
M3: Establish Industry Institute Interaction Program to enhance the
entrepreneurship skills, leadership qualities, team-spirit and
ethical responsibilities.
M4: Prepare students for lifelong learning through sustainable
development.
CO1. Specify and analyses the lexical, syntactic and semantic structures of advanced
language features.
CO2. Separate the lexical, syntactic and semantic analysis into meaningful phases for a
compiler to undertake language translation.
CO4. Describe techniques for intermediate code and machine code optimization.
Lab Instructions
3. Always follow the instruction given by lab staff for to perform the assigned
experiment.
5. Do not go to any other seat to assist any student without permission of lab
staff, if so, may be punished for that.
6. Always come to lab with your file and file work should be completed.
8. Always get checked and signed your file work in time (experiment which
was performed in previous lab positively to be checked) after that faculty
may not check your work.
9. After performing the experiment the computer should be turned off and
power supply should be OFF.
BTU SYLLABUS
5CS4-22 COMPILER DESIGN LAB
Credit: 2 Max. Marks: 50(IA: 30, ETE: 20)
5 Count total occurrence of each character in a given file. [Taking file from user]
6 Write a C program to insert, delete and display the entries in Symbol Table.
9 Write a lex program to count the no. of vowels and consonants in a C file.
PROGRAM 1
This laboratory course is intended to make the students PROGRAM on the basic
techniques of compiler construction and tools that can used to perform syntax-
directed translation of a high-level programing 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 programing languages, code generation,
machine independent optimizations, dynamic memory allocation, and object
orientation.
PROGRAM 2:
Yes
VIVA VOCE:
REFERENCES:
PROGRAM 3:
Objective: Count total no. of keywords in a file. [Taking file from user]
CODE:
/*
* C PROGRAM to Count the Occurrences of each C Keyword
* using Array Structure
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define KEYMAX 32
struct keyword
{
char word[10];
int occur;
};
int main()
{
int i = 0, j = 0, pos;
char string[100], unit[20], c;
struct keyword key[32] = {"auto", 0, "break", 0,
"case", 0,
"char", 0, "const", 0,
"continue", 0,
"default", 0, "do", 0,
"double", 0,
"else", 0, "enum", 0, "extern",
0,
} while (c != '\n');
string[i - 1] = '\0';
printf("The string entered is: %s\n", string);
for (i = 0; i < strlen(string); i++)
{
while (i < strlen(string) && string[i] != ' ' &&
isalpha(string[i]))
{
unit[j++] = tolower(string[i++]);
}
if (j != 0)
{
unit[j] = '\0';
pos = binarysearch(unit, key);
j = 0;
if (pos != -1)
{
key[pos].occur++;
}
}
}
printf("***********************\n
Keyword\tCount\n***********************\n");
for (i = 0; i < KEYMAX; i++)
{
if (key[i].occur)
{
printf(" %s\t %d\n", key[i].word,
key[i].occur);
}
}
return 0;
}
low = 0;
high = KEYMAX - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (strcmp(word, key[mid].word) < 0)
{
high = mid - 1;
}
return -1;
}
$ gcc keywordoccur.c
$ ./a.out
Enter string: break, float and double are c keywords. float and double are primitive data types.
The string entered is: break, float and double are c keywords. float and double are primitive
data types.
Keyword Count
break 1
double 2
float 2
VIVA VOCE:
1. What is string.h header file?
2. How many primitive data types in C program?
3. What is user define data type?
REFERENCES:
PROGRAM 4:
Objective: Count total no of operators in a file. [Taking file from user]
CODE:
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* File pointer to hold reference to our file */
FILE * fPtr;
char ch;
/*
* Open file in r (read) mode.
* "data/file1.txt" is complete file path to read
*/
fPtr = fopen("data/file1.txt", "r");
do
{
/* Read single character from file */
ch = fgetc(fPtr);
REFERENCES:
PROGRAM 5:
Objective: Count total occurrence of each character in a given file.
[Taking file from user]
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
FILE *fptr;
char path[100];
char words[MAX_WORDS][50];
char word[50];
int count[MAX_WORDS];
scanf("%s", path);
if (fptr == NULL)
exit(EXIT_FAILURE);
count[i] = 0;
index = 0;
strlwr(word);
len = strlen(word);
if (ispunct(word[len - 1]))
word[len - 1] = '\0';
isUnique = 1;
if (strcmp(words[i], word) == 0)
isUnique = 0;
if (isUnique)
strcpy(words[index], word);
count[index]++;
index++;
else
count[i - 1]++;
// Close file
fclose(fptr);
/*
*/
/*
*/
return 0;
VIVA VOCE:
REFERENCES:
PROGRAM 6:
CODE:
#include <STDIO.H>
class Node {
public:
Node()
{
next = NULL;
}
void print()
{
cout << "Identifier's Name:" << identifier
<< "\nType:" << type
<< "\nScope: " << scope
<< "\nLine Number: " << lineNo << endl;
}
class SymbolTable {
Node* head[MAX];
public:
SymbolTable()
{
for (int i = 0; i < MAX; i++)
head[i] = NULL;
}
if (start == NULL)
return "-1";
start->lineNo = l;
return true;
}
start = start->next;
}
par->next = NULL;
tmp->next = NULL;
delete tmp;
return true;
}
return false;
}
if (start == NULL)
return "-1";
if (start->identifier == id) {
start->print();
return start->scope;
}
start = start->next;
}
if (head[index] == NULL) {
head[index] = p;
return true;
}
else {
Node* start = head[index];
while (start->next != NULL)
start = start->next;
start->next = p;
cout << "\n"
<< id << " inserted";
return true;
}
return false;
}
// Driver code
int main()
{
SymbolTable st;
string check;
cout << "**** SYMBOL_TABLE ****\n";
// insert 'if'
if (st.insert("if", "local", "keyword", 4))
cout << " -successfully";
else
cout << "\nFailed to insert.\n";
// insert 'number'
if (st.insert("number", "global", "variable", 2))
cout << " -successfully\n\n";
else
cout << "\nFailed to insert\n";
// find 'if'
check = st.find("if");
if (check != "-1")
cout << "Identifier Is present\n";
else
cout << "\nIdentifier Not Present\n";
// delete 'if'
if (st.deleteRecord("if"))
cout << "if Identifier is deleted\n";
else
cout << "\nFailed to delete\n";
// modify 'number'
if (st.modify("number", "global", "variable", 3))
cout << "\nNumber Identifier updated\n";
return 0;
}
Output:
**** SYMBOL_TABLE ****
if inserted -successfully
number inserted -successfully
Identifier's Name:if
Type:keyword
Scope: local
Line Number: 4
Identifier Is present
if Identifier is deleted
VIVA VOCE:
1. What is symbol table?
2. What are the parameters in symbol table?
3. How identifier is different from keywords?
REFERENCES:
PROGRAM 7:
%{
/* Definition section */
%}
/* Rule Section */
%%
%%
// driver code
int main()
{
printf("\nEnter Mobile Number : ");
yylex();
printf("\n");
return 0;
}
Input: 7017175023
Output: Mobile Number Valid
Input: 0001112223
Output: Mobile Number Invalid
VIVA VOCE:
4. What is symbol table?
5. What are the parameters in symbol table?
6. How identifier is different from keywords?
REFERENCES:
PROGRAM 8:
Objective: Write a lex PROGRAM to count blank spaces, words,lines in
a given file.
CODE:
%{
int vow_count=0;
int const_count =0;
%}
%%
[aeiouAEIOU] {vow_count++;}
[a-zA-Z] {const_count++;}
%%
main()
{
printf("Enter the string of vowels and consonents:");
yylex();
printf("Number of vowels are: %d\n", vow);
printf("Number of consonants are: %d\n", cons);
return 0;
}
Input:
Geeks for Geeks
gfg gfg
Output:
No. of lines=2
No. of spaces=3
No. of tabs=1
No. of other characters=19
Input:
Hello
How are you?
Output:
No. of lines=2
No. of spaces=4
No. of tabs=1
No. of other characters=15
PROGRAM 9:
Objective: Write a lex PROGRAM to count the no. of vowels and
consonants in a C file.
CODE:
%{
int vow_count=0;
int const_count =0;
%}
%%
[aeiouAEIOU] {vow_count++;}
[a-zA-Z] {const_count++;}
%%
main()
{
printf("Enter the string of vowels and
consonents:");
yylex();
printf("Number of vowels are: %d\n", vow);
printf("Number of consonants are: %d\n",
cons);
return 0;
}
Number of consonants are: 12
Input: Hello everyone
Output: Number of vowels are: 6
Number of consonants are: 7
Input:
Geeks for Geeks
gfg gfg
Output:
No. of lines=2
No. of spaces=3
No. of tabs=1
No. of other characters=19
VIVA VOCE:
1. How many keywords are there in C?
2. What is strcmp function?
3. How do we use header files in C program?
REFERENCES:
10. V.V Das, Compiler Design using FLEX and YACC, PHI
11. J.P. Tremblay and P.G. Sorrenson, “The Theory and Practice of Compiler
Writing”, McGraw Hill, 1985.
12. Holub, Compiler Design in C, PHI.
PROGRAM 10:
CODE:
/* Rule Section */
%%
[aA] {return A;}
[bB] {return B;}
\n {return NL;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}
Parser Source Code :
%{
/* Definition section */
#include<stdio.h>
#include<stdlib.h>
%}
%token A B NL
/* Rule Section */
%%
stmt: S NL { printf("valid string\n");
exit(0); }
;
S: A S B |
;
%%
//driver code
main()
{
printf("enter the string\n");
yyparse();
}
Input: ab
Output: valid string
Input: aab
Output: invalid string
Input: aabb
Output: valid string
Input: abb
Output: invalid string
Input: aaabbb
VIVA VOCE:
7. What is symbol table?
8. What are the parameters in symbol
table?
9. How identifier is different from
keywords?
REFERENCES:
PROGRAM 11:
Objective: Write a YACC PROGRAM to evaluate an arithmetic expression
involving operators +,-,* and /
Yacc Part :
%token NUMBER ID NL
%left ‘+’ ‘-‘
%left ‘*’ ‘/’
%%
stmt : exp NL { printf(“Value = %d\n”,$1); exit(0);}
;
exp : exp ‘+’ exp { $$=$1+$3; }
| exp ‘-‘ exp { $$=$1-$3; }
| exp ‘*’ exp { $$=$1*$3; }
| exp ‘/’ exp { if($3==0)
{
printf(“Cannot divide by 0”);
exit(0);
}
else
$$=$1/$3;
}
| ‘(‘ exp ‘)’ { $$=$2; }
| ID { $$=$1; }
| NUMBER { $$=$1; }
;
%%
int yyerror(char *msg)
{
printf(“Invalid Expression\n”);
exit(0);
}
main ()
{
printf(“Enter the expression\n”);
yyparse();
}
VIVA VOCE:
1. How many keywords are there in C?
2. What is strcmp function?
3. How do we use header files in C program?
REFERENCES:
PROGRAM 12:
CODE:
#include "y.tab.h"
%}
%%
"a"|"A" {return A;}
"b"|"B" {return B;}
[ \t] {;}
\n {return 0;}
. {return yytext[0];}
%%
6.y
%{
#include<stdio.h>
%}
%token A B
%%
stmt: S
;
S: A S B
|
;
%%
void main()
{
printf("enter \n");
yyparse();
printf("valid");
exit(0);
}
void yyerror()
{
printf("invalid ");
exit(0);
}
VIVA VOCE:
10. What is symbol table?
11. What are the parameters in symbol table?
12. How identifier is different from keywords?
REFERENCES:
16. V.V Das, Compiler Design using FLEX and YACC, PHI
17. J.P. Tremblay and P.G. Sorrenson, “The Theory and Practice of Compiler
Writing”, McGraw Hill, 1985.
18. Holub, Compiler Design in C, PHI.
PROGRAM 13..
CODE:
int count, n = 0;
int k;
char ck;
int e;
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 alredy been calculated
if (xxx == 1)
continue;
land += 1;
// Function call
follow(ck);
ptr += 1;
printf(" }\n\n");
km = m;
point1++;
}
}
void follow(char c)
{
int i, j;
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]);
}
}
}
}
}
{
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);
}
}
}
}
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++;
}
}
}
Output :
First(E)= { (, i, }
First(R)= { +, #, }
First(T)= { (, i, }
First(Y)= { *, #, }
First(F)= { (, i, }
-----------------------------------------------
Follow(E) = { $, ), }
Follow(R) = { $, ), }
Follow(T) = { +, $, ), }
Follow(Y) = { +, $, ), }
Follow(F) = { *, +, $, ), }
VIVA VOCE:
REFERENCES: