CFG to PDA

2 min read Updated Fri Apr 24 2026 03:19:45 GMT+0000 (Coordinated Universal Time)

A langauge is context-free iff a PDA recognizes it.

Top-down approach

Simulates left-most derivation.

Suppose a CFG G=(V,Σ,R,S)G=(V,\Sigma,R,S) is given. The corresponding PDA is defined as M=(Q,Σ,Γ,q0,Z0,A,δ)M=(Q,\Sigma,\Gamma,q_0,Z_0,A,\delta) where:

  • Q={q0,q1,q2}Q=\set{ q_0, q_1, q_2 }
    Only 3 states are enough.
  • Σ\Sigma (input alphabet) is the same as of GG
  • Γ=VΣ{Z0}\Gamma=V\cup \Sigma \cup \set{ Z_0 }
    Stack contains the terminals, the non-terminals and Z0Z_0.
  • A={q2}A=\set{ q_2 }

And δ\delta is defined as follows:

ConfigurationNext StateStack Top ReplacementDescription
(q0,Λ,Z0)(q_0,\Lambda,Z_0)q1q_1SZ0S Z_0Move to q1q_1 and push start symbol SS to the stack
(q1,Λ,Z0)(q_1,\Lambda,Z_0)q2q_2Z0Z_0Only move to q2q_2 from q1q_1 (not q0q_0) when stack has Z0Z_0 only
(q1,Λ,X)(q_1,\Lambda,X)q1q_1α\alphaXV,XαP\forall X \in V, X\rightarrow \alpha \in P
(q1,a,a)(q_1,a,a)q1q_1Λ\LambdaaΣ\forall a \in \Sigma

Bottom-up approach

Simulates right-most derivation in reverse.

Suppose G=(V,Σ,P,S)G = (V, \Sigma, P, S). The corresponding PDA M=(Q,Σ,Γ,q0,Z0,A,δ)M = (Q, \Sigma, \Gamma, q_0, Z_0, A, \delta) where:

  • Q={q0,q1,q2}Q = \set{ q_0, q_1, q_2 }
    Only 3 states are enough.
  • Σ\Sigma is the same as CFG
  • Γ=VΣ{Z0}\Gamma = V \cup \Sigma \cup \set{Z_0}
    Stack contains the terminals, the non-terminals and Z0Z_0.
  • A={q2}A = \set{ q_2 }

And the transition function is defined as:

ConfigurationNext StateStack ReplacementDescription
(q0,Λ,Z0)(q_0,\Lambda,Z_0)q1q_1Z0Z_0Move to working state.
(q1,a,X)(q_1,a,X)q1q_1aXaXPush input symbol aa onto stack.
(q1,Λ,α)(q_1, \Lambda, \alpha)q1q_1XXIf XαPX \to \alpha \in P. Reverse of production. Main step of bottom-up parsing.
(q1,Λ,SZ0)(q_1, \Lambda, S Z_0)q2q_2Z0Z_0Accept when reduced to start symbol.