0% found this document useful (0 votes)
6 views26 pages

3025 CD

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)
6 views26 pages

3025 CD

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

MARWADI UNIVERSITY

DEPARTMENT OF COMPUTER ENGINEERING


CLASS: TC5 BATCH: A

COMPILER DESIGN
(01CE0714)

2024-2025

STUDENT LAB MANUAL

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

INDEX
Sr.
Title Date Grade Sign
No.
Write a C Program to remove Left Recursion
1
from grammar
Write a C Program to remove Left Factoring
2 from grammar
Write a C program to implement finite
3 automata and string validation.
Prepare report for Lex and install Lex on
4 Linux/Windows
(a) WALEx Program to count words,
characters, lines, Vowels and consonants from
5 given input
(b) WALEx Program to generate string which
is ending with zeros.
(a) WALex Program to generate Histogram of
words
6
(b) WALex Program to remove single or multi
line comments from C program.
WALex Program to check weather given
7
statement is compound or simple.
WALex Program to extract HTML tags from
8 .html file.
Write a C Program to compute FIRST Set of
9 the given grammar
Write a C Program to compute FOLLOW Set
10 of the given grammar
Write a C Program to implement Operator
11 precedence parser
Write a C Program for constructing LL (1)
12
parsing
13 Write a C program to implement SLR parsing
Prepare a report on YACC and generate
14 Calculator Program using
YACC.

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Practical 1
Title: Write a C Program to remove Left Recursion from the grammar

Hint : A Grammar G (V, T, P, S) is left recursive if it has a production in the form.

A → A α |β.

The above Grammar is left recursive because the left of production is occurring at
a first position on the right side of

Solution: It can eliminate left recursion by replacing a pair of production with

A → βA′

A → αA′|

Program :

#include<stdio.h>
#include<string.h>
#define SIZE 10

int main() {
char non_terminal;
char beta, alpha;
int num;
char production[10][SIZE];
int index = 3; /* starting of the string following "->" */

printf("Enter Number of Production: ");


scanf("%d", &num);
printf("Enter the grammar as E->E-A:\n");

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

for (int i = 0; i < num; i++) {


scanf("%s", production[i]);
}

for (int i = 0; i < num; i++) {


printf("\nGRAMMAR: %s", production[i]);
non_terminal = production[i][0];

if (non_terminal == production[i][index]) {
alpha = production[i][index + 1];
printf(" is left recursive.\n");

while (production[i][index] != 0 && production[i][index] != '|') {


index++;
}

if (production[i][index] != 0) {
beta = production[i][index + 1];
printf("Grammar without left recursion:\n");
printf("%c->%c%c\'", non_terminal, beta, non_terminal);
printf("\n%c\'->%c%c\'|E\n", non_terminal, alpha, non_terminal);
} else {
printf(" can't be reduced\n");
}
} else {
printf(" is not left recursive.\n");
}

index = 3;
}

return 0;
}

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Output:

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Practical 2
Title: Write a C Program to remove Left Factoring from the grammar

Hint :
For example, consider the grammar:

A→abb∣acc|asx

This grammar has a common prefix

ab in its production rules. To eliminate this common prefix, we rewrite the


grammar as:

A→aX
X→bb∣cc∣asx

Program:
#include <stdio.h>
#include <string.h>

int main() {
char gram[100];
char part1[50], part2[50];
char modifiedGram[50], newGram[50];
int i, j = 0, k = 0, pos;

printf("Enter Production : A->");


fgets(gram, sizeof(gram), stdin);

for (i = 0; gram[i] != '|'; i++, j++)


part1[j] = gram[i];
part1[j] = '\0';

for (j = ++i, i = 0; gram[j] != '\0'; j++, i++)


part2[i] = gram[j];
part2[i] = '\0';

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

for (i = 0; i < strlen(part1) && i < strlen(part2); i++) {


if (part1[i] == part2[i]) {
modifiedGram[k] = part1[i];
k++;
pos = i + 1;
} else {
break;
}
}

modifiedGram[k] = 'X';
modifiedGram[++k] = '\0';
modifiedGram[j] = '\0';

strcpy(newGram, "");
strcat(newGram, part1 + pos);
strcat(newGram, "|");
strcat(newGram, part2 + pos);

// Print the modified grammar


printf("\nGrammar Without Left Factoring : \n");
printf(" A->%s", modifiedGram);
printf("\n X->%s\n", newGram);

return 0;
}

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Output:

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Practical 3
Title: Write a C Program to remove Left Factoring from the grammar

Hint: Design deterministic finite automata (DFA) with Σ = {0, 1} that accepts the

languages ending with “01” over the characters {0, 1}.

Solution: The strings that are generated for a given language are as follows −

L={01,001,101,110001,1001,……….}

The minimum length of the string is 2, the number of states that the DFA

consists of for the given language is: 2+1 = 3 states

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Program:

#include <stdio.h>
#define MAX 100

int main() {
char str[MAX], f = 'a';
int i;

printf("Parth_Dhanani-92210103059\n");
printf("Enter the string to be checked: ");
scanf("%s", str);

for (i = 0; str[i] != '\0'; i++) {


switch (f) {
case 'a':
if (str[i] == '0')
f = 'b';
else if (str[i] == '1')
f = 'a';
break;
case 'b':
if (str[i] == '0')
f = 'b';
else if (str[i] == '1')
f = 'c';
break;
case 'c':
if (str[i] == '0')
f = 'b';
else if (str[i] == '1')
f = 'a';
break;
}
}

if (f == 'c')

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

printf("String is accepted\n");
else
printf("String is not accepted\n");

return 0;
}
Output:

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Experiment 4
Title A : To study about Lexical Analyzer Generator (LEX) and Flex (Fast
Lexical Analyzer).
● Description of LEX

Lex is a tool or a computer program that generates Lexical Analyzers (converts the
stream of characters into tokens). The Lex tool itself is a compiler. The Lex compiler
takes the input and transforms that input into input patterns. It is commonly used
with YACC(Yet Another Compiler Compiler). It was written by Mike Lesk and Eric
Schmidt.

Function of Lex

1. In the first step the source code which is in the Lex language having the file name
‘File.l’ gives as input to the Lex Compiler commonly known as Lex to get the output as
lex.yy.c.

2. After that, the output lex.yy.c will be used as input to the C compiler which gives the
output in the form of an ‘a.out’ file, and finally, the output file a.out will take the stream
of character and generates tokens as output.

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

● Structure of LEX Program

%{
Definition section
%}
%%
Rules section
%%
User Subroutine section

The Definition section is the place to define macros and import header files written in C.
It is also possible to write any C code here, which will be copied verbatim into the
generated source file. It is bracketed with %{ and %}.

The Rules section is the most important section; Each rule is made up of two parts: a
pattern and an action separated by whitespace. The lexer that lex generates will execute
the action when it recognizes the pattern. Patterns are simply regular expressions. When
the lexer sees some text in the input matching a given pattern, it executes the associated C
code. It is bracketed with %% & %%.

The User Subroutine section in which all the required procedures are defined. It
contains the main in which C statements and functions that are copied verbatim to the
generated source file. These statements presumably contain code called by the rules in the
rules section/.

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

● Predefined Functions and Variables of LEX

Name Function
int yylex(void) call to invoke lexer, returns token
char *yytext pointer to matched string
yyleng length of matched string
yylval value associated with token
wrapup, return 1 if done, 0 if not
int yywrap(void)
done
FILE *yyout output file
FILE *yyin input file
INITIAL initial start condition
BEGIN
switch start condition
condition
ECHO write matched string
● Description of FLEX
FLEX (fast lexical analyzer generator) is a tool/computer program for generating lexical
analyzers (scanners or lexers) written by Vern Paxson in C around 1987. It is used
together with Berkeley Yacc parser generator or GNU Bison parser generator. Flex and
Bison both are more flexible than Lex and Yacc and produces faster code.
Bison produces parser from the input file provided by the user. The function yylex() is
automatically generated by the flex when it is provided with a .l file and this yylex()
function is expected by parser to call to retrieve tokens from current/this token stream.

● Structure of FLEX Program

%{

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

// Definitions

%}

%%

Rules

%%

User code section

Definition Section: The definition section contains the declaration of variables, regular
definitions, manifest constants. In the definition section, text is enclosed in “%{
%}” brackets. Anything written in this brackets is copied directly to the file lex.yy.c

Rules Section: The rules section contains a series of rules in the form: pattern action and
pattern must be unintended and action begin on the same line in {} brackets. The rule
section is enclosed in “%% %%”.

User Code Section: This section contains C statements and additional functions. We can
also compile these functions separately and load with the lexical analyzer.

Installing Flex for (Lex

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Experiment 5
Title: (a)WALEx Program to count words, characters, lines, Vowels and
consonants from given input.

Program:

#%{
#include <stdio.h>
int ch=0, w=1, l=1, v=0, c=0;
%}

%%

[aeiouAEIOU] {v++;ch++;}
[a-zA-Z] {c++;ch++;}
[\t ]+ {w++;}
[\n] {l++;w++;}
.;

%%

void main ()
{
yyin = fopen("input.txt","r");
yylex();
printf("No. of Characters : %d",ch);
printf("\nNo. of Words : %d",w);
printf("\nNo. of Lines : %d",l);
printf("\nNo. of Vowels : %d",v);
printf("\nNo. of Consonants : %d",c);
}

int yywrap()
{
return 1;

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Text File: (File name : input.txt)

Hello hi

I am Flutter Developer

Output:

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Title: (b)WALEx Program to generate string which is ending with zeros.

Program:

%{

#include <stdio.h>

%}

%%

[0+1]*0 {printf("\nString Accepted");}

.* {printf("\nString Rejected");}

%%

void main ()

printf("Enter String :");

yylex();

printf("\nEnd of the Program");

int yywrap()

return 1;

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Output:

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Experiment 6
Title: ((a) WALex Program to generate Histogram of words

Program:

%{
#include<stdio.h>
#include<string.h>
char word[] = "Google";
int count = 0 ;
%}
%%
[a-zA-Z]+ { if(strcmp( yytext, word)==0)
count ++; }
.;
%%
int yywrap()
{
return 1;
}
int main()
{
extern FILE *yyin,*yyout;

yyin=fopen("r.txt","r");
yylex();
printf("The word '%s' appears %d times.\n", word, count);
}

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Text File: (File name : r.txt)

Google, a global technology giant, has become synonymous with innovation and
information. Whether you're using Google Search to find answers to your
questions, exploring new places on Google Maps, or collaborating with others
through Google Docs, the company's influence is undeniable. Google continues
to push the boundaries of technology with its developments in artificial
intelligence, cloud computing, and mobile operating systems like Android. By
integrating Google services into daily life, users worldwide benefit from the
seamless and efficient tools that Google consistently provides.

Output:

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Experiment 7
Title: WA Lex Program to check weather given statement is compound or simple.

Program:

%{
#include<stdio.h>
int is_simple=0;
%}

%%
[ \t]+[aA][nN][dD][ \t]+ { is_simple=1; }
[ \t]+[oO][rR][ \t]+ { is_simple=1; }
[ \t]+[bB][uU][tT][ \t]+ { is_simple=1; }
.'
%%

int yywrap()
{
return 1;
}

void main()
{
printf("enter the sentence : ");
yylex();
if(is_simple==0)
printf("Sentence is Simple\n");
else
printf("Sentence is Compound\n");
}

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Output:

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

Experiment 8
Title: WALex Program to extract HTML tags from .html file.

Program:

%{

#include <stdio.h>

extern FILE *yyin;

%}

%%

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

%%

int yywrap() {

return 1;

int main(int argc, char *argv[]) {

yyin = fopen("r.html", "r");

if (!yyin) {

perror("Failed to open file");

return 1;

Sanjana Rathod 92210103025


MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC5 BATCH: A

yylex();

fclose(yyin);

return 0;

HTML File: (File name : r.txt)

<!DOCTYPE html>
<html>
<body>

<h1>This is CD Practical-8</h1>
<p>THis practical is about to find HTML tages in html code</p>

</body>
</html>

Output:

Sanjana Rathod 92210103025

You might also like