Top-Down Parsing

Outline

Introduction to Top-Down Parsing

Recursive Descent Parsing

Recursive Descent Parsing

  1. Try \(E_0 \rightarrow T_1 + E_2\)

  2. Try \(T_1 \rightarrow (E_3)\)

    • The left parenthesis does not match the token \(int(5)\)
  3. Try \(T_1 \rightarrow int\)

    • Matches, but \(+\) after \(T_1\) does not match \(*\)
  4. Try \(T_1 \rightarrow int * T_2\)

    • Matches and consumes two tokens

      • Try \(T_2 \rightarrow int\) matches, but \(+\) after \(T_1\) does not

      • Try \(T_2 \rightarrow int * T_3\) but \(+\) does not match end-of-input

  5. Has exhausted the choices for \(T_2\)

    • Backtrack to choice for \(E_0\)

Recursive Descent Parsing

  1. Try \(E_0 \rightarrow T_1\)

  2. Follow same steps as before for \(T_1\)

    • and succeed with \(T_1 \rightarrow int(5) * T_2\) and \(T_2 \rightarrow int(2)\)

    • with the following parse tree

Recursive Descent Parsing: Notes

When Recursive Descent Does Not Work

Elimination of Left Recursion

Elimination of Left-Recursion

General Left Recursion

Summary of Recursive Descent

Predictive Parsers

\(LL(1)\) Languages

Predictive Parsing and Left Factoring

Left-Factoring Example

\(LL(1)\) Parsing Table Example

\(LL(1)\) Parsing Table Example

Using Parsing Tables

\(LL(1)\) Parsing Algorithm

initialize stack = <S, $> and next
repeat
  case stack of
    <X, rest>  : if T[X, *next] = Y1 ... Yn
                 then stack := <Y1 ... Yn rest>
                 else error()
    <t, rest>  : if t == *next++
                 then stack := <rest>
                 else error()
until stack == <>

\(LL(1)\) Parsing Example

Stack Input Action
\(E \; \$\) \(int * int \; \$\) \(T \; X\)
\(T \; X \; \$\) \(int * int \; \$\) \(int \; Y\)
\(int \; Y \; \; X \; \$\) \(int * int \; \$\) terminal
\(Y \; \; X \; \$\) \(* int \; \$\) \(* \; T\)
\(* \; T \; X \; \$\) \(* int \; \$\) terminal
\(T \; X \; \$\) \(int \; \$\) \(int \; Y\)
\(int \; Y \; X \; \$\) \(int \; \$\) terminal
\(Y \; X \; \$\) \(\$\) \(\epsilon\)
\(X \; \$\) \(\$\) \(\epsilon\)
\(\$\) \(\$\) ACCEPT

Constructing Parsing Tables

Constructing Parsing Tables

Computing First Sets

First Sets Example

Computing Follow Sets

Follow Sets Example

Constructing \(LL(1)\) Parsing Tables

Notes on \(LL(1)\) Parsing Tables