0% found this document useful (0 votes)
35 views19 pages

CD Lab Manual

The document is a lab manual for the Compiler Design course at CMR College of Engineering & Technology for B.Tech II Year students. It outlines the vision and mission of the institution and department, program educational objectives, course outcomes, and a detailed syllabus including various programming tasks. Additionally, it provides information on required software and tools, along with sample programs for implementing a symbol table and a lexical analyzer.

Uploaded by

arjun118102314
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views19 pages

CD Lab Manual

The document is a lab manual for the Compiler Design course at CMR College of Engineering & Technology for B.Tech II Year students. It outlines the vision and mission of the institution and department, program educational objectives, course outcomes, and a detailed syllabus including various programming tasks. Additionally, it provides information on required software and tools, along with sample programs for implementing a symbol table and a lexical analyzer.

Uploaded by

arjun118102314
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

CMR College of Engineering & Technology

Kandlakoya(v), Medchal Road,


Hyderabad, Telangana, India -501401,
Telephone: 08418 - 200699. Email: [email protected].

DEPARTMENT OF INFORMATION TECHNOLOGY


R-22 REGULATION
COMPILER DESIGN

LAB MANUAL

(A412507)

B.TECH: II YEAR – II
SEMESTER (2023-2024)

CMR College of Engineering & Technology


1
Vision
Our Vision is to remain a premier academic institution striving continuously for
excellence in technical education, research and render technological services to the
nation.

Mission
• Our Mission is to create and sustain a community of learning in which students acquire
knowledge and learn to apply it professionally with a concern for the society.
• Pursue and Disseminate Research Findings and Offer Knowledge-BasedTechnological
Services to Satisfy the Needs of Society and the Industry.
• Promote Professional Ethics, Leadership Qualities and Social Responsibilities.

Vision of the Department

• To evolve as a center of academic excellence in Information Technology by


building strong teaching and research environment.

Mission of the Department

• To offer high quality graduate and post graduate programs in computer science education
and to prepare students for professional career and/or higher studies globally.

• To develop self learning abilities and professional ethics to serve the society.

CMR College of Engineering & Technology


2
Program Educational Objectives (PEOs)

Excel in their professional career and higher education in


PEO - I Information Technology and chosen fields.

Demonstrate leadership qualities, team work and professional


PEO - II ethics to serve the society

Adapt to state of art technology through continuous learning in


PEO - III the areas of interest.

CMR College of Engineering & Technology


3
CMR College of Engineering & Technology
Kandlakoya(v), Medchal Road Hyderabad, Telangana, India - 501401,
Telephone: 08418 - 200699. Email: [email protected].

DEPARTMENT OF INFORMATION TECHNOLOGY

Academic Year -2023-24


Semester –III

Subject : COMPILER DESIGN LAB

Subject Code : A412507

Class & Branch/ Specialization : B.TECH - IT II Year II Sem

COURSE (LAB) OUTCOMES

S.No. Course (Lab) Outcomes

1 Design, develop and implement a compiler for any language.


Design and implement a lexical analyzer recognizing identifiers,
2
constants, comments and operators.
3 Create YACC specifications to recognize valid arithmetic expressions,
variables and implement a calculator.
4 Use LEX and YACC tools for developing a scanner and a parser.

5 Design and implement LL and LR Parsers.

Signature of the HOD

CMR College of Engineering & Technology


4
SYLLABUS

WEEK NAME OF THE PROGRAM


1 Write a C program for implementation of Symbol Table.
2 Develop a lexical analyzer to recognize a few patterns in C. (Ex:
3 Implementation of Lexical Analyzer using Lex Tool
4A Program to recognize a valid arithmetic expression that uses operator +, - , * and
/.
B Program to recognize a valid variable which starts with a letter followed by any
number of letters or digits.
C Implementation of Calculator using LEX and YACC.
5 Convert the BNF rules into YACC form and write code to generate Abstract
Syntax Tree
6 Implement type checking
7 Implement any one storage allocation strategies (heap, stack, static)
8 Write a lex program to count the number of words and number of lines in a given
file or program
9 Write a ‘C’ program to implement lexical analyzer using c program.
10 Write recursive descent parser for the grammar E->E+T E->T T->T*F T->F F-
>(E)/id
11 Write recursive descent parser for the grammar S->(L) S->a L->L,S L->S
12 Write a C program to calculate first function for the grammar E->E+T E->T T-
>T*F T->F F->(E)/id
13 Write a YACC program to implement a top down parser for the given grammar.
14 Write a YACC program to evaluate algebraic expression.

CMR College of Engineering & Technology


5
TEXTBOOKS:
1. Compilers: Principles, Techniques and Tools, Second Edition, Alfred V. Aho,
Monica S. Lam, Ravi Sethi, Jeffry D. Ullman.

REFERENCE BOOKS:

1. Lex & YACC – John R. Levine, Tony Mason, Doug Brown, O’Reilly
2. Compiler Construction, Louden, Thomson

CMR College of Engineering & Technology


6
INDEX

S.No. Name of the Program Page No.


1 Write a C program for implementation of Symbol Table.
2 Develop a lexical analyzer to recognize a few patterns in C. (Ex:
3 Implementation of Lexical Analyzer using Lex Tool
4A Program to recognize a valid arithmetic expression that uses operator +, - , *
and /.

B Program to recognize a valid variable which starts with a letter followed by any
number of letters or digits.

C Implementation of Calculator using LEX and YACC.


5 Convert the BNF rules into YACC form and write code to generate Abstract
Syntax Tree
6
Implement type checking
7
Implement any one storage allocation strategies (heap, stack, static)
8 Write a lex program to count the number of words and number of lines in a given
file or program
9 Write a ‘C’ program to implement lexical analyzer using c program.
10 Write recursive descent parser for the grammar E->E+T E->T T->T*F T->F F-
>(E)/id
11 Write recursive descent parser for the grammar S->(L) S->a L->L,S L->S
12 Write a C program to calculate first function for the grammar E->E+T E->T T-
>T*F T->F F->(E)/id
13
Write a YACC program to implement a top-down parser for the given grammar.
14
Write a YACC program to evaluate algebraic expression.

CMR College of Engineering & Technology


7
Laboratory Equipment/Software/Tools Required
 Linux (OS)
 Code Blocks

CMR College of Engineering & Technology


8
Software Installation Procedure:

CMR College of Engineering & Technology


9
Week1

1. Implementation of symbol table


ALGORITHM:
1. Start the program for performing insert, display, delete, search and modify option in symbol table
2. Define the structure of the Symbol Table
3. Enter the choice for performing the operations in the symbol Table
4. If the entered choice is 1, search the symbol table for the symbol to be inserted. If the symbol is already
present, it displays “Duplicate Symbol”. Else, insert the symbol and the corresponding address in the symbol
table.
5. If the entered choice is 2, the symbols present in the symbol table are displayed.
6. If the entered choice is 3, the symbol to be deleted is searched in the symbol table. If it is not found in the
symbol table it displays “Label Not found”. Else, the symbol is deleted.
7. If the entered choice is 5, the symbol to be modified is searched in the symbol table. The label or address or
both can be modified.
PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct table
{ char var[10]; int value;
};
struct table tbl[20];
int i,j,n;
void create();
void modify();
int search(char variable[],int n);
void insert();
void display();
void main()
{ int ch,result=0; char v[10]; do
{ printf("Enter your choice\n1.Create\n2.Insert\
n3.Modify\n4.Search\n5.Display\n6.Exit:");
scanf("%d",&ch); switch(ch)
CMR College of Engineering & Technology
10
{
case 1:
create();
break; case 2:
insert();
break; case 3:
modify();
break; case 4:
printf("Enter the variable to be searched for:\n");
scanf("%s",&v); result=search(v,n);
if(result==0)
printf("The variable does not belong to the table\
n");
else
printf("The location of the variable is %d\nThe
value of %s is%d\
n",result,tbl[result].var,tbl[result].value);
break; case 5:
display();
break; case 6:
exit(1);
}
}
while(ch!=6); getch();
}
void create()
{
printf("Enter the no. of entries:");
scanf("%d",&n);
printf("Enter the variable and the value:\n");
for(i=1;i<=n;i++)
{ scanf("%s%d",tbl[i].var,&tbl[i].value); check:
if(tbl[i].var[0]>='0'&&tbl[i].var[0]<='9')
{ printf("The variable should start with an alphabet\nEnter
correct variable name:\n"); scanf("%s
%d",tbl[i].var,&tbl[i].value); goto check;
} check1:
for(j=1;j<i;j++)
{ if(strcmp(tbl[i].var,tbl[j].var)==0)
{ printf("The variable already exists.Enter another
CMR College of Engineering & Technology
11
variable\n"); scanf("%s%d",tbl[i].var,&tbl[i].value); goto
check1;
}
}
}
printf("The table after creation is:\n"); display();
}
void insert()
{ if(i>=20) printf("Cannot insert.Table is full\n"); else {
n++;
printf("Enter the value and variable\n"); scanf("%s
%d",tbl[n].var,&tbl[n].value); check:
if(tbl[i].var[0]>='0'&&tbl[i].var[0]<='9')
{ printf("The variable should start with an alphabet\nEnter
correct variable name:\n"); scanf("%s
%d",tbl[i].var,&tbl[i].value); goto check;
} check1: for(j=1;j<n;j++)
{ if(strcmp(tbl[j].var,tbl[i].var)==0)
{ printf("The variable already exist.Enter another
variable\n"); scanf("%s%d",tbl[i].var,&tbl[i].value); goto
check1;
}
}
printf("The table after insertion is:\n"); display();
}
}
void modify()
{ char variable[10]; int result=0;
printf("Enter the variable to be modified\n");
scanf("%s",&variable); result=search(variable,n);
if(result==0) printf("%s does not belong to table\
n",variable); else
{ printf("The current value of the variable %s is %d\
nEnter the new variable and its value\
n",tbl[result].var,tbl[result].value); scanf("%s
%d",tbl[result].var,&tbl[result].value); check:
if(tbl[i].var[0]>='0'&&tbl[i].var[0]<='9')
{ printf("The variable should start with an alphabet\nEnter
correct variable name:\n"); scanf("%s
%d",tbl[i].var,&tbl[i].value); goto check;

CMR College of Engineering & Technology


12
}
}
printf("The table after modification is:\n"); display();
}
int search(char variable[],int n)
{ int flag; for(i=1;i<=n;i++)
{ if(strcmp(tbl[i].var,variable)==0)
{ flag=1; break;
}
} if(flag==1) return i;
else return 0;
} void display()
{
printf("VARIABLE\t VALUE\n"); for(i=1;i<=n;i++)
printf("%s\t\t%d\n",tbl[i].var,tbl[i].value);
}

OUTPUT

Enter your choice


1.Create
2.Insert
3.Modify
4.Search
5.Display
6.Exit:1

Enter the no. of entries:3 Enter the


variable and the value:
AIM 45
ASK 34
BALL 56

The table after creation is:


VARIABLE VALUE
AIM 45
ASK 34
BALL 56

Enter your choice


1.Create
2.Insert
3.Modify
4.Search
5.Display

CMR College of Engineering & Technology


13
6.Exit:2

Enter the value and variable


SIM 25

The table after insertion is:


VARIABLE VALUE
AIM 45
ASK 34
BALL 56
SIM 25

Enter your choice


1.Create
2.Insert
3.Modify
4.Search
5.Display 6.Exit:3

Enter the variable to be modified


ASK
The current value of the variable ASK is 34 Enter the new variable and its value
RIM 40

The table after modification is:


VARIABLE VALUE
AIM 45
RIM 40
BALL 56
SIM 25

Enter your choice


1.Create
2.Insert
3.Modify
4.Search
5.Display
6.Exit:4

Enter the variable to be searched for:


RIM
The location of the variable is 2
The value of RIM is 40

Enter your choice


1.Create
2.Insert
3.Modify
4.Search
CMR College of Engineering & Technology
14
5.Display
6.Exit:5

VARIABLE VALUE
AIM 45
RIM 40
BALL 56
SIM 25
Enter your choice
1.Create
2.Insert
3.Modify
4.Search
5.Display
6.Exit:6

RESULT:

Thus the C program to implement Symbol Table was executed and verified successfully.

CMR College of Engineering & Technology


15
Week 2
2. Develop a lexical analyzer to recognize a few patterns including (ex. Identifiers, constants,
comments, operators etc.)
AIM:

To develop a lexical analyzer to recognize a few patterns in C.


ALGORITHM:

1. Open the input file in read mode.

2. Read the string from file till end of file.

3. If the character is a slash then call skipcomment() for skip the comment statements in the file.
4. If the first string matches with any delimiters operator then print as a delimiter.
5. If the first string matches with any header then print that string as a header file.
6. If the first string matches with any operator then print that as an operator.
7. If the first string matches with any keywords then print that string as a keyword.
8. If the string is not a keyword then print that as an identifier.

PROGRAM:

/* This program is for creating a Lexical Analyzer. lexical.c */


#include<stdio.h>
#include<string.h> //Necessary Header files
#include<conio.h>
#include<ctype.h>
FILE *fp; //File pointer for accessing the file
char delim[14]={‘ ‘,’\t’,’\n’,’,’,’;’,’(‘,’)’,’{‘,’}’,’[‘,’]’,’#’,’<‘,’>‘}; char oper[7]={‘+’,’-’,’*’,’/’,’%’,’=‘,’!’}; //Array holding all the
operators

/* Set of Keywords to check and list out */ char key[21][12]=


{“int”,”float”,”char”,”double”,”bool”,”void”,”extern”,”unsigned”,”goto”,
”static”,”class”,”struct”,”for”,”if”,”else”,”return”,”register”,”long”,”while”,”do”};

/*The Preprocessor directives*/


char predirect[2][12]={“include”,”define”};

/*The possible header files*/


char header[6][15]={“stdio.h”,”conio.h”,”malloc.h”,”process.h”,”string.h”,”ctype.h”}; void skipcomment(); //Function to skip
comments. void analyze(); //Function analyzing the input file
void check(char[]); //Function to check whether the string matches any of the keywords int isdelim(char); //Function to check if
the character retrieved from the file is a delimiter int isop(char); //Function to check if the character retrieved from the file is an
operator int fop=0,numflag=0,f=0; //necessary flag values char c,ch,sop; //necessary character variables to store
the characters retrieved
CMR College of Engineering & Technology
16
void main() //Main Function
{ char fname[12]; clrscr();
printf(“\nEnter filename : “); scanf(“%s”,fname);
fp=fopen(fname,”r”); //Opening the file if(fp==NULL) //Checking Existence of the File
printf(“\nThe file doesn’t exist.”);
else //If Check succeeds analyze(); printf(“\nEnd of file\n”);
getch();
} //End of Main function

void analyze() //Analyse Function


{
char token[50]; //Declare a token character array int j=0;
while(!feof(fp)) //While the file is not over
{ c=getc(fp);
if(c==‘/’) //checking for comments in the file
{ skipcomment(); //Function to skip comment statements
}
else if(c==‘“‘) //Skipping printf statements and other such display while((c=getc(fp))!=‘“‘);
else if(isalpha(c)) //checking if the character is an alphabet or not
{
if(numflag==1)
{
token[j]=‘\0’;
check(token);
numflag=0;
j=0;
} f=0;
else

{
token[j]=c; //Combining the
characters to get the
token
j++;
} if(f==0) f=1;
}
else if(isalnum(c))
{ if(numflag==0) numflag=1;
token[j]=c; //combining the characters to get the token j++; }
else
{
if(isdelim(c)) //Checking for delimiters.
{
if(numflag==1)
{
token[j]=‘\0’; check(token); numflag=0;
CMR College of Engineering & Technology
17
} if(f==1) { token[j]=‘\0’;
numflag=0; check(token);
} j=0; f=0;
printf(“\nDelimitter\t %c”,c);
} else if(isop(c)) //Checking for operators
{ if(numflag==1)
{ token[j]=‘\0’; check(token);
numflag=0; j=0; f=0;
}
if(f==1) { token[j]=‘\0’;
j=0; f=0; numflag=0; check(token);
} if(fop==1)
{ fop=0;
printf(“\nOperator\t %c%c”,c,sop); //In case the operator is like ‘++’or ‘--
} else printf(“\nOperator\t %c”,c); //In other
cases.
}
else if(c==‘.’)
{ token[j]=c; j++;
}
}
}
}

int isdelim(char c) //Function to check if the character retrieved from the file is a delimiter.
{ int i; for(i=0;i<14;i++)
{ if(c==delim[i]) return 1;
} return 0;
}

int isop(char c) //Function to check if the character retrieved from the file is an operator.
{ int i,j; char ch; for(i=0;i<7;i++)
{ if(c==oper[i])
{ ch=getc(fp); for(j=0;j<6;j++) //In case the operator is like
‘++’ or ‘--’, etc.
{ if(ch==oper[j])
{ fop=1; sop=ch;
return 1;
} } ungetc(ch,fp); return 1;
} } return 0;
} void check(char t[]) //Function to check if the token is an identifier, keyword, header file name
{ int i; if(numflag==1)
{ printf(“\nNumber\t\t %s”,t); return; } for(i=0;i<2;i++)
{ if(strcmp(t,predirect[i])==0)
{
printf(“\nPreprocessor directive %s”,t); return;
} } for(i=0;i<6;i++)
{
if(strcmp(t,header[i])==0)
{

CMR College of Engineering & Technology


18
printf(“\nHeader file\t %s”,t); return; }
}
for(i=0;i<21;i++)
{ if(strcmp(key[i],t)==0)
{ printf(“\nKeyword\t\t %s”,key[i]); return;
} }
printf(“\nIdentifier\t %s”,t);
}

void skipcomment() //Function to skip over the comment statements in the file.
{ ch=getc(fp);
if(ch==‘/’) //Checking single line comments
{
while((ch=getc(fp))!=‘\n’);
} else if(ch==‘*’) //Checking multiple line comments.
{ while(f==0) { ch=getc(fp); if(ch==‘*’)
{ c=getc(fp); if(c==‘/’) f=1;
} } f=0; }
}

INPUT FILE: iplex.c


#include<stdio.h> #include<conio.h> void main() { clrscr(); printf(“Welcome\n”); getch(); }

CMR College of Engineering & Technology


19

You might also like