Sub topic 6
Simplifying Grammars: Useless Symbols, Epsilon and Unit Productions
Assume you know alphabets, strings, finite automata, and basic set operations. A context-free grammar (CFG) is easier to analyze after removing rules that add no useful structure.
Three sources of unnecessary structure
A useless symbol is a variable that cannot contribute to a terminal string generated from the start symbol. There are two reasons:
- A symbol is nongenerating if it cannot derive any string containing only terminals.
- A symbol is unreachable if no derivation from the start symbol can reach it.
An epsilon production has the form \(A \to \epsilon\), where \(\epsilon\) is the empty string. A variable that can derive \(\epsilon\) is called nullable.
A unit production has the form \(A \to B\), where both sides are variables. It adds no terminal or structural information, so it can usually be replaced by copying the rules of \(B\).
A safe simplification workflow
Use the following sequence:
- Find nullable variables and remove epsilon productions by adding the alternatives obtained by omitting nullable variables.
- Remove unit productions by adding each non-unit rule reachable through a chain of unit rules.
- Remove nongenerating symbols and then unreachable symbols.
- Repeat a check if a transformation creates new useless symbols.
If the start symbol can derive \(\epsilon\), introduce a fresh start symbol \(S0\) with \(S0 \to S \mid \epsilon\). This preserves the empty string while preventing later transformations from removing the intended start rule.
Original:
S -> AB | C
A -> aA | ε
B -> bB | b
C -> D
D -> d
E -> eE
F -> G
G -> F
After removing ε from A:
S -> AB | B | C
A -> aA | a
B -> bB | b
C -> D
D -> d
After removing unit productions:
S -> AB | bB | b | d
A -> aA | a
B -> bB | bHere, E is unreachable from S. Symbols F and G are mutually recursive but nongenerating, because neither can reach a terminal string. All three are removed.
Why the order matters
Removing epsilon rules can create new alternatives, such as \(S \to B\). That new rule may be a unit production and must be handled afterward. Unit elimination can expose terminal rules that make other symbols generating. Therefore, do not delete symbols based only on the original grammar.
The simplified grammar usually generates the same language as the original grammar, except that epsilon may require special handling through a fresh start symbol.
::: callout note For unit elimination, compute the transitive closure of unit rules. If \(A \Rightarrow B\) and \(B \Rightarrow C\), copy non-unit rules from both \(B\) and \(C\) to \(A\). :::
Exercise
In the grammar S -> AB, A -> ε, B -> b, which new production is required when removing the epsilon production?
Show answer
Add S -> B, because the nullable A may be omitted from S -> AB.