Sub topic 10
From CFG to PDA and back
This chapter assumes you can write a context-free grammar (CFG) and read a derivation. It also assumes you know how a pushdown automaton (PDA) moves, and that you know acceptance by empty stack and by final state. The goal is to show both directions of the equivalence: every CFG has an equivalent PDA, and every PDA has an equivalent CFG. You then get the facts that GATE questions test.
The claim
A language is context-free if and only if some nondeterministic PDA accepts it. The proof has two constructions:
- CFG to PDA. The PDA simulates a leftmost derivation on its stack.
- PDA to CFG. Each variable of the grammar describes one way the PDA can consume a stack symbol.
From CFG to PDA
Take a grammar G = (V, T, P, S). Build a PDA with one state q that accepts by empty stack:
- Start with S on the stack. The top of the stack is the leftmost symbol.
- For each production A → α, add the move "on ε input with A on top, replace A by α". This move is nondeterministic whenever A has more than one production.
- For each terminal a, add the move "on input a with a on top, pop it".
The stack always holds the part of a sentential form that has not been matched yet. Variables at the top are expanded. Terminals at the top are checked against the input. If the input is a derivable string, some sequence of choices empties the stack exactly when the input ends.
Worked trace for S → aSb | ab
The table traces the input aabb. The stack is written with its top on the left.
| Step | Move | Remaining input | Stack |
|---|---|---|---|
| 0 | start | aabb | S |
| 1 | expand S → aSb | aabb | aSb |
| 2 | match a | abb | Sb |
| 3 | expand S → ab | abb | abb |
| 4 | match a | bb | bb |
| 5 | match b | b | b |
| 6 | match b | (empty) | (empty) |
The stack and the input are both empty, so the string is accepted.
Running the construction
The Python function below explores every configuration of this PDA. A configuration is a pair (input position, stack). It prunes any stack longer than the remaining input. That pruning is valid only when the grammar has no ε-productions, because then every stack symbol must produce at least one terminal. Without it, a left-recursive grammar would make the search infinite.
def cfg_pda_accepts(w, rules, start="S"):
"""Search the one-state PDA built from a CFG without epsilon productions.
rules maps a variable to a list of right-hand-side strings.
Uppercase letters are variables, lowercase letters are terminals."""
first = (0, start)
seen = {first}
todo = [first]
while todo:
pos, stack = todo.pop()
if not stack:
if pos == len(w):
return True
continue
top, rest = stack[0], stack[1:]
if top in rules:
for rhs in rules[top]:
nxt = (pos, rhs + rest)
if len(nxt[1]) <= len(w) - pos and nxt not in seen:
seen.add(nxt)
todo.append(nxt)
elif pos < len(w) and w[pos] == top:
nxt = (pos + 1, rest)
if nxt not in seen:
seen.add(nxt)
todo.append(nxt)
return False
rules = {"S": ["aSb", "ab"]}
for s in ["ab", "aabb", "aab", "abab", ""]:
print(repr(s), cfg_pda_accepts(s, rules))The output is True for ab and aabb, and False for the other three strings.
From PDA to CFG
Start with a PDA M = (Q, Σ, Γ, δ, q₀, Z₀) that accepts by empty stack. Any PDA can be converted to this form first.
The grammar has these variables:
- A start variable S.
- A variable [p X q] for every p, q in Q and X in Γ.
The intended meaning of [p X q] is this: the PDA can go from state p to state q, consume exactly the string that [p X q] derives, and in doing so remove X from the stack. It never touches the symbols below X.
The productions are:
- S → [q₀ Z₀ q] for every state q.
- If δ(p, a, X) contains (r, ε), where a may be ε, add [p X r] → a.
- If δ(p, a, X) contains (r, Y₁Y₂…Yk) with k ≥ 1, add for every choice of states q₁, …, qk:
[p X qk] → a [r Y₁ q₁] [q₁ Y₂ q₂] … [q{k-1} Yk qk]
Rule 3 says that to remove X, the PDA first replaces it by Y₁…Y_k. It then removes Y₁ (ending in some state q₁), then Y₂, and so on. The grammar guesses all the intermediate states.
Sizes that GATE asks about
- The number of variables is at most |Q|² · |Γ| + 1.
- A move that pushes k symbols produces |Q|^k productions of type 3. A move that pushes two symbols in a PDA with 3 states gives 9 productions.
- Many of these variables are useless. Removing useless symbols (see the chapter on simplification) shrinks the grammar. The construction is correct without that clean-up, but it is wasteful.
Acceptance modes inside the equivalence
For nondeterministic PDAs, final-state acceptance and empty-stack acceptance define the same class of languages. The two conversions are mechanical. The next table summarises them.
| Direction | What you add |
|---|---|
| Final state to empty stack | A new bottom marker, a new start state, and ε-moves from every final state into a new state that pops until the stack is empty. |
| Empty stack to final state | A new bottom marker. When it appears alone on the stack, move by an ε-transition to a new final state. |
This equivalence fails for deterministic PDAs. A deterministic PDA that accepts by empty stack can only accept prefix-free languages, which are languages where no string is a proper prefix of another. For example, {a}* can be accepted by final state, but no deterministic empty-stack PDA accepts it. The chapter on deterministic and nondeterministic PDAs returns to this.
Common errors
- Direction of the stack. In the CFG-to-PDA construction, the right-hand side α is pushed so that its first symbol ends up on top. If you push it in the wrong order, you simulate a derivation of the reversed string.
- Using final states in the CFG-to-PDA PDA. The one-state PDA has no final state to speak of. Accept by empty stack, or add the standard conversion.
- Expecting determinism. The PDA built from a CFG is nondeterministic whenever a variable has several productions. That does not mean the language needs a nondeterministic PDA. For example, S → aSb | ab produces a nondeterministic PDA, yet this language has a deterministic one.
- Forgetting ε-productions in the simulation. Pruning by stack length, as in the Python code, is wrong for grammars with ε-productions.
Why the equivalence matters
The equivalence moves facts between the two models:
- Closure under union, concatenation, and Kleene star is easiest to show with grammars.
- Closure under intersection with a regular language is easiest to show with PDAs, by running the PDA and a finite automaton in parallel.
- Parsers use PDA-like stacks, and the CYK algorithm from a later chapter uses the grammar form.
Exercise
A PDA has 3 states and 2 stack symbols and accepts by empty stack. At most how many variables does the grammar from the triple construction have? One transition of this PDA pushes two symbols. How many type-3 productions does that single transition generate?
Show answer
The variables are S plus [p X q] for 3 × 2 × 3 = 18 triples, so at most 19. A transition pushing two symbols yields |Q|² = 9 productions, one for each choice of the two intermediate states q₁ and q₂.
Exercise
Build the one-state PDA from the grammar S → aSb | ε. List its moves, then say whether the Python function in this chapter can test this grammar.
Show answer
The moves are: on ε with S on top, replace S by aSb; on ε with S on top, replace S by nothing; on a with a on top, pop; on b with b on top, pop. The PDA accepts by empty stack. The Python function cannot be used as written, because the grammar has an ε-production and the pruning rule "stack length at most remaining input" would reject valid derivations such as the one for the empty string.