0% found this document useful (0 votes)
30 views44 pages

Fhdrfyh

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)
30 views44 pages

Fhdrfyh

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

lOMoARcPSD|25566240

Cd 191 - lab manual

B.tech CSE (Parul University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Anish Kushwaha ([email protected])
lOMoARcPSD|25566240

FACULTY OF ENGINEERING AND TECHNOLOGY


BACHELOR OF TECHNOLOGY

COMPILER DESIGN (203105351)


6TH SEMESTER
COMPUTER SCIENCE DEPARTMENT

Laboratory Manual

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

CERTIFICATE

This is to certify that Mr. PRASHANT SRINIVAS DASARI with enrolment


no.190303105376 has successfully completed his/her laboratory
experiments in the COMPILER DESIGN (203105352) from the
department of Computer Engineering & Science during the academic
year 2021-2022.

Date of Submission:......................... Staff In charge: Prof……………….

Head Of Department: Dr………

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352

INDEX
Sr.n Experiment Title Page No Date of Date of Mark Sign
o Performance Assessment s
From To

1 Program to
implement Lexical
Analyzer.

2 Program to count
digits, vowels and
symbols in C.

3 Program to check
validation of
Username and
Password in C

4 Program to
implement
Predictive Parsing
LL(1) in C.

5 Program to
implement Recursive
Descent Parsing in C.

6 Program to
implement Operator
Precedence Parsing
in C.

7 Program to
implement LALR
Parsing in C.

8 To Study the Lexical


Analyzer
Generator(LEX) and
Flex(Fast Lexical
Analyzer)

190303105376 3 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
9 Implement the
following programs
using Lex. a. Create a
Lexer to take input
from a text file and
count no of
characters, no. of
lines & no. of words.
b. Write a Lex
program to count
the number of
vowels and
consonants in a
given input string.

10 Implement the
following programs
using Lex. a. Write a
Lex program to print
out all numbers from
the given file. b.
Write a Lex program
to print out all HTML
tags in a file. c. Write
a Lex program which
adds line numbers to
the given file and
displays the same
onto the standard
output.

190303105376 4 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352

PRACTICAL NO: 1
AIM: Program to implement Lexical Analyzer.

Theory: -Lexical Analysis is the very first phase in the compiler designing. A Lexer takes the
modified source code which is written in the form of sentences . In other words, it helps you to
convert a sequence of characters into a sequence of tokens. The lexical analyzer breaks this
syntax into a series of tokens. It removes any extra space or comment written in the source
code.

Programs that perform Lexical Analysis in compiler design are called lexical analyzers or lexers.
A lexer contains tokenizer or scanner. If the lexical analyzer detects that the token is invalid, it
generates an error. The role of Lexical Analyzer in compiler design is to read character streams
from the source code, check for legal tokens, and pass the data to the syntax analyzer when it
demands.

Code:-
#include<stdio.h>

#include<ctype.h>

#include<string.h>

#include<stdlib.h>

void keyw(char *p);

int i=0,id=0,kw=0,num=0,op=0,sp=0,ar=0,count=0,new_line=0;

char keys[32]
[10]={"auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for

190303105376 5 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
","goto","if","int","long","register","return","short","signed","sizeof","static","struct","switch","typedef","union","
unsigned","void","volatile","while"};

void main()

char ch,str[25],seps[20]=" \t\n,;(){}[]#\"<>",oper[]="!%^&*-+=~|.<>/?";

int j;

char fname[50];

FILE *f1;

f1 = fopen("Laxcode.txt","r");

if(f1==NULL)

printf("file not found");

exit(0);

while((ch=fgetc(f1))!=EOF)

for(j=0;j<=14;j++)

if(ch==oper[j])

printf("%c is an operator\n",ch);

op++;

count++;

str[i]='\0';

keyw(str);

190303105376 6 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
if(ch=='\n'){

new_line++;

for(j=0;j<=14;j++)

if(i==-1)

break;

if(ch==seps[j])

if(ch=='#')

while(ch!='>')

printf("%c",ch);

ch=fgetc(f1);

printf("%c is a header file\n",ch);

i=-1;

break;

if(ch=='"')

do

ch=fgetc(f1);

printf("%c",ch);

}while(ch!='"');

190303105376 7 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
printf("\b is an argument\n");

i=-1;

ar++;

count++;

break;

if(ch==',' || ch==';' || ch=='(' || ch==')' || ch=='{' || ch=='}' || ch=='[' || ch==']')

printf("%c is a Sepretor\n",ch);

sp++;

count++;

str[i]='\0';

keyw(str);

if(i!=-1)

str[i]=ch;

i++;

else

i=0;

printf("\n Keywords: %d\n Identifiers: %d\n Operators: %d\nNumbers:%d\nSepretor:%d\nArgument:


%d",kw,id,op,num,sp,ar);

printf("\nTotal number of Token:%d",count);

190303105376 8 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
printf("\n Number Of lines:%d",new_line);

void keyw(char *p)

int k,flag=0;

for(k=0;k<=31;k++)

if(strcmp(keys[k],p)==0)

printf("%s is a keyword\n",p);

kw++;

count++;

flag=1;

break;

if(flag==0)

if(isdigit(p[0]))

printf("%s is a number\n",p);

num++;

count++;

else

if(p[0]!='\0')

190303105376 9 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
{

printf("%s is an identifier\n",p);

id++;

count++;

i=-1;

Output:

Screenshot of output:

190303105376 10 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
PRACTICAL: 2
AIM: - Program to count digits, vowels and symbols in C.

Code: -
#include<stdio.h>

#include<string.h>

int main()

char str[100];

printf("Enter String: ");

fgets(str,100,stdin);

int l=strlen(str);

int i,v=0,c=0,d=0,s=0;

for(i=0;i<l-1;i++){

if('a'<=str[i] && str[i]<='z' || 'A'<=str[i] && str[i]<='Z'){

if(str[i]=='a' || str[i]=='A' || str[i]=='e' || str[i]=='E' || str[i]=='I' ||

str[i]=='i' || str[i]=='o' || str[i]=='O' || str[i]=='u' || str[i]=='U'){

v++;

else{

c++; }

else if('0'<=str[i] && str[i]<='9'){

d++;

190303105376 11 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
else{

s++;

printf("\nTotal Vowels : %d \nTotal Consonant : %d \nTotal Digits : %d \nTotal Special Characters :


%d",v,c,d,s);

printf("\n");

return 0;

Output:-

190303105376 12 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
Practical – 3
AIM: - Program to check validation of User Name and Password in C.

Code: -
#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main()

int flagA=1,i,usrlen,passlen;

char usr[20],pass[20];

printf("Enter Username : ");

fgets(usr,20,stdin);

usrlen=strlen(usr);

if(usrlen<=2){

printf("\nUsername length should be atleast 2\n");

int a=0,at=0,dot=0;

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

if('A'<=usr[i] && usr[i]<='Z'){

printf("Username should not contain capital letters.");

flagA=0;

break;

else if('a'<=usr[i] && usr[i]<='z'){

a++;

190303105376 13 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
}

else if(usr[i]=='@'){

at++;

else if(usr[i]=='.'){

dot++;

if(at==1 && dot>=1 && flagA==1){

printf("\nUsername is Valid :)");

else{

printf("\nNot a Valid username!!");

printf("\n\nEnter Password : ");

fgets(pass,20,stdin);

passlen = strlen(pass);

if(passlen<8){

printf("\nPassword length should be atleast 8\n");

exit(0);

int ca=0,sa=0,sp=0,d=0;

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

if('A'<=pass[i] && pass[i]<='Z'){

ca++;

else if('a'<=pass[i] && pass[i]<='z'){

190303105376 14 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
sa++;

else if('0'<=pass[i] && pass[i]<='9'){

d++;

else{

sp++;

if(ca>=1 && sa>=1 && sp>=1 && d>=1){

printf("\nPassword is Valid :)");

else{

printf("\nNot a valid password");

printf("\n");

return 0;

Output: -

190303105376 15 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
PRACTICAL-4

Aim : Program to implement Predictive Parsing LL(1) in C.

Theory:-
Predictive Parser :-
A predictive parser is a recursive descent parser with no backtracking or
backup. It is a top-down parser that does not require backtracking. At each step,
the choice of the rule to be expanded is made upon the next terminal symbol.
Code:-
#include<stdio.h>
#include<conio.h>
#include<string.h>
char prol[10][10]={"E","E'","E'","T","T'","T'","F","F"};
char pror[10][10]={"TE'","+TE'","@","FT'","*FT'","@","(E)","%"};
char prod[10][10]={"E->TE'","E'->+TE'","T->FT'","T->*F","F->(E)","F-
>%"};
char first[10][10]={"(%","+@","(%","*@","(%"};
char follow[10][10]={"$)","$)","+$)","+$)","*+$)"};
char table[5][6][10];
numr(char c)
{
switch(c)
{
case 'E': return 0;
case 'T': return 1;
case 'F': return 2;
case '+': return 0;
case '*': return 1;
case '(': return 2;
case ')': return 3;
case '%': return 4;
case '$': return 5;
}
return(2);
}
void main()
{ int i,j,k;
190303105376 16 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
// clrscr();
for(i=0;i<5;i++)
for(j=0;j<6;j++)
strcpy(table[i][j]," ");
printf("\nThe following is the predictive parsing table for the following
grammar:\n");
for(i=0;i<10;i++)
printf("%s\n",prod[i]);
printf("\nPredictive parsing table is\n");
fflush(stdin);
for(i=0;i<10;i++)
{
k=strlen(first[i]);
for(j=0;j<10;j++)
if(first[i][j]!='@')
strcpy(table[numr(prol[i][0])+1][numr(first[i][j])+1],prod[i]);
}
for(i=0;i<10;i++)
{if(strlen(pror[i])==1)
{if(pror[i][0]=='@')
{ k=strlen(follow[i]);
for(j=0;j<k;j++)
strcpy(table[numr(prol[i][0])+1][numr(follow[i][j])+1],prod[i]);
}}}
strcpy(table[0][0]," ");
strcpy(table[0][1],"+");
strcpy(table[0][2],"*");
strcpy(table[0][3],"(");
strcpy(table[0][4],")");
strcpy(table[0][5],"%");
strcpy(table[0][5],"$");
strcpy(table[1][0],"E");
strcpy(table[2][0],"T");
strcpy(table[3][0],"F");
printf("\n \n");
for(i=0;i<5;i++)
for(j=0;j<6;j++)

190303105376 17 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
{printf("%-10s",table[i][j]); if(j==5) printf("\n
--------------------------------- \n");
}
getch();
}
Output:

190303105376 18 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352

PRACTICAL-5
AIM: Program to implement Recursive Descent Parsing in C.

Theory:- Recursive descent is a top-down parsing technique that constructs the parse
tree from the top and the input is read from left to right. It uses procedures for every terminal
and non-terminal entity. This parsing technique recursively parses the input to make a parse
tree, which may or may not require back-tracking.

Program:
#include<stdio.h>

#include<string.h>

#include<ctype.h>

char input[10];

int i,error;

void S();

void A();

main()

{ i=0;

error=0;

printf("\nRecursive decent parsing for the followinggrammer\n"); printf("\nS->AA\nA->aA/b\n");

printf("Enter a String : ");

gets(input);

S();

if(strlen(input)==i&&error==0)

printf("\nAccepted..!!!\n");

else printf("\nRejected..!!!\n");

void S(){

190303105376 19 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
printf("S is parsing Now\n");

{ A();

A();

}}

void A(){

printf("A is parsing Now\n");

{ if(input[i]=='a')

printf("Terminal a is accepted\n");

{ i++;

A();

}}

else

if(input[i]=='b')

printf("Terminal b is accepted\n");

i++;

Output:

190303105376 20 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
Experiment No: 6
Aim: Program to implement Operator Precedence Parsing in C.
Program :
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char stack[20],ip[20],opt[10][10][1],ter[10];
int i,j,k,n,top=0,row,col;
int len;
for(i=0;i<10;i++)
{
stack[i]=NULL;
ip[i]=NULL;
for(j=0;j<10;j++)
{
opt[i][j][1]=NULL;
}
}
printf("Enter the no.of terminals:");
scanf("%d",&n);
printf("\nEnter the terminals:");
scanf("%s",ter);
printf("\nEnter the table values:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Enter the value for %c %c:",ter[i],ter[j]);
scanf("%s",opt[i][j]);
}
}
printf("\nOPERATOR PRECEDENCE TABLE:\n");
for(i=0;i<n;i++)
{
printf("\t%c",ter[i]);
}
printf("\n ");
printf("\n");
for(i=0;i<n;i++)
{
printf("\n%c |",ter[i]);
for(j=0;j<n;j++)
{
printf("\t%c",opt[i][j][0]);

190303105376 21 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
}
}
stack[top]='$';
printf("\n\nEnter the input string(append with $):");
scanf("%s",ip);
i=0;
printf("\nSTACK\t\t\tINPUT STRING\t\t\tACTION\n");
printf("\n%s\t\t\t%s\t\t\t",stack,ip);
len=strlen(ip);
while(i<=len)
{
for(k=0;k<n;k++)
{
if(stack[top]==ter[k])
row=k;
if(ip[i]==ter[k])
col=k;
}
if((stack[top]=='$')&&(ip[i]=='$'))
{
printf("String is ACCEPTED");
break;
}
else if((opt[row][col][0]=='<') ||(opt[row][col][0]=='='))
{
stack[++top]=opt[row][col][0];
stack[++top]=ip[i];
ip[i]=' ';
printf("Shift %c",ip[i]);
i++;
}
else
{
if(opt[row][col][0]=='>')
{
while(stack[top]!='<')
{
--top;
}
top=top-1;
printf("Reduce");
}
else
{
printf("\nString is not accepted");
break;
}

190303105376 22 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
}
printf("\n");
printf("%s\t\t\t%s\t\t\t",stack,ip);
}
getch();
}

Output:

190303105376 23 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
Experiment No: 7
Aim : Program to implement LALR Parsing in C.
Program :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void push(char *,int *,char);
char stacktop(char *);
void isproduct(char,char);
int ister(char);
int isnter(char);
int isstate(char);
void error();
void isreduce(char,char);
char pop(char *,int *);
void printt(char *,int *,char [],int);
void rep(char [],int);
struct action
{
char row[6][5];
};
const struct action A[12]={
{"sf","emp","emp","se","emp","emp"},
{"emp","sg","emp","emp","emp","acc"},
{"emp","rc","sh","emp","rc","rc"},
{"emp","re","re","emp","re","re"},
{"sf","emp","emp","se","emp","emp"},
{"emp","rg","rg","emp","rg","rg"},
{"sf","emp","emp","se","emp","emp"},
{"sf","emp","emp","se","emp","emp"},
{"emp","sg","emp","emp","sl","emp"},
{"emp","rb","sh","emp","rb","rb"},
{"emp","rb","rd","emp","rd","rd"},
{"emp","rf","rf","emp","rf","rf"}
};
struct gotol
{
char r[3][4];
};
const struct gotol G[12]={
{"b","c","d"},
{"emp","emp","emp"},
{"emp","emp","emp"},
{"emp","emp","emp"},
{"i","c","d"},

190303105376 24 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
{"emp","emp","emp"},
{"emp","j","d"},
{"emp","emp","k"},
{"emp","emp","emp"},
{"emp","emp","emp"},
};
char ter[6]={'i','+','*',')','(','$'};
char nter[3]={'E','T','F'};
char states[12]={'a','b','c','d','e','f','g','h','m','j','k','l'};
char stack[100];
int top=-1;
char temp[10];
struct grammar
{
char left;
char right[5];
};
const struct grammar rl[6]={
{'E',"e+T"},
{'E',"T"},
{'T',"T*F"},
{'T',"F"},
{'F',"(E)"},
{'F',"i"},
};
int main()
{
char inp[80],x,p,dl[80],y,bl='a';
int i=0,j,k,l,n,m,c,len;
printf(" Enter the input :");
scanf("%s",inp);
len=strlen(inp);
inp[len]='$';
inp[len+1]='\0';
push(stack,&top,bl);
printf("\n stack \t\t\t input");
printt(stack,&top,inp,i);
do
{
x=inp[i];
p=stacktop(stack);
isproduct(x,p);
if(strcmp(temp,"emp")==0)
error();
if(strcmp(temp,"acc")==0)
break;

190303105376 25 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
else
{
if(temp[0]=='s')
{
push(stack,&top,inp[i]);
push(stack,&top,temp[1]);
i++;
}
else
{
if(temp[0]=='r')
{
j=isstate(temp[1]);
strcpy(temp,rl[j-2].right);
dl[0]=rl[j-2].left;
dl[1]='\0';
n=strlen(temp);
for(k=0;k<2*n;k++)
pop(stack,&top);
for(m=0;dl[m]!='\0';m++)
push(stack,&top,dl[m]);
l=top;
y=stack[l-1];
isreduce(y,dl[0]);
for(m=0;temp[m]!='\0';m++)
push(stack,&top,temp[m]);
}
}
}
printt(stack,&top,inp,i);
}while(inp[i]!='\0');
if(strcmp(temp,"acc")==0)
printf(" \n accept the input ");
else
printf(" \n do not accept the input ");
getch();
}
void push(char *s,int *sp,char item)
{
if(*sp==100)
printf(" stack is full ");
else
{
*sp=*sp+1;
s[*sp]=item;
}

190303105376 26 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
}
char stacktop(char *s)
{
char i;
i=s[top];
return i;
}
void isproduct(char x,char p)
{
int k,l;
k=ister(x);
l=isstate(p);
strcpy(temp,A[l-1].row[k-1]);
}
int ister(char x)
{
int i;
for(i=0;i<6;i++)
if(x==ter[i])
return i+1;
return 0;
}
int isnter(char x)
{
int i;
for(i=0;i<3;i++)
if(x==nter[i])
return i+1;
return 0;
}
int isstate(char p)
{
int i;
for(i=0;i<12;i++)
if(p==states[i])
return i+1;
return 0;
}
void error()
{
printf(" error in the input ");
exit(0);
}
void isreduce(char x,char p)
{
int k,l;

190303105376 27 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
k=isstate(x);
l=isnter(p);
strcpy(temp,G[k-1].r[l-1]);
}
char pop(char *s,int *sp)
{
char item;
if(*sp==-1)
printf(" stack is empty ");
else
{
item=s[*sp];
*sp=*sp-1;
}
return item;
}
void printt(char *t,int *p,char inp[],int i)
{
int r;
printf("\n");
for(r=0;r<=*p;r++)
rep(t,r);
printf("\t\t\t");
for(r=i;inp[r]!='\0';r++)
printf("%c",inp[r]);
}
void rep(char t[],int r)
{
char c;
c=t[r];
switch(c)
{
case 'a': printf("0");
break;
case 'b': printf("1");
break;
case 'c': printf("2");
break;
case 'd': printf("3");
break;
case 'e': printf("4");
break;
case 'f': printf("5");
break;
case 'g': printf("6");
break;

190303105376 28 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
case 'h': printf("7");
break;
case 'm': printf("8");
break;
case 'j': printf("9");
break;
case 'k': printf("10");
break;
case 'l': printf("11");
break;
default :printf("%c",t[r]);
break;
}
}
OUTPUT:

190303105376 29 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
Experiment No: 8
Aim : To Study about Lexical Analyzer Generator (LEX) and Flex (Fast Lexical Analyzer)

Lex - A Lexical Analyzer Generator:-

Lex is a program generator designed for lexical processing of character input streams. It accepts
a high-level, problem oriented specification for character string matching, and produces a
program in a general purpose language which recognizes regular expressions. The regular
expressions are specified by the user in the source specifications given to Lex. The Lex written
code recognizes these expressions in an input stream and partitions the input stream into
strings matching the expressions.

The grammar in the above diagram is a text file you create with a text edtior. Yacc will read
your grammar and generate C code for a syntax analyzer or parser. The syntax analyzer uses
grammar rules that allow it to analyze tokens from the lexical analyzer and create a syntax tree.
The syntax tree imposes a hierarchical structure the tokens. For example, operator precedence
and associativity are apparent in the syntax tree. The next step, code generation, does a depth-
first Lexical Analyzer Syntax Analyzer a = b + c * d id1 = id2 + id3 * id4 = + * id1 source code
tokens syntax tree id2 id3 id4 load id3 mul id4 add id2 store id1 Code Generator generated
code Lex Yacc patterns grammar 5 walk of the syntax tree to generate code. Some compilers
produce machine code, while others, as shown above, output assembly language.

What is Flex?
Flex is a powerful, open source application framework which allows to build traditional
applications for browser, mobile and desktop using the same programming model, tool, and
codebase

190303105376 30 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
Flex provides FLEX SDK consisting of the Flex class library (ActionScript classes), the Flex
compilers, the debugger, the MXML and ActionScript programming languages, and other
utilities to build expressive and interactive rich internet applications (RIA)

Flex takes care of the user interface (UI) or the client-side functionality of a web application.
Server-side functionality dependent on server-side components written in a traditional scripting
language

How to use FLEX?


FLEX (Fast LEXical analyzer generator) is a tool for generating scanners. In stead of writing a
scanner from scratch, you only need to identify the vocabulary of a certain language (e.g.
Simple), write a specification of patterns using regular expressions (e.g. DIGIT [0-9]), and FLEX
will construct a scanner for you. FLEX is generally used in the manner depicted here:

First, FLEX reads a specification of a scanner either from an input file *.lex, or from standard
input, and it generates as output a C source file lex.yy.c. Then, lex.yy.c is compiled and linked
with the "-lfl" library to produce an executable a.out. Finally, a.out analyzes its input stream and
transforms it into a sequence of tokens.

.lex is in the form of pairs of regular expressions and C code. (sample1.lex, sample2.lex) lex.yy.c
defines a routine yylex() that uses the specification to recognize tokens. a.out is actually the
scanner!

How to Compile & Run LEX / YACC Programs on Windows ?


If you are installing Ubuntu (or any Linux based OS) on your system either through Virtual Box
or by making your system Multi-Bootable, just to execute your Lex & Yacc programs; then you
might be wasting your HDD space & your valuable time. You can easily skip this annoying
process and run your programs in Windows OS without any hassles.

Here's how you can do it:

190303105376 31 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
Installing Softwares:

1. Download Flex 2.5.4a

2. Download Bison 2.4.1

3. Download DevC++

4. Install Flex at "C:\GnuWin32"

5. Install Bison at "C:\GnuWin32"

6. Install DevC++ at "C:\Dev-Cpp"

7. Open Environment Variables.

8. Add "C:\GnuWin32\bin;C:\Dev-Cpp\bin;" to path.

Compilation & Execution of your Program:

1. Open Command prompt and switch to your working directory where you have stored your
lex file (".l") and yacc file (".y")

2. Let your lex and yacc files be "hello.l" and "hello.y". Now, follow the preceding steps to
compile and run your program.

1. For Compiling Lex file only:

1. flex hello.l

2. gcc lex.yy.c

2. For Compiling Lex & Yacc file both:

1. flex hello.l

2. bison -dy hello.y

3. gcc lex.yy.c y.tab.c

3. For Executing the Program

1. a.exe

EXAMPLE:- HELLO.L FILE

%{

190303105376 32 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
#include "y.tab.h"

int yyerror(char *errormsg);

%}

%%

("hi"|"oi")"\n"

{ return HI; }

("tchau"|"bye")"\n" { return BYE; }

. { yyerror("Unknown char"); }

%%

int main(void)

yyparse(); return 0;

int yywrap(void)

return 0;

int yyerror(char *errormsg)

fprintf(stderr, "%s\n", errormsg); exit(1);

190303105376 33 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
HELLO.Y FILE

%{

#include <stdio.h>

#include <stdlib.h> int yylex(void); int yyerror(const char *s);

%}

%token HI BYE

%%

program: hi bye ;

hi:

HI { printf("Hello World\n"); } ; bye:

BYE { printf("Bye World\n"); exit(0); } ;

Output :

190303105376 34 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
Experiment No: 9
Aim : A). Create a Lexer to take input from text file and count no of characters,
no. of lines & no. of words.

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

%%

main(void)

yyin= fopen("practical9.txt","r");

yylex();

total=s_letters+c_letters+num+spl_char;

printf(" This File contains ...");

printf("\n\t%d lines", lines);

190303105376 35 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
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);}

Practical9.txt FILE :

Hii

I'm Ram From Cse

Output :

190303105376 36 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
B). Write a Lex program to count number of vowels and consonants in a given
input string.

Program :

%{

int vow_count=0;

int const_count =0;

%}

%%

[aeiouAEIOU] {vow_count++;}

[a-zA-Z] {const_count++;}

%%

main()

yyin= fopen("practical8.txt","r");

yylex();

printf("The number of vowels are: %d\n",vow_count);

printf("The number of consonants are: %d\n",const_count);

return 0;

yywrap()

return 1;

190303105376 37 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
}

practical8.txt FILE

Hii

I'm Ram From Cse

Output :

190303105376 38 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352

Experiment No: 10
Aim : A). Write a Lex program to print out all numbers from the given file.

Program :

%{

#include<stdio.h>

int num=0;

%}

%%

[0-9] num++; ECHO;

%%

main(void)

yyin= fopen("practical10.txt","r");

yylex();

printf("\n\t%d digits", num);

int yywrap()

return(1);

190303105376 39 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
Practical10.txt FILE

23332

23

Sbfjehbcc

Output :

B). Write a Lex program to printout all HTML tags in file.

Program :

%{

#include<stdio.h>

%}

%%

\<[^>]*\> printf("%s\n",yytext);

.|\n;

%%

int yywrap()

190303105376 40 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
{

return 1;

int main()

yyin=fopen("practical10b.txt","r");

yylex();

return 0;

Practical10b.txt FILE

<html><body>

<h1> Hello</h1> <br>

</body>

</html>

Output:

190303105376 41 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
C). Write a Lex program which adds line numbers to the given file and display
the same onto the standard output.

Program :

%{

#include<stdio.h>

int line_number = 1;

%}

line .*\n

%%

{line} { printf("%d %s", line_number++, yytext); }

%%

int yywrap(){}

int main()

extern FILE *yyin;

yyin=fopen("add.txt","r");

if(yyin==NULL){

printf("File Not Found");

yylex();

return 0;

Add.txt FILE

190303105376 42 | Page

Downloaded by Anish Kushwaha ([email protected])


lOMoARcPSD|25566240

Faculty of Engineering
&Technology
Subject Name: COMPILER
DESIGN
Subject Code: 203105352
#include<stdio.h>

int main()

int a=10,b=20;

int c=a+b;

printf("Addition of a and b is:%d",c);

return 0;

Output:

190303105376 43 | Page

Downloaded by Anish Kushwaha ([email protected])

You might also like