A langauge is context-free iff a PDA recognizes it.
Top-down approach
Simulates left-most derivation.
Suppose a CFG G=(V,Σ,R,S) is given. The corresponding PDA is defined as M=(Q,Σ,Γ,q0,Z0,A,δ) where:
- Q={q0,q1,q2}
Only 3 states are enough.
- Σ (input alphabet) is the same as of G
- Γ=V∪Σ∪{Z0}
Stack contains the terminals, the non-terminals and Z0.
- A={q2}
And δ is defined as follows:
| Configuration | Next State | Stack Top Replacement | Description |
|---|
| (q0,Λ,Z0) | q1 | SZ0 | Move to q1 and push start symbol S to the stack |
| (q1,Λ,Z0) | q2 | Z0 | Only move to q2 from q1 (not q0) when stack has Z0 only |
| (q1,Λ,X) | q1 | α | ∀X∈V,X→α∈P |
| (q1,a,a) | q1 | Λ | ∀a∈Σ |
Bottom-up approach
Simulates right-most derivation in reverse.
Suppose G=(V,Σ,P,S). The corresponding PDA M=(Q,Σ,Γ,q0,Z0,A,δ) where:
- Q={q0,q1,q2}
Only 3 states are enough.
- Σ is the same as CFG
- Γ=V∪Σ∪{Z0}
Stack contains the terminals, the non-terminals and Z0.
- A={q2}
And the transition function is defined as:
| Configuration | Next State | Stack Replacement | Description |
|---|
| (q0,Λ,Z0) | q1 | Z0 | Move to working state. |
| (q1,a,X) | q1 | aX | Push input symbol a onto stack. |
| (q1,Λ,α) | q1 | X | If X→α∈P. Reverse of production. Main step of bottom-up parsing. |
| (q1,Λ,SZ0) | q2 | Z0 | Accept when reduced to start symbol. |