0% found this document useful (0 votes)
135 views133 pages

Compiler Design Practical File Overview

This practical file on Compiler Design outlines various experiments and concepts related to compiler functionality, including the differences between compilers and interpreters, and the phases of compilation such as lexical analysis, syntax analysis, and code generation. It includes detailed descriptions of implementing different types of parsers and a lexical analyzer using C programming. The document serves as a partial fulfillment for a Bachelor of Engineering degree in Computer Science and Engineering.

Uploaded by

gwagon620
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)
135 views133 pages

Compiler Design Practical File Overview

This practical file on Compiler Design outlines various experiments and concepts related to compiler functionality, including the differences between compilers and interpreters, and the phases of compilation such as lexical analysis, syntax analysis, and code generation. It includes detailed descriptions of implementing different types of parsers and a lexical analyzer using C programming. The document serves as a partial fulfillment for a Bachelor of Engineering degree in Computer Science and Engineering.

Uploaded by

gwagon620
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

Practical File

on

Compiler Design
A Practical file submitted in partial fulfillment of
the requirements for the award of

Bachelor of Engineering
IN
COMPUTER SCIENCE AND ENGINEERING

Submitted by

Ashmeet Kaur
(Roll no: LCO17365)

Under the supervision of


( Dr. Gulshan Goyal , Assistant Professor)

CHANDIGARH COLLEGE OF ENGINEERING AND TECHNOLOGY

(DEGREE WING)
Government Institute under Chandigarh (UT) Administration, Affiliated to Panjab
University , Chandigarh
Sector-26, Chandigarh. PIN-160019
Jan-June, 2020
Table of Content

PAGE
S. NO. EXPERIMENT DATE REMARK
NO.

Introduction of Compiler Design and


1 Define Translator or Difference between 01 - 13
Compiler and Interpreter

Implementation a program to design a


DFA using three categories: Prefix,
2 14 - 29
Substring, Suffix and also recognised the
string.

To construct a program which finds out


3 the comments from an input program. 30 - 34

Program to construct a Lexical Analyser


4 using C 35 - 41

To input Context Free grammar and


5 42 - 48
process string.

To construct a Program to implement


6 49 - 54
Shift Reduce Parser using C.

To construct a Program to implementa-


7 55 - 63
tion of LL Parser using C.

To construct a Program to implementa-


8 tion of SLR Parser using C. 64 - 81

To construct a Program to implementa-


9 tion of CLR Parser using C. 82 - 105

To construct a Program to implementa-


10 tion of LALR Parser using C. 106 - 129
Table of Figures

FIGURE NO NAME OF FIGURE PAGE NO


1.1 Block diagram of basic compiler 01
1.2 Diagram for single pass compiler 01
1.3 Diagram representing multi pass compiler 02
1.4 Compiler 03
1.5 Interpreter 04
1.6 Block diagram of compiler phases 06
1.7 Example of Syntax Analyzer 08
1.8 Example of Semantic Analyzer 08
2.1 Algo for implementation DFA 14
2.2 Implementation for DFA 15
2.3 With option 1 string accepted 26
2.4 With option 1 string rejected 26
2.5 With option 2 string accepted 27
2.6 With option 2 string rejected 27
2.7 With option 3 string accepted 28
2.8 With option 3 string accepted 28
3.1 Algo for Find out the comments 30
3.2 Flowchart for find out the comments 31
3.3 Output for showing final results 33
4.1 Basic model for lexical Analyser 35
4.2 Algo for lexical Analyser 36
4.3 Flowchart for lexical Analyser 36
4.4 Final Result for lexical Analyser 40
5.1 Logic 42
5.2 Algo for input grammer 43
5.3 Flowchart for input grammer 43
5.4 Output Input grammer 47
6.1 Algo for implement shift reduce parser 49
6.2 Flowchart for implementation of shift 51
reduce parser
6.3 Output of shift reduce parser 54
7.1 Algo for implement LL parser 55
7.2 Flowchart for implementation of LL 56
parser
7.3 Output for the when the given grammer 62
is LL
7.4 Output for the when the given grammer is 62
LL
8.1 Algo for implementation SLR parser 64
8.2 Flowchart for implementation of SLR 65
parser
8.3 Output for the when the given grammer 78
is SLR
8.4 Output for the when the given grammer is 79
SLR
8.5 Output for the when the given grammer 80
is SLR
9.1 Algo for implementation of CLR Parser 82
9.2 Flowchart for implementation of CLR 83
parser
9.3 The given grammer is CLR 104
9.4 The given grammer is CLR 104
9.5 The given grammer is CLR 105
10.1 Algo for implement of LALR parser 106
10.2 Flowchart for implementation of LALR 107
parser
10.3 The given grammer is LALR 127
10.4 The given grammer is LALR 128
10.5 The given grammer is LALR 129

Table of Tables

TABLE NO NAME OF TABLE PAGE NO


1.1 Difference between compiler and 04
interpreter
1.2 Difference between Single pass and 05
Multi pass Compiler
1.3 Table for given lexemes and tokens 07
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

Experiment No- 1

Aim: Introduction of Compiler Design and Define Translator or Difference between


Compiler and Interpreter

Theory :-
A compiler translates the code written in one language to some other language without
changing the meaning of the program. It is also expected that a compiler should make
the target code efficient and optimized in terms of time and space. Compiler design
covers basic translation mechanism and error detection & recovery. Compiler is a
software which converts a program which is written in high level language(Source
Language) to low level language (Target).

Fig 1.1- Block diagram of basis compiler (ref: www.geeksforgeeks.com)

Single Pass Compiler

In single pass Compiler source code directly transforms into machine code. For
example, Pascal language.

Fig 1.2: Diagram representing single pass compiler. (ref: www.geeksforgeeks.com)

1|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Multi Pass Compilers

The multi pass compiler processes the source code or syntax tree of a program several
times. It divided a large program into multiple small programs and process them. It
develops multiple intermediate codes. All of these multi pass take the output of the
previous phase as an input. So it requires less memory.

Fig 1.3: Diagram representing multi pass compiler. (ref: www.geeksforgeeks.com)

FUNCTIONALITIES OF A COMPILER
1. Recognise legal programs
2. Generate correct code
3. Manage Storage of all variables and code
4. Agree on format for object code

ADVANTAGES AND DISADVANTAGES

ADVANTGAES
• Self Contained and Efficient
• Hardware Optimization

DISADVANTAGES
• Compiled programs are targeted towards a particular platform and hence are
platform dependent.
• Compile Times
• They are slower in execution than assembly programs.

2|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

TRANSLATORS: The most general term for a software code converting tool is
“translator.” A translator, in software programming terms, is a generic term that could
refer to a compiler, assembler, or interpreter; anything that converts higher level code
into another high-level code or lower-level, such as assembly language or machine
code. A program written in high-level language is called as source code. To convert the
source code into machine code, translators are needed.
A translator takes a program written in source language as input and converts it into a
program in target language as output. It also detects and reports the error during
translation.
Roles of translator are:
• Translating the high-level language program input into an equivalent machine
language program.
• Providing diagnostic messages wherever the programmer violates specification of the
high-level language program.

Different type of translators


The different types of translator are as follows:
1. Compiler
Compiler is a translator which is used to convert programs in high-level language to
low-level language. It translates the entire program and also reports the errors in source
program encountered during the translation.

Figure 1.4- Compiler (ref: www.ecomputernotes.com)

2. Interpreter
Interpreter is a translator which is used to convert programs in high-level language to
low-level language. Interpreter translates line by line and reports the error once it
encountered during the translation process. It directly executes the operations specified
in the source program when the input is given by the user. It gives better error
diagnostics than a compiler.

3|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Figure 1.5- Interpreter (courtesy- ecomputernotes.com)

DIFFERENCE BETWEEN COMPILER AND INTERPRETER

Table 1.1 - Difference between Compiler and Interpreter

4|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

DIFFERENCE BETWEEN SINGLE PASS AND MULTI PASS COMPLIER

Table 1.2 - Difference between Single pass and Multi pass Compiler

PHASES OF COMPLIER
The design of compiler is in several phases, each of which converts one form of source
program into another. Basically, we can say that the compilation process is a sequence
of various phases. Each phase takes input from its previous stage, has its own
representation of source program, and feeds its output to the next phase of the compiler.

5|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

The different phases of compiler are as follows:


1. Lexical analysis
2. Syntax analysis
3. Semantic analysis
4. Intermediate code generation
5. Code optimization
6. Code generation

Figure 1.6- Block diagram of compiler phases (courtesy- ecomputernotes.com)

1. LEXICAL ANALYZER
Lexical analysis is the first phase of compiler which is also termed as scanning. Source
program is scanned to read the stream of characters and those characters are grouped to
form a sequence called lexemes which produces token as output.
Token: Token is a sequence of characters that represent lexical unit, which matches
with the pattern, such as keywords, operators, identifiers etc.
Lexeme: Lexeme is instance of a token i.e., group of characters forming a token. ,
Pattern: Pattern describes the rule that the lexemes of a token takes. It is the structure
that must be matched by strings.
• Once a token is generated the corresponding entry is made in the symbol table.

6|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Input: stream of characters

Output: Token

Token Template: <token-name, attribute-value>

(eg.) c=a+b*5;

Lexemes and tokens

Lexemes Tokens

C identifier

= assignment symbol

A identifier

+ + (addition symbol)

B identifier

* * (multiplication symbol)

5 5 (number)

Table 1.3- Table for given Lexemes and tokens (courtesy- ecomputernotes.com)

Hence, <id, 1><=>< id, 2>< +><id, 3 >< * >< 5>

2. SYNTAX ANALYZER
Syntax analysis is the second phase of compiler which is also called as parsing. Parser
converts the tokens produced by lexical analyzer into a tree like representation called
parse tree. A parse tree describes the syntactic structure of the input.
Syntax tree is a compressed representation of the parse tree in which the operators
appear as interior nodes and the operands of the operator are the children of the node
for that operator.
Input: Tokens
Output: Syntax tree

7|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Figure 1.7 - Example of Syntax Analyzer (courtesy- ecomputernotes.com)

3. SEMANTIC ANALYZER
• Semantic analysis is the third phase of compiler.
• It checks for the semantic consistency.
• Type information is gathered and stored in symbol table or in syntax tree.
• Performs type checking.

Figure 1.8 - Example of Semantic Analyzer (courtesy- ecomputernotes.com)

4. INTERMEDIATE CODE GENERATOR


Intermediate code generation produces intermediate representations for the source
program which are of the following forms:
o Postfix notation
o Three address code
o Syntax tree
Intermediate code is converted to machine language using the last two phases which
are platform dependent. Intermediate code, it is same for every compiler out there, but
after that, it depends on the platform. To build a new compiler we don’t need to build
it from scratch. We can take the intermediate code from the already existing compiler
and build the last two parts.

8|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Most commonly used form is the three address code.

t1 = inttofloat (5)

t2 = id3* tl

t3 = id2 + t2

id1 = t3

Properties of intermediate code

• It should be easy to produce.

• It should be easy to translate into target program.

5. CODE OPTIMIZER
Code optimization phase gets the intermediate code as input and produces optimized
intermediate code as output. It results in faster running machine code. It can be done by
reducing the number of lines of code for a program.
This phase reduces the redundant code and attempts to improve the intermediate code
so that faster-running machine code will result. During the code optimization, the result
of the program is not affected.
To improve the code generation, the optimization involves
➢ Deduction and removal of dead code (unreachable code).
➢ Calculation of constants in expressions and terms.
➢ Collapsing of repeated expression into temporary string.
➢ Loop unrolling.
➢ Moving code outside the loop.
➢ Removal of unwanted temporary variables.

t1 = id3* 5.0

id1 = id2 + t1

6. CODE GENERATOR
Code generation is the final phase of a compiler. It gets input from code optimization
phase and produces the target code or object code as result. Intermediate instructions
are translated into a sequence of machine instructions that perform the same task.

9|P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

• The code generation involves


➢ Allocation of register and memory.
➢ Generation of correct references.
➢ Generation of correct data types.
➢ Generation of missing code.

LDF R2, id3

MULF R2, # 5.0

LDF R1, id2

ADDF R1, R2

STF id1, R1

All of the aforementioned phases involve the following tasks:


• Symbol table management.
• Error handling.

Symbol Table Management


Symbol table is used to store all the information about identifiers used in the program.
It is a data structure containing a record for each identifier, with fields for the attributes
of the identifier. It allows finding the record for each identifier quickly and to store or
retrieve data from that record.
Whenever an identifier is detected in any of the phases, it is stored in the symbol table.

Error Handling
Each phase can encounter errors. After detecting an error, a phase must handle the error
so that compilation can proceed.
• In lexical analysis, errors occur in separation of tokens.
• In syntax analysis, errors occur during construction of syntax tree.
• In semantic analysis, errors may occur at the following cases:
(i) When the compiler detects constructs that have right syntactic structure but no
meaning
(ii) During type conversion.
In code optimization, errors occur when the result is affected by the optimization.
In code generation, it shows error when code is missing etc.

10 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Error Encountered in Different Phases


Each phase can encounter errors.
After detecting an error, a phase must some how deal with the error, so that compilation
can proceed.
A pr ogram may have the following kinds of errors at various stages:
Lexical Errors
It includes incorrect or misspelled name of some identifier i.e., identifiers typed
incorrectly.
Syntactical Errors
It includes missing semicolon or unbalanced parenthesis.
Syntactic errors are handled by syntax analyzer (parser).
Semantical Errors
These errors are a result of incompatible value assignment.
The semantic errors that the semantic analyzer is expected to recognize are:
• Type mismatch.
• Undeclared variable.
• Reserved identifier misuse.
• Multiple declaration of variable in a scope.
• Accessing an out of scope variable.
• Actual and formal parameter mismatch.
Logical errors
These errors occur due to not reachable code-infinite loop.

EXAMPLE:

Source Code:

X= A + B * 100

Lexical Analyzer:

[id1,100] = [id2, 200] + [id3, 300] * [const, 400] (where id = identifier)

Syntax Analyzer:

Construction of Parsee Tree-

11 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

:=

id1 +

id2 *

id3 100

Intermediate Code Generator:

t1 = id3 * 100

t2 = id2 * t1

id1 = t3

Code Optimizer:

t1 = id3 * 100

id1 = id2 * t1

Target Code Generator:

MOVF id3, R1

MULF #100.0, R1

MOVF id2, R2

ADDF R1, R2

MOVF R2, id1

Frequently Asked Questions (FAQs)


Ques 1: Define Complier?
Ans 1: A Compiler is a computer program that transforms source code written in a
programming language into another computer language.

Ques 2: Define different phases of Compiler Design?


Ans 2: Complier Design has 6 types of phases
1. Lexical Analysis

12 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

2. Syntax Analysis
3. Semantic Analysis
4. Intermediate Code Generation
5. Code Optimization
6. Code Generation

Ques 3: What is use of symbol table?


Ans 3: Symbol table is used to store the variables used in the program.

Ques 4: Define Translator?


Ans 4: The most general term for a software code converting tool is “translator.” A
translator, in software programming terms, is a generic term that could refer to a
compiler, assembler, or interpreter; anything that converts higher level code into
another high-level code or lower-level, such as assembly language or machine code.

Ques 5: Difference between Compiler and Interpreter?


Ans 5: Compiler:- Performs the translation of a program as a whole. The Execution
of Compiler is Fast as compare to Interpreter. And also required more memory.
Interpreter:- Performs Statement by Statement translation. In Interpreter the execution
is slower than compiler. Less requirement of Memory.

13 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

Experiment No. 2

Aim :- Implementation a program to design a DFA using three categories: Prefix,


Substring, Suffix and also recognised the string.

Input:- Select the category


1. Prefix
2. Substring
3. Suffux

Expected\Required Output:- Is string is accepted or rejected with transition


table.

Algorithm:

Input:- Select one the option which you want to implement DFA
Output:- String is accepted or rejected with transition table
Begin
1. Input your choice for selecting a particular DFA among the ones provided.
2. Enter a string composed of the symbols for any input variables.
3. Traverse the string character by character to perform transitions.
4. Transition Table created when input variables or number of states or apply
category to perform for process.
5. Check if the last state reached is final state and display message of acceptance or
rejection.
6. If user wants to perform another test case, then repeat from step 1.

End

Algorithm 2.1 – “Implementation for DFA”

14 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Flowchart:

Figure 2.2 – “Implementation for DFA”

Source Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 100

void ending_with();
void starting_with();
void substring();

15 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

void string_processing();
int strcomp();
void display();
int y,an,qn,state,t[MAX][MAX];
char q[MAX],a[MAX],st[MAX],temp[MAX];
int main()
{
int i,j;
char choice;
y=0;
printf("ENTER THE NUMBER OF INPUT ALPHABETS:-> ");
scanf("%d",&an);
printf("ENTER THE ALPHABETS:-> \n");
for(i=0;i<an;i++)
{
printf("a[%d] : ",i);
scanf(" %c",&a[i]);
}
while(1)
{
printf("\n-----------Enter The Category------------*");
printf("\n1. PREFIX\n2. SUBSTRING\n3. SUFFIX\n4. EXIT\n");
printf("CATEGORY WHICH YOU WANT TO PERFORM PLZZ SELECT:-> ");
scanf("%d",&choice);
switch(choice)
{
case 1:{
starting_with();
display();
string_processing();
break;
}
case 2:{
substring();

16 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

display();
string_processing();
y=0;
break;
}
case 3:{
ending_with();
display();
string_processing();
break;
}
case 4:{
exit(0);
}
default:
{
printf("\n-----SELECT A VALID OPERATION.-----");
}}}
return 0;
}
void ending_with()
{
char curr_a;
int i,j,k,x;
printf("ENTER THE SUFFIX:-> ");
scanf("%s",&st);
x = strlen(st);
qn = x+1;
for(i=0;i<qn;i++)
{
q[i] = i;
}

for(i=0;i<qn;i++)

17 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

{
for(j=0;j<an;j++)
{
t[i][j] = 200;
}
}
for(i=0;i<x;i++)
{
curr_a = st[i];
for(j=0;j<an;j++)
{
if(curr_a==a[j])
break;
}
t[i][j] = i+1 ;
//printf(" %d",t[i][j]);
}
for(i=0;i<qn;i++)
{
for(j=0;j<i;j++)
{
temp[j] = st[j];
}
for(j=0;j<an;j++)
{
if(t[i][j]==200)
{
temp[i] = a[j];
temp[i+1] = '\0';
state = strcomp();

if(state==-1)
t[i][j] = 0;
else

18 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

t[i][j] = state;
}
}
}}
void starting_with()
{
char curr_a;
int i,j,k,x;
y=1;
printf("ENTER THE PREFIX:->");
scanf("%s",&st);
x = strlen(st);
qn = x+2;
for(i=0;i<qn;i++)
{
q[i] = i;
}
for(i=0;i<qn;i++)
{
for(j=0;j<an;j++)
{
t[i][j] = 200;
}
}
for(i=0;i<x;i++)
{
curr_a = st[i];
for(j=0;j<an;j++)
{
if(curr_a==a[j])
break;
}
t[i][j] = i+1 ;
//printf(" %d",t[i][j]);

19 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

}
for(i=0;i<qn;i++)
{
for(j=0;j<an;j++)
{
if(i<qn-2&&t[i][j]==200)
{
t[i][j] = qn-1;
}
else if(i==qn-2)
{
t[i][j] = i;
}
else if(i==qn-1)
{
t[i][j] = i;
}
}
}}
void substring()
{
char curr_a;
int i,j,k,x;
printf("ENTER THE SUBSTRING:-> ");
scanf("%s",&st);
x = strlen(st);
qn = x+1;
for(i=0;i<qn;i++)
{
q[i] = i;
}
for(i=0;i<qn;i++)
{
for(j=0;j<an;j++)

20 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

{
t[i][j] = 200;
}
}
for(i=0;i<x;i++)
{
curr_a = st[i];
for(j=0;j<an;j++)
{
if(curr_a==a[j])
break;
}
t[i][j] = i+1 ;
}
for(i=0;i<qn;i++)
{
for(j=0;j<i;j++)
{
temp[j] = st[j];
}
for(j=0;j<an;j++)
{
if(i==qn-1)
{
t[i][j] = qn-1;
}
else
{
if(t[i][j]==200)
{
temp[i] = a[j];
temp[i+1] = '\0';
state = strcomp();
if(state==-1)

21 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

t[i][j] = 0;
else
t[i][j] = state;
}
}
}
}
}
int strcomp()
{
int l1, l2, i=0, j=0, k, res=-1, f;
l1 = strlen(st);
l2 = strlen(temp);
for(i=0;i<l2;i++)
{
j = i;
k = 0;
f = 1;
while(k<l1 && j<l2)
{
if(st[k]!=temp[j])
{
f=0;
break;
}
k++;
j++;
}
if(f && j>=l2)
{
res = l2-i;
break;
}
}

22 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

// printf(" %d",res);
return res;
}
void display()
{
int i,j;
printf("\nTRANSITION TABLE :->\n\n");
for(i=0;i<=qn+1;i++)
{
for(j=0;j<=an;j++)
{
if(i==0&&j==0)
{
printf(" Q\\E |");
}
else if(i==0&&j!=0)
{
printf(" %c",a[j-1]);
}
else if(i==1)
{
printf("\n--------------------------------------");
break;
}
else if(i!=0&&i!=1&&j==0)
{
if(i-2 == 0 )
{
printf("\n ->q%d |",i-2);
}
else if(y==1&&i-2==qn-2)
{
printf("\n q%d* |",qn-2);
}

23 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

else if(i-2==qn-1&&y==1)
{
printf("\n #q%d |",qn-1);
}
else if(i-2==qn-1&&y!=1)
{
printf("\n q%d* |",qn-1);
}
else
{
printf("\n q%d |",i-2);
}
}
else
{
printf(" q%d",t[i-2][j-1]);
}
}
}
printf("\n\n :\nQ - state\nE - input alphabet\n-> - initial state\n* - final state");
if(y==1)
{
printf("\n# - Dead state )");
}
else
{
printf(" )");
}
}
void string_processing()
{
int i,j,x,curr_q,index,final;
char ch,curr_a,str[MAX];
do

24 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

{
printf("\n\nENTER THE STRING TO BE PROCESSED :-> ");
scanf("%s",&str);
x = strlen(str);
curr_q = 0;
printf("\nSTRING PROCESSING :->\n\n");
for(i=0;i<x;i++)
{
curr_a = str[i];
for(j=0;j<an;j++)
{
if(curr_a==a[j]){
index = j;
}
}
printf("d(q%d, %c) ->",curr_q,a[index]);
curr_q = t[curr_q][index] ;
printf("q%d\n",curr_q);
}
if(y==1)
final = qn-2;
else
final = qn-1;
if(curr_q==final){
printf("\n\nSince q%d belongs to final state,\nString is Accepted.",curr_q);
}
else{
printf("\n\nSince q%d does not belongs to final state,\nString is Rejected.",curr_q);
}
printf("\n\nIF YOU WANT TO PROCESS ANOTHER STRING ? (y/n) : ");
scanf(" %c",&ch);
}while(ch != 'n');
}

25 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Output:-
1. String Accepted using Prefix:

Figure 2.3 – “String accepted using Prefix”

2. String Rejected using Prefix

Figure 2.4 – “String rejected using Prefix”

26 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

3. String Accepted using Substring

Figure2.5 – “String Accepted using Substring”

4. String Rejected using Substring

Figure 2.6 – “String rejected using Substring”

27 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

5. String Accepted using Suffix

Figure 2.7 – “String accepted using Suffix”

6. String Rejected using Suffix

Figure 2.8 – “String rejected using Suffix”

28 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Frequently Asked Questions (FAQs)


Ques 1: How to define different cases in DFA?
Ans 1: We can define different cases Like string starting with, ending with, or substring

Ques 2: What is DFA?


Ans 2: A deterministic finite automaton (DFA) is a 5-tuple (Q,Σ,δ,q0,F), where
i. Q is a finite set called the states,
ii.Σ is a finite set called the alphabet,
iii. δ: Q x Σ → Q is the transition function,
iv. q0 ∈ Q is the start state, and
v. F ⊆ Q is the set of final states

Ques 4: What is the Transition Function of DFA?


Ans 4: δ: Q x Σ → Q

Ques 5: What is the purpose of DFA in Compiler Design?


Ans 5: DFA is used to recognize the tokens during the lexical analysis phase of a
compiler.

Ques 6: What is the initial state?


Ans 6: Initial state of a DFA is the start state from where the string starts processing
on the automata.

Ques 7: What is the Final state?


Ans 7: A final state is a state that marks the accepted string on a DFA if the processing
on completion halts at the final state.

Ques 8: What is the Dead state?


Ans8: Dead state is a state from where we cannot exit once entered i.e. there is no
transition out of dead state for any input character. Every transition leads to dead state.

Ques 9: Can a DFA has more than one final state?


Ans 9: Yes, a DFA can have more than one final states to mark acceptance of strings.

29 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

Experiment No. 3

Aim :- To construct a program which finds out the comments from an input
program.
Input :- Program in C language
Expected Output :- To Find the Number of Comments in the given Source code.

Theory
The following DFA is a lexical analyzer which is supposed to recognize comments.
The lexical analyzer will ignore the comment and goes back to the state one.
The C programming language has two kinds of comments, ones with a start and end
marker of the form /* comment */, and another one which starts off with two slashes, //,
and goes to the end of the line, like Perl comments. The /* */ kind are the original kind,
and the // kind were borrowed from C++..

Algorithm:

Input :- The program language is C

Output:- Find the number of comments in the given Souce code

Begin

1. Input the C code to be checked.


2. Process Line by Line comment Tag is encountered.
3. Check if it is a single-line comment or multi-line comment, and increment the
corresponding variable and total number of comments.
4. If no line left to be processed, then print the variables.
End

Algorithm 3.1 – “Find out the comments”

30 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Flowchart:

Figure 3.2 – “Flowchart for find out the comments”

Source Code:
#include<stdio.h>

#include<conio.h>

#include<string.h>

int main(){

int i,single_line,multi_line;

char a[10000];

31 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

single_line=0;

multi_line=0;

i=0;

printf("Enter the code : \n");

scanf("%[^\t]s",a);

while(a[i]!='\0'){

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

i++;

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

single_line++;

i++;

while(a[i]!='\n'){

if(a[i]=='\0')

break;

i++;

}}

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

multi_line++;

i++;

while(a[i]!='*' && a[i+1]!='/'){

if(a[i]=='\0')

break;

i++;

}}}

32 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

else{

i++;

}}

printf("Results:\n");

printf("Total comments\t: %d\n", single_line+multi_line);

printf("Single-line \t: %d\n",single_line);

printf("Multi-line \t: %d",multi_line);

return 0;

Output:-

Figure 3.3 – Output for showing final results

33 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Frequently Asked Questions (FAQs)


Ques 1: What is Comment?
Ans 1: In computer programming, a comment is a programmer-readable explanation
in the source code of a computer program. They are added with the purpose of making
the source code easier for humans to understand, and are generally ignored by compilers
and interpreters.

Ques 2: Does Compiler Ignores Comment ?


Ans 2: Yes

Ques 3: What is Importance of Comment in program?


Ans 3: Comment are important for a large source code , it can define the different
different modules so the finding the error is simple.

Ques 4: Different types of Comment?


Ans 4: Complier has two types single line comments and multi line comments

34 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

PRACTICAL - 4
Aim :- Program to construct a Lexical Analyser using C
Input :- Any Program in C language can be scanned for any identifiers, Operators
Expected Output :- To Find Sequence of Tokens
Theory:-
Lexical analysis is the first phase of a compiler. It takes the modified source code from
language preprocessors that are written in the form of sentences. The lexical analyzer
breaks these syntaxes into a series of tokens, by removing any whitespace or comments
in the source code.
If the lexical analyzer finds a token invalid, it generates an error. The lexical analyzer
works closely with the syntax analyzer. It reads character streams from the source code,
checks for legal tokens, and passes the data to the syntax analyzer when it demands.

Figure 4.1 – “Basic model for lexical Analyser”

LEXEME:- A lexeme is a sequence of characters that are included in the source


program according to the matching pattern of a token. It is nothing but an instance of a
token.

TOKEN:-The token is a sequence of characters which represents a unit of information


in the source program.

PATTERN:- A pattern is a description which is used by the token. In the case of a


keyword which uses as a token, the pattern is a sequence of characters.

35 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Algorithm:
Input:- Program or source code in C language can be secured for any identifiers,
Operators
Output:- Find the sequence of Tokens
BEGIN
1)Input a code that is written in C language.
2)Divide the code into the lexemes.
3)Map the lexemes to the tokens.
4)Print the table consisting of lexemes and the corresponding tokens.
END

Algorithm 4.2 – “Algorithm for lexical Analyser”

Flowchart:-

Figure 4.3 – “Flowchart for Lexixcal Analyser”

36 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Source Code:-
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int buffer ,a=0,b=0,m=0,n=0,flag=0;
char str[100][100],type[100][100],token[100][100];
printf("~~~~~ENTER THE PROGRAM~~~~~\n");
printf("~~~~~WHEN THE PROGRAM IS FINISHES THEN ENTER END~~~~~\n");
while(buffer<1000)
{
scanf("%s",str[a]);
if(!strcmp(str[a],"end"))
break;
a++;
buffer++;
}
a=0;
while(strcmp(str[a],"end"))
{
b=0;
while(str[a][b]!='\0')
{
while(str[a][b]!=' '&&str[a][b]!=','&&str[a][b]!=';'&&str[a][b]!='\0')
{
token[m][n]=str[a][b];
n++;
b++;
flag=1;
}
if(flag==1)
{

37 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

m=m+1;
n=0;
}
if(str[a][b]==','||str[a][b]==';')
{
token[m][n]=str[a][b];
m=m+1;
b=b+1;
}
if(str[a][b]==' ')
b=b+1;
}
a=a+1;
}
a=0;
b=0;
while(strcmp(str[a],"end"))
{
if(!strcmp(token[a],"int")||!strcmp(token[a],"char")||!strcmp(token[a],"float")||!st
rcmp(token[a],"main")||!strcmp(token[a],"return")||!strcmp(token[a],"void"))
{
strcpy(type[a],"keywords");
a=a+1;
continue;
}
if(!strcmp(token[a],"=")||!strcmp(token[a],"+")||!strcmp(token[a],"-
")||!strcmp(token[a],",*")||!strcmp(token[a],"/"))
{
strcpy(type[a],"operators");
}
if(!strcmp(token[a],";")||!strcmp(token[a],","))
{
strcpy(type[a],"punctuation_mark");
}

38 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(token[a][b]>='a'&&token[a][b]<='z'||token[a][b]>='A'&&token[a][b]<='Z'||token[a]
[b]=='_')
{
strcpy(type[a],"identifier");
b=0;
}
if(token[a][b]>='0'&& token[a][b]<='9')
{
strcpy(type[a],"number");
b=0;
}
if(!strcmp(token[a],"{")||!strcmp(token[a],"}")||!strcmp(token[a],")")||!strcmp(token[a]
,"("))
{
strcpy(type[a],"delimiter");
}
a=a+1;
}
for(a=0;a<=m;a++)
{
printf("%d\t",a);
printf("%s\t",token[a]);
printf("%s\n",type[a]);
}
return(0);
}

39 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Output:-

Figure 4.4 – Final Result For Lexical Analyser

40 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Frequently Asked Questions (FAQs)


Ques 1: What is Lexical Analysis?
Ans 1: Lexical analysis is one in which the stream of characters making up thesource
program is read from left to right and grouped into tokens that are sequences of
characters having a collective meaning

Ques 2: What is a symbol table?


Ans 2: A symbol table is a data structure containing a record for each identifier, with
fields for the attributes of the identifier.

Ques 3: Define Lexemes and Tokens?


Ans 3:
Lexemes:- Lexemes are the words derived from the character input stream.
Tokens:- Tokens are lexemes mapped into a token-name and an attribute-value.

41 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

PRACTICAL - 5
Aim :- To input Context Free grammar and process string.
Input :- Input for the program will be the production rules of grammar and a string
for string verification.
Expected Output: Output of program will be grammar and status of string
verification.
Basic Methodology: Grammars are used to describe the syntax of a programming
language. It specifies the structure of expression and statements.
Definition :-A context free grammar G is defined by four tuples as G = (V, T, P, S)
Where, G – Grammar, V - Set of variables, T - Set of Terminals, P - Set of productions,
S - Start symbol.
It produces Context Free Language (CFL) which is defined as,

Figure 5.1 – Logic

Algorithm :-

Input: Production rules from user input.


Output: Grammar and status of string verification.
Begin
1. Ask user for no. of production rules.
2. After than enter production rules.
3. Print production rules.
4. Enter the string to be processed by grammar.
5. Create a stack to store the string to be processed.
6. Remove first character from string and store it in stack.
7. Then compare each character with the possibility of matching with production rule.
8. If the match is found, remove character from stack.
9. Concatenate the string with previously matched strings.

42 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

10.If all the characters are successfully matched then print string is accepted
otherwise print rejected.
End

Algorithm 5.2 – Algorithm for Input grammer

Flowchart:

Figure 5.3 – Flowchart for input grammer

43 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Source code:
#include<bits/stdc++.h>
using namespace std;

struct grammer{
char p[20];
char prod[20];
}g[10];

int main()
{
int i,stpos,j,k,l,m,o,p,f,r;
int np,tspos,cr;
cout<<"\nEnter Number of productions:";
cin>>np;
char sc,ts[10];
cout<<"\nEnter productions:\n";

for(i=0;i<np;i++)
{
cin>>ts;
strncpy(g[i].p,ts,1);
strcpy(g[i].prod,&ts[3]);
}

char ip[10];
cout<<"\nEnter Input:";
cin>>ip;
int lip=strlen(ip);
char stack[10];
stpos=0;
i=0;
//moving input

44 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

sc=ip[i];
stack[stpos]=sc;
i++;stpos++;
//cout<<"\n\nStack\t\tInput\t\tAction";
do
{
r=1;
while(r!=0)
{
cout<<"\n";
for(p=0;p<stpos;p++)
{
cout<<stack[p];
}
cout<<"\t\t";
for(p=i;p<lip;p++)
{
cout<<ip[p];
}
if(r==2)
{
cout<<"\t\tReduced";
}
else
{
cout<<"\t\tShifted";
}
r=0;
//try reducing
for(k=0;k<stpos;k++)
{
f=0;
for(l=0;l<10;l++)
{

45 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

ts[l]='\0';
}
tspos=0;
for(l=k;l<stpos;l++) //removing first caharcter
{
ts[tspos]=stack[l];
tspos++;
}
//now compare each possibility with production
for(m=0;m<np;m++)
{
cr = strcmp(ts,g[m].prod);
//if cr is zero then match is found
if(cr==0)
{
for(l=k;l<10;l++) //removing matched part from stack
{
stack[l]='\0';
stpos--;
}
stpos=k;
//concatinate the string
strcat(stack,g[m].p);
stpos++;
r=2;
}
}
}
}
//moving input
sc=ip[i];
stack[stpos]=sc;
i++;stpos++;
}while(strlen(stack)!=1 && stpos!=lip);

46 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(strlen(stack)==1)
{
cout<<"\n\n \t\t\tSTRING IS ACCEPTED\t\t\t";
}
else
cout<<"\n\n \t\t\tSTRING IS REJECTED\t\t\t";
return 0;
}
Output:

Figure 5.4 – Output input grammer

47 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Frequently Asked Questions (FAQs)


Ques 1: How many types of grammar are there in computation?

Ans 1: There are 4 types of grammar, type 0, type 1, type 2, type 3.

Ques 2: What are non-terminals?

Ans 2: They are syntactic variables that denote a set of strings.

Ques 3: What is a start symbol?

Ans 3: Start symbol is the head of the production stated first in the grammar.

Ques 4: What is relation between CFG and RE?

Ans 4: Every regular language is a context free language but reverse does not hold.

Ques 5: What is a type 2 grammar known?

Ans 5: Context free grammar. A context free grammar G is defined by four tuples as,

G=(V,T,P,S) Where, G – Grammar, V - Set of variables, T - Set of Terminals,


P - Set of productions, S - Start symbol.

48 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

PRACTICAL – 6
Aim :- To construct a Program to implement Shift Reduce Parser using C.
Input :- Input grammar production rules and string for processing.

Expected Output: Stack Implementation table.


Theory:- Shift Reduce parser attempts for the construction of parse in a similar
manner as done in bottom up parsing i.e. the parse tree is constructed from
leaves(bottom) to the root(up). A more general form of shift reduce parser is LR parser.
Basic Operations performed by shift reduce parser are:
• Shift: This involves moving of symbols from input buffer onto the stack.
• Reduce: If the handle appears on top of the stack then, its reduction by using
appropriate production rule is done i.e. RHS of production rule is popped out of
stack and LHS of production rule is pushed onto the stack.
• Accept: If only start symbol is present in the stack and the input buffer is empty
then, the parsing action is called accept. When accept action is obtained, it is
means successful parsing is done.
• Error: This is the situation in which the parser can neither perform shift action
nor reduce action and not even accept action.

Algorithm :-
Input: Input grammar production rules and string for processing.
Output: Display Stack Implementation table.
Begin
1. Get the input expression and store it in the input buffer.
2. Read the data from the input buffer one at the time.
3. Using stack and push & pop operation shift and reduce symbols with respect to
production rules available.
4. Continue the process till symbol shift and production rule reduce reaches the
start symbol.
5. Display the Stack Implementation table with corresponding Stack actions with
input symbols.

End

Algorithm 6.1 – Implement Shift Reduce Parser

49 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Flowchart:

Figure 6.2 – Implementation of Shift Reduce Parser

Source Code:
#include"stdio.h"

#include"stdlib.h"

#include"conio.h"

#include"string.h"

char ip_sym[15],stack[15];

int ip_ptr=0,st_ptr=0,len,i;

char temp[2],temp2[2];

char act[15];

void check();

50 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

main()

printf("\n~~~~~~~SHIFT REDUCE PARSER~~~~~~~~~\n");

printf("\n GRAMMER\n");

printf("\n E->E+E\n E->E/E");

printf("\n E->E*E\n E->a/b");

printf("\n\n Enter the input:");

gets(ip_sym);

printf("\n~~~~~~STACK IMPLEMENTATION TABLE~~~~~~\n");

printf("\n STACK\t\t INPUT\t\tACTION");

printf("\n _____\t\t_______\t\t______\n");

printf("\n $\t\t%s$\t\t--",ip_sym);

strcpy(act,"shift ");

temp[0]=ip_sym[ip_ptr];

temp[1]='\0';

strcat(act,temp);

len=strlen(ip_sym);

for(i=0;i<=len-1;i++)

stack[st_ptr]=ip_sym[ip_ptr];

stack[st_ptr+1]='\0';

ip_sym[ip_ptr]=' ';

ip_ptr++;

printf("\n $%s\t\t%s$\t\t%s",stack,ip_sym,act);

strcpy(act,"shift ");

temp[0]=ip_sym[ip_ptr];

51 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

temp[1]='\0';

strcat(act,temp);

check();

st_ptr++;

st_ptr++;

check();

void check()

int flag=0;

temp2[0]=stack[st_ptr];

temp2[1]='\0';

if((!strcmpi(temp2,"a"))||(!strcmpi(temp2,"b")))

stack[st_ptr]='E';

if(!strcmpi(temp2,"a"))

printf("\n $%s\t\t%s$\t\tE->a",stack, ip_sym);

else

printf("\n $%s\t\t%s$\t\tE->b",stack,ip_sym);

flag=1;

if((!strcmpi(temp2,"+"))||(strcmpi(temp2,"*"))||(!strcmpi(temp2,"/")))

flag=1;

52 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if((!strcmpi(stack,"E+E"))||(!strcmpi(stack,"E\E"))||(!strcmpi(stack,"E*E")))

strcpy(stack,"E");

st_ptr=0;

if(!strcmpi(stack,"E+E"))

printf("\n $%s\t\t%s$\t\tE->E+E",stack,ip_sym);

else

if(!strcmpi(stack,"E\E"))

printf("\n $%s\t\t %s$\t\tE->E\E",stack,ip_sym);

else

printf("\n $%s\t\t%s$\t\tE->E*E",stack,ip_sym);

flag=1;

if(!strcmpi(stack,"E")&&ip_ptr==len)

printf("\n $%s\t\t%s$\t\tACCEPT",stack,ip_sym);

getch();

exit(0);

if(flag==0)

printf("\n%s\t\t\t%s\t\t reject",stack,ip_sym);

exit(0);

return;

53 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Output:

Figure 6.3 – Output of Shift Reduce Parser

Frequently Asked Questions (FAQs)


Ques 1: What are different actions performed in Shift Reduce Parser?

Ans 1: Shift, Reduce, Action, Error.

Ques 2: What is shift reduce parser known as?

Ans 2: A Shift Reduce Parser is also known as Bottom Up parser.

54 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

PRACTICAL – 7
Aim :- To construct a Program to implementation of LL Parser using C.
Input :- Input grammar rules, first and follow of non-terminals.

Expected Output: Display Parsing table.


Theory:-In computer science, an LL parser (Left-to-right, Leftmost derivation) is
a top-down parser for a subset of context-free languages. It parses the input from Left
to right, performing Leftmost derivation of the sentence.An LL parser is called an
LL(k) parser if it uses ktokens of lookahead when parsing a sentence. A grammar is
called an LL(k) grammar if an LL(k) parser can be constructed from it. A formal
language is called an LL(k) language if it has an LL(k) grammar. An LL parser is called
an LL(*), or LL-regular, parser if it is not restricted to a finite number k of tokens of
lookahead, but can make parsing decisions by recognizing whether the following tokens
belong to a regular language.

Algorithm :-
Input: Input grammar rules, first and follow of non-terminals.
Output: Display Parsing table.
Begin
6. Generate FIRST and FOLLOW’s for all the non-terminals in the provided
grammar.
7. Now generate FIRST of right side of production rules.
8. The predictive parser makes use of one look ahead token.
a. LL stands for “Left to right parse, Leftmost derivation”
9. If k look ahead tokens are needed, then we say the grammar is LL(k).
a. For k > 1, the columns are the possible sequences of k tokens, and the
tables become large.

End

Algorithm 7.1 – Implement LL parser

55 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Flowchart:

Figure 7.2 – Implementation of LL parser

Source Code:
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
//usingnamespacestd;
int main()
{
char
pro[10][10],first[10][10],follow[10][10],nt[10],ter[10],res[10][10][10],temp[10];int
npro,noter=0,nont=0,i,j,k,flag=0,count[10][10],row,col,l,m,n,index;
for(i=0;i<10;i++)
{

56 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

for(j=0;j<10;j++)
{
count[i][j]=NULL;
for(k=0;k<10;k++)
{
res[i][j][k]=NULL;
}
}
}
printf("Enter the Number of productions which you want to enter :->");
scanf("%d",&npro);
printf("Enter the productions which you want to process :->");
for(i=0;i<npro;i++)
{
scanf("%s",pro[i]);
}
for(i=0;i<npro;i++)
{
flag=0;
for(j=0;j<nont;j++)
{
if(nt[j]==pro[i][0])
{
flag=1;
}
}
if(flag==0)
{
nt[nont]=pro[i][0];
nont++;
}
}
printf("\n--------------------Enter the FIRST values------------------\n");
for(i=0;i<nont;i++)

57 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

{
printf("FIRST value(%c) :-> ",nt[i]);
scanf("%s",first[i]);
}
printf("\n-------------------Enter the FOLLOW values------------------\n");
for(i=0;i<nont;i++)
{
printf("Follow value(%c) :->",nt[i]);
scanf("%s",follow[i]);
}
for(i=0;i<nont;i++)
{
flag=0;
for(j=0;j<strlen(first[i]);j++)
{
for(k=0;k<noter;k++)
{
if(ter[k]==first[i][j])
{
flag=1;
}
}
if(flag==0)
{
if(first[i][j]!='#')
{
ter[noter]=first[i][j];
noter++;
}
}
}
}
for(i=0;i<nont;i++)
{

58 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

flag=0;
for(j=0;j<strlen(follow[i]);j++)
{
for(k=0;k<noter;k++)
{
if(ter[k]==follow[i][j])
{
flag=1;
}
}
if(flag==0)
{
ter[noter]=follow[i][j];
noter++;
}}
}
for(i=0;i<nont;i++)
{
for(j=0;j<strlen(first[i]);j++)
{
flag=0;
if(first[i][j]=='#')
{
col=i;
for(m=0;m<strlen(follow[col]);m++)
{
for(l=0;l<noter;l++)
{
if(ter[l]==follow[col][m])
{
row=l;
}
}
temp[0]=nt[col];

59 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

temp[1]='-' ;
temp[2]='>';
temp[3]='#';
temp[4]='\0';
printf("temp %s",temp);
strcpy(res[col][row],temp);
count[col][row]+=1;
for(k=0;k<10;k++){
temp[k]=NULL;}}
}
else{
for(l=0;l<noter;l++)
{
if(ter[l]==first[i][j])
{
row=l;}
}
for(k=0;k<npro;k++){
if(nt[i]==pro[k][0])
{
col=i;
if((pro[k][3]==first[i][j])&&(pro[k][0]==nt[col]))
{
strcpy(res[col][row],pro[k]);
count[col][row]+=1;
}
else
{
if((isupper(pro[k][3]))&&(pro[k][0]==nt[col]))
{
flag=0;
for(m=0;m<nont;m++)
{
if(nt[m]==pro[k][3]){index=m;flag=1;}

60 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

}
if(flag==1){
for(m=0;m<strlen(first[index]);m++)
{if(first[i][j]==first[index][m])
{strcpy(res[col][row],pro[k]);
count[col][row]+=1;}
}}
}}}}}
}}
printf("LL1 Table\n\n");
flag=0;
for(i=0;i<noter;i++)
{
printf("\t%c",ter[i]);
}
for(j=0;j<nont;j++)
{
printf("\n\n%c",nt[j]);
for(k=0;k<noter;k++)
{
printf("\t%s",res[j][k]);
if(count[j][k]>1){flag=1;}
}
}
if(flag==1)
{printf("\n**********THE GIVEN GRAMMAR WHICH YOU WANT TO
PROCESS IS NOT LL**********");}
else
{printf("\n**********THE GIVEN GRAMMAR WHICH YOU WANT TO
PROCESS IS LL**********");}
getch();}

61 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Output:

Figure 7.3 – Output for when the given grammer is LL

Figure 7.4 – Output for when the given grammer is not LL

62 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Frequently Asked Questions (FAQs)


Ques 1: What is a LL parser?

Ans 1: An LL parser is a top-down parser for a subset of context-free languages. It


parses the input from Left to right, performing Leftmost derivation of the sentence.
An LL parser is called an LL(k) parser if it uses k tokens of lookahead when parsing a
sentence.

Ques 2: What are LL(0) and LR(0) parsers?

Ans: LL(0) parsers mean they process the token stream from Left to right, using
Leftmost derivation with no look ahead. LL(0) parsers build the parse tree from top to
bottom.

LR(0) parsers mean they process the token stream from Left to right, using Rightmost
derivation with zero look ahead. They build the parse tree from bottom to top.

63 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

PRACTICAL – 8
Aim :- To construct a Program to implementation of SLR Parser using C.
Input :- Insert input as grammar rules.

Expected Output: SLR Parsing Table and Display that the Grammar is SLR or Not.

Algorithm :-
Input: Insert input as grammar rules.
Output: SLR Parsing Table and Display that the Grammar is SLR or Not.

Begin
1. Given a language Grammar rules.
2. Build The Augmented Grammar
3. Construct the collection of LR(0) items sets
{I0, I1,…….., In} ) for Given grammar .
4. Build the GOTO table
5. Build The DFA related to the item sets
6. Calculate FIRST and FOLLOW to Build SLR Parsing Table
7. Few Keys Needed for Parsing table is:
a)If the item set contains a rule like {S’->S}
then enter Accept under $ column of this rule in the parsing table.

b)If the item Sets contains rules like {S->w.}


then enter its rule no in the parsing table using FOLLOW.
8. Complete the Parse table in this manner.

End

Algorithm 8.1 – Implement SLR parser

64 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Flowchart:

Figure 8.2 – Implementation of SLR parser

Source Code:
#include <stdio.h>
#include <string.h>
#include <conio.h>
char prod[100][100], term[100], non_term[100], action[100][100][100];
int term_len, non_term_len, first[100][100], follow[100][100], hash1[100],
no_of_prod, hash2[100], canonical[100][100][10], can_len, go_to[100][100]; void
calc_first(int k){

65 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

int j, flag=0, len, l, m, i;


if(hash1[k]) return;
hash1[k] = 1;
for(i=0;i<no_of_prod;i++){
if(prod[i][0]==non_term[k]){
flag = 0;
len = strlen(prod[i]);
for(j=3;j<len;j++){
if(!flag){
if(prod[i][j]>='A'&&prod[i][j]<='Z'){
for(l=0;l<non_term_len;l++){
if(non_term[l]==prod[i][j]) break;
}
flag = 1;
if(hash1[l]){
for(m=0;m<term_len;m++){
if(first[l][m]){
first[k][m] = 1;
if(term[m]=='^') flag=0;
}
}
}
else{
calc_first(l);
for(m=0;m<term_len;m++)
{
if(first[l][m]){
first[k][m] = 1;
if(term[m]=='^') flag=0;
}
}
}
}
else if(prod[i][j]!='|'){

66 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

for(l=0;l<term_len;l++){
if(term[l]==prod[i][j]) break;
}
first[k][l] = 1;
flag = 1;
}
}
else{
if(prod[i][j]=='|') flag=0;
}
}
}
}
}
void calc_follow(int k){
int i, len, j, l, flag=0, m;
if(hash2[k]) return;
hash2[k] = 1;
for(i=0;i<no_of_prod;i++){
len = strlen(prod[i]);
for(j=3;j<len;j++){
if(flag){
if(prod[i][j]>='A' && prod[i][j]<='Z'){
flag = 0;
for(l=0;l<non_term_len;l++){
if(non_term[l]==prod[i][j]) break;
}
if(l<non_term_len){
for(m=0;m<term_len;m++){
if(first[l][m]){
follow[k][m] = 1;
if(term[m]=='^') flag=1;
}
}

67 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

}
}
else{
for(l=0;l<term_len;l++)
{
if(term[l]==prod[i][j]) break;
}
if(l<term_len){
follow[k][l] = 1;
}
else{
if(prod[i][j]=='|'){
for(l=0;l<non_term_len;l++){
if(non_term[l]==prod[i][0]) break;
}
if(l<non_term_len){
calc_follow(l);
for(m=0;m<term_len;m++){
if(follow[l][m]) follow[k][m] = 1;
}
}
flag = 0;
}
}
flag=0;
}
}
if(prod[i][j]==non_term[k]){
flag = 1;
}
}
if(flag){
for(l=0;l<non_term_len;l++){
if(non_term[l]==prod[i][0]) break;

68 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

}
if(l<non_term_len){
calc_follow(l);
for(m=0;m<term_len;m++){
if(follow[l][m]) follow[k][m] = 1;
}
}
flag = 0;
}
}
}
void print(int in){
int i, j, len, k;
printf("I%d:\n", in);
for(i=0;i<10;i++){
if(canonical[in][no_of_prod-1][i]!=-1){
len = strlen(prod[no_of_prod-1]);
for(j=0;j<=len;j++){
if(j==canonical[in][no_of_prod-1][i]) printf(".");
printf("%c", prod[no_of_prod-1][j]);
}
puts("");
}
else break;
}
for(i=0;i<no_of_prod-1;i++){
for(k=0;k<10;k++){
if(canonical[in][i][k]!=-1){
len = strlen(prod[i]);
for(j=0;j<=len;j++){
if(j==canonical[in][i][k]) printf(".");
printf("%c", prod[i][j]);
}
puts("");

69 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

}
else break;
}
}
}
void closure(int arr[][10]){
long long i, j, flag=1, k, l;
char c;
for(i=0;i<10;i++){
if(arr[no_of_prod-1][i]!=-1){
c = prod[no_of_prod-1][arr[no_of_prod-1][i]];
for(j=0;j<no_of_prod;j++){
if(prod[j][0]==c){
for(k=0;k<10;k++){
if(arr[j][k]==3) break;
else if(arr[j][k]==-1){
arr[j][k] = 3;
break;
}
}
}
}
}
else break;
}
while(flag){
flag = 0;
for(i=0;i<no_of_prod;i++){
for(k=0;k<10;k++){
if(arr[i][k]!=-1){
c = prod[i][arr[i][k]];
for(j=0;j<no_of_prod;j++){
if(prod[j][0]==c){
for(l=0;l<10;l++){

70 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(arr[j][l]==3) break;
else if(arr[j][l]==-1){
arr[j][l] = 3;
flag = 1;
break;
}
}
}
}
}
else break;
}
}
}
}
int Goto(int in, int i, int n){
int j, ans=0, arr[100][10], flg=0, k, l, len;
char c;
for(j=0;j<100;j++)
for(k=0;k<10;k++) arr[j][k] = -1;
for(j=0;j<no_of_prod;j++){
for(k=0;k<10;k++){
if(canonical[in][j][k]!=-1){
if(n){
if(prod[j][canonical[in][j][k]]==non_term[i]){
for(l=0;l<10;l++){
if(arr[j][l]==canonical[in][j][k]+1) break;
else if(arr[j][l]==-1){
flg=1;
arr[j][l] = canonical[in][j][k]+1;
break;
}
}
}

71 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

}
else{
if(prod[j][canonical[in][j][k]]==term[i]){
for(l=0;l<10;l++){
if(arr[j][l]==canonical[in][j][k]+1) break;
else if(arr[j][l]==-1){
flg=1;
arr[j][l] = canonical[in][j][k]+1;
break;
}
}
}
}
}
else break;
}
}
if(!flg) return 0;
closure(arr);
for(j=0;j<can_len;j++){
flg = 0;
for(k=0;k<no_of_prod;k++){
for(l=0;l<10;l++){
if(canonical[j][k][l]!=arr[k][l]){
flg = 1;
break;
}
}
if(flg) break;
}
if(!flg){
ans = j;
break;
}

72 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

}
if(flg){
for(j=0;j<no_of_prod;j++){
for(l=0;l<10;l++) canonical[can_len][j][l] = arr[j][l];
}
ans = can_len;
can_len++;
}
if(n) go_to[in][i] = ans;
else sprintf(action[in][i], "s%d", ans);
if(flg){
for(i=0;i<no_of_prod;i++){
len = strlen(prod[i]);
for(j=0;j<10;j++){
if(arr[i][j]!=-1){
if(arr[i][j]==len){
if(i==no_of_prod-1)
sprintf(action[can_len-1][term_len-1], "acc\0");
else{
c = prod[i][0];
for(k=0;k<non_term_len;k++){
if(non_term[k]==c) break;
}
for(l=0;l<term_len;l++){
if(follow[k][l]) sprintf(action[can_len-1][l], "r%d\0", i+1);
}
}
}
}
else break;
}
}
}
return flg;

73 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

}
int main(){
int i, j, len, k, a, b, t, flag;
char c, temp[100];
can_len = 0;
term_len = non_term_len = 0;
printf("Enter the Number of productions which you want to enter :-> ");
scanf("%d", &no_of_prod);
printf("\n");
for(i=0;i<no_of_prod;i++){
scanf("%s", &prod[i]);
len = strlen(prod[i]);
for(j=0;j<len;j++){
if(prod[i][j]>='A' && prod[i][j]<='Z'){
for(k=0;k<non_term_len;k++){
if(non_term[k]==prod[i][j]) break;
}
if(k==non_term_len){
non_term[non_term_len] = prod[i][j];
non_term_len++;
}
}
else
if(prod[i][j]!='-' && prod[i][j]!='>' && prod[i][j]!='|'){
for(k=0;k<term_len;k++){
if(term[k]==prod[i][j]) break;
}
if(k==term_len){
term[term_len] = prod[i][j];
term_len++;
}
}
}
}

74 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

printf("\n NON TERMINALS :->\n");


printf("%c", non_term[0]);
for(i=1;i<non_term_len;i++){
printf(",%c", non_term[i]);
}
puts("");
printf("\nTERMINALS :->\n");
printf("%c", term[0]);
for(i=1;i<term_len;i++){
printf(",%c", term[i]);
}
puts("");
printf("\n**********FIRST**********\n");
for(i=0;i<non_term_len;i++){
calc_first(i);
printf("%c = { ", non_term[i]);
for(j=0;j<term_len;j++){
if(first[i][j]) break;
}
if(j<term_len){
printf("%c", term[j]);
j++;
for(;j<term_len;j++){
if(first[i][j]) printf(" ,%c", term[j]);
}
}
printf(" }\n");
}
term[term_len] = '$';
term_len++;
printf("\n***********FOLLOW*********\n");
follow[0][term_len-1] = 1;
for(i=0;i<non_term_len;i++){
calc_follow(i);

75 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

printf("%c = { ", non_term[i]);


for(j=0;j<term_len;j++){
if(follow[i][j]) break;
}
if(j<term_len){
printf("%c", term[j]);
j++;
for(;j<term_len;j++){
if(follow[i][j]) printf(" ,%c", term[j]);
}
}
printf(" }\n");
}
for(i=0;i<100;i++){
for(j=0;j<100;j++){
sprintf(action[i][j], "\0");
go_to[i][j] = -1;
}
}
sprintf(prod[no_of_prod], "X->%c\0", prod[0][0]);
no_of_prod++;
for(i=0;i<100;i++){
for(j=0;j<no_of_prod;j++){
for(k=0;k<10;k++) canonical[i][j][k] = -1;
}
}
puts("\n---------------CANONICAL LR COLLECTION FOR GRAMMAR--------------
-");
canonical[0][no_of_prod-1][0] = 3;
closure(canonical[0]);
can_len++;
puts("");
print(0);
flag = 1;

76 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

while(flag){
flag = 0;
for(i=0;i<can_len;i++){
for(j=0;j<non_term_len;j++){
if(Goto(i, j, 1)){
printf("\nGOTO(I%d, %c) ", i, non_term[j]);
print(can_len-1);
flag = 1;
}
}
for(j=0;j<term_len;j++){
if(Goto(i, j, 0)){
printf("\nGOTO(I%d, %c) ", i, term[j]);
print(can_len-1);
flag = 1;
}
}
}
}
printf("\nSLR Parsing Table\n\n");
printf("State\t|\t\tAction");
for(i=0;i<term_len-2;i++) printf("\t");
printf("|\tGoTo\n");
printf("***************************************************************
************\n\t|");
for(i=0;i<term_len;i++){
printf("%c\t", term[i]);
}
printf("|");
for(i=0;i<non_term_len;i++){
printf("%c\t", non_term[i]);
}
puts("\n**************************************************************
*************");

77 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

for(i=0;i<can_len;i++){
printf("%d\t|", i);
for(j=0;j<term_len;j++){
printf("%s\t", action[i][j]);
}
printf("|");
for(j=0;j<non_term_len;j++)
{
if(go_to[i][j]!=-1) printf("%d", go_to[i][j]);
printf("\t");
}
puts("");
}
return 0;
}

Output:

Figure 8.3 – First Follow for the given SLR grammer

78 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Figure 8.4 – Output for when the given grammer is SLR

79 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Figure 8.5 – Output for when the given grammer is SLR

Frequently Asked Questions (FAQs)


Ques 1 : What is a the Full form of SLR Parser?

Ans 1: SLR :- A Simple LR parser

Ques 2: What is SLR parser?

Ans 2: A Simple LR or SLR parser is a type of LR parser with small parse tables and
a relatively simple parser generator algorithm. As with other types of LR(1) parser, an
SLR parser is quite efficient at finding the single correct bottom-up parse in a single
left-to-right scan over the input stream, without guesswork or backtracking. The parser
is mechanically generated from a formal grammar for the language.

80 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Ques 3: Use of Parsers.


Ans 3: A parser is a compiler or interpreter component that breaks data into smaller
elements for easy translation into another language. A parser takes input in the form
of a sequence of tokens or program instructions and usually builds a data structure in
the form of a parse tree or an abstract syntax tree.

81 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

PRACTICAL – 9
Aim :- To construct a Program to implementation of CLR Parser using C.
Input :- Input a string to be parsed.

Expected Output: If the entered string satisfies the provided grammar rules, then a
message is displayed “accept the input” otherwise “error in input” or “do not accept the
input”.

Algorithm :-

Input: Input a string to be parsed.


Output: If the entered string satisfies the provided grammar rules, then a message is
displayed “accept the input” otherwise “error in input” or “do not accept the input”.

Begin
1. Given a language Grammar rules.
2. Build The Augmented Grammar
3. Construct the collection of LR(1) items sets
{I0, I1,…….., In} ) for Given grammar .
4. This contains one look ahead symbol
5. Initial Item set contains a look ahead symbol as ‘$’
6. A-> α B β,a
Then we calculate FIRST { β,a} as the new look ahead symbol.
7. We calculate the whole set of items like this.
8. We Build CLR parsing table.
a) If the item set contains a rule like {S’->S}
then enter Accept under $ column of this rule in the parsing table.
b) If the item Sets contains rules like {S->w.}
then enter its rule no in the parsing table using FOLLOW.
9. We display the table.

End

Algorithm 9.1 – Implement CLR parser

82 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Flowchart:-

Figure 9.2 – Implementation of CLR parser

Source Code:
#include <stdio.h>

#include <string.h>

#include <conio.h>

char prod[100][100], term[100], non_term[100], action[100][100][100];

int term_len, non_term_len, first[100][100], follow[100][100], hash1[100],


no_of_prod, hash2[100], canonical[100][20][10][10], can_len, go_to[100][100], clr;

83 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

void calc_first(int k){

int j, flag=0, len, l, m, i;

if(hash1[k]) return;

hash1[k] = 1;

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

if(prod[i][0]==non_term[k]){

flag = 0;

len = strlen(prod[i]);

for(j=3;j<len;j++){

if(!flag){

if(prod[i][j]>='A'&&prod[i][j]<='Z'){

for(l=0;l<non_term_len;l++){

if(non_term[l]==prod[i][j]) break;

flag = 1;

if(hash1[l]){

for(m=0;m<term_len;m++){

if(first[l][m]){

first[k][m] = 1;

if(term[m]=='^') flag=0;

84 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

else{

calc_first(l);

for(m=0;m<term_len;m++){

if(first[l][m]){

first[k][m] = 1;

if(term[m]=='^') flag=0;

else if(prod[i][j]!='|'){

for(l=0;l<term_len;l++){

if(term[l]==prod[i][j]) break;

first[k][l] = 1;

flag = 1;

else{

if(prod[i][j]=='|') flag=0;

85 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

void calc_follow(int k){

int i, len, j, l, flag=0, m;

if(hash2[k]) return;

hash2[k] = 1;

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

len = strlen(prod[i]);

for(j=3;j<len;j++){

if(flag){

if(prod[i][j]>='A' && prod[i][j]<='Z'){

flag = 0;

for(l=0;l<non_term_len;l++){

if(non_term[l]==prod[i][j]) break;

if(l<non_term_len){

for(m=0;m<term_len;m++){

if(first[l][m]){

follow[k][m] = 1;

if(term[m]=='^') flag=1;

86 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

else{

for(l=0;l<term_len;l++){

if(term[l]==prod[i][j]) break;

if(l<term_len){

follow[k][l] = 1;

else{

if(prod[i][j]=='|'){

for(l=0;l<non_term_len;l++){

if(non_term[l]==prod[i][0]) break;

if(l<non_term_len){

calc_follow(l);

for(m=0;m<term_len;m++){

if(follow[l][m]) follow[k][m] = 1;

flag = 0;

flag=0;

87 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(prod[i][j]==non_term[k]){

flag = 1;

if(flag){

for(l=0;l<non_term_len;l++){

if(non_term[l]==prod[i][0]) break;

if(l<non_term_len){

calc_follow(l);

for(m=0;m<term_len;m++){

if(follow[l][m]) follow[k][m] = 1;

flag = 0;

void print(int in){

int i, j, len, k, l, prnt;

printf("I%d:\n", in);

88 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

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

prnt = 0;

for(k=0;k<term_len;k++){

if(canonical[in][no_of_prod-1][i][k]){

if(!prnt){

len = strlen(prod[no_of_prod-1]);

for(j=0;j<=len;j++){

if(j==i) printf(".");

printf("%c", prod[no_of_prod-1][j]);

printf(",%c", term[k]);

prnt = 1;

else printf("|%c", term[k]);

if(prnt) puts("");

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

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

prnt = 0;

for(k=0;k<term_len;k++){

if(canonical[in][l][i][k]){

89 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(!prnt){

len = strlen(prod[l]);

for(j=0;j<=len;j++){

if(j==i) printf(".");

printf("%c", prod[l][j]);

printf(",%c", term[k]);

prnt = 1;

else printf("|%c", term[k]);

if(prnt) puts("");

void Frst(char * str, int * arr){

int j, flag=0, len, l, m, i, k;

len = strlen(str);

for(j=0;j<len;j++){

if(!flag){

if(str[j]>='A'&& str[j]<='Z'){

for(l=0;l<non_term_len;l++){

90 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(non_term[l]==str[j]) break;

flag = 1;

for(m=0;m<term_len;m++){

if(first[l][m]){

arr[m] = 1;

if(term[m]=='^') flag=0;

else if(str[j]!='|'){

for(l=0;l<term_len;l++){

if(term[l]==str[j]) break;

arr[l] = 1;

flag = 1;

else break;

void closure(int arr[][10][10]){

int i, j, flag=1, k, l, m, arr1[10], n;

91 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

char c, str[100];

while(flag){

flag = 0;

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

for(k=0;k<10;k++){

for(n=0;n<10;n++){

if(arr[i][k][n]){

c = prod[i][k];

for(j=0;j<no_of_prod;j++){

if(prod[j][0]==c){

for(m=0;m<10;m++) arr1[m] = 0;

for(m=k+1;prod[i][m]!='\0';m++){

str[m-k-1] = prod[i][m];

str[m-k-1] = term[n];

str[m-k] = '\0';

Frst(str, arr1);

for(m=0;m<term_len;m++){

if(arr1[m] && !arr[j][3][m] ){

flag = 1;

arr[j][3][m] = 1;

92 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

int Goto(int in, int sym, int nt){

int j, ans=0, arr[100][10][10]={0}, flg=0, k, l, len, i, m;

char c;

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

for(j=0;j<10;j++){

for(k=0;k<term_len;k++){

if(canonical[in][i][j][k]){

if(nt){

if(prod[i][j]==non_term[sym]){

arr[i][j+1][k] = 1;

flg = 1;

else if(prod[i][j]==term[sym]){

arr[i][j+1][k] = 1;

93 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

flg = 1;

if(!flg) return 0;

closure(arr);

for(j=0;j<can_len;j++){

flg = 0;

for(k=0;k<no_of_prod;k++){

for(l=0;l<10;l++){

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

if(canonical[j][k][l][i]!=arr[k][l][i]){

flg = 1;

break;

if(flg) break;

if(flg) break;

if(!flg){

94 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

ans = j;

break;

if(flg){

for(j=0;j<no_of_prod;j++){

for(l=0;l<10;l++){

for(i=0;i<term_len;i++)

canonical[can_len][j][l][i] = arr[j][l][i];

ans = can_len;

can_len++;

if(nt) go_to[in][sym] = ans;

else{

if(action[in][sym][0]=='\0') sprintf(action[in][sym], "s%d\0", ans);

else{

sscanf(action[in][sym], "s%d", &k);

if(k!=ans){

clr = 0;

len = strlen(action[in][sym]);

sprintf(action[in][sym]+len, ",s%d", ans);

95 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(flg){

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

len = strlen(prod[i]);

for(j=0;j<10;j++){

for(l=0;l<term_len;l++){

if(arr[i][j][l] && j==len){

if(i==no_of_prod-1)

sprintf(action[can_len-1][term_len-1], "acc\0");

else{

if(action[can_len-1][l][0]=='\0')

sprintf(action[can_len-1][l], "r%d\0", i+1);

else{

sscanf(action[can_len-1][l], "r%d", &k);

if(k!=i+1){

clr = 0;

len = strlen(action[can_len-1][l]);

sprintf(action[can_len-1][l]+len, "r%d\0", i+1);

96 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

return flg;

int main(){

int i, j, len, k, a, b, t, flag;

char c, temp[100];

clr = 1;

can_len = 0;

term_len = non_term_len = 0;

printf("Enter the Number of productions which you want to enter :-> ");

scanf("%d", &no_of_prod);

printf("\n");

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

scanf("%s", &prod[i]);

len = strlen(prod[i]);

for(j=0;j<len;j++){

if(prod[i][j]>='A' && prod[i][j]<='Z'){

for(k=0;k<non_term_len;k++){

if(non_term[k]==prod[i][j]) break;

97 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(k==non_term_len){

non_term[non_term_len] = prod[i][j];

non_term_len++;

else

if(prod[i][j]!='-' && prod[i][j]!='>' && prod[i][j]!='|'){

for(k=0;k<term_len;k++){

if(term[k]==prod[i][j]) break;

if(k==term_len){

term[term_len] = prod[i][j];

term_len++;

printf("\n***********NON TERMINALS**********\n");

printf("%c", non_term[0]);

for(i=1;i<non_term_len;i++){

printf(",%c", non_term[i]);

puts("");

98 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

printf("\n**********TERMINALS**********\n");

printf("%c", term[0]);

for(i=1;i<term_len;i++){

printf(",%c", term[i]);

puts("");

printf("\nFirst\n");

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

calc_first(i);

printf("%c = { ", non_term[i]);

for(j=0;j<term_len;j++){

if(first[i][j]) break;

if(j<term_len){

printf("%c", term[j]);

j++;

for(;j<term_len;j++){

if(first[i][j]) printf(" ,%c", term[j]);

printf(" }\n");

term[term_len] = '$';

99 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

term_len++;

printf("\nFollow\n");

follow[0][term_len-1] = 1;

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

calc_follow(i);

printf("%c = { ", non_term[i]);

for(j=0;j<term_len;j++){

if(follow[i][j]) break;

if(j<term_len){

printf("%c", term[j]);

j++;

for(;j<term_len;j++){

if(follow[i][j]) printf(" ,%c", term[j]);

printf(" }\n");

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

for(j=0;j<100;j++){

sprintf(action[i][j], "\0");

go_to[i][j] = -1;

100 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

sprintf(prod[no_of_prod], "X->%c\0", prod[0][0]);

no_of_prod++;

puts("\n----------CANONICAL LR(1) COLLECTION OF SETS FOR GRAMMAR---


-------");

canonical[0][no_of_prod-1][3][term_len-1] = 1;

closure(canonical[0]);

can_len++;

puts("");

print(0);

flag = 1;

while(flag){

flag = 0;

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

for(j=0;j<non_term_len;j++){

if(Goto(i, j, 1)){

printf("\nGOTO(I%d, %c) ", i, non_term[j]);

print(can_len-1);

flag = 1;

for(j=0;j<term_len-1;j++){

101 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(Goto(i, j, 0)){

printf("\nGOTO(I%d, %c) ", i, term[j]);

print(can_len-1);

flag = 1;

if(clr){

puts("\nThe Grammar is CLR(1)");

printf("\nCLR Parsing Table\n\n");

printf("State\t|\t\tAction");

for(i=0;i<term_len-2;i++) printf("\t");

printf("|\tGoTo\n");

printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~\n\t|");

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

printf("%c\t", term[i]);

printf("|");

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

printf("%c\t", non_term[i]);

102 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

puts("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~");

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

printf("%d\t|", i);

for(j=0;j<term_len;j++){

printf("%s\t", action[i][j]);

printf("|");

for(j=0;j<non_term_len;j++){

if(go_to[i][j]!=-1) printf("%d", go_to[i][j]);

printf("\t");

puts("");

else{

puts("\n**********The Grammar is not CLR(1)**********");

return 0;

103 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Output:-

Figure 9.3 – The given grammer is CLR

Figure 9.4 – The given grammer is CLR

104 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Figure 9.5– The given grammer is CLR

Frequently Asked Questions (FAQs)


Ques 1: What is a the Full form of CLR Parser?

Ans 2: CLR :- A canonical LR parser

Ques 2: What Is a CLR parser?

Ans 2: A canonical LR parser or LR(1) parser is an LR(k) parser for k=1, i.e. with
a single lookahead terminal. The special attribute of this parser is that all
LR(k) parsers with k>1 can be transformed into a LR(1) parser. It can handle all
deterministic context-free languages.

105 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Date: _______

PRACTICAL – 10
Aim :- To construct a Program to implementation of LALR Parser using C.
Input :- Input a string to be parsed.

Expected Output: If the entered string satisfies the provided grammar rules, then a
message is displayed “accept the input” otherwise “error in input” or “do not accept the
input”.

Algorithm :-
Input: Input a string to be parsed.
Output: If the entered string satisfies the provided grammar rules, then a message is
displayed “accept the input” otherwise “error in input” or “do not accept the input”.

Begin
1. Given a language Grammar rules.
2. Build The Augmented Grammar
3. Construct the collection of LR(1) items sets
{I0, I1,…….., In} ) for Given grammar .
4. Now if the rules in the different item sets is same but different Look Ahead
Symbols,
Then Create a single Item Set By combining Both item Sets and Union The
Look Ahead Symbols.
Eg: if I5: {S->L. , a} and I7: {S->L. ,b} ,then Create a single Item Set
As
I57: {S->L. ,a/b}
5. Like This Create set of all LALR(1) items.
6. Build the parsing table.
7. If there are no parsing conflicts, then the given grammar is said to be an
LALR(1) grammar.

End

Algorithm 10.1 – Implement LALR parser

106 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Flowchart:

Figure 10.2 – Implementation of LALR parser

Source Code:
#include <stdio.h>

#include <string.h>

107 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

#include <conio.h>

char prod[100][100], term[100], non_term[100], action[100][100][100];

int term_len, non_term_len, first[100][100], follow[100][100], hash1[100],


no_of_prod, hash2[100], canonical[100][20][10][10], can_len, go_to[100][100],
eq_items[100], lalr;

void calc_first(int k){

int j, flag=0, len, l, m, i;

if(hash1[k]) return;

hash1[k] = 1;

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

if(prod[i][0]==non_term[k]){

flag = 0;

len = strlen(prod[i]);

for(j=3;j<len;j++){

if(!flag){

if(prod[i][j]>='A'&&prod[i][j]<='Z'){

for(l=0;l<non_term_len;l++){

if(non_term[l]==prod[i][j]) break;

flag = 1;

if(hash1[l]){

for(m=0;m<term_len;m++){

if(first[l][m]){

first[k][m] = 1;

if(term[m]=='^') flag=0;

108 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

else{

calc_first(l);

for(m=0;m<term_len;m++){

if(first[l][m]){

first[k][m] = 1;

if(term[m]=='^') flag=0;

else if(prod[i][j]!='|'){

for(l=0;l<term_len;l++){

if(term[l]==prod[i][j]) break;

first[k][l] = 1;

flag = 1;

else{

if(prod[i][j]=='|') flag=0;

void calc_follow(int k){

int i, len, j, l, flag=0, m;

109 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(hash2[k]) return;

hash2[k] = 1;

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

len = strlen(prod[i]);

for(j=3;j<len;j++){

if(flag){

if(prod[i][j]>='A' && prod[i][j]<='Z'){

flag = 0;

for(l=0;l<non_term_len;l++){

if(non_term[l]==prod[i][j]) break;

if(l<non_term_len){

for(m=0;m<term_len;m++){

if(first[l][m]){

follow[k][m] = 1;

if(term[m]=='^') flag=1;

else{

for(l=0;l<term_len;l++){

if(term[l]==prod[i][j]) break;

if(l<term_len){

follow[k][l] = 1;

110 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

else{

if(prod[i][j]=='|'){

for(l=0;l<non_term_len;l++){

if(non_term[l]==prod[i][0]) break;

if(l<non_term_len){

calc_follow(l);

for(m=0;m<term_len;m++){

if(follow[l][m]) follow[k][m] = 1;

flag = 0;

flag=0;

if(prod[i][j]==non_term[k]){

flag = 1;

if(flag){

for(l=0;l<non_term_len;l++){

if(non_term[l]==prod[i][0]) break;

if(l<non_term_len){

calc_follow(l);

111 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

for(m=0;m<term_len;m++){

if(follow[l][m]) follow[k][m] = 1;

flag = 0;

void print(int in){

int i, j, len, k, l, prnt;

printf("I%d:\n", in);

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

prnt = 0;

for(k=0;k<term_len;k++){

if(canonical[in][no_of_prod-1][i][k]){

if(!prnt){

len = strlen(prod[no_of_prod-1]);

for(j=0;j<=len;j++){

if(j==i) printf(".");

printf("%c", prod[no_of_prod-1][j]);

printf(",%c", term[k]);

prnt = 1;

else printf("|%c", term[k]);

112 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(prnt) puts("");

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

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

prnt = 0;

for(k=0;k<term_len;k++){

if(canonical[in][l][i][k]){

if(!prnt){

len = strlen(prod[l]);

for(j=0;j<=len;j++){

if(j==i) printf(".");

printf("%c", prod[l][j]);

printf(",%c", term[k]);

prnt = 1;

else printf("|%c", term[k]);

if(prnt) puts("");

void Frst(char * str, int * arr){

int j, flag=0, len, l, m, i, k;

len = strlen(str);

for(j=0;j<len;j++){

113 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(!flag){

if(str[j]>='A'&& str[j]<='Z'){

for(l=0;l<non_term_len;l++){

if(non_term[l]==str[j]) break;

flag = 1;

for(m=0;m<term_len;m++){

if(first[l][m]){

arr[m] = 1;

if(term[m]=='^') flag=0;

else if(str[j]!='|'){

for(l=0;l<term_len;l++){

if(term[l]==str[j]) break;

arr[l] = 1;

flag = 1;

else break;

void closure(int arr[][10][10]){

int i, j, flag=1, k, l, m, arr1[10], n;

char c, str[100];

114 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

while(flag){

flag = 0;

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

for(k=0;k<10;k++){

for(n=0;n<10;n++){

if(arr[i][k][n]){

c = prod[i][k];

for(j=0;j<no_of_prod;j++){

if(prod[j][0]==c){

for(m=0;m<10;m++) arr1[m] = 0;

for(m=k+1;prod[i][m]!='\0';m++){

str[m-k-1] = prod[i][m];

str[m-k-1] = term[n];

str[m-k] = '\0';

Frst(str, arr1);

for(m=0;m<term_len;m++){

if(arr1[m] && !arr[j][3][m] ){

flag = 1;

arr[j][3][m] = 1;

115 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

int Goto(int in, int sym, int nt){

int j, ans=0, arr[100][10][10]={0}, flg=0, k, l, len, i, m;

char c;

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

for(j=0;j<10;j++){

for(k=0;k<term_len;k++){

if(canonical[in][i][j][k]){

if(nt){

if(prod[i][j]==non_term[sym]){

arr[i][j+1][k] = 1;

flg = 1;

else if(prod[i][j]==term[sym]){

arr[i][j+1][k] = 1;

flg = 1;

if(!flg) return 0;

closure(arr);

for(j=0;j<can_len;j++){

116 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

flg = 0;

for(k=0;k<no_of_prod;k++){

for(l=0;l<10;l++){

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

if(canonical[j][k][l][i]!=arr[k][l][i]){

flg = 1;

break;

if(flg) break;

if(flg) break;

if(!flg){

ans = j;

break;

if(flg){

for(j=0;j<no_of_prod;j++){

for(l=0;l<10;l++){

for(i=0;i<term_len;i++) canonical[can_len][j][l][i] = arr[j][l][i];

ans = can_len;

can_len++;

117 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(nt) go_to[in][sym] = ans;

else{

if(action[in][sym][0]=='\0') sprintf(action[in][sym], "s%d\0", ans);

else{

sscanf(action[in][sym], "s%d", &k);

if(k!=ans){

lalr = 0;

len = strlen(action[in][sym]);

sprintf(action[in][sym]+len, ",s%d", ans);

if(flg){

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

len = strlen(prod[i]);

for(j=0;j<10;j++){

for(l=0;l<term_len;l++){

if(arr[i][j][l] && j==len){

if(i==no_of_prod-1) sprintf(action[can_len-1][term_len-1], "acc\0");

else{

if(action[can_len-1][l][0]=='\0') sprintf(action[can_len-1][l], "r%d\0", i+1);

else{

sscanf(action[can_len-1][l], "r%d", &k);

if(k!=i+1){

lalr = 0;

len = strlen(action[can_len-1][l]);

sprintf(action[can_len-1][l]+len, "r%d\0", i+1);

118 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

return flg;

void print_(int in){

int i;

in = eq_items[in];

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

if(eq_items[i]==in) printf("%d", i);

int main(){

int i, j, len, k, a, b, t, flag, l, m, flg1, flg2;

char c, temp[100];

lalr = 1;

can_len = 0;

term_len = non_term_len = 0;

printf("Enter the Number of productions which you want to enter :-> ");

scanf("%d", &no_of_prod);

printf("\n");

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

119 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

scanf("%s", &prod[i]);

len = strlen(prod[i]);

for(j=0;j<len;j++){

if(prod[i][j]>='A' && prod[i][j]<='Z'){

for(k=0;k<non_term_len;k++){

if(non_term[k]==prod[i][j]) break;

if(k==non_term_len){

non_term[non_term_len] = prod[i][j];

non_term_len++;

else if(prod[i][j]!='-' && prod[i][j]!='>' && prod[i][j]!='|'){

for(k=0;k<term_len;k++){

if(term[k]==prod[i][j]) break;

if(k==term_len){

term[term_len] = prod[i][j];

term_len++;

printf("\n-----------NON TERMINALS----------\n");

printf("%c", non_term[0]);

for(i=1;i<non_term_len;i++){

printf(",%c", non_term[i]);

120 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

puts("");

printf("\n----------TERMINALS----------\n");

printf("%c", term[0]);

for(i=1;i<term_len;i++){

printf(",%c", term[i]);

puts("");

printf("\nFirst\n");

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

calc_first(i);

printf("%c = { ", non_term[i]);

for(j=0;j<term_len;j++){

if(first[i][j]) break;}

if(j<term_len){

printf("%c", term[j]);

j++;

for(;j<term_len;j++){

if(first[i][j]) printf(" ,%c", term[j]);

printf(" }\n");}

term[term_len] = '$';

term_len++;

printf("\nFollow\n");

follow[0][term_len-1] = 1;

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

121 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

calc_follow(i);

printf("%c = { ", non_term[i]);

for(j=0;j<term_len;j++){

if(follow[i][j]) break;}

if(j<term_len){

printf("%c", term[j]);

j++;

for(;j<term_len;j++){

if(follow[i][j]) printf(" ,%c", term[j]);

printf(" }\n");}

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

for(j=0;j<100;j++){

sprintf(action[i][j], "\0");

go_to[i][j] = -1;

}}

sprintf(prod[no_of_prod], "X->%c\0", prod[0][0]);

no_of_prod++;

puts("\n----------CANONICAL LR(1) COLLECTION OF SETS FOR GRAMMAR---


-------");

canonical[0][no_of_prod-1][3][term_len-1] = 1;

closure(canonical[0]);

can_len++;

puts("");

print(0);

flag = 1;

while(flag){

122 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

flag = 0;

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

for(j=0;j<non_term_len;j++){

if(Goto(i, j, 1)){

printf("\nGOTO(I%d, %c) ", i, non_term[j]);

print(can_len-1);

flag = 1;

for(j=0;j<term_len-1;j++){

if(Goto(i, j, 0)){

printf("\nGOTO(I%d, %c) ", i, term[j]);

print(can_len-1);

flag = 1;}

}}

if(lalr){

puts("\n**********The Grammar is LALR(1)**********");

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

if(!eq_items[i]){

eq_items[i] = i;

for(j=i+1;j<can_len;j++){

flag = 1;

for(k=0;k<no_of_prod;k++){

for(l=0;l<10;l++){

flg1 = flg2 = 0;

for(m=0;m<term_len;m++){

123 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

if(canonical[i][k][l][m]) flg1=1;

if(canonical[j][k][l][m]) flg2=1;

if(flg1!=flg2){

flag = 0;

break;}

if(!flag) break;

if(flag) eq_items[j] = i;

printf("\nItems having same core are :->\n");

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

if(eq_items[i]==i){

flag = 0;

for(j=i+1;j<can_len;j++){

if(eq_items[j]==i){

if(!flag){

printf("%d, %d", i, j);

flag = 1;}

else printf(", %d", j);

}}

if(flag) puts("");

}}

printf("\nLALR Parsing Table\n\n");

124 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

printf("State\t|\t\tAction");

for(i=0;i<term_len-2;i++) printf("\t");

printf("|\tGoTo\n");

printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~\n\t|");

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

printf("%c\t", term[i]);

printf("|");

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

printf("%c\t", non_term[i]);

puts("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~");

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

if(eq_items[i]==i){

print_(i);

printf("\t|");

for(j=0;j<term_len;j++){

if(action[i][j][0]=='s'){

sscanf(action[i][j], "s%d", &k);

printf("s");

print_(k);

printf("\t");

else if(action[i][j][0]=='r'||action[i][j][0]=='\0')

flag = 0;

125 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

k = eq_items[i];

for(l=0;l<can_len;l++){

if(eq_items[l]==k && action[l][j][0]=='r')

if(!flag){

printf("%s", action[l][j]);

flag = 1;

else printf("%s", action[l][j]+1);

printf("\t");

else printf("%s\t", action[i][j]);

printf("|");

for(j=0;j<non_term_len;j++){

if(go_to[i][j]!=-1) print_(go_to[i][j]);

printf("\t");

puts("");

else{

puts("\n~~~~~~~~~~~~~~~~~~~~~~~~~~The Grammar is not


LALR(1)~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

126 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

return 0;

Output:-

Figure 10.3 – The given grammer is LALR

127 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Figure 10.4 – The given grammer is LALR

128 | P a g e
DEPARTMENT OF COMPUTER SCIENCE
COMPILER DESIGN PRACTICAL (CS-654) LCO17365

Figure 10.5 – The given grammer is LALR

Frequently Asked Questions (FAQs)


Ques 1: What is a the Full form of LALR Parser?

Ans 1: LALR:- LOOK AHEAD LR PARSER

Ques 2: What Is a LALR parser?

Ans 2: It is intermediate in Power between SLR and CLR parser. It is compaction of


CLR Parser and hence tables obtained in this will be smaller than CLR Parsing Table.

129 | P a g e
DEPARTMENT OF COMPUTER SCIENCE

You might also like