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

Core concepts

Formal definition

A CFG is G=(V,Σ,R,S)G = (V, \Sigma, R, S) where VV is a finite set of variables (nonterminals), Σ\Sigma is the terminal alphabet (V∩Σ=∅V \cap \Sigma = \emptyset), S∈VS \in V is the start symbol, and RR is a finite set of productions A→αA \to \alpha with A∈VA \in V and α∈(V∪Σ)∗\alpha \in (V \cup \Sigma)^*.

A derivation step replaces one occurrence of a variable by a production's right-hand side. Write ⇒\Rightarrow for one step, ⇒∗\Rightarrow^* for zero or more. The language is

L(G)={w∈Σ∗∣S⇒∗w}.L(G) = \{ w \in \Sigma^* \mid S \Rightarrow^* w \}.

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 SS, 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 {anbncm∣n,m≥0}∪{anbmcm∣n,m≥0}\{a^n b^n c^m \mid n, m \ge 0\} \cup \{a^n b^m c^m \mid n, m \ge 0\}: strings anbncna^n b^n c^n 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. S→aSb∣εS \to aSb \mid \varepsilon for {anbn}\{a^n b^n\}.
  • Union. New start S→S1∣S2S \to S_1 \mid S_2.
  • Concatenation. S→S1S2S \to S_1 S_2.
  • Star. S→S1S∣εS \to S_1 S \mid \varepsilon.
  • Expressions. E→E+T∣TE \to E+T \mid T, T→T∗F∣FT \to T*F \mid F, F→(E)∣aF \to (E) \mid a 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.

Text
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 == target

Mathematical 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 S→S+S∣aS \to S+S \mid a

The number of leftmost derivations of a+a+⋯+aa+a+\cdots+a (nn summands, n−1n-1 plus signs) in the ambiguous grammar S→S+S∣aS \to S+S \mid a is the Catalan number Cn−1C_{n-1}. So n=3n=3 gives C2=2C_2=2, n=4n=4 gives C3=5C_3=5.

Worked examples

Example 1: {anbn}\{a^n b^n\}

Grammar S→aSb∣εS \to aSb \mid \varepsilon. Leftmost derivation of aabbaabb: S⇒aSb⇒aaSbb⇒aabbS \Rightarrow aSb \Rightarrow aaSbb \Rightarrow aabb.

Example 2: ambiguous plus grammar

S→S+S∣aS \to S+S \mid a. Two leftmost derivations of a+a+aa+a+a:

  1. S⇒S+S⇒a+S⇒a+S+S⇒a+a+S⇒a+a+aS \Rightarrow S+S \Rightarrow a+S \Rightarrow a+S+S \Rightarrow a+a+S \Rightarrow a+a+a
  2. S⇒S+S⇒S+S+S⇒a+S+S⇒a+a+S⇒a+a+aS \Rightarrow S+S \Rightarrow S+S+S \Rightarrow a+S+S \Rightarrow a+a+S \Rightarrow a+a+a, where the second step rewrites the first SS as S+SS+S, giving the tree (a+a)+a(a+a)+a.

The first derivation expands the second SS at step 3 and builds a+(a+a)a+(a+a). The two derivations differ at the first choice point, so the trees differ.

Two parse trees; Catalan C2=2C_2=2.

Two parse trees for a+a+a in the ambiguous plus grammar
Figure 1. Two distinct parse trees for the string a+a+a under S→S+S∣aS \to S+S \mid a: left-associated and right-associated sums.

Example 3: balanced parentheses

S→(S)S∣εS \to (S)S \mid \varepsilon. Generates exactly the balanced strings (Dyck words). It is unambiguous: the first symbol ( must match a unique ), which fixes the split. By contrast S→SS∣(S)∣εS \to SS \mid (S) \mid \varepsilon generates the same language ambiguously (()()() splits by S→SSS \to SS as S1S2S_1 S_2 with S1=S_1 = ()() and S2=S_2 = (), or with S1=S_1 = () and S2=S_2 = ()(); and ε\varepsilon can be inserted anywhere, giving infinitely many trees).

Example 4: {aibjck∣i=j or j=k}\{a^i b^j c^k \mid i=j \text{ or } j=k\}

S→AC∣BDS \to AC \mid BD, A→aAb∣εA \to aAb \mid \varepsilon, C→cC∣εC \to cC \mid \varepsilon, B→aB∣εB \to aB \mid \varepsilon, D→bDc∣εD \to bDc \mid \varepsilon. The ACAC branch generates anbncma^n b^n c^m and the BDBD branch generates ambncna^m b^n c^n. 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 ACAC (A⇒abA \Rightarrow ab, C⇒cC \Rightarrow c) and one through BDBD (B⇒aB \Rightarrow a, D⇒bcD \Rightarrow bc). A string has two trees in this grammar exactly when i=j=ki = j = k. 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 GG be any CFG for the language, let pp be its Ogden constant, and let N=p!N = p!.

  1. Take z=aNbNc2Nz = a^N b^N c^{2N} and mark the aa's. Ogden's lemma splits z=uvwxyz = uvwxy with at least one marked symbol in vxvx, at most pp marked symbols in vwxvwx, and uvmwxmyuv^m w x^m y in the language for every m≥0m \ge 0. Every split except v=asv = a^s, x=bsx = b^s with 1≤s≤p1 \le s \le p leaves the language for some mm: pumping breaks the order a∗b∗c∗a^* b^* c^*, or makes i≠ji \ne j while j≠kj \ne k.
  2. Since ss divides NN, pumping with m=N/s+1m = N/s + 1 gives a2Nb2Nc2Na^{2N} b^{2N} c^{2N}. The pumped tree has a node whose subtree yields vmwxmv^m w x^m: no cc, and more than NN bb's.
  3. Symmetrically, starting from a2NbNcNa^{2N} b^N c^N with the cc's marked gives a tree for the same string a2Nb2Nc2Na^{2N} b^{2N} c^{2N} with a node whose subtree yields no aa and more than NN bb's.
  4. Two subtrees of one tree are nested or disjoint. These two cannot be nested (one yield has an aa and no cc, the other a cc and no aa), and two disjoint yields would hold more than 2N2N bb's. So the two trees differ, and GG 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

GrammarStringParse treesPattern
S→SS∣aS \to SS \mid aana^n1, 1, 2, 5, 14, 42 for n=1..6n = 1..6Catalan Cn−1C_{n-1}
S→aS∣Sa∣aS \to aS \mid Sa \mid aana^n1, 2, 4, 8, 16 for n=1..5n = 1..52n−12^{n-1}: each step adds the next aa on the left or the right
S→S+S∣S∗S∣aS \to S+S \mid S*S \mid aa+a*a2(a+a)∗a(a+a)*a and a+(a∗a)a+(a*a)

The layered grammar E→E+T∣TE \to E+T \mid T, T→T∗F∣FT \to T*F \mid F, F→(E)∣aF \to (E) \mid a gives a+a*a exactly one tree, with ∗* below ++. Precedence comes from the layer (lower layer binds tighter) and left associativity from left recursion (E→E+TE \to E+T, not E→T+EE \to T+E).

Example 6: the dangling else

S→iCtS∣iCtSeS∣aS \to iCtS \mid iCtSeS \mid a, C→bC \to b (ii = if, tt = then, ee = 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

LanguageGrammar
palindromes over {a,b}\{a,b\}S→aSa∣bSb∣a∣b∣εS \to aSa \mid bSb \mid a \mid b \mid \varepsilon
{anb2n∣n≥0}\{a^n b^{2n} \mid n \ge 0\}S→aSbb∣εS \to aSbb \mid \varepsilon
{aibj∣i≠j}\{a^i b^j \mid i \ne j\}S→aSb∣A∣BS \to aSb \mid A \mid B, A→aA∣aA \to aA \mid a, B→bB∣bB \to bB \mid b
{aibjck∣j=i+k}\{a^i b^j c^k \mid j = i + k\}S→ABS \to AB, A→aAb∣εA \to aAb \mid \varepsilon, B→bBc∣εB \to bBc \mid \varepsilon
{w∣#a(w)=#b(w)}\{w \mid \#_a(w) = \#_b(w)\}S→aSbS∣bSaS∣εS \to aSbS \mid bSaS \mid \varepsilon
{aibj∣i≤j≤2i}\{a^i b^j \mid i \le j \le 2i\}S→aSb∣aSbb∣εS \to aSb \mid aSbb \mid \varepsilon

The third row shows the standard trick for "≠\ne": 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 a [ε] b [ab]a\,[\varepsilon]\,b\,[ab] and a [ba] b [ε]a\,[ba]\,b\,[\varepsilon].

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, ε\varepsilon-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. {anbncn}\{a^n b^n c^n\} and {aibjck∣i=j=k}\{a^i b^j c^k \mid i = j = k\} have no CFG.
  • IS THIS GRAMMAR AMBIGUOUS. Look for a production with the same variable twice on the right (S→SSS \to SS, S→S+SS \to S+S) or two rules that can produce the same prefix (S→aS∣SaS \to aS \mid Sa); 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 GG ambiguous?" has no algorithm; "is w∈L(G)w \in L(G)?" does (CYK).

Summary

Sources

  1. 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).
  2. M. Sipser, Introduction to the Theory of Computation, 3rd ed., Cengage Learning: Section 2.1 (context-free grammars: designing grammars, ambiguity).
  3. 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).

Next steps