Context free grammars and simplification — Unit 3 Notes (Theory of Automata and Formal Languages)

BCS404 · Unit 3

Context free grammars and simplification notes — Unit 3

Free unit-wise study notes on context free grammars and simplification for Theory of Automata and Formal Languages, Semester 4 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.

Moving beyond the limits of DFAs. Covers the power of Context-Free Grammars (CFG), derivation trees, handling Ambiguity, simplifying grammars by removing useless symbols and unit productions, and standardizing grammars into Chomsky Normal Form (CNF) and Greibach Normal Form (GNF).

Notebook — 12 pages

Page 1

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

1. Context-Free Grammars (CFG)

In Unit 2, we proved that regular languages (DFAs/REs) cannot count. They cannot handle languages with nested dependencies like anbna^n b^n.

To describe these more complex, nested languages (which form the foundation of all programming language syntax, like matching nested `{ }` brackets in C++), Noam Chomsky introduced Context-Free Grammars.

1.1 The CFG Definition

A CFG is a 4-tuple G=(V,T,P,S)G = (V, T, P, S). The variables VV, terminals TT, and start symbol SS are the same as regular grammars. The massive power difference lies in the Production Rules PP.

The CFG Rule: Every production must be in the form:
AαA \rightarrow \alpha

Where:
-
AVA \in V (Exactly ONE single Non-Terminal variable on the Left side).
-
α(VT)\alpha \in (V \cup T)^* (The Right side can be literally ANYTHING. Any combination of terminals, non-terminals, mixed together in any order, or even the empty string ϵ\epsilon).

Because the left side is just a single isolated variable 'A', we can replace 'A' with α\alpha regardless of the surrounding context. Hence, "Context-Free".

Next — CFG Examples and Power

1 of 12

Page 2

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

2. CFG Examples and Power

2.1 Solving the Counting Problem

How does a CFG solve L={anbn}L = \{a^n b^n\}? Through symmetric recursion.

Grammar:
SaSbS \rightarrow aSb
SϵS \rightarrow \epsilon

Derivation of string `aaabbb`:
SaSbS \Rightarrow aSb
aaSbb\Rightarrow aaSbb (Replaced inner S with aSb)
aaaSbbb\Rightarrow aaaSbbb (Replaced inner S with aSb)
aaabbb\Rightarrow aaabbb (Replaced inner S with ϵ\epsilon)

Because the grammar enforces placing one 'a' on the left and one 'b' on the right simultaneously in a single rule, it is mathematically impossible to generate a mismatched number. A DFA could never do this.

2.2 CFG for Palindromes

Generating strings that read the same forwards and backwards (wwRww^R).
S0S01S101ϵS \rightarrow 0S0 | 1S1 | 0 | 1 | \epsilon

Next — Derivations and Parse Trees

2 of 12

Page 3

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

3. Derivations and Parse Trees

A derivation is the step-by-step sequence of applying production rules to convert the Start symbol into a string of pure terminals.

3.1 Leftmost vs Rightmost Derivation

If a string contains multiple variables (e.g., ABcDA B c D), which one do you replace first?

  • Leftmost Derivation (LMD): At every step, you strictly replace the leftmost non-terminal variable in the string. (This is how most actual compilers parse code).
  • Rightmost Derivation (RMD): At every step, you strictly replace the rightmost non-terminal variable.

3.2 The Parse Tree (Derivation Tree)

A visual, graphical representation of a derivation.
- The Root is the start symbol
SS.
- Internal nodes are non-terminal variables.
- The Leaves are terminal symbols (or
ϵ\epsilon).
- Reading the leaves from left to right yields the final generated string (the yield of the tree).

Crucially, a Parse Tree completely ignores the arbitrary order of substitution (LMD vs RMD). It only shows the structural hierarchy.

Next — Ambiguity in Grammars

3 of 12

Page 4

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

4. Ambiguity in Grammars

This is a critical flaw that breaks compilers.

4.1 The Definition

A Context-Free Grammar is Ambiguous if there exists even a single string in the language that can be generated by two completely different Parse Trees (which is mathematically equivalent to having two distinct Leftmost Derivations).

Consider a math expression grammar: EE+EEEidE \rightarrow E + E \mid E * E \mid id.

Parse the string: `id + id id`. - Tree 1 groups it as `(id + id) id`.
- Tree 2 groups it as `id + (id * id)`.

Both trees are perfectly valid according to the grammar rules. However, they evaluate to completely different mathematical results. If a C++ compiler used an ambiguous grammar, the statement `x = 2 + 3 * 4` might compute to 14 on Monday and 20 on Tuesday. This is catastrophic.

Next — Removing Ambiguity

4 of 12

Page 5

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

5. Removing Ambiguity

There is no magic, universal algorithm to remove ambiguity from any grammar (it is an undecidable problem). It requires human engineering, specifically by forcing Precedence and Associativity into the grammar hierarchy.

5.1 Enforcing Precedence

To fix the math expression grammar, we must force multiplication to happen structurally lower in the parse tree than addition, so it evaluates first.

We introduce new variable layers: EE (Expression), TT (Term), FF (Factor).
EE+TTE \rightarrow E + T \mid T
TTFFT \rightarrow T * F \mid F
F(E)idF \rightarrow (E) \mid id

This new grammar generates the exact same strings, but structurally forces `*` to be resolved before `+`. It is completely Unambiguous.

5.2 Inherent Ambiguity

Some languages are so mathematically twisted that EVERY possible grammar you could ever write for them will be ambiguous. These are called Inherently Ambiguous Languages. (e.g., L={anbncm}{anbmcm}L = \{a^n b^n c^m\} \cup \{a^n b^m c^m\}).

Next — Simplification of CFG

5 of 12

Page 6

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

6. Simplification of CFG

Often, grammars contain garbage rules that bloat the compiler but do absolutely nothing useful. Before we can optimize a grammar into Normal Form, we must surgically remove three types of garbage, strictly in this order:

  • 1. Elimination of Useless Symbols
  • 2. Elimination of ϵ\epsilon-Productions
  • 3. Elimination of Unit Productions

6.1 Removing Useless Symbols

A variable is "useful" only if it satisfies TWO conditions:
1.
Generating: It must eventually be able to derive a string of pure terminals. (e.g., if AaAA \rightarrow aA, it loops forever and never produces a final string. AA is non-generating).
2.
Reachable: There must be a path from the Start Symbol SS to reach the variable. (e.g., if SaBS \rightarrow aB, and there's a rule CdC \rightarrow d, CC is unreachable dead code).

You must first delete all non-generating symbols, and THEN delete all unreachable symbols.

Next — Removing Epsilon and Unit Productions

6 of 12

Page 7

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

7. Removing $\epsilon$ and Unit Productions

7.1 Eliminating ϵ\epsilon-Productions

An ϵ\epsilon-production is a rule like AϵA \rightarrow \epsilon. These make parse trees arbitrarily deep without adding any symbols.

1. Find all "Nullable" variables (variables that can eventually derive ϵ\epsilon).
2. For every rule that contains a nullable variable on the right side, add new rules simulating all possible combinations of that variable disappearing.

Example: Rule is SaAbAS \rightarrow aAbA. AA is nullable.
New rules:
SaAbAS \rightarrow aAbA (Keep both)
SabAS \rightarrow abA (Drop first A)
SaAbS \rightarrow aAb (Drop second A)
SabS \rightarrow ab (Drop both A's)
3. Finally, delete the actual
AϵA \rightarrow \epsilon rule.

7.2 Eliminating Unit Productions

A Unit Production is a rule of the form ABA \rightarrow B, where a single variable points to exactly one other single variable. These are useless "middlemen" that just copy data.

1. Find all unit pairs (A,B)(A, B) meaning A can eventually derive B.
2. If
BightarrowalphaB ightarrow alpha (where α\alpha is NOT a unit production), add the rule AalphaA \rightarrow alpha directly to A.
3. Delete all rules of the form
XYX \rightarrow Y.

Next — Chomsky Normal Form (CNF)

7 of 12

Page 8

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

8. Chomsky Normal Form (CNF)

A standardized, highly structured mathematical format for CFGs. Grammars in CNF are predictable, making parser algorithms (like the CYK algorithm) much faster to execute.

8.1 The Strict Rules of CNF

A grammar is strictly in CNF if EVERY single production rule is in one of two exact formats:

  • ABCA \rightarrow BC (A variable is replaced by EXACTLY TWO variables).
  • AaA \rightarrow a (A variable is replaced by EXACTLY ONE terminal).

No mixing of terminals and variables (e.g., AaBA \rightarrow aB is illegal). No rules with three variables (e.g., ABCDA \rightarrow BCD is illegal).

Mathematical Property: If a grammar is in CNF, any string of length nn will take EXACTLY 2n12n - 1 derivation steps to generate. The parse tree becomes a perfect binary tree.

Next — Converting to CNF

8 of 12

Page 9

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

9. Converting a CFG to CNF

You can algorithmically convert any simplified CFG into CNF.

9.1 The Conversion Algorithm

  • Step 1: Ensure the grammar is simplified (No ϵ\epsilon, no units, no useless).
  • Step 2: Isolate Terminals. For any rule of length > 1 containing terminals (e.g., AaBcA \rightarrow aBc), replace the terminal with a new dedicated variable.
    Create
    XaaX_a \rightarrow a.
    Change the rule to
    AXaBXcA \rightarrow X_a B X_c.
    (Now, all long rules consist purely of variables).
  • Step 3: Break long variable chains. If a rule has more than 2 variables (e.g., ABCDA \rightarrow BCD), break it down in a cascading fashion using new variables.
    Change to:
    ABY1A \rightarrow BY_1
    Y1CDY_1 \rightarrow CD.
    (Now, every rule is either
    ABCA \rightarrow BC or AaA \rightarrow a. The grammar is perfectly in CNF).

Next — Greibach Normal Form (GNF)

9 of 12

Page 10

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

10. Greibach Normal Form (GNF)

Another standard format, invented by Sheila Greibach. While CNF forces binary trees, GNF is specifically designed to make reading strings from left to right extremely efficient. It is heavily used in building Pushdown Automata.

10.1 The Strict Rules of GNF

A grammar is strictly in GNF if EVERY single production rule is in the format:

AaαA \rightarrow a \alpha

Where:
-
aa is EXACTLY ONE terminal symbol at the absolute left position.
-
α\alpha is a string of zero or more VARIABLES. (VV^*).

Valid GNF rules: AaA \rightarrow a, AaBA \rightarrow aB, AaBCDA \rightarrow aBCD.
Invalid rules:
ABaA \rightarrow Ba (variable first), AabA \rightarrow ab (two terminals).

Mathematical Property: Because every single rule application guarantees exactly one new terminal is generated at the front, a string of length nn will be generated in exactly nn steps.

Next — Left Recursion

10 of 12

Page 11

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

11. Left Recursion

A major hurdle in converting to GNF (and building top-down parsers) is Left Recursion.

11.1 The Infinite Loop

A grammar has Left Recursion if a variable can directly or indirectly derive a string starting with itself: AAαA \rightarrow A\alpha.

A top-down parser trying to process this will see an 'A', and replace it with 'A α\alpha'. It then sees the new 'A' and replaces it with 'A α\alpha'. It loops infinitely, crashing the compiler with a Stack Overflow without ever reading a single terminal character.

11.2 Eliminating Left Recursion

We mathematically transform left-heavy rules into right-heavy rules using a new variable.

Given: AAαmidβA \rightarrow A\alpha mid \beta (where β\beta does not start with A).
Replace with:
AβAA \rightarrow \beta A'
AαAmidϵA' \rightarrow \alpha A' mid \epsilon

This generates the exact same language but completely eliminates the infinite loop.

Next — Summary Checklist

11 of 12

Page 12

Wink Notes

B.Tech CSE — 4th Semester

Theory of Automata and Formal Languages

Unit - 3

12. Summary Checklist

Unit 3 is heavily algorithmic. You must be able to surgically modify grammars without changing the underlying language.

12.1 University Exam Checklist

  • Define a Context-Free Grammar. Why is it "Context-Free"? How is it mathematically more powerful than a Regular Grammar?
  • Given a CFG, write the Leftmost and Rightmost derivations for a specific string.
  • Draw a Parse Tree (Derivation Tree) for a given string.
  • Define Ambiguity. Prove a given grammar is ambiguous by drawing two distinct parse trees for the same string.
  • How do you mathematically remove inherent ambiguity? (Trick question: You can't. Explain why).
  • Perform CFG Simplification: Show the exact step-by-step algorithms to remove Useless Symbols, ϵ\epsilon-productions, and Unit Productions.
  • State the structural rules of Chomsky Normal Form (CNF).
  • Convert a given CFG into CNF using the step-by-step algorithm.
  • State the structural rules of Greibach Normal Form (GNF).
  • Define Left Recursion and show the mathematical formula to eliminate it.

12 of 12

Continue in this subject