Chapter 4

Context-free grammars

A grammar specifies how to build strings. Separate its production structure from the complexity of its language: a complicated CFG can still describe a regular language.

4.1 Productions, derivations and language extraction

Past papers · CS 2014–2026 (23 papers): 8 questions, 11 marks

A CFG is G=(V,Σ,P,S)G=(V,\Sigma,P,S), where VV is a finite variable set disjoint from terminal alphabet Σ\Sigma, PP is a finite production set and S∈VS\in V is the start variable. Every production has one variable on its left: A→αA\to\alpha with α∈(V∪Σ)∗\alpha\in(V\cup\Sigma)^*. The language is L(G)={w∈Σ∗:S⇒∗w}L(G)=\{w\in\Sigma^*:S\Rightarrow^*w\}. The star permits zero or more derivation steps.

Read recursive rules as paired or independent contributions. S→aSb∣ϵS\to aSb\mid\epsilon couples the two counts. S→aS∣BS\to aS\mid B, B→bB∣ϵB\to bB\mid\epsilon permits independent counts. A variable occurrence is expanded independently of other occurrences of the same variable.

Grammar patternLanguage or invariant
S→uS∣ϵS\to uS\mid\epsilon, fixed terminal string uuu∗u^*
S→aSb∣ϵS\to aSb\mid\epsilonanbna^nb^n, n≥0n\ge0
S→aSbb∣ϵS\to aSbb\mid\epsilonanb2na^nb^{2n}, n≥0n\ge0
S→aSa∣bSb∣ϵS\to aSa\mid bSb\mid\epsilonEven-length palindromes over {a,b}\{a,b\}
S→aSa∣bSb∣a∣b∣ϵS\to aSa\mid bSb\mid a\mid b\mid\epsilonAll palindromes over {a,b}\{a,b\}
S→aSb∣TS\to aSb\mid T, T→cT∣ϵT\to cT\mid\epsilonancmbna^nc^mb^n, m,n≥0m,n\ge0
S→aSb∣SS∣ϵS\to aSb\mid SS\mid\epsilonBalanced parentheses if aa opens and bb closes
S→aSbS∣bSaS∣ϵS\to aSbS\mid bSaS\mid\epsilonAll words with equal counts of a,ba,b

To prove an exact language, prove both directions: productions preserve the claimed restriction, and every word satisfying it has a derivation. A few generated examples prove neither direction in full.

4.2 Grammar invariants and production counts

Past papers · CS 2014–2026 (23 papers): 3 questions, 6 marks

Assign each production a terminal-count contribution and a variable-count change. Sum contributions over a complete derivation. This gives necessary relations without enumerating strings; use a constructive argument if sufficiency is needed.

4.3 Ambiguity

Past papers · CS 2014–2026 (23 papers): 2 questions, 2 marks

A CFG is ambiguous if some terminal word has two different parse trees, equivalently two distinct leftmost derivations or two distinct rightmost derivations. Different orders of expanding unrelated variables in one parse tree do not establish ambiguity.

A language is inherently ambiguous if every CFG for it is ambiguous. One ambiguous grammar does not imply inherent ambiguity: S→aS∣Sa∣ϵS\to aS\mid Sa\mid\epsilon is ambiguous for a∗a^*, which also has the unambiguous grammar S→aS∣ϵS\to aS\mid\epsilon. The language {aibjck:i=j or j=k, i,j,k≥1}\{a^ib^jc^k:i=j\text{ or }j=k,\ i,j,k\ge1\} is a standard inherently ambiguous CFL; overlap of two grammar branches alone is not a proof of inherent ambiguity.

Expression grammars can encode precedence and associativity by separating expression, term and factor variables. Detailed parsing methods, including LL(kk), belong to the Compiler Design handbook.

4.4 Simplification and normal forms

Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks

A nullable variable derives ϵ\epsilon. Compute nullable variables to a fixed point. When eliminating ϵ\epsilon rules, add versions of each production with nullable occurrences omitted; retain a new start-to-ϵ\epsilon rule if the language contains ϵ\epsilon. A unit production is A→BA\to B; take the transitive unit closure and transfer non-unit productions.

A generating variable derives a terminal string. First remove nongenerating symbols and rules, then remove unreachable symbols from the start. Reversing those two passes may leave newly unreachable symbols. Recheck usefulness after other transformations.

For CNF conversion, introduce a fresh start, eliminate empty/unit productions and useless symbols, replace terminals in longer right-hand sides by new variables, and split right-hand sides longer than two into binary chains. CNF does not mean the grammar is unambiguous.

4.5 CFG membership and finite tests

Past papers · CS 2014–2026 (23 papers): 2 questions, 3 marks

For membership, convert to CNF and use the CYK dynamic programme. It terminates even if a direct grammar search would loop through recursive productions. Test ϵ\epsilon separately by nullability.

CFG emptiness is decidable: compute generating variables and test the start. Finiteness is decidable after removing useless symbols and converting to CNF: a cycle in the variable-dependency graph yields unbounded growth, since every binary rule's other child produces at least one terminal. Without that cleanup, a cycle alone need not imply an infinite language.

CFG universality, equivalence, inclusion, ambiguity and disjointness of two CFG languages are undecidable. These are problems about arbitrary input grammars; particular instances can still be easy. The finite-state analogue may be decidable even when the CFG problem is not.

Last-minute recall

  • Every CFG production has one variable on the left.
  • Repeated variable occurrences expand independently.
  • Use terminal and variable balances to find invariants.
  • Ambiguity requires two trees or two derivations of the same fixed order.
  • CNF gives 2n−12n-1 steps only for nonempty words.
  • Nullable and unit closures are fixed-point computations.
  • Membership, emptiness and finiteness are decidable for CFGs.
  • Universality and equivalence are undecidable for arbitrary CFGs.

Revise offline: the whole Theory of Computation handbook as one PDF

40 pages · 1.7 MBFree to read online. Sign in to download the PDF.We save the handbook, version and request time in My downloads. Privacy policy

All chapters · Corrections