Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
181 views

Compiler Design Lab Manual Final

The document is a lab manual for a Compiler Design course. It includes the vision and mission statements of the institute and computer science department, program and course outcomes, lab instructions, and a list of 13 experiments to be performed in the Compiler Design lab.

Uploaded by

BHAVIKA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
181 views

Compiler Design Lab Manual Final

The document is a lab manual for a Compiler Design course. It includes the vision and mission statements of the institute and computer science department, program and course outcomes, lab instructions, and a list of 13 experiments to be performed in the Compiler Design lab.

Uploaded by

BHAVIKA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

DEPARTMENT OF COMPUTER SCIENCE

ENGINEERING

LAB MANUAL
B.Tech. V Semester

COMPILER DESIGN LAB (5CS4-22 CD)

Modern Institute of Technology & Research Centre,


Alwar, Rajasthan
Affiliated to Bikaner Technical University, Bikaner.
5CS4-22 COMPILER DESIGN LAB

TABLE OF CONTENTS
PAGE
S NO NAME OF EXPERIMENT
NO

Vision and Mission of the Institute ii

Vision and Mission of the Department iii

Program Outcome (s) iv

Course Outcome (s) vi

Lab Instructions vii

BTU Syllabus viii


Introduction: Objective, scope and outcome of the course 1
1
To identify whether given string is keyword or not. 2-3
2
3 Count total no. of keywords in a file. [Taking file from user] 4-7

4 Count total no of operators in a file. [Taking file from user] 8-9

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

Write a LEX program to identify following:


7 1. Valid mobile number 2. Valid url 3. Valid identifier 23-24
4. Valid date (dd/mm/yyyy) 5. Valid time (hh:mm:ss)
8 Write a lex program to count blank spaces,words,lines in a given file. 25-26

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

Department of Computer Science Engineering, MITRC, Alwar i


5CS4-22 COMPILER DESIGN LAB

Vision and Mission of the Institute

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.

Department of Computer Science Engineering, MITRC, Alwar ii


5CS4-22 COMPILER DESIGN LAB

Vision and Mission of the Department

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.

Department of Computer Science Engineering, MITRC, Alwar iii


5CS4-22 COMPILER DESIGN LAB

Program Outcomes (POs)

1. Engineering Knowledge: Apply the knowledge of mathematics,


science, engineering fundamentals and an engineering specialization to
the solution of complex engineering problem.
2. Problem analysis: Identify, formulate, review research literature,
and analyze complex engineering problems reaching substantiated
conclusions using first principles of mathematics, natural sciences, and
engineering science.
3. Design/development of solutions: Design solutions for complex
engineering problems and design system components or processes that
meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based
knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate
techniques, resources, and modern engineering and IT tools including
prediction and modelling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the
contextual knowledge to assess societal, health, safety, legal and
Department of Computer Science Engineering, MITRC, Alwar iv
5CS4-22 COMPILER DESIGN LAB

cultural issues and the consequent responsibilities relevant to the


professional engineering practice.
7. Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics
and responsibilities and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual,
and as a member or leader in diverse teams, and in multidisciplinary
settings.
10. Communication: Communicate effectively on complex
engineering activities with the engineering community and with
society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and
give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and
apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the
preparation and ability to engage in independent and life-long learning
in the broadest context of technological change.

Department of Computer Science Engineering, MITRC, Alwar v


5CS4-22 COMPILER DESIGN LAB

Course Outcomes (Cos)

Course Outcomes: Upon successful completion of the course/Lab the


Students will be able to

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.

CO3. Write a scanner,parser,semantic analyzer without the aid of automatic CO generators.

CO4. Describe techniques for intermediate code and machine code optimization.

Department of Computer Science Engineering, MITRC, Alwar vi


5CS4-22 COMPILER DESIGN LAB

Lab Instructions

1. Keep Silence in the lab.

2. Sit on your own seat which is assigned by faculty or lab staff.

3. Always follow the instruction given by lab staff for to perform the assigned
experiment.

4. Every student is responsible for any damage to the computer or any


component which is assigned for lab work.

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.

7. Please keep your bag at right place inside the lab.

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.

Department of Computer Science Engineering, MITRC, Alwar vii


5CS4-22 COMPILER DESIGN LAB

BTU SYLLABUS
5CS4-22 COMPILER DESIGN LAB
Credit: 2 Max. Marks: 50(IA: 30, ETE: 20)

0L+0T+2P End Term Exam: 2 Hours

S.No List of Experiments


1 Introduction: Objective, scope and outcome of the course

2 To identify whether given string is keyword or not.

3 Count total no. of keywords in a file. [Taking file from user]

4 Count total no of operators in a file. [Taking file from user]

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.

7 Write a LEX program to identify following:


1. Valid mobile number 2. Valid url 3. Valid identifier
4. Valid date (dd/mm/yyyy) 5. Valid time (hh:mm:ss)

8 Write a lex program to count blank spaces,words,lines in a given file.

9 Write a lex program to count the no. of vowels and consonants in a C file.

10 Write a YACC program to recognize strings aaab,abbb using a^nb^n, where


b>=0.

11 Write a YACC program to evaluate an arithmetic expression involving operators


+,-,* and /.

12 Write a YACC program to check validity of a strings abcd,aabbcd using grammar


a^nb^nc^md^m, where n , m>0

13 Write a C program to find first of any grammar

Department of Computer Science Engineering, MITRC, Alwar viii


5CS4A-22 Compiler Design lab

PROGRAM 1

Objective : scope and outcome of the lab

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.

Department of Computer Science Engineering MITRC, ALWAR 1


5CS4A-22 Compiler Design lab

PROGRAM 2:

Objective: To identify whether given string is keyword or not.


CODE:

// C PROGRAM to check whether a given


// string is a keyword or not
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

// Function to check whether the given


// string is a keyword or not
// Returns 'true' if the string is a KEYWORD.
bool isKeyword(char* str)
{
if (!strcmp(str, "auto") || !strcmp(str, "default")
|| !strcmp(str, "signed") || !strcmp(str, "enum")
||!strcmp(str, "extern") || !strcmp(str, "for")
|| !strcmp(str, "register") || !strcmp(str, "if")
|| !strcmp(str, "else") || !strcmp(str, "int")
|| !strcmp(str, "while") || !strcmp(str, "do")
|| !strcmp(str, "break") || !strcmp(str,
"continue")
|| !strcmp(str, "double") || !strcmp(str, "float")
|| !strcmp(str, "return") || !strcmp(str, "char")
|| !strcmp(str, "case") || !strcmp(str, "const")
|| !strcmp(str, "sizeof") || !strcmp(str, "long")
|| !strcmp(str, "short") || !strcmp(str,
"typedef")
|| !strcmp(str, "switch") || !strcmp(str,
"unsigned")
|| !strcmp(str, "void") || !strcmp(str, "static")

Department of Computer Science Engineering MITRC, ALWAR 2


5CS4A-22 Compiler Design lab

|| !strcmp(str, "struct") || !strcmp(str, "goto")


|| !strcmp(str, "union") || !strcmp(str,
"volatile"))
return (true);
return (false);
}
// Driver code
int main()
{
isKeyword("geeks") ? printf("Yes\n")
: printf("No\n");
isKeyword("for") ? printf("Yes\n")
: printf("No\n");
return 0;
}
Output:
Input: str = "geeks"

Output: geeks is not a keyword

Input: str = "for"

Output: for is a keyword


No

Yes

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:

1. V.V Das, Compiler Design using FLEX and YACC, PHI.


2. A. K MAHTA, CD.

Department of Computer Science Engineering MITRC, ALWAR 3


5CS4A-22 Compiler Design lab

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 binarysearch(char [], struct keyword[]);

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,

Department of Computer Science Engineering MITRC, ALWAR 4


5CS4A-22 Compiler Design lab

"float", 0, "for", 0, "goto",


0,
"if", 0, "int", 0, "long", 0,
"register", 0, "return", 0,
"short", 0,
"signed", 0, "sizeof", 0,
"static", 0,
"struct", 0, "switch", 0,
"typedef", 0,
"union", 0, "unsigned", 0,
"void", 0,
"volatile", 0, "while", 0,};

printf("Enter string: ");


do
{
fflush(stdin);
c = getchar();
string[i++] = c;

} 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);

Department of Computer Science Engineering MITRC, ALWAR 5


5CS4A-22 Compiler Design lab

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

int binarysearch(char *word, struct keyword key[])


{
int low, high, mid;

low = 0;
high = KEYMAX - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (strcmp(word, key[mid].word) < 0)
{
high = mid - 1;
}

Department of Computer Science Engineering MITRC, ALWAR 6


5CS4A-22 Compiler Design lab

else if (strcmp(word, key[mid].word) > 0)


{
low = mid + 1;
}
else
{
return mid;
}
}

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:

1. V.V Das, Compiler Design using FLEX and YACC, PHI


2. J.P. Tremblay and P.G. Sorrenson, “The Theory and Practice of Compiler
Writing”, McGraw Hill, 1985.
3. Holub, Compiler Design in C, PHI.

Department of Computer Science Engineering MITRC, ALWAR 7


5CS4A-22 Compiler Design lab

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");

/* fopen() return NULL if last operation was


unsuccessful */
if(fPtr == NULL)
{
/* Unable to open file hence exit */
printf("Unable to open file.\n");
printf("Please check whether file exists and you
have read privilege.\n");
exit(EXIT_FAILURE);
}
Department of Computer Science Engineering MITRC, ALWAR 8
5CS4A-22 Compiler Design lab

/* File open success message */


printf("File opened successfully. Reading file
contents character by character. \n\n");

do
{
/* Read single character from file */
ch = fgetc(fPtr);

/* Print character read on console */


putchar(ch);

} while(ch != EOF); /* Repeat this if last read


character is not EOF */

/* Done with this file, close file to release


resource */
fclose(fPtr);
return 0;
OUTPUT:
No of operators: 4
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:

1. V.V Das, Compiler Design using FLEX and YACC, PHI


2. J.P. Tremblay and P.G. Sorrenson, “The Theory and Practice of Compiler
Writing”, McGraw Hill, 1985.

Department of Computer Science Engineering MITRC, ALWAR 9


5CS4A-22 Compiler Design lab

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>

#define MAX_WORDS 1000

int main()

FILE *fptr;

char path[100];

int i, len, index, isUnique;

// List of distinct words

char words[MAX_WORDS][50];

char word[50];

// Count of distinct words

int count[MAX_WORDS];

Department of Computer Science Engineering MITRC, ALWAR 10


5CS4A-22 Compiler Design lab

/* Input file path */

printf("Enter file path: ");

scanf("%s", path);

/* Try to open file */

fptr = fopen(path, "r");

/* Exit if file not opened successfully */

if (fptr == NULL)

printf("Unable to open file.\n");

printf("Please check you have read


previleges.\n");

exit(EXIT_FAILURE);

// Initialize words count to 0

for (i=0; i<MAX_WORDS; i++)

Department of Computer Science Engineering MITRC, ALWAR 11


5CS4A-22 Compiler Design lab

count[i] = 0;

index = 0;

while (fscanf(fptr, "%s", word) != EOF)

// Convert word to lowercase

strlwr(word);

// Remove last punctuation character

len = strlen(word);

if (ispunct(word[len - 1]))

word[len - 1] = '\0';

// Check if word exits in list of all distinct


words

isUnique = 1;

for (i=0; i<index && isUnique; i++)

if (strcmp(words[i], word) == 0)

isUnique = 0;

Department of Computer Science Engineering MITRC, ALWAR 12


5CS4A-22 Compiler Design lab

// If word is unique then add it to distinct


words list

// and increment index. Otherwise increment


occurrence

// count of current word.

if (isUnique)

strcpy(words[index], word);

count[index]++;

index++;

else

count[i - 1]++;

// Close file

fclose(fptr);

/*

Department of Computer Science Engineering MITRC, ALWAR 13


5CS4A-22 Compiler Design lab

* Print occurrences of all words in file.

*/

printf("\nOccurrences of all distinct words in file:


\n");

for (i=0; i<index; i++)

/*

* %-15s prints string in 15 character width.

* - is used to print string left align inside

* 15 character width space.

*/

printf("%-15s => %d\n", words[i], count[i]);

return 0;

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:

1. V.V Das, Compiler Design using FLEX and YACC, PHI


2. J.P. Tremblay and P.G. Sorrenson, “The Theory and Practice of Compiler
Writing”, McGraw Hill, 1985.

Department of Computer Science Engineering MITRC, ALWAR 14


5CS4A-22 Compiler Design lab

3. Holub, Compiler Design in C, PHI.

Department of Computer Science Engineering MITRC, ALWAR 15


5CS4A-22 Compiler Design lab

PROGRAM 6:

Objective: Write a C PROGRAM to insert, delete and display the entries


in Symbol Table.

CODE:

#include <STDIO.H>

const int MAX = 100;

class Node {

string identifier, scope, type;


int lineNo;
Node* next;

public:
Node()
{
next = NULL;
}

Node(string key, string value, string type, int lineNo)


{
this->identifier = key;
this->scope = value;
this->type = type;
this->lineNo = lineNo;
next = NULL;
}

void print()
{
cout << "Identifier's Name:" << identifier
<< "\nType:" << type
<< "\nScope: " << scope
<< "\nLine Number: " << lineNo << endl;
}

Department of Computer Science Engineering MITRC, ALWAR 16


5CS4A-22 Compiler Design lab

friend class SymbolTable;


};

class SymbolTable {
Node* head[MAX];

public:
SymbolTable()
{
for (int i = 0; i < MAX; i++)
head[i] = NULL;
}

int hashf(string id); // hash function


bool insert(string id, string scope,
string Type, int lineno);

string find(string id);

bool deleteRecord(string id);

bool modify(string id, string scope,


string Type, int lineno);
};

// Function to modify an identifier


bool SymbolTable::modify(string id, string s,
string t, int l)
{
int index = hashf(id);
Node* start = head[index];

if (start == NULL)
return "-1";

while (start != NULL) {


if (start->identifier == id) {
start->scope = s;
start->type = t;

Department of Computer Science Engineering MITRC, ALWAR 17


5CS4A-22 Compiler Design lab

start->lineNo = l;
return true;
}
start = start->next;
}

return false; // id not found


}

// Function to delete an identifier


bool SymbolTable::deleteRecord(string id)
{
int index = hashf(id);
Node* tmp = head[index];
Node* par = head[index];

// no identifier is present at that index


if (tmp == NULL) {
return false;
}
// only one identifier is present
if (tmp->identifier == id && tmp->next == NULL) {
tmp->next = NULL;
delete tmp;
return true;
}

while (tmp->identifier != id && tmp->next != NULL) {


par = tmp;
tmp = tmp->next;
}
if (tmp->identifier == id && tmp->next != NULL) {
par->next = tmp->next;
tmp->next = NULL;
delete tmp;
return true;
}

// delete at the end


else {

Department of Computer Science Engineering MITRC, ALWAR 18


5CS4A-22 Compiler Design lab

par->next = NULL;
tmp->next = NULL;
delete tmp;
return true;
}
return false;
}

// Function to find an identifier


string SymbolTable::find(string id)
{
int index = hashf(id);
Node* start = head[index];

if (start == NULL)
return "-1";

while (start != NULL) {

if (start->identifier == id) {
start->print();
return start->scope;
}

start = start->next;
}

return "-1"; // not found


}

// Function to insert an identifier


bool SymbolTable::insert(string id, string scope,
string Type, int lineno)
{
int index = hashf(id);
Node* p = new Node(id, scope, Type, lineno);

if (head[index] == NULL) {
head[index] = p;

Department of Computer Science Engineering MITRC, ALWAR 19


5CS4A-22 Compiler Design lab

cout << "\n"


<< id << " inserted";

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

int SymbolTable::hashf(string id)


{
int asciiSum = 0;

for (int i = 0; i < id.length(); i++) {


asciiSum = asciiSum + id[i];
}

return (asciiSum % 100);


}

// Driver code
int main()
{
SymbolTable st;
string check;
cout << "**** SYMBOL_TABLE ****\n";

Department of Computer Science Engineering MITRC, ALWAR 20


5CS4A-22 Compiler Design lab

// 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";

// find and print 'number'


check = st.find("number");
if (check != "-1")
cout << "Identifier Is present\n";
else
cout << "\nIdentifier Not Present";

return 0;
}
Output:
**** SYMBOL_TABLE ****

Department of Computer Science Engineering MITRC, ALWAR 21


5CS4A-22 Compiler Design lab

if inserted -successfully
number inserted -successfully

Identifier's Name:if
Type:keyword
Scope: local
Line Number: 4
Identifier Is present

if Identifier is deleted

number Identifier updated


Identifier's Name:number
Type:variable
Scope: global
Line Number: 3
Identifier Is present

VIVA VOCE:
1. What is symbol table?
2. What are the parameters in symbol table?
3. How identifier is different from keywords?

REFERENCES:

4. V.V Das, Compiler Design using FLEX and YACC, PHI


5. J.P. Tremblay and P.G. Sorrenson, “The Theory and Practice of Compiler
Writing”, McGraw Hill, 1985.
6. Holub, Compiler Design in C, PHI.

Department of Computer Science Engineering MITRC, ALWAR 22


5CS4A-22 Compiler Design lab

PROGRAM 7:

Objective: Write a LEX PROGRAM to identify following:


1. Valid mobile number
2. Valid url
3. Valid identifier
CODE:
/* Lex PROGRAM to check valid Mobile Number */

%{
/* Definition section */
%}

/* Rule Section */
%%

[1-9][0-9]{9} {printf("\nMobile Number Valid\n");}

.+ {printf("\nMobile Number Invalid\n");}

%%

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

Department of Computer Science Engineering MITRC, ALWAR 23


5CS4A-22 Compiler Design lab

VIVA VOCE:
4. What is symbol table?
5. What are the parameters in symbol table?
6. How identifier is different from keywords?

REFERENCES:

7. V.V Das, Compiler Design using FLEX and YACC,


PHI
8. J.P. Tremblay and P.G. Sorrenson, “The Theory and
Practice of Compiler Writing”, McGraw Hill, 1985.
9. Holub, Compiler Design in C, PHI.

Department of Computer Science Engineering MITRC, ALWAR 24


5CS4A-22 Compiler Design lab

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

Department of Computer Science Engineering MITRC, ALWAR 25


5CS4A-22 Compiler Design lab

Input:
Hello
How are you?

Output:
No. of lines=2
No. of spaces=4
No. of tabs=1
No. of other characters=15

Department of Computer Science Engineering MITRC, ALWAR 26


5CS4A-22 Compiler Design lab

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: This is GeeksforGeeks


Output: Number of vowels are: 7

Department of Computer Science Engineering MITRC, ALWAR 27


5CS4A-22 Compiler Design lab

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.

Department of Computer Science Engineering MITRC, ALWAR 28


5CS4A-22 Compiler Design lab

PROGRAM 10:

Objective: Write a YACC PROGRAM to recognize strings


aaab,abbb using a^nb^n, where b>=0.

CODE:

Lexical Analyzer Source Code :


%{
/* Definition section */
#include "y.tab.h"
%}

/* 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

Department of Computer Science Engineering MITRC, ALWAR 29


5CS4A-22 Compiler Design lab

/* Rule Section */
%%
stmt: S NL { printf("valid string\n");
exit(0); }
;
S: A S B |
;
%%

int yyerror(char *msg)


{
printf("invalid string\n");
exit(0);
}

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

Department of Computer Science Engineering MITRC, ALWAR 30


5CS4A-22 Compiler Design lab

Output: valid string

VIVA VOCE:
7. What is symbol table?
8. What are the parameters in symbol
table?
9. How identifier is different from
keywords?

REFERENCES:

13. V.V Das, Compiler Design using


FLEX and YACC, PHI
14. J.P. Tremblay and P.G.
Sorrenson, “The Theory and Practice
of Compiler Writing”, McGraw Hill,
1985.
15. Holub, Compiler Design in C,
PHI.

Department of Computer Science Engineering MITRC, ALWAR 31


5CS4A-22 Compiler Design lab

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);
}

Department of Computer Science Engineering MITRC, ALWAR 32


5CS4A-22 Compiler Design lab

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:

1. V.V Das, Compiler Design using FLEX and YACC, PHI


2. J.P. Tremblay and P.G. Sorrenson, “The Theory and Practice of Compiler
Writing”, McGraw Hill, 1985.
3. Holub, Compiler Design in C, PHI.

Department of Computer Science Engineering MITRC, ALWAR 33


5CS4A-22 Compiler Design lab

PROGRAM 12:

Objective: Write a YACC PROGRAM to check validity of a strings


abcd,aabbcd using grammar a^nb^nc^md^m, where n , m>0

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");

Department of Computer Science Engineering MITRC, ALWAR 34


5CS4A-22 Compiler Design lab

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.

Department of Computer Science Engineering MITRC, ALWAR 35


5CS4A-22 Compiler Design lab

PROGRAM 13..

Objective: Write a C PROGRAM to find first of any grammar.

CODE:

// C PROGRAM to calculate the First and


// Follow sets of a given grammar
#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];

Department of Computer Science Engineering MITRC, ALWAR 36


5CS4A-22 Compiler Design lab

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");
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;

Department of Computer Science Engineering MITRC, ALWAR 37


5CS4A-22 Compiler Design lab

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;

// 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;

Department of Computer Science Engineering MITRC, ALWAR 38


5CS4A-22 Compiler Design lab

}
}
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 alredy been calculated

Department of Computer Science Engineering MITRC, ALWAR 39


5CS4A-22 Compiler Design lab

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];
}
}

Department of Computer Science Engineering MITRC, ALWAR 40


5CS4A-22 Compiler Design lab

printf(" }\n\n");
km = m;
point1++;
}
}

void follow(char c)
{
int i, j;

// 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]);

Department of Computer Science Engineering MITRC, ALWAR 41


5CS4A-22 Compiler Design lab

}
}
}
}
}

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)
{
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]))

Department of Computer Science Engineering MITRC, ALWAR 42


5CS4A-22 Compiler Design lab

{
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)
break;
}

//Including the First set of the


// Non-Terminal in the Follow of
// the original query

Department of Computer Science Engineering MITRC, ALWAR 43


5CS4A-22 Compiler Design lab

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, }

Department of Computer Science Engineering MITRC, ALWAR 44


5CS4A-22 Compiler Design lab

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

Follow(E) = { $, ), }

Follow(R) = { $, ), }

Follow(T) = { +, $, ), }

Follow(Y) = { +, $, ), }

Follow(F) = { *, +, $, ), }

VIVA VOCE:

1. How to calculate first of given grammar?


2. How to calculate follow of any grammar?
3. What is epsilon?

REFERENCES:

1. V.V Das, Compiler Design using FLEX and YACC, PHI


2. J.P. Tremblay and P.G. Sorrenson, “The Theory and Practice of Compiler
Writing”, McGraw Hill, 1985.
3. Holub, Compiler Design in C, PHI.

Department of Computer Science Engineering MITRC, ALWAR 45

You might also like