Section 6 · 10 min read

Context-free grammars and PDAs

Context-free grammars, derivations and ambiguity, Chomsky and Greibach normal forms, pushdown automata, deterministic CFLs, and how to decide whether a language is context-free.

On this page
  1. Where this fits
  2. Context-free grammars
  3. Simplifying grammars
  4. Normal forms
  5. Pushdown automata
  6. Identifying context-free languages
  7. Worked examples
  8. Common traps
  9. Quick revision

Where this fits

Context-free languages (CFLs) sit one level above the regular languages. A finite automaton has bounded memory; a pushdown automaton adds one stack, which is exactly enough to match nested pairs such as brackets, anbna^n b^n, or a string against its reverse. GATE questions here usually ask you to identify which languages are CFL, which are deterministic CFL, whether a grammar is ambiguous, or what a grammar or PDA generates.

Context-free grammars

A CFG is a 4-tuple G=(V,T,P,S)G = (V, T, P, S):

  • VV: variables (non-terminals)
  • TT: terminals, disjoint from VV
  • PP: productions of the form A→αA \to \alpha, where A∈VA \in V and α∈(V∪T)∗\alpha \in (V \cup T)^*
  • S∈VS \in V: start symbol

"Context-free" means the left side is a single variable, so a variable can be rewritten regardless of what surrounds it. L(G)={w∈T∗:S⇒∗w}L(G) = \{w \in T^* : S \Rightarrow^* w\}.

Derivations and parse trees

A leftmost derivation always rewrites the leftmost variable; a rightmost derivation always rewrites the rightmost. Each parse tree corresponds to exactly one leftmost derivation and exactly one rightmost derivation. So the following say the same thing about a string ww:

  • ww has two different parse trees
  • ww has two different leftmost derivations
  • ww has two different rightmost derivations

Two derivations that differ only in the order of rewriting but build the same tree do not show ambiguity.

Ambiguity

A grammar is ambiguous if some string in its language has two parse trees. A language is inherently ambiguous if every grammar for it is ambiguous. The standard example is

{aibjck:i=j or j=k}\{a^i b^j c^k : i = j \text{ or } j = k\}

because strings anbncna^n b^n c^n can be produced through either half of the union, and no grammar can avoid that for all nn.

Deciding whether an arbitrary CFG is ambiguous is undecidable. In exams you show ambiguity by giving one string with two trees; you show unambiguity by arguing that each step of the derivation is forced.

Common ambiguous shapes:

  • S→SS∣aS \to SS \mid a (associativity not fixed)
  • E→E+E∣E∗E∣idE \to E + E \mid E * E \mid id (neither precedence nor associativity fixed)
  • S→aS∣aSb∣ϵS \to aS \mid aSb \mid \epsilon (an extra aa can be emitted before or after matching)
  • dangling else: S→if S∣if S else S∣xS \to \text{if } S \mid \text{if } S \text{ else } S \mid x

Simplifying grammars

Before converting to a normal form, clean the grammar in this order:

  1. Remove ϵ\epsilon-productions (find nullable variables, add versions of each production with nullable variables dropped). If ϵ∈L\epsilon \in L, keep S→ϵS \to \epsilon with a fresh start symbol.
  2. Remove unit productions A→BA \to B.
  3. Remove useless symbols: first non-generating ones, then unreachable ones. The order matters; doing reachability first can leave useless symbols behind.

Normal forms

Chomsky Normal Form

Every production is A→BCA \to BC or A→aA \to a (plus S→ϵS \to \epsilon if needed, with SS not on any right side). Facts used in GATE:

  • A derivation of a string of length n≥1n \ge 1 takes exactly 2n−12n - 1 steps: n−1n - 1 binary steps to create nn variables, then nn terminal steps.
  • A parse tree is binary, so a string of length nn has a tree with height at least ⌈log⁡2n⌉+1\lceil \log_2 n \rceil + 1.
  • The CYK algorithm decides membership in O(n3)O(n^3) time for a fixed grammar.

Greibach Normal Form

Every production is A→aαA \to a\alpha with aa a terminal and α∈V∗\alpha \in V^*. Each step adds exactly one terminal, so a string of length nn takes exactly nn steps. GNF grammars have no left recursion, which is why GNF connects directly to PDAs that read one symbol per move.

Pushdown automata

A PDA is M=(Q,Σ,Γ,δ,q0,Z0,F)M = (Q, \Sigma, \Gamma, \delta, q_0, Z_0, F) where Γ\Gamma is the stack alphabet, Z0Z_0 the initial stack symbol and

δ:Q×(Σ∪{ϵ})×Γ→finite subsets of Q×Γ∗\delta : Q \times (\Sigma \cup \{\epsilon\}) \times \Gamma \to \text{finite subsets of } Q \times \Gamma^*

A move reads one input symbol (or none), pops the top stack symbol, and pushes a string in its place.

Two acceptance modes:

  • By final state: input consumed and the machine is in a state of FF.
  • By empty stack: input consumed and the stack is empty.

For nondeterministic PDAs the two modes accept the same class, and that class is exactly the CFLs.

Deterministic PDAs and DCFLs

A DPDA has at most one possible move in every configuration: for each (q,a,X)(q, a, X) at most one move, and if an ϵ\epsilon-move exists on (q,X)(q, X) then no input move exists on (q,a,X)(q, a, X) for any aa.

The deterministic CFLs (DCFLs) are those accepted by a DPDA by final state. Key facts:

  • Regular ⊂\subset DCFL ⊂\subset CFL, both inclusions proper.
  • {wcwR}\{wcw^R\} is DCFL; {wwR}\{ww^R\} is CFL but not DCFL (the machine cannot know where the middle is).
  • DPDAs accepting by empty stack accept only DCFLs with the prefix property (no string in the language is a proper prefix of another). So for DPDAs, final-state acceptance is strictly more powerful.
  • DCFLs are closed under complement but not under union, intersection or reversal.
  • Every DCFL has an unambiguous grammar (in fact an LR(1) grammar). The converse is false: {wwR}\{ww^R\} is unambiguous but not DCFL.

Extra stacks

A PDA with two stacks can simulate a Turing machine tape (one stack holds the part left of the head, the other the part right of it). So "PDA with two stacks" is as powerful as a Turing machine, not "slightly more than a PDA".

Identifying context-free languages

Ask what needs to be compared and how.

Pattern Class Why
anbna^n b^n, anb2na^n b^{2n}, anbmcmdna^n b^m c^{m} d^{n} DCFL nested matching, single stack
anbmcn+ma^n b^m c^{n+m} DCFL push both, pop for cc
aibja^i b^j with i≠ji \ne j, i>ji > j, i≤2ji \le 2j DCFL one comparison, settled at the end
{w:na(w)=nb(w)}\{w : n_a(w) = n_b(w)\} DCFL stack holds the surplus
wwRww^R CFL, not DCFL middle must be guessed
aibjcka^i b^j c^k with i=ji = j or j=kj = k CFL, not DCFL union, choice must be guessed
anbncna^n b^n c^n not CFL two comparisons at once
anbmcndma^n b^m c^n d^m not CFL crossing matches
wwww not CFL same-order copy
an2a^{n^2}, a2na^{2^n}, apa^p (pp prime) not CFL over a unary alphabet, CFL = regular
complement of wwww CFL guess one mismatched position

Rules of thumb:

  • One unbounded comparison, or several that are properly nested: CFL.
  • Two comparisons that overlap or cross, or a same-order copy: not CFL.
  • Over a one-letter alphabet, every CFL is regular (Parikh's theorem). So a unary language with non-periodic lengths is not even context-free.
  • "Or" between comparisons is fine (union); "and" between independent comparisons over the same symbols usually is not.

Worked examples

Worked example 1: Writing a grammar

Give a CFG for L={aibjck:i=j+k}L = \{a^i b^j c^k : i = j + k\}.

Rewrite the condition as akajbjcka^{k} a^{j} b^{j} c^{k}: the outer aa's match the cc's, the inner aa's match the bb's. Nest them:

S→aSc∣TT→aTb∣ϵS \to aSc \mid T \qquad T \to aTb \mid \epsilon

SS wraps a…ca \dots c pairs around a core; TT builds ajbja^j b^j. Each string has one derivation, so the grammar is also unambiguous. Check: aabcaabc is a (ab) ca\,(ab)\,c with j=k=1j = k = 1, i=2i = 2.

Worked example 2: Proving and removing ambiguity

E→E+E∣E∗E∣idE \to E + E \mid E * E \mid id. The string id+id∗idid + id * id has two leftmost derivations:

  1. E⇒E+E⇒id+E⇒id+E∗E⇒id+id∗E⇒id+id∗idE \Rightarrow E + E \Rightarrow id + E \Rightarrow id + E * E \Rightarrow id + id * E \Rightarrow id + id * id (∗* below ++)
  2. E⇒E∗E⇒E+E∗E⇒id+E∗E⇒id+id∗E⇒id+id∗idE \Rightarrow E * E \Rightarrow E + E * E \Rightarrow id + E * E \Rightarrow id + id * E \Rightarrow id + id * id (++ below ∗*)

Fix it by layering precedence and choosing left recursion for left associativity:

E→E+T∣TT→T∗F∣FF→idE \to E + T \mid T \qquad T \to T * F \mid F \qquad F \to id

Now ++ can only appear at the EE level, so ∗* always binds tighter, and the tree for every string is forced.

Worked example 3: Converting to CNF

Convert S→aSb∣abS \to aSb \mid ab (language anbna^n b^n, n≥1n \ge 1).

  1. No ϵ\epsilon-productions, no unit productions, no useless symbols.
  2. Replace terminals in long bodies: A→aA \to a, B→bB \to b, giving S→ASB∣ABS \to ASB \mid AB.
  3. Break bodies longer than two: S→AXS \to AX, X→SBX \to SB.

Final CNF:

S→AX∣ABX→SBA→aB→bS \to AX \mid AB \qquad X \to SB \qquad A \to a \qquad B \to b

Check with aabbaabb (length 4): S⇒AX⇒ASB⇒AABBS \Rightarrow AX \Rightarrow ASB \Rightarrow AABB then four terminal steps. Binary steps: S→AXS \to AX, X→SBX \to SB, S→ABS \to AB is 3; terminal steps 4; total 7=2⋅4−17 = 2 \cdot 4 - 1.

Worked example 4: A PDA for equal counts

L={w∈{a,b}∗:na(w)=nb(w)}L = \{w \in \{a,b\}^* : n_a(w) = n_b(w)\}.

Idea: the stack holds the current surplus. If the top is the same letter as the input, or the stack is at Z0Z_0, push. If the top is the opposite letter, pop.

  • δ(q,a,Z0)=(q,AZ0)\delta(q, a, Z_0) = (q, AZ_0), δ(q,b,Z0)=(q,BZ0)\delta(q, b, Z_0) = (q, BZ_0)
  • δ(q,a,A)=(q,AA)\delta(q, a, A) = (q, AA), δ(q,b,B)=(q,BB)\delta(q, b, B) = (q, BB)
  • δ(q,a,B)=(q,ϵ)\delta(q, a, B) = (q, \epsilon), δ(q,b,A)=(q,ϵ)\delta(q, b, A) = (q, \epsilon)
  • δ(q,ϵ,Z0)=(f,Z0)\delta(q, \epsilon, Z_0) = (f, Z_0) with ff accepting

This machine is deterministic except for the ϵ\epsilon-move to ff, which can be avoided by making qq itself accepting whenever Z0Z_0 is on top (use a separate state for "balanced"). So LL is a DCFL. A grammar: S→aSbS∣bSaS∣ϵS \to aSbS \mid bSaS \mid \epsilon. There are (63)=20\binom{6}{3} = 20 strings of length 6 in LL.

Worked example 5: Classifying a batch

Which are context-free?

  1. {anbmcn:n,m≥0}\{a^n b^m c^n : n, m \ge 0\}: push aa's, ignore bb's, pop on cc's. CFL (in fact DCFL).
  2. {anbncmdm}\{a^n b^n c^m d^m\}: concatenation of two CFLs. CFL.
  3. {anbmcndm}\{a^n b^m c^n d^m\}: the aa-cc match and the bb-dd match cross. Not CFL; pump apbpcpdpa^p b^p c^p d^p: the window vxyvxy of length at most pp touches at most two adjacent blocks, so it cannot change aa and cc together.
  4. {aibjck:i≠j or j≠k}\{a^i b^j c^k : i \ne j \text{ or } j \ne k\}: union of two one-comparison languages. CFL. Its complement within a∗b∗c∗a^*b^*c^* is anbncna^nb^nc^n, which shows CFLs are not closed under complement.

Common traps

  • Different derivation orders are not ambiguity. Only different trees (equivalently, different leftmost derivations) count.
  • Ambiguity is a grammar property; inherent ambiguity is a language property. An ambiguous grammar may have an unambiguous equivalent.
  • DPDA by empty stack is weaker than DPDA by final state. For NPDAs they are equal.
  • wcwRwcw^R vs wwRww^R. The marker makes it deterministic.
  • Unary languages. A unary CFL is regular, so {a2n}\{a^{2^n}\} is not CFL.
  • Two stacks equal a Turing machine, not "a bigger CFL class".
  • CNF step count is 2n−12n - 1, GNF is nn. Do not swap them.
  • Removing useless symbols: non-generating first, then unreachable.

Quick revision

  • CFG: single variable on the left; parse trees correspond one to one with leftmost derivations.
  • Ambiguous = some string with two parse trees. Ambiguity of a CFG is undecidable.
  • {aibjck:i=j or j=k}\{a^ib^jc^k : i = j \text{ or } j = k\} is inherently ambiguous.
  • CNF: A→BC∣aA \to BC \mid a, 2n−12n - 1 steps, CYK in O(n3)O(n^3). GNF: A→aαA \to a\alpha, nn steps.
  • NPDA by final state = NPDA by empty stack = CFL.
  • Regular ⊂\subset DCFL ⊂\subset CFL; wwRww^R is the standard CFL that is not DCFL.
  • DCFL: closed under complement; not under union, intersection, reversal.
  • One comparison or nested comparisons: CFL. Crossing comparisons, same-order copies, or three-way equality: not CFL.
  • Two-stack PDA = Turing machine.

Further reading

Test this section