Bottom-Up Parsing

Outline

Top-Down Parsing: Review

Predictive Parsing: Review

Bottom-Up Parsing

An Introductory Example

The Idea

Bottom-up Parsing Example

Reductions

Notation

Shift-Reduce Parsing

Shift-Reduce Example

The Stack

Question: To Shift or Reduce

\(LR(1)\) DFA Example

\(LR(1)\) DFA Example (Continued)

\(LR(1)\) DFA Example (Continued)

Representing the DFA

Representing the DFA Example

\(int\) \(+\) \((\) \()\) \(\$\) \(E\)
0 s1 g2
1 r(\(E \rightarrow int\)) r(\(E \rightarrow int\))
2 s3 accept
3 s4
4 s5 g6
5 r(\(E \rightarrow int\)) r(\(E \rightarrow int\))
6 s8 s7
7 r(\(E \rightarrow E + (E)\)) r(\(E \rightarrow E + (E)\))
8 s9
9 s5 g10
10 s8 s11
11 r(\(E \rightarrow E + (E)\)) r(\(E \rightarrow E + (E)\))

The \(LR\) Parsing Algorithm

The \(LR\) Parsing Algorithm

let I = w$ be the initial input
let j = 0
let DFA state 0 be the start state
let stack = <dummy, 0>
repeat
  case action[top_state(stack), I[j]] of
    shift k: push <I[j++], k>
    reduce X -> A:
      pop |A| pairs
      push <X, goto[top_state(stack), X]>
    accept: halt normally
    error: halt and report error

\(LR\) Parsers

Key Issue: How is the DFA Constructed?

\(LR(0)\) Items

\(LR(0)\) Items: Intuition

\(LR(1)\) Items

Note

Convention

\(LR(1)\) Items Continued

\(LR(1)\) Items Continued

The Closure Operation

Constructing the Parsing DFA (1)

Constructing the Parsing DFA (2)

The DFA Transitions

LR Parsing Tables: Notes

Shift/Reduce Conflicts

Shift/Reduce Conflicts

More Shift/Reduce Conflicts

More Shift/Reduce Conflicts

Using Precedence to Resolve Shift/Reduce Conflicts

Using Precedence to Resolve Shift/Reduce Conflicts

Precedence Declarations Revisited

Reduce/Reduce Conflicts

Reduce/Reduce Conflicts

Using Parser Generators

\(LR(1)\) Parsing Tables are Big

The Core of a Set of \(LR\) Items

\(LALR\) States

A \(LALR(1)\) DFA

The \(LALR\) Parser Can Have Conflicts

\(LALR\) versus \(LR\) Parsing

Semantic Actions in \(LR\) Parsing

Performing Semantic Actions: Example

Performing Semantic Actions: Example

Performing Semantic Actions: Example

String Action
\(\vert int * int + int\) shift
\(int(4) \vert * int + int\$\) shift
\(int(4) * \vert int + int\$\) shift
\(int(4) * int(9) \vert + int\$\) reduce \(T \rightarrow int\)
\(int(4) * T(9) \vert + int\$\) reduce \(T \rightarrow int * T\)
\(T(36) \vert + int\$\) shift
\(T(36) + \vert int\$\) shift
\(T(36) + int(6) \vert\$\) reduce \(T \rightarrow int\)
\(T(36) + T(6) \vert\$\) reduce \(E \rightarrow T\)
\(T(36) + E(6) \vert\$\) reduce \(E \rightarrow T + E\)
\(E(42) \vert\$\) accept

Notes on Parsing