The Wayback Machine - https://web.archive.org/web/20241115215920/https://www.geeksforgeeks.org/recursive-descent-parser/
Open In App

Recursive Descent Parser

Last Updated : 09 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite – Construction of LL(1) Parsing Table, Classification of top down parsers 

Parsing is the process to determine whether the start symbol can derive the program or not. If the Parsing is successful then the program is a valid program otherwise the program is invalid. 

There are generally two types of Parsers: 

  1. Top-Down Parsers: 
    • In this Parsing technique we expand the start symbol to the whole program.
    • Recursive Descent and LL parsers are the Top-Down parsers.
  2. Bottom-Up Parsers: 
    • In this Parsing technique we reduce the whole program to start symbol.
    • Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers.

Recursive Descent Parser: 

It is a kind of Top-Down Parser. A top-down parser builds the parse tree from the top to down, starting with the start non-terminal. A Predictive Parser is a special case of Recursive Descent Parser, where no Back Tracking is required. 
By carefully writing a grammar means eliminating left recursion and left factoring from it, the resulting grammar will be a grammar that can be parsed by a recursive descent parser.

Example:

Before removing left recursion After removing left recursion
E –> E + T | T 
T –> T * F | F 
F –> ( E ) | id
E –> T E’ 
E’ –> + T E’ | e 
T –> F T’ 
T’ –> * F T’ | e 
F –> ( E ) | id

**Here e is Epsilon
For Recursive Descent Parser, we are going to write one program for every variable. 
 

Example:
Grammar:

C




#include <stdio.h>
#include <string.h>
 
#define SUCCESS 1
#define FAILED 0
 
// Function prototypes
int E(), Edash(), T(), Tdash(), F();
 
const char *cursor;
char string[64];
 
int main() {
    puts("Enter the string");
    scanf("%s", string); // Read input from the user
    cursor = string;
    puts("");
    puts("Input          Action");
    puts("--------------------------------");
 
    // Call the starting non-terminal E
    if (E() && *cursor == '\0') { // If parsing is successful and the cursor has reached the end
        puts("--------------------------------");
        puts("String is successfully parsed");
        return 0;
    }
    else {
        puts("--------------------------------");
        puts("Error in parsing String");
        return 1;
    }
}
 
// Grammar rule: E -> T E'
int E() {
    printf("%-16s E -> T E'\n", cursor);
    if (T()) { // Call non-terminal T
        if (Edash()) // Call non-terminal E'
            return SUCCESS;
        else
            return FAILED;
    }
    else
        return FAILED;
}
 
// Grammar rule: E' -> + T E' | $
int Edash() {
    if (*cursor == '+') {
        printf("%-16s E' -> + T E'\n", cursor);
        cursor++;
        if (T()) { // Call non-terminal T
            if (Edash()) // Call non-terminal E'
                return SUCCESS;
            else
                return FAILED;
        }
        else
            return FAILED;
    }
    else {
        printf("%-16s E' -> $\n", cursor);
        return SUCCESS;
    }
}
 
// Grammar rule: T -> F T'
int T() {
    printf("%-16s T -> F T'\n", cursor);
    if (F()) { // Call non-terminal F
        if (Tdash()) // Call non-terminal T'
            return SUCCESS;
        else
            return FAILED;
    }
    else
        return FAILED;
}
 
// Grammar rule: T' -> * F T' | $
int Tdash() {
    if (*cursor == '*') {
        printf("%-16s T' -> * F T'\n", cursor);
        cursor++;
        if (F()) { // Call non-terminal F
            if (Tdash()) // Call non-terminal T'
                return SUCCESS;
            else
                return FAILED;
        }
        else
            return FAILED;
    }
    else {
        printf("%-16s T' -> $\n", cursor);
        return SUCCESS;
    }
}
 
// Grammar rule: F -> ( E ) | i
int F() {
    if (*cursor == '(') {
        printf("%-16s F -> ( E )\n", cursor);
        cursor++;
        if (E()) { // Call non-terminal E
            if (*cursor == ')') {
                cursor++;
                return SUCCESS;
            }
            else
                return FAILED;
        }
        else
            return FAILED;
    }
    else if (*cursor == 'i') {
        printf("%-16s F -> i\n", cursor);
        cursor++;
        return SUCCESS;
    }
    else
        return FAILED;
}




Similar Reads

Difference Between Recursive Predictive Descent Parser and Non-Recursive Predictive Descent Parser
Syntax analysis is an important task of compilers. Parsing techniques can be used for the analysis of the structure of programming languages. Out of these techniques, Recursive Predictive Descent Parsing and Non-Recursive Predictive Descent Parsing are two well-known top-down methods. Although both intend to analyze strings according to grammar rul
6 min read
Total Recursive Functions and Partial Recursive Functions in Automata
Total Recursive Functions: A recursive function is called total recursive function if it is defined for its all arguments.Let f(a1, a2, ...an) be a function defined on function g(b1, b2, ...bn).Then f is a total function if every element of f is assigned to some unique element of function g. A total function is called recursive or primitive recursi
2 min read
Shift Reduce Parser in Compiler
Prerequisite – Parsing | Set 2 (Bottom Up or Shift Reduce Parsers) 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 the shift-reduce parser is the LR parser. This parser requires some data structu
8 min read
LR Parser
In this article, we will discuss LR parser, and it's overview and then will discuss the algorithm. Also, we will discuss the parsing table and LR parser working diagram. Let's discuss it one by one. LR parser :LR parser is a bottom-up parser for context-free grammar that is very generally used by computer programming language compiler and other ass
3 min read
Difference between LL and LR parser
LL Parser includes both the recursive descent parser and non-recursive descent parser. Its one type uses backtracking while another one uses parsing table. Theses are top down parser. Example: Given grammar is S -> Ac A -> ab where S is start symbol, A is non-terminal and a, b, c are terminals. Input string: abc Parse tree generated by LL par
2 min read
Parsing ambiguous grammars using LR parser
LR parser can be used to parse ambiguous grammars. LR parser resolves the conflicts (shift/reduce or reduce/reduce) in parsing table of ambiguous grammars based on certain rules (precedence and/or associativity of operators) of the grammar. Example: Lets take the following ambiguous grammar: E -> E+E E -> E*E E -> id Lets assume, the prece
3 min read
Working of Bottom up parser
In this article, we are going to cover working of the bottom-up parser and will see how we can take input and parse it and also cover some basics of bottom-up parser. Pre-requisite - Parsing Bottom-up parser : It will start from string and proceed to start.In Bottom-up parser, Identifying the correct handle (substring) is always difficult.It will f
2 min read
Role of Operator Precedence Parser
In this, we will cover the overview of Operator Precedence Parser and mainly focus on the role of Operator Precedence Parser. And will also cover the algorithm for the construction of the Precedence function and finally will discuss error recovery in operator precedence parsing. Let's discuss it one by one. Introduction :Operator Precedence Parser
4 min read
CLR Parser (with Examples)
LR parsers :It is an efficient bottom-up syntax analysis technique that can be used to parse large classes of context-free grammar is called LR(k) parsing. L stands for the left to right scanningR stands for rightmost derivation in reversek stands for no. of input symbols of lookahead Advantages of LR parsing : It recognizes virtually all programmi
7 min read
LALR Parser (with Examples)
LALR Parser :LALR Parser is lookahead LR parser. It is the most powerful parser which can handle large classes of grammar. The size of CLR parsing table is quite large as compared to other parsing table. LALR reduces the size of this table.LALR works similar to CLR. The only difference is , it combines the similar states of CLR parsing table into o
6 min read
Compiler Design SLR(1) Parser Using Python
Prerequisite: LR Parser, SLR Parser SLR (1) grammar SLR stands for Simple LR grammar. It is an example of a bottom-up parser. The "L" in SLR represents the scanning that advances from left to right and the "R" stands for constructions of derivation in reverse order, and the “(1)” represents the number of input symbols of lookahead. Shift and Reduce
15+ min read
Predictive Parser in Compiler Design
In this, we will cover the overview of Predictive Parser and mainly focus on the role of Predictive Parser. And will also cover the algorithm for the implementation of the Predictive parser algorithm and finally will discuss an example by implementing the algorithm for precedence parsing. Let’s discuss it one by one. Predictive Parser :A predictive
2 min read
SLR Parser (with Examples)
LR parsers is an efficient bottom-up syntax analysis technique that can be used to parse large classes of context-free grammar is called LR(k) parsing. L stands for left-to-right scanningR stands for rightmost derivation in reversek is several input symbols. when k is omitted k is assumed to be 1. Advantages of LR parsing LR parsers handle context-
4 min read
Problem on LR(0) parser
Prerequisite: LR Parser. The LR parser is an efficient bottom-up syntax analysis technique that can be used for a large class of context-free grammar. This technique is also called LR(0) parsing.L stands for the left to right scanningR stands for rightmost  derivation in reverse0 stands for no. of input symbols of lookahead. Augmented grammar :If G
4 min read
Working of Top Down Parser
A top-down parser is a type of parser used in compiler design and language processing. It works by starting at the highest level of grammar (usually called the "start symbol") and breaking it down step by step into its components, trying to match the structure of the input. In this article, we are going to cover the working of a top-down parser and
3 min read
Algorithm for non recursive Predictive Parsing
Prerequisite - Classification of Top Down Parsers Predictive parsing is a special form of recursive descent parsing, where no backtracking is required, so this can predict which products to use to replace the input string. Non-recursive predictive parsing or table-driven is also known as LL(1) parser. This parser follows the leftmost derivation (LM
4 min read
Recursive Relationships in ER diagrams
Prerequisite - ER Model  A relationship between two entities of a similar entity type is called a recursive relationship. Here the same entity type participates more than once in a relationship type with a different role for each instance. In other words, a relationship has always been between occurrences in two different entities. However, the sam
4 min read
DBMS Tutorial – Learn Database Management System
Database Management System is a software or technology used to manage data from a database. Some popular databases are MySQL, Oracle, MongoDB, etc. DBMS provides many operations e.g. creating a database, Storing in the database, updating an existing database, delete from the database. DBMS is a system that enables you to store, modify, and retrieve
8 min read
Operating System Tutorial
An Operating System(OS) is software that manages and handles the hardware and software resources of a computer system. It provides interaction between users of computers and computer hardware. An operating system is responsible for managing and controlling all the activities and sharing of computer resources. An operating system is a low-level Soft
7 min read
Difference Between IPv4 and IPv6
The address through which any computer communicates with our computer is simply called an Internet Protocol Address or IP address. For example, if we want to load a web page or download something, we require the address to deliver that particular file or webpage. That address is called an IP Address. There are two versions of IP: IPv4 and IPv6. IPv
7 min read
Differences between TCP and UDP
Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) both are protocols of the Transport Layer Protocols. TCP is a connection-oriented protocol whereas UDP is a part of the Internet Protocol suite, referred to as the UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. In this article, we will discuss the diffe
9 min read
Types of Operating Systems
An Operating System performs all the basic tasks like managing files, processes, and memory. Thus, the operating system acts as the manager of all the resources, i.e. resource manager. Thus, the operating system becomes an interface between the user and the machine. It is one of the most required software that is present in the device. Operating Sy
11 min read
TCP/IP Model
The TCP/IP model is a fundamental framework for computer networking. It stands for Transmission Control Protocol/Internet Protocol, which are the core protocols of the Internet. This model defines how data is transmitted over networks, ensuring reliable communication between devices. It consists of four layers: the Link Layer, the Internet Layer, t
13 min read
What is OSI Model? - Layers of OSI Model
The OSI (Open Systems Interconnection) Model is a set of rules that explains how different computer systems communicate over a network. OSI Model was developed by the International Organization for Standardization (ISO). The OSI Model consists of 7 layers and each layer has specific functions and responsibilities. This layered approach makes it eas
14 min read
Types of Network Topology
Network topology refers to the arrangement of different elements like nodes, links, or devices in a computer network. Common types of network topology include bus, star, ring, mesh, and tree topologies, each with its advantages and disadvantages. In this article, we will discuss different types of network topology in detail. What is Network Topolog
12 min read
Types of Keys in Relational Model (Candidate, Super, Primary, Alternate and Foreign)
Keys are one of the basic requirements of a relational database model. It is widely used to identify the tuples(rows) uniquely in the table. We also use keys to set up relations amongst various columns and tables of a relational database. Different Types of Database Keys Candidate Key Primary Key Super Key Alternate Key Foreign Key Composite Key To
6 min read
ACID Properties in DBMS
This article is based on the concept of ACID properties in DBMS that are necessary for maintaining data consistency, integrity, and reliability while performing transactions in the database. Let's explore them. A transaction is a single logical unit of work that accesses and possibly modifies the contents of a database. Transactions access data usi
7 min read
Introduction of ER Model
Peter Chen developed the ER diagram in 1976. The ER model was created to provide a simple and understandable model for representing the structure and logic of databases. It has since evolved into variations such as the Enhanced ER Model and the Object Relationship Model The Entity Relational Model is a model for identifying entities to be represent
10 min read
Page Replacement Algorithms in Operating Systems
In an operating system that uses paging for memory management, a page replacement algorithm is needed to decide which page needs to be replaced when a new page comes in. Page replacement becomes necessary when a page fault occurs and no free page frames are in memory. However, another page fault would arise if the replaced page is referenced again.
8 min read
Normal Forms in DBMS
Normalization is the process of minimizing redundancy from a relation or set of relations. Redundancy in relation may cause insertion, deletion, and update anomalies. So, it helps to minimize the redundancy in relations. Normal forms are used to eliminate or reduce redundancy in database tables. Normalization of DBMSIn database management systems (
12 min read
Article Tags :
three90RightbarBannerImg