CD File.
CD File.
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.
OUTCOMES:
Upon the completion of Compiler Design practical course, the student will be able to:
1. Understand the working of lex and yacc compiler for debugging of programs.
2. Understand and define the role of lexical analyzer, use of regular expression and transition diagrams.
3. Understand and use Context free grammar, and parse tree construction.
4. Learn & use the new tools and technologies used for designing a compiler.
5. Develop program for solving parser problems.
6. Learn how to write programs that execute faster.
3
Introduction of Compiler Design
Compiler is a software which converts a program written in high level language (Source Language)
to low level language (Object/Target/Machine 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 compiler is running.
Phases of a Compiler –
There are 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.
4
Analysis Phase – An semantic tree representation is created from the give source code:
1. Lexical Analyzer
2. Syntax Analyzer
3. Semantic Analyzer
Lexical analyzer divides the program into “tokens”, Syntax analyzer recognizes “sentences” in the
program using syntax of language and Semantic analyzer checks static semantics of each
construct.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[5][10]={"printf","scanf","if","else","break"}; char
str[10];
int i,flag;
clrscr();
for(i=0;i<strlen(str);i++)
{
if(strcmp(str,a[i])==0)
{
flag=1;
break;
}
else
flag=0;
}
6
if(flag==1)
puts("Keyword");
else
puts("String");
getch();
}
7
EXPERIMENT-3
AIM:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
static int count=0;
int isKeyword(char buffer[]){
char keywords[32][10] =
{"auto","break","case","char","const","continue","default","do","double","else","enum","extern","fl
oat","for","goto","if","int","long","register","return","short","signed","sizeof","static","struct","switc
h","typedef","union","unsigned","void","volatile","while"};
int i, flag = 0;
return flag;
}
int main(){
char ch, buffer[15] ;
FILE *fp;
int i,j=0;
fp = fopen("KESHAV3.C","r");
if(fp == NULL){
printf("error while opening the file\n");
exit(0);
8
}
if(isKeyword(buffer) == 1)
printf("%s is keyword\n", buffer);
}
printf("no of keywords= %d", count);
fclose(fp);
return 0;
}
9
EXPERIMENT-4
AIM:
PROGRAM:
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
static int count=0;
int main(){
char ch, buffer[15], operators[] = "+-*/%=";
FILE *fp;
int i;
clrscr();
fp = fopen("KESHAV3.C","r");
if(fp == NULL){
printf("error while opening the file\n");
exit(0);
}
}
printf("no of operators= %d", count);
fclose(fp);
return 0;
}
10
EXPERIMENT-5
AIM:
Count total occurrence of each character in a given file. [Taking file from user]
PROGRAM:
#include <stdio.h>
#include <string.h>
#include<conio.h>
int main ()
{
FILE * fp;
char string[100];
int c = 0, count[26] = { 0 }, x;
{ c=0;
while (string[c] != '\0')
{
/** Considering characters from 'a' to 'z' only and ignoring others. */
x = string[c] - 'a';
count[x]++;
11
c++;
}
}
12
EXPERIMENT-6
AIM:
Write a C program to insert, delete and display the entries in Symbol Table.
PROGRAM:
//Implementation of symbol table
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
void main()
{
int i=0,j=0,x=0,n;
void *p,*add[5];
char ch,srch,b[15],d[15],c;
printf("Expression terminated by $:");
while((c=getchar())!='$')
{
b[i]=c;
i++;
}
n=i-1;
printf("Given Expression:");
i=0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("\n Symbol Table\n");
printf("Symbol \t addr \t type");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c \t %d \t identifier\n",c,p);
x++;
j++;
13
}
else
{
ch=c;
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(ch);
add[x]=p;
d[x]=ch;
printf("\n %c \t %d \t operator\n",ch,p);
x++;
j++;
}}}}
14
EXPERIMENT-7
AIM:
PROGRAM:
/* Rule Section */
%%
%%
// driver code
int main()
{
printf("\nEnter Mobile Number : ");
yylex();
printf("\n");
return 0;
}
int yywrap()
{
}
15
2. Valid url
%%
.+ {printf("\nURL Invalid\n");}
%%
void main() {
yylex();
printf("\n");
}
int yywrap()
{
}
16
3. Valid identifier
%%
void main() {
yylex();
printf("\n");
}
int yywrap()
{
}
17
4. Valid date (dd/mm/yyyy)
%{
#include<stdio.h>
int i=0,yr=0,valid=0;
%}
%%
([0-2][0-9]|[3][0-1])\/((0(1|3|5|7|8))|(10|12))\/([1-2][0-9][0-9][-0-9]) {valid=1;}
([0-2][0-9]|30)\/((0(4|6|9))|11)\/([1-2][0-9][0-9][0-9]) {valid=1;}
([0-1][0-9]|2[0-8])\/02\/([1-2][0-9][0-9][0-9]) {valid=1;}
29\/02\/([1-2][0-9][0-9][0-9]) { while(yytext[i]!='/')i++;
i++;while(yytext[i]!='/')i++;i++;while(i<yyleng)yr=(10*yr)+(yytext[i++]-'0');
if(yr%4==0||(yr%100==0&&yr%400!=0))valid=1;}
%%
void main()
{
yyin=fopen("new","r");
yylex();
if(valid==1) printf("It is a valid date\n");
else printf("It is not a valid date\n");
}
int yywrap()
{
return 1;
}
18
5. Valid time(hh:mm:ss)
%{
#include<stdio.h>
int i=0,yr=0,valid=0;
%}
%%
([0-2][0-9]:[0-6][0-9]\:[0-6][0-9]) {printf("%s It is a valid time\n",yytext);}
%%
void main()
{
yyin=fopen("new","r");
yylex();
}
int yywrap()
{
return 1;
}
19
EXPERIMENT-8
AIM:
PROGRAM:
%{
#include<stdio.h>
int lines=0, words=0,s_letters=0,c_letters=0, num=0, spl_char=0,total=0;
%}
%%
\n { lines++; words++;}
[\t ' '] words++;
[A-Z] c_letters++;
[a-z] s_letters++;
[0-9] num++;
. spl_char++;
%%
void main(void)
{
FILE *fp;
char f[50];
printf("enterfile name \n");
scanf("%s",f);
yyin= fopen(f,"r");
yylex();
total=s_letters+c_letters+num+spl_char;
printf(" This File contains ...");
printf("\n\t%d lines", lines);
printf("\n\t%d words",words);
printf("\n\t%d small letters", s_letters);
printf("\n\t%d capital letters",c_letters);
printf("\n\t%d digits", num);
printf("\n\t%d special characters",spl_char);
printf("\n\tIn total %d characters.\n",total);
}
int yywrap()
{
return(1);
}
20
EXPERIMENT-9
AIM:
Write a lex program to count the no. of vowels and consonants in a C file.
PROGRAM:
%{
#include<stdio.h>
int vcount=0,ccount=0;
%}
%%
[a|i|e|o|u|E|A|I|O|U] {vcount++;}
[a-z A-Z (^a|i|e|o|u|E|A|I|O|U) ] {ccount++;}
%%
int main()
{
FILE *fp;
char f[50];
printf("enterfile name \n");
scanf("%s",f);
yyin= fopen(f,"r");
yylex();
printf("No. of Vowels :%d\n",vcount);
printf("No. of Consonants :%d\n",ccount);
return 0;
}
int yywrap()
{
}
21
EXPERIMENT-10
AIM:
Write a YACC program to recognize strings aaab,abbb using a^nb^n, where b>=0.
PROGRAM:
Gm.l
%{
#include "y.tab.h"
%}
%%
"a"|"A" {return A;}
"b"|"B" {return B;}
[ \t] {;}
\n {return 0;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}
Gm.y
%{
#include<stdio.h>
%}
%token A B
%%
stmt: S
;
S: A S B
|
;
%%
void main()
{
printf("enter \n");
yyparse();
printf("valid");
exit(0);
22
}
void yyerror()
{
printf("invalid ");
exit(0);
}
23
EXPERIMENT-11
AIM:
Write a YACC program to evaluate an arithmetic expression involving operators +,-,* and /.
PROGRAM:
Expr.l
%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);
return number;}
[\t] {;}
[\n] {return 0;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}
Expr.y
%{
#include<stdio.h>
int res=0;
%}
%token number
%left '+' '-'
%left '*' '/'
%%
stmt:expr {res=$$;}
;
expr:expr '+' expr {$$=$1+$3;}
|expr '-' expr {$$=$1-$3;}
|expr '*' expr {$$=$1*$3;}
|expr '/' expr {if($3==0)
exit(0);
else $$=$1/$3;}
24
|number
;
%%
void main()
{
printf(" enter expr\n");
yyparse();
printf("valid=%d",res);
exit(0);
}
void yyerror()
{
printf("invalid\n");
exit(0);
}
25
EXPERIMENT-12
AIM:
Write a YACC program to check validity of a strings abcd,aabbcd using grammar a^nb^nc^md^m,
where n , m>0
PROGRAM:
Grammer.y
%{
#include<stdio.h>
#include<stdlib.h>
int yyerror(char*);
int yylex();
%}
%token A B C D NEWLINE
%%
stmt: S NEWLINE { printf("valid\n");
return 1;
}
;
S: X Y
;
X: A X B
|
;
Y: C Y D
|
;
%%
extern FILE *yyin;
void main()
{
printf("enter \n");
do
{
yyparse();
}
while(!feof(yyin));
}
int yyerror(char* str)
{
26
printf("invalid ");
return 1;
}
Grammer.l
%{
#include"y.tab.h"
%}
%%
a|
A {return A;}
c|
C {return C;}
b|
B {return B;}
d|
D {return D;}
[ \t] {;}
"\n" {return NEWLINE;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}
27
EXPERIMENT-13
AIM:
PROGRAM:
#include<stdio.h>
#include<ctype.h>
void FIRST(char );
int count,n=0;
char prodn[10][10], first[10];
void main()
{
int i,choice;
char c,ch;
printf("How many productions ? :");
scanf("%d",&count);
printf("Enter %d productions epsilon= $ :\n\n",count);
for(i=0;i<count;i++)
scanf("%s%c",prodn[i],&ch);
do
{
n=0;
printf("Element :");
scanf("%c",&c);
FIRST(c);
printf("\n FIRST(%c)= { ",c);
for(i=0;i<n;i++)
printf("%c ",first[i]);
printf("}\n");
void FIRST(char c)
{
int j;
28
if(!(isupper(c)))first[n++]=c;
for(j=0;j<count;j++)
{
if(prodn[j][0]==c)
{
if(prodn[j][2]=='$') first[n++]='$';
else if(islower(prodn[j][2]))first[n++]=prodn[j][2];
else FIRST(prodn[j][2]);
}
}
}
29