Introduction
A context-free grammar (CFG) generates a language by rewriting nonterminals one at a time, independently of surrounding context. The languages of CFGs are the context-free languages (CFLs), recognized by pushdown automata. CFGs are the backbone of programming-language syntax and of GATE questions on derivations, parse trees and ambiguity.
Prerequisites
- Alphabets, Strings and Languages: terminals as alphabet symbols; strings and languages.
Core concepts
Formal definition
A CFG is where is a finite set of variables (nonterminals), is the terminal alphabet (), is the start symbol, and is a finite set of productions with and .
A derivation step replaces one occurrence of a variable by a production's right-hand side. Write for one step, for zero or more. The language is
Leftmost and rightmost derivations
A leftmost derivation always rewrites the leftmost variable of the current sentential form; rightmost rewrites the rightmost. Every parse tree corresponds to exactly one leftmost and one rightmost derivation.
Parse trees
A parse tree has root , internal nodes labelled by variables, children ordered as a production's right-hand side, and leaves that concatenate to the derived terminal string (the yield).
Ambiguity
A grammar is ambiguous if some string has two different parse trees (equivalently, two different leftmost derivations, or two different rightmost derivations). A language is inherently ambiguous if every CFG for it is ambiguous. The classic example is : strings lie in both parts, and every grammar for the language is ambiguous. That is a known result proved with Ogden's lemma (sketch in Example 4); finding two trees in one grammar does not prove it. Ambiguity is a property of a grammar; inherent ambiguity is a property of a language.
Facts to know.
- Deciding whether an arbitrary CFG is ambiguous is undecidable. There is no general algorithm, so ambiguity is shown by exhibiting a second tree for one specific string.
- Every regular language and every DCFL has an unambiguous grammar. So an inherently ambiguous language is never a DCFL.
- Two different derivations do not mean ambiguity: a leftmost and a rightmost derivation of the same tree are different derivations. Only two different trees (or two leftmost derivations) count.
Ambiguity versus nondeterminism. Ambiguity is about multiple trees for one string. Nondeterministic PDAs may still define unambiguous languages.
How it works
Designing CFGs
- Matching counts. for .
- Union. New start .
- Concatenation. .
- Star. .
- Expressions. , , yields a standard unambiguous arithmetic grammar.
Algorithms and pseudocode
Membership for general CFGs is decidable (CYK after Chomsky normal form; see later notes). For small exam grammars, try to derive the string by hand or build a parse tree.
LEFTMOST-DERIVE(G, target)
1 sentential <- G.S
2 while sentential has a variable
3 A <- leftmost variable
4 choose production A -> alpha // nondeterministic search
5 replace that A by alpha
6 if sentential is all terminals: return sentential == targetMathematical explanation
Leftmost derivations and trees
Theorem: a string has two distinct leftmost derivations iff it has two distinct parse trees. Proof idea: a tree determines a unique leftmost expansion order; different trees disagree at the first production choice on the leftmost variable path.
Catalan numbers and
The number of leftmost derivations of ( summands, plus signs) in the ambiguous grammar is the Catalan number . So gives , gives .
Worked examples
Example 1:
Grammar . Leftmost derivation of : .
Example 2: ambiguous plus grammar
. Two leftmost derivations of :
- , where the second step rewrites the first as , giving the tree .
The first derivation expands the second at step 3 and builds . The two derivations differ at the first choice point, so the trees differ.
Two parse trees; Catalan .

Example 3: balanced parentheses
. Generates exactly the balanced strings (Dyck words). It is unambiguous: the first symbol ( must match a unique ), which fixes the split. By contrast generates the same language ambiguously (()()() splits by as with ()() and (), or with () and ()(); and can be inserted anywhere, giving infinitely many trees).
Example 4:
, , , , . The branch generates and the branch generates . The language is a CFL that is not a deterministic CFL (treated in the DPDA note).
This grammar is ambiguous. abc has one tree through (, ) and one through (, ). A string has two trees in this grammar exactly when . Two trees in one grammar prove only that this grammar is ambiguous; they say nothing about other grammars for the same language.
The language is inherently ambiguous. This is a known result: every CFG for the language is ambiguous. The standard proof uses Ogden's lemma, a stronger pumping lemma in which only marked positions count. By contrast, the balanced-parentheses language in Example 3 has both an ambiguous grammar and an unambiguous grammar.
Related material. A proof sketch, not a full proof. Let be any CFG for the language, let be its Ogden constant, and let .
- Take and mark the 's. Ogden's lemma splits with at least one marked symbol in , at most marked symbols in , and in the language for every . Every split except , with leaves the language for some : pumping breaks the order , or makes while .
- Since divides , pumping with gives . The pumped tree has a node whose subtree yields : no , and more than 's.
- Symmetrically, starting from with the 's marked gives a tree for the same string with a node whose subtree yields no and more than 's.
- Two subtrees of one tree are nested or disjoint. These two cannot be nested (one yield has an and no , the other a and no ), and two disjoint yields would hold more than 's. So the two trees differ, and is ambiguous.
Step 1 compresses a longer case analysis; the sketch shows the structure of the argument only.
Example 5: counting parse trees in three grammars
| Grammar | String | Parse trees | Pattern |
|---|---|---|---|
| 1, 1, 2, 5, 14, 42 for | Catalan | ||
| 1, 2, 4, 8, 16 for | : each step adds the next on the left or the right | ||
a+a*a | 2 | and |
The layered grammar , , gives a+a*a exactly one tree, with below . Precedence comes from the layer (lower layer binds tighter) and left associativity from left recursion (, not ).
Example 6: the dangling else
, ( = if, = then, = else). The string ibtibtaea has 2 trees: the e attaches to the inner if or to the outer one. Programming languages resolve it by the rule "else matches the nearest unmatched then", which an unambiguous grammar can encode with separate "matched" and "unmatched" statement variables.
Example 7: grammars for common languages
| Language | Grammar |
|---|---|
| palindromes over | |
| , , | |
| , , | |
The third row shows the standard trick for "": generate equal counts, then force a nonempty surplus on one side. The fifth row generates the language because every nonempty string with equal counts splits at the first point where the counts balance. The grammar is still ambiguous: abab has the two trees and .
Important properties and observations
- Every regular language is context-free (right-linear grammars).
- CFLs are not closed under intersection or complement (see properties note).
- Useless symbols, -productions and unit productions can be eliminated (next note).
- Left recursion is allowed in CFGs but problematic for top-down parsers (Compiler Design).
Common misconceptions.
- "One parse tree (equivalently one leftmost derivation) per generated string" holds only for unambiguous grammars; arbitrary derivation orders need not be unique.
- "Ambiguous language" when only the grammar is ambiguous; the language may still have an unambiguous CFG.
- Confusing terminals and variables in productions.
GATE examination perspective
- DRAW THE TREE. Match leaves to the string; check every parent against a production.
- LEFTMOST VS RIGHTMOST. For the next leftmost step, rewrite only the leftmost variable.
- COUNT PARSE TREES. Catalan for the pure plus grammar; otherwise enumerate carefully.
- DESIGN MATCHING COUNTERS. One stack-worth of memory: one matching pair of counts, not three equal counts. and have no CFG.
- IS THIS GRAMMAR AMBIGUOUS. Look for a production with the same variable twice on the right (, ) or two rules that can produce the same prefix (); then exhibit one string with two leftmost derivations.
- TWO DERIVATIONS ARE NOT TWO TREES. A leftmost and a rightmost derivation of one tree do not show ambiguity.
- GRAMMAR VERSUS LANGUAGE. "The language is ambiguous" is meaningful only as inherent ambiguity, which needs a proof about every grammar (Example 4). An ambiguous grammar often has an unambiguous equivalent (Example 5).
- UNDECIDABLE. "Is ambiguous?" has no algorithm; "is ?" does (CYK).
Summary
Sources
- J. E. Hopcroft, R. Motwani, J. D. Ullman, Introduction to Automata Theory, Languages, and Computation, 3rd ed., Pearson Addison-Wesley, Sections 5.1 (context-free grammars), 5.2 (parse trees), 5.4 (ambiguity in grammars and languages, including 5.4.4 inherent ambiguity), 9.5.2 (undecidability of ambiguity for CFGs).
- M. Sipser, Introduction to the Theory of Computation, 3rd ed., Cengage Learning: Section 2.1 (context-free grammars: designing grammars, ambiguity).
- P. Linz, An Introduction to Formal Languages and Automata, 6th ed., Jones & Bartlett Learning: Sections 5.1 (context-free grammars, derivation trees) and 5.2 (parsing and ambiguity).