Shift Reduce Parsing in Compiler Design

Like the bottom-up parsing, the shift reduce parser also builds the parse tree from the leaves (bottom) to the root (up). The LR parser is a more versatile variation of the shift-reduce parser.

Shift Reduce Parser requires two Data Structures:

  1. An input buffer for storing the input string.
  2. Stack for storing and accessing the production rules.

Basic Operations:

  • Shift: In this operation, symbols from the input buffer are transferred to the stack.
  • Reduce: If the handle appears on top of the stack, then it is reduced using the proper production rule, which push the LHS of a production rule into the stack and pop out the RHS of a production rule from it.
  • Accept: The parsing operation is referred to as accepting if the stack contains only the start symbol, and the input buffer is empty. When the acceptable action is achieved, successful parsing gets take place.
  • Error: In this case, the parser is unable to perform shift action, decrease action, or even accept action.

Example 1:

Consider the grammar:

S –> S + S 
S –> S * S 
S –> id 

Applying shift reduce parsing to the input string "id + id + id".

StackInput BufferParsing Action
$id+id+id$Shift
$id+id+id$Reduce S->id
$S+id+id$Shift
$S+id+id$Shift
$S+id+id$Reduce S->id
$S+S+id$Reduce S->S+S
$S+id$Shift
$S+id$Shift
$S+id$Reduce S->id
$S+S$Reduce S->S+S
$S$Accept

Example 2:

Consider the grammar:

E –> 2E2 
E –> 3E3 
E –> 4 

Applying shift reduce parsing to the input string "32423"

StackInput BufferParsing Action
$32423$Shift
$32423$-Shift
$32423$Shift
$32423$Reduce by E?4
$32E23$Shift
$32E23$Reduce by E?2E2
$3E3$Shift
$3E3$Reduce by E?3E3
$E$Accept

Example 3:

Consider the grammar:

S –>  ( L ) | a        
L –>  L , S | S   

Applying shift reduce parsing to the input string "(a,(a,a))”

StackInput BufferParsing Action
$(a,(a,a))$Shift
$(a,(a,a))$Shift
 $(a,(a,a))$Reduce S?a
$(S,(a,a))$Reduce L ?S
$(L,(a,a))$Shift
$(L,(a,a))$Shift
$(L,(a,a))$Shift
$(L,(a,a))$Shift
$(L,(S,a))$Reduce S?a
$(L,(L,a))$Shift
$(L,(L,a))$Reduces S?a
$(L,(L,S)))$Reduces L?L,S
$(L,(L))$Shift
$(L,(L))$Reduces S?(L)
$(L,S)$Reduces L?L,S
$(L)$Shift
$(L)$Reduces S?(L)
$S$Accept

Implementation of Shift Reduce Parsing in C++:

// Including libraries that is required for the operation
#include <bits/stdc++.h>
using namespace std;
// These are Global Variables
int z = 0, i = 0, j = 0, c = 0;


// You have to modify the array so that it's size could be increased
// Parsing will be done as per the length of string
char ab[16], ace[20], stak[15], act[10];
/* This Function's purpose is to check whether
 a production rule
which is to be Reduce is in the stack.
 Rules can be E->2E2 , E->3E3 , E->4 */
void checking()
{
    // Copied string is to be printed as an action
    strcpy(ace,"REDUCE TO E -> "); 
    // c=length of string that is taken as input
    for(z = 0; z < c; z++)
    {
        // checking for producing rule E->4
        if(stak[z] == '4')
        {
            printf("%s4", ace);
            stak[z] = 'E';
            stak[z + 1] = '\0';           
            //printing the action
            printf("\n$%s\t%s$\t", stak, ab);
        }
    }     
    for(z = 0; z < c - 2; z++)
    {
        // checking for another production
        if(stak[z] == '2' && stak[z + 1] == 'E' &&
                                stak[z + 2] == '2')
        {
            printf("%s2E2", ace);
            stak[z] = 'E';
            stak[z + 1] = '\0';
            stak[z + 2] = '\0';
            printf("\n$%s\t%s$\t", stak, ab);
            i = i - 2;
        }    
    }       
    for(z = 0; z < c - 2; z++)
    {
        //checking for E->3E3
        if(stak[z] == '3' && stak[z + 1] == 'E' &&
                                stak[z + 2] == '3')
        {
            printf("%s3E3", ace);
            stak[z]='E';
            stak[z + 1]='\0';
            stak[z + 1]='\0';
            printf("\n$%s\t%s$\t", stak, ab);
            i = i - 2;
        }
    }
    return ; // return to main
}
// It is ab Driver Function
int main()
{
    printf("GRAMMAR is -\nE->2E2 \nE->3E3 \nE->4\n");  
    // ab is input string
    strcpy(ab,"32423");
    // strlen(ab) will return the length of ab to c
    c=strlen(ab);
    // "SHIFT" is copied to act to be printed
    strcpy(act,"SHIFT");
    // This will print Labels (column name)
    printf("\nstack \t input \t action");
    // This will print the initial
    // values of stack and input
    printf("\n$\t%s$\t", ab);   
    // This will Run upto length of input string
    for(i = 0; j < c; i++, j++)
    {
        // Printing action
        printf("%s", act);  
        // Pushing into stack
        stak[i] = ab[j];    
        stak[i + 1] = '\0';
        // Moving the pointer
        ab[j]=' ';
        // Printing action
        printf("\n$%s\t%s$\t", stak, ab);  
        // Call checking function ..which will
        // checking the stack whether its contain
        // any production or not
        checking();
    }
    // Rechecking last time if contain
    // any valid production then it will
    // replace otherwise invalid
    checking();
    // if top of the stack is E(starting symbol)
    // then it will accept the input
    if(stak[0] == 'E' && stak[1] == '\0')
        printf("Accept\n");
    else //else reject
        printf("Reject\n");
}

Output:

GRAMMAR is -
E->2E2 
E->3E3 
E->4
stack    input   action
$       32423$  SHIFT
$3       2423$  SHIFT
$32       423$  SHIFT
$324       23$  REDUCE TO E -> 4
$32E       23$  SHIFT
$32E2       3$  REDUCE TO E -> 2E2
$3E         3$  SHIFT
$3E3         $  REDUCE TO E -> 3E3
$E           $  Accept

Picture of output terminal:

Shift Reduce Parsing

Related Topics

SLR 1 Parsing Compiler Design

SLR(1) Parsing It is a simple LR parsing. Most of the function of this parsing is the same as LR(0) parsing. The parsing table for both the parser vary. The SLR(1)...

5 minutes read.

YACC in Compiler Design

YACC  YACC is known as Yet Another Compiler Compiler. It is used to produce the source code of the syntactic analyzer of the language produced by LALR (1) grammar. The input...

5 minutes read.

Symbol Table Compiler Design

Symbol Table It is an important data structure used by the compiler. It stores information about various entities such as object, class, variable names, functions name, interfaces, procedure, literals, string etc.  The...

3 minutes read.

Translation of Array References in Compiler Design

Translation of Array References We can access the elements of an array stored in consecutive blocks very easily and quickly. In a programming language like C and Java, the size of...

2 minutes read.

Data Flow Analysis in Compiler Design

Data Flow Analysis All the optimization techniques we have learned earlier depend on data flow analysis. DFA is a technique used to know about how the data is flowing in any...

3 minutes read.

Switch Case Statement Compiler Design

Case Statement The “case” or “switch” statement is available in various languages. The following is the syntax for the case statement: switch (E)  {             case V1: S1             case V2: S2 ...

1 minute read.

Ambiguity Elimination Compiler Design

Ambiguity Elimination Ambiguity elimination makes the sentence clear and readable. A sentence is grammatically ambiguous if it can produce more than one parse tree for a particular grammar. In this article,...

3 minutes read.

Three-Address Code

Three-Address Code If there is at most one operator on the right side of the instruction, then the instruction will be the three-address code so that no arithmetic expressions are permitted....

2 minutes read.

Lexical Analysis in Compiler Design

Lexical Analysis It is the first phase of the compiler. As we know, it is also known as a scanner. The input for lexical analysis is source code. After taking source...

2 minutes read.

Run-Time Storage Management

Run-Time Storage Management Every executing program has its own logical address space. Logical address space is partitioned into: Code: It is responsible for storing the executable target code. Static: It is used to...

3 minutes read.

LR Parser Compiler Design

LR Parser LR parsing is a type of bottom-up parsing that is used to parse the large class of grammars. Here "L" stands for left-to-right scanning of the input "R" stands...

6 minutes read.

Run-Time Environments

Run-Time Environments Storage Organization Every target program has its own logical address, and an executable program runs in it. The logical address space has the location for each program value. The...

2 minutes read.

Target Machine

Target Machine A target machine is a byte-addressable machine. This machine has n general-purpose registers, R0, R1,.....Rn-1. A Simple Target Machine Model has three-address instruction. A full-edged assembly language would have...

3 minutes read.

Syntax-Directed Translation

Syntax-Directed Translation A context-free-grammar with some additional rules is known as a syntax-directed definition. In SDT, attributes are associated with grammar symbols and rules are associated with productions. The attributes can...

3 minutes read.

Syntax Analysis Compiler Design

Syntax Analysis This article will describe the parsing method used in the compiler. The grammatical rule of programming language can be constructed with the help of context-free grammars or BNF (Backus–Naur...

3 minutes read.

Code Generation

Code Generation The last phase of the compiler is code generation. It is the compiler's back-end that makes multiple passes over the IR before generating the target program. The code generator's...

4 minutes read.

LEX

LEX Lex is a tool/computer program that generates a Lexical analyzer. Lex is developed by Vern Paxson in C around 1987. Lex works together with the YACC parser generator. It allows...

3 minutes read.

Intermediate-Code Generator Compiler Design

Intermediate-Code Generator The process of translating a source language into machine code for a given target machine is done by intermediate-code. It lies between the high-level language and the machine language....

2 minutes read.

Stack Allocation of Space

Stack Allocation of Space Almost all compilers for languages that use procedure, functions, or methods manage their run-time memory as a stack. Whenever a procedure is called, the local variable's space...

2 minutes read.

Shift Reduce Parsing in Compiler Design

Like the bottom-up parsing, the shift reduce parser also builds the parse tree from the leaves (bottom) to the root (up). The LR parser is a more versatile variation of...

4 minutes read.