0% found this document useful (0 votes)
85 views30 pages

CD File.

The document provides an index listing 13 experiments related to compiler design topics such as writing programs to count keywords, operators, and characters in a file, implement a symbol table, and use lex and yacc to validate inputs like mobile numbers, URLs, identifiers, dates, and times. The index includes a brief description of the objective and aim of each experiment to provide guidance on programming exercises for students to learn compiler design principles and tools.

Uploaded by

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

CD File.

The document provides an index listing 13 experiments related to compiler design topics such as writing programs to count keywords, operators, and characters in a file, implement a symbol table, and use lex and yacc to validate inputs like mobile numbers, URLs, identifiers, dates, and times. The index includes a brief description of the objective and aim of each experiment to provide guidance on programming exercises for students to learn compiler design principles and tools.

Uploaded by

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

INDEX

S.No Conte Page


. nt Number
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.
. EXPERIMENT-1
AIM:
Introduction: Objective, scope and outcome of the 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.

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.

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.
5
EXPERIMENT-2
AIM:

Program to find whether given string is keyword or not

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

puts("Enter the string :: ");


gets(str);

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:

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

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;

for(i = 0; i < 32; ++i){


if(strcmp(keywords[i], buffer) == 0){
flag = 1;
count++;
break;
}
}

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
}

while((ch = fgetc(fp)) != EOF){


if(isalnum(ch)){
buffer[j++] = ch;
}
else if((ch == ' ' || ch == '\n') && (j != 0)){
buffer[j] = '\0';
j = 0;

if(isKeyword(buffer) == 1)
printf("%s is keyword\n", buffer);

}
printf("no of keywords= %d", count);
fclose(fp);

return 0;
}

9
EXPERIMENT-4

AIM:

Count total no of operators in a file. [Taking file from user] #include<stdio.h>

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

while((ch = fgetc(fp)) != EOF){


for(i = 0; i < 6; ++i){
if(ch == operators[i]) {
printf("%c is operator\n", ch);
count++;
}
}

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

fp = fopen ("deepa.txt", "r");


clrscr();

while (fscanf (fp, "%s", string) != EOF)

{ c=0;
while (string[c] != '\0')
{

/** Considering characters from 'a' to 'z' only and ignoring others. */

if (string[c] >= 'a' && string[c] <= 'z')


{

x = string[c] - 'a';

count[x]++;

11
c++;

}
}

for (c = 0; c <26 ; c++)


printf ("%c occurs %d times in the string.\n", c + 'a', count[c]);
return 0;

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:

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)

PROGRAM:

1. 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;
}
int yywrap()
{
}

15
2. Valid url

%%

((http)|(ftp))s?:\/\/[a-zA-Z0-9]{2,}(\.[a-z]{2,})+(\/[a-zA-Z0-9+=?]*)* {printf("\nURL Valid\n");}

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

%%

void main() {

printf("\nEnter URL : ");

yylex();

printf("\n");

}
int yywrap()
{
}

16
3. Valid identifier

%%

^[a - z A - Z _][a - z A - Z 0 - 9 _] * printf("Valid Identifier");

// regex for invalid identifiers


^[^a - z A - Z _] printf("Invalid Identifier");
.;
%%

void main() {

printf("\nEnter Identifier: ");

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:

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

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:

Write a C program to find first of any grammar.

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

printf("press 1 to continue : ");


scanf("%d%c",&choice,&ch);
}
while(choice==1);
}

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

You might also like