Module 7 · 15 min read · Free chapter
Context-free grammars and pushdown automata
A context-free grammar replaces one variable at a time and generates nested languages such as aⁿbⁿ. Pushdown automata, which add a stack to a finite automaton, accept exactly these languages. CFLs are closed under union, concatenation and star but not under intersection or complement, and aⁿbⁿcⁿ is not context-free.
Start from zero: a stack of tiffins
A dabbawala collects lunch boxes and piles them in a crate, one on top of another. When he unloads, the box he put in last comes out first. A pile that works this way is called a stack, and it can be as tall as the crate allows.
Now think of brackets in a sum, such as . Every opening bracket must be closed later, and the most recent one must close first. A stack checks this perfectly: push a mark for each opening bracket and pop one for each closing bracket.
In the last chapter we saw that a finite automaton cannot check , because it cannot count without limit. Give the automaton a stack and the problem disappears: push one plate for each , pop one for each , and accept if the plates run out exactly at the end. That machine is a pushdown automaton, and the rules that describe such nested languages are context-free grammars.
Why it matters. Every programming language has nested brackets, blocks and expressions, so its syntax is written as a context-free grammar. The parser in a compiler is a pushdown automaton, which is why this topic appears in GATE every year in some form.
Context-free grammars, derivations and parse trees
A context-free grammar (CFG) is a 4-tuple . Here is a finite set of variables, is the set of terminals (the alphabet), is the start symbol, and is a set of productions of the form , where is a single variable and . It is called context-free because can be replaced by wherever it appears, whatever surrounds it.
Take the grammar . Starting from , we may replace by as many times as we like and finally by . So , and the language of the grammar is exactly , which no finite automaton can accept.
When a sentential form has several variables, we must choose which to replace. A leftmost derivation always replaces the leftmost variable, and a rightmost derivation always replaces the rightmost one. For the grammar , , , the leftmost derivation is and the rightmost one is .
A parse tree shows a derivation without the order of steps. The root is , each inner node is a variable whose children spell the right side of a production, and the leaves read left to right give the derived string, called the yield. Every parse tree corresponds to exactly one leftmost derivation and exactly one rightmost derivation.
Why it matters. A compiler does not just check that a program is valid; it builds the parse tree, because the tree shows which operation applies to which operands. Everything that follows in this chapter is about building these trees reliably.
Ambiguity
A grammar is ambiguous if some string has two or more different parse trees, or equivalently two different leftmost derivations. The classic example is the expression grammar . The string has one tree with at the root and another with at the root.
The two trees mean different things. With values 2, 3 and 4, the first tree computes and the second computes . A compiler cannot allow such a choice, so we rewrite the grammar with one variable per precedence level:
Now can only appear below a , so it always binds tighter than . The left recursion in also makes group from the left, so means .
Ambiguity is a property of a grammar, and usually another grammar for the same language removes it. Some languages, however, are inherently ambiguous: every grammar for them is ambiguous. The standard example is , where strings with can always be derived in two ways.
There is no general algorithm to decide whether a given CFG is ambiguous. That problem is undecidable, so exam answers rely on finding two parse trees for one string, not on a mechanical test.
Why it matters. Precedence and associativity rules in every language manual come from exactly this rewriting. GATE asks you to spot ambiguous grammars and to count the parse trees of a short string.
Simplification and normal forms
Grammars written by people often contain clutter. Simplification removes it in a fixed order: first -productions , then unit productions , then useless symbols. A symbol is useless if it never derives a terminal string (non-generating) or can never be reached from (unreachable), and the non-generating ones must be removed first.
The order matters because each step can create work for the next. Removing -productions adds new unit productions, and removing unit productions can leave symbols unreachable. Doing useless symbols in the wrong order can leave a useless symbol behind.
A grammar is in Chomsky normal form (CNF) if every production is or , with allowed only when is in the language. Parse trees in CNF are binary, which makes counting easy. A string of length needs exactly steps of the form and steps of the form , so every derivation has exactly steps.
Convert to CNF. First add and , so the rules become . Then break the long right side with a new variable :
The string has length 4, so its derivation must take steps. Indeed uses 7 steps.
In Greibach normal form (GNF) every production is , where is a terminal and is a string of variables. Each step then produces exactly one terminal, so a string of length is derived in exactly steps. GNF is useful for building a PDA that reads one symbol per move.
Why it matters. CNF is the input format for the CYK membership algorithm, and both forms appear in GATE as "how many steps does the derivation take?". Simplification is also the first step of every proof about CFGs.
Pushdown automata: final state, empty stack, DPDA and NPDA
A pushdown automaton (PDA) is a finite automaton with a stack. Formally it is a 7-tuple , where is the stack alphabet and is the symbol at the bottom of the stack at the start. A move looks at the current state, the next input symbol (or ) and the top of the stack, then changes state and replaces the top symbol by a string, which can push, pop or leave the stack unchanged.
Here is a PDA for that accepts by final state :
On the stack grows to , the two 's pop it back to , and the -move enters . On one is left on the stack, so is never reached and the string is rejected.
A PDA can accept in two ways: by final state, when the input is used up and the state is in , or by empty stack, when the input is used up and the stack is empty. For nondeterministic PDAs the two modes accept exactly the same languages, and those languages are exactly the context-free languages.
A deterministic PDA (DPDA) never has a choice of move. Unlike finite automata, here determinism costs power. The even palindromes need a guess about where the middle is, so they are context-free but not deterministic. With a marked middle, is deterministic, because the PDA switches from pushing to popping when it sees .
For DPDAs, the two acceptance modes also differ. Empty-stack acceptance gives only languages with the prefix property, where no string in the language is a proper prefix of another. Every deterministic CFL has an unambiguous grammar, which is why parsers prefer them.
Why it matters. Real parsers are deterministic, so programming languages are designed to be deterministic context-free. GATE often asks which of several languages need nondeterminism.
Closure, non-closure and the pumping lemma for CFLs
Context-free languages are closed under fewer operations than regular ones. Union is easy: given grammars with start symbols and , add . Concatenation uses , and star uses .
But CFLs are not closed under intersection. Both and are context-free, yet their intersection is , which is not. Since and union is closed, CFLs cannot be closed under complement either.
| Operation | CFL | DCFL |
|---|---|---|
| Union | Yes | No |
| Intersection | No | No |
| Complement | No | Yes |
| Intersection with a regular language | Yes | Yes |
| Concatenation and star | Yes | No |
| Reversal and homomorphism | Yes | No |
To prove that a language is not context-free, use the pumping lemma for CFLs. If is context-free, there is a number such that every with splits as with:
The idea is that a tall parse tree must repeat a variable on some path. The part between the two copies can be repeated, which pumps and together.
Proof: is not context-free. Assume it is, with pumping length , and take . Because , the window cannot touch all three blocks, so and together contain at most two of the letters , and . Pumping with then increases at most two of the three counts, or breaks the order of letters if or mixes two letters, so , which is a contradiction.
The same lemma shows that is not context-free. Notice the contrast with , which is context-free, because a stack reverses naturally but cannot copy.
Why it matters. "Which of these is closed?" and "which of these is context-free?" are standard GATE one-mark questions. The intersection counter-example and the proof answer most of them.
The CYK idea and decision problems for CFLs
Given a grammar in CNF and a string of length , the CYK algorithm decides whether is in the language. It fills a triangular table: the cell for each substring holds every variable that can derive that substring. Short substrings come first, and a substring of length is handled by trying each of its split points and combining the cells of the two pieces through rules .
Take the grammar , , and the string . The length-1 cells are , and . For length 2, gets from and gets from .
For the whole string, the split pairs with , which no rule produces. The split pairs with , and puts in the top cell, so is in the language. There are about cells and each tries up to splits, so CYK takes time for a fixed grammar.
Several other questions about CFLs also have algorithms. Emptiness is decided by checking whether is generating, and finiteness by checking whether the simplified CNF grammar has a cycle among its variables. But many natural questions are undecidable for CFLs: whether two grammars generate the same language, whether a grammar generates all of , whether a grammar is ambiguous, and whether two CFLs have an empty intersection.
Why it matters. CYK shows that every CFL can be parsed in polynomial time, which is why grammars are practical at all. The list of undecidable CFL problems is a frequent GATE question, and the reasons behind it are taught with Turing machines.
Descriptive lens: how written papers ask this
Written papers ask about grammars and pushdown automata in four ways:
- Write a grammar or a PDA for a language given in words, and show a derivation or a run.
- Show that a grammar is ambiguous, and give an unambiguous grammar for the same language.
- Convert a grammar to Chomsky or Greibach normal form after simplifying it.
- Prove a closure or non-closure result, or use the pumping lemma to show that a language is not context-free.
Practice questions (our own, not previous-year questions).
- Design a PDA that accepts by empty stack, and trace its moves on . (10 marks)
- Show that the grammar is ambiguous, and write an unambiguous grammar that gives higher precedence. (10 marks)
- Prove that context-free languages are closed under union but not under intersection or complement. (15 marks)
Answer plan for question 3.
- Define context-free grammars briefly, and state the claim in three parts.
- For union, take grammars and with disjoint variables, add a new start symbol with , and argue that it generates exactly .
- For intersection, give and with a grammar for each, and show that their intersection is .
- Prove with the pumping lemma that is not context-free, so intersection is not closed.
- For complement, use the identity and argue that closure under complement and union would force closure under intersection.
- Conclude that CFLs are closed under union but not under intersection or complement, and note that intersection with a regular language is still closed.
Quick revision
- A CFG is with productions , and generates .
- Each parse tree has exactly one leftmost and one rightmost derivation.
- A grammar is ambiguous if one string has two parse trees, and deciding ambiguity is undecidable.
- Simplify in the order -productions, unit productions, then useless symbols.
- In CNF a string of length takes steps, and in GNF it takes steps.
- A PDA is a finite automaton with a stack, and NPDAs accept exactly the CFLs.
- For NPDAs, final state and empty stack are equivalent, but for DPDAs empty stack is weaker.
- is a CFL but not a DCFL, and is not a CFL at all.
- CFLs are closed under union, concatenation, star and intersection with regular languages, but not under intersection or complement.
- The CFL pumping lemma needs and .
- CYK decides membership in , while equivalence and universality of CFLs are undecidable.