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
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, , 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 :
- : variables (non-terminals)
- : terminals, disjoint from
- : productions of the form , where and
- : start symbol
"Context-free" means the left side is a single variable, so a variable can be rewritten regardless of what surrounds it. .
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 :
- has two different parse trees
- has two different leftmost derivations
- 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
because strings can be produced through either half of the union, and no grammar can avoid that for all .
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:
- (associativity not fixed)
- (neither precedence nor associativity fixed)
- (an extra can be emitted before or after matching)
- dangling else:
Simplifying grammars
Before converting to a normal form, clean the grammar in this order:
- Remove -productions (find nullable variables, add versions of each production with nullable variables dropped). If , keep with a fresh start symbol.
- Remove unit productions .
- 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 or (plus if needed, with not on any right side). Facts used in GATE:
- A derivation of a string of length takes exactly steps: binary steps to create variables, then terminal steps.
- A parse tree is binary, so a string of length has a tree with height at least .
- The CYK algorithm decides membership in time for a fixed grammar.
Greibach Normal Form
Every production is with a terminal and . Each step adds exactly one terminal, so a string of length takes exactly 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 where is the stack alphabet, the initial stack symbol and
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 .
- 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 at most one move, and if an -move exists on then no input move exists on for any .
The deterministic CFLs (DCFLs) are those accepted by a DPDA by final state. Key facts:
- Regular DCFL CFL, both inclusions proper.
- is DCFL; 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: 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 |
|---|---|---|
| , , | DCFL | nested matching, single stack |
| DCFL | push both, pop for | |
| with , , | DCFL | one comparison, settled at the end |
| DCFL | stack holds the surplus | |
| CFL, not DCFL | middle must be guessed | |
| with or | CFL, not DCFL | union, choice must be guessed |
| not CFL | two comparisons at once | |
| not CFL | crossing matches | |
| not CFL | same-order copy | |
| , , ( prime) | not CFL | over a unary alphabet, CFL = regular |
| complement of | 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 .
Rewrite the condition as : the outer 's match the 's, the inner 's match the 's. Nest them:
wraps pairs around a core; builds . Each string has one derivation, so the grammar is also unambiguous. Check: is with , .
Worked example 2: Proving and removing ambiguity
. The string has two leftmost derivations:
- ( below )
- ( below )
Fix it by layering precedence and choosing left recursion for left associativity:
Now can only appear at the level, so always binds tighter, and the tree for every string is forced.
Worked example 3: Converting to CNF
Convert (language , ).
- No -productions, no unit productions, no useless symbols.
- Replace terminals in long bodies: , , giving .
- Break bodies longer than two: , .
Final CNF:
Check with (length 4): then four terminal steps. Binary steps: , , is 3; terminal steps 4; total .
Worked example 4: A PDA for equal counts
.
Idea: the stack holds the current surplus. If the top is the same letter as the input, or the stack is at , push. If the top is the opposite letter, pop.
- ,
- ,
- ,
- with accepting
This machine is deterministic except for the -move to , which can be avoided by making itself accepting whenever is on top (use a separate state for "balanced"). So is a DCFL. A grammar: . There are strings of length 6 in .
Worked example 5: Classifying a batch
Which are context-free?
- : push 's, ignore 's, pop on 's. CFL (in fact DCFL).
- : concatenation of two CFLs. CFL.
- : the - match and the - match cross. Not CFL; pump : the window of length at most touches at most two adjacent blocks, so it cannot change and together.
- : union of two one-comparison languages. CFL. Its complement within is , 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.
- vs . The marker makes it deterministic.
- Unary languages. A unary CFL is regular, so is not CFL.
- Two stacks equal a Turing machine, not "a bigger CFL class".
- CNF step count is , GNF is . 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.
- is inherently ambiguous.
- CNF: , steps, CYK in . GNF: , steps.
- NPDA by final state = NPDA by empty stack = CFL.
- Regular DCFL CFL; 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.