47.01.05 · theoretical-cs / formal-languages-automata

Context-Free Grammars, Parse Trees, and Pushdown Automata

shipped3 tiersLean: none

Anchor (Master): Sipser 2013 Introduction to the Theory of Computation 3e (Cengage) §2.1-2.3; Hopcroft, Motwani & Ullman 2006 Introduction to Automata Theory, Languages, and Computation 3e (Pearson) §5.1-5.4 (CFG-PDA equivalence proofs, Chomsky normal form construction, Greibach normal form)

Intuition Beginner

Think of a sentence in English. "The cat sat on the mat." A grammar for English would say: a sentence is a noun phrase followed by a verb phrase. A noun phrase is "the" followed by a noun. A noun is "cat" or "mat." And so on.

The key idea is that a grammar is a collection of replacement rules. You start with a single symbol (the "start symbol") and repeatedly replace symbols according to the rules until only words remain. Different choices of which rule to apply when produce different sentences.

A context-free grammar (CFG) works this way for formal languages. Each rule says "replace this single symbol with this sequence of symbols." The word "context-free" means the rule does not depend on what other symbols are nearby — the replacement applies regardless of context.

This is more powerful than a finite automaton because the rules can nest structures inside each other. A finite automaton cannot count an arbitrary number of open parentheses and match them with close parentheses, because it has only finitely many states. But a CFG handles this with a single rule: "a balanced string is an open parenthesis, a balanced string, and a close parenthesis."

A pushdown automaton (PDA) is the machine counterpart of a CFG. It is like an NFA with a stack. The stack provides unlimited memory, but with a restricted access pattern: you can only look at and change the top of the stack. This is exactly enough to match parentheses — push on open, pop on close.

Visual Beginner

A parse tree for the string "a + b * c" using a simple arithmetic grammar:

        E
       /|\
      E  +  E
      |    /|\
      T   T  *  T
      |   |     |
      F   F     F
      |   |     |
      a   b     c

Rules: , , .

The parse tree shows that "a + b * c" is derived by first splitting into , then the right splits into . This captures the structure that multiplication binds tighter than addition.

String Derived? Parse tree depth
a 3
a + b 4
a + b * c As above 5

Worked example Beginner

We build a CFG for the language of all strings of balanced parentheses over the alphabet { ( , ) }.

Rules. The grammar has one variable and the rules:

  • (wrap a balanced string in parentheses)
  • (concatenate two balanced strings)
  • (the empty string is balanced)

Derive the string "()()". Start with . Apply : we get . Apply to the first : we get . Apply to the inner : we get . Apply to the remaining : we get . Apply : we get "()()." Done.

Derive "(()". Can we? We need a balanced string, but "(()" has two open and one close — it is not balanced. No derivation can produce it. The grammar correctly generates only balanced strings.

Parse tree for "(())". . The tree is:

    S
   /|\
  ( S )
   /|\
  ( S )
    |
    ε

Check your understanding Beginner

Formal definition Intermediate+

Definition (CFG). A context-free grammar is a 4-tuple where:

  • is a finite set of variables (nonterminals),
  • is a finite set of terminals with ,
  • is a finite set of production rules, written ,
  • is the start variable.

Definition (derivation). For strings , we write (alpha derives beta in one step) if and for some . The reflexive transitive closure is . The language generated by is .

Definition (parse tree). A parse tree (derivation tree) for is a rooted tree where: the root is labelled ; each internal node labelled has children labelled where ; each leaf is labelled with a terminal or ; reading the leaves left-to-right yields the derived string.

Definition (ambiguity). A CFG is ambiguous if there exists a string that has two or more distinct parse trees (equivalently, two distinct leftmost derivations). A language is inherently ambiguous if every CFG for is ambiguous.

Definition (Chomsky normal form). A CFG is in Chomsky normal form (CNF) if every rule is of the form (two variables) or (one terminal), and is allowed only if .

Theorem (conversion to CNF). Every CFG can be converted into a CFG in Chomsky normal form with (and if is added back).

The conversion proceeds in stages: add a new start variable, eliminate -productions (rules of the form where ), eliminate unit productions (), and split long right-hand sides into binary branching rules.

Definition (PDA). A pushdown automaton is a 6-tuple where:

  • is a finite set of states,
  • is the input alphabet,
  • is the stack alphabet,
  • is the transition function,
  • is the start state,
  • is the set of accept states.

A transition means: in state , reading input (or ), and popping from the stack (or for no pop), go to state and push onto the stack (or for no push).

Counterexamples to common slips

  • "A CFG with rules is context-free." Yes, this is a right-linear grammar, which is a special case of CFG. Right-linear grammars generate exactly the regular languages.

  • "CNF restricts the grammar so much that some languages cannot be expressed." CNF is a normal form: every context-free language has a CFG in CNF. The conversion may increase the number of variables but does not change the language.

  • "A PDA's stack can read any position." The stack is last-in-first-out (LIFO). You can only read and modify the top element. This restriction is what makes the PDA weaker than a Turing machine.

Key theorem with proof Intermediate+

Theorem (CFG = PDA). A language is context-free (generated by some CFG) if and only if it is recognised by some PDA.

Proof sketch (CFG to PDA). Given , construct a PDA with two states and . The PDA operates as follows: push onto the stack. In , repeatedly do one of two things. If the top of the stack is a variable , nondeterministically choose a rule and replace on the stack with (pushing the symbols right-to-left so the leftmost symbol is on top). If the top of the stack is a terminal , read the next input symbol and check that it matches ; if so, pop . Accept when the input is exhausted and the stack is empty.

The PDA simulates a leftmost derivation of : each variable replacement corresponds to a grammar rule, and each terminal match corresponds to reading the input. Every accepting computation of yields a valid derivation of the input string, and every derivation yields an accepting computation.

Proof sketch (PDA to CFG). Given , construct with variables for each pair of states . The variable generates all strings that take from state with empty stack to state with empty stack. Rules: for each transition that pushes a symbol and a later transition that pops it, add a rule encoding the matching push-pop pair. The start variable is for each .

Bridge. The CFG-PDA equivalence is the foundational reason the context-free languages admit two complementary descriptions: a generative model (grammar rules) and a recognitive model (machine with stack). This builds toward the CYK parsing algorithm of 47.01.06, which uses the CNF structure for dynamic programming, and it appears again in 47.02.01 where CFL membership is shown to be in P. The central insight is that the stack provides exactly the right amount of memory to handle one level of nesting — this is exactly the computational resource that separates context-free from regular languages, and it generalises the finite-state model of 47.01.01 by adding unbounded LIFO storage. Putting these together with the pumping lemma for CFLs yields a complete characterisation of what can and cannot be expressed with nested structure.

Exercises Intermediate+

Lean formalization Intermediate+

Mathlib has Computability.ContextFreeGrammar with a basic definition of context-free grammars and derivations, but it does not define pushdown automata, the CFG-to-PDA conversion, or Chomsky normal form. The foundational gap is the absence of a PDA structure with stack operations, the proof that CFG.language G = PDA.language (CFG.toPDA G), and the Chomsky normal form normalisation algorithm with a correctness proof showing CFG.language (CFG.toCNF G) = CFG.language G. The PDA-to-CFG direction is also absent. This unit ships without a lean_module.

Advanced results Master

Three results deepen the theory of context-free languages.

Theorem 1 (CYK algorithm). Given a CFG in Chomsky normal form and a string of length , the membership question can be decided in time.

The algorithm uses dynamic programming. For each substring , compute the set of variables that can derive it. A substring of length 1 can be derived by variables with rule . For longer substrings, split at every position and check if there exist with deriving and deriving . This places CFL recognition in P.

Theorem 2 (closure under substitution). If is context-free over and each is context-free, then the substitution is context-free.

The proof replaces each terminal in the grammar for with the start variable of the grammar for , yielding a CFG for the substituted language. This closure property implies closure under union, concatenation, and star, but not intersection.

Theorem 3 (Pumping lemma for CFLs). If is context-free, then there exists (the pumping length) such that any with can be written with , , and for all [Sipser §2.3].

The proof uses the self-embedding property of parse trees: a parse tree for a sufficiently long string must repeat a variable on some root-to-leaf path, and the subtree rooted at the lower occurrence can be pumped.

Synthesis. The CFG-PDA equivalence is the foundational reason the context-free languages form a robust class with both generative and recognitive characterisations. The central insight is that one level of unbounded nesting — captured by the stack in a PDA or by recursive rules in a CFG — is exactly the right amount of structure to go beyond regularity while remaining decidable and efficiently parsable. This builds toward the CYK algorithm, which exploits the CNF structure for polynomial-time parsing, and it appears again in the Chomsky hierarchy where context-free languages sit between regular and context-sensitive. Putting these together with the DFA-NFA equivalence of 47.01.01 and the subset construction of 47.01.02 reveals a pattern: each level of the hierarchy adds a specific computational resource (deterministic states, nondeterministic states, a stack, a tape) and this is exactly what defines the boundary between adjacent levels.

Full proof set Master

Proposition 1 (CFG to PDA construction correctness). Let be a CFG. The PDA constructed with states , stack alphabet , and transitions that (i) push then onto the stack in , (ii) loop in replacing variables by rule right-hand sides and matching terminals, and (iii) accept in by popping , satisfies .

Proof. (.) For any , there is a leftmost derivation . The PDA simulates this derivation: when a variable is on top of the stack, it applies the same rule used in the derivation. When a terminal is on top, it matches the next input symbol. Since the derivation produces , the PDA consumes and empties its stack.

(.) Any accepting computation of starts with on the stack and ends with an empty stack after reading the entire input. Each time replaces a variable by a rule right-hand side, this corresponds to one derivation step. The sequence of replacements yields a derivation .

Proposition 2 (conversion to Chomsky normal form preserves the language). Let be a CFG. The grammar obtained by (i) adding a new start variable, (ii) eliminating -productions for non-start variables, (iii) eliminating unit productions, and (iv) splitting long right-hand sides into binary rules satisfies .

Proof. Each step preserves the language. Step (i) adds without changing derivable strings. Step (ii) removes for by adding, for each rule , the rule (simulating the nullable ). This preserves all non-empty derivations and handles through . Step (iii) removes by transitively replacing with the rules of . Step (iv) replaces with a chain using fresh variables. Each step preserves the set of derivable terminal strings.

Proposition 3 (PDA to CFG construction correctness). Let be a PDA. The grammar with variables and rules as described above satisfies .

Proof. By double inclusion. For , the accepting computation of decomposes into nested push-pop pairs on the stack. Each pair from state to state (pushing symbol at state , popping at state ) corresponds to a rule in . The nesting structure of push-pop pairs mirrors the parse tree structure. Conversely, every derivation in encodes a valid PDA computation because each rule corresponds to a genuine push-pop matching.

Connections Master

  • 47.01.01 — DFAs recognise the regular languages; PDAs extend DFAs with a stack to recognise the context-free languages, a strict superset.

  • 47.01.02 — The subset construction shows DFAs and NFAs have equal power; the CFG-PDA equivalence is the analogous result for the context-free level of the Chomsky hierarchy.

  • 47.01.06 — The CYK algorithm uses the Chomsky normal form structure defined here for polynomial-time parsing of context-free languages.

  • 47.02.01 — CFL membership (the parsing problem) is in P via the CYK algorithm; the relationship between CFL recognition and complexity classes connects formal languages to computational complexity.

Historical & philosophical context Master

Context-free grammars were introduced by Noam Chomsky in 1956 as part of his hierarchy of formal grammars, originally developed to model the syntax of natural languages [Chomsky 1956]. Chomsky defined four levels of grammars (type 0 through type 3), with context-free grammars at type 2, and proved that each level generates a strictly larger class of languages than the one below.

The equivalence between CFGs and PDAs was established independently by several researchers in the early 1960s. The PDA model was formalised by A. G. Oettinger in 1961 and independently by M. P. Schutzenberger. The CFG-to-PDA construction, where the PDA simulates a leftmost derivation using its stack, is sometimes called the "top-down parser" construction because it mirrors recursive-descent parsing used in compiler design.

Chomsky normal form was introduced by Chomsky as part of his study of the algebraic properties of context-free grammars. The normal form is essential for the CYK algorithm (Cocke, Younger, and Kasami, independently discovered circa 1965-1967) and for proving the pumping lemma for context-free languages. The fact that any CFG can be put into CNF without changing its language is a structural result analogous to the subset construction for NFAs: it shows that the apparently complex generality of CFG rules can be reduced to a simple canonical form [Sipser §2.1].

Bibliography Master

@book{sipser2013,
  author    = {Sipser, Michael},
  title     = {Introduction to the Theory of Computation},
  edition   = {3rd},
  publisher = {Cengage Learning},
  year      = {2013},
}
@book{hopcroft2006,
  author    = {Hopcroft, John E. and Motwani, Rajeev and Ullman, Jeffrey D.},
  title     = {Introduction to Automata Theory, Languages, and Computation},
  edition   = {3rd},
  publisher = {Pearson},
  year      = {2006},
}
@article{chomsky1956three,
  author  = {Chomsky, Noam},
  title   = {Three Models for the Description of Language},
  journal = {IRE Transactions on Information Theory},
  volume  = {2},
  number  = {3},
  pages   = {113--124},
  year    = {1956},
}