---
title: "Context-Free Grammars and Pushdown Automata"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 23
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/23-context-free-grammars-and-pushdown-automata
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 23 — Context-Free Grammars and Pushdown Automata

[Chapter 22](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#ch-b2-regular-languages) proved that no finite automaton recognises the balanced bracket words, and so none checks the brackets of an arithmetic expression or of a program. Two rules describe them all:

```rust
    let g = grammar::Grammar::parse("S -> ( S ) S | ε");
    println!("{}", g.show());
    let words = g.generated(10);
    let mut short: Vec<&String> = words.iter().filter(|w| w.len() <= 6).collect();
    short.sort_by_key(|w| w.len());
    println!("generated, up to length 6: {short:?}");
    for n in (0..=10).step_by(2) {
        let bracket = |m: u32, i: usize| if m >> i & 1 == 0 { '(' } else { ')' };
        let all = (0..1u32 << n).map(|m| (0..n).map(|i| bracket(m, i)).collect::<String>());
        let good: Vec<String> = all.filter(|w| balanced(w)).collect(); // all 2^n words tried
        let same = good.iter().all(|w| words.contains(w))
            && words.iter().filter(|w| w.len() == n).count() == good.len();
        let k = good.len();
        println!("length {n:2}: {k:3} balanced words; generated, and nothing else: {same}");
    }
}
```

***Listing 23.1.** A grammar of two rules, and every bracket word up to length 10 tested against a counter code/bachelor-2/23-context-free-languages/listings/hook.rs*

```
$ rustc --edition 2021 -O -o hook hook.rs && ./hook
S -> ( S ) S | ε
generated, up to length 6: ["", "()", "(())", "()()", "((()))", "(()())", "(())()", "()(())", "()()()"]
length  0:   1 balanced words; generated, and nothing else: true
length  2:   1 balanced words; generated, and nothing else: true
length  4:   2 balanced words; generated, and nothing else: true
length  6:   5 balanced words; generated, and nothing else: true
length  8:  14 balanced words; generated, and nothing else: true
length 10:  42 balanced words; generated, and nothing else: true
```

***Output 23.1.** The balanced words: 1, 1, 2, 5, 14, 42 of each even length, and the grammar generates exactly them.*

The rule reads: a balanced word is empty, or an opening bracket, a balanced word, the closing bracket, and another balanced word. A rule may name itself inside brackets, so the description nests to any depth, which a finite memory cannot. This chapter defines such grammars, the trees they give to words and the trouble when a word has two, a normal form and the cubic-time algorithm that decides membership for any grammar, the automata with a stack that recognise the same languages, and the languages that are still out of reach.

**You already know.**

Chapters [21](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#ch-b2-finite-automata) and [22](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#ch-b2-regular-languages): words, languages, DFAs and NFAs, [regular expressions](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regex), the pumping lemma for [regular languages](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular), $\{a^nb^n\}$ not regular, closure of [regular languages](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular) under intersection. The Year 1 volume: trees, their height, a binary tree of height $h$ has at most $2^h$ leaves; dynamic programming, filling a table of answers to subproblems from the smallest up.

## 23.1 Grammars

**Definition 23.1 (Context-free grammar).**

A *context-free grammar* is $G = (N, \Sigma, P, S)$: a finite set $N$ of *nonterminals*, an [alphabet](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-word) $\Sigma$ of *terminals* disjoint from $N$, a finite set $P$ of *productions* $A \to \alpha$ with $A \in N$ and $\alpha
\in (N \cup \Sigma)^*$, and a *start symbol* $S \in N$. Productions with the same left side are written together, $A \to \alpha \mid \beta$.

**Definition 23.2 (Derivation, generated language).**

A word over $N \cup \Sigma$ is a *sentential form*. If $A \to \alpha$ is a production, $\beta A \gamma \Rightarrow
\beta \alpha \gamma$ is an *immediate derivation*; a *derivation* $\alpha
\Rightarrow^* \beta$ is a sequence of zero or more of them. The language *generated* by $G$ is $L(G) = \{w \in \Sigma^* : S \Rightarrow^* w\}$. A language is *context-free* if some [context-free grammar](#def-b2-context-free-languages-grammar) generates it.

“[Context-free](#def-b2-context-free-languages-derivation)” says that a [nonterminal](#def-b2-context-free-languages-grammar) is replaced whatever surrounds it. The listings write a grammar one [nonterminal](#def-b2-context-free-languages-grammar) per line, a name with a capital for a [nonterminal](#def-b2-context-free-languages-grammar), one character for a terminal, and `ε` for the empty right side; the library `grammar.rs` reads that text. Three grammars of familiar languages:

- arithmetic expressions: $E \to E + E \mid E * E \mid (E) \mid a$ , with $a$ standing for any number or name;
- propositional formulas over the variables $p$ , $q$ : $F \to F \vee F \mid F \wedge F \mid \neg F \mid (F) \mid p \mid q$ ;
- a toy markup, where $w$ is a word, $[\,\cdots]$ a link and $*\cdots*$ bold text: $D \to D\,D \mid w \mid *D* \mid [D]$ .

The [derivations](#def-b2-context-free-languages-derivation) of $()()$ from $S \to (S)S \mid \varepsilon$ include $S \Rightarrow (S)S \Rightarrow ()S \Rightarrow
()(S)S \Rightarrow ()()S \Rightarrow ()()$. Which words a grammar generates is computed by `generated`, a fixed point: start with nothing, and add to each [nonterminal](#def-b2-context-free-languages-grammar) the concatenations of what the symbols of its right sides already derive, cut at a length $n$, until nothing changes.

**Definition 23.3 (Right-linear grammar).**

A grammar is *right-linear* if every production is $A \to uB$ or $A \to u$, with $u
\in \Sigma^*$ and $B \in N$: a [nonterminal](#def-b2-context-free-languages-grammar), if any, comes last.

**Proposition 23.4 (Regular languages are context-free).**

A language is regular if and only if a [right-linear grammar](#def-b2-context-free-languages-right-linear) generates it. So every [regular language](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular) is [context-free](#def-b2-context-free-languages-derivation), and $\{a^nb^n : n \ge 0\}$, [generated](#def-b2-context-free-languages-derivation) by $S \to aSb \mid \varepsilon$, shows the inclusion is strict.

**Proof.** From a DFA, take one [nonterminal](#def-b2-context-free-languages-grammar) per state, the start state as [start symbol](#def-b2-context-free-languages-grammar), a production $q \to a\,\delta(q, a)$ per transition and $q \to \varepsilon$ per [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa): a [derivation](#def-b2-context-free-languages-derivation) $q_0 \Rightarrow a_1 q_1 \Rightarrow a_1 a_2 q_2
\Rightarrow \cdots$ follows a run, and ends in a word exactly when the run ends in an [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa). Conversely, cut each production $A \to a_1 \cdots a_k B$ into a chain of $k$ transitions through $k - 1$ new states, from state $A$ to state $B$ (a spontaneous one if $k = 0$), and each $A \to a_1 \cdots a_k$ into a chain to one new [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa): the NFA’s runs follow the [derivations](#def-b2-context-free-languages-derivation), and [Chapter 21](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#ch-b2-finite-automata) makes it deterministic. ∎

## 23.2 Parse trees and ambiguity

**Definition 23.5 (Parse tree, leftmost and rightmost derivation).**

A *parse tree* for $G$ is an ordered tree whose root is $S$, whose inner nodes are [nonterminals](#def-b2-context-free-languages-grammar), whose leaves are [terminals](#def-b2-context-free-languages-grammar) or $\varepsilon$, and where the children of each inner node $A$, read from left to right, are the right side of a production $A \to \alpha$. Its *yield* is its leaves read from left to right. A [derivation](#def-b2-context-free-languages-derivation) is *leftmost* if each step replaces the leftmost [nonterminal](#def-b2-context-free-languages-grammar), and *rightmost* if each replaces the rightmost one.

A word is in $L(G)$ exactly when it is the yield of a [parse tree](#def-b2-context-free-languages-parse-tree), and [parse trees](#def-b2-context-free-languages-parse-tree), [leftmost derivations](#def-b2-context-free-languages-parse-tree) and [rightmost derivations](#def-b2-context-free-languages-parse-tree) of a word are in bijection: a tree is turned into its [leftmost derivation](#def-b2-context-free-languages-parse-tree) by expanding its nodes in preorder, and a [derivation](#def-b2-context-free-languages-derivation) into a tree by hanging each production’s right side under the node it expands. The method `leftmost` finds a [leftmost derivation](#def-b2-context-free-languages-parse-tree) by a breadth-first search over sentential forms, dropping those whose first [terminals](#def-b2-context-free-languages-grammar) do not match the word:

```
$ rustc --edition 2021 -O -o derive derive.rs && ./derive
E -> E + T | T
T -> T * F | F
F -> ( E ) | a
   E
=> E + T
=> T + T
=> F + T
=> a + T
=> a + T * F
=> a + F * F
=> a + a * F
=> a + a * a
8 steps, one per node of the parse tree that is not a letter
```

***Output 23.2.** A grammar of expressions with one [nonterminal](#def-b2-context-free-languages-grammar) per level of priority, and the [leftmost derivation](#def-b2-context-free-languages-parse-tree) of $a + a * a$.*

**Definition 23.6 (Ambiguous grammar, weak equivalence).**

A grammar is *ambiguous* if some word has two different [parse trees](#def-b2-context-free-languages-parse-tree). Two grammars are *weakly equivalent* if they generate the same language, whatever trees they give.

A program reads meaning from the tree. In the grammar $E \to E + E \mid E * E \mid (E) \mid a$, $a + a * a$ has a tree that multiplies first and one that adds first, two different values:

![Two parse trees of a + a * a in the grammar E E + E E * E (E) a. Left: a + (a * a); right: (a + a) * a.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-context-free-languages/fig-4035db326cab.svg)

![Two parse trees of a + a * a in the grammar E E + E E * E (E) a. Left: a + (a * a); right: (a + a) * a.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-context-free-languages/fig-568256b3482a.svg)

*Two [parse trees](#def-b2-context-free-languages-parse-tree) of $a + a * a$ in the grammar $E \to E + E \mid E * E \mid (E) \mid a$. Left: $a + (a * a)$; right: $(a + a) * a$.*

The grammar of [Output 23.2](#out-b2-context-free-languages-derive) removes the ambiguity with one [nonterminal](#def-b2-context-free-languages-grammar) per level: an expression $E$ is a sum of terms $T$, a term a product of factors $F$, and a factor a letter or a bracketed expression. A $+$ can then appear inside a product only within brackets, so multiplication binds tighter; and since $E \to E + T$ has its recursion on the left, $a + a + a$ groups as $(a + a) + a$. The function `trees` of `count.rs` counts [parse trees](#def-b2-context-free-languages-parse-tree) by dynamic programming over the spans of the word:

```
$ rustc --edition 2021 -O -o ambiguity ambiguity.rs && ./ambiguity
word        trees: flat  levels
a+a*a                  2       1
a*a+a                  2       1
a+a+a                  2       1
a+a+a+a                5       1
(a+a)*a                1       1
same words up to length 7: true
word        trees: dangling  matched
ix                         1        1
ixex                       1        1
iixex                      2        1
iixexex                    1        1
iiixex                     3        1
same words up to length 9: true
```

***Output 23.3.** [Parse trees](#def-b2-context-free-languages-parse-tree) counted in the flat and the levelled expression grammars, then in two grammars of `if`…`else`.*

The two expression grammars are [weakly equivalent](#def-b2-context-free-languages-ambiguous), as the program checks up to length 7. The second pair is the *dangling else*: with $i$ for “if a condition then”, $e$ for “else” and $x$ for any other statement, $S \to iS
\mid iSeS \mid x$ gives $iixex$ two trees, the `else` belonging to either `if`.

![The dangling else: in iixex, the else belongs to the inner if (left) or to the outer one (right).](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-context-free-languages/fig-4162bc863846.svg)

![The dangling else: in iixex, the else belongs to the inner if (left) or to the outer one (right).](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-context-free-languages/fig-e6ce650849d8.svg)

*The dangling `else`: in $iixex$, the `else` belongs to the inner `if` (left) or to the outer one (right).*

Languages settle it by a rule, “an `else` belongs to the nearest `if` without one”, and the grammar $S \to M \mid U$, $M \to iMeM \mid x$, $U \to iS \mid iMeU$ writes the rule down: between an $i$ and its $e$ only a *matched* statement $M$, every $i$ of which has its $e$, may appear. It is [weakly equivalent](#def-b2-context-free-languages-ambiguous) to the first and unambiguous on every word the program tried. Some [context-free languages](#def-b2-context-free-languages-derivation) have no unambiguous grammar at all, and no program can decide in general whether a grammar is [ambiguous](#def-b2-context-free-languages-ambiguous); these facts are proved in more advanced texts.

## 23.3 Chomsky normal form

**Definition 23.7 (Chomsky normal form).**

A grammar is in *Chomsky normal form* if every production is $A \to BC$ with $B, C$ [nonterminals](#def-b2-context-free-languages-grammar), or $A \to a$ with $a$ a terminal, except possibly $S \to \varepsilon$ when the [start symbol](#def-b2-context-free-languages-grammar) $S$ appears in no right side. Its *size* $|G|$ is the sum over the [productions](#def-b2-context-free-languages-grammar) of one plus the length of the right side.

**Method 23.8 (Conversion to Chomsky normal form).**

Apply in this order:

1. START: if $S$ derives $\varepsilon$ and appears in a right side, add a new start $S_0 \to S$ ;
2. TERM: in every right side of length at least 2, replace each terminal $c$ by a new [nonterminal](#def-b2-context-free-languages-grammar) written `'c'` , with `'c'` $\to c$ ;
3. BIN: cut every $A \to X_1 X_2 \cdots X_k$ with $k \ge 3$ into $A \to X_1 Y_1$ , $Y_1 \to X_2 Y_2$ , …, $Y_{k-2} \to X_{k-1} X_k$ , with new [nonterminals](#def-b2-context-free-languages-grammar) $Y_i$ ;
4. DEL: compute the nullable [nonterminals](#def-b2-context-free-languages-grammar) (those that derive $\varepsilon$ ); for every production, add each version with some nullable occurrences dropped; then remove every $A \to \varepsilon$ except $S \to \varepsilon$ ;
5. UNIT: for each $A$ , find by a graph search the [nonterminals](#def-b2-context-free-languages-grammar) $B$ with $A \Rightarrow^* B$ through [productions](#def-b2-context-free-languages-grammar) with one [nonterminal](#def-b2-context-free-languages-grammar) on the right; give $A$ every non-unit production of each such $B$ ; remove the unit [productions](#def-b2-context-free-languages-grammar) .

```rust
    /// Chomsky normal form, in five steps: a new start; terminals in long right sides
    /// replaced; long right sides cut in pairs; ε-rules removed; unit rules removed.
    pub fn cnf(&self) -> Grammar {
        let mut g = self.clone();
        let start = Sym::N(self.start.clone());
        let used_inside = self.rules.iter().any(|(_, rhs)| rhs.contains(&start));
        if used_inside && self.nullable().contains(&self.start) { // START: S0 -> S, if needed
            g.start = self.fresh(&self.start);
            g.rules.insert(0, (g.start.clone(), vec![Sym::N(self.start.clone())]));
        }
        let mut out = vec![];
        for (a, rhs) in std::mem::take(&mut g.rules) { // TERM: a terminal c in A -> X Y ...
            let rhs: Vec<Sym> = rhs.iter().map(|s| match s {
                Sym::T(c) if rhs.len() >= 2 => {
                    let name = format!("'{c}'"); // ... becomes the nonterminal 'c'
                    out.push((name.clone(), vec![s.clone()]));
                    Sym::N(name)
                }
                _ => s.clone(),
            }).collect();
            out.push((a, rhs));
        }
        g.rules = out;
        let (mut out, mut used) = (vec![], g.nonterminals());
        for (a, mut rhs) in std::mem::take(&mut g.rules) { // BIN: A -> X1 Y1, Y1 -> X2 Y2 ...
            let mut lhs = a;
            while rhs.len() > 2 {
                let y = (0..).map(|i| format!("X{i}")).find(|n| !used.contains(n)).unwrap();
                used.insert(y.clone());
                out.push((lhs, vec![rhs.remove(0), Sym::N(y.clone())]));
                lhs = y;
            }
            out.push((lhs, rhs));
        }
        g.rules = out;
```

***Listing 23.2.** START, TERM and BIN: new names for the [terminals](#def-b2-context-free-languages-grammar) and for the pieces of long right sides code/bachelor-2/23-context-free-languages/listings/grammar.rs*

```rust
        let null = g.nullable(); // DEL: every way to drop nullable symbols, then no ε
        let mut out = vec![];
        for (a, rhs) in &g.rules {
            for mask in 0..1u32 << rhs.len() {
                let keep: Vec<Sym> = rhs.iter().enumerate().filter(|&(i, s)| {
                    mask >> i & 1 == 0 || !matches!(s, Sym::N(b) if null.contains(b))
                }).map(|(_, s)| s.clone()).collect();
                let rule = (a.clone(), keep);
                if (!rule.1.is_empty() || *a == g.start) && !out.contains(&rule) {
                    out.push(rule);
                }
            }
        }
        g.rules = out;
        let unit = |rhs: &[Sym]| matches!(rhs, [Sym::N(_)]); // UNIT: through unit chains
        let mut out = vec![];
        for a in g.nonterminals() {
            let mut reach = vec![a.clone()];
            let mut k = 0;
            while k < reach.len() {
                for (b, rhs) in &g.rules {
                    if *b == reach[k] && unit(rhs) {
                        if let [Sym::N(c)] = rhs.as_slice() {
                            if !reach.contains(c) {
                                reach.push(c.clone());
                            }
                        }
                    }
                }
                k += 1;
            }
            for (b, rhs) in &g.rules {
                let rule = (a.clone(), rhs.clone());
                if reach.contains(b) && !unit(rhs) && !out.contains(&rule) {
                    out.push(rule);
                }
            }
        }
```

***Listing 23.3.** DEL and UNIT: every way to drop nullable symbols, then every production reachable through unit chains code/bachelor-2/23-context-free-languages/listings/grammar.rs*

**Proposition 23.9 (The normal form).**

The method returns a grammar in [Chomsky normal form](#def-b2-context-free-languages-cnf) that generates $L(G)$, of size at most proportional to $|G|^2$.

**Proof.** START, TERM and BIN keep the language: each new [nonterminal](#def-b2-context-free-languages-grammar) derives exactly the piece it replaces. DEL: if a version drops nullable symbols, the dropped symbols could derive $\varepsilon$ in $G$, so nothing new is [generated](#def-b2-context-free-languages-derivation); conversely, in a [parse tree](#def-b2-context-free-languages-parse-tree) of a nonempty word, cutting every subtree whose yield is empty leaves a tree that uses only the new versions. UNIT: a chain of unit [productions](#def-b2-context-free-languages-grammar) $A \Rightarrow B \Rightarrow \cdots \Rightarrow C \Rightarrow \alpha$ in a [derivation](#def-b2-context-free-languages-derivation) is replaced by the one production $A \to \alpha$, and every new production stands for such a chain; the search stops on a cycle of unit [productions](#def-b2-context-free-languages-grammar) because it visits each [nonterminal](#def-b2-context-free-languages-grammar) once. After BIN every right side has at most two symbols, so DEL makes at most three versions of each production, and the size stays proportional to $|G|$ up to that point. UNIT gives each of at most $|G|$ [nonterminals](#def-b2-context-free-languages-grammar) a copy of at most all the [productions](#def-b2-context-free-languages-grammar): at most $|G|^2$. ∎

The order matters: DEL before BIN would make $2^k$ versions of a right side with $k$ nullable symbols. The expression grammar with levels has no $\varepsilon$ and so needs no new start:

```
$ rustc --edition 2021 -O -o cnf cnf.rs && ./cnf
E -> E X0 | T X1 | '(' X2 | a
T -> T X1 | '(' X2 | a
F -> '(' X2 | a
X0 -> '+' T
X1 -> '*' F
X2 -> E ')'
'(' -> (
')' -> )
'*' -> *
'+' -> +
rules: 6 -> 16; size: 18 -> 41
the same 257 words up to length 9: true
```

***Output 23.4.** The expression grammar in [Chomsky normal form](#def-b2-context-free-languages-cnf), and a check of its words.*

The unit [productions](#def-b2-context-free-languages-grammar) $E \to T$ and $T \to F$ are gone: $E$ now has the [productions](#def-b2-context-free-languages-grammar) of $T$ and $F$ as well.

## 23.4 The CYK algorithm

In [Chomsky normal form](#def-b2-context-free-languages-cnf), a [nonterminal](#def-b2-context-free-languages-grammar) derives a word of length at least 2 by splitting it into two nonempty parts, derived by the two [nonterminals](#def-b2-context-free-languages-grammar) of a production. A table over the factors of the word, filled from the shortest up, decides membership.

**Method 23.10 (The CYK algorithm).**

Let $G$ be in [Chomsky normal form](#def-b2-context-free-languages-cnf) and $w = a_1 \cdots a_n$ nonempty. For the factor of length $\ell$ starting after position $i$, compute the set $T[i][\ell]$ of [nonterminals](#def-b2-context-free-languages-grammar) that derive it: $T[i][1] = \{A : A \to a_{i+1}\}$, and for $\ell = 2, \dots, n$, $T[i][\ell]$ holds $A$ whenever there are a production $A \to BC$ and a split $1 \le k < \ell$ with $B \in T[i][k]$ and $C \in T[i + k][\ell - k]$. Then $w \in L(G)$ if and only if $S \in
T[0][n]$.

```rust
    /// CYK on a grammar in Chomsky normal form: table[i][l - 1] holds the nonterminals that
    /// derive the l letters from position i. Also returns the number of split points tried.
    pub fn cyk(&self, word: &str) -> (Vec<Vec<BTreeSet<String>>>, usize) {
        let w: Vec<char> = word.chars().collect();
        let n = w.len();
        let mut table = vec![vec![BTreeSet::new(); n]; n];
        for (i, &c) in w.iter().enumerate() {
            for (a, rhs) in &self.rules {
                if rhs[..] == [Sym::T(c)] {
                    table[i][0].insert(a.clone());
                }
            }
        }
        let mut splits = 0;
        for l in 2..=n {
            for i in 0..=n - l {
                for k in 1..l { // the first k letters, then the other l - k
                    splits += 1;
                    for (a, rhs) in &self.rules {
                        if let [Sym::N(b), Sym::N(c)] = rhs.as_slice() {
                            let (left, right) = (&table[i][k - 1], &table[i + k][l - k - 1]);
                            if left.contains(b) && right.contains(c) {
                                table[i][l - 1].insert(a.clone());
                            }
                        }
                    }
                }
            }
        }
        (table, splits)
    }
```

***Listing 23.4.** CYK: the table, one cell per factor, and a count of the split points code/bachelor-2/23-context-free-languages/listings/grammar.rs*

```
$ rustc --edition 2021 -O -o cyk cyk.rs && ./cyk
length 5: {E}
length 4: {} {X0}
length 3: {E} {} {E,T}
length 2: {} {X0} {} {X1}
length 1: {E,F,T} {'+'} {E,F,T} {'*'} {E,F,T}
a+a*a accepted: true; split points tried: 20
```

***Output 23.5.** The table of $a + a * a$, the whole word on top, the letters at the bottom.*

![The CYK table of a + a * a as a pyramid: each cell sits above the factor it covers. The top cell holds E, so the word is an expression; the cell over a + a holds E, and the one over a * a holds E and T.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-context-free-languages/fig-5662c656fb66.svg)

*The CYK table of $a + a * a$ as a pyramid: each cell sits above the factor it covers. The top cell holds $E$, so the word is an expression; the cell over $a + a$ holds $E$, and the one over $a * a$ holds $E$ and $T$.*

**Theorem 23.11 (CYK).**

The [CYK algorithm](#met-b2-context-free-languages-cyk) decides whether $w \in L(G)$. It examines $(n^3 - n)/6$ split points, each against every production $A \to BC$, so its time is proportional to $n^3 |G|$.

**Proof.** By induction on $\ell$, $A \in T[i][\ell]$ if and only if $A \Rightarrow^* a_{i+1} \cdots a_{i+\ell}$. For $\ell = 1$, in [Chomsky normal form](#def-b2-context-free-languages-cnf) a [nonterminal](#def-b2-context-free-languages-grammar) derives a letter only through a production $A \to a$. For $\ell \ge 2$, a [derivation](#def-b2-context-free-languages-derivation) of the factor starts with some $A \to BC$, and $B$ and $C$ then derive a nonempty prefix of length $k$ and the rest, which by the hypothesis is when $B \in T[i][k]$ and $C \in T[i + k][\ell - k]$. For the count: a factor of length $\ell$ has $\ell - 1$ split points, and there are $n - \ell + 1$ factors of that length, so the number of split points is

$$
\sum_{\ell=2}^{n} (n - \ell + 1)(\ell - 1) = \sum_{j=1}^{n-1} (n - j)j = n \frac{(n - 1)n}{2} - \frac{(n - 1)n(2n -
1)}{6} = \frac{n^3 - n}{6}.
$$

∎

The table holds more than a yes or no. Replacing each set by a count of trees per [nonterminal](#def-b2-context-free-languages-grammar), a product for each split and a sum over splits and [productions](#def-b2-context-free-languages-grammar), counts the [parse trees](#def-b2-context-free-languages-parse-tree) of the word. For $E \to E + E \mid a$ on $a + a +
\cdots + a$ with $k$ operands, a tree chooses the $+$ at its root and then trees for both sides, the recurrence of the Catalan numbers, $C_{k-1} = \frac{1}{k}\binom{2k - 2}{k - 1}$:

```
$ rustc --edition 2021 -O -o count_trees count_trees.rs && ./count_trees
operands  trees          Catalan C(k - 1)
       1  1              1
       2  1              1
       3  2              2
       4  5              5
       5  14             14
       6  42             42
       7  132            132
       8  429            429
      12  58786          58786
      16  9694845        9694845
      20  1767263190     1767263190
```

***Output 23.6.** [Parse trees](#def-b2-context-free-languages-parse-tree) of a sum of $k$ operands in the [ambiguous grammar](#def-b2-context-free-languages-ambiguous), against the Catalan numbers.*

One [ambiguous](#def-b2-context-free-languages-ambiguous) rule gives a sum of 20 operands 1 767 263 190 trees; from 38 operands the count no longer fits in 64 bits ([Exercise 23.11](#exo-b2-context-free-languages-11)).

**History.**

Noam Chomsky described phrase-structure grammars, the [context-free](#def-b2-context-free-languages-derivation) ones among them, in a paper of 1956 on models of language. Programming languages took them up at once: the report on ALGOL 60, edited by Peter Naur in 1960, gave the language’s syntax as a grammar in a notation since called Backus–Naur form. The cubic algorithm carries the initials of John Cocke, Daniel Younger and Tadao Kasami, who found it independently in the 1960s; Younger’s paper appeared in 1967.

## 23.5 Pushdown automata

A finite automaton cannot count; give it a stack and it can.

**Definition 23.12 (Pushdown automaton).**

A *pushdown automaton* (PDA) is $(Q, \Sigma, \Gamma, \Delta, q_0, Z_0, F)$: a finite set of states $Q$, an input [alphabet](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-word) $\Sigma$, a *stack alphabet* $\Gamma$, a finite set $\Delta$ of *moves* $(q, x, Z) \to (q', \gamma)$ with $x \in \Sigma \cup \{\varepsilon\}$, $Z \in \Gamma$ and $\gamma \in \Gamma^*$, a start state $q_0$, a bottom symbol $Z_0 \in \Gamma$, and [accepting states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) $F \subseteq Q$. In state $q$ with $Z$ on top of the stack, the move reads $x$ (nothing if $x = \varepsilon$), goes to $q'$ and replaces $Z$ by $\gamma$, whose first symbol ends on top. A *configuration* is a state, the unread input and the stack. The automaton *accepts* $w$ if some sequence of moves leads from $(q_0, w, Z_0)$ to a configuration with no input left and an [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa).

![A PDA for \anbn\. A label x, Z / reads x with Z on top and replaces it by . State 0 pushes an A per a; the move to 1 guesses the middle; state 1 pops an A per b; state 2 is reached when only the bottom Z is left.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-context-free-languages/fig-a8f8f0865859.svg)

*A PDA for $\{a^nb^n\}$. A label $x, Z / \gamma$ reads $x$ with $Z$ on top and replaces it by $\gamma$. State 0 pushes an $A$ per $a$; the move to 1 guesses the middle; state 1 pops an $A$ per $b$; state 2 is reached when only the bottom $Z$ is left.*

Like an NFA, a PDA may have several moves from one configuration. The listing explores the configurations by a search, with a bound on the stack’s height so that it always stops:

```rust
    /// Accepted if some run reads the whole word and ends in an accepting state. The search
    /// ignores configurations whose stack is longer than `limit`; it returns the answer
    /// and the number of configurations visited.
    pub fn accepts(&self, word: &str, limit: usize) -> (bool, usize) {
        let w: Vec<char> = word.chars().collect();
        let first = (self.start, 0, vec![self.bottom]); // state, letters read, stack
        let mut seen = HashSet::from([first.clone()]);
        let mut todo = vec![first];
        while let Some((q, i, stack)) = todo.pop() {
            if i == w.len() && self.accept.contains(&q) {
                return (true, seen.len());
            }
            let Some(&top) = stack.last() else { continue }; // an empty stack blocks
            for m in self.moves.iter().filter(|m| m.from == q && m.pop == top) {
                let j = match m.read {
                    None => i,
                    Some(c) if w.get(i) == Some(&c) => i + 1,
                    Some(_) => continue,
                };
                let mut next = stack[..stack.len() - 1].to_vec();
                next.extend(m.push.iter().rev()); // push's first symbol on top
                if next.len() <= limit && seen.insert((m.to, j, next.clone())) {
                    todo.push((m.to, j, next));
                }
            }
        }
        (false, seen.len())
    }
```

***Listing 23.5.** Some run accepts: a search over configurations code/bachelor-2/23-context-free-languages/listings/pda.rs*

```
$ rustc --edition 2021 -O -o pda_demo pda_demo.rs && ./pda_demo
a^n b^n  ""        true   (3 configurations)
a^n b^n  "ab"      true   (7 configurations)
a^n b^n  "aabb"    true   (10 configurations)
a^n b^n  "aab"     false  (8 configurations)
a^n b^n  "abab"    false  (7 configurations)
a^n b^n  "aaabbb"  true   (13 configurations)
the grammar's automaton has 6 moves
brackets "()"      true   (12 configurations)
brackets "(()())"  true   (24 configurations)
brackets "())("    false  (12 configurations)
brackets "((("     false  (13 configurations)
```

***Output 23.7.** The automaton above, and the automaton built from $S \to (S)S \mid \varepsilon$ by [Theorem 23.13](#thm-b2-context-free-languages-cfg-to-pda).*

**Theorem 23.13 (From a grammar to a pushdown automaton).**

For every [context-free grammar](#def-b2-context-free-languages-grammar) $G$ there is a PDA with three states that recognises $L(G)$.

**Proof.** [Stack alphabet](#def-b2-context-free-languages-pda) $N \cup \Sigma \cup \{\$\}$, states 0, 1, 2, accepting 2. Moves: $(0, \varepsilon, \$) \to (1, S\$)$; for each production $A \to \alpha$, $(1, \varepsilon, A) \to (1, \alpha)$; for each terminal $a$, $(1, a, a) \to (1,
\varepsilon)$; and $(1, \varepsilon, \$) \to (2, \varepsilon)$. The claim, by induction on the number of steps: in state 1, the automaton can go from $(1, xy, S\$)$ to $(1, y, \alpha\$)$ exactly when there is a [leftmost derivation](#def-b2-context-free-languages-parse-tree) $S
\Rightarrow^* x\alpha$ with $x$ the [terminals](#def-b2-context-free-languages-grammar) already matched and $\alpha$ empty or starting with a [nonterminal](#def-b2-context-free-languages-grammar) (or, between two steps, with a terminal still to match). An expansion move is a step of the [derivation](#def-b2-context-free-languages-derivation); a matching move reads a letter that the [derivation](#def-b2-context-free-languages-derivation) has already produced. So the automaton reaches $(1, \varepsilon, \$)$, and then state 2, exactly when $S \Rightarrow^* w$. ∎

**Theorem 23.14 (From a pushdown automaton to a grammar).**

For every PDA there is a [context-free grammar](#def-b2-context-free-languages-grammar) that generates the language it recognises. So the [context-free languages](#def-b2-context-free-languages-derivation) are exactly the languages recognised by pushdown automata.

**Proof.** *Admitted at this level.* ∎

The proof builds a [nonterminal](#def-b2-context-free-languages-grammar) for each pair of states and each stack symbol, deriving the words that lead from the first state to the second while that symbol is popped. It is long and is not needed here. Deterministic automata are another matter: the PDA for $\{a^nb^n\}$ guesses the middle, though a deterministic one exists (the first $b$ marks it); some languages, such as the even-length palindromes, need guessing, and the parsers of the Year 3 volume’s chapters on parsing build deterministic PDAs from grammars of a restricted kind.

## 23.6 The limits of context-free languages

**Theorem 23.15 (Pumping lemma for context-free languages).**

If $L$ is [context-free](#def-b2-context-free-languages-derivation), there is $p$ such that every $z \in L$ with $|z| \ge p$ can be written $z = uvwxy$ with $|vwx|
\le p$ and $vx \ne \varepsilon$, so that $uv^iwx^iy \in L$ for every $i \ge 0$.

**Proof.** Take a grammar for $L$ in [Chomsky normal form](#def-b2-context-free-languages-cnf), with $k$ [nonterminals](#def-b2-context-free-languages-grammar), and $p = 2^k$. A [parse tree](#def-b2-context-free-languages-parse-tree) in this form is binary above its leaves: if its longest path from the root to a terminal has $h$ [nonterminals](#def-b2-context-free-languages-grammar), the word has at most $2^{h-1}$ letters. So for $|z| \ge 2^k$ the tree has a path with at least $k + 1$ [nonterminals](#def-b2-context-free-languages-grammar), and among the lowest $k + 1$ of them some $A$ appears twice. Let the upper $A$ derive $vwx$ and the lower $A$ derive $w$, and $z = uvwxy$. The subtree of the upper $A$ has paths of at most $k + 1$ [nonterminals](#def-b2-context-free-languages-grammar), so $|vwx| \le 2^k = p$. The upper $A$ has two children, the lower $A$ lies under one of them, and the other derives a nonempty word that is part of $v$ or $x$: $vx
\ne \varepsilon$. Replacing the lower subtree by a copy of the upper one, $i - 1$ times, or the upper by the lower, gives trees of $uv^iwx^iy$. ∎

![A long word has a tall tree, and a tall path repeats a nonterminal A. The upper A derives vwx, the lower one w; either subtree can stand in for the other, which pumps v and x together.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-context-free-languages/fig-8748c5c8f25c.svg)

*A long word has a tall tree, and a tall path repeats a [nonterminal](#def-b2-context-free-languages-grammar) $A$. The upper $A$ derives $vwx$, the lower one $w$; either subtree can stand in for the other, which pumps $v$ and $x$ together.*

**Proposition 23.16 (Closure).**

[Context-free languages](#def-b2-context-free-languages-derivation) are closed under union, concatenation and star, and under intersection with a [regular language](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular). They are not closed under intersection or complement. The language $\{a^nb^nc^n : n \ge 0\}$ is not [context-free](#def-b2-context-free-languages-derivation).

**Proof.** With [start symbols](#def-b2-context-free-languages-grammar) $S_1$, $S_2$ and disjoint [nonterminals](#def-b2-context-free-languages-grammar), $S \to S_1 \mid S_2$, $S \to S_1 S_2$ and $S \to S_1 S \mid
\varepsilon$ give the union, the concatenation and the star. Intersection with a [regular language](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular) is [Exercise 23.12](#exo-b2-context-free-languages-12). For $\{a^nb^nc^n\}$, take $z = a^pb^pc^p$: since $|vwx| \le p$, $vwx$ meets at most two of the three blocks, so pumping with $i = 2$ changes the number of at most two of the letters (or breaks their order) and leaves the word outside the language. Now $\{a^nb^nc^m\}$ and $\{a^mb^nc^n\}$ are [context-free](#def-b2-context-free-languages-derivation), by $S \to TC$, $T \to aTb \mid \varepsilon$, $C \to cC \mid \varepsilon$ and a symmetric grammar, and their intersection is $\{a^nb^nc^n\}$: no closure under intersection. Since $L \cap M$ is the complement of the union of the complements, closure under complement would give closure under intersection. ∎

A [pushdown automaton](#def-b2-context-free-languages-pda) has one stack, and $a^nb^nc^n$ needs to count twice. The same argument, applied after an intersection with $a^+b^+a^+b^+$, shows that $\{ww\}$ is not [context-free](#def-b2-context-free-languages-derivation) either ([Exercise 23.10](#exo-b2-context-free-languages-10)): checking that two parts of a program agree, such as a variable’s declaration and its uses, is beyond any grammar, and compilers check it in a later pass with a table of names.

## 23.7 Exercises

**Exercise 23.1 ★.**

Give a [leftmost derivation](#def-b2-context-free-languages-parse-tree) of $(a) * a$ in the grammar with levels of [Output 23.2](#out-b2-context-free-languages-derive), and draw its [parse tree](#def-b2-context-free-languages-parse-tree).

**Solution of Exercise 23.1.**

```
$ rustc --edition 2021 -O -o exo_leftmost exo_leftmost.rs && ./exo_leftmost
   E
=> T
=> T * F
=> F * F
=> ( E ) * F
=> ( T ) * F
=> ( F ) * F
=> ( a ) * F
=> ( a ) * a
```

***Output 23.10.** The [leftmost derivation](#def-b2-context-free-languages-parse-tree) of $(a) * a$.*

The tree: $E$ has one child $T$; that $T$ has the children $T$, $*$, $F$; the left $T$ goes down through $F$ to $(E)$, whose $E$ goes down through $T$ and $F$ to $a$; the right $F$ is $a$. Its nine inner nodes are the eight steps plus the [start symbol](#def-b2-context-free-languages-grammar) $E$.

**Exercise 23.2 ★.**

Someone writes $S \to (S)S \mid )S(S \mid \varepsilon$ for the balanced bracket words. Show that it generates $())($. Which language does it generate?

**Solution of Exercise 23.2.**

```
$ rustc --edition 2021 -O -o exo_brackets exo_brackets.rs && ./exo_brackets
(())  balanced: true
()    balanced: true
()()  balanced: true
())(  balanced: false
)(    balanced: false
)(()  balanced: false
)()(  balanced: false
))((  balanced: false
every word up to length 10 has as many ( as ): true
```

***Output 23.11.** The words of length at most 4, and a check up to length 10.*

$S \Rightarrow (S)S \Rightarrow ()S \Rightarrow ())S(S \Rightarrow ())(S \Rightarrow ())($. The grammar generates the words with as many $($ as $)$. Each production adds one of each, so every [generated](#def-b2-context-free-languages-derivation) word has equal numbers. Conversely, let $w$ be nonempty with equal numbers, say starting with $($, and let $(u)$ be its shortest nonempty prefix with equal numbers: the difference between the numbers of $($ and $)$ stays positive inside it, so it ends with $)$, and $u$ and the rest $v$ both have equal numbers; by induction on the length they are [generated](#def-b2-context-free-languages-derivation), and $S \to (S)S$ gives $w$. A word starting with $)$ is handled by $S \to )S(S$ in the same way.

**Exercise 23.3 ★.**

Write a grammar for the palindromes over $\{a, b\}$, and check it on every word of length at most 12.

**Solution of Exercise 23.3.**

```
$ rustc --edition 2021 -O -o exo_palindromes exo_palindromes.rs && ./exo_palindromes
253 palindromes up to length 12, all generated, and nothing else
```

***Output 23.12.** The grammar against every word.*

$P \to aPa \mid bPb \mid a \mid b \mid \varepsilon$: a palindrome of length at least 2 starts and ends with the same letter around a shorter palindrome, and those of length 0 and 1 are the last three [productions](#def-b2-context-free-languages-grammar). There are $2^{\lceil
n/2 \rceil}$ palindromes of length $n$, and $1 + 2 + 2 + 4 + 4 + \cdots + 64 + 64 = 253$ up to length 12.

**Exercise 23.4 ★.**

Draw the [parse trees](#def-b2-context-free-languages-parse-tree) of $a + a + a + a$ in $E \to E + E \mid E * E \mid (E) \mid a$. How many are there, and how many does the grammar with levels give?

**Solution of Exercise 23.4.**

Five trees, one per way to bracket the three additions: $((a + a) + a) + a$, $(a + (a + a)) + a$, $(a + a) + (a + a)$, $a + ((a + a) + a)$ and $a + (a + (a + a))$; this is $C_3 = 5$. The grammar with levels gives one, the first, since $E
\to E + T$ puts the last addition at the root ([Output 23.3](#out-b2-context-free-languages-ambiguity)).

**Exercise 23.5 ★★.**

For $S \to AB \mid AC$, $C \to SB$, $A \to a$, $B \to b$, fill the CYK tables of $aabb$ and $abab$. Which language does the grammar generate?

**Solution of Exercise 23.5.**

```
$ rustc --edition 2021 -O -o exo_cyk exo_cyk.rs && ./exo_cyk
aabb:
  length 4: {S}
  length 3: {} {C}
  length 2: {} {S} {}
  length 1: {A} {A} {B} {B}
abab:
  length 4: {}
  length 3: {} {}
  length 2: {S} {} {S}
  length 1: {A} {B} {A} {B}
```

***Output 23.13.** The two tables.*

For $aabb$: the letters give $A, A, B, B$; the middle $ab$ is $S$ by $S \to AB$; $abb$ is $C$ by $C \to SB$; the whole word is $S$ by $S \to AC$. For $abab$ the two $ab$ are $S$, but nothing derives $aba$, $bab$ or the whole word. $S \to
AB$ gives $ab$ and $S \to AC \to aSb$ wraps a word of the language in $a \cdots b$: the language is $\{a^nb^n : n \ge
1\}$.

**Exercise 23.6 ★★.**

A program removes unit [productions](#def-b2-context-free-languages-grammar) by following them recursively from each [nonterminal](#def-b2-context-free-languages-grammar). What happens on $S \to A \mid
ab$, $A \to B \mid a$, $B \to A \mid b$? How does [Method 23.8](#met-b2-context-free-languages-cnf) avoid it, and what does it produce?

**Solution of Exercise 23.6.**

```
$ rustc --edition 2021 -O -o exo_unit_cycle exo_unit_cycle.rs && ./exo_unit_cycle
S -> A | a b
A -> B | a
B -> A | b
naive: still going after 12 unit rules: S -> A -> B -> A -> B -> A -> B -> A -> B -> A -> B -> A -> B ...
with a list of the nonterminals already reached:
S -> 'a' 'b' | a | b
'a' -> a
'b' -> b
```

***Output 23.14.** The naive recursion, and the method.*

Following $A \to B$ then $B \to A$ leads back to $A$, and the recursion never ends (here it is stopped at depth 12; otherwise the stack overflows). The method searches the graph of the unit [productions](#def-b2-context-free-languages-grammar) and visits each [nonterminal](#def-b2-context-free-languages-grammar) at most once, so from $S$ it reaches $\{S, A, B\}$ and gives $S$ the [productions](#def-b2-context-free-languages-grammar) $ab$, $a$ and $b$; $A$ and $B$ are then no longer reachable from $S$ and are dropped.

**Exercise 23.7 ★★.**

Write a recogniser for $S \to TS \mid c$, $T \to aSb$ with one function per [nonterminal](#def-b2-context-free-languages-grammar), each reading one word of its [nonterminal](#def-b2-context-free-languages-grammar) from the current position; the next letter tells which production to use. Check it against the grammar on every word of length at most 9 over $\{a, b, c\}$.

**Solution of Exercise 23.7.**

```rust
impl Reader<'_> {
    fn next_is(&self, c: u8) -> bool {
        self.w.get(self.pos) == Some(&c)
    }

    fn s(&mut self) -> bool {
        if self.next_is(b'c') { // S -> c
            self.pos += 1;
            true
        } else {
            self.next_is(b'a') && self.t() && self.s() // S -> T S: T starts with a
        }
    }

    fn t(&mut self) -> bool {
        self.pos += 1; // the a, checked by the caller
        if !self.s() || !self.next_is(b'b') {
            return false;
        }
        self.pos += 1;
        true
    }
}

pub fn recognise(word: &str) -> bool {
    let mut r = Reader { w: word.as_bytes(), pos: 0 };
    r.s() && r.pos == word.len() // one S, and nothing left over
}
```

*One function per [nonterminal](#def-b2-context-free-languages-grammar) code/bachelor-2/23-context-free-languages/exercises/descent.rs*

```
$ rustc --edition 2021 -O -o exo_descent exo_descent.rs && ./exo_descent
29524 words tried, 4 in the language, 0 disagreements
the words of the language up to length 9: {"aacbcbc", "acbacbc", "acbc", "c"}
```

***Output 23.15.** The recogniser against the grammar.*

The two [productions](#def-b2-context-free-languages-grammar) of $S$ start with different letters, $c$ or the $a$ of $T$, so one letter decides; $T$ has one production. Each function returns whether it read one word of its [nonterminal](#def-b2-context-free-languages-grammar), moving the position past it, and the whole word is accepted when $S$ succeeds and nothing is left. Every word of the language has a length $3k + 1$.

**Exercise 23.8 ★★.**

Prove that $S \to (S)S \mid \varepsilon$ generates exactly the balanced words: those with as many $($ as $)$ in which no prefix has more $)$ than $($.

**Solution of Exercise 23.8.**

Every [generated](#def-b2-context-free-languages-derivation) word is balanced, by induction on the [derivation](#def-b2-context-free-languages-derivation): $\varepsilon$ is, and if $u$ and $v$ are, so is $(u)v$: its numbers are equal, a prefix inside $(u$ has one more $($ than a prefix of $u$, and a prefix $(u)v'$ has as many of each as $v'$. Conversely, by strong induction on the length: let $w$ be balanced and nonempty. Its first letter is $($, since the prefix of length 1 cannot have more $)$. Let $(u)$ be the shortest nonempty prefix with as many $)$ as $($; inside it the difference stays positive, so $u$ is balanced, and the rest $v$ is balanced too (its prefixes add to a balanced prefix). Both are shorter than $w$, so $S \Rightarrow^* u$ and $S \Rightarrow^* v$, and $S
\Rightarrow (S)S \Rightarrow^* (u)v = w$.

**Exercise 23.9 ★★.**

Build a PDA for the words over $\{a, b\}$ with as many $a$ as $b$, and test it on all words of length at most 10.

**Solution of Exercise 23.9.**

```rust
    let mv = |read, pop, push: &str| Move { from: 0, read: Some(read), pop, to: 0,
                                           push: push.chars().collect() };
    let mut moves = vec![
        mv('a', 'Z', "AZ"), mv('a', 'A', "AA"), mv('a', 'B', ""), // the stack holds the
        mv('b', 'Z', "BZ"), mv('b', 'B', "BB"), mv('b', 'A', ""), // surplus: A's or B's
    ];
    moves.push(Move { from: 0, read: None, pop: 'Z', to: 1, push: vec!['Z'] });
    let equal = Pda { start: 0, bottom: 'Z', accept: vec![1], moves };
```

*Six moves on the surplus, and an accepting move code/bachelor-2/23-context-free-languages/listings/exo_pda_equal.rs*

```
$ rustc --edition 2021 -O -o exo_pda_equal exo_pda_equal.rs && ./exo_pda_equal
2047 words up to length 10: accepted exactly when as many a as b
abba    true
aabbb   false
babaab  true
```

***Output 23.16.** The automaton on every word up to length 10.*

The stack holds the surplus: $k$ symbols $A$ above the bottom if $k$ more $a$ than $b$ have been read, $k$ symbols $B$ if $k$ more $b$. An $a$ pushes an $A$ unless a $B$ is on top, which it pops; symmetrically for $b$. By induction on the input read, the stack is always that surplus, so the bottom is on top exactly when the numbers are equal, and the last move accepts then. This automaton guesses only when the counts are equal and input remains: it may read on or take the spontaneous move to the [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa), and the wrong choice dies there, which the search over runs handles. A deterministic version keeps “counts equal” in its state: two states, equal (accepting) and unequal, moving from one to the other when the bottom symbol comes back on top or leaves it.

**Exercise 23.10 ★★★.**

Prove that $\{ww : w \in \{a, b\}^*\}$ is not [context-free](#def-b2-context-free-languages-derivation). Use [Exercise 23.12](#exo-b2-context-free-languages-12) with the [regular language](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular) $a^+b^+a^+b^+$.

**Solution of Exercise 23.10.**

Let $L = \{ww\}$ and $R = a^+b^+a^+b^+$. If $L$ were [context-free](#def-b2-context-free-languages-derivation), so would be $L \cap R = \{a^ib^ja^ib^j : i, j \ge
1\}$ ([Exercise 23.12](#exo-b2-context-free-languages-12)). Take $p$ from [Theorem 23.15](#thm-b2-context-free-languages-pumping) and $z =
a^pb^pa^pb^p$. Since $|vwx| \le p$, $vwx$ lies inside one block or across two adjacent ones. If $v$ or $x$ contains two different letters, $uv^2wx^2y$ is not in $R$. Otherwise pumping with $i = 2$ makes one or two adjacent blocks longer and leaves the others unchanged: the first and third blocks, or the second and fourth, no longer have the same length. Either way $uv^2wx^2y \notin L \cap R$, a contradiction.

**Exercise 23.11 ★★★.**

Write the [CYK algorithm](#met-b2-context-free-languages-cyk) that counts [parse trees](#def-b2-context-free-languages-parse-tree), with integers of unbounded size made of 32-bit digits (addition, multiplication, division by a small number, printing in decimal). Check it against the Catalan numbers for sums of up to 100 operands.

**Solution of Exercise 23.11.**

```rust
pub fn trees(g: &Grammar, word: &str) -> Big {
    let w: Vec<char> = word.chars().collect();
    let n = w.len();
    let mut cell: Vec<Vec<HashMap<&str, Big>>> = vec![vec![HashMap::new(); n + 1]; n];
    for (i, &c) in w.iter().enumerate() {
        for (a, _) in g.rules.iter().filter(|(_, rhs)| rhs[..] == [Sym::T(c)]) {
            cell[i][1].insert(a, Big::small(1)); // one tree: A -> c
        }
    }
    for l in 2..=n {
        for i in 0..=n - l {
            for k in 1..l {
                for (a, rhs) in &g.rules {
                    let [Sym::N(b), Sym::N(c)] = rhs.as_slice() else { continue };
                    let x = cell[i][k].get(b.as_str()); // b on the first k letters
                    let y = cell[i + k][l - k].get(c.as_str()); // c on the rest
                    let Some((x, y)) = x.zip(y) else { continue }; // both parts must exist
                    let more = x.mul(y); // a tree for b on the left, one for c on the right
                    let total = match cell[i][l].get(a.as_str()) {
                        Some(t) => t.add(&more),
                        None => more,
                    };
                    cell[i][l].insert(a, total);
                }
            }
        }
    }
    cell[0][n].get(g.start.as_str()).cloned().unwrap_or(Big::small(0))
}
```

*CYK with counts code/bachelor-2/23-context-free-languages/exercises/bigcount.rs*

```
$ rustc --edition 2021 -O -o exo_bigcount exo_bigcount.rs && ./exo_bigcount
 10 operands: 4 digits, 4862..., equal to C(9): true
 25 operands: 13 digits, 128990414732..., equal to C(24): true
 50 operands: 27 digits, 509552245179..., equal to C(49): true
100 operands: 57 digits, 227508830794..., equal to C(99): true
```

***Output 23.17.** Sums of 10 to 100 operands.*

A number is a vector of 32-bit digits; a product of two digits plus a digit and a carry stays below $2^{64}$, so each step is exact in 64 bits. Each cell maps a [nonterminal](#def-b2-context-free-languages-grammar) to its number of trees: one per production $A \to a$ at the bottom, and for each split and each $A \to BC$ the product of the counts of $B$ and $C$, added to $A$’s count. In [Chomsky normal form](#def-b2-context-free-languages-cnf) a tree is exactly a choice of production and split at each node, so the sum counts each tree once; here the conversion of $E \to E + E \mid a$ (into $E \to E\,X_0$, $X_0 \to \text{\texttt{'+'}}\,E$) keeps the trees in bijection. The Catalan numbers are computed by $C_k = C_{k-1} \cdot 2(2k - 1)/(k + 1)$, a division that is always exact. $C_{99}$ has 57 digits.

**Exercise 23.12 ★★★.**

Prove that the intersection of a [context-free language](#def-b2-context-free-languages-derivation) and a [regular language](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular) is [context-free](#def-b2-context-free-languages-derivation), by running a PDA and a DFA side by side.

**Solution of Exercise 23.12.**

Let $P$ be a PDA with states $Q$ and [accepting states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) $F$, and $D$ a complete DFA with states $R$, start $r_0$, transitions $\delta$ and [accepting states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) $F'$. The product PDA has states $Q \times R$, start $(q_0, r_0)$, the same stack, [accepting states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) $F \times F'$, and the moves $((q, r), a, Z) \to ((q', \delta(r, a)), \gamma)$ for each move $(q, a, Z) \to (q', \gamma)$ of $P$ reading a letter, and $((q, r), \varepsilon, Z) \to ((q', r), \gamma)$ for each spontaneous move. By induction on the number of moves, the product goes from $((q_0, r_0), w, Z_0)$ to $((q, r), y,
\gamma)$ exactly when $P$ goes from $(q_0, w, Z_0)$ to $(q, y, \gamma)$ and $r = \delta^*(r_0, x)$ with $w = xy$. So it accepts $w$ exactly when $P$ accepts it and $D$ does. A product of two PDAs would need two stacks, which is why the intersection of two [context-free languages](#def-b2-context-free-languages-derivation) can fail to be [context-free](#def-b2-context-free-languages-derivation).

## 23.8 Problem: The town’s markup language

**Problem 23.1.**

Weekend problem — The town’s markup language

The town’s website lets residents write notices in a small markup: $w$ stands for a word, $[\,\cdots]$ makes a link, and the first version wrote bold text between two $*$. The program below studies the first grammar, a second one, and the cost of checking notices.

```
$ rustc --edition 2021 -O -o markup markup.rs && ./markup
D -> D D | w | * D * | [ D ]
  w          1 trees
  ww         1 trees
  www        2 trees
  [w]w[w]    2 trees
  *w*w*w*    4 trees
  **w**      1 trees
D -> I D | I
I -> w | < D > | [ D ]
  each of the 516 documents up to length 8 has one tree: true
in Chomsky normal form (13 rules):
D -> I D | w | '<' X0 | '[' X1
I -> w | '<' X0 | '[' X1
X0 -> D '>'
X1 -> D ']'
'<' -> <
'>' -> >
'[' -> [
']' -> ]
  <w[w]>w  accepted: true   split points: 56
    length 7: {D}
    length 6: {D,I} {}
    length 5: {} {X0} {}
    length 4: {} {D} {X0} {}
    length 3: {} {} {D,I} {} {}
    length 2: {} {} {} {X1} {} {}
    length 1: {'<'} {D,I} {'['} {D,I} {']'} {'>'} {D,I}
  <w[w>]w  accepted: false  split points: 56
  [<ww>]   accepted: true   split points: 35
```

***Output 23.8.** The two markup grammars, tree counts, the second grammar in [Chomsky normal form](#def-b2-context-free-languages-cnf), and CYK on three notices.*

**Part I — A grammar.**

1. Give a [leftmost derivation](#def-b2-context-free-languages-parse-tree) of $[w]w$ in the first grammar.
2. Describe the notices the first grammar generates.
3. Prove that the set of notices is not regular, using the words $[^n w\, ]^n$ .
4. Write a [right-linear grammar](#def-b2-context-free-languages-right-linear) for the notices that use neither bold nor links.
5. Draw the two [parse trees](#def-b2-context-free-languages-parse-tree) of $www$ .
6. List the four trees of `*w*w*w*` , as bracketings.

**Part II — Ambiguity found and removed.**

7. Which production makes $www$ [ambiguous](#def-b2-context-free-languages-ambiguous) , and how does $D \to ID \mid I$ remove that ambiguity?
8. With $D \to ID \mid I$ and $I \to w \mid *D* \mid [D]$ , find two trees of `*w*w*w*` .
9. Why does the second grammar write bold text between `<` and `>` ?
10. The program checks 516 notices. What does this prove about the second grammar, and what does it not prove?
11. Are the first grammar and the grammar of question 8 [weakly equivalent](#def-b2-context-free-languages-ambiguous) ?
12. Give a [leftmost derivation](#def-b2-context-free-languages-parse-tree) of `<w>[w]` in the second grammar.

**Part III — Chomsky normal form and CYK.**

13. Which steps of [Method 23.8](#met-b2-context-free-languages-cnf) change the second grammar, and why is no new start needed?
14. Why does $D$ receive the [productions](#def-b2-context-free-languages-grammar) of $I$ ?
15. Explain the bottom row of the table of `<w[w]>w` .
16. Why does the cell of length 3 starting at $[$ hold $D$ and $I$ ?
17. Which cell shows that `<w[w>]w` is rejected, and why is it empty?
18. Check the numbers of split points printed for lengths 7 and 6.

**Part IV — The cost.**

```
$ rustc --edition 2021 -O -o cyk_cost cyk_cost.rs && ./cyk_cost
   n  accepted  split points  (n^3 - n)/6  time (ms)
  21  true              1540         1540        0.0
  42  true             12341        12341        0.2
  84  true             98770        98770        1.5
 168  true            790244       790244        9.7
 336  true           6322120      6322120       77.8
```

***Output 23.9.** CYK on notices of growing length, on the laptop.*

19. Prove that a word of length $n$ has $(n^3 - n)/6$ split points.
20. Check the formula against the output above.
21. By how much does the time grow when $n$ doubles, and why?
22. How many [productions](#def-b2-context-free-languages-grammar) $A \to BC$ does the normal form of the second grammar have, and what is the cost per split point?
23. Estimate the time for a notice of 20 000 letters.
24. State the result: CYK’s cubic count, $(n^3 - n)/6$ split points for a word of length $n$ .

**Solution of Problem 23.1.**

**1.** $D \Rightarrow D\,D \Rightarrow [D]\,D \Rightarrow [w]\,D \Rightarrow [w]w$.

**2.** The nonempty sequences of items, an item being a word $w$, a nonempty notice in bold between two $*$, or a nonempty notice as a link between brackets.

**3.** Intersected with the [regular language](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular) $[^*w\,]^*$, the notices give $\{[^nw\,]^n\}$; for $i \ne j$ the words $[^i$ and $[^j$ have different residuals ($w\,]^i$ is in one only), so this is not regular, and since [regular languages](https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages#def-b2-regular-languages-regular) are closed under intersection, neither are the notices.

**4.** $D \to wD \mid w$.

**5.** Both have the root $D \to D\,D$: one with $ww$ under the left child, $(ww)w$, the other with $ww$ under the right child, $w(ww)$.

**6.** One bold item `*(w *w* w)*`, whose inner sequence of three items is grouped in two ways; and the sequence `*w*`, `w`, `*w*`, grouped in two ways.

**7.** $D \to D\,D$, which is associative but says nothing of the grouping. With $D \to ID \mid I$, a sequence is a first item followed by the rest, in one way only.

**8.** The list of three items `*w*`, `w`, `*w*`; and one item `*D*` whose $D$ is the list `w`, `*w*`, `w`.

**9.** With the same symbol for opening and closing, a $*$ can be read either way, which question 8 shows. With `<` and `>` a reader always knows which it is, as with brackets.

**10.** That no notice of length at most 8 has two trees, nothing more. A proof for every length: in $I$, the first letter chooses the production; in $D \to ID \mid I$, the item ends where its closing symbol matches its opening one (or after one $w$), so the split is forced, and an induction on the length gives one tree.

**11.** Yes: both generate the nonempty sequences of items with bold between $*$; only the trees differ.

**12.** `D` $\Rightarrow$ `I D` $\Rightarrow$ `<D> D` $\Rightarrow$ `<I> D` $\Rightarrow$ `<w> D` $\Rightarrow$ `<w> I` $\Rightarrow$ `<w>[D]` $\Rightarrow$ `<w>[I]` $\Rightarrow$ `<w>[w]`.

**13.** TERM (the four symbols in the right sides of length 3), BIN (cutting `<D>` and `[D]` into `'<'` $X_0$, $X_0 \to D$ `'>'` and the same with $X_1$) and UNIT ($D \to I$). No [nonterminal](#def-b2-context-free-languages-grammar) derives $\varepsilon$, so START and DEL change nothing.

**14.** Because of the unit production $D \to I$: every item is also a notice.

**15.** Each letter’s cell holds the [nonterminals](#def-b2-context-free-languages-grammar) with a production to it: `'<'` for `<`, $D$ and $I$ for $w$ (by $I \to w$, and $D \to w$ from UNIT), `'['`, `']'` and `'>'` for the three others.

**16.** It covers $[w]$: $X_1$ derives $w]$ by $X_1 \to D$ `']'` (the cell of length 2 at $w$), and `'['` $X_1$ is a right side of both $I$ and $D$.

**17.** The top cell, of length 7, is empty, so $D$ is not in it. The factor `[w>` is the trouble: no production puts a `>` right after a link’s content, so no cell over a factor containing it holds $D$, $I$, $X_0$ or $X_1$ ending there correctly.

**18.** $(7^3 - 7)/6 = 56$ and $(6^3 - 6)/6 = 35$.

**19.** As in [Theorem 23.11](#thm-b2-context-free-languages-cyk): $\sum_{\ell=2}^{n} (n - \ell + 1)(\ell - 1) = \sum_{j=1}^{n-1}
(n - j)j = (n^3 - n)/6$.

**20.** The two columns agree on all five lines; for $n = 21$, $(9\,261 - 21)/6 = 1\,540$.

**21.** About 7 to 8 times: the work is cubic, and $2^3 = 8$; for the smallest notices the time is too short to measure well.

**22.** Seven: $D \to ID$, $D \to$ `'<'` $X_0$, $D \to$ `'['` $X_1$, $I \to$ `'<'` $X_0$, $I \to$ `'['` $X_1$, $X_0 \to D$ `'>'`, $X_1 \to D$ `']'`; each split point tests all seven, so the time is about $7 \times (n^3 - n)/6$ tests.

**23.** Scaling the last line by $(20\,000/336)^3 \approx 211\,000$: about $0.078 \times 211\,000 \approx
16\,000$ seconds, some four and a half hours. Checking a long notice needs a linear-time method for a restricted kind of grammar, which is what the parsers of compilers use.

**24.** *CYK’s cubic count*: on a grammar in [Chomsky normal form](#def-b2-context-free-languages-cnf), CYK examines $(n^3 - n)/6$ split points for a word of length $n$, each against every production $A \to BC$, so its time grows as $n^3$; the program counted exactly that number for notices of 21 to 336 letters, and its time grew about eightfold at each doubling.
