Sub topic 6
Simplifying grammars: useless symbols, epsilon and unit productions
This chapter assumes you can read a context-free grammar (CFG) as a four-tuple (V, Σ, P, S) and can write a derivation. A grammar as written often has symbols that never help, productions that erase symbols, and productions that only rename one variable as another. Normal forms such as Chomsky normal form require these to be removed first. So do the CYK algorithm and several decision procedures. GATE also asks about them directly.
The three clean-ups
- A useless symbol is a variable that never appears in any derivation of a terminal string from S. It is useless for one of two reasons. Either it cannot derive any terminal string (not generating), or it cannot be reached from S (not reachable).
- An ε-production has the form A → ε. A variable is nullable if A ⇒* ε.
- A unit production has the form A → B, where B is a single variable.
Each clean-up must preserve the language. The one exception is ε. Once ε-productions are removed, the grammar cannot derive ε, so the result generates L(G) − {ε}.
Order matters
Apply the steps in this order: ε-productions, then unit productions, then useless symbols.
There are two reasons for this order. Removing ε-productions can create new unit productions. For example, S → AB becomes S → A when B is nullable. Removing useless symbols last also discards variables that the earlier steps left behind.
Step 1: remove ε-productions
- Compute the nullable set. Start with every A that has A → ε. Then repeatedly add any A that has a production whose body consists only of nullable variables. Stop when nothing changes.
- For every production, add a version for each way of deleting some subset of the nullable variables in the body. Drop any version whose body is empty.
- Delete all ε-productions.
A body with k nullable variable occurrences yields up to 2^k versions, and the all-deleted version is dropped. For S → ABC with A, B and C all nullable, that gives 7 non-empty bodies.
If ε was in the language (S is nullable), add S → ε back. This is safe only if S appears on no right-hand side. Otherwise, introduce a new start symbol S₀ with S₀ → S | ε.
Step 2: remove unit productions
- Find all unit pairs (A, B), meaning A ⇒* B using only unit productions. Every (A, A) counts.
- For each pair (A, B), and for each non-unit production B → α, add A → α.
- Delete all unit productions.
Computing the pairs by closure also handles cycles such as A → B, B → A.
Step 3: remove useless symbols
Do this in two passes, and do them in this order.
- Generating: start with the variables that have a production body made only of terminals (or an empty body). Repeatedly add any variable that has a body whose symbols are all terminals or already generating. Remove every non-generating variable and every production that mentions one.
- Reachable: starting from S, mark every variable that appears in a body of a marked variable. Remove everything unmarked.
Reversing the passes can leave useless symbols behind. Take S → a | AB, A → a, B → Bb. B is not generating. If you test reachability first, A and B both survive. Removing B then deletes S → AB and leaves A unreachable but still in the grammar. The correct order gives S → a alone.
Worked example
Start with this grammar:
S -> A B | C
A -> a A | ε
B -> b | A
C -> a C
D -> dStep 1. A is nullable (A → ε). B is nullable (B → A). S is nullable (S → AB). C is not, since every body of C contains a terminal. So ε ∈ L(G). Expanding the nullable variables gives:
S -> A B | A | B | C | ε
A -> a A | a
B -> b | A
C -> a C
D -> dS → ε is safe to keep because S appears on no right-hand side.
Step 2. The non-trivial unit pairs are (S, A), (S, B), (S, C) and (B, A). Also (S, A) is reached again through B. Copying the non-unit productions gives:
S -> A B | a A | a | b | a C | ε
A -> a A | a
B -> b | a A | a
C -> a C
D -> dStep 3. The generating variables are A, B, S and D. C only derives strings that still contain C, so it is not generating. Removing C and S → aC leaves S, A, B and D. Reachability from S gives {S, A, B}, so D goes too:
S -> A B | a A | a | b | ε
A -> a A | a
B -> b | a A | aAs a check, the original grammar generates a\b ∪ a\, and the result generates the same set.
Computing the sets in code
The three fixed-point computations share one pattern: loop until nothing changes.
grammar = {
"S": [["A", "B"], ["C"]],
"A": [["a", "A"], []],
"B": [["b"], ["A"]],
"C": [["a", "C"]],
"D": [["d"]],
}
def nullable(g):
result, changed = set(), True
while changed:
changed = False
for v, bodies in g.items():
if v not in result and any(all(s in result for s in b) for b in bodies):
result.add(v)
changed = True
return result
def generating(g):
result, changed = set(), True
while changed:
changed = False
for v, bodies in g.items():
ok = any(all(s in result or s not in g for s in b) for b in bodies)
if v not in result and ok:
result.add(v)
changed = True
return result
def reachable(g, start):
seen, todo = {start}, [start]
while todo:
v = todo.pop()
for body in g[v]:
for s in body:
if s in g and s not in seen:
seen.add(s)
todo.append(s)
return seen
gen = generating(grammar)
pruned = {v: [b for b in bodies if all(s in gen or s not in grammar for s in b)]
for v, bodies in grammar.items() if v in gen}
print(sorted(nullable(grammar))) # ['A', 'B', 'S']
print(sorted(gen)) # ['A', 'B', 'D', 'S']
print(sorted(reachable(pruned, "S"))) # ['A', 'B', 'S']An empty body makes all(...) true, so ε-productions count correctly in both nullable and generating.
Common errors
- Forgetting that the all-deleted version of a body is dropped, which would reintroduce ε-productions.
- Deleting only the variable's ε-production without adding the shortened bodies. This shrinks the language.
- Removing unit productions by deletion alone. You must copy the non-unit bodies across each unit pair.
- Leaving the start symbol's ε behind and then claiming the grammar is in a normal form. Chomsky normal form allows S → ε only when S is not on any right-hand side.
- Testing reachability before generating.
GATE patterns
Questions typically ask for one of these:
- The number of productions after removing ε or unit productions. Count carefully with 2^k − 1 for k nullable occurrences in a body, and remember duplicates collapse.
- Whether a stated variable is nullable, generating or reachable.
- Whether the simplified grammar still generates the same language. It does, except for ε as described above.
Exercise
In the grammar S -> A B C, A -> a | ε, B -> b | ε, C -> c | ε, how many productions does S have after ε-production removal, including S -> ε if it is needed?
Show answer
All of A, B and C are nullable, so S is nullable and ε is in the language. Deleting any non-empty subset of the three variables gives 2^3 - 1 = 7 shorter bodies, which with the original ABC makes 8 non-empty bodies: ABC, AB, AC, BC, A, B, C. Counting carefully, ABC plus the 6 proper non-empty subsets of remaining variables (AB, AC, BC, A, B, C) gives 7 non-empty bodies. Since S appears on no right-hand side, S -> ε can be kept, so S has 8 productions in total.
Exercise
Why must a grammar be checked for non-generating symbols before unreachable symbols?
Show answer
A variable can be reachable only through a production that contains a non-generating variable. Removing the non-generating variable deletes that production, which can make the first variable unreachable. If reachability is checked first, that variable would be kept as a useless symbol.