Skip to content

Lecture No. 21

Dated: 09-04-2025

Shift Reduce: the Stack

The shift action pushes a terminal1 on the stack.
Reduce

  • Pops one or more symbols from the stack (right hand side of production1)
  • Pushes a non terminal1 on the stack (left hand side of production1)

Discovering Handles

The upper edge of a partially constructed parse tree2 is called its upper frontier.
The parser3 must find some substring \(\beta\) of the upper frontier where

  • \(\beta\) is the right hand side of some production \(A \to \beta\) and
  • \(A \to \beta\) is one step in right most derivation of input stream

Each potential match is represented as a pair \(<A \to \beta, k>\) where \(k\) is the position on the tree2's current frontier of the right end of \(\beta\).
This pair is called the handle of the bottom up parser.3

Handle Pruning

The use of stack simplifies the parsing algorithm in 2 ways.

  1. It trivializes the problem of managing space for the frontier by pushing the input characters at top of the stack.
  2. It makes sure that all handles occur with their right ends at the top of the stack, eliminating the need to keep track of position \(k\).

Shift-reduce Parsing Algorithm

push $ onto stack
sym ← nextToken()
repeat until

stack.push("$")
sym = nextToken()

while (not (sym == "$" and stack[1] == "G")): # Goal symbol right above $ symbol
    if (stack.top() == "A -> B"):
        stack.pop() # pops all B
        stack.push("A")
    else if (sym != "$"):
        stack.push(sym)
        sym = nextToken()
    else:
        # report error and halt

References


  1. Read more about grammar terminologies

  2. Read more about parse trees

  3. Read more about parsers