Sub topic 10
From CFG to PDA and Back
Assume you know alphabets, strings, context-free grammars (CFGs), derivations, and basic pushdown automata (PDAs). This chapter connects the two models. A CFG generates a language, while a PDA recognises a language. They have exactly the same expressive power.
From a CFG to a PDA
Let
\[ G=(V,\Sigma,R,S) \]
be a CFG. Here, \(V\) is the set of variables, \(\Sigma\) is the set of terminals, \(R\) is the set of productions, and \(S\) is the start variable.
Construct a PDA that accepts by empty stack:
- Put \(S\) on the stack.
- If the stack top is a variable \(A\), nondeterministically choose a rule \(A\to\alpha\) and replace \(A\) with \(\alpha\).
- If the stack top is a terminal \(a\), read \(a\) from the input and pop it.
- Accept when the input is fully read and the stack is empty.
The PDA must be nondeterministic because it may have several productions for the same variable. The stack stores the part of a derivation that has not yet been matched.
When a stack uses its rightmost item as the top, push the right-hand side in reverse order. This makes the leftmost symbol available first.
For \(S\to aSb\mid ab\), the PDA can choose expansions that produce \(a^n b^n\). A wrong choice eventually leaves either an unmatched terminal or unread input.
from collections import deque
rules = {"S": [("a", "S", "b"), ("a", "b")]}
def accepts(word):
"""Simulate the CFG-to-PDA construction for a^n b^n."""
queue = deque([(0, ("S",))])
seen = set()
while queue:
position, stack = queue.popleft()
configuration = (position, stack)
if configuration in seen:
continue
seen.add(configuration)
if not stack:
if position == len(word):
return True
continue
top = stack[-1]
if top in rules:
for right_side in rules[top]:
new_stack = stack[:-1] + tuple(reversed(right_side))
queue.append((position, new_stack))
elif position < len(word) and top == word[position]:
queue.append((position + 1, stack[:-1]))
return False
print(accepts("aabb")) # True
print(accepts("aab")) # FalseFrom a PDA to a CFG
The reverse construction records complete stack-removal computations. First convert the PDA into a convenient form:
- Every transition reads either one input symbol or epsilon.
- A transition changes one stack symbol into either zero, one, or two symbols.
- Acceptance uses a designated final state or empty stack.
For states \(p,q\) and stack symbol \(A\), create a variable \([pAq]\). It means: starting in state \(p\) with \(A\) on top, the PDA can remove \(A\), consume some input, and finish in state \(q\).
Productions describe the possible first transitions. For example, a transition that reads \(a\) and pops \(A\) gives:
\[ [pAr]\to a \]
If a transition replaces \(A\) with \(BC\), the grammar introduces an intermediate state \(s\):
\[ [pAq]\to a[pBs][sCq] \]
Adding such rules for every valid state choice produces a CFG for the PDA's language. The construction is finite because the PDA has finitely many states and stack symbols.
The key equivalence
| Model | Memory mechanism | Nondeterministic power |
|---|---|---|
| CFG | Recursive variables | Exactly the CFLs |
| PDA | One unbounded stack | Exactly the CFLs |
Thus, a language is context-free if and only if some PDA recognises it.
Exercise
For the grammar S -> aSb | ab, what stack operation corresponds to expanding S with the rule S -> ab when the stack top is the rightmost item?
Show answer
Pop S and push b followed by a, so that a is on top and will be matched first.